Posts

Incrementing alphabets as a form of ID

Occasionally, whether you are designing or integrating APIs, you would come across the need to have unique identifier that includes alphabet(s). For example, how can we implement the following unique identifier, AANNNNNN, where NNNNN is numeric serial, and AA is the alphabetical serial.  So, each time we need a new ID, it would be   AA000000,...,AA999999,AB000000,...   I will not go into what you should do after ZZ999999, but rather how to maintain the alphabetical side of this ID. The first thing that came into my mind would be splitting the alphabets from the numerical serial, but how can I store the alphabets as a sequence in the database?  The solution would be to store a numeric representation of the alphabets in the database, and convert them accordingly when you read the sequence. Using Excel as an example, we would have the following,  1: A  ...  26: Z  27: AA  28: AB  ... and so on  Since I need a 2-character alph...

An extra .0 when returning JSON response that contains decimal type

Sometimes when we are designing API responses, we might want to return a JSON string which contains decimal-type field. We could easily represent the decimal-type field with string, so the response is in the following format: {     "amount": "3.00" } However, for whatever reason, if you want to return the amount field   in decimal, and let's say it is very important the number of decimal place is shown correctly, there is some configuration required to get that right, as without any intervention, the client will end up seeing something as follow. *I am writing this based on the API designed using .NET's tech. stack. {     "amount": 3.0 } Assuming we want the amount to be returned in 2 decimal places, 3.00, we could achieve that with the use of attribute. Let's start by creating a class with a property called amount . public class Receipt {     public decimal amount { get; set; } } At some point, we want to serialize the above...

Add current Git commit to web.config on each build [.NET Core/ASP.NET Core]

*Docker service might eliminate the following technique's usability. In this post, I am going to demonstrate a way to actually write the current commit of your version control module (I am using Git) into a location, let's say in your web.config . One of the issue I have faced when managing multiple console apps., or even web projects is that it is not easy to keep track of the com mit which the applications belong to. However, there is a simple technique to actually write the current commit of a specific branch into a location inside your project. The technique is the same regardless of the project type. * I am talking about .NET based projects. Although I only tested this in .NET Core based projects, I am pretty sure it works almost the same in .NET Framework/ASP.NET MVC based projects. The main idea is the utilize the build engine, MSBuild, to do something after building your application. The command execute a task could be derived in your .csproj file. You can defin...

Ways to perform eager loading via NHibernate

By default we know that lazy loading is enabled in NHibernate. So, let's say if we decide to keep the default, how do we enable eager loading with NHibernate? There are 2 ways to do that (there are more, but I will mention 2 that you will commonly see): 1.  Query<Entity>().Fetch(x => x.ClassA).Fetch(x => x.ClassB); 2. var tempQuery =  Query<Entity>().Fetch(x => x.ClassA).ToFuture();      Query<Entity>(). Fetch(x => x.ClassB).ToFuture();     var entityList =  tempQuery   .ToList(); Do note that Fetch is used to fetch reference, while FetchMany is used to fetch collection. If you are wondering what is the difference between 1 and 2, it is the use of ToFuture to split the SQL statement to multiple queries. The problem with multiple Fetch in a single LINQ query is that it would result in Cartesian product of the main object, in this case, Entity  . Hence, it is not recommended to use multiple...

Generic query with NHibernate with eager loading

In my previous post, I showed how we could create generic methods to perform query,  https://csharptipstricks.blogspot.com/2019/12/usage-of-expression-to-create-generic.html . However, the methods present there does not allow eager loading. In case you are wondering how eager loading is performed, see below. Do know that there are ways to assign eager loading during mapping, but I will not show it in this post. Method I : SessionFactory.OpenSession().Query<MyEntity>().Fetch(x => x.Property1).Fetch(x => x.Property2).ToList(); Method II : var tempMyEntityQuery = GetSession().Query<MyEntity>().Fetch(x => x.Property1).ToFuture(); GetSession().Query<MyEntity>().Fetch(x => x.Property2).ToFuture(); List<MyEntity> myEntityList = tempMyEntityQuery .ToList(); Both the methods above will eager load Property1 & Property2 in a single trip to the database. However, I would choose method I because a single statement (with left outer join)...

The use of trigger to simplify the population of timestamp during update (PostgreSQL)

Often in development, we will want to include Created and Updated columns in each of our table, for tracking and recording purpose. However, if you are like me, we cannot avoid interacting with the database outside of our code, be it we want to insert or update a record manually. In case of PostgreSQL database, we can use function and trigger to track a particular column in a table. The function is for us to ensure that there is a new value for the Updated column, but we would not want to override a value is one is provided, we just want to ensure the Updated  column is up-to-date, just in case none is provided. Firstly, we need to create a function to provide a new value for the Updated column, if one is not given. CREATE OR REPLACE FUNCTION UPDATED_CHANGED ( ) RETURNS TRIGGER AS $$ begin IF NEW . UPDATED < = OLD . UPDATED THEN NEW . UPDATED : = NOW ( ) AT TIME ZONE 'UTC' ; END IF ; RETURN NEW ; END ; $$ LANGUAGE plpgsql ; Here, we are ...

ASP.NET Core service locator pattern

There are many posts out there which specifically say that we should not use service locator pattern (unless necessary), which we would not be able to determine the dependencies during compile time because the dependencies are hidden. However, I am going to point out an issue in case if you need to use it, in the context of ASP.NET Core projects. I have a class Foo , which will be bind to IFoo , and I will need to configure a named HttpClient for that class via the following extension,   services.AddHttpClient<IFoo, Foo>(); If we do the above, Foo will be treated as an object which is Singleton injected. In case you are not aware, we cannot inject services which has a smaller lifespan than the service itself. Hence, we cannot inject services which are transient or scoped into Foo . Here comes the problem, what should we do? That's where service locator pattern comes to the rescue! There might be other way, but let's say we decide to use the service locator provide...

The danger of duplicated mapping of many-to-one in NHibernate

If you use NHibernate, you will often have to deal with lots of many-to-one mapping. However, if you are not careful, you might accidentally create duplicated mapping due to the use of foreign key. Let's say you have a class,  A ,   which has a column, A_ID as the primary key. Class  B is related to A via a column, A_ID (in B), which is the foreign key referencing A 's primary key. Hence, we would define our B object like the following, public class B { public virtual A ClassA { get ; set ; } public virtual long A_ID { get ; set ; } } We have both the properties to represent the object A (due to the foreign key mapping), as well as the column which acts as the foreign key. The following is the XML mapping file. <property name="A_ID">       <column name="A_ID" not-null="true" /> </property> <many-to-one name="ClassA" column="A_ID" cascade="save-update"/> We want ...

Implementation of distributed cache

One of the things that we can't escape while developing a system, is the use of database to store data. However, we ought to know that the frequency of database access will directly affect our system's performance. This is where caching comes in. Caching not only reduces the number of calls required to access the database, but also to increase the speed we could retrieve the data that we need. Cache is a storage pattern which allows for fast retrieval of data which we need frequently, and it should not be a set of data which changes constantly. In case of ASP.NET Core, there are 2 types of caching that we can use; in-memory cache & distributed cache . In-memory cache means that the cache is available for access within the application itself only. If we are building a system that contains multiple apps. which spread across multiple servers, each app. will have its own cache, which might be redundant, since all of them utilize the same data. This is where distributed cac...

Single application pool vs multiple application pool [ASP.NET Core]

There are often debates on whether to deploy ASP.NET applications in a single application pool, or assign a application pool for each application. In case of ASP.NET MVC with .NET Framework, the cons involved in the latter are: Each application pool has it's own memory pool, hence memory will deplete quickly, especially if you are hosting quite a number of applications in your server. It would difficult for you to perform updates on just a single application, especially if it requires you to turn off the application pool. #2 can be solved quite easily with the use of load balancer, since you could divert traffic to other server while you perform maintenance on the current server. However, there is no easy solution to #1 but to increase the memory of your server. Initially, I thought the same would apply to ASP.NET Core applications. However, we need to remember that IIS is just a reverse proxy in ASP.NET Core application, at least if you choose the out-of-process hosting...

Working with request body in ASP.NET Core

During API development, we might often want to read the raw request body for logging or signature validation . In case of ASP.NET Core, we could use EnableRewind() to read the request body multiple times. using ( var reader = new StreamReader(Request.Body)) { var body = reader.ReadToEnd(); Request.Body.Seek(0, SeekOrigin.Begin); } However, if we are to use StreamReader  to read the request body, we will dispose the StreamReader using the using statement. This is a mistake if we are to read the request body in the future. Hence, we should use the following way instead. The following snippet is being taken from inside a Controller . // Read the request body, but do not dispose it var stream = new StreamReader(httpContextAccessor.HttpContext.Request.Body); stream.BaseStream.Position = 0; requestBody = await stream.ReadToEndAsync(); httpContextAccessor.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);

Usage of Expression to create generic query method for NHibernate

In my previous post about caching and generic query via NHibernate [ https://csharptipstricks.blogspot.com/2019/12/caching-and-generic-query-using.html ], there was a method that takes Expression as a parameter, as shown below: // Check if a record exists or not public async Task< bool > IsRecordExistsAsync<K>(Expression<Func<K, bool >> condition) where K : class { bool isExist = await GetSession().QueryOver<K>() .Where(condition) .RowCountAsync() > 0; return isExist; } Initially, I had the intention of creating a common method which could produce an Expression that holds a Func<K, bool> delegate. The method is as follow: public static Expression<Func<T, bool >> CreateCondition<T>(Func<T, bool > func) { return x => func(x); } When I use the Expression produced via the method above as an input parameter fo...

The importance of request identity

ASP.NET Core One of the more important aspect of API development is we have to give each request an identity. This is especially important if we are logging each request & response for tracing, caching, or validation. In case of ASP.NET Core, a request identity could be injected at the scoped level where it will lives through the life-cycle of a request. To bind the request data, we could use a middleware. Since the class is injected at the scoped level, each access to the class/object would be the same within the request life-cycle. A class to store the information of a request. public class RequestIdentity { public string ClientKey { get ; set ; } public RequestIdentity() {} public void BindRequestData( string clientKey) { ClientKey = clientKey; } } Using a middleware, we could easily bind the required information into the class. Let's assume the client key is supposedly being included in the header. public class RequestIdentityInit...

Caching and generic query using NHibernate [.NET Core]

One of the important aspects in API design is to reduce the number of fetch request to database. NHibernate provides 2 levels of caching, with the first level cache persist through a session only, while the 2nd level cache persists across multiple sessions. The second level cache can be implemented by installing the NuGet package of NHibernate.Caches.SysCache . Then, it involves some configuration setup to utilize the cache feature. However, there is an alternative way that exists in .NET Core which we could use to build a simpler cache. The caching that we could use is IMemoryCache . Firstly, we could setup the cache during  ConfigureServices . public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); } Then, assuming we want to retrieve all the records from a table called DailySales , and we want to keep the records in the cache for 1 minute, we could do the following. private readonly IMemoryCache cache; public DBHelper(IMe...