Friday, January 12, 2018

JWT Sample Code

Json Web Token.

Looks like Json Web Tokens or simply JWT is having a lot of popularity that Microsoft released a library to encrypt and decrypt those tokens.

In order to generate a JWT token you should install this nuget package

System.IdentityModel.Tokens.Jwt

Then you can generate tokens that contain information like CompanyId, UserName or even password as follows

        private  string Secret = "db3OIsj+BXE9NZDy0t8W3TcNekrF+2d/1sFnWG4HnV8TZY30iTOdtVWJG8abWvB1GlOgJuQZdcF2Luqm/hccMw==";

        public  string GenerateToken()
        {
            // var hmac = new HMACSHA256();
            //Secret = Convert.ToBase64String(hmac.Key);

            var sKey = Convert.FromBase64String(Secret);
            var tHandler = new JwtSecurityTokenHandler();

            var tDesc = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim("companycode", "companycode"),
                    new Claim("username", "username"),
                    new Claim("password", "password"),
                    new Claim("companyid", "25"),
                }),

                Expires = DateTime.UtcNow.AddMinutes(45),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(sKey),SecurityAlgorithms.HmacSha256Signature),
                Issuer = "HajOnSoft.com"
            };

            var stoken = tHandler.CreateToken(tDesc);
            return  tHandler.WriteToken(stoken);
        }

In the generate token method, you can add claims to pass parameters as you please.


To get a specific value from the token you can call a method like this

        public  int GetCompanyId(string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;

                if (jwtToken == null)
                    return -1;

                var symmetricKey = Convert.FromBase64String(Secret);

                var validationParameters = new TokenValidationParameters()
                {
                    RequireExpirationTime = true,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)
                };

                SecurityToken securityToken;
                var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken);
                var myClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "companyid");
                if (myClaim != null)
                    return int.Parse(myClaim.Value);
                else
                {
                    return -1;
                }
            }

            catch (Exception ex)
            {
                return -1;
            }
        }


for more information visit
http://techcerberus.blogspot.com/2017/03/jwt-in-aspnet-web-api-and-mvc.html


Sunday, December 17, 2017

On MicroServices

Microservices is Service Oriented Architecture done well. It is based on creating small services (micro-sized) that are focussed on a business domain and are small enough to be called Micro. Every microservice service should be doing one thing (one thing only) and doing it very well. should be light weight and technology agnostic and communicate via something like http REST, each service should own its own database and be independently changeable and deployable. Every transaction will most likely be completed by many services and because there are many services there should be a way to monitor them.

Every Microservice should be Coherent and that means it is focussed on doing one thing, it should not change because another service is changing or a new column in some database is being added. That means when adding new functionality you should add a new micros service. You micorservice should have only one reason to change.
AutonomousShould be independent and own its contracts, independently developed. should probably respond right away via asynchronous patterns, you should also look into Message Queue, RabbitMQ and ATOM. Observable, You should have a central monitoring System to know what services are operational now and what is their individual health status. monitor exceptions, centralized logging, maintain correlation ID, etc.. there are many software solutions that provide this out of the box already like Azure Service fabric. basically every service should be able to register itself so that other services can discover it is up and running. Resilient, Services should also be able to fail gracefully and provide default values when they are not operational.

You may however provide an API gateway for all clients as an entry point for all Microservices. the API gateway can perform some common tasks like authentication and then relay to the specific microservice. 

Every microservice should own its own database, for shared data you can create a separate microservice for static or shared data but should not provide a single monolithic service for all system wide CRUD operations since it will continuously change which is against the first princible which is cohesion.

Monday, November 27, 2017

Tree traversal

If you will be asked in an interview to traverse a tree most likely it will not be depth first or breadth first but rather it will be a special traversal. You will be given a hierarchical table with ID's and parent ID's like the following table for instance.
The table below indicate that the first two nodes has no parent for instance, and then few nodes are under one of them and so on.

ID ParentId Name
5 null Grandfather
8 null Grandmother
7 5 son 1
4 5 daughter
2 5 son 2
3 7 grandchild

and then you will be asked to print the above nodes as follows
-Grandfather
        -Son 1
                -Grandchild
        -daughter
        -Son 2
-Grandmother

Here is the solution with explanation

class Program
    {
        static void Main(string[] args)
        {
            var n = MakeModel();// Make the model  
            PrintNode(n, new Customer{ID = -1, ParentId = null, Name = "-1"}, -1); 
            //Pass one node that can combine the root nodes under it
            Console.ReadKey();
        }

        private static void PrintNode(List<Customer> nodes, Customer n, int dept)
        {
            //Algorithm
            //When readhing a node, immediately print it
            //Get all children for the current node and recursively call the same method passing a child node at a time
            //each time you go one level deeper increase a the depth variable that maintaines 
            //how deep in the tree you are now
            if (dept >= 0) Console.WriteLine( new String('\t', dept) + "-" +  n.Name);
            var children = nodes.Where(x => x.ParentId == n.ID).ToList();
                foreach (var child in children)
                    PrintNode(nodes, child, dept + 1);
                    //Code here will execute on the way back
        }

        private static List<Customer> MakeModel()
        {
            var output = new List<Customer>
            {
                new Customer {ID = 5, ParentId = -1, Name = "Grandfather"},
                new Customer {ID = 8, ParentId = -1, Name = "Grandmother"},
                new Customer {ID = 7, ParentId = 5, Name = "Son 1"},
                new Customer {ID = 4, ParentId = 5, Name = "daughter"},
                new Customer {ID = 2, ParentId = 5, Name = "Son 2"},
                new Customer {ID = 3, ParentId = 7, Name = "Grandchild"}
            };
            return output;
        }
        
    }


    public class Customer
    {
        public int ID { get; set; }
        public int? ParentId { get; set; }

        public string Name { get; set; }

    }

Wednesday, November 01, 2017

Merge two sorted arrays

//Given two sorted integer arrays A and B, merge B into A as one sorted array.
            //example 1346789
            //        35689  

            var arr1 = new List<int> { 4,5 };
            var arr2 = new List<int> { 1,2,3 };

            //Loop length of arr1 - start 0 untill end of array - p = index
            //Optimization use shortest array 
            //Pick element at p, compare it with all elements in arr2 - Loop Arr2 start from last point examined
            //if arr1 Element <= arr2 element and < arr2
            //insert arr1 element left of arr2 element, otherwise keep going
            var r2 = arr2.Count;
            for (int p = 0; p < arr1.Count; p++)
            {
                for (int j = 0; j < r2; j++)
                {
                    if (arr1[p] <= arr2[j])
                    {
                        arr2.Insert(j, arr1[p]);
                        r2 = arr2.Count;
                        break;
                    }

                    if (j == r2-1) //Last item in arr2 and loop did not break above
                    {
                        arr2.Add(arr1[1]);
                        r2 = arr2.Count;
                    }
                }


            }

Insertion Sort

 var arr = new List<int> { 5,6,1,2,3,1 };// input.ToCharArray().Cast<int>().ToList();
            //Loop length of array - start from second position
            
            //Compare pointer to previous item
            //make smaller to the left untill you reach the beginning of the array

            var currentItem = 0;
            for (int p = 1; p < arr.Count; p++)
            {
                currentItem = arr[p];
                //Loop from current p position to beginning of array - pointing at location of comparison with current item and potential location of currentItem
                //If currentItem is smaller then swap 
                for (int i = p - 1 ; i >= 0; i--)
                {
                    if (currentItem < arr[i])
                    {
                        var temp = arr[i];
                        arr[i] = currentItem;
                        arr[i+1] = temp;
                    } 
                    else
                    {
                        break;
                    }
                }
                
            }

           

Tuesday, October 31, 2017

Find Peak

            //given a number of characters find the peak character which is the current that is repeated the most, there can be more than one character at the peak if the number of repeatition tie
            var input = "abbabacdexxxxxxdx"; //return x
            var arr = input.ToCharArray();
            arr = arr.OrderBy(x=> x).ToArray(); //order the list to know when to stop counting occurence
            //Initialize result container
            var result = new List<char>();
            //Loop length of array - pointing to index from left p = 0 
            var currentMax = 0;
            var prevChar = arr[0];
            var r = 0;
            for (int p = 0; p < arr.Length ; p++)
            {
                if (arr[p] == prevChar)
                {
                    r++;
                }
                else
                {
                    if (r > currentMax)
                    {
                        result = new List<char> { arr[p - 1] };
                    }
                    else if (r == currentMax)
                    {
                        result.Add(arr[p - 1]);
                    }
                    currentMax = r;
                    prevChar = arr[p];
                    r = 1;
                }
            }
            //Keep previous character
            //Compare arr[p] to previous 
            //Equal count repeatition r of a
            //not equal stop counting repeatition and compare to max if less than max discard 
            //If equal to max append to peak
            //if less than discard
            //greater than max 
            //discard output collected previously and initialize it only with this character

            if (r > currentMax)
            {
                result = new List<char> { arr.Last() };
            }
            else if (r == currentMax)
            {
                result.Add(arr.Last());

            }

Reverse string without its special characters

Special characters need to stay in place while the entire string is reversed

 //Reverse string without moving any special character from its place
            var input = "ab$cde#x"; //"xe$cdb#a";
            var arr = input.ToCharArray();

            var h = -1;
            var t = -1;
            //Loop - half length of the array with pointer index of array from left
            for (int p = 0; p < arr.Length/2; p++)
            {
                //Find non special character from left
                if (Regex.IsMatch(arr[p].ToString(),"[a-z]") && h < 0) //non special character
                    h = p;

                //Find non special chracter from right
                if (Regex.IsMatch(arr[arr.Length - p - 1].ToString(), "[a-z]") && t < 0) //non special character
                    t = arr.Length - p - 1;


                //If holding two non special chracters then swap them
                if (h >= 0 && t >= 0) //Non special chracters both directions
                {
                    //Swap
                    var temp = arr[h];
                    arr[h] = arr[t];
                    arr[t] = temp;

                    h = -1;
                    t = -1;
                }
                
               



            }

Rotate Array

Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. How many different ways do you know to solve this problem?

Using LINQ
            var arr = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
            //Rorate array to the right
            var k = 10 % 7;

            //should move to the beginnning
            var output = arr.Skip(arr.Count - k).ToList();
            output.AddRange(arr.Take(arr.Count - k));
         

            Console.ReadLine();

Using Add Method

 var arr = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
            //Rorate array to the right
            var k = 10 % 7;
            //Move the head of the array to the tail number of times = k
            for (int i = 0; i < arr.Count - k; i++)
            {
                arr.Add(arr[0]);
                arr.RemoveAt(0);
            }

Using Insert
 var arr = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
            //Rorate array to the right
            var k = 10 % 7;
            //Move the head of the array to the tail number of times = k
            for (int i = 0; i < k; i++)
            {
                arr.Insert(0, arr.Last());
                arr.RemoveAt(arr.Count -1);
            }

Reverse Words in a string

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?

            
Allocating Extra space for output

var input = "ayman ali";
            input = " " + input;
            var arr = input.ToCharArray();
            var output = string.Empty;
            var b = 0;
            var e = arr.Length;
            for (int p = arr.Length - 1; p >= 0; p--)
            {
                if (arr[p] == ' ' )// little off beginning of word
                {
                    b = p + 1;
                    output += input.Substring(b, e - b) + " ";
                    e = p ;

                }
            }
            Console.WriteLine(output.TrimEnd(' '));

            Console.ReadLine();

Without allocating extra space
            //Reverse words in string
            var input = "ayman ali";
             input = input + " ";
            var arr = input.ToCharArray();
            //Loop - Pointer (p) is index - Length is length of array
            //If space found - e = p - 1, begin (b) saved from before
            //Reverse string in place
                //Loop half length of string
                //i to m (Mirror) m = e-i

            //Reverse whole string

            var b = 0;
            var e = 0;
            for (int p = 0; p < arr.Length ; p++)
            {
                if (arr[p] == ' ')
                {
                    e = p - 1;
                    for (int i = b; i < (b+ (e-b) /2); i++)
                    {
                        var temp = arr[i];
                        var m = e - (i - b);
                        arr[i] = arr[m];
                        arr[m] = temp;
                    }
                    b = p + 1;

                }
            }
            //arr need to be revsrsed
            e = arr.Length-1;
            for (int p = 0; p < e/2; p++)
            {
                var temp = arr[p];
                var m = e - p - 1;
                arr[p] = arr[m];
                arr[m] = temp;
            }

            Console.WriteLine(string.Join(string.Empty, arr.Take(e)));
         
            Console.ReadLine();

Monday, October 30, 2017

Reverse Word Characters in Place

Given a string, Reverse every word in the string in place. For example if you have Ayman Ali, running the algorithm should result in namyA ilA.

Solutions
            //Reverse words in string
            var input = "ayman ali";
            input += " ";
            //Convert into Array
            var arr = input.ToCharArray();
            //Loop Through the array with the length of the array
            var b = 0; //Pointer to an actual element
            var e = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] == ' ') //Space reached
                {

                    e = i - 1;
                    //Rotate in place
                    for (int p = b; p < e - ((e-b) / 2); p++)
                    {
                        var temp = arr[p];
                        var m = e - (p - b);
                        arr[p] = arr[m];
                        arr[m] = temp;
                    }
                    b = e + 2;
                }
            }
            //If first element note b = Begin of new word
            //IF space or end of string
            //      Record the position as end of word (e)
            //      Rotate the word beginning with b and ending with e
            //      let b = e + 2
            //Else 
            //      Continue
            //End Loop


            //Rotate a word
            //Loop through the word (Length half the word) begin with b and end with e
            //Save Pointer element temporarily
            //Save mirror position (m) into pointer position (p) - Define mirror position 
            //save p into m

            Console.WriteLine(string.Join("",arr.Take(arr.Length-1)));

           //Console.WriteLine(string.Join(",", out));

            Console.ReadLine();

Tuesday, June 06, 2017

File upload and unzipping files

If you want to unzip a file here are few lines that unzips a zip file and delivers the contents as a stream. Here I am assuming the zip file contain images

 if (fuPhotos.FileName.ToLower().EndsWith(".zip"))
                {
                    var za = new System.IO.Compression.ZipArchive(fuPhotos.PostedFile.InputStream);
                    foreach (var entry in za.Entries)
                    {
                        var img = System.Drawing.Image.FromStream(entry.Open());
                        img.Save(@"c:\temp\" + Path.GetFileName(entry.FullName));
                    }
                }


 if (fuPhotos.FileName.ToLower().EndsWith(".zip"))
This line allows you to check the extension so you are certain the user is uploading a zip file. the extension is one way of detecting that.


var za = new System.IO.Compression.ZipArchive(fuPhotos.PostedFile.InputStream);
This line will get the stream of that file, you need to get a stream because the stream is a generic object that you can handle with other classes like StreamReader, StreamWriter, FileStream, MemoryStream and other objects like System.Drawing.Image that can get you an image from a stream

 foreach (var entry in za.Entries)
This line allows you to loop to work on every entry in the zip file. the entry is a file inside the zip file. you can access its name, contents, etc..

var img = System.Drawing.Image.FromStream(entry.Open());
The Image class can read a stream and entry.Open gets the stream of the entry

img.Save(@"c:\temp\" + Path.GetFileName(entry.FullName));
This line allows you to save the stream


You can deal with multiple files if the user uploads multiple files if you change your code as follows

foreach (var onezipFile in fuPhotos.PostedFiles)
                {

                    if (onezipFile.FileName.ToLower().EndsWith(".zip"))
                    {
                        var za = new System.IO.Compression.ZipArchive(onezipFile.InputStream);
                        foreach (var entry in za.Entries)
                        {
                            var img = System.Drawing.Image.FromStream(entry.Open());
                            img.Save(@"c:\temp\" + Path.GetFileName(entry.FullName));
                        }
                    }

                }