Monday, July 5, 2010

Avoiding TCP/IP Port Exhaustion

When a client initiates a TCP/IP socket connection to a server, the client typically connects to a specific port on the server and requests that the server respond to the client over an ephemeral, or short lived, TCP or UDP port. On Windows Server 2003 and Windows XP the default range of ephemeral ports used by client applications is from 1025 through 5000. Under certain conditions it is possible that the available ports in the default range will be exhausted.

Increase the upper range of ephemeral ports that are dynamically allocated to client TCP/IP socket connections.

Start Registry Editor.

Browse to, and then click the following key in the registry:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

On the Edit menu, click New, DWORD Value, and then add the following registry value to increase the number of ephemeral ports that can by dynamically allocated to clients:

Value name:MaxUserPort

Value data



Close Registry Editor.

Note
You must restart your computer for this change to take effect.

Note

Increasing the range of ephemeral ports used for client TCP/IP connections consumes Windows kernel memory. Do not increase the upper limit for this setting to a value higher than is required to accommodate client application socket connections so as to minimize unnecessary consumption of Windows kernel memory.
Reduce the client TCP/IP socket connection timeout value from the default value of 240 seconds

Start Registry Editor.

Browse to, and then click the following key in the registry:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

On the Edit menu, click New, DWORD Value, and then add the following registry value to reduce the length of time that a connection stays in the TIME_WAIT state when the connection is being closed. While a connection is in the TIME_WAIT state, the socket pair cannot be reused:

Value name

TcpTimedWaitDelay

Value data



Close Registry Editor.

Note:

You must restart your computer for this change to take effect.

Determining the Control that Caused a PostBack in pageload

This article is for find which contorl that caused a post back.

Some times you might need to perform some action on an ASP.NET postback based on the control that caused the postback to occur. Some scenarios for this might include a form with many regions, each having it's own CustomValidator and the ability to perform a postback when a button for the section is clicked. Another scenario might be to set focus back to the control that caused the postback.

By using below methode we will find the which control has triggred post back.

public static Control GetPostBackControl(Page page)
{

Control postbackControlInstance = null;

string postbackControlName = page.Request.Params.Get("__EVENTTARGET");

if (postbackControlName != null && postbackControlName != string.Empty)
{
postbackControlInstance = page.FindControl(postbackControlName);
}

else
{
// handle the Button control postbacks

for (int i = 0; i < page.Request.Form.Keys.Count; i++)
{
postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]);

if (postbackControlInstance is System.Web.UI.WebControls.Button)
{
return postbackControlInstance;
}
}
}

// handle the ImageButton postbacks

if (postbackControlInstance == null)
{
for (int i = 0; i < page.Request.Form.Count; i++)
{
if ((page.Request.Form.Keys[i].EndsWith(".x")) || (page.Request.Form.Keys[i].EndsWith(".y")))
{
postbackControlInstance = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length - 2));
return postbackControlInstance;
}
}
}

return postbackControlInstance;

}

Above takes a parameter which is a reference to the Page, it then uses that to look for the control that caused the postback. You can easily use this as follows:

Control cause = GetPostBackControl(this.Page);

Insert excel data into DB by using C#.NET

In this example i am going to describe how to Import or insert data into Sql server from Excel spreadsheet using sqlbulkcopy method.

Create a Excel workbook as shown in image below and insert some data into it.

Create a table in SQL database as shown in below

ColumnName Data Type
ID int
Name varchar(50)
Location varchar(50)


Now write this code to insert data into SQL table
public partial class _Default : System.Web.UI.Page
{
string strConnection = ConfigurationManager.ConnectionStrings
["ConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
//Create connection string to Excel work book
string excelConnectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\Details.xls;
Extended Properties="
"Excel 8.0;HDR=YES;""";

//Create Connection to Excel work book
OleDbConnection excelConnection =
new OleDbConnection(excelConnectionString);

//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand
("Select [ID],[Name],[Location] from [Detail$]",
excelConnection);

excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();

SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "Details";
//sqlBulk.ColumnMappings.Add("ID", "ID");
//sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.WriteToServer(dReader);
}
}


If there are more columns in your database table or excel workbook and you want to insert data in some of them than you need to add ColumnMappings like this

sqlBulk.ColumnMappings.Add("ID", "ID");
sqlBulk.ColumnMappings.Add("Name", "Name");

Below i am writing the code without sqlbulk by using dataset.

protected void Button2_Click(object sender, EventArgs e)
{
DataSet dUser_Info = new DataSet();

string excelConnectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;""", "C:\\Details.xls");

string query = String.Format("Select [Id],[Name],[Location] from [Sheet1$]");
OleDbConnection oleCon = new OleDbConnection(excelConnectionString);
OleDbDataAdapter oleAdp = new OleDbDataAdapter(query, oleCon);
try
{
oleAdp.Fill(dUser_Info);
}
catch (OleDbException ex)
{
if (ex.Message == "No value given for one or more required parameters.")
{
//paramter name is invalid
return;
}
}

SqlConnection DBConn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectString"]);

DBConn.Open();

foreach (DataRow dr in dUser_Info.Tables[0].Rows)
{
SqlCommand DBQuery = new System.Data.SqlClient.SqlCommand();


DBQuery.Connection = DBConn;

DBQuery.CommandText = "insert into tbuserinfo (Id,Name,Location) values('" + dr["Id"].ToString() + "','" + dr["Name"].ToString() + "','" + dr["Location"].ToString()+"'";

DBQuery.ExecuteNonQuery();

}

DBConn.Close();

}

How to Bind Enum Types to the Dropdown or any other bindable Control in ASP.NET by using C#.NET

This article is for those who want to bind the bindable controls(Drop down...etc) in Web/Window Form to the Enum data type.

Sometimes, we want to bind the Enums to the bindable controls instead of fetching the data from the database and then bind it to the bindable controls. Here I explain how to bind the Enums that you have defined in your Common Classes/Utility Classes Code.

Imagine you have an enum defined in your code like so:

[Serializable]
public enum Departments
{
Marketing=0,
IT=1,
BusinessDevelopment=3,
Finance=4
}

Every Enum type derives from System.Enum. There are two static methods that help bind data to a binable control (and retrieve the value). These are Enum.GetNames and Enum.Parse. Using GetNames,you are able to bind to your binable control as follows:

Below i am writing the example how to bind the enum to dropdown list.

Dropdown list id:DDLDeparments

DDLDeparments.DataSource = System.Enum.GetNames(typeof(Departments));
DDLDeparments.DataBind();

Now if you want the Enum value Back on Selection ....

private void DDLDeparments_SelectedIndexChanged(object sender, System.EventArgs e)
{
Departments selecteddep = (Departments)Enum.Parse(DDLDeparments.SelectedValue);
}