July 30, 2011

Code Snippet to create a div dynamically in C#



System.Web.UI.HtmlControls.HtmlGenericControl DivObj =
        new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
    DivObj .ID = "DIV1";
    DivObj .Style.Add(HtmlTextWriterStyle.BackgroundColor, "Red");
    DivObj .Style.Add(HtmlTextWriterStyle.Height, "10px");
    DivObj .Style.Add(HtmlTextWriterStyle.Width, "200px");
    DivObj .InnerHtml = "Some Text";
    this.Controls.Add(DivObj) ;

July 28, 2011

Code Example for Caching Multiple Versions of a Web Form using VaryByParam

Below is the code example to cache multiple version of the single web form based on any change in querystring paramete using VaryByParam attribute of OuputCache directive



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Excache2.aspx.cs" Inherits="Excache2" %>
<%@ OutputCache Duration="300" VaryByParam="*" %>
<HTML>
  <body>
    <form id="Form1" method="post" runat="server">
      <h2>Caching Multiple Versions of a Web Form</h2>
      <hr>
   <p> When user is redirected from some page to this form based on any change 
    in query string parameter different versions of this web form will be cached
    </form>
  </body>
</HTML>


for example 


////////////////////////////////////////////////////////// GET/excache2.aspx?id=1   - one version cached for id=1
GET/excache2.aspx?id=2   - one more  version cached for id=2

Code Example for caching using Output cache directive

below is the code example to cache a single o/p of a form for some specified duration



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExCache1.aspx.cs" Inherits="ExCache1" %>


<%@ OutputCache Duration="60" VaryByParam="None" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
  <body>
    <form id="Form1" method="post" runat="server">
    <p>  This page will be cached for 60 seconds </p>
    </form>
  </body>
</HTML>

July 27, 2011

A potentially dangerous Request.Form value was detected from the client (txtInput=
").

One of my students asked that below error comes when trying to i/p some HTML elements in the textbox or textarea

A potentially dangerous Request.Form value was detected from the client (txtInput="<br />"). 
Description: 
Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case. 



Solution:



1.)To avoid this problem and allow HTML tags in TextBox control you need to change ValidateRequest of Page directive to false. You can do it like in code bellow:
<%@ Page Language="C#" AutoEventWireup="false" CodeFile="Default.aspx.cs"ValidateRequest="false" Inherits="_Default" %>

After this change, your application will accept every input, including HTML tags.

Above Solution is dangerous as There is no validation for the data and it is vulnerable to attack with outside scripts and code.
if we want to just disable the validation for one textbox control that is what not possible in ASP.NET
So to make this validation disable just for one control below Java  Script code I have written 


Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest ="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>


<!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 language="javascript" type ="text/javascript">
        function encodeData() {
            alert("come");
            var obj = document.getElementById("txtInput");
            alert(obj);
               alert(obj.value)
               var toEncode = obj.value;
               document.getElementById("txtInput").value = toEncode.replace(/&/gi, '&amp;').replace(/\"/gi, '&quot;').replace(/</gi, '&lt;').replace(/>/gi, '&gt;');
               alert(document.getElementById("txtInput").value);


        }
         </script>
</head>
   <body>
      <form id="Form1" runat="server">
         


         <asp:TextBox Runat="server" ID="txtInput" TextMode="MultiLine" Columns="50" Rows="10"/>
         <asp:Button Runat="server" ID="btnSubmit" Text="Submit" OnClientClick ="encodeData();"   OnClick="btnSubmit_Click"/>
         <br/>
         <asp:Literal Runat="server" ID="SeeOutPut" />
         <asp:Label ID="justShow" runat ="server" ></asp:Label>
      </form>
   </body>
</html> 




Default.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 _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
        }
    }


    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SeeOutPut.Text = Server.HtmlDecode(txtInput.Text);
        txtInput.Text = Server.HtmlDecode(txtInput.Text);
        justShow.Text = Server.HtmlDecode(txtInput.Text);
    }
}

July 24, 2011

Code Snippet to Execute Stored Procedure (Which Returns DataSet) in C#


Below is the code snippet to execute SP on SqlServer which is returning int

1.) Use the below namespace

using System.Data.SqlClient;
using System.Data.;


2.) Create Connection Object in your class in below manner

 SqlConnection connObj = new SqlConnection();

3.) Use the below method to execute SP and return the o/p



    public DataSet RunSpReturndataset(String param1, String strSpName)
    {
        createConnection();
        DataSet ds = new DataSet();
        try
        {
            SqlCommand objCommand = new SqlCommand(strSpName, connObj);
            objCommand.CommandType = CommandType.StoredProcedure;


            objCommand.Parameters.Add("@param1", SqlDbType.VarChar, 50);
            objCommand.Parameters["@param1"].Value = param1;


            objCommand.Parameters.Add("@Outparam", SqlDbType.Int);
            objCommand.Parameters["@Outparam"].Direction = ParameterDirection.Output;
            SqlDataAdapter sqldataAdpter = new SqlDataAdapter(objCommand);
            sqldataAdpter.Fill(ds);
            closeConnection();
        }
        catch (Exception ex)
        {
       
            evtlog.WriteError(ex.Message);
            HttpContext.Current.Response.Redirect("Error.aspx");
        }


        return ds;

    }




    public void createConnection()
    {
        try
        {
            connObj.ConnectionString = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
            connObj.Open();
        }
        catch (Exception ex)
        {
            //evtlog.LogException(ex.Message, "createConnection");
            evtlog.WriteError(ex.Message);
            HttpContext.Current.Response.Redirect("Error.aspx");


        }


    }



 public void closeConnection()
    {
        try
        {


            connObj.Close();
        }
        catch (Exception ex)
        {
           // evtlog.LogException(ex.Message, "closeConnection");
            evtlog.WriteError(ex.Message);
            HttpContext.Current.Response.Redirect("Error.aspx");


        }
     }

Code Snippet to Execute Stored Procedure (Which Returns int) from ASP.NET Application

Below is the code snippet to execute SP on SqlServer which is returning int

1.) Use the below namespace

using System.Data.SqlClient;
using System.Data.;


2.) Create Connection Object in your class in below manner

 SqlConnection connObj = new SqlConnection();

3.) Use the below method to execute SP and return the o/p


public int RunSpReturnint(string strSpName, string Param1, String Param2)
    {
        createConnection();
        DataSet ds = new DataSet();
        int result = 0;
        try
        {
            SqlCommand objCommand = new SqlCommand(strSpName, connObj);
            objCommand.CommandType = CommandType.StoredProcedure;
            objCommand.Parameters.Add("@Param1", SqlDbType.VarChar, 255);
            objCommand.Parameters["@Param1"].Value = Param1;


            objCommand.Parameters.Add("@Param2", SqlDbType.VarChar, 255);
            objCommand.Parameters["@Param2"].Value = Param2;




            objCommand.Parameters.Add("@Outparam", SqlDbType.Int);
            objCommand.Parameters["@Outparam"].Direction = ParameterDirection.Output;
            objCommand.ExecuteNonQuery();
            result = (int)objCommand.Parameters["@Outparam"].Value;
            closeConnection();


        }
        catch (Exception ex)
        {
            // evtlog.LogException(ex.Message, "RunSpReturnint");
            evtlog.WriteError(ex.Message);
            HttpContext.Current.Response.Redirect("Error.aspx");
        }


        return result;




    }




    public void createConnection()
    {
        try
        {
            connObj.ConnectionString = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
            connObj.Open();
        }
        catch (Exception ex)
        {
            //evtlog.LogException(ex.Message, "createConnection");
            evtlog.WriteError(ex.Message);
            HttpContext.Current.Response.Redirect("Error.aspx");


        }


    }



 public void closeConnection()
    {


        try
        {


            connObj.Close();
        }
        catch (Exception ex)
        {
           // evtlog.LogException(ex.Message, "closeConnection");
            evtlog.WriteError(ex.Message);
            HttpContext.Current.Response.Redirect("Error.aspx");


        }
        


    }

July 23, 2011

ASP.NET MultiViewCode Example

When you want multiple forms on a single .aspx page and at a time user should be able to see just one , you can use MultiView Control which divide single page in multiple views below is the code sample for that

ExMultiView.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExMultiView.aspx.cs" Inherits="ExMultiView" %>


<!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 id="Head1" runat="server">
</HEAD>


<BODY>
    <FORM id="form1" runat="server">
        <DIV>
           <table border="0" cellpadding="2" cellspacing="3" width="100%">
            <tr>
                <td>
                   <asp:LinkButton ID="lnkTab1" runat="server" OnClick="lnkTab1_Click">Reporting of Order On Sender</asp:LinkButton></td>
                <td>
                  <asp:LinkButton ID="lnkTab2" runat="server" OnClick="lnkTab2_Click">Date Wise Reporting of Order</asp:LinkButton></td>
               
            </tr>
            <tr>
                <td colspan="3">
                    <asp:MultiView ID="MultiView1" runat="server">
                         <table width="100%" cellpadding="2" cellspacing="5">
                         <tr>
                            <td>
                            <asp:View ID="View1" runat="server">
                             <table >
                             <tr>
                                 <td> Sender First Name </td>
                                 <td><asp:TextBox ID="txtSenderFName" runat="server"></asp:TextBox></td>
                                
                              </tr>
                              <tr> 
                                    <td>Sender Last Name </td>
                                    <td><asp:TextBox ID="txtSenderLastName" runat="server" ValidationGroup ="Report1"></asp:TextBox></td>
                                    <td><asp:RequiredFieldValidator ID="rfvSenderLastName" runat="server" ErrorMessage="* Required" ControlToValidate ="txtSenderLastName" SetFocusOnError ="true" ValidationGroup ="Report1" ForeColor="red" ></asp:RequiredFieldValidator ></td>
                              
                              </tr>
                              
                                     <tr> 
                                    <td style="height: 26px"> <asp:Button ValidationGroup ="Report1" ID="brnSearch" runat="server" Text="Search"  /></td>
                                    
                               </tr>
                                                           
                              </table>
                               <asp:GridView ID="GridViewReport1" runat="server">
                                </asp:GridView> 
                              </asp:View>
                            </td>
                            <td>
                                <asp:View ID="View2" runat="server">
                         
                           Second Form Comes here
                         
                             </asp:View>
                            </td>
                          
                        </tr>
                        </table>
                   </asp:MultiView>
               </td>
            </tr>
        </table>
    </FORM>
</BODY>
</HTML>

ExMultiView.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class ExMultiView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            MultiView1.ActiveViewIndex = 0;
        }
    }


   
    protected void lnkTab1_Click(object sender, EventArgs e)
    {
        MultiView1.ActiveViewIndex = 0;
    }
    protected void lnkTab2_Click(object sender, EventArgs e)
    {
        MultiView1.ActiveViewIndex = 1;
    }
    protected void lnkTab3_Click(object sender, EventArgs e)
    {
        MultiView1.ActiveViewIndex = 2;
    }
}

below 'll be the 0/p in which first view is enabled 

If Click on the Second tab , second view will be displayed 


July 18, 2011

Code Example for Editable(UPDATE,DELETE,CANCEL) Grid View ASP.NET

Below is the code sample for editable GridView which has (UPDATE ,DELETE and CANCEL ) functionality

ExEditGridView.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExEditGridView.aspx.cs" Inherits="ExEditGridView" %>


<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
           <asp:GridView ID="GridView1" runat="server" onrowupdated="GridView1_RowUpdated" 
               onrowcancelingedit="GridView1_RowCancelingEdit" 
               onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating" 
               onrowdeleting="GridView1_RowDeleting" >
               <Columns>
                   <asp:CommandField ShowEditButton="True" />
                    <asp:CommandField ShowDeleteButton="True" />
               </Columns>
        </asp:GridView>
        
    </div>
    </form>
</body>
</html>


ExEditGridView.aspx.cs using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Security;
using System.Web.Security;
using System.Configuration;


public partial class ExEditGridView : System.Web.UI.Page
{
    SqlConnection connObj = new SqlConnection();
    DataSet ds = new DataSet();
    SqlDataAdapter objAdapter;
    protected void Page_Load(object sender, EventArgs e)
    {
        connObj.ConnectionString = ConfigurationManager.ConnectionStrings["dotNetTrainingConnectionString"].ToString();
        connObj.Open();

        if (!IsPostBack)
        {
            BindData();
            FillGrid();
        }
     
     
    }

    public void BindData()
    {

     SqlCommand objCommand = new SqlCommand("Select * from student", connObj);
        objAdapter = new SqlDataAdapter(objCommand);
        objAdapter.Fill(ds);

        connObj.Close();
    }

    public void FillGrid()
    {

        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
    }


    protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
        int index = GridView1.EditIndex;
        GridViewRow row = GridView1.Rows[index];

        // Retrieve the value of the first cell
        Response .Write ( "Updated record " + row.Cells[1].Text);
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindData();
        FillGrid();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        BindData();
       GridViewRow row = GridView1.Rows[e.RowIndex];

        DataRow drnew =ds.Tables[0].NewRow ();
       

        drnew[1] = ((TextBox)(row.Cells[3].Controls[0])).Text;
        drnew[2] = ((TextBox)(row.Cells[4].Controls[0])).Text;

        ds.Tables [0].Rows.Add (drnew );

        //Update the values.


        ds.Tables[0].TableName = "student";

        SqlCommand comm = new SqlCommand("UPDATE  student SET FirstName=@FirstName,LastName=@LastName WHERE STUDENT_id="+((TextBox)(row.Cells[2].Controls[0])).Text, connObj);
        comm.Parameters.Add("@LastName", SqlDbType.VarChar, 255, "LastName");
        comm.Parameters.Add("@FirstName", SqlDbType.VarChar, 255, "FirstName");
     


        objAdapter.InsertCommand  = comm;
        objAdapter.Update(ds, "student");


        //Reset the edit index.
        GridView1.EditIndex = -1;

   

        //Bind data to the GridView control.
        BindData();
        FillGrid();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        //Bind data to the GridView control.
        BindData();
        FillGrid();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridViewRow delRow = GridView1.Rows[e.RowIndex];
        int ID =int.Parse (delRow.Cells[2].Text);

        SqlCommand cmd = new SqlCommand("delete  FROM STUDENT where Student_Id =" + ID, connObj);
        cmd.ExecuteNonQuery();
        BindData();
        FillGrid();

    }
}

July 1, 2011

Posting form data from ASP.NET page to another URL Using LINK Button

Sometime you need to post a form to an different url from asp.net pages
Below is the Exaple to post data from one page to another and retrieve it back using the Link Button


Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>


<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       Name: <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
       
        <asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="~/Default2.aspx">Next</asp:LinkButton></div>
    </form>
</body>
</html>


Default2.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(Request.Form["txtName"].ToString());
    }
}