Host Asp.Net Application in Web Farms

0

Written on 9:12 PM by Mj blog

Manoj 4_0 

Web Farms?


A web farm is a group or collection of servers which act as a single server and housed in single location. A Web farm can also be called as a server cluster.

Why Web Farms ?


It is used to increase the scalability, performance of the website when the load is more. The Major advantage is the availability (less downtime) of your web application. If one server in the Web farm is crashed or disabled , other servers in the Web farm take over, so users are never aware of the offline server.

ASP.net Application in Web Farms


Points to Remember


ASP.net uses viewstate which has a encryption along with machine key of the server. In web farm you don’t know which machine is going to return you the requested page  (provided the Affinity is set to single no problem).


Scenario : when you request a Home page and it come to the browser with a viewstate from server A and when you select some dropdownlist and that has a autopostback the request might go to server B , the viewstate encryption does not match and you will see the “Yellow Screen of Death”
Let’s see the various approaches to host a ASP.net Applicaiton in Web Farm

Approach 1:

Disable the EnableStateMac, EnableViewStateMac indicates that ASP.NET should run a machine authentication check (MAC) on the page’s view state when the page is posted back from the client;

   1: <system.web>


   2:   <pages enableViewStateMac=”false/>


   3: </system.web>






True - if view state should be MAC checked


False - We need to ensure that it is kept to false


You can do this in web.config else in Machine.config in c:\windows\Microsoft.net\Framework\v2.*\config folder



Approach 2:



The Next option is provide the unique Machine key to all the servers in the web farms you can find the

<Machine Key> tag in the Machine.config file





   1: <machineKey     


   2: validationKey=‘A130E240DF1C49E2764EF8A86CEDCBB11274E5298A130CA08B90EED016C0 


   3: 14CEAE1D86344C29E67E99DF83347E43820050A2B9C9FC89E0574BF3394B6D0401A9


   4: decryptionKey=’2CC37FFA8D14925B9CBCC0E3B1506F35066FEF33FEB4ADC8


   5:  validation=‘SHA1/>






If all the machine’s where using same machine key there is no need to disable the viewstate




Approach 3:



Maintaining session is difficult since the request can go to any machines, hence we can use the ASP.net State Server, but remember you should have the unique machinekey throughtout all the servers in the web farm

Open the web.config of the ASP.net Application and add the following syntax





   1: <configuration>


   2:   <sessionstate


   3:     mode=”stateserver


   4:     cookieless=”false


   5:     timeout=”20


   6:     sqlconnectionstring=”data source=127.0.0.1;user id=userid;password=password


   7:     server=”127.0.0.1


   8:     port=”42424/>


   9: </configuration>








Approach 4:



The Next Step is maintaining Session State using SQL Server.

Open the %windir%\Microsoft.NET\Framework\<versionNumber>\


You will find two SQL Scripts


InstallSqlState.sql


UninstallSqlState.sql


Run the InstallSqlState Script and you will have a new database and tables all stuff in the database and if you feel to remove it you can use the UninstallSqlState.sql scripts


Open the web.config of the ASP.net Application and add the following syntax





   1: <configuration>


   2:   <sessionstate


   3:     mode=”sqlserver


   4:     cookieless=”false


   5:     timeout=”20


   6:     sqlconnectionstring=”data source=127.0.0.1;user id=userid;password=password


   7:     server=”127.0.0.1


   8:     port=”42424/>


   9: </configuration>






So when every you hit a request all the sessions are maintained in SQL Server


Thus you can host a ASP.net Application in Web Farms

Adding NameSpace in ASP.net or C#

1

Written on 10:10 PM by Mj blog

Namespace are nothing but logical grouping of class inside the Assembly. Lets see the ways of adding Namespace in ASP.net

  1.  <%@Import Namespace =”System.Data” %>  - Embedding in HTML Source code
  2. Using System.Data – Importing in CS file
  3. System.Data.DataSet – Calling directly in CS code

The 3 ways are very common and there is a one more way to add namespace, consider your application has 100 pages and you need to add System.Data namespace to every page individually you can do this.

Go to the web.config and add the namepace in Pages element like this

<configuration>

      <appSettings/>

      <connectionStrings/>

      <system.web>

    <pages>

      <namespaces>

        <add namespace ="System.Data"/>

      </namespaces>

    </pages>

      </system.web>

</configuration>

So you learned 4 ways of adding Namespace in ASP.net. There is one more way also but it will be machine specific. Lets see, when ever we create add a new page or create new website in the visual studio the page has some namespace included in the .cs file … Ever wondered how that happened, actually microsoft has a hidden web.config file where all those namespace has been predefined. To fine out more go this path

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG

you will find a “web.config” file where ASP.net has predefined its default namespace, you can add your namespace there so that it appears in every page of the website you create.

Sorry guys I have not tried this with App.config file of windows application, if any one explore that pls report

Merger Header in GridView

1

Written on 10:26 PM by Mj blog

Let’s see how to merge the Header in the Gridview this can be achieved by either C# . Lets place a gridview on the aspx HTML source file

Sample View

gridsample

HTML Source Code

<asp:GridView ID="GridView1" runat="server" BackColor="White"
        BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4"
        ForeColor="Black" GridLines="Horizontal" onrowcreated="GridView1_RowCreated">
        <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
        <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
        <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White"
            BorderColor="#000066" BorderStyle="Solid" BorderWidth="1px" />
    </asp:GridView>

C# Code

It’s simple create row created event and use this code

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //Build Gridview in runtime
            GridView objGrdView = (GridView)sender; 
            GridViewRow objGrdViewRow = new
            GridViewRow(0, 0,  DataControlRowType.Header,  DataControlRowState.Insert);         
            //Create table cell
            TableCell objTblCell = new TableCell();
            //Add cell
            objTblCell.Text = "Name"; //provide the heard test
            objTblCell.ColumnSpan = 2;
            objTblCell.CssClass = "lblColor";
            objTblCell.HorizontalAlign = HorizontalAlign.Center;
            objGrdViewRow.Cells.Add(objTblCell);
            //Add cell 
            objTblCell = new TableCell(); //Create another cell
            objTblCell.HorizontalAlign = HorizontalAlign.Center;
            objTblCell.CssClass = "lblColor";
            objTblCell.Text = "Employee";
            objTblCell.ColumnSpan = 1;
            objGrdViewRow.Cells.Add(objTblCell);
            objGrdView.Controls[0].Controls.AddAt(0, objGrdViewRow);
        }
    }

we have checked for the row type whether its a header row and then we have taken the instance of the gridview then we have created new gridview row which is like tr of the table and table cell which is equal to the td of the table and we have inserted those td in the tr and then inserted the row on the first row of the gridview (which is nothing but a table on the runtime)

I forgot to say guys you have to bind the gridview ….

Hope its useful

Inserting a Row Within a Gridview footer

1

Written on 3:30 PM by Mj blog

Let's see how to insert a row in gridview from its footer template, Normally we will have seperate div area where we keep our Label and texbox and dropdownlist seperately and we will have a add button lets now reduce the space constraint by providing those controls on the footer template of the gridview and save space, we also know that by default gridview does not supports inserting data but now we are going to override that rule

Issues and work around
Before doing this there is special case when the database has no records the gridview never appears rite what shall we do this problem for this i have given a solution in my last blog check it . I am adding that source code also with this blog

Our Scenario
In this scenario I am going to have three columns one is ID column which will not be inserted and secound is Name which needs to be inserted hence we place a textbox and there is Status selection hence we are keeping a dropdownlist in the footer control then create a template for insert button

Now the steps to be followed


Step 1: Place a gridview and bind it with the database, create columns in the gridview and convert that to template

Step 2: Place Footer template for each column that to be inserted and create the controls we need for inserting the row

step 3 : Here we are going to bind our dropdownlist , to do so create gridview rowcreated event and bind the dropdownlist

Step 4: Then create a onclick event for insert button , provide the CommandName="Insert" and write the code for inserting the records in database

Let's see the HTML Source code


<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="False" DataKeyNames
="Id" CellPadding="4" ForeColor="Black" GridLines="Vertical" ShowFooter="True" BackColor="White"
BorderColor="#DEDFDE" BorderStyle="Solid"
BorderWidth="2px" OnRowCreated
="GridView1_RowCreated">
<RowStyle BackColor="#F7F7DE" />
<Columns>
<asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID">
<EditItemTemplate>

<asp:Label ID="Label1" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<EditItemTemplate>

<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="isactive">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("isactive") %>'></asp:TextBox>

</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("isactive") %>'></asp:Label> </ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlIsActive" runat="server">
</asp:DropDownList>
</FooterTemplate> </asp:TemplateField>
<asp:TemplateField FooterStyle-HorizontalAlign="Center">
<FooterTemplate>
<asp:Button ID="btnInsert" runat="server" Text="Insert" CommandName="Insert" OnClick="InsertRows" />
</FooterTemplate>
</asp:TemplateField>
</Columns>

<FooterStyle BackColor="#CCCC99" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<EmptyDataTemplate>
No Record Found
</EmptyDataTemplate>
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />

</asp:GridView>

Lets See the C# Code


using System;

using System.Collections.Generic;

using System.Collections;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Xml;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;


public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
BindGrid(); //Binding the gridview on page load
}
}
/// <summary>
/// This method connect to Sql database, fetch data returns dataset
/// </summary>
/// <returns></returns>
public DataSet ReturnMenuDetails()
{
DataSet ds = new DataSet();
using (SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings ["SqlConnectionString"].ConnectionString.ToString()))
{
sqlconn.Open();
SqlDataAdapter sqldap = new
SqlDataAdapter("select ID , Name , isactive from detail", sqlconn);
sqldap.Fill(ds);
}
return ds;
}
/// <summary>
/// This method return a datatable with empty row
/// </summary>
/// <returns></returns>
public DataTable ReturnEmptyDataTable()
{
DataTable dtMenu = new DataTable(); //declaringa datatable
DataColumn dcMenuID = new DataColumn("ID", typeof(System.Int32));

//creating a column in the same
//Name of column available in the sql server
dtMenu.Columns.Add(dcMenuID);// Adding column to the datatable

DataColumn dcMenuName = new
DataColumn("Name", typeof(System.String));
dtMenu.Columns.Add(dcMenuName);

DataColumn dcMenuActive = new
DataColumn("isactive", typeof(System.String));
dtMenu.Columns.Add(dcMenuActive);
DataRow datatRow = dtMenu.NewRow();

//Inserting a new row,datatable .newrow creates a blank row
dtMenu.Rows.Add(datatRow);//adding row to the datatable
return dtMenu;
}
/// <summary>
/// This method checks for no of rows returned from sql server and binds the
/// datasource with the gridview based on the resultset, if no rows returned are zero
/// from sql server then it will bind the datatable to the gridview to display the columns
/// when no record was returned
/// </summary>
public void BindGrid()
{
if (ReturnMenuDetails().Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ReturnMenuDetails();
}
else {
GridView1.DataSource = ReturnEmptyDataTable();

}
GridView1.DataBind();
}
/// <summary>
/// This method will search the dropdownlist in the footer template of the gridview
/// and bind the dropdownlist for this example i have used arraylist
/// we can bind from database also
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
//Checking whether the rended row is footer
if (e.Row.RowType == DataControlRowType.Footer)
{
ArrayList arraDropdown = new ArrayList();
arraDropdown.Add(new ListItem("Select", "-1"));
arraDropdown.Add(new ListItem("Yes", "Yes"));
arraDropdown.Add(new ListItem("No", "No"));
//searching for dropdownlist in the footer view of gridview
DropDownList ddl = (DropDownList)e.Row.Cells[0].FindControl("ddlIsActive");
//Binding the dropdownlist with arraylist
ddl.DataSource = arraDropdown;
ddl.DataBind();
}
}
/// <summary>
/// This method will be fired when ever the insert button is clicked
/// This method searches for the textbox and dropdownlist placed in
/// the footer template of gridview and passes the values to the
/// SQL query and binds the grid
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void InsertRows(object sender, EventArgs e)
{
TextBox txtName = (TextBox)GridView1.FooterRow.FindControl("TextBox4");
DropDownList ddlys = (DropDownList)GridView1.FooterRow.FindControl("ddlIsActive");
using (SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings ["SqlConnectionString"].ConnectionString.ToString()))
{
SqlCommand sqldap = new
SqlCommand("insert into switch_master(switch_Name,isactive,created_by) values ('" + txtName.Text + "','" + ddlys.SelectedItem.Text + "','Manoj')", sqlconn);
sqlconn.Open();
sqldap.ExecuteNonQuery();
}
BindGrid();
}
}


Thus we can insert new rows in the within gridview

Show Header and Footer Rows in an Empty GridView

0

Written on 3:21 PM by Mj blog

Lets see how to show columns in empty gridview and also show header and footer of empty gridview. The gridview does not show any header or footer when the datasource returns a empty data the only thing we can do is give some message in the empty data template, but we can acheive this following way

Step 1: place a gridview on the aspx page
Step 2: Set ShowHeader and ShowFooter option as true in the gridview property
Step 3: Bind the gridview with dataset
Step 4: create a datatable having the same column name and no. of columns of database counter part
Step 5: when binding check whether gridview with datasource check for the no. of rows the dataset returns from the databse,if the rows not greater than zero bind the datatable to the gridview
Step 6: This will show the header, footer and column also

Now See the Sample code …..

Default.aspx HTML Source code


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Id" CellPadding="4" ForeColor="#333333" GridLines="None" ShowFooter="True" >
<RowStyle BackColor="#F7F6F3"ForeColor="#333333" />

<Columns>

<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
</Columns>

<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<EmptyDataTemplate>
No Record Found
</EmptyDataTemplate>

<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />

<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>


The Gridview has two columns in the with column name as ID and Name, show footer and show header option is set to true


Default.aspx.cs C# source code

using System;

using System.Collections.Generic;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Xml;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;


public partial class _Default : System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid(); //Binding the gridview on page load
}
}
/// <summary>
/// This method connect to Sql database, fetch data returns dataset
/// </summary>
/// <returns></returns>
public DataSet ReturnMenuDetails()
{

DataSet ds = new DataSet();
using (SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString.ToString()))
{
SqlDataAdapter sqldap = new
SqlDataAdapter("select * from details", sqlconn);
sqldap.Fill(ds);
}
return ds;
}
/// <summary>
/// This method return a datatable with empty row
/// </summary>
/// <returns></returns>
public DataTable ReturnEmptyDataTable()
{
DataTable dtMenu = new DataTable(); //declaringa datatable
DataColumn dcMenuID = new DataColumn("ID", typeof(System.Int32));

//creating a column in the same
//Name of column available in the sql server
dtMenu.Columns.Add(dcMenuID);// Adding column to the datatable
DataColumn dcMenuName = new DataColumn("Name", typeof(System.String));
dtMenu.Columns.Add(dcMenuName);
DataRow datatRow = dtMenu.NewRow();

//Inserting a new row,datatable .newrow creates a blank row
dtMenu.Rows.Add(datatRow);//adding row to the datatable
return dtMenu;
}
/// <summary>
/// This method checks for no of rows returned from sql server and binds the
/// datasource with the gridview based on the resultset, if no rows returned are zero
/// from sql server then it will bind the datatable to the gridview to display the columns
/// when no record was returned
/// </summary>
public void BindGrid()
{
//checking for no. of rows returned from the dataset
if(ReturnMenuDetails().Tables[0].Rows.Count>0)
{
GridView1.DataSource = ReturnMenuDetails();
}
else
{
GridView1.DataSource = ReturnEmptyDataTable();
}
GridView1.DataBind();
}
}
Thus we can show the header, footer and the column name