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

 

 

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

How to validate a credit card number?

1

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: http://en.wikipedia.org/wiki/Bank_card_number

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.
http://en.wikipedia.org/wiki/Bank_card_number
http://en.wikipedia.org/wiki/List_of_Issuer_Identification_Numbers

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. (http://en.wikipedia.org/wiki/Luhn_algorithm)

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')
 .Reverse()
 .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