Creating Organization Hierarchy in ASP.NET using Google Organizational Chart

In this post I will show you how to integrate google org chart in your asp.net application.
  • First create a new empty website in visual studio
  • Add jquery and google visualization api reference to the default page
Let's first create dummy data.Create following table schema and insert some dummy data into this.
Table Schema

CREATE TABLE [dbo].[EMPLOYEES] (
    [EmpID] CHAR (4)     NOT NULL,
    [Ename] VARCHAR (10) NULL,
    [MGR]   CHAR (4)     NULL,
    PRIMARY KEY CLUSTERED ([EmpID] ASC),
    UNIQUE NONCLUSTERED ([EmpID] ASC)
);
Insert Data
INSERT INTO [dbo].[EMPLOYEES] ([EmpID], [Ename], [MGR]) VALUES (N'7369', N'Smith', N'7902')
INSERT INTO [dbo].[EMPLOYEES] ([EmpID], [Ename], [MGR]) VALUES (N'7499', N'Allen', N'7698')
INSERT INTO [dbo].[EMPLOYEES] ([EmpID], [Ename], [MGR]) VALUES (N'7521', N'Ward', N'7698')
INSERT INTO [dbo].[EMPLOYEES] ([EmpID], [Ename], [MGR]) VALUES (N'7566', N'Jones', N'7839')
INSERT INTO [dbo].[EMPLOYEES] ([EmpID], [Ename], [MGR]) VALUES (N'7654', N'Martin', N'7698')
INSERT INTO [dbo].[EMPLOYEES] ([EmpID], [Ename], [MGR]) VALUES (N'7698', N'Blake', N'7839')
INSERT INTO [dbo].[EMPLOYEES] ([EmpID], [Ename], [MGR]) VALUES (N'7782', N'Clark', N'7839')
INSERT INTO [dbo].[EMPLOYEES] ([EmpID], [Ename], [MGR]) VALUES (N'7788', N'Scott', N'7566')
INSERT INTO [dbo].[EMPLOYEES] ([EmpID], [Ename], [MGR]) VALUES (N'7839', N'King', NULL)
INSERT INTO [dbo].[EMPLOYEES] ([EmpID], [Ename], [MGR]) VALUES (N'7844', N'Turner', N'7698')
INSERT INTO [dbo].[EMPLOYEES] ([EmpID], [Ename], [MGR]) VALUES (N'7876', N'Adams', N'7788')
INSERT INTO [dbo].[EMPLOYEES] ([EmpID], [Ename], [MGR]) VALUES (N'7900', N'James', N'7698')
INSERT INTO [dbo].[EMPLOYEES] ([EmpID], [Ename], [MGR]) VALUES (N'7902', N'Ford', N'7566')
INSERT INTO [dbo].[EMPLOYEES] ([EmpID], [Ename], [MGR]) VALUES (N'7934', N'Miller', N'7782')

How to read mp3 tag info using c#

Mp3 tag  consists of attaching a fixed block size of 128 bytes at the end of the file in question. This block contains the following tags: A header that identifies the presence of block ID3 and version. Specifically, said header comprises TAG characters.

Title: 30 characters.
Artist: 30 characters.
Album: 30 characters.
Year: 4 characters.
Comment: 30 characters.
Genre (music): a character.

How to encrypt Bitmap image in c#


In this post I will show you how to encrypt bitmap image in c#.The technique is very simple.First we extract header from the image and then encrypt the rest byte data and then combined the header with this encrypted data.


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Enc
{
    class Program
    {
        static string FILENAME = @"D:\ub.bmp";
        static string ENCFILENAME = @"D:\enc.bmp";
        static void Main(string[] args)
        {
            //Create instance of DES
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            //Generate IV and Key
            des.GenerateIV();
            des.GenerateKey();
            //Set Encryption mode
            des.Mode = CipherMode.ECB;
            //Read
            FileStream fileStream = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
            MemoryStream ms = new MemoryStream();
            fileStream.CopyTo(ms);
            //Store header in byte array (we will used this after encryption)
            var header = ms.ToArray().Take(54).ToArray();
            //Take rest from stream
            var imageArray = ms.ToArray().Skip(54).ToArray();
            //Create encryptor
            var enc = des.CreateEncryptor();
            //Encrypt image
            var encimg = enc.TransformFinalBlock(imageArray, 0, imageArray.Length);
            //Combine header and encrypted image
            var image = Combine(header, encimg);
            //Write encrypted image to disk
            File.WriteAllBytes(ENCFILENAME, image);


        }
        public static byte[] Combine(byte[] first, byte[] second)
        {
            byte[] ret = new byte[first.Length + second.Length];
            Buffer.BlockCopy(first, 0, ret, 0, first.Length);
            Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
            return ret;
        }
    }
}

How to post array of hashes in wcf

In this post I will show you how to post json array hashes in wcf rest service.Before going to code snippet let's discuss some basic terminology.

What is Array of Hashes
Array of hashes is a data structure in which each record itself contains key/value pairs. Arrays of hashes are used less frequently than the other structures.Below is example of array of hashes
AoH = (
    {
       husband  => "barney",
       wife     => "betty",
       son      => "bamm bamm",
    },
    {
       husband => "george",
       wife    => "jane",
       son     => "elroy",
    },

    {
       husband => "homer",
       wife    => "marge",
       son     => "bart",
    },
  );
JSON String

When we enclosed the json data into quote then we called this string is JSON string
var jsonString='[{ "x": 10, "y": 20, "z": 30 }, { "x": 12, "y": 21, "z": 33 }, { "x": 13, "y": 23, "z": 35}]';

Object literal
When we don't enclosed string in quote then we called this as JSON object literals
var jsonObject= [{ "x": 10, "y": 20, "z": 30 }, { "x": 12, "y": 21, "z": 33 }, { "x": 13, "y": 23, "z": 35}];

For this demo I am going to use JSON.NET library.First go to nuget package manager and install json lib.After that create a simple REST service shown as below.
https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http://3.bp.blogspot.com/-pxgGPGCnpAE/UfqRQKBLOMI/AAAAAAAACis/VwfcmWb2BWc/s640/newton.png&container=blogger&gadget=a&rewriteMime=image/*

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Newtonsoft.Json;
namespace WcfService2
{

    public class Service1 : IService1
    {
        public string GetData(string value)
        {
            StringBuilder stringBuilder = new StringBuilder();
            dynamic data = JsonConvert.DeserializeObject(value);
            foreach (var item in data)
            {
                stringBuilder.Append(item.x);
            }
            return stringBuilder.ToString();
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService2
{

    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "POST")]
        string GetData(string value);

    }

}

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WcfService2.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-2.0.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#id").click(function () {
                var d = '[{ "x": 10, "y": 20, "z": 30 }, { "x": 12, "y": 21, "z": 33 }, { "x": 13, "y": 23, "z": 35}]';
                $.ajax({
                    type: 'POST',
                    url: "http://localhost:1449/Service1.svc/GetData",
                    data: JSON.stringify(d),
                    contentType: "application/json",
                    success: function (data) {
                    },
                    complete: function () {
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="S" id="id" />
    </div>
    </form>
</body>
</html>

Low level bit hacks

I came across a very interesting article on Peteris Krumin’s blog on how to use boolean operators to perform really useful low level bit hacks.

Most people are used to just using AND and OR operators on integers, but this article goes into much more detail, explaining good – and fast – ways to manipulate integers at a bit level.

It is well worth it to go and check it out.

How to stream video in asp.net using WCF rest service

In this post I will show you how to stream video in asp.net using WCF rest service.The techniques used here is as we don't know the exact content lenght of the data so we used Content-Encoding transfer encoding allows a server to maintain an HTTP persistent connection for dynamically generated content. In this case the HTTP Content-Length header cannot be used to delimit the content and the next HTTP request/response, as the content size is as yet unknown. Chunked encoding has the benefit that it is not necessary to generate the full content before writing the header, as it allows streaming of content as chunks and explicitly signaling the end of the content, making the connection available for the next HTTP request/response..
  • Open visual studio and create a simple wcf service.
  • Add a new class and add following code into it

How to create custom config section in asp.net

You can extend ASP.NET configuration settings with XML configuration elements of
your own. To do this, you create a custom configuration section handler.
The handler must be a .NET Framework class that inherits from 
the System.Configuration.ConfigurationSection class. The section handler 
interprets and processes the settings that are defined in XML configuration 
elements in a specific section of a Web.config file. You can read and write 
these settings through the handler's properties.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace CustomConfigSection
{
    public class LoginRedirectByRoleSection : ConfigurationSection
    {
        [ConfigurationProperty("roleRedirects")]
    public RoleRedirectCollection RoleRedirects
        {
    get
            {
    return (RoleRedirectCollection)this["roleRedirects"];
            }
    set
            {
    this["roleRedirects"] = value;
            }
        }
    }
    public class RoleRedirect : ConfigurationElement
    {
        [ConfigurationProperty("role", IsRequired = true)]
    public string Role
        {
    get
            {
    return (string)this["role"];
            }
    set
            {
    this["role"] = value;
            }
        }
        [ConfigurationProperty("url", IsRequired = true)]
    public string Url
        {
    get
            {
    return (string)this["url"];
            }
    set
            {
    this["url"] = value;
            }
        }
    }
    public class RoleRedirectCollection : ConfigurationElementCollection
    {
    public RoleRedirect this[int index]
        {
    get
            {
    return (RoleRedirect)BaseGet(index);
            }
        }
    public RoleRedirect this[object key]
        {
    get
            {
    return (RoleRedirect)BaseGet(key);
            }
        }
    protected override ConfigurationElement CreateNewElement()
        {
    return new RoleRedirect();
        }
    protected override object GetElementKey(ConfigurationElement element)
        {
    return ((RoleRedirect)element).Role;
        }
    }
}

<configSections>
    <section name="loginRedirectByRole" type="CustomConfigSection.LoginRedirectByRoleSection,CustomConfigSection" allowLocation="true" allowDefinition="Everywhere" />
    </configSections>
    <loginRedirectByRole>
    <roleRedirects>
    <add role="Administrator" url="~/Admin/Default.aspx" />
    <add role="User" url="~/User/Default.aspx" />
    </roleRedirects>
    </loginRedirectByRole>

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomConfigSection;
namespace CustomConfigSection
{
    public partial class WebForm1 : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
        {
           LoginRedirectByRoleSection roleRedirectSection = (LoginRedirectByRoleSection)ConfigurationManager.GetSection("loginRedirectByRole");
    foreach (RoleRedirect roleRedirect in roleRedirectSection.RoleRedirects)
            {
    if (Roles.IsUserInRole("", roleRedirect.Role))
                {
                    Response.Redirect(roleRedirect.Url);
                }
            }
        }
    }
}

How to read webpage asynchronously in c#

most programming languages a called method is executed synchronously, i.e. in the thread of execution from which it is invoked. If the method needs a long time to completion, e.g. because it is loading data over the internet, the calling thread is blocked until the method has finished. When this is not desired, it is possible to start a "worker thread" and invoke the method from there. In most programming environments this requires many lines of code, especially if care is taken to avoid the overhead that may be caused by creating many threads. AMI solves this problem in that it augments a potentially long-running ("synchronous") object method with an "asynchronous" variant that returns immediately, along with additional methods that make it easy to receive notification of completion, or to wait for completion at a later time.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
namespace AsyncDemo
{
class Program
    {
static void Main(string[] args)
        {
string url = @"http://microsoft.com";
            DownloadAsync(url);
            Console.WriteLine("Doing Some more work in main");
            Console.ReadLine();
        }
private static void DownloadAsync(string url)
        {
var httpwebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpwebRequest.BeginGetResponse(ar =>
                {
var webResponse = httpwebRequest.EndGetResponse(ar);
using (var responseStream = webResponse.GetResponseStream())
                    {
var manulaResetEvent = new ManualResetEvent(false);
//Set the buffer size
byte[] buffer = new byte[1024];
//Callback
                        AsyncCallback readCallback = null;
                        readCallback = ir =>
                            {
var bytesRead = responseStream.EndRead(ir);
if (bytesRead > 0)
                                {
                                    Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, buffer.Length));
                                    responseStream.BeginRead(buffer, 0, buffer.Length, readCallback, null);
                                }
else
                                {
//Alowing waiting thread to proceed
                                    manulaResetEvent.Set();
                                }
                            };
                        responseStream.BeginRead(buffer, 0, buffer.Length, readCallback, null);
//Block the current thread
                        manulaResetEvent.WaitOne();
                    }
                }, null);
        }
    }
}

Silverlight MVVM

What is MVVM pattern as per wikipedia "The Model View ViewModel (MVVM) is an architectural pattern used in software engineering that originated from Microsoft as a specialization of the Presentation Model design pattern introduced by Martin Fowler.[1] Largely based on the model–view–controller pattern (MVC), MVVM is a specific implementation targeted at UI development platforms which support the event-driven programming in Windows Presentation Foundation (WPF) and Silverlight on the .NET platforms using XAML and .NET languages. Technically different, but similar, Presentation Model design patterns are available in HTML5[2][3] through KnockoutJS, and for Java the ZK framework (Model-View-Binder)."







ViewModelBase.cs



using System;
using System.ComponentModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace MVVMDEMO.ViewModel
{
    /// <summary>
    /// 
    /// </summary>
    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            var propertyChanged = PropertyChanged;

            if (propertyChanged != null)
            {
                propertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }



    }
}

Kth Largest Element in Array


public class KthElement
    {
    public static int kthElement(int[] arr, int k)
       {
    int n = arr.Length;
    int lo = 0;
    int hi = n - 1;
    if (lo == hi)
    return arr[lo];
           while (true)
           {
    int pivotIndex = Partition(arr, lo, hi);
    int rank = pivotIndex - lo + 1;
    if (rank == k)
    return arr[pivotIndex];
    else if (k < rank)
    return kthElement(arr, k);
    else
    return kthElement(arr, k - rank);
           }
           
       }
    private static int Partition(int[] arr, int left, int right)
       {
    int pivot = arr[left];
    int i = left + 1;
    int j = right;
           while (i < j)
           {
               while (arr[i] <pivot) i++;
               while (arr[j] >= pivot) j--;
    if (i < j)
                   Swap(arr, i, j);
           }
           Swap(arr, left, j);
    return j;
       }
    private static void Swap(int[] arr, int i, int j)
       {
    int temp = arr[i];
           arr[i] = arr[j];
           arr[j] = temp;
       }
    }

Levenshtein distance (Edit distance)

The edit distance of two strings, s1 and s2, is defined as the minimum number of point mutations required to change s1 into s2, where a point mutation is one of:

  1. change a letter,
  2. insert a letter, or
  3. delete a letter




class EditDistanceAlgo
    {
        static int[,] m;
        public static char diagCh;
        public static int LevenshteinDistance(string s, string t)
        {
        int[,] d = new int[s.Length + 1, t.Length + 1];
        for (int i = 0; i <= s.Length; i++)
                d[i, 0] = i;
        for (int j = 0; j <= t.Length; j++)
                d[0, j] = j;
        for (int j = 1; j <= t.Length; j++)
        for (int i = 1; i <= s.Length; i++)
        if (s[i - 1] == t[j - 1])
                        d[i, j] = d[i - 1, j - 1];  //no operation
        else
                        d[i, j] = Math.Min(Math.Min(
                            d[i - 1, j] + 1,    //a deletion
                            d[i, j - 1] + 1),   //an insertion
                            d[i - 1, j - 1] + 1 //a substitution
                            );
            TraceBack("", "", "", d, s.Length, t.Length, s, t);
        return d[s.Length, t.Length];
        }
        public static void TraceBack(string row1, string row2, string row3, int[,] mm, int i, int j, string s1, string s2)
        {
        string result = "";
        if (i > 0 && j > 0)
            {
        var diag = mm[i - 1, j - 1];
                diagCh = '|';
        if (s1[i - 1] != s2[j - 1])
                {
                    diag++; diagCh = ' ';
                }
        if (mm[i, j] == diag)
                    TraceBack(s1[i - 1] + row1, diagCh + row2, s2[j - 1] + row3, mm, i - 1, j - 1, s1, s2);    // change or match
        else if (mm[i, j] == mm[i - 1, j] - 0 + 1) // delete
                    TraceBack(s1[i - 1] + row1, ' ' + row2, '-' + row3, mm, i - 1, j, s1, s2);
        else
                    TraceBack('-' + row1, ' ' + row2, s2[j - 1] + row3, mm, i, j - 1, s1, s2);      // insertion
            }
        else if (i > 0)
                TraceBack(s1[i - 1] + row1, ' ' + row2, '-' + row3, mm, i - 1, j, s1, s2);
        else if (j > 0)
                TraceBack('-' + row1, ' ' + row2, s2[j - 1] + row3, mm, i, j - 1, s1, s2);
        else // i==0 and j==0
                result += row1 + '\n' + row2 + '\n' + row3 + '\n';
            Console.WriteLine(result);
        }//traceBack
    }


Longest increasing subsequence problem (Dynamic Programming)

The input consists of two sequences ~x = x1, . . . , xn and ~y = y1, . . . , ym. The goal is to find a longest common subsequence of ~x and ~y, that is a sequence z1, . . . , zk that is a subsequence both of ~x and of ~y. Note that a subsequence is not always substring: if ~z is a subsequence of ~x, and zi = xj and zi+1 = xj 0, then the only requirement is that j 0 > j, whereas for a substring it would have to be j 0 = j + 1.For example, let ~x and ~y be two DNA strings ~x = T GACT A and ~y = GT GCAT G; n = 6 and m = 7. Then one common subsequence would be GT A. However, it is not the longest possible common subsequence: there are common subsequences T GCA, T GAT and T GCT of length 4

0/1 Knapsack problem

Description

using System;

public class Knapsack
{
    static int nbObjects = 8;
    static int[] weight = { 2, 3, 5, 2, 4, 6, 3, 1 };
    static int[] utility = { 5, 8, 14, 6, 13, 17, 10, 4 };
    static int weightmax = 12;
    static int[,] array;
    static void Display()
    {
        int i, u, w;
        u = 0;
        w = weightmax;
        for (i = nbObjects - 1; i >= 1; i--)
        {
            if (array[i, w] != array[i - 1, w])
            {
                Console.Write((i + 1) + " ");
                w = w - weight[i];
                u = u + utility[i];
            }
        }

        if (array[0, w] != 0)
        {
            Console.WriteLine("1");
            w = w - weight[0];
            u = u + utility[0];
        }
    }
    public static void SolveDP()
    {
        array = new int[nbObjects, weightmax + 1];
        // initialize the first row
        for (int j = 0; j <= weightmax; j++)
            if (j < weight[0])
            {
                array[0, j] = 0;

            }
            else
            {
                array[0, j] = utility[0];

            }
        // for all other rows
        for (int i = 1; i < nbObjects; i++)
        {
            for (int j = 0; j <= weightmax; j++)
            {
                if (j - weight[i] < 0)
                    array[i, j] = array[i - 1, j];
                else
                    array[i, j] = Math.Max(array[i - 1, j], array[i - 1, j - weight[i]] + utility[i]);
            }
        }
        Display();
    }

}

Generate permutations of a given string in c#

In this post I will show you how to generate the permutations of a given string in c#.

Pseudocode:
If you have no more characters left to rearrange, print current permutation

for (every possible choice among the characters left to rearrange)
{
           Make a choice and add that character to the permutation so far
           Use recursion to rearrange the remaining letters
}
using System.Collections.Generic;
using System;
using System.Generic;
using System.Linq;
using System.Text;
namespace Permutation
{
    class Program
    {
    static void Main(string[] args)
        {
            Permutation("abc");
        }
    /// <summary>
    /// Wrapper function
    /// </summary>
    /// <param name="input"></param>
    public static void Permutation(string input)
        {
            RecPermutation("", input);
        }
    private static void RecPermutation(string soFar, string input)
        {
    if (string.IsNullOrEmpty(input))
            {
                Console.WriteLine(soFar);
    return;
            }
    else
            {
    for (int i = 0; i < input.Length; i++)
                {
                    
    string remaining = input.Substring(0, i) + input.Substring(i + 1);
                    RecPermutation(soFar + input[i], remaining);
                }
            }
        }
    }
}
Recursion Tree
|-- RecPermute'', 'abc'
|   |-- RecPermute'a', 'bc'
|   |   |-- RecPermute'ab', 'c'
|   |   |   |-- RecPermute'abc', ''
abc
|   |   |   |--  return None
|   |   |--  return None
|   |   |-- RecPermute'ac', 'b'
|   |   |   |-- RecPermute'acb', ''
acb
|   |   |   |--  return None
|   |   |--  return None
|   |--  return None
|   |-- RecPermute'b', 'ac'
|   |   |-- RecPermute'ba', 'c'
|   |   |   |-- RecPermute'bac', ''
bac
|   |   |   |--  return None
|   |   |--  return None
|   |   |-- RecPermute'bc', 'a'
|   |   |   |-- RecPermute'bca', ''
bca
|   |   |   |--  return None
|   |   |--  return None
|   |--  return None
|   |-- RecPermute'c', 'ab'
|   |   |-- RecPermute'ca', 'b'
|   |   |   |-- RecPermute'cab', ''
cab
|   |   |   |--  return None
|   |   |--  return None
|   |   |-- RecPermute'cb', 'a'
|   |   |   |-- RecPermute'cba', ''
cba
|   |   |   |--  return None
|   |   |--  return None
|   |--  return None
|--  return None

Recursive merge sort implementation in c#

Merge Sort


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MergeSort
{
    public class Program
    {
        private int[] originalArray;
        private int[] resultArray;

        public void MergeSort(int[] array)
        {
            this.originalArray = array;
            this.resultArray = new int[array.Length];
            Merge(0, array.Length - 1);
        }

        private void Merge(int low, int high)
        {
            if (low < high)
            {
                int middle = (low + high) / 2;
                Merge(low, middle);
                Merge(middle + 1, high);
                Sort(low, middle, high);
            }
        }
        /// <summary>
        /// Returns a new sorted list containing the same elements as L
        /// </summary>
        /// <param name="low"></param>
        /// <param name="middle"></param>
        /// <param name="high"></param>
        private void Sort(int low, int middle, int high)
        {

            for (int index = low; index <= high; index++)
            {
                resultArray[index] = originalArray[index];
            }
            int i = low;
            int j = middle + 1;
            int k = low;
            while (i <= middle && j <= high)
            {
                if (resultArray[i] <= resultArray[j])
                {
                    originalArray[k] = resultArray[i];
                    i++;
                }
                else
                {
                    originalArray[k] = resultArray[j];
                    j++;
                }
                k++;
            }
            while (i <= middle)
            {
                originalArray[k] = resultArray[i];
                k++;
                i++;
            }
        }
        public static void Main(String[] args)
        {
            int[] arr = { -4, 7, -9, 11, 8, 22, 98, 5 };

            Program example = new Program();
            example.MergeSort(arr);
        }
    }

}

Quicksort implementation in c#

Quicksort is a very efficient sorting algorithm invented by C.A.R. Hoare. It has two phases:
  1. the partition phase and
  2. the sort phase.
Quicksort a good example of the divide and conquer strategy for solving problems. In quicksort, we divide the array of items to be sorted into two partitions and then call the quicksort procedure recursively to sort the two partitions, ie we divide the problem into two smaller ones and conquer by solving the smaller ones.

How to implement selection sort in c#

In this post I will show you how to implement selection sort in c#.Before going to implement selection sort let's describe how selection sort works.

  1. go through the list one item at a time.
  2. keep track of the smallest item found.
  3. Find the smallest item out and add it to a list of sorted items.
  4. Repeat until all the items have been sorted




class Program
    {
        // Selection Sort Algorithm
        public static void SelectionSort(int[] arr)
        {
            int i, j;
            int min;
            for (i = 0; i < arr.Length - 1; i++)
            {
                min = i;
                for (j = i + 1; j < arr.Length; j++)
                {
                    if (arr[j] < arr[min])
                    {
                        min = j;
                    }
                }
                Swap(arr, i, min);
            }
        }
        private static void Swap(int[] arr, int i, int min)
        {

            int temp = arr[i];
            arr[i] = arr[min];
            arr[min] = temp;
        }
        static void Main(string[] args)
        {

            int[] arr = new int[] { 1, 2, 0, -3, 32 };
            SelectionSort(arr);

        }


    }

C# Lambda Expression One-Liners

In this post I will show you  some  powerful one liner Lambda expression

            //Write factorial function using lambda expression

            Func<int, int> fact = null;
            fact = x => x == 0 ? 1 : x * fact(x - 1);


            //Function that prints nth fibonacci number

            Func<int, int> Fib = null;
            Fib = (n) => n == 0 || n == 1 ? 1 : Fib(n - 1) + Fib(n - 2);

            //Function checks that number is odd or even
            Func<int, bool> IsOdd = null;
            IsOdd = x => x % 2 != 0;

            //Merge two array into single array
            int[] arr = new int[] { 1, 2, 3, 4, 5, 6 };
            Func<int[], int, int[]> MultiplyEachArrayElement = null;
            MultiplyEachArrayElement = (n, i) => n.Select(x => x * i).ToArray();

            //Merge Two array into single array
            int[] arr2 = new int[] { 1, 2, 3, 4, 5, 6 };
            Func<int[], int[], int[]> Merge = null;
            Merge = (x, y) => x.Zip(y, (a, b) => a + b).ToArray();

            //Find the length of given string
            Func<string, int> Length = null;
            Length = str => str.Length;

            //Convert sentance into word
            Func<string, char[], string[]> Sentence = null;
            Sentence = (x, s) => x.Split(s);
            //Find Gcd of two given numbers
            Func<int, int, int> Gcd = null;
            Gcd = (a, b) => b == 0 ? a : Gcd(b, a % b);

            //Find LCM of two given number
            Func<int, int, int> LCM = null;
            LCM = (a, b) => (a * b) / Gcd(a, b);

            //Function for downloading data from given url
            Func<string, string> Download = null;
            Download = (x) => new WebClient().DownloadString(x);

            //Function for finsing max of two number
            Func<int, int, int> Max = null;
            Max = (x, y) => x > y ? x : y;

            //Function for finding max of three numbers
            Func<int, int, int, int> MaxOfThree = null;
            MaxOfThree = (x, y, z) => x > y & y > z ? x : x < y && x > y ? y : z;
            Console.WriteLine(MaxOfThree(1, 2, 038));

            //Function for summing array elements

            Func<int[], int> Sum = null;
            Sum = (x) => x.Sum();

            //Power function
            Func<int, int, int> Power = null;
            Power = (x, y) => y == 0 ? 1 : x * Power(x, y - 1);

            //Find the extension of given filename
            Func<string, string> FileExtension = null;
            FileExtension = (x) => x.Split('.')[1];

Boyer-Moore search algorithm implementation in c#


Boyer-Mooreis a string searching algorithm. It avoids checking most positions in the source string. The implementation here uses constant characters.
public class Search
    {
        private static int[] BuildBadCharTable(char[] needle)
        {
            int[] badShift = new int[256];
            for (int i = 0; i < 256; i++)
            {
                badShift[i] = needle.Length;
            }
            int last = needle.Length - 1;
            for (int i = 0; i < last; i++)
            {
                badShift[(int)needle[i]] = last - i;
            }
            return badShift;
        }

        public static int boyerMooreHorsepool(String pattern, String text)
        {
            char[] needle = pattern.ToCharArray();
            char[] haystack = text.ToCharArray();

            if (needle.Length > haystack.Length)
            {
                return -1;
            }
            int[] badShift = BuildBadCharTable(needle);
            int offset = 0;
            int scan = 0;
            int last = needle.Length - 1;
            int maxoffset = haystack.Length - needle.Length;
            while (offset <= maxoffset)
            {
                for (scan = last; (needle[scan] == haystack[scan + offset]); scan--)
                {
                    if (scan == 0)
                    { //Match found
                        return offset;
                    }
                }
                offset += badShift[(int)haystack[offset + last]];
            }
            return -1;
        }

    }

Draw Fractal tree in wpf

In this post I will show you how to draw Fractal tree in WPF.Before going to implementation details first go throw this link.

Algorithm:To draw a fractal tree is simple:
  1. Draw the trunk
  2. At the end of the trunk, split by some angle and draw two branches
  3. Repeat at the end of each branch until a sufficient level of branching is reached



Create a new WPF application and add following code





<Window x:Class="HelloWorld.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Viewbox Stretch="Uniform">
            <StackPanel>
                <StackPanel Orientation="Horizontal"
Margin="5,5,5,0">
                    <Button Name="btnStart" Click="btnStart_Click"
Width="50" Content="Start"/>
                    <TextBlock Name="tbLabel" Margin="20,5,0,0"/>
                </StackPanel>
                <Canvas Name="canvas1" Width="300" Height="300"
Margin="5"/>
            </StackPanel>
        </Viewbox>

    </Grid>
</Window>






using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;

namespace HelloWorld
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private int depth = 0;
        private int i = 0;
        private double lengthScale = 0.75;
        private double deltaTheta = Math.PI / 5;
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //Application.Current.Dispatcher.BeginInvoke(
            //                DispatcherPriority.Background,
            //                new Action(() => DrawSine()));


        }
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            canvas1.Children.Clear();
            tbLabel.Text = "";
            i = 0;
            depth = 1;
            CompositionTarget.Rendering += StartAnimation;
        }
        private void StartAnimation(object sender, EventArgs e)
        {
            i += 1;
            if (i % 60 == 0)
            {
                DrawBinaryTree(canvas1, depth, new Point(canvas1.Width / 2, 0.83 * canvas1.Height), 0.2 * canvas1.Width, -Math.PI / 2);
                string str = "Binary Tree - Depth = " + depth.ToString();
                tbLabel.Text = str;
                depth += 1;
                if (depth > 10)
                {
                    tbLabel.Text = "Binary Tree - Depth =10. Finished";
                    CompositionTarget.Rendering -= StartAnimation;
                }
            }
        }
        private void DrawBinaryTree(Canvas canvas, int depth, Point pt, double length, double theta)
        {
            double x1 = pt.X + length * Math.Cos(theta);
            double y1 = pt.Y + length * Math.Sin(theta);
            Line line = new Line();
            line.Stroke = Brushes.Blue;
            line.X1 = pt.X;
            line.Y1 = pt.Y;
            line.X2 = x1;
            line.Y2 = y1;
            canvas.Children.Add(line);
            if (depth > 1)
            {
                DrawBinaryTree(canvas, depth - 1, new Point(x1, y1), length * lengthScale, theta + deltaTheta);
                DrawBinaryTree(canvas, depth - 1, new Point(x1, y1), length * lengthScale, theta - deltaTheta);
            }
            else
                return;
        }
        //private void DrawSine()
        //{
        //    for (int i = 0; i < 71; i++)
        //    {
        //        double x = i * Math.PI;
        //        double y = 40 + 30 * Math.Sin(x / 10);
        //        polygon1.Points.Add(new Point(x, y));
        //    }
        //}
    }
}




How to draw Sierpinski triangle in WPF

In this post,I will show you how to draw Sierpinski triangle in wpf.
Create a new WPF application and add foloowing code in MainWindow.xaml




<Window x:Class="Sierpinski.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Viewbox Stretch="Uniform">
            <StackPanel>
                <StackPanel Orientation="Horizontal"
Margin="5,5,5,0">
                    <Button Name="btnStart" Click="btnStart_Click"
Width="50" Content="Start"/>
                    <TextBlock Name="tbLabel" Margin="20,5,0,0"/>
                </StackPanel>
                <Canvas Name="canvas1" Width="300" Height="300"
Margin="5"/>
            </StackPanel>
        </Viewbox>

    </Grid>
</Window>


Open MainWindow.xaml.cs and add following code into it


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Sierpinski
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private int depth = 0;
        private int i = 0;
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {

        }
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            canvas1.Children.Clear();
            
            CompositionTarget.Rendering += StartAnimation;
        }
        private void StartAnimation(object sender, EventArgs e)
        {
            i += 1;
            if (i % 40== 0)
            {

                Point p1 = new Point(canvas1.Width / 2, 10);
                Point p2 = new Point(10, canvas1.Height - 10);
                Point p3 = new Point(canvas1.Width - 10, canvas1.Height - 10);
                DisplayTriangle(canvas1, p1, p2, p3, depth);
                depth += 1;
                if (depth > 5)
                {

                    CompositionTarget.Rendering -= StartAnimation;
                }
            }

        }


        private void DisplayTriangle(Canvas canvas, Point p1, Point p2, Point p3, int deep)
        {

            if (deep > 0)
            {
                

                // Get the midpoint on each edge in the triangle
                Point p12 = midpoint(p1, p2);
                Point p23 = midpoint(p2, p3);
                Point p31 = midpoint(p3, p1);
                // Recursively display three triangles
                DisplayTriangle(canvas, p1, p12, p31, deep-1);
                DisplayTriangle(canvas, p12, p2, p23, deep-1);
                DisplayTriangle(canvas, p31, p23, p3, deep-1);
                
            }
            else
            {
                // Draw a triangle to connect three points
                DrawLine(p1, p2, canvas1);
                DrawLine(p1, p3, canvas1);
                DrawLine(p2, p3, canvas1);
                return;
                

            }
        }

        private void DrawLine(Point From, Point To, Canvas TargetCanvas)
        {
            Line line = new Line();
            line.Stroke = Brushes.Red;
            line.StrokeThickness = 1.0;
            line.X1 = From.X;
            line.Y1 = From.Y;
            line.X2 = To.X;
            line.Y2 = To.Y;
            TargetCanvas.Children.Add(line);
        }
        private static Point midpoint(Point p1, Point p2)
        {
            return new Point((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2);
        }
    }
}

Convert json string to CLR type

In this post I will show you how to convert json string to CLR types using c#


Assembly Required
System.Web.Design

using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
namespace ConsoleApplication1
{
    public class Likes
    {
    public List<Like> data { get; set; }
    }
    public class Like
    {
    public string Category { get; set; }
    public string Name { get; set; }
    public string ID { get; set; }
    public string created_time { get; set; }
    public Like()
        {
        }
    }
    public class Program
    {
    static void Main(string[] args)
        {
    string jsonData = @"{
                                   ""data"": [    {
                               ""category"": ""Community"",
                                ""name"": ""Swati"",
                                ""id"": ""190847514395344"",
                                ""created_time"": ""2013-01-09T07:24:29+0000""
                            },
                            {
                                ""category"": ""Wine/spirits"",
                                ""name"": ""Chill with Rémy, India"",
                                ""id"": ""184640834879687"",
                                ""created_time"": ""2013-01-08T05:41:59+0000""
                            },
                            {
                                ""category"": ""Fictional character"",
                                ""name"": ""MAMU"",
                                ""id"": ""366505623417822"",
                                ""created_time"": ""2012-12-04T17:51:36+0000""
                            }]}";
            JavaScriptSerializer js = new JavaScriptSerializer();
            Likes result = js.Deserialize<Likes>(jsonData);
        }
    }
}