Friday, July 29, 2011

Check integrity of two files

This method is used to check the integrity of two files using MD5 checksum. It accepts two string parameters. The source file location and the destination file location.

public bool PerformHashCheck(string sourcepath, string destinationpath)
        {
            bool result = false;
            FileStream sourcefile = new FileStream(sourcepath, FileMode.Open);
            FileStream destinationfile = new FileStream(destinationpath, FileMode.Open);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] sourceBytes = md5.ComputeHash(sourcefile);
            byte[] destinationBytes = md5.ComputeHash(destinationfile);
            sourcefile.Close();
            destinationfile.Close();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < sourceBytes.Length; i++)
            {
                sb.Append(sourceBytes[i].ToString("x2"));
            }
            string sourceHash = sb.ToString();
            StringBuilder db = new StringBuilder();
            for (int i = 0; i < destinationBytes.Length; i++)
            {
                db.Append(destinationBytes[i].ToString("x2"));
            }
            string desntinationHash = db.ToString();
            if (sourceHash.Equals(desntinationHash))
            {
                result = true;
            }
            return result;
        }

Tuesday, July 19, 2011

Forms Authentication with asp.net

This is a step by step guide to enable forms authentication in your web application. We will be authenticating against and LDAP directory.

Step 1: Add this to your web.config file. Tow main parameters below are the loginUrl and defaultUrl

<configuration> 
  <system.web>   
    <authentication mode="Forms">
      <forms loginUrl="Login.aspx"
             protection="All"
             timeout="30"
             name=".ASPXAUTH"
             path="/"
             requireSSL="false"
             slidingExpiration="true"
             defaultUrl="Home.aspx"
             cookieless="UseDeviceProfile"
             enableCrossAppRedirects="false" />
    </authentication>
    <authorization>
      <deny users="?" />
    </authorization>
  </system.web>
</configuration>

Step 2: Create a class that handles the LDAP authentication. You might have to add a reference to System.DirectoryServices to your project

public class LDAPAuthenticator
{
    private static string USurl = "LDAP://<IP Address>:389/DC=<value>,DC=<value>";
    public HttpCookie Ticket { get; set; }
    public LDAPAuthenticator()
    { }

    public string Authenticate(string Username, string Password)
    {
        string AUTHSTATUS = string.Empty;
        DirectoryEntry USentry = new DirectoryEntry(USurl, Username, Password);       
        try
        {
            //Bind to the native AdsObject to force authentication.           
            DirectorySearcher USsearch = new DirectorySearcher(USentry);
            USsearch.Filter = "(sAMAccountName=" + Username + ")";
            USsearch.PropertiesToLoad.Add("cn");
            SearchResult USresult = USsearch.FindOne();
            if (null == USresult)
            {
                AUTHSTATUS = "FAIL";              
            }
            else
            {
                AUTHSTATUS = "PASS";
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                    Username,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(30), // value of time out property
                    false, // Value of IsPersistent property
                    String.Empty,
                    FormsAuthentication.FormsCookiePath);
                string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                HttpCookie authCookie = new HttpCookie( FormsAuthentication.FormsCookieName, encryptedTicket);
                this.Ticket = authCookie;
                return AUTHSTATUS;
            }           
        }
        catch (Exception ex)
        {
            AUTHSTATUS = ex.Message;
            return AUTHSTATUS;
        }
        return AUTHSTATUS;
    }
}

Step 3: Create a web form called Login.aspx and a code behind file Login.aspx.cs . Include a username field and password field and a login Button. On the submit button/login button click event add this code

protected void LoginButton_Click(object sender, EventArgs e)
    {
        LDAPAuthenticator auth = new LDAPAuthenticator();
        string AUTHSTATUS = auth.Authenticate(UserNameTextBox.Text, PasswordTextBox.Text);
        if (AUTHSTATUS.Trim() == "PASS")
        {
            Session.Add("SESSIONUSER", sessionuser);
            Response.Cookies.Add(auth.Ticket);
            Response.Redirect("Home.aspx", false);           
        }
        else
        {
            AUTHSTATUSLabel.Text = AUTHSTATUS;
        }
    }   

Thats it.

Cheers
Bhushan

Friday, July 15, 2011

Using jQuery to change value of corresponsing drop down list

Scenario: I have two drop down lists and when I change the value of the first drop down, jQuery should change the value of the second drop down.

ASP.net and jQuery

<asp:DropDownList ID="TestTypeDropDown" runat="server"/>
<asp:DropDownList ID="TestTypeDropDown2" runat="server"/>

jQuery

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js%22%3E%3C/script>
<script type="text/javascript">
$(document).ready(function () {
            $("#<%=TestTypeDropDown.ClientID%>").bind('change', function () {
                $("#<%=TestTypeDropDown2.ClientID%>").val($("#<%=TestTypeDropDown.ClientID%>").val());
            });
</script>

Tuesday, July 12, 2011

jQuery and asp:UpdatePanel

When you are using an Update Panel and want to execute a function in jQuery on click of a button within the UpdatePanel, the function runs only once.

For example, If you are using a login screen and the Login button is located within the UpdatePanel. On click of the Login button you want to hide the Login button. This can be done simply using

$(document).ready(function () {
    $('#LoginButton').bind('click', function () {function () {
    $('#LoginButton').bind('click', function () {'#LoginButton').bind('click', function () {
    $("#LoginButton").fadeOut();"#LoginButton").fadeOut();
});

To solve this, use Sys.WebForms.PageRequestManager.getInstance()

See the following code

<script type="text/javascript">
        $(document).ready(function () {
            $('#LoginButton').bind('click', function () {
                $("#LoginButton").fadeOut();
                $("#ClearButton").fadeOut();
            });
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            prm.add_endRequest(function () {
                $('#LoginButton').bind('click', function () {
                    $("#LoginButton").fadeOut();
                    $("#ClearButton").fadeOut();
                });
            });
        });   
    </script>

Thank you

Monday, July 11, 2011

Templates in Gridview (Binding data from SQL result)

When you have a Gridview and hook it up to a datasource, the result will be displayed in BoundFields.
You sometimes might want to have a textbox instead of an auto-generated BoundField .

Here's how I do it

Step 1: Generate your Gridview as you normally do. Select a datasource, select a SqlStoredProcedure/query and a schema will be generated with Boundfields automatically.

For example, in my case, the stored procedure returns 3 fields. Entry, Date Posted and Posted By.
And this is how the BoundFields look.
<asp:GridView ID="JournalGrid" runat="server" EmptyDataText="No Journal Entries"
            AutoGenerateColumns="False" DataSourceID="JournalDS">
    <Columns>
    <asp:BoundField DataField="Entry" HeaderText="Entry"
        SortExpression="Entry" />                                      
    <asp:BoundField DataField="Date Posted" HeaderText="Date Posted"
        SortExpression="Date Posted" />
    <asp:BoundField DataField="Posted By" HeaderText="Posted By"
        SortExpression="Posted By" />
    </Columns>
</asp:GridView>

Step 2: Lets say we want to change the Entry to be displayed as a Textbox

Change the BoundField for the Entry to:

<asp:TemplateField>
    <ItemTemplate>
    <asp:TextBox ID="EntriesText" Runat="server" ReadOnly="true" Text='<%# Bind("Entry") %>'
      TextMode="MultiLine" Rows="5" Columns="50" />          
    </ItemTemplate>
</asp:TemplateField> 

Final code look like this:

<asp:GridView ID="JournalGrid" runat="server" EmptyDataText="No Journal Entries"
     AutoGenerateColumns="False" DataSourceID="JournalDS">
<Columns>
<asp:TemplateField>
     <ItemTemplate>
     <asp:TextBox ID="EntriesText" Runat="server" ReadOnly="true" Text='<%# Bind("Entry") %>'
          TextMode="MultiLine" Rows="5" Columns="50" />          
    </ItemTemplate>
</asp:TemplateField>                                                    
<asp:BoundField DataField="Date Posted" HeaderText="Date Posted"
     SortExpression="Date Posted" />
<asp:BoundField DataField="Posted By" HeaderText="Posted By"
     SortExpression="Posted By" />
</Columns>
</asp:GridView>

Cheers

Friday, July 8, 2011

Loading image generator

http://www.ajaxload.info/

Updating specific row in a DataSet ( C# and asp.net )

This is a tutorial on updating a specific row in a DataSet. For this example, I will be performing the updation on a DataSet that exists in the Cache.

For this particular example, let us consider a DataSet which contains a Table of Employee Data.

Step 1: Populating the DataSet

DataSet ds = new DataSet();
SqlDataAdapter ad = new SqlDataAdapter("GETREPORTINGEMPLOYEES",conn);
ad.SelectCommand.CommandType = CommandType.StoredProcedure;
ad.SelectCommand.Parameters.AddWithValue("@MANAGERID", MANAGERID);
ad.Fill(ds, "GETREPORTINGEMPLOYEES");

Step 2: Add the DataSet to Cache

Cache.Insert("REPORTINGEMPLOYEES", ds, null , DateTime.Now.AddMinutes(60), TimeSpan.Zero);

Step 3: Retreive DataSet from Cache

DataSet ds = (DataSet)Cache["REPORTINGEMPLOYEES"];

Step 4: Perform Update

//Searching the DataSet using column names
//The column names are what our sql stored procedure returns
//For ex: SELECT ID, NAME, PHONE, RANK FROM EMPLOYEE
//Say I want to update the Rank where the employee ID is 2340873
//First I get the DataRow[]
DataRow[] EmpRow = ds.Tables[0].Select("ID = '2340873'");
//Then I update the Rank as I know it is the 3rd column in the Row
//I know it is the 3rd row because of the SQL query which returns 4 columns
EmpRow[0][3] = 4;

Cheers

Hiding UpdatePanel during UpdateProgress ( jQuery and asp.net )

This is a small tutorial on hiding an update panel during update progress.

Required:
1. jQuery UpdatePanel plugin ( http://plugins.jquery.com/project/updatepanelplugin )
2. Ajax control toolkit ( http://www.asp.net/ajax/ajaxcontroltoolkit/samples/ )

Step 1: Include your jQuery script and jQuery UpdatePanel plugin in the head content of your html page

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.updatepanel.js"></script>

Step 2: Register the ajax control toolkit

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>

Step 3: Add the ToolScript Manager, UpdateProgress and UpdatePanel along with the contents you want within the UpdateProgress and UpdatePanel. In my example, I am just using a gif image to show in progress. My UpdatePanel will contain a search button which calls my code behind. And a gridview to populate search results. You can have anything inside the UpdatePanel.

<!-- Tool script manager -->
<ajaxcontroltoolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</ajax:ajaxcontroltoolkit>

<!-- Update Progress indicator -->
<asp:UpdateProgress runat="server" ID="PageUpdate" AssociatedUpdatePanelID="SearchResultsPanel">
    <ProgressTemplate>
        <asp:Image runat="server" ID="SearchImage" ImageUrl="~/images/loading/ajax-loader.gif" />
    </ProgressTemplate>
</asp:UpdateProgress>

<!-- Update Panel -->
    <asp:UpdatePanel runat="server" ID="SearchResultsPanel" EnableViewState="true">
    <ContentTemplate>
        <asp:Button runat="server" ID="Search" Text="Search" Width="70px" OnClick="Search_Click" />
        <asp:GridView ID="SearchGrid" runat="server" EmptyDataText="No records found." />
    </ContentTemplate>
</asp:UpdatePanel>

Step 4: Include the Javascript that hides the UpdatePanel

<script type="text/javascript">
$(document).ready(function () {
    //This is to fade out the UpdatePanel
    $("#<%=SearchResultsPanel.ClientID%>").beginRequest(function () {
        $("#<%=SearchResultsPanel.ClientID%>").fadeOut();   
    });
    //This is to fade in the UpdatePanel
    $("#<%=SearchResultsPanel.ClientID%>").panelUpdated(function () {
        $("#<%=SearchResultsPanel.ClientID%>").fadeIn();});
    });
</script>

Pretty simple :)
Cheers