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

Just Learned: Self-XSS


Have you ever tried chrome inspector with Facebook? If so, I am sure you have seen this. This warning message is to help prevent Self-XSS scams.



Self-XSS is a social engineering attack that is designed to gain control of your social media account. In a self-XSS attack, an attacker convinces a user to runs malicious code on the address bar of his/her web browser.

Following video covers both share-baiting (a pure social engineering attack) and self-XSS (a combination of social engineering and a browser vulnerability).


Addition Reference:

How to create formatted console.log message

console.log ("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large");

Formatted Crome Console

How Facebook disabled Chrome developer console earlier

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.

Automate PNG & JPG Image Optimization


Download Source Code


If you are a web developer, you already know how important to reduce the image size by compressing the image. When you are checking the page speed using the tool like “Google PageSpeed Insight” or “Yahoo YSlow”, you can see how many bytes we can save by compressing the image.

Google:Page Speed

Images saved from programs like Fireworks can contain kilobytes of extra comments, and use too many colors, even though a reduction in the color palette may not perceptibly reduce image quality. Improperly optimized images can take up more space than they need to; for users on slow connections, it is especially important to keep image sizes to a minimum.

You should perform both basic and advanced optimization on all images. Basic optimization includes cropping unnecessary space, reducing the color depth to the lowest acceptable level, removing image comments, and saving the image to an appropriate format. You can perform basic optimization with any image editing program, such as GIMP.  Advanced optimization involves further (lossless) compression of JPEG and PNG files. You should see a benefit for any image file that can reduced by 25 bytes or more (less than this may not result in any appreciable performance gain). Optimize images >

There are some online tools like “Yahoo” use lossless compression techniques and reduce file size by removing the unnecessary bytes from the image. However, if you want to make it automate, how do you do that? Several standalone tools are available that perform lossless compression on JPEG and PNG files.

For JPG Google recommended using,

  • Jpegtran – available for both Windows and Linux and Mac
  • Jpegoptim – available only on Linux

For PNG Google recommended using,

Using the code

Here I wrote a windows batch file that recursively search the given folder and optimized the JPEG and PNG files.

  1. Download jpegtran, OptPNG and PNGOUT executable files. (Or download attached zip file all the necessary files already included)
  2. Create a folder “ImageOptimization” in your C:\ Drive. (You can change those name and folder location by editing the batch file content) and put above downloaded utility files there.
  3. Create a batch file “optimize.bat” within the folder and copy following code into it
    @echo none
    REM Optimizing JPEG with jpegtran
    forfiles /p %1 /s /m "*.jpg" /c "cmd /c  echo processing @path && D:\ImageOptimization\jpegtran.exe -optimize -progressive -copy none -outfile @path @path"
    REM Optimizing PNG with pngout
    forfiles /p %1 /s /m "*.png" /c "cmd /c  echo processing @path && D:\ImageOptimization\pngout.exe @path"
    REM Optimizing PNG with optipng
    rem forfiles /p %1 /s /m "*.png" /c "cmd /c  echo processing @path && D:\ImageOptimization\optipng.exe -force -o7 @path"

    Although I included both PNGOUT and OPTPNG in the script you no need to use both.

  4. Finally, you can execute the bat file by passing the image folder you wish to optimize
    optimize.bat “D:\image”

How it works

  • forfiles command – Select a file (or set of files) and execute a command on each file (Batch processing) Refer:
  • %1 – accept the folder as a parameter. In above example, this equals to “D:\Image”

forfiles command find all the images in the given directory (recursively) and execute the optimizing executable by passing the image as a parameter to them (@path).


  1. You can further improve by adding this batch command as a context menu command
  2. Alternatively, even you can use a scheduler (e.g. Windows scheduler) to find the daily updated file and optimize them by slightly modifying the forfiles command with “/d” option.

How to transfer ownership of your android application


Suppose you have developed an Android game and publish that on the Google play. Many users downloaded your app, and you have released few versions also. What if a company wants to acquire your app game? You need to transfer your app to the new business account, and it should display as their registered app. Google makes it quicker and easier way to transfer the ownership of application from one account to another account.

  1. First you have to login to the Google play publish account using the original app owner’s credentials.
  2. Then click Help & Feedback -> Contact Support
    Google Play: Contact Support
  3. Select “I would like to have my apps transferred to a new account. Once you select that it asks to fill the form to resolve the issue.
    Google Play: Contact Support
    Google Play: App Transfer Form
  4. Follow the provided guidelines. It contains several checklist to make sure you are ready to submit the transfer request
    Google Play: App Transfer Checklist
    Make sure,
    You’ll need to prepare both developer account tosubmit your app transfer.

    Original Account – This is the account where your app is currently published.
    Target Account – This is the account you want to transfer your app to.

    Google Play: App Transfer Checklist
    Google Play: Checklist step

  5. Finally, Fill the “Application Transfer Request” and submit the form. Normally Google responds to your request within a day, and if all the details are correct they transfer the app to new account
    Google Play: App Transfer Final Step
    Google Play: Application Transfer Request Form

Google Play: Submit Success

Emoji and web application


Download SQL query

I am back after few months or so of not blogging. Have you heard something called “Emoji”?

iPad Emoji Keyboard

Emoji; is the Japanese term for the ideograms or smileys used mostly in Japanese electronic messages and webpages. These small images are starting to appear more and more outside Japan. Originally meaning pictograph, the word emoji literally means “picture” (e) + “letter” (moji).

If you want to know what the emoji meanings check the following cheat sheet

Although originally only available in Japan, some emoji character sets have been incorporated into Unicode (Unicode 6.0 in 2010), allowing them to be used elsewhere as well. The core emoji are as of Unicode 6.0 consists of 722 characters.

More recent iOS, Android, Windows 8 and OS X (Mountain Lion +) display Emoji natively, regardless of the typeface. However, how we display that on the all other desktop and the web application? When you are viewing Emoji with unsupported device or browser, Emoji shows up as squares or foreign text. You can convert them to a viewable format just by pasting it in the box above then viewing it in the preview.

I have found that several open source JavaScript libraries and the projects support for this. The most comprehensive seems to be Github’s Gemoji project.

Following are some of other good projects and scripts

For more info about Emoji Unicode table, please check below URL

Emoji and Database

Emojis are UTF-8 encoded symbols. Therefore, to save the Emoji in the database, your database column should support for the UTF-8 encoding.

Emoji and MySQL

To store the Emoji in the MySQL, you have to modify the table character set to support UTF-8.  Please keep in mind starting from iOS5, Emoji represents as 4-byte characters.  That means your MySQL table charset should set as utf8mb4. (Earlier version of iOS Emoji worked well with utf8 charset). utf8mb4 support is dependent on the MySQL version that you use. MySQL 5.5+ works fine with 4-byte characters when properly configured.

create table MyEmoji (emojicolumn VARCHAR(255) CHARACTER SET utf8mb4) default character set utf8mb4;

Make Sure Followings,

  1. Your database table character set is: utf8mb4
  2. Your PHP application character set is: UTF-8
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
     header('Content-type: text/html; charset=utf-8');
  3. In the application database, connection character set is: utf8mb4

For more information:

Emoji and MS SQL

SQL Server does not support UTF-8 by default. However, it supports UCS2 to store Unicode characters. (UCS2 is typically UTF-16).  SQL server handles the UTF-8 conversion automatically. However, keep in mind, MS SQL VARCHAR column type does not support for this. Instead of that you have to use NVARCHAR column type. Then you must precede all Unicode strings with a prefix N when you deal with Unicode string constants in SQL Server

For more information:

CREATE TABLE [dbo].[MyEmoji](
    [EmojiColumn] [nvarchar](255) NULL
INSERT INTO MyEmoji (EmojiColumn) VALUES (N'EncodedString')

Make sure followings,

  1. Your database table column is: nvarchar
  2. You are sending in Unicode data by adding an N in front of the encoded string

How to enable Emoji keyboard in iOS and Android

iPhone –
Android –

EmoJi for PHP