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.