Monday, 24 February 2014

Enableeventvalidation in asp.net

This feature eases the threat of unauthorized or nasty postback requests and callbacks. It is strongly suggested that you do not disable event validation.

Invalid postback or callback argument.  Event validation is enabled using. It don’t allow the user to insert the malicious data to post into browser;

 <%@ Page   enableEventValidation="true"  %>

By marking as EnableEventValidation= false ; any post back event like drop down or Button submit it won’t check the malicious data or Html encoded data.

Disabling the EnableEventValidation by below code;

   <%@ Page   enableEventValidation="false"  %>
You can do and assign the enableEventvalidation from code behind also like below code


protected void Page_Init(object sender, EventArgs e)
        {
            Page.EnableEventValidation = false;
        }


Enabling event validation for whole application by setting the enableEventvalidation=false in

web.config file by;
<system.web>
    <pages  enableEventValidation="false">
     </pages>
    </system.web>

Encrypt ViewState in ASP.NET

To reduce the chance of someone intercepting the info stored in the ViewState, it is good design to encode the ViewState.
There are different ways algorithms for doing the encryption for view state like SHA1,MD5 and 3DES. (I am not explaining the details about the algorithm in this articles)
 
Most popular algorithm for encrypting the ViewState is 3DES.
 
<system.web>
   <machineKey validation="3DES" />
   <pages  enableViewStateMac="true" >
   </pages>
 </system.web>
 

Reduce viewstate size asp net

ViewState : Web is a stateless medium; i.e., states are not sustained between requests by default. A web page is formed every time a page is posted to the server. The ASP.NET framework provides us several ways to maintain the state. Where ViewState is the one of the way. ViewState. We can persist data during postbacks with the help of ViewState. Why do we call ViewState as client-side? Because the data is stored on the page, and if we move from one page to another, the data would be lost.

Where does the ViewState gets stored? : The ViewState is stored on the page in a hidden field named __viewstate.
Problem On ViewState : The ViewState is stored on the page in the form of a hidden variable. It’s always advised to use the ViewState as little as possible. We also have other ways to reduce the performance overhead.
How to Reduce ViewState Size: There are many ways to reduce the view state size
·         Either use the compression\decompression
·         Maintain the view state on another server.

I am demonstrating you one of the way to doing it by SessionPageStatePersister; The SessionPageStatePersister utilizes server sessions associated with the browser session to store the data.
There are pros and cons to consuming the SessionPageStatePersister. Using session in its place of a hidden field avoids an increase in the page size being shown to and from the browser. In many conditions, the page state is a major part of the overall markup. However, loading this data in session consumes valuable server resources. Hidden fields do not have an linked timeout the way sessions do.
In order to use a persist other than the default, you override the PageStatePersister property of the page and return an instance of another persister.
protected override PageStatePersister PageStatePersister
        {
            get
            {
                return new SessionPageStatePersister(this);
            }
        }
If you want to apply it throughout the application, you can create a derived class and there you defined the SessionPageStatePersister and Inherit that derived page throughout your applications.
   public class PagePersisterBasePage : Page
    {
        public PagePersisterBasePage()
        {
        }
        protected override PageStatePersister PageStatePersister
        {
            get
            {
                return new SessionPageStatePersister(this);
            }
        }



    }

How IIS Process ASP.NET Request

When request come from client to the server a lot of operation is performed before sending response to the client. This is all about how IIS Process the request. 

Web Server
Web Server” comes into picture when we want to host the application on a centralized location and wanted to access from many locations. Web server is responsible for handle all the requests that are coming from clients, process them and provide the responses.

When we run our ASP.NET Web Application from visual studio IDE, VS Integrated ASP.NET Engine is responsible to execute all kind of asp.net requests and responses.  The process name is“WebDev.WebServer.Exe” which actually takw care of all request and response of an web application which is running from Visual Studio IDE.


IIS 

IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is used to host your ASP.NET Web application. IIS has it’s own ASP.NET Process Engine  to handle the ASP.NET request. So, when a request comes from client to server, IIS takes that request and  process it and send response back to clients.

Request Processing :


Hope, till now it’s clear to you that what is Web server and IIS is and what is the use of them. Now let’s have a look how they do things internally. Before we move ahead, you have to know about two main concepts
1.    Worker Process
2.  
 Application Pool
Worker Process:  Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system.  All the ASP.Net functionality runs under the scope of worker process.  When a request comes to the server from a client worker process is responsible to generate the request and response. In a single word we can say worker process is the heart of ASP.NET Web Application which runs on IIS.

Read Data from Excel Sheet in c#

Reading the data from excel sheet without opening it; there you need to just call the method into you application.

You need to connect to the excel data base by OLEDB connection and call the  excel sheet;

protected void btnShow_Click(object sender, EventArgs e)
        {
            GetData();
        }
      
        // save the data into dataview
        private void GetData()
        {
            DataTable sheetData = new DataTable();
            string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= 'c:\\Product DetailsEmployee.xlsx';Extended Properties='Excel 8.0;HDR=Yes;'";
            string query = "select * from [Sheet1$]";
            DataSet excelDataSet = new DataSet();
            OleDbDataAdapter da = new OleDbDataAdapter(query, strConn);
            da.Fill(excelDataSet);
            DgValue.DataSource = excelDataSet.Tables[0];
            DataView dv = ((DataTable)DgValue.DataSource).DefaultView;
            DataView dv_filter = new DataView();
            dv_filter.Table = excelDataSet.Tables[0];
            dv_filter.RowFilter = "Product_ID = '" + textBox1.Text + "'";
            DgValue.DataSource = dv_filter;
        }     

how to connect database in c# code project


Connecting the data to database and fetch the records from database and fill the Data adopter; and assign that value to Datatable;


You need to import the SqlConnection and SqlCommand for connecting database to SQl in C#
.
_connection is the variable which is use to make the connection. Where SQLConnection need to implement in C#.

SqlConnection _connection = new SqlConnection(_connectionstring);

Connectionstring is use to pass the connection string, currently we are giving the example of window authentication to the sql server,

 string _connectionstring = @"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";


SQL command is use to pass the command (or operation) that you want to perform any thing. In current we are trying to read the data from database and maintain it into Datatable.
                SqlCommand _command = new SqlCommand(_sql, _connection);


Full code
protected void btnShow_Click(object sender, EventArgs e)
        {
            BindData();
        }
        private void BindData()
        {
            try
            {
                string _connectionstring = @"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
                string _sql = "SELECT * FROM [Orders]";
                SqlConnection _connection = new SqlConnection(_connectionstring);
                SqlCommand _command = new SqlCommand(_sql, _connection);
                SqlDataAdapter _adapter = new SqlDataAdapter(_command);
                DataTable _table = new DataTable();
                _adapter.Fill(_table);
              
            }
            catch
            {
                throw;
            }

        }




In above code using the Datatable to maintain the result getting from the SQlDataAdptor.
SqlDataAdapter  it is using as the bridge for datatable and SQL database. It only convert the data result to datatable. 

It is called and connectionless architecture.


Code open ajax popup in asp.net

ASP.net code to place the model pop up in the html code.
Before wrinting the below code you need to import the ajaxcontrol toolkit dll into your application then you need to register it;

<!-------------test -- >
<-------------------->




In the below  code there is model popup which is having one button and text box where user can enter email address.

<@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit">


Below code attach the model popup with the panel as assign to it as their it is PopupControlID="Panel1".
<asp:Panel ID="Panel1" runat="server" Style="display: none" Width="450px" CssClass="thinBorder">
            <asp:Panel ID="Panel3" runat="server" Width="450px" Style="height: 30px" CssClass="tableHeader">
                <div>
                    <table width="100%">
                        <tr>
                            <td align="left" style="cursor: move;">
                                Enter Email Id
                            </td>
                            <td align="right">
                                <img id="CancelButton" src="Images/cancel.gif" alt="Cancle" />
                            </td>
                        </tr>
                    </table>
                </div>
            </asp:Panel>
            <div>
                <asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Conditional">
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="OkButton" EventName="Click" />
                    </Triggers>
                    <ContentTemplate>
                        <table cellpadding="0" cellspacing="0" id="tblSendmailText" runat="server"class="sectionBg1"
                            border="0" width="450px">
                            <tr>
                                <td colspan="2" style="height: 5px">
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2" style="height: 5px">
                                    <asp:Label ID="lblMessage" runat="server"></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2" style="height: 5px">
                                    [Thanks to share the information. Please enter email Id in text Area ]
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2" style="height: 5px">
                                </td>
                            </tr>
                            <tr>
                                <td align="left" width="90px">
                                    Email ID ::
                                </td>
                                <td align="left" width="300px">
                                    <asp:TextBox ID="txtEmail" runat="server"Width="189px"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"ValidationGroup="A1"
                                        ControlToValidate="txtEmail"ErrorMessage="*"></asp:RequiredFieldValidator>
                                    <asp:RegularExpressionValidator ID="RegularExpressionValidator2"runat="server" ValidationGroup="A1"
                                        ErrorMessage="Invalid Emailid!!" ControlToValidate="txtEmail"ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2" style="height: 5px">
                                </td>
                            </tr>
                            <tr>
                                <td align="left">
                                </td>
                                <td align="left">
                                    <asp:Button runat="server" OnClick="btnSubmit_Click" ValidationGroup="A1"Text="Submit"
                                        CssClass="buttonStyle" ID="OkButton" />
                                </td>
                            </tr>
                        </table>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </asp:Panel>
        <ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="lnkSendmail"
            PopupControlID="Panel1" BackgroundCssClass="modalBackground" CancelControlID="CancelButton"
            DropShadow="false" OnCancelScript="UserRegistionClear1();" OnLoad="ModalPopupExtender1_Load" />


 Below code attach the model popup with the panel as assign to it as their it is PopupControlID="Panel1"

<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="lnkSendmail"
            PopupControlID="Panel1" BackgroundCssClass="modalBackground" CancelControlID="CancelButton"
            DropShadow="false" OnCancelScript="UserRegistionClear1();" OnLoad="ModalPopupExtender1_Load" />


to Open the model popup we need to call that in one of the event in the any of the control like below. it assign with it by  TargetControlID="lnkSendmail"



 <asp:LinkButton runat="server" ID="lnkSendmail" ><img src="Images/mail_icon.gif"   alt="Send Mail"/></asp:LinkButton>

Ajax model popup will appear like