Pad numbers with leading and ending zeros

0

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

1
12
123
1234
12345
….
123456789

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

List 1:
0000000001
0000000012
0000000123
…..
0123456789

List 2:
1000000000
1200000000
1230000000
….
1234567890

C# – PadLeft / PadRight

In C#, you can use PadLeft and PadRight functions to do this.
https://msdn.microsoft.com/en-us/library/system.string.padleft(v=vs.110).aspx

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();
Console.WriteLine("List 2");
foreach (var i in numbers)
{
Console.WriteLine(i.ToString().PadRight(10, '0'));
}

 

PadLeft and PadRight

PadLeft and PadRight

SQL

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
) ON [PRIMARY]
GO;

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

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

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

SQL – LEFT, RIGHT FUNCTIONS

 

 

Windows 10: GodMode

0

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.{ED7BA470-8E54-465E-825C-99712043E01C}

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

0

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

  • Stop SQL SERVER
  • 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';
GO;

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

Method 2: Change Password

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

Method 3: Give system admin roles to the windows user

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

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

0

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>
    [JsonConverter(typeof(ComplexTypeConverter))]
    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

http://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm

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);

                    }
                    else
                    {
                        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));
                    }
                    else
                    {
                        jo.Add(propInfo.Name, JToken.FromObject(propVal ?? string.Empty, serializer));
                    }

                }
            }
            jo.WriteTo(writer);
        }
    }

Try yourself with dot net fiddle

https://dotnetfiddle.net/Fbyfzd

Just Learned: Self-XSS

0

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.

Facebook-Self-XSS-Warning

Self-XSS

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

https://developer.chrome.com/devtools/docs/console

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

http://stackoverflow.com/questions/21692646/how-does-facebook-disable-the-browsers-integrated-developer-tools/21692733#21692733

Round up a number to highest 10s place

0

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.