Reflection deserialization and custom attributes


Download Source Code

So, last week one of my colleagues wanted to serialize an object along with custom property attribute to JSON. Interesting… JSON.NET by default will not allow serializing custom property attribute. So, you have to write custom JSON converter to fix this. Let’s take a look at how you can solve this problem

Suppose you have following custom attribute class

    /// <summary>
    /// Complex Type Attribute
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class ComplexAttribute : System.Attribute
        public string Type { get; set; }
        public string DisplayName { get; set; }


Moreover, you use it as below.

    /// <summary>
    /// Creating Blog ComplexType
    /// </summary>
    public class Blog
        [ComplexAttribute(Type = "String", DisplayName = "Blog Title")]
        public string Title { get; set; }

        [ComplexAttribute(Type = "HTML")]
        public string Content { get; set; }


So, you are expecting below JSON serializing output

"Title":{"type":"String","displayname":"Blog Title","value":"Attribute To JSON"},
"Content":{"type":"HTML","displayname":"Content","value":"<p>This blog is still not implemented</p>"}

Custom JsonConverter

JsonConverter is an abstract class provides with JSON.NET that allows you to convert an object to and from JSON. By inheriting that you can customize default serialization and deserialization behavior as you want.

Reading attributes with reflection

Attributes and reflection go hand in hand. So, when you override WriteJson method to create your custom serialization, you can use the reflection to read the attributes value.  When it desterilize back to the object, we can use reflection same way to set the property value.

    /// <summary>
    /// Complext type converter
    /// This class will conver attribute as JSON property
    /// </summary>
    public class ComplexTypeConverter : JsonConverter
        public override bool CanConvert(Type objectType)
            return (typeof(iComplexType).IsAssignableFrom(objectType));

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            object rootObject = Activator.CreateInstance(objectType);
            JToken objJSON = JToken.ReadFrom(reader);

            foreach (var token in objJSON)
                PropertyInfo propInfo = rootObject.GetType().GetProperty(token.Path, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                if (propInfo.CanWrite)
                    var tk = token as JProperty;
                    if (tk.Value is JObject)
                        JValue val = tk.Value.SelectToken("value") as JValue;
                        propInfo.SetValue(rootObject, Convert.ChangeType(val.Value, propInfo.PropertyType.UnderlyingSystemType), null);

                        propInfo.SetValue(rootObject, Convert.ChangeType(tk.Value, propInfo.PropertyType.UnderlyingSystemType), null);

            return rootObject;

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            var jo = new JObject();
            var type = value.GetType();
            foreach (PropertyInfo propInfo in type.GetProperties())
                if (propInfo.CanRead)
                    object propVal = propInfo.GetValue(value, null);

                    var cutomAttribute = propInfo.GetCustomAttribute<ComplexAttribute>();
                    if (cutomAttribute != null)

                        jo.Add(propInfo.Name, JToken.FromObject(new { type = cutomAttribute.Type, displayname = cutomAttribute.DisplayName ?? propInfo.Name, value = propVal ?? string.Empty }, serializer));
                        jo.Add(propInfo.Name, JToken.FromObject(propVal ?? string.Empty, serializer));


Try yourself with dot net fiddle

Round up a number to highest 10s place


Download Source Code

Recently we faced a problem that we need to round-up a number to greatest 10s place.
For ex: we needed to round-up a number as follows
1023 -> 2000
37911 -> 40000
912345 –> 1000000

First we checked Math.Round(). However, it did not solve our problem.  Math.Round() supports only rounds a value to the nearest integer or the specified number of fractional digits. Further checking we come up a solution by using Math.Ceiling() method.

Math.Ceiling()returns the smallest integral value that is greater than or equal to the specified double-precision floating point number.
For ex:
Math.Ceiling(7.3)     -> 8
Math.Ceiling(7.64)     -> 8
Math.Ceiling(0.12)     -> 1

Below is the solution we came up

decimal[] values = { 1023, 37911, 23000, 1234, 912345 };
foreach (var value in values) {
//// get the lenght of the 10s places;
var length = (int)Math.Log10((double)value);
//// using Math.Pow() calculate the power of 10s
var power = Math.Pow(10, length);
//// var roundadValue = Math.Ceiling(1023 / 1000) * 1000;
var roundadValue = Math.Ceiling(value / (decimal)power) * (decimal)power;

Console.WriteLine("Value:{0} Rounded Value:{1}", value, roundadValue); 


Math.Ceiling() Results

The Logic

Math.Ceiling(value / (decimal)power) * (decimal)power;
var roundadValue = Math.Ceiling(1023 / 1000) * 1000;

So, for any number, fist compute power of 10s and then it use for the above calculation to get the results.

Counting Consecutive Dates Using SQL


Download demo query

Recently I have answered one of the SQL-based questions in the CodeProject. Thanks for the participant that question wake up me to write this blog post.


He has a table (tblLeave) with the data like below.

5023		SL    	14/12/2012 0:00		14/12/2012 0:00		1
5023		SL    	15/12/2012 0:00		15/12/2012 0:00		1
5023		COF   	16/12/2012 0:00		16/12/2012 0:00		1
5023		SL    	19/12/2012 0:00		19/12/2012 0:00		1
5023		SL    	22/12/2012 0:00		22/12/2012 0:00		1
5023		SL    	23/12/2012 0:00		23/12/2012 0:00		1
5023		SL    	24/12/2012 0:00		24/12/2012 0:00		1
5023		PL    	28/12/2012 0:00		28/12/2012 0:00		1
5023		PL    	29/12/2012 0:00		29/12/2012 0:00		1
5023		PL    	30/12/2012 0:00		30/12/2012 0:00		1
5023		PL    	31/12/2012 0:00		31/12/2012 0:00		1

Moreover, he wants to output the data as below

5023    SL      14/12/2012 0:00 15/12/2012 0:00 2
5023    COF     16/12/2012 0:00 16/12/2012 0:00 1
5023    SL      19/12/2012 0:00 19/12/2012 0:00 1
5023    SL      22/12/2012 0:00 24/12/2012 0:00 3
5023    PL      28/12/2012 0:00 31/12/2012 0:00 4

Condition: If the same type of leave taken continuously, it should be merged in one row mentioning from_date to to_date.


When I saw that question the first time, I did not go through in details and just thought that was an easy grouping query. And I just gave following answer.

FROM tblLeave

However, that is wrong, he made comments saying it does not make sense and highlighted the condition he wants. (Thanks to him; he did not down vote my answer). Again I read the question… Oh… That was a tricky question. He needs to group the leave by consecutive date. Isn’t that tricky?

To answer that, I use the DATEDIFF SQL function

DATEDIFF ( datepart , startdate , enddate )

Following is my answer and the output

FROM tblLeave) AS dt
PAYCODE     LV_TYPE FROM_DATE               TO_DATE                 LVALUE
----------- ------- ----------------------- ----------------------- -----------
5023        SL      2012-12-14 00:00:00.000 2012-12-15 00:00:00.000 2
5023        COF     2012-12-16 00:00:00.000 2012-12-16 00:00:00.000 1
5023        SL      2012-12-19 00:00:00.000 2012-12-19 00:00:00.000 1
5023        SL      2012-12-22 00:00:00.000 2012-12-24 00:00:00.000 3
5023        PL      2012-12-28 00:00:00.000 2012-12-31 00:00:00.000 4

Query Explanation:

Before explaining the logic see the following query and the output.

FROM tblLeave
PAYCODE     LV_TYPE FROM_DATE               ROW_NUMBER           Diff
----------- ------- ----------------------- -------------------- -----------
5023        SL      2012-12-14 00:00:00.000 1                    41254
5023        SL      2012-12-15 00:00:00.000 2                    41254
5023        COF     2012-12-16 00:00:00.000 3                    41254
5023        SL      2012-12-19 00:00:00.000 4                    41256
5023        SL      2012-12-22 00:00:00.000 5                    41258
5023        SL      2012-12-23 00:00:00.000 6                    41258
5023        SL      2012-12-24 00:00:00.000 7                    41258
5023        PL      2012-12-28 00:00:00.000 8                    41261
5023        PL      2012-12-29 00:00:00.000 9                    41261
5023        PL      2012-12-30 00:00:00.000 10                   41261
5023        PL      2012-12-31 00:00:00.000 11                   41261

By seen this, you will realize that above query generate the same Diff  value for all the consecutive dates. Now you can easily group this and get the counts as you like.

Adding styles dynamically to ASP.NET page header


Recently when I was working on the ASP.NET website I wanted to modify the page styles dynamically. I googled and found that there are various techniques out there for this. In this Article, I wish to share those techniques with.

Following are some of the techniques out there to accomplish this.

1. By using Page.header.Controls.Add()

Page.Header property gets the document header of the page if the head element is defined with “runat=server”  tag in the page declaration.The Header property gets a reference to an HtmlHead object that you can use to set document header information for the page. The HtmlHeadallows you to add information such as style sheets, style rules, a title, and metadata to the head element.

By using a literal control, you can include the CSS file or even a style set.

Literal cssFile = new Literal()
    Text = @"styleFilePath) + @""" type=""text/css"" rel=""stylesheet""/>"


new LiteralControl(
background: black;
border: 1px solid;

Alternatively, HtmlGenericControl can use to add the styles file

//// Insert css file to header
HtmlGenericControl oCSS = oCSS = newHtmlGenericControl();
oCSS.TagName = "link";
oCSS.Attributes.Add("href", "css/mystyle.css");
oCSS.Attributes.Add("rel", "stylesheet");
oCSS.Attributes.Add("type", "text/css");

2.  Page.Header.Stylesheet

The more elegant technique is used of the Page.Header.Stylesheet Instead of using the string to defend styles (like above with Literal) you can use the style properties to create this.

//// Create dynamic style rule which applies to the css class selector (“.MyCssClass”)
Style dynamicClassStyle = new Style();
dynamicClassStyle.BorderStyle = BorderStyle.Solid;
dynamicClassStyle.BorderColor = System.Drawing.Color.Black;
dynamicClassStyle.BorderWidth = new Unit(1);
dynamicClassStyle.BackColor = System.Drawing.Color.White;
Page.Header.StyleSheet.CreateStyleRule(dynamicClassStyle, null, ".MyCssClass");


//// Create dynamic style rule which applies to type selector ("DIV")
Style dynamicTypeStyle = new Style();
dynamicTypeStyle.BorderStyle = BorderStyle.Solid;
dynamicTypeStyle.BorderColor = System.Drawing.Color.Black;
dynamicTypeStyle.BorderWidth = new Unit(1);
dynamicTypeStyle.BackColor = System.Drawing.Color.White;
Page.Header.StyleSheet.CreateStyleRule(dynamicTypeStyle, null, "DIV");

For more information, please refer

With whatever the technique you follow, please remember the following hints also,

Adding styles programmatically using the methods of the IStyleSheet interface during asynchronous postbacks is not supported. When you add AJAX capabilities to a Web page, asynchronous postbacks update regions of the page without updating the whole page.

Web service and Script service


Most of you are familiar with writing a web service using c#. Visual Studio provides the project template that easily creates a web service for you.

Visual Studio Project Template

Hello world web service

I am sure you may know how to call this web service using c#. However, do you know how to call the web service using client-side scripts such as JavaScript? There are various ways to do this. I will demonstrate this using jQuery$.ajax() function.

        function callSvc() {
                type: "POST",
                url: "Service1.asmx/HelloWorld",
                data: "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data, status) { alert(data); },
                error: function(request, status, error) { alert(request); alert(status); alert(error); }

When you call the HelloWorld() service, by default you will get “500 – Internal server error” error message.

JavaScript debug mode

This error raised because you have not configured this service to access using client side scripts. When you Check the responseText, you will notice that it says “Only Web services with a [ScriptService] attribute on the class definition can be called from script.”

To resolve this, you have to configure your web service with [ScriptService] attribute.

public class Service1 : System.Web.Services.WebService

When adding [ScriptService] attribute to the web service, it gets automatically handled by the ScriptHandlerFactory and creates a JavaScript proxy class for the web service. That means you will be able to call the web service from the client side script same way as you call it from the code behind. You can view the generated proxy class by using the following command.


Compare the generated proxy class with the service description (http://<URL>/Service1.asmx?WSDL) and let me know what you noticed.

Download Demo Project

How to validate a credit card number?


All you know what information contains in your NIC number. But do you know what information contains in the Credit Card Number? Here are some useful details.

Card Length

Typically, credit card numbers are all numeric and the length of the credit card number is between 12 digits to 19 digits.

  • 14, 15, 16 digits – Diners Club
  • 15 digits – American Express
  • 13, 16 digits – Visa
  • 16 digits – MasterCard

For more information refer:

Containing Information

Sample Credit Card

1 – Major Industry Identifier (MII)

The first digit of the credit card number is the Major Industry Identifier (MII). It designates the category of the entry which issued the card.

  • 1 and 2 – Airlines
  • 3 – Travel
  • 4 and 5 – Banking and Financial
  • 6 – Merchandising and Banking/Financial
  • 7 – Petroleum
  • 8 – Healthcare, Telecommunications
  • 9 – National Assignment

2 – Issuer Identification Number

The first 6 digits are the Issuer Identification Number. It will identify the institution that issued the card. Following are some of the major IINs.

  • Amex – 34xxxx, 37xxxx
  • Visa – 4xxxxxx
  • MasterCard – 51xxxx – 55xxxx
  • Discover – 6011xx, 644xxx, 65xxxx

3 – Account Number

Taking away the 6 identifier digits and the last digits, remaining digits are the person’s account number (7th and following excluding last digits)

4 – Check digits

Last digit is known as check digits or checksum. It is used to validate the credit card number using Luhn algorithm (Mod 10 algorithm).

For more information please refer.

Luhn algorithm (Mod 10)

The Luhn algorithm or Luhn formula, also known as the “modulus 10” or “mod 10” algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in US and Canadian Social Insurance Numbers. It was created by IBM scientist Hans Peter Luhn. (

When you implementing the ecommerce application, it is good practice to validate credit card number before send it to the bank validation. This saves a lot of time and money by avoiding a trip to the bank.

Here are the Luhn steps which can used to validate the credit card number.

4 0 1 2 8 8 8 8 8 8 8 8 1 8 8 1

1. Starting with the check digit double the value of every other digit (right to left every 2nd digit)

Mod 10 Step 1

2. If doubling of a number results in a two digits number, add up the digits to get a single digit number. This will results in eight single digit numbers

Mod 10 Step 2

3. Now add the un-doubled digits to the odd places

Mod 10 Step 3

4. Add up all the digits in this number

Mod 10 Step 4

If the final sum is divisible by 10, then the credit card number is valid. If it is not divisible by 10, the number is invalid.

Here is the code sample that I used to do the mod10 validation

public static bool Mod10Check(string creditCardNumber)
 //// check whether input string is null or empty
 if (string.IsNullOrEmpty(creditCardNumber))
 return false;

//// 1. Starting with the check digit double the value of every other digit
 //// 2. If doubling of a number results in a two digits number, add up the digits to get a single digit number. This will results in eight single digit numbers
 //// 3. Get the sum of the digits
 int sumOfDigits = creditCardNumber.Where((e) => e >= '0' && e <= '9')
 .Select((e, i) => ((int)e - 48) * (i % 2 == 0 ? 1 : 2))
 .Sum((e) => e / 10 + e % 10);
 //// If the final sum is divisible by 10, then the credit card number is valid. If it is not divisible by 10, the number is invalid.
 return sumOfDigits % 10 == 0;

The original article was modified according to the comments made by Code Project super users.

Download Demo Project

Exclude crystal report embedding when building the ASP.Net web site


If you have worked with ASP.Net web applications which include number of crystal reports as part of that, you might have experienced it takes a long time to build the web site. This happens, because by default crystal reports are set to be embedded as a resource.In default your “web.config” displays as follows.

Web config default configuration for crystal report

To resolve this, you can simply modify the embedRptInResource=”false” as follows.

            <add embedRptInResource="false"/>