Pad numbers with leading and ending zeros


In a recent project, I got a list of integers something similar to following.


and, I was asked to add zeros to the left or right of the list and make it as below.

List 1:

List 2:

C# – PadLeft / PadRight

In C#, you can use PadLeft and PadRight functions to do this.

String.PadLeft Method (Int32, Char)
String.PadRight Method (Int32, Char)

int[] numbers = { 1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789 };

Console.WriteLine("List 1");
foreach (var i in numbers)
Console.WriteLine(i.ToString().PadLeft(10, '0'));

Console.WriteLine("List 2");
foreach (var i in numbers)
Console.WriteLine(i.ToString().PadRight(10, '0'));


PadLeft and PadRight

PadLeft and PadRight


Here comes the interesting part, I had to do this using SQL. In SQL there are no inbuilt PadLeft or PadRight functions.  So, I have used the LEFT and RIGHT SQL functions with a small hack.

CREATE TABLE [dbo].[NumberPadding](
[Number] [int] NOT NULL

INSERT INTO dbo.NumberPadding
VALUES (1), (12), (123), (1234), (12345), (123456), (1234567), (12345678), (123456789)

SELECT LEFT (CAST([Number] AS VARCHAR) + '0000000000', 10) FROM dbo.NumberPadding;

SELECT RIGHT ('0000000000' + CAST([Number] AS VARCHAR) , 10) FROM dbo.NumberPadding;




Windows 10: GodMode


GodeMode is a hidden folder trick that allows users to access all of the operating system’s control panels from within a single folder.

To enable “GodMode” feature for Windows 10, you just need to create a new folder and then name the folder as following:

GodMode: Folder

GodMode: Folder

By default, when you create the GodeMode folder, folder icon change to control panel icon.

Double click the folder and enjoy the features..:)

Windows 10: GodMode

Windows 10: GodMode

Some SQL Tips


1.  I am back after a very long break. So, I somehow forgot SQL Server ‘SA’ Password, and this is how I recovered that.

  • Change the startup parameters by adding add -m;
  • Start SQL Server
  • Open command prompt and type SQLCMD

Method 1:  Create new user and add to systemadmin role

CREATE LOGIN recovery1 WITH PASSWORD = 'abc123%';
sp_addsrvrolemember 'recovery1', 'sysadmin';

Now login using created user and change the ‘Sa’ password

Method 2: Change Password

EXEC sp_password NULL, abc123!@#$', 'sa';

Method 3: Give system admin roles to the windows user

EXEC sp_addsrvrolemember 'Softcat\tharaka_r', 'sysadmin';

2.  I could not remember who wrote this query, but I am sure it was not me. :p  So, I just simplified that.

DECLARE @RunDate AS DATETIME = getdate()
SELECT CONCAT (DATEPART(yyyy,DATEADD(dd,30,@RunDate)),'-', DATEPART(mm,DATEADD(dd,30,@RunDate)),'-', DATEPART(dd,DATEADD(dd,30,@RunDate))) AS DateNow , 30 AS Value;

Simplified version:

DECLARE @RunDate AS DATETIME = getdate();
SELECT CONVERT(VARCHAR(10),DATEADD (dd,30, @RunDate),120) AS DateNow , 30 AS Value;

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.