-->

Wednesday, April 9, 2014

How to check two string are equal in ASP.NET

Introduction

If you want to compare two string object then we can use compare( ) method of the string class. Using this method you can compare characters through casing rules and the alphabetic order. It returns 32-bit signed integer value. If returning value is equal to zero then both string are equal otherwise string is greater or less.
Suppose, your string returns less than zero value it means your first string is less than to string b.

Lets take an simple example

Source code
<div>
        <asp:Button ID="Button1" runat="server" Text="String Compare" onclick="Button1_Click" />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>
    </div>

Business logic code

#region stringcompare

    protected void Button1_Click(object sender, EventArgs e)
    {
        string a = "hello";
        string b = "hello";
        int c = string.Compare(a, b);
        if (c == 0)
        {
            Label1.Text = "Both string are equal";

        }
        else
        {
            if (c < 0)
            {
                Label1.Text = "string a is less than string b";

            }
            else
            {
                Label1.Text = "string a is greater than string b";
            }

        }
    }

    #endregion 

Code generate the following output
How to check two string are equal in ASP.NET

Friday, April 4, 2014

How to fix Incorrect syntax near the keyword from in ASP.NET

Today i facing a new problem that is
Incorrect syntax near the keyword from
I am receiving this error message when i retrieve the record from the database table, this code is successfully run in visual studio 2010 or earlier but not successfully run in vs 2012 or higher. So I think about that error and solve the problem that is

Incorrect syntax near the keyword 'from'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'from'.

Solution 

use brackets around the table like

Select * from [products]

If you use aggregate operators  query then should use '()' like

Select count (*) from [products]

Wednesday, April 2, 2014

Example of AppendFormat method in ASP.NET

 <form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" Height="42px" onclick="Button1_Click"
        Text="Click" Width="84px" BackColor="#990000" ForeColor="White" />
    <div style="width: 110px; height: 37px; margin-bottom: 28px">
   
        <asp:Label ID="Label1" runat="server" Text="Label" BackColor="#CCFF33"
            BorderColor="Black"></asp:Label>
   
    </div>
    <p>
        &nbsp;</p>
    </form>

code behind code -

 protected void Button1_Click(object sender, EventArgs e)
    {
        StringBuilder stringb = new StringBuilder();
        int intgerValue = 110;
        string stringValue = "Apple";
        Boolean BooleanValue = true;
        stringb.AppendFormat("intger Value: {0}.string Value: {1}  and Boolean Value: {2}", intgerValue, stringValue, BooleanValue);
        Label1.Text = stringb.ToString();  
  
    }


Output-

Tuesday, April 1, 2014

How to pass ampersand in query string parameter in ASP.NET

According to our previous article how to use query string in asp.net, we use query string parameter for searching value from the database.Now, If you want to pass parameter value with special character like "&" . Let's take an simple example,  how to pass & in QueryString parameter.

I-method

Response.Redirect("~/Default3.aspx?userName=" + Server.UrlEncode("you&me") + "&Password=jacob");

Here, In above mentioned code your username contains & symbol between you&me and we use & for separates the field.

II-method

~/Default3.aspx?userName=you%26me&password=jacob

Here, we use %26, in the place of & symbol. Any browser consider & symbol as %26.

Complete Code

   Default2.aspx code

<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">LinkButton</asp:LinkButton>

Default2.aspx.cs code

protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Default3.aspx?userName=" + Server.UrlEncode("you&me") + "&Password=jacob");
    }

Now, your button click event call another webform, where you bind  gridview through QueryString
Default3.aspx code

<form id="form1" runat="server">
    <div>
    
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            DataKeyNames="sno" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="sno" HeaderText="sno" InsertVisible="False" 
                    ReadOnly="True" SortExpression="sno" />
                <asp:BoundField DataField="userName" HeaderText="userName" 
                    SortExpression="userName" />
                <asp:BoundField DataField="Password" HeaderText="Password" 
                    SortExpression="Password" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
            SelectCommand="SELECT * FROM [user] WHERE (([userName] = @userName) AND ([Password] = @Password))">
            <SelectParameters>
                <asp:QueryStringParameter Name="userName" QueryStringField="userName" 
                    Type="String" />
                <asp:QueryStringParameter Name="Password" QueryStringField="Password" 
                    Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
    
    </div>

    </form>

 Code Generate the following output

How to pass ampersand in query string parameter in ASP.NET

How to pass ampersand in query string parameter in ASP.NET

Monday, March 31, 2014

How to Implement Server Side Validation in Asp.Net MVC

Server side validation can be performed by submitting the model and then check the values in related action of the controller. Asp.Net MVC framework populates a ModelState object with any validation failure and passes that object to controller. If any error found just add the error in the state of model by using ModelState object of type ModelStateDictionary.

According to our previous article about client side validation, programmer have to change some minor changes in the view as well as controller’s action. Just write the following code in our GetValues view:

@using (Html.BeginForm())
{
    <div>
        <div>Name: </div>
        <div>
            @Html.TextBox("username")
            @Html.ValidationMessage("nameError")
        </div>
        <input type="submit" value="Send" />
    </div>
}

Here I have added a validation message having the key "nameError" to show the validation message for username. The message passed with this key will be shown through this line of code. Programmer have to change the action code according to this view code and it should be look like:

[HttpPost]
public ActionResult GetValues(string username)
{
if (username == string.Empty)
{
ModelState.AddModelError("nameError", "Name must not be empty");
}
return View();
}

As you can see the condition I have placed that it will only check whether the textbox is empty. If username will be passed empty then it will just add an error message having the same key written in the view code, by using the code written in if block.

Run the MVC application the leave black the textbox, click on send button. It will go to the action, check the condition and then return the view after adding the error. The page will be look like:

How to Implement Server Side Validation in Asp.Net MVC

So this is how to perform server side validation and client side validation in MVC. In further articles we will understand more about these.

Sunday, March 30, 2014

Save Password using Encoding, decoding and Hashing Techniques in ASP.NET

Introduction

Plain text change in unreadable format known as encoding. And reverse of it known as decoding. Change a plain text into cipher text using any key known as hashing. There are lots of techniques available in hashing.
Here we take a simple example of among. First we start from Encoding.


How to change plain text into cipher text (Unreadable format)

first of all, take a string variable, after that take a byte array, which size is equal to string Length. Look like

String str = "Hello World";
Byte [] encode = new Byte[str.Length];

Get Bytes of string value using getBytes( ) method of UTF8 encoding. Now, your code look like

encode = Encoding.UTF8.GetBytes(str);
Now, change encoded byte array into Base64String.

encodepwd = Convert.ToBase64String(encode); // here encodepwd is the string variable.
Store encoded password is stored in encodepwd variable.

How to Change cipher Text into Plain Text

First of all, encoded string convert into specified string format, which is equivalent 8-bit unsigned integer array using FromBase64String ( ) method. count number of characters using GetCharCount( ) of byte array like.
 byte[] todecode = Convert.FromBase64String(decryptpwd);
 int charcountvariable = decode.GetCharCount(todecode, 0, todecode.Length);
Decode sequence of byte into set of characters using GetChars( ) method.

 char[] decode_array = new char[charcountvariable];
        decode.GetChars(todecode, 0, todecode.Length,decode_array ,0);

Complete source code

 <form id="form1" runat="server">
    <div>
    
        <table style="width:100%;">
            <tr>
                <td class="style1">
                    UserName</td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style1">
                    Password</td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;</td>
                <td>
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save" />
                </td>
                <td>
                    &nbsp;</td>
            </tr>
        </table>
    
    </div>
    <asp:GridView ID="GridView1" runat="server" Caption="Encrypted Data">
    </asp:GridView>
    <br />
    <asp:GridView ID="GridView2" runat="server" Caption="Decrypted Data" 
        onrowdatabound="GridView2_RowDataBound">
    </asp:GridView>
    <br />
    </form>

Business Logic Code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;

    public _Default()
    {
        con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        cmd = new SqlCommand();


    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            bindgridview1();
            bindgridview2();
            
        }

    }

    private void bindgridview2()
    {
        con.Open();
        cmd.CommandText = "select * from [user]";
        cmd.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView2.DataSource = ds;
        GridView2.DataBind();
      
    }

    private void bindgridview1()
    {
        con.Open();
        cmd.CommandText = "select * from [user]";
        cmd.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        GridView1.DataSource = ds;
        GridView1.DataBind();
        

        
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string pwdtxt = encodepassword(TextBox2.Text);
        con.Open();
        cmd.CommandText = "insert into [user](userName,Password)values(@us,@pw)";
        cmd.Parameters.AddWithValue("@us", TextBox1.Text);
        cmd.Parameters.AddWithValue("@pw", pwdtxt);
        cmd.Connection = con;
        cmd.ExecuteNonQuery();
        con.Close();
        bindgridview1();
        bindgridview2();


    }

    private string encodepassword(string p)
    {
        string encodepwd = string.Empty;
        byte[] encode = new byte[p.Length];
        encode = Encoding.UTF8.GetBytes(p);
        encodepwd = Convert.ToBase64String(encode);
        return encodepwd;

    }
    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row .RowType ==DataControlRowType .DataRow)
        {
            string decryptpwd = e.Row.Cells[2].Text;
            e.Row.Cells[2].Text = decryptpassword(decryptpwd);
        }
        
    }

    private string decryptpassword(string decryptpwd)
    {
        string decryptpass = string.Empty;
        UTF8Encoding encode = new UTF8Encoding();
        Decoder decode = encode.GetDecoder();
        byte[] todecode = Convert.FromBase64String(decryptpwd);
        int charcountvariable = decode.GetCharCount(todecode, 0, todecode.Length);
        char[] decode_array = new char[charcountvariable];
        decode.GetChars(todecode, 0, todecode.Length,decode_array ,0);

        decryptpass = new String(decode_array);
        return decryptpass;
       
    }
    
}

Code Generate the following output

Save Password using Encoding, decoding

MD5 Hashing Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;

    public _Default()
    {
        con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        cmd = new SqlCommand();


    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            bindgridview1();
           
            
        }

    }
    private void bindgridview1()
    {
        con.Open();
        cmd.CommandText = "select * from [user]";
        cmd.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        GridView1.DataSource = ds;
        GridView1.DataBind();
        

        
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string pwdtxt = getMd5Hash(TextBox2.Text);
        con.Open();
        cmd.CommandText = "insert into [user](userName,Password)values(@us,@pw)";
        cmd.Parameters.AddWithValue("@us", TextBox1.Text);
        cmd.Parameters.AddWithValue("@pw", pwdtxt);
        cmd.Connection = con;
        cmd.ExecuteNonQuery();
        con.Close();
        bindgridview1();
     


    }

    private static string getMd5Hash(string p)
    {
        MD5 md5Hasher = MD5.Create();

       
        byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(p));

       
        StringBuilder sBuilder = new StringBuilder();

       
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

      
        return sBuilder.ToString();

    }
  
}

Code Generate the following output

hashed password

Saturday, March 29, 2014

Difference between LINQ to XML and DOM Method

XML Document Object Model (DOM) is the current predominant XML programming API. In XML DOM, you build an XML tree in the bottom up direction. The typical way to create an XML tree using DOM is to use Xml Document. LINQ to XML also supports the Xml Document approach for constructing an XML tree, but also supports an alternative approach, called the functional construction. The functional construction uses the XElement and XAttribute constructors to build an XML tree.

In LINQ to XML, you can directly work with XML elements and attributes. You can create XML elements without using a document object. It also loads the T: System.Xml .Linq.XElement object directly from an XML file. It also serializes the T: System". Xml. Linq. XElement object to a file or a stream. When you compare this with XML DOM, the XML document is used as a logical container for the XML tree. In XML DOM, the nodes, which also include the elements and attributes, are created in the context of an XML document. The use of XML DOM is also complex. For example, if you want to use an element across multiple documents, you must import the nodes across the documents. This kind of complexity is not included in LINQ to XML.

The use of LINQ to XML also simplifies the names and namespaces by eliminating the prerequisite to deal with namespace prefix completely. The use of XML DOM does not let you change the name of node. As a substitute, you have to create a new node and copy all the child nodes to it, which leads to losing the original child identity.
LINQ to XML supports whitespace more simply than XML DOM.
© Copyright 2013 Computer Programming | All Right Reserved