Pages

Search

Tuesday, March 13, 2012

Sample Code Implemented using EAP


EAP (Event Asynchronous Pattern), helps to invoke a function in another thread which enables the current thread to continue. This can be achieved using Threads as well, but EAP helps to raise an event which alerts the client or caller sending the result or error while performing action etc…
Below code is sample to explain EAP, taking calculator as an example.
Performing “Sum” is an operation in “Calculator” class. This function can be called directly which is regular just like synchronous.
Calculator class also has an another method “SumAsync”, which is called sending the same arguments as like with “Sum” but an extra argument which can be used in the “Async” or helps to map the asyn response with the asyn request.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Threading;
using System.Collections.Specialized;
namespace Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            Calculator objCalc = new Calculator();

            //an event to observe when the sum operation gets completed
            objCalc.OnSumCompleted += new EventHandler<SumCompletedEventArgs>(objCalc_OnSumCompleted);

            //invoking the sum async function sending the appropriate user state

            //Calling the async operations
            objCalc.SumAsync(5, 8, new { Desc = "Sum of 5 and 8" });
            //performing same asyn operations with same userstates to check
            //if throwing dduplicate operation error
            objCalc.SumAsync(5, 8, new { Desc = "Sum of 5 and 8" });
            objCalc.SumAsync(4, 8, new { Desc = "Sum of 4 and 8" });
            Console.Read();
        }

        static void objCalc_OnSumCompleted(object sender, SumCompletedEventArgs e)
        {
            //Checking if the operation has returened any error
            if(e.Error==null)
                //writing the result
            Console.WriteLine(sender.GetType().InvokeMember("Desc",
                System.Reflection.BindingFlags.GetProperty, null, sender, null) + " is " + e.Result);
            else
                //writing the error
                Console.WriteLine("Error occured while performing "+sender.GetType().InvokeMember("Desc", System.Reflection.BindingFlags.GetProperty, null, sender, null) + "\n" + e.Error.Message);
            Console.Read();
        }
    }

    //Sum completed event arguments
    public class SumCompletedEventArgs : AsyncCompletedEventArgs
    {
        public int Result;
        public SumCompletedEventArgs(Exception exp, bool Cancelled, object UserState)
            : base(exp, Cancelled, UserState)
        {
        }
    }

    //Calculator class which supports add operations in EAP and Synchronously
    public class Calculator
    {
        //Hybrid dictionary for thread safe and adding the request tasks
        HybridDictionary tasks = new HybridDictionary();

        //delegate to invoke Sum Operation completed event
        public delegate void SumCompletedEventHandler(SumCompletedEventArgs e);

        //Event which gets fired when sum operation is completed
        public event EventHandler<SumCompletedEventArgs> OnSumCompleted;

        //Function which sums up given numbers.
        //Sleep is included to observer asyn behaviour
        public int Sum(int a, int b)
        {
            Thread.Sleep(2000);
            return a + b;
        }

        //sum async method called sending "userstate" asn extra argument
        public void SumAsync(int a, int b, object UserState)
        {
            AsyncOperation asyncOp = null;
            try
            {
                //Checking if the request with given userstate is already in progress
                lock (tasks.SyncRoot)
                {
                    //creating async operation to track the async operation
                    asyncOp = AsyncOperationManager.CreateOperation(UserState);
                    if (tasks.Contains(UserState))
                        throw new Exception("User state is already in progress, duplicate operations cannot be performed");
                    tasks[UserState] = asyncOp;
                }

                //Invoking the function which sums up the values,
                Action<int, int, AsyncOperation> objSumWorker = new Action<int, int, AsyncOperation>(SumWorker);
                objSumWorker.BeginInvoke(a, b, asyncOp, null, null);
            }
            catch (Exception exp)
            {
                SumCompletedEventArgs e = new SumCompletedEventArgs(exp, false, UserState);
                asyncOp.PostOperationCompleted(
                    (o) =>
                    {
                        if (OnSumCompleted != null)
                            OnSumCompleted(o, e);
                    }, UserState
                    );
            }
        }

        private void SumWorker(int a, int b, AsyncOperation argAsync)
        {
            //creating an object for sumcompleted
            SumCompletedEventArgs e = new SumCompletedEventArgs(null, false, argAsync.UserSuppliedState);
            try
            {
                //finding the sum of given 2 numbers
                e.Result = Sum(a, b);

                //removing the request userstate from collection
                lock (tasks.SyncRoot)
                {
                    tasks.Remove(argAsync.UserSuppliedState);
                }

                //invoking anonymous function in asyn synchronisation context
                argAsync.PostOperationCompleted
                    (
                    (o) =>
                    {
                        if (OnSumCompleted != null)
                            OnSumCompleted(o, e);
                    }, argAsync.UserSuppliedState
                    );
            }
            catch (Exception exp)
            {
                e = new SumCompletedEventArgs(exp, false, argAsync.UserSuppliedState);
            }
        }
    }
}




Thursday, March 8, 2012

Freezing Header Row in Grid view


When we use asp:gridview to bind data, it is required to freeze the header row when there are more rows and also when grid is embedded in a div to show scroll bar when grid height falls outside the div height.

Below source (javascript) helps to make the header freezed.

Aspx Page

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <style type="text/css">
        .Grid_Header_Cell
        {
            position: relative;
            background-color: White;
            border: 2px solid silver;
        }
        .Grid_Header
        {
            position: relative;
        }
    </style>
    <script type="text/javascript">
        function freezeGridHeader(grdid, divid) {
            var tbl = document.getElementById("MainContent_" + grdid);
            var dv = document.getElementById(divid);
            var hdrtr = tbl.getElementsByTagName("tr")[0];
            hdrtr.className = "Grid_Header";
            var hdrth = hdrtr.getElementsByTagName("th");
            for (i = 0; i < hdrth.length; i++)
                hdrth[i].className = "Grid_Header_Cell";
            hdrtr.style.top = dv.scrollTop - 2;
            hdrtr.style.left = dv.scrollLeft - 1;
        }
    </script>
    <div style="height: 200px; overflow: auto" id="div_scr">
        <div>
            <asp:GridView ID="grd" runat="server" Width="98%">
            </asp:GridView>
        </div>
    </div>
</asp:Content>



Aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Bind();
            Page.ClientScript.RegisterStartupScript(typeof(_Default), "grid_header_freeze", "<script>setTimeout(\"freezeGridHeader('grd','div_scr');\",100);</script>");
        }
    }

    private void Bind()
    {
        DataTable dt1 = new DataTable();
        dt1.Columns.Add("col1", typeof(System.Int32));
        dt1.Columns.Add("col2");

        DataRow dr = dt1.NewRow();
        dr["col1"] = 1;
        dr["col2"] = "Row1";
        dt1.Rows.Add(dr);

        for (int i = 2; i < 100; i++)
        {
            dr = dt1.NewRow();
            dr["col1"] = i;
            dr["col2"] = "Row"+i;
            dt1.Rows.Add(dr);
        }
        grd.DataSource = dt1;
        grd.DataBind();
    }
}



Wednesday, March 7, 2012

LDAP Authentication using C#


LDAP stands for Light Weight Directory Access Protocol.
Below source is an example to redirect to “newuser.aspx” incase if the user has browsed the web application for the first time.
In “Global.asax.cs”, under “Session_Start” event application checks if the requesting user is already authenticated before and added in DB.
If the user is available, application doesnot restrict where as if the user is new whose details will not be available in DB application redirects to “newuser.aspx”.
In page load of “newuser.aspx”, application connects to LDAP server and gets the details of the user based on SID (User Security Identifier) and logs the details in database.
Global.asax.cs
void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Authenticate.User objUser = Authenticate.UserDB.GetUser(Request.ServerVariables["LOGON_USER"]);
        if (objUser == null)
            Response.Redirect("NewUser.aspx");
    }

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

namespace Authenticate
{
    public class ActiveDirectory
    {
        private static string SidToHex(System.Security.Principal.SecurityIdentifier securityIdentifier)
        {
            // determine the length of the security identifier (in bytes) so that we can turn it into a byte array
            int binaryLength = securityIdentifier.BinaryLength;

            // create a byte array of that length
            byte[] byteArray = new byte[binaryLength];

            // populate the byte array with the binary form of the security identifier
            securityIdentifier.GetBinaryForm(byteArray, 0);

            // setup a stringbuilder, with the default starting and max size to be twice the length of the byte array
            // which will allow two characters per byte
            System.Text.StringBuilder retval = new System.Text.StringBuilder(binaryLength * 2, binaryLength * 2);

            // loop through each of the spots in the byteArray, converting each to the string hex value
            foreach (byte bt in byteArray)
                retval.Append(bt.ToString("X2"));

            // return the new string
            return retval.ToString();
        }

        //To get User based on SID
        public static User GetUser(System.Security.Principal.SecurityIdentifier sid)
        {
            //connecting to LDAP Server and finding user based on sid
            System.DirectoryServices.DirectoryEntry objDirectoryEntry = new System.DirectoryServices.DirectoryEntry("LDAP://<SID=" + SidToHex(sid) + ">");
            objDirectoryEntry = new System.DirectoryServices.DirectoryEntry("LDAP://" + (string)objDirectoryEntry.Properties["distinguishedName"][0], null, null,
    System.DirectoryServices.AuthenticationTypes.Secure | System.DirectoryServices.AuthenticationTypes.ReadonlyServer);
            //reading the user details
            User objUser = new User()
            {
           //prperty names as per how they are added in LDAP
                Name = objDirectoryEntry.Properties["FirstName"].Value.ToString(),
                EmailID =
                    objDirectoryEntry.Properties["mail"].Value.ToString()
            };
            return objUser;
        }

    }
}

NewUser.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class NewUser : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //get user object, reading details from active directory
            Authenticate.User objUser = Authenticate.ActiveDirectory.GetUser(Request.LogonUserIdentity.User);

            //setting the user name
            objUser.Name = Request.ServerVariables["LOGON_USER"];

            //Adding the user to the binary file, so that when the same user
            //logins again, application can authenticate using binary file
            Authenticate.UserDB.AddUser(objUser);
        }
    }
}

Comparing Data Tables



Below source helps to identify the datarows in a source table whose values are modified or different with respect to the similar row in the target table.

Below code, is only to identify the changes rows but not to identify the new inserted rows or deleted rows.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace Datasets
{
    class Program
    {
        static void Main(string[] args)
        {
            //creating 2 datasets,
            DataTable dt1 = new DataTable();
            dt1.Columns.Add("col1", typeof(System.Int32));
            dt1.Columns.Add("col2");

            DataRow dr = dt1.NewRow();
            dr["col1"] = 1;
            dr["col2"] = "Row1";
            dt1.Rows.Add(dr);

            dr = dt1.NewRow();
            dr["col1"] = 2;
            dr["col2"] = "Row2";
            dt1.Rows.Add(dr);

            DataTable dt2 = dt1.Copy();

            //changing the value of 2nd record
            dt2.Rows[0]["col2"] = null;
            DataSet d1 = new DataSet();
            DataSet d2 = new DataSet();
            d1.Tables.Add(dt1);
            d2.Tables.Add(dt2);
            CompareDataSets<int>(d1, d2, "col1");
        }

        //setting the primary column datatype as generic
        //sending the primary column name as argument
        static void CompareDataSets<T>(DataSet ds1, DataSet ds2, string strPrimaryColumn)
        {
            DataTable dtSrc = ds1.Tables[0];
            DataTable dtTar = ds2.Tables[0];
            var rws = (from r1 in dtSrc.AsEnumerable()
                       from r2 in dtTar.AsEnumerable()
                       where (r1.Field<T>(strPrimaryColumn).ToString().CompareTo(r2.Field<T>(strPrimaryColumn).ToString()) == 0)
                       && !r1.ItemArray.Compare(r2.ItemArray)
                       select r1
                  );
            //writing the id of the records which are differed
            foreach (var o in rws)
            {
                Console.WriteLine(o[strPrimaryColumn].ToString());
            }
            Console.Read();
        }
    }

    public static class ArrayExtension
    {
        //extension method to compare 2 arrays
        public static bool Compare(this Array Source, Array Target)
        {
            //checking if length are same
            if (Source.Length != Target.Length)
                return false;
            for (int i = 0; i < Source.Length; i++)
            {
                //checking if values are differed
                if (Source.GetValue(i) != null && Target.GetValue(i) != null)
                {
                    if (Source.GetValue(i).ToString().CompareTo(Target.GetValue(i).ToString()) != 0)
                        return false;
                }
                else
                {
                    if (Source.GetValue(i) == null && Target.GetValue(i) == null)
                        continue;
                    else
                        return false;
                }
            }
            return true;
        }
    }
}


Tuesday, March 6, 2012

JavaScript Anonymous functions


Usually we declare function in JavaScript as like
        function sum(a, b) {
            return a + b;
        }

This is the regular practice of defining functions.
Beside there are enhanced capabilities of JavaScript which helps to override functions, define static functions, adding methods or members to an object and prototype, etc…
The same above function can be declared as

var sum = function (a, b) {
            return a + b;
        }
Here  “sum” is the anonymous function object.
The above anonymous object can be send as a an argument to a function to invoke.
Ex:-
var sum = function (a, b) {
            return a + b;
        }

        function testSum(f1, a, b) {
            return f1(a, b);
        }
//sending function object and function arguments
alert(testSum(sum, 8, 10));

Another example of anonymous :-
Ex:-
    var fun2 = {
            "prop1": "hi",
            "met1": function (a, b) { return a + b; }
        };

alert(fun2.met1(4, 5));
alert(fun2.prop1);
This is just like static  members which doesn’t require instance to be created to access members.

Ex:-
var fun3 = function () {
            this.met1 = function (a, b) { c = a + b; };
            this.c = 0;
            this.met2 = function () { alert(c); };
            this.toString = function () { alert("value is " + c); };
        }

var objFun3 = new fun3();
objFun3.met1(8, 10);
objFun3.met2();
objFun3.toString();

To add a new function to fun3,
fun3.prototype.met4 = function () {
                alert('function 4');
            }

Or
fun3.prototype = { "met4": function () { alert("fun4 method 4"); } };

Ex:- Adding a new function to object (objFun3)
objFun3.met3 = function () {
                alert("object method 3");
            }
Adding new function of object will not add to the class (function – fun3) prototype.
So a new instance or another instance of “fun3” other than “objFun3”, will not be able to invoke “met3”.

Overriding a function in object (objFun3)
ex:-
objFun3.met1 = function (a, b) { return a - b; };
When the method (met1) is invoked using “objFun3” only then the above function will be invoked, otherwise for a different instance the (met1) method in “fun3” prototype is invoked.

Adding Static members,
Ex:-
fun3.met3 = function () { alert("fun3 method 3 1"); };

The static members are added to function (fun3) but not to the prototype.
Hence the static member can be invoked without creating instance to the function (fun3)