Archive for March 18th, 2008

how to use IList Generic Interface to store data?

Tuesday, March 18th, 2008

IList Generic Interface represents a collection of objects that can be individually accessed by index.
First, you will need to import the System.Collections.Generic namespace.
using System.Collections.Generic;

The System.Collections.Generic namespace contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.

We use the BindData function to do the work.
We use GridView control to display data. The code as follow:
private void BindData()
{
IList<UserInfo> userinfos = new List<UserInfo>();
for (int i = 0; i < 5; i++)
{
UserInfo info = new UserInfo(”username” + i.ToString(), “password” + i.ToString());
userinfos.Add(info);
}
this.GridView1.DataSource = userinfos;
this.GridView1.DataBind();
}

I add one userinfo custom class which is used to store data.
The code as follow:
using System;

/// <summary>
/// UserInfo
/// </summary>
public class UserInfo
{
private string _userName = string.Empty;
private string _password = string.Empty;
public UserInfo()
{

}
public UserInfo(string userName, string password)
{
this._userName = userName;
this._password = password;
}

public string UserName
{
get
{
return _userName;
}
}
public string Password
{
get
{
return _password;
}
}
}

Posted by Mahesh ( Tryangled )

How to use Globalization in ASP.NET?

Tuesday, March 18th, 2008

The System.Globalization namespace contains classes that define culture-related information, including the language, the country/region, the calendars in use, the format patterns for dates, currency, and numbers, and the sort order for strings. These classes are useful for writing globalized (internationalized) applications. We will show you a simple sample about how to write a globalized calendar in ASP.NET 2.0 and VB.NET.

We will show three languages in the calendar, English, Chinese and Janpanse.

First, import the namespace of System.Threading.
Imports System.Threading

When we select one language the page will show by the selected language.
System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo(Me.DropDownList1.SelectedValue)
System.Threading.Thread.CurrentThread.CurrentUICulture = New System.Globalization.CultureInfo(Me.DropDownList1.SelectedValue)

The flow for the code behind page is as follows.

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo(Me.DropDownList1.SelectedValue)
System.Threading.Thread.CurrentThread.CurrentUICulture = New System.Globalization.CultureInfo(Me.DropDownList1.SelectedValue)
End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo(Me.DropDownList1.SelectedValue)
System.Threading.Thread.CurrentThread.CurrentUICulture = New System.Globalization.CultureInfo(Me.DropDownList1.SelectedValue)
End Sub
End Class

Posted by Mahesh ( Tryangled )

RSS Reader using ASP.NET 2.0 and C# 2005?

Tuesday, March 18th, 2008

At first, import the namespace of System.Net, System.IO, and System.Xml
using System.Net;
using System.IO;
using System.Xml;

we created a simple function to process the RSS feed from a sample URL. This function define a string of rssURL as its parameter. This string contains the RSS’s URL. It will use the value of rssURL to create a WebRequest.

WebRequest is the abstract base class for the .NET Framework’s request/response model for accessing data from the Internet. An application that uses the request/response model can request data from the Internet in a protocol-agnostic manner, in which the application works with instances of the WebRequest class while protocol-specific descendant classes carry out the details of the request.

Requests are sent from an application to a particular URI, such as a Web page on a server. The URI determines the proper descendant class to create from a list of WebRequest descendants registered for the application. WebRequest descendants are typically registered to handle a specific protocol, such as HTTP or FTP, but can be registered to handle a request to a specific server or path on a server.

The response to this request will be put into WebResponse object. The WebResponse class is the abstract base class from which protocol-specific response classes are derived. Applications can participate in request and response transactions in a protocol-agnostic manner using instances of the WebResponse class while protocol-specific classes derived from WebResponse carry out the details of the request. Client applications do not create WebResponse objects directly; they are created by calling the GetResponse method on a WebRequest instance.

After then, the WebResponse object will be used to create a stream to get the XML data. Stream is the abstract base class of all streams. A stream is an abstraction of a sequence of bytes, such as a file, an input/output device, an inter-process communication pipe, or a TCP/IP socket. The Stream class and its derived classes provide a generic view of these different types of input and output, isolating the programmer from the specific details of the operating system and the underlying devices. The we used a XmlDocument to store the stream data. XmlDocument manipulating the data of XML, finally read the RSS contents from Feed.
protected void Page_Load(object sender, EventArgs e)
{
string rssURL = “http://www.tryangled.com/icom_includes/feeds/tryangled/rss-all.xml”;
Response.Write(”<font size=5><b>Site: ” + rssURL + “</b></font><Br />”);
ProcessRSSItem(rssURL);
Response.Write(”<hr />”);

rssURL = “http://www.try.com/icom_includes/feeds/special/dev-5.xml”;
Response.Write(”<font size=5><b>Site: ” + rssURL + “</b></font><Br />”);
ProcessRSSItem(rssURL);
}

public void ProcessRSSItem(string rssURL)
{
WebRequest myRequest = WebRequest.Create(rssURL);
WebResponse myResponse = myRequest.GetResponse();
Stream rssStream = myResponse.GetResponseStream();
XmlDocument rssDoc = new System.Xml.XmlDocument();
rssDoc.Load(rssStream);
XmlNodeList rssItems = rssDoc.SelectNodes(”rss/channel/item”);
string title = “”;
string link = “”;
string description = “”;
for (int i = 0; i <rssItems.Count; i++)
{
XmlNode rssDetail;

rssDetail = rssItems.Item(i).SelectSingleNode(”title”);
if (rssDetail != null)
{
title = rssDetail.InnerText;
}
else
{
title = “”;
}

rssDetail = rssItems.Item(i).SelectSingleNode(”link”);
if (rssDetail != null)
{
link = rssDetail.InnerText;
}
else
{
link = “”;
}

rssDetail = rssItems.Item(i).SelectSingleNode(”description”);
if (rssDetail != null)
{
description = rssDetail.InnerText;
}
else
{
description = “”;
}

Response.Write(”<p><b><a href=’” + link + “‘ target=’new’>” + title + “</a></b><br/>”);
Response.Write(description + “</p>”);
}
}

Posted by Mahesh ( Tryangled )

Deleting a directory using ASP.NET 2.0 and C# .NET?

Tuesday, March 18th, 2008

The .NET Framework offers a number of types that makes accessing resources on filesystems easy to use.
To delete a simple directory to the disk, we will need to first import the System.IO namespace. The System.IO namespace contains the Delete() method that we will use to perform our delete with.

using System.IO;
We’ll put our code in the btnSubmit_Click() event.

When the btnSubmit_Click() event fires it executes the Delete() method of the Directory namespace with the specified directory name in with the current directory (MapPath(”.”)) concatenating with our directory name and the boolean value of chkRecurse. This last argument specifies whether or not we would like to delete every subdirectory within our primary directory.

protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
Directory.Delete(MapPath(”.”) + “\\” + txtDir.Text, chkRecurse.Checked);
}
catch (Exception ex)
{
lblStatus.Text = ex.Message;
}
}

Posted by Mahesh ( Tryangled )

How to retrieve a webpage using ASP.NET 2.0 and C# .NET?

Tuesday, March 18th, 2008

To display an external webpage we will need to use the System.IO, System.Net, and System.Text namespaces.
using System.IO;
using System.Net;
using System.Text;

We’ll put our code in the Page_Load() event.

When the Page_Load() event fires it instantiates a new WebRequest object with the URL that we wish to retrieve. We then execute the GetResponse() method of this new object which returns a WebResponse object. After this is complete it is simply a matter of executing the GetResponseStream() method of the WebResponse object and reading the stream that is returned.

protected void Page_Load(object sender, EventArgs e)
{
WebRequest req = WebRequest.Create(”http://www.tryangled.com”);
WebResponse resp = req.GetResponse();
Stream s = resp.GetResponseStream();
StreamReader sr = new StreamReader(s,Encoding.ASCII);
string doc = sr.ReadToEnd();
lblStatus.Text = doc;
}
The flow for the code behind page is as follows.
using System;
using System.Data;
using System.Configuration;
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;
using System.IO;
using System.Net;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WebRequest req = WebRequest.Create(”http://www.tryangled.com”);
WebResponse resp = req.GetResponse();
Stream s = resp.GetResponseStream();
StreamReader sr = new StreamReader(s,Encoding.ASCII);
string doc = sr.ReadToEnd();
lblStatus.Text = doc;
}
}

Posted by Mahesh ( Tryangled )

Pinging with options using ASP.NET 2.0 and C# .NET?

Tuesday, March 18th, 2008

The .NET Framework offers a number of types that makes accessing resources on the network easy to use.
To perform a simple ping with options, we will need to use the System.Net, System.Net.Network.Information, System.Text namespaces.
using System.Net;
using System.Net.NetworkInformation;
using System.Text;

We’ll put our code in the btnSubmit_Click() event.

When the btnSubmit_Click() event fires it creates a new Ping object. We can then execute the Send method of this object to send a ping to the host specified in our text box. Executing this method also returns a PingReply object which we can use to gather information such as the Address, Roundtrip Time, TTL, and Buffer Size.

protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
lblStatus.Text = null;
txtPing.Text = null;
//Ping Options and Parameters
PingOptions pingopts = new PingOptions();
pingopts.DontFragment = chkFrag.Checked;
pingopts.Ttl = Convert.ToInt32(txtTTL.Text);

//create byte array for buffer
byte[] buffer = Encoding.ASCII.GetBytes(txtBuffer.Text);

Ping ping = new Ping();
PingReply pingreply = ping.Send(txtHost.Text,Convert.ToInt32(txtTimeOut.Text),buffer,pingopts);
txtPing.Text += “Address: ” + pingreply.Address + “\r”;
txtPing.Text += “Roundtrip Time: ” + pingreply.RoundtripTime + “\r”;
txtPing.Text += “TTL (Time To Live): ” + pingreply.Options.Ttl + “\r”;
txtPing.Text += “Buffer Size: ” + pingreply.Buffer.Length.ToString() + “\r”;

}
catch (Exception err)
{
lblStatus.Text = err.Message;
}
}
The front end .aspx page looks something like this:
<table width=”600″ border=”0″ align=”center” cellpadding=”5″ cellspacing=”1″ bgcolor=”#cccccc”>
<tr>
<td width=”100″ align=”right” bgcolor=”#eeeeee” class=”header1″>Hostname/IP:</td>
<td align=”center” bgcolor=”#FFFFFF”> <asp:textbox ID=”txtHost” runat=”server”></asp:textbox>

</td>
</tr>
<tr>
<td width=”100″ align=”right” bgcolor=”#eeeeee” class=”header1″>Ping Options:</td>
<td align=”center” bgcolor=”#FFFFFF”>
TTL (Time To Live):  <asp:TextBox ID=”txtTTL” runat=”server” Width=”24px”></asp:TextBox> <br />
<asp:CheckBox ID=”chkFrag” runat=”server” Text=”Dont Fragment” /> <br />
Buffer:
<asp:TextBox ID=”txtBuffer” runat=”server” Width=”175px”></asp:TextBox> <br />
Timeout:
<asp:TextBox ID=”txtTimeOut” runat=”server” Width=”24px”></asp:TextBox><br />
<asp:button ID=”btnSubmit” runat=”server” Text=”Submit” OnClick=”btnSubmit_Click” /></td>
</tr>
<tr>
<td width=”100″ align=”right” bgcolor=”#eeeeee” class=”header1″>Ping Results:</td>
<td align=”center” bgcolor=”#FFFFFF”> <asp:textbox ID=”txtPing” runat=”server” Height=”66px” TextMode=”MultiLine” Width=”226px”></asp:textbox>
<br /> <asp:label ID=”lblStatus” runat=”server”></asp:label></td>
</tr>
</table>

The flow for the code behind page is as follows.

using System;
using System.Data;
using System.Configuration;
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;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
lblStatus.Text = null;
txtPing.Text = null;

//Ping Options and Parameters
PingOptions pingopts = new PingOptions();
pingopts.DontFragment = chkFrag.Checked;
pingopts.Ttl = Convert.ToInt32(txtTTL.Text);

//create byte array for buffer
byte[] buffer = Encoding.ASCII.GetBytes(txtBuffer.Text);

Ping ping = new Ping();
PingReply pingreply = ping.Send(txtHost.Text,Convert.ToInt32(txtTimeOut.Text),buffer,pingopts);
txtPing.Text += “Address: ” + pingreply.Address + “\r”;
txtPing.Text += “Roundtrip Time: ” + pingreply.RoundtripTime + “\r”;
txtPing.Text += “TTL (Time To Live): ” + pingreply.Options.Ttl + “\r”;
txtPing.Text += “Buffer Size: ” + pingreply.Buffer.Length.ToString() + “\r”;

}
catch (Exception err)
{
lblStatus.Text = err.Message;
}
}
}

Posted by Mahesh ( Tryangled )

Rewriting a URL using ASP.NET 2.0 and C#.NET?

Tuesday, March 18th, 2008

To rewrite a URL on-the-fly in ASP.NET. This is done in the Global.asax file which contains event handlers for major events like Application_Start and Session_Start. This file is located in the root of the application directory and handles application level logic that doesnt interact with or create UI objects.

To perform any kind of advanced URL rewriting you will need to use the RegularExpression class objects found in System.Text.RegularExpressions.
Whenever a new HTTP request starts the Application_BeginRequest() event fires and we grab the current request in a HTTPContext object.
HttpContext myContext = HttpContext.Current;

By accessing the Request property of this object we can study an HttpRequest object and determine information commonly included in most HTTP requests (such as the URL requested). In this example, we want to redirect any request for “Default.aspx” and rewrite it to “Something.aspx”. We start by creating a Regex object that will capture the appropriate text.

Regex rewrite_regex = new Regex(@”(.+)\/((.+)\.aspx)”, RegexOptions.IgnoreCase);

This regular expression has three capturing groups: the directory the file is in, the filename (without extension), and the filename (with extension). We test the last group (filename w/ extension) to make sure it matches “Default.aspx” before we use the RewritePath() function of our HttpRequest object and forward the user before any page has been loaded.
try
{
//see if we need to rewrite the URL
Match match_rewrite = rewrite_regex.Match(myContext.Request.Path.ToString());

if (match_rewrite.Groups[2].Captures[0].ToString() == “Default.aspx”)
{
myContext.RewritePath(”Something.aspx”);
}
}
catch (Exception ex)
{
Response.Write(”ERR in Global.asax :” + ex.Message + “\n\n” + ex.StackTrace.ToString() + “\n\n”);
}
The flow for the entire Global.asax page is as follows. Some event stubs are created by default when adding a new Global.asax file via Visual Studios. These are included for completeness.

<%@ Application Language=”C#” %>
<script runat=”server”>
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.

}
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext myContext = HttpContext.Current;
Regex rewrite_regex = new Regex(@”(.+)\/((.+)\.aspx)”, RegexOptions.IgnoreCase);
try
{
//see if we need to rewrite the URL
Match match_rewrite = rewrite_regex.Match(myContext.Request.Path.ToString());
if (match_rewrite.Groups[2].Captures[0].ToString() == “Default.aspx”)
{
myContext.RewritePath(”Something.aspx”);
}
}
catch (Exception ex)
{
Response.Write(”ERR in Global.asax :” + ex.Message + “\n\n” + ex.StackTrace.ToString() + “\n\n”);
}
}
</script>

Posted by Mahesh ( Tryangled )

Windows performance monitoring in ASP.NET(C#)?

Tuesday, March 18th, 2008

Using the namespace of System.Diagnostics to get the data from Windows performance counter
using System;
using System.Net;
using System.Diagnostics;

At first declare three PerformanceCounter instances, define the category and counters in performance monitor
Then display the values obtained in different Labels. Label1 is for displaying the available memory, Lable2 is for the current processes numbers, while Lable3 is used for the total processes

By the looping of PerformanceCounterCategory.GetCategories method to go through all available categories
PerformanceCounter objMemperf = new PerformanceCounter(”Memory”,”Available Bytes”);
PerformanceCounter objProcperf = new PerformanceCounter(”System”, “Processes”);
PerformanceCounter objComperf = new PerformanceCounter(”System”, “Threads”);

Label1.Text = string.Format(”{0:#,###}”, objMemperf.NextValue()) + “Byte”;
Label2.Text = objProcperf.NextValue().ToString();
Label3.Text = objComperf.NextValue().ToString();
if (!Page.IsPostBack)
{
foreach(PerformanceCounterCategory objPer in PerformanceCounterCategory.GetCategories())
{
ListBox1.Items.Add(new ListItem(objPer.CategoryName));
}
}

The whole code behind front page
using System;
using System.Data;
using System.Configuration;
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;
using System.Text;
using System.Diagnostics;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PerformanceCounter objMemperf = new PerformanceCounter(”Memory”,”Available Bytes”);
PerformanceCounter objProcperf = new PerformanceCounter(”System”, “Processes”);
PerformanceCounter objComperf = new PerformanceCounter(”System”, “Threads”);

Label1.Text = string.Format(”{0:#,###}”, objMemperf.NextValue()) + “Byte”;
Label2.Text = objProcperf.NextValue().ToString();
Label3.Text = objComperf.NextValue().ToString();

if (!Page.IsPostBack)
{
foreach(PerformanceCounterCategory objPer in PerformanceCounterCategory.GetCategories())
{
ListBox1.Items.Add(new ListItem(objPer.CategoryName));

}
}
}
}

Posted by Mahesh ( Tryangled )

Making web progress bar using ASP.NET 2.0 and C#

Tuesday, March 18th, 2008

First, to create a  WebProgressBar.aspx  page and WebProgressBar.aspx.cs. Then import the System.Web.SessionState, System.Text and  System.Threading  namespaces.

The System.Web.SessionState namespace supplies classes and interfaces that enable storage of data specific to a single client within a Web application on the server. The session-state data is used to give the client the appearance of a persistent connection with the application. While the System.Threading namespace provides classes and interfaces that enable multithreaded programming.

using System.Web.SessionState;
using System.Text;
using System.Threading;

In order to demo the progress bar clearly, we simulate a long task by using the Thread.Sleep method to block the current thread for the specified number of milliseconds. Each block represent the different state. The session state value will be changed after each block.

The method of showModalDialog is used to create a modal dialog box that displays the specified HTML of progress bar.
private void LongTask()
{

for (int i = 0; i < 11; i++)
{
System.Threading.Thread.Sleep(1000);
Session[”State”] = i + 1;
}
Session[”State”] = 100;

}
public static void OpenProgressBar(System.Web.UI.Page Page)
{
StringBuilder sbScript = new StringBuilder();

sbScript.Append(”<script language=’JavaScript’ type=’text/javascript’>\n”);
sbScript.Append(”<!–\n”);
sbScript.Append(”window.showModalDialog(’Progress.aspx’,”,’dialogHeight: 100px; dialogWidth: 350px; edge: Raised; center: Yes; help: No; resizable: No; status: No;scroll:No;’);\n”);
sbScript.Append(”// –>\n”);
sbScript.Append(”</script>\n”);
Page.RegisterClientScriptBlock(”OpenProgressBar”, sbScript.ToString());
}

Button1_Click event is for starting the threads.
public void Button1_Click(object sender, System.EventArgs e)
{
Thread thread = new Thread(new ThreadStart(LongTask));
thread.Start();

Session[”State”] = 1;
OpenProgressBar(this.Page);
}

The front WebProgressBar.aspx page looks something like this:

<body>
<form id=”form1″ runat=”server”>
<fieldset>
<legend>WebProgressBar</legend>
<div>
<asp:Button id=”Button1″ runat=”server” Text=”Start Long Task!” OnClick=”Button1_Click”></asp:Button>
</div></fieldset>
</form>
</body>

In order to show the progress strip, we created Progress.aspx page. The bar will be refershed based on the session states, therefore, we can show the progress. The code behind page is as follows.
private int state = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session[”State”] != null)
{
state = Convert.ToInt32(Session[”State”].ToString());
}
else
{
Session[”State”] = 0;
}
if (state > 0 && state <= 10)
{
this.lblMessages.Text = “Processing”;
this.panelProgress.Width = state * 30;
this.lblPercent.Text = state * 10 + “%”;
Page.RegisterStartupScript(”", “<script>window.setTimeout(’window.Form1.submit()’,100);</script>”);
}
if (state == 100)
{
this.panelProgress.Visible = false;
this.panelBarSide.Visible = false;
this.lblMessages.Text = “Task Completed!”;
Page.RegisterStartupScript(”", “<script>window.close();</script>”);
}

}

The front Progress.aspx page looks something like this:
<body>
<form id=”Form1″ method=”post” runat=”server”>
<asp:Label id=”lblMessages” runat=”server”></asp:Label>
<asp:Panel id=”panelBarSide” runat=”server” Width=”300px” BorderStyle=”Solid” BorderWidth=”1px”
ForeColor=”Silver”>
<asp:Panel id=”panelProgress” runat=”server” Width=”10px” BackColor=”Green”></asp:Panel>
</asp:Panel>
<asp:Label id=”lblPercent” runat=”server” ForeColor=”Blue”></asp:Label>
</form>

</body>

The WebProgressBar.aspx for the whole code behind page is as follows.

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;
using System.Web.SessionState;
using System.Text;
using System.Threading;

public partial class WebProgressBar : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

private void LongTask()
{

for (int i = 0; i < 11; i++)
{
System.Threading.Thread.Sleep(1000);
Session[”State”] = i + 1;
}
Session[”State”] = 100;

}
public static void OpenProgressBar(System.Web.UI.Page Page)
{
StringBuilder sbScript = new StringBuilder();

sbScript.Append(”<script language=’JavaScript’ type=’text/javascript’>\n”);
sbScript.Append(”<!–\n”);
sbScript.Append(”window.showModalDialog(’Progress.aspx’,”,’dialogHeight: 100px; dialogWidth: 350px; edge: Raised; center: Yes; help: No; resizable: No; status: No;scroll:No;’);\n”);
sbScript.Append(”// –>\n”);
sbScript.Append(”</script>\n”);
Page.RegisterClientScriptBlock(”OpenProgressBar”, sbScript.ToString());
}
public void Button1_Click(object sender, System.EventArgs e)
{
Thread thread = new Thread(new ThreadStart(LongTask));
thread.Start();

Session[”State”] = 1;
OpenProgressBar(this.Page);
}

}

The Progress.aspx for the whole code behind page is as follows.
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 Progress : System.Web.UI.Page
{
private int state = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session[”State”] != null)
{
state = Convert.ToInt32(Session[”State”].ToString());
}
else
{
Session[”State”] = 0;
}
if (state > 0 && state <= 10)
{
this.lblMessages.Text = “Task undertaking!”;
this.panelProgress.Width = state * 30;
this.lblPercent.Text = state * 10 + “%”;
Page.RegisterStartupScript(”", “<script>window.setTimeout(’window.Form1.submit()’,100);</script>”);
}
if (state == 100)
{
this.panelProgress.Visible = false;
this.panelBarSide.Visible = false;
this.lblMessages.Text = “Task Completed!”;
Page.RegisterStartupScript(”", “<script>window.close();</script>”);
}

}
}

Posted by Mahesh ( Tryangled )

How to use Themes and user interface in ASP.NET?

Tuesday, March 18th, 2008

We will use the namespace of System.Web.UI in this tutorial.

Imports System.Web.UI
Please add two controls of labels, textboxs and buttons to the webpage page, and a control of dropdownlist to select color of controls in the page. Then please create theme folder of BlueTheme and PorpleTheme, and add Control.skin, Default.css to the folders.

Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreInit
Page.Theme = Request(”ChooseTheme”)
End Sub ‘Page_PreInit

‘Control.skin of the BlueTheme

<asp:TextBox
BackColor=”#c4d4e0″
ForeColor=”#0b12c6″
Runat=”Server” />
<asp:Label
ForeColor=”#0b12c6″
Runat=”Server” />
<asp:Button
BackColor=”#c4d4e0″
ForeColor=”#0b12c6″
Runat=”Server” />

‘Control.skin of the PorpleTheme

<asp:TextBox
BackColor=”#ccccff”
ForeColor=”#602bff”
Runat=”Server” />
<asp:Label
ForeColor=”#602bff”
Runat=”Server” />
<asp:Button
BackColor=”#ccccff”
ForeColor=”#602bff”
Runat=”Server” />

Default.css    //Style sheet file

body
{
margin:0;
padding:0;
overflow:hidden;
}
.tableStyle
{
font-family:”@Terminal”;
font-size:12px;
color:#000000;
line-height:120%;
background-image:url(image/bg.jpg);
}
.tdStyle
{
background-image:url(image/Bar_out.gif);
}

The flow for the code behind page as follows.

Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreInit
Page.Theme = Request(”ChooseTheme”)
End Sub ‘Page_PreInit
End Class

Posted by Mahesh ( Tryangled )