• Tuple extension methods in C#7

    Tuple extension methods in C#7

    Tuples allow us to package more than one value as the return type of a method. This is very handy when we don’t want to create an additional data transfer object just to return an extra piece of data together with the main value/object we want to return.

    A perfect example in my opinion of when this is useful is when we want to return a partial (paged/filtered) collection of entities from the database and at the same time return the total amount of entities that are in the db. The code snippet below does that for database user entities.

    After fetching a part of records from the db table, and fetching the total count, I often build what I call a generic PagedCollection object which contains the collection of filtered objects, total count of records in the database, the page count which gets calculated based on the filter params (page size) passed from the client-side and I also like to add the currently requested page number into the mix. This way I have everything I need to bind this “page of data” with a grid component on the client-side.

    In the past, although it’s not really a best practice, I would use C# out params for this specific case of getting the entity count at the same time as the collection itself and in my opinion tuples make this a bit cleaner and nicer. Another benefit of this is that tuples can be used with async methods, where out parameters can’t.

  • Creating and consuming JWT tokens in .Net WebAPI

    Creating and consuming JWT tokens in .Net WebAPI

    In this post I’ll explain how to create and consume the JWT tokens in .Net WebAPI. I’m using this in an OWIN-based WebAPI project under .Net v4.6.1. If you’re using .Net Core instead – the token generation will probably be the same, but the way of consuming it might differ slightly because of differences between the classic and Core middleware API’s. I used the official Microsoft Microsoft.Owin.Security.Jwt NuGet package. One important thing to note is that this is an alternative approach to using the default .Net bearer token.

    Why use JWT anyway? Well JWT is nice because the payload part of the token (usually containing user data such as email, username or user roles) is only encoded and can be read on the client-side very easily (good auth libraries such as Satellizer for AngularJS or ng2-ui-auth for Angular 2+ will take care of that for you out of the box). This saves you an additional round-trip to the server which you would otherwise have to do to “load up the current user” into your SPA app.

    Let’s get started. The first thing we’re going to need is this small extension class which we’ll need both in token generation and in the middleware setup. It contains two simple string extension methods which allow us to create SigningCredentials and the SymmetricSecurityKey from a jwtSecret key (which should be a long string of random characters).

    Now let’s move on the the most important part, the class which actually creates the token – JwtTokenProvider. You would typically use this provider from your AccountController in actions such as Login or SocialAuth after you’ve successfully authenticated the user. In you Login action simply swap the old code which you might have which generates the default bearer token, and return the newly created JWT token instead (only if the user has been successfully authenticated of course!).

    The client-side will then need to properly store the token and use it in each request that requires authentication (the typical way of handling this is by setting the token as the value of the Authorization header for each request via some sort of request interceptor).

    Also, if you’re using dependency injection, you’ll have to add the IJwtTokenProvider interface yourself. To simplify the post and to concentrate on the most important bits to JWT token creation, I left that part out on purpose. If you’re not using DI, simply instantiate the provider class and create the token.

    Also, here is the simple UserModel that was used in the JwtTokenProvider. Feel free to extend it to your needs.

    Now, to glue this all together and to enable the WebAPI to read (decrypt and decode) the tokens on each request, we need to tell the middleware how to do it. You can add this piece of code to your Startup.cs or even better, extract this code into a separate method inside App_Start/AuthConfig.cs and then just call it from the Startup.cs.

    After this, all the [Authorize] attributes you had previously should continue working as before when you were still using the default bearer token. You should also be able to access the current user using for example HttpContext.Current.User.Identity from within your controller actions.

    In one of the upcoming posts I’ll demonstrate a neat technique to share the current user context vertically between all your app layers (such as the business layer and/or repository) – something that you can’t do using the HttpContext because you don’t really want to have all the “web” dll’s in your lower layers, they should stay clean and agnostic.

    If you have any questions or comments, leave them below. Thnx!

  • Converting to and from local time in C#/.Net with Noda Time

    Converting to and from local time in C#/.Net with Noda Time

    Working with DateTime in .Net can be quirky. Even more, default .Net libraries follow MS standards and use their own set of timezones instead of the widely accepted TZDB (IANA) standard (which you should probably be using instead – because standards are good for you). Without going into too much detail, you will probably do yourself a favour if you go straight to Noda Time library for all your timezone conversion needs. Noda Time is a very powerful library for handling all things date and time and it’s made by none other than Jon Skeet himself. To make things easy and precise for all of us, he keeps track of all the changes that happen to the TZDB list (yes, countries still keep changing these things around) and makes sure the library is up to date.

    The two examples in the demo explain the most basic things you might want to do with time and timezones:

    1. Converting UTC time to local time in a certain timezone
    2. Trying to find out what the UTC representation of time is for local time in a certain timezone


    I used the US/Pacific timezone (which is UTC-8h) in sample code. All screenshots display current variable values so it’s easy to follow what’s going on with various date objects as they get converted back and forth.

    The first example creates a UTC DateTimeKind DateTime object and converts it to local US/Pacific time and the second example converts the local US/Pacific object of Unspecified DateTimeKind to UTC. Notice how time in both examples gets shifted by 8h but in opposite directions.

    And since that was a screenshot, here is the code sample in case you want to c/p it:

    The following screenshots visualize all the mini-steps of each of the two conversions. The first one is really simple and there’s not much that needs to be done to convert from UTC to local time. The second one one the other hand has to be converted multiple time to get the UTC from local time. Values of all the variables have been displayed so hopefully it will be easy to follow. I’ll let the code speak for itself:

    And the code for both methods:

    Also, here’s one additional article you should probably read if you intend to work with Noda Time in your code. It will help you wrap your head around Noda Time data types, choosing the right one for the job and conversions between them.

    Hope it helps, bai!

  • Filtering collections by non-existing child entities in LLBLGen Pro ORM

    Filtering collections by non-existing child entities in LLBLGen Pro ORM

    This is an interesting one. Let’s take a very standard scenario as an example. Say we have a one-to-many relation (customer-order) between two tables (diagram made using QuickDBD):

    And say we want to fetch all the customers that haven’t made a single order yet. It’s sort of the opposite of filtering by nested entities which was covered in an earlier post of the series. In this case we want to fetch all the customers that have a zero count of children entities. To do this, we’ll have to use JoinHint and DBNull LLBLGen constructs. Here is how:

    If you have any further questions, please leave them below. Cheers!

  • Filtering collections by multiple field values in LLBLGen Pro ORM

    Filtering collections by multiple field values in LLBLGen Pro ORM

    Sometimes we need to fetch a very specific subset of records from the database. For example when we already have a list of specific Id’s of records that we need to fetch. That’s what this post will cover.

    To accomplish this kind of filtering with LLBLGen we need to use the FieldCompareRangePredicate. It’s usage is very similar to the FieldLikePredicate from the previous post of the series.

    That’s it. If you have any questions, leave them bellow. Enjoy!


  • Filtering collections by LIKE operator in LLBLGen Pro ORM

    Filtering collections by LIKE operator in LLBLGen Pro ORM

    This will be a simple one. It’s another useful way of filtering entity collections in LLBLGen Pro. If you don’t know anything about filtering, predicate expressions or buckets in LLBLGen, check out some of the previous posts from the series.

    What the LIKE operator enables us to do in SQL is it allows us to filter collections by partial string matches which is a quite common action if you have any search input fields in your app. For example if we wanted to find all the products that have the word “blue” in their name we would use the LIKE operator. The way to do it in LLBLGen would be to use the FieldLikePredicate:

    There really isn’t much more to it, it’s pretty straightforward and simple.

    Hope it helped. If you have any questions or comments, drop them below. Cheers!


Back to top