Tuesday, August 9, 2011

SQL truncate decimal points, Get only Date


SQL get only date and not time

For Ex: 12/07/2009 and not 12/07/2009 10:09:20...

convert(varchar(10),@YOUR_DATE,101)

SQL Remove decimal points

For Ex: 203.98 and not 203.98079
select cast((123.456-(123.456%.001)) as decimal (18,2))

Monday, August 1, 2011

Disabling ipv6 in Ubuntu

Installed netbeans on my Ubuntu 11.04 and it was failing to connect and install updates. Disabling ipv6 solved the issue.

Check status of ipv6
Terminal:
cat /proc/sys/net/ipv6/conf/all/disable_ipv6
0 means it's enabled and 1 - disabled

echo "#disable ipv6" | sudo tee -a /etc/sysctl.conf
echo "net.ipv6.conf.all.disable_ipv6 = 1" | sudo tee -a /etc/sysctl.conf
echo "net.ipv6.conf.default.disable_ipv6 = 1" | sudo tee -a /etc/sysctl.conf
echo "net.ipv6.conf.lo.disable_ipv6 = 1" | sudo tee -a /etc/sysctl.conf

Done. Restart and check status of ipv6 again.

Cheers
Bhushan


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