Hangfire

What is Hangfire?

The Hangfire is an open-source .net package. It allows you to run scheduled jobs with limited amount of administrative cost. Just like Windows Scheduler, Windows Service deployment is not easy, but with the help of Hangfire you can run different types of background jobs such as one time jobs (aka fire and forget), recurring jobs.

Hangfire also provides you a dashboard that represent various information such as job status report, graph, exception details etc…

How to use Hangfire?

There are many good articles on how to use and setup Hangfire. However, I suggest you to read this book from the Author: https://media.readthedocs.org/pdf/hangfire/latest/hangfire.pdf

Extra Bit

Since I have successfully implemented the same in my job, I would like to preserve my learning in this blog, along with my good looking sketch notes.

Take Away:

  • If you are planning to use for an Enterprise Platform, I suggest you to buy Hangfire Pro version, which comes with dedicated support, performance counter and other improved benefits such as Redis database support.
  • Hangfire logs a lot. Hence, I suggest you to either implement your own LogProvider for the Hangfire or if you are using a log framework such as NUnit then don’t forget to set a filter on severity level.
  • If you are using Hangfire with the Microsoft SQL Server then you might want to assess the default polling time, which is every 15 seconds.
  • By default Hangfire dashboard is accessible for localhost. You can enable or disable for production, but don’t forget to set some sort of an Authentication mechanism. The good thing is, if you don’t want Windows or Basic Authentication, you can provide your own implementation.
  • If you can afford to have a separate Hangfire database, then please create a dedicated database for your Hangfire instance. It will give you an opportunity to scale, and share the same Hangfire instance with many other projects. Otherwise, you can stick to a separate database schema.
  • Hangfire is awesome because you don’t need any server access like in the case of Windows Scheduler or Windows Services.

Like I said before you can use this sketch note for your reference.

Namaste!

 

Setting HttpContext Response using HttpResponseMessage or Request.CreateResponse in WebApi2

Background

In my recent Continuous Improvement (CI) initiative I have been introducing few ActionFilters for the WebApi Controllers.

These action filters validates the request by using payload or the current user token against some business logics. If the request is not fulfilling business requirements then the filter should stop further processing and send response (ActionContext.Response) back from the filter pipeline.

In my projects, as of now, the default response content type is JSON.

HttpContent – ObjectContent or StringContent

The .NET Framework provides a few built-in implementations of HttpContent, here are some of the most commonly used:

  • ByteArrayContent: represents in-memory raw binary content
  • StringContent: represents text in a specific encoding (this is a specialisation of ByteArrayContent)
  • StreamContent: represents raw binary content in the form of a Stream.
  • ObjectContent is the generic implementation of the <T> type.

Problem

My basic requirement is to send JSON and I got stuck into the argument of using different objects that .net framework provides. Because my response type JSON, which is string, I can use StringContent StreamContent or even ObjectContent. The problem, what is the difference and what is the best approach in using different HttpContent sub classes.

Lets dig into each type one by one.

StringContent

StringContent is the subclass of ByteArrayContent, which is inheriting from further inheriting from HttpContent.

If I use StringContent then in that case I will have to tell lots of things when building an object such as setting content type, character set etc.. .

var errorResponse = new ResponseBase {
     Messages = new List { new Message {
             Type = MessageTypes.Error,
             Code = ErrorCode ,
             Description = ErrorMessage 
            } }
};

var response = new HttpResponseMessage {
 StatusCode = System.Net.HttpStatusCode.OK,
 Content = new StringContent(
 Newtonsoft.Json.JsonConvert.SerializeObject(errorResponse), System.Text.Encoding.UTF8, 
"application/json"),
 };

actionContext.Response = response;

I am setting the encoding as well the content type manually. Thus, what if the client negotiate the content type as XML ?

ByteArrayContent is definitely a good candidate when you have your data in the byte format such as Picture Content from the server.

ObjectContent

I can use ObjectContent class type, which is inherited from HttpContent. I can even pass a formatter object. However, it is not that easy to use because I need to pass the object type and it cannot take the formatter automatically. Again, there is a lot of hard coded settings that I need to pass to the ObjectContent.

var response = new HttpResponseMessage(HttpStatusCode.OK)
 {
 Content = new ObjectContent(typeof(ResponseBase),
 myobject,
 GlobalConfiguration.Configuration.Formatters.JsonFormatter)
 };

actionContext.Response = response;

The another most important factor of not using StringContent, ByteArrayContent, or ObjectContent directly with HttpResponseMessage is it does not recognise any serialisation configuration such as Camel case settings. Thus, either you have to pass it if it accept or do manual manipulations.

So what should be used then?

Well… the Winner is…Request.CreateResponse extension method.

Even though I have not mentioned this but the winner is somebody else. If you are using WebApi 2, like I am, it has introduced a method against Http request message object that instead of creating HttpResponse object and assigning to the response, we could just set the actionContext.Request.CreateResponse(…) extension method.

actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, 
modelState.ValidationErrors(ErrorCode));

Benefits

  • It is neat and clean. I don’t have to create an HttpResponse object and set contents separately.
  • Based on the current HttpConfiguration and Content-Type passed in Request header, the CreateResponse extension negotiate the Formatter that it will from the HttpConfiguration.Formatters list. It means that I don’t have to specify any Serialization Configuration.
  • If the configuration has been modified, for example, in case of JSON Camel case then it pick up automatically with no special check from our side.
  •  It will look after for everything by default. Otherwise we have to do allot manually. Thus it has removed some potential bugs as well.
What is the value of actionContext.Response.Content.Headers.ContentType if you use 
Request.CreateResponse method?

By using CreateResponse it automatically checks the content type, from the request, and use 
that specific formatter. Otherwise, If there is no content-type in the request, then the 
default is based on which one is first in the list of HttpConfiguration.Formatters.

In case of StringContent, we'd to hard code the content type so even if the client is
negotiating for XML content types, it will send JSON. which is wrong.

 

Extension Methods in C#

Let say you want to extend a class that you cannot inherit. These classes might be defined as sealed or even a 3rd party DLL that you have just downloaded from nugget. How would you extend these classes?

Let us take an example of struct types in C# that are sealed by default, such as DateTime, String, Int32 etc..

You know that cannot extend DateTime as:

public struct CustomDateTime: DateTime    {    }
Error at compile time: Type CustomDateTime in interface list is not an interface

One option is to Wrap DateTime variable within CustomDateTime class and then provide your custom solutions. As an example:

public class CustomDateTime
 {
 private DateTime _dateTime;
public CustomDateTime()
 {
}
 public CustomDateTime(long ticks)
 {
 }
public CustomDateTime(long ticks, DateTimeKind kind)
 {
 }
public CustomDateTime(int year, int month, int day)
 {
 }
public CustomDateTime(int year, int month, int day, Calendar calendar)
 {
 }
public CustomDateTime(int year, int month, int day, int hour, int minute, int second)
 {
 }
public CustomDateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar)
 {
 }
public CustomDateTime(int year, int month, int day, int hour, int minute, int second, CustomDateTimeKind kind)
 {
 }
public CustomDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
 {
 }
public CustomDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond,
 Calendar calendar)
 {
 }
public CustomDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond,
 CustomDateTimeKind kind)
 {
 }
public CustomDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond,
 Calendar calendar, CustomDateTimeKind kind)
 {
 }
 }
 

As you can see here that you are actually reinventing a wheal.

You have an another, second, option to define static class such as:

public static class DateTimeUtility
 {
 public static string CustomFormat(DateTime date)
 {
 return "Your Date is: " + date.ToLongDateString();
 }
 }
public class Program
 {
 public static void Main()
 {
 DateTimeUtility.CustomFormat(new DateTime());
 }
 }

 

However, it is not user friendly because:

  • You have to pass variable
  • Not easy to read
  • You have to write more code. For e.g. DateTimeUtility.CustomFormat

 

Extension methods are not a necessity but it is an elegant way of writing code.

With the help of extension method the CustomFormat will become an instance method of DateTime.

The above code will look like as:

 

public static class DateTimeUtility    {
        public static string CustomFormat(this DateTime date)
        {
            return "Your Date is: " + date.ToLongDateString();
        }
    }

    public class Program
    {
        public static void Main()
        {
            var dateTime = new DateTime();
            dateTime.CustomFormat();
        }

Hence, you can write your method once with Template type and you will be able to use the same again and again.
An another example could be to implement “Between” check:

public static class ComparableExtensions
{
 public static bool WithRange<T>(this T actual, T lower, T upper) where T : IComparable<T>
 {
 return actual.CompareTo(lower) >= 0 && actual.CompareTo(upper) < 0;
 }
}
Var number = 5;
if (number. WithRange (3,7))
{
 // ....
}

 

Tips #1 camelCase Json from webApi

Problem:

I have came into the situation where I need to build webapi that returns value in camel case so that it is defined as per javascript writing notation standard.

 

Solution:

I have two options that either I define json property for each POCO ( Plain old CLR object).

 [JsonObject("todoItem")]
 public class TodoItem
 {

[JsonProperty("id")]
public int ID { get; set; }
 [JsonProperty("title")]
 public string Title { get; set; }

 [JsonProperty("isCompleted")]
 public bool Completed { get; set; }
 }

This way Json seialization woudl know how it should represent the json result.

The another solution by using Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver class.

Use this below snippet to configure the serialization format.

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

I have wrote this line at WebApiConfig.cs file for WEB API project:

public static void Register(HttpConfiguration config)
 {
// configure serialize settings so that the response comes as camel case serialization.
 config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
 }