Practical Demo

Practical Demonstration For Dotnet

My New Blog

Friends and my dudes.. I have altered my blog and change its address to http://www.dotnetandwp7.blogspot.com so please go to that page and refer. In that page i'm going to post Windows phone 7 application development Articles also.. Have a Nice Day....

Sunday, March 4, 2012

DataList Image Binding


DataList Image Binding: Hai Folks, In this posting I’m going to explain how to insert image into database and how to bind the inserted image into datalist control. Let us see in detail. First of all we have to create the database with the following fields.


 Here the Prod_Img field only goes to store the specified/selected image in a binary format. After creating these database table designs our next step is to create the Front-End to insert the image details into database. Create the following Front-End design. Name the webpage name is “imginsert.aspx”.


  Imginsert.aspx.cs:
 Add the namespace for database connectivity.
 using System.Data.SqlClient;
 using System.Data;
 protected void Page_Load(object sender, EventArgs e)

{

//Random Number Generation for image_ID
 Random rn = new Random();

//this Label1 is used to bind the generated random number.
 Label1.Text = "PRD" + rn.Next(10000, 90000);
 }
protected void Button1_Click(object sender, EventArgs e)
 {
 SqlConnection con = new SqlConnection();
 // SqlCommand cmd = new SqlCommand();
 con.ConnectionString = "Data Source=.;Initial Catalog=DB_Name;uid=sa;password=hi";
 try
 {
 FileUpload img = (FileUpload)FileUpload1;
 Byte[] imgByte = null;
 if (img.HasFile && img.PostedFile != null)
 {
 //To create a PostedFile
 HttpPostedFile File = FileUpload1.PostedFile;
 //Create byte Array with file len
 imgByte = new Byte[File.ContentLength];
 //force the control to load data in array
 File.InputStream.Read(imgByte, 0, File.ContentLength);
 }
 // Insert the employee name and image into db
 con.Open();
 string sql = "INSERT INTO products(Prod_Id,Prod_Name,Prod_Desc,Prod_Img,Prod_Cost) VALUES(@pid,@pname,@pdesc,@pimg,@pcost) SELECT @@IDENTITY";
 SqlCommand cmd = new SqlCommand(sql, con);
 cmd.Parameters.AddWithValue("@pid",Label1.Text); cmd.Parameters.AddWithValue("@pname",TextBox1.Text); cmd.Parameters.AddWithValue("@pdesc",TextBox2 .Text);
 cmd.Parameters.AddWithValue("@pimg", imgByte); cmd.Parameters.AddWithValue("@pcost",TextBox3.Text);
 //int id = Convert.ToInt32(cmd.ExecuteScalar());
 //lblResult.Text = String.Format("Employee ID is {0}", id);
 cmd.ExecuteNonQuery();
 }
 catch
 {
 Label2.Text = "There was an error";
 }
 finally
 {
 con.Close();
 }
 Next we are going to design the datalist.aspx page for binding the inserted image details in datalist. To do this we have to design the ItemTemplate for datalist.


<asp:DataList ID="DataList1" runat="server" BackColor="#666666" RepeatColumns="2">

        <AlternatingItemStyle BackColor="#993366" />

        <ItemStyle BackColor="#990099" />

        <ItemTemplate>

            <table class="style1"

                

                style="font-size: 20px; font-weight: lighter; color: #000000; font-family: 'Bookman Old Style'">

                <tr>

                    <td class="style2">

                        Product_ID:</td>

                    <td class="style3">

                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("Prod_ID") %>'></asp:Label>

                    </td>

                </tr>

                <tr>

                    <td class="style2">

                        Product_Name</td>

                    <td class="style3">

                        <asp:Label ID="Label2" runat="server" Text='<%# Eval("Prod_Name") %>'></asp:Label>

                    </td>

                </tr>

                <tr>

                    <td class="style2">

                        Product_Description:</td>

                    <td class="style3">

                        <asp:Label ID="Label3" runat="server" Text='<%# Eval("Prod_Desc") %>'></asp:Label>

                    </td>

                </tr>

                 <tr>

                    <td class="style2">

                        Product_Cost</td>

                    <td class="style3">

                        <asp:Label ID="Label4" runat="server" Text='<%# Eval("Prod_Cost") %>'></asp:Label>

                    </td>

                </tr>

                <tr>

                    <td class="style2">

                        Product_Image:</td>

                    <td class="style3">

                        <asp:ImageButton ID="ImageButton1" runat="server" Height="159px"  ImageUrl='<%# "img_handler.ashx?Prod_ID="+ Eval("Prod_ID") %>'

                            Width="197px" />

                    </td>

                </tr>

              

            </table>

        </ItemTemplate>

    </asp:DataList>





Datalist.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
 public partial class datalist : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
 if (!IsPostBack)
 {
 SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.;Initial Catalog=DB_Name;uid=sa;password=hi";
con.Open();
SqlCommand command = new SqlCommand("SELECT Prod_ID,Prod_Name,Prod_Desc,Prod_Img,Prod_cost from products", con);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
DataList1 .DataSource = dt; DataList1.DataBind();
 //gvImages.Attributes.Add("bordercolor", "black");
con.Close();
 }
 }
}
 Now we are going to add handler for binding images to datalist.
 Choose website ->add new item->Generic Handler and name the handler is “img_handler.ashx” .
<%@ WebHandler Language="C#" Class="img_handler" %>;
 using System;
using System.Web;
using System.Data.SqlClient;
 using System.Data;
 public class img_handler : IHttpHandler {
 public void ProcessRequest (HttpContext context)
{
 string strcon = "Data Source=.;Initial Catalog=DB_Name;uid=sa;password=hi";
string imageid = context.Request.QueryString["Prod_ID"];
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand command = new SqlCommand("select Prod_Img from products where Prod_ID='"+imageid+"'", connection);
 SqlDataReader dr = command.ExecuteReader();
 dr.Read();
 context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
 }
 public bool IsReusable { get { return false; } }
}

Output:

Friday, March 2, 2012

How to Insert and download Images, Word file, Audio and video files in ASP.NET

Hai Folks, In this post I will explain how to insert images, audio, video, word document, power point presentation and PDF files to Database(Sql Server 2005) and how to download using asp.net. As we all know about how to insert data into database. But inserting these kind (Image, video, audio etc) of data is little bit different from the normal data insertion. To insert these kinds of data we have to convert these data into a binary format and then insert. In Sql server 2005 we have the data type named “VarBinary(MAX)” that is used for inserting these type of data to data base. If you choose “VarBinary(500)” instead of “VarBinary(MAX)” means, sometimes it will throw the Error named “String or binary data would be truncated”. So be aware of it. First we will design the database creation: Go to Microsoft Sql Server 2005 Sql server management studio from all programs menu. Then create database and named it. Then create a new table with the necessary fields that is listed below.
Note that, Here the Name is File name and the ContentType is the type of the File (.doc , .docx, .jpg, .png, .ppt, .pdf etc). Next design the following Front-End for inserting files to DB.
Now Double click the button and go to coding page. protected void Page_Load(object sender, EventArgs e)
{
Session [“uname”]=TextBox1.Text.ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
string filePath = frmUpload.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".ppt":
contenttype = "application/vnd.ms-PowerPoint";
break;
case ".pptx":
contenttype = "application/vnd.ms-PowerPoint";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
}
if (contenttype != String.Empty)
{
Stream fs = frmUpload.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "insert into quotation(uname,Name, ContentType, Data) values (@uname, @Name, @ContentType, @Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@uname", SqlDbType.VarChar).Value = uname;
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = contenttype;
cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
}
else
{
}
}
private Boolean InsertUpdateData(SqlCommand cmd)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source=.;Initial Catalog=DB_Name;uid=sa;password=hi";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
Here the Boolean return type named InsertUpdateData is mainly used to insert/Execute the given query and return the true/false value. Next we simply redirect this insert page to some other page using the following code. Now type this coding at the end of the button1_click event Response.Redirect(“download.aspx”); Now this is to be redirected the “download.aspx” from the current page. Now design the download.aspx page with the following Controls
After that goto download.aspx.cs page and do the following things. Get the session value first using the following coding. string uname = Session[“uname”]. ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.;
Initial Catalog=DB_Name;uid=sa;password=hi";
con.Open();
string str = "Select Name from quotation where uname=@tig ";
SqlCommand cmd = new SqlCommand(str, con);
cmd.Parameters.Add("@tig", SqlDbType.VarChar).Value = uname;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField =ds.Tables[0].Columns["Name"].ColumnName.ToString();
DropDownList1.DataBind();
con.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string strQuery ="select uname,ContentType,Data from quotation where uname=@cid";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@cid",SqlDbType.VarChar).Value = DropDownList1.Text;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source=.;Initial Catalog=DB_Name;uid=sa;password=hi";
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
private void download(DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition","attachment;filename="+
dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
Now your selected file has to be download in your desired location. Happy Coding..!

Wednesday, August 17, 2011

DATALIST CONTROL IN ASP.NET 3.5

Datalist Control in ASP.Net
DataList is a data bound list control that displays items using certain templates defined at the design time. The content of the DataList control is manipulated by using templates sections such as AlternatingItemTemplate, EditItemTemplate, FooterTemplate, HeaderTemplate, ItemTemplate, SelectedItemTemplate and SeparatorTemplate. Each of these sections has its own characteristics to be defined but at a very minimum, the ItemTemplate needs to be defined to display the items in the DataList control. Other sections can be used to provide additional look and feel to the DataList control.



The contents of the DataList control can be manipulated by using templates. The following table lists the supported templates.
The DataList control displays data items in a repeating list, and optionally supports selecting and editing the items. The content and layout of list items in DataList is defined using templates. At a minimum, every DataList must define an ItemTemplate; however, several optional templates can be used to customize the appearance of the list.

AlternatingItemTemplate: If defined, provides the content and layout for alternating items in the DataList. If not defined, ItemTemplate is used.

EditItemTemplate: If defined, provides the content and layout for the item currently being edited in the DataList. If not defined, ItemTemplate is used.

FooterTemplate: If defined, provides the content and layout for the footer section of the DataList. If not defined, a footer section will not be displayed.

HeaderTemplate: If defined, provides the content and layout for the header section of the DataList. If not defined, a header section will not be displayed.

ItemTemplate: Required template that provides the content and layout for items in the DataList.

SelectedItemTemplate: If defined, provides the content and layout for the currently selected item in the DataList. If not defined, ItemTemplate is used.

SeparatorTemplate: If defined, provides the content and layout for the separator between items in the DataList. If not defined, a separator will not be displayed.

At the very minimum, the ItemTemplate needs to be defined to display the items in the DataList control. Additional templates can be used to provide a custom look to the DataList control.


The appearance of the DataList control may be customized by setting the style properties for the different parts of the control. The following table lists the different style properties.

AlternatingItemStyle: Specifies the style for alternating items in the DataList control.

EditItemStyle: Specifies the style for the item being edited in the DataList control.

FooterStyle: Specifies the style for the footer in the DataList control.

HeaderStyle: Specifies the style for the header in the DataList control.

ItemStyle: Specifies the style for the items in the DataList control.

SelectedItemStyle: Specifies the style for the selected item in the DataList control.

SeparatorStyle: Specifies the style for the separator between the items in the DataList control.

You can also show or hide different parts of the control. The following table lists the properties that control which parts are shown or hidden.

ShowFooter: Shows or hides the footer section of the DataList control.

ShowHeader: Shows or hides the header section of the DataList control.

The display direction of a DataList control can be vertical or horizontal. Set the RepeatDirection property to specify the display direction.
The layout of the DataList control is controlled with the RepeatLayout property. Setting this property to RepeatLayout.Table will display the DataList in a table format, while RepeatLayout.Flow displays the DataList without a table structure.

Lets we saw in detail.
To create a datalist oriented application we have to construct the templates.
That is ItemTemplate and EditItemTemplate.
ItemTemplate has been created in the following manner.

Similarly
Lets we saw an example Program..
In Default.aspx page Do the following.
<%@ 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>
<br />
<asp:DataList runat="server"
DataKeyField="ID"
ID="DataList1"
OnEditCommand="DataList1_EditCommand"
OnCancelCommand="DataList1_CancelCommand"
OnUpdateCommand="DataList1_UpdateCommand">
<EditItemTemplate>
ID: <asp:Label ID="Label1" runat="server"
Text='<%# Eval("ID") %>'>
</asp:Label>
<br />
Name: <asp:TextBox ID="textCategoryName" runat="server"
Text='<%# Eval("name") %>'>
</asp:TextBox>
<br />
Description: <asp:TextBox ID="textDescription"
runat="server"
Text='<%# Eval("description") %>'>
</asp:TextBox>
<br />
<asp:LinkButton ID="LinkButton1" runat="server"
CommandName="update" >
Save
</asp:LinkButton>
 
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="cancel" >
Cancel
</asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
ID:
<asp:Label ID="IDLabel" runat="server"
Text='<%# Eval("ID") %>'></asp:Label>
<br />
name:
<asp:Label ID="nameLabel" runat="server"
Text='<%# Eval("name") %>'></asp:Label>
<br />
description:
<asp:Label ID="descriptionLabel" runat="server"
Text='<%# Eval("description") %>'></asp:Label>
<br />
<asp:LinkButton runat="server" ID="LinkButton1"
CommandName="edit" >
Edit
</asp:LinkButton><br />
<br />
</ItemTemplate>

</asp:DataList>
</div>
</form>
</body>
</html>

Now Go to Default.aspx.cs:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Bind data to the Data List control when page load first time
bindList();
}
}
void bindList()
{
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
sqlcon.ConnectionString = "data source=.;Initial Catalog=datagrid;uid=sa;password=hi";
//Open Sql server Connection
sqlcon.Open();
sqlcmd = new SqlCommand("select * from employ", sqlcon);
//Execute query and fill value in data table
SqlDataAdapter da;
da = new SqlDataAdapter(sqlcmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
//Bind data into the DataList control
DataList1.DataSource = dt;
DataList1.DataBind();
}
//Close SQl Server Connection
sqlcon.Close();
}
protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
{
//Get Edit Item index when user click edit button
DataList1.EditItemIndex = e.Item.ItemIndex;
bindList();

}
protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)
{

//Leave it Item in default for reload DataList
DataList1.EditItemIndex = -1;
bindList();

}
protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
{
//Get User entered value in the Edit mode text boxes
string name = ((TextBox)e.Item.FindControl("textCategoryName")).Text;
string description = ((TextBox)e.Item.FindControl("textDescription")).Text;

//Get the Identity Primary DataKey value when user click update button
int eno = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
sqlcmd = new SqlCommand("update employ set name='" + name + "',description='" + description + "' where ID='" + eno + "'", sqlcon);
sqlcon.ConnectionString = "data source=.;Initial Catalog=datagrid;uid=sa;password=1soft";
sqlcon.Open();
//Execute query to perform update operation on SQL Server
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
//Set datalist default index -1 for display record
DataList1.EditItemIndex = -1;
//Bind new updated data on DataList control
bindList();

}
}

Dont Forgot to create the Database Table Design..
Happy Coding..

Thursday, August 4, 2011

Data Caching in ASP.NET3.5 in DataList View..

Hai My readers,
In this post i will Give a sample program for data caching in asp.net3.5.
Finally i filled all the databound values into the Datalist.
Lets we see in details.

If you are using static data with your ASP.NET applications, such
as that from a database server like Microsoft SQL Server, you should take a
look at caching your data. Previously, this was not an easy thing to do, but the
caching in .NET makes caching your data and objects a trivial task.

In ASP.NET, every page you write extends the
System.Web.UI.Page class, which contains a member called Cache. You use the
Cache property as you would any other IEnumerable, which gives you methods and
properties to get, set, and enumerate through members. We will be looking at
getting and setting items in the cache. In the simplest example, you can
retrieve any object from the cache like so:

Object obj = (Object)Cache["key"];

What this does is look in the Cache for an item with the key "key".
If such an item exists, the object is returned. While we don't need to cast the
returned object to Object, this is just an example of how you must cast the
return to the class type you want returned. If the item is not found, null is
returned, so you will need to do some checking:

Object obj = (Object)Cache["key"];
if (obj == null) {
// Generate a new object and insert it into the cache
}
// Use your object

You can also assign object to the cache like the following code example, but
using Cache.Inset() is a much better means as you'll see later:

Cache["key"] = obj;

Lets We see in details..
Create a Page named Default.aspx and type the coding below..
<%@ 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>
<title>Cache Dependency Tester</title>
<meta content="Microsoft Visual Studio 7.0" name="GENERATOR" />
<meta content="C#" name="CODE_LANGUAGE" />
<meta content="JavaScript" name="vs_defaultClientScript" />
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema" />
</head>
<body ms_positioning="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:DataList id="dlUsers" style="Z-INDEX: 101; LEFT: 44px; POSITION: absolute; TOP: 104px" runat="server" Height="148px" Width="343px" BorderWidth="1px" GridLines="Horizontal" CellPadding="4" BackColor="White" ForeColor="Black" BorderStyle="None" BorderColor="#CCCCCC">
<SelectedItemStyle font-bold="True" forecolor="White" backcolor="#CC3333"></SelectedItemStyle>
<FooterStyle forecolor="Black" backcolor="#CCCC99"></FooterStyle>
<HeaderStyle font-bold="True" forecolor="White" backcolor="#333333"></HeaderStyle>
<ItemTemplate>
<table bgcolor="#CCCCFF" border="Black" cellspacing="20">
<tr>
<td><b>User_ID:</b><%#DataBinder.Eval(Container.DataItem,"UserId")%><br />
<b>First_Name:</b><%#DataBinder.Eval(Container.DataItem,"FirstName")%><br />
<b>Last_Name:</b><%#DataBinder.Eval(Container.DataItem,"LastName")%><br /></td>
<td>
</td>
<td>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
<asp:Label id="lblChange" style="Z-INDEX: 102; LEFT: 46px; POSITION: absolute; TOP: 63px" runat="server" Height="28px" Width="295px"></asp:Label>
</form>
</body>
</html>

In that design page i drag and drop one datalist control and added the necessary template.

Goto Default.aspx.cs and type the following Code.
protected void Page_Load(object sender, EventArgs e)
{
DataSet dsUsers;
try
{
if(Cache["Users"]==null)
{
SqlConnection cn;
dsUsers = new DataSet("new");
cn = new SqlConnection("data source=.;Initial Catalog=restaurent;uid=sa;password=1soft;");
// cn = new SqlConnection(ConfigurationSettings.AppSettings.Get("conn"));
SqlDataAdapter daUsers;
daUsers = new SqlDataAdapter("Select * from tblUsers",cn);
cn.Open();
daUsers.Fill(dsUsers,"tblUsers");
//Update the cache object
Cache.Insert("Users",dsUsers, new System.Web.Caching.CacheDependency(
Server.MapPath("Master.xml")), DateTime.Now.AddSeconds(45),TimeSpan.Zero);
HttpContext.Current.Trace.Write(DateTime.Now.AddSeconds(45).ToString() + "is expiry time..");
cn.Close();
cn.Dispose();
HttpContext.Current.Trace.Write("from Database..");
lblChange.Text ="From the database....";
}
else
{
HttpContext.Current.Trace.Write("From cache..");
lblChange.Text ="From the cache....";
dsUsers= (DataSet) Cache["Users"];
}
dlUsers.DataSource =dsUsers;
dlUsers.DataMember = dsUsers.Tables[0].TableName ;
//lblChange.Text += Server.MapPath("Master.xml");
this.DataBind();
}
catch(Exception ex)
{
lblChange.Text = ex.Message;
}
}
Now run the prgram..and u get the desired output.
Happy Coding....

Friday, July 8, 2011

Form-based Authentication in ASP.NET

It is a common need for a web site to have membership and login system, particularly when part of the web site is restricted in access by non-members. This tutorial will guide you through how to create such a form-based authentication in ASP.NET using C#.

There are totally four things you need to create in order to make a form-based authentication.

1. A database (Access 2000 or SQL server, or any RDBMS with a .NET ODBC driver) with a membership table.

2. A login web control

3. web.config file

4. The actual login page

The membership table

At least you should have a table to store member information. The table can be as simple as having only the MemberID, strUserName and strPassword fields:

-------------

tblMembership

-------------

MemberID

strUserName

strPassword

-------------

You can add any useful fields to this table for your particular need like FirstName, LastName, E-mail address, or even IPAddress for tracking purpose. To keep the problem simple, we will just keep this 3 fields in our discussion.

The login web control

Code for the login web control (login.ascx):
<%@ Control language="C#" %>
<script language="C#" runat="server">
public String BackColor = "#FFFFFF";
public String UserId {
get {
return User.Text;
}
set {
User.Text = value;
}
}

public String Password {
get {
return Pass.Text;
}
set {
Pass.Text = value;
}
}

public String BackGroundColor {
get {
return BackColor;
}
set {
BackColor = value;
}
}

public bool IsValid {
get {
return Page.IsValid;
}
}
</script>
<table style="background-color:<%=BackColor%>
;font: 10pt verdana;border-width:1;
border-style:solid;border-color:black;"
cellspacing=15 ID="Table1">
<tr>
<td><b>Login: </b></td>
<td><ASP:TextBox id="User" runat="server"/></td>
</tr>
<tr>
<td><b>Password: </b></td>
<td><ASP:TextBox id="Pass" TextMode="Password"
runat="server"/></td>
</tr>
<tr>
<td></td>
<td><ASP:Button Text="Submit"
OnServerClick="Submit_Click" runat="server"/></td>
</tr>
<tr>
<td align="center" valign="top" colspan="2">
<asp:RegularExpressionValidator id="Validator1"
ASPClass="RegularExpressionValidator" ControlToValidate="Pass"
ValidationExpression="[0-9a-zA-Z]{5,}"
Display="Dynamic"
Font-Size="8pt"
runat=server>
Password must be >= 5 alphanum chars<br>
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator id="Validator2"
ControlToValidate="User"
Font-Size="8pt"
Display="Dynamic"
runat=server>
UserId cannot be blank<br>
</asp:RequiredFieldValidator>
<asp:RequiredFieldValidator id="Validator3"
ControlToValidate="Pass"
Font-Size="8pt"
Display="Dynamic"
runat=server>
Password cannot be blank<br>
</asp:RequiredFieldValidator>
</td>
</tr>
</table>


There are a table in which are two textboxes and a button. In order for the password textbox to hide password of the user, we add the TextMode="password" attribute to the password textbox. Note that we have used 3 validator to validates the userName and password: Validator1 and Validator3 validates the password field to check for any empty password or password which are too short. Validator2 check for empty userName.

In this control, I use property to encapsulate any detail of the login control. For a detail discussion on property, read my separate tutorial: Property: Encapsulation in C#

Now, lets see the web.config file.

The web.config file
<configuration>
<system.web>
<customErrors mode="Off"/>
<authentication mode="Forms">
<forms name=".ASPXFORUM"
loginUrl="login.aspx" protection="All"
timeout="30" path="/" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>

What you have to keep watch to is the lines with <authentication> and <authorization> tags.

The mode="Forms" attribute to the authentication tag indicates that form-based authentication is used in the case. The other available attributes are window (for Win NT authentication), passport(for Passport authentication) and none. The protection="All" means both encription and validation-based protection were used. The timeout="30" attribute indicates the cookie expiration period. The path attribute denotes the cookie path. The name attribute is the name of the cookie use. Lastly and the most important one is loginUrl which denotes the login page which will be re-directed to whenever authentication is needed.

For the authorization section, there is only one tag here which is <deny users="?" />. The <deny> tag here specifies that we will deny any un-authenticated user for accessing this directory and any sub-directories where this web.config file is placed. The other tag available is the <allow> tag which would be used to specify what users are allow to access in the current folder and deny access to other user instead.

The login.aspx page

Here is the complete code for the login page:
<%@ Page language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Web.Security" %>
<%@ Register TagPrefix="MySite" TagName="Login" Src="login.ascx" %>

<script language="C#" runat="server">
private void Page_Load(Object sender, EventArgs E) {
if ((Page.IsPostBack) && (Page.IsValid)) {
string strDSN =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Membership.mdb";
string strSQL = "SELECT userName, userPassword FROM Membership
WHERE userName='" + MyLogin.UserId + "'";

OleDbConnection myConn = new OleDbConnection(strDSN);
OleDbCommand myCmd = new OleDbCommand(strSQL, myConn);
OleDbDataReader dr = null;
try {
myConn.Open();
dr = myCmd.ExecuteReader();

if(dr.Read()) {
if(dr.GetString(1).Trim() == MyLogin.Password.Trim()) {
FormsAuthentication.RedirectFromLoginPage(MyLogin.UserId, false);
}
else
Message.Text = "Sorry! Your login or password is incorrect.
<br>Please log in again.";
}
else
{
Message.Text = "Sorry! Your login or password is incorrect.
<br>Please log in again.";
}
}
catch(Exception myException) {
Response.Write("Oops. The error: " + myException.Message);
}
finally {
myConn.Close();
}
}
}
</script>
<html>
<body>
<h3>Login</h3>
<form runat="server" ID="Form1">
<asp:Label id="Message" runat="server" />
<MySite:Login id="MyLogin" BackColor="#FFFFCC" runat="server"/>
</form>
</body>
</html>


What you need to observe in this snipplet of code is the namespaces which need to be imported and the use of a web control by using the Register directive. The TagPrefix attribute is the prefix you use to specify this user control instead of the asp: tag prefix to use with web controls. TagName is the tag you use and src points to the source code of the actual user control which we had discussed before.

The database connection codings here is quite trivial, it simply query the table and see whether the user name exists in the table. If yes, the password is checked, otherwise, an error message is delivered.

The worth-noting line is:
FormsAuthentication.RedirectFromLoginPage(MyLogin.UserId, false);


This line will redirect the user to the page where he/she originally requested if he/she is successfully authenticated. The false at the end indicates that persistent cookie is not used in this case. Turn it to true if you need to use persistent cookie.

Friday, March 4, 2011

Send Mail in ASP.NET using Gmail Account

Mail sending concept in ASP.NET:
It’s very easy one to send mail to other mail id using Gmail account. Do to this follow the steps below.
In visual studio 2008,
Step1: File-> New Website -> give name as Default.aspx-> give ok.
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>Send Email using ASP.Net and C# with GMAIL</title>
</head>
<body>
<form id="form1" runat="server">
<div align="center">
<h2> Send email from your GMAIL Account</h2>
<table>
<tr>
<td style="text-align: right">Your Gmail Id : </td><td style="text-align: left"><asp:TextBox ID="txtGmailId" runat="server" Width="200px"></asp:TextBox></td>
</tr>
<tr>
<td style="text-align: right">Your Gmail Password : </td><td style="text-align: left"><asp:TextBox ID="txtPassword" TextMode="Password" runat="server" Width="200px"></asp:TextBox></td>
</tr>
<tr>
<td style="text-align: right">To : </td><td style="text-align: left"><asp:TextBox ID="txtTo" runat="server" Width="200px"></asp:TextBox></td>
</tr>
<tr>
<td style="text-align: right">Subject : </td><td style="text-align: left"><asp:TextBox ID="txtSubject" runat="server" Width="200px"></asp:TextBox></td>
</tr>
<tr>
<td style="text-align: right;vertical-align:top;">Message : </td><td><asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine" Height="100px" Width="300px"></asp:TextBox></td>
</tr>
<tr>
<td></td>
<td style="text-align: left">
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" Width="100px" /></td>
</tr>
</table>
<asp:Label ID="lblError" ForeColor="red" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>

Step2:
In coding page type the following coding.
Default.aspx.cs:
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;

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

}
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
MailSender.SendEmail(txtGmailId.Text + "@gmail.com", txtPassword.Text, txtTo.Text, txtSubject.Text, txtMessage.Text, System.Web.Mail.MailFormat.Text, "");
lblError.Text = "Mail sent successfully.";
}
catch(Exception ex)
{
lblError.Text = ex.Message;
}
}
}
Step3:
Create a new class file by way of selecting,
Website -> Add New Item-> Choose class file named as MailSender.cs

MailSender.cs:
using System.Web.Mail;
using System;
public class MailSender
{
public static bool SendEmail(
string pGmailEmail,
string pGmailPassword,
string pTo,
string pSubject,
string pBody,
System.Web.Mail.MailFormat pFormat,
string pAttachmentPath)
{
try
{
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserver",
"smtp.gmail.com");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
"465");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusing",
"2");
//sendusing: cdoSendUsingPort, value 2, for sending the message using
//the network.

//smtpauthenticate: Specifies the mechanism used when authenticating
//to an SMTP
//service over the network. Possible values are:
//- cdoAnonymous, value 0. Do not authenticate.
//- cdoBasic, value 1. Use basic clear-text authentication.
//When using this option you have to provide the user name and password
//through the sendusername and sendpassword fields.
//- cdoNTLM, value 2. The current process security context is used to
// authenticate with the service.
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1");
//Use 0 for anonymous
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusername",
pGmailEmail);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendpassword",
pGmailPassword);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
"true");
myMail.From = pGmailEmail;
myMail.To = pTo;
myMail.Subject = pSubject;
myMail.BodyFormat = pFormat;
myMail.Body = pBody;
if (pAttachmentPath.Trim() != "")
{
MailAttachment MyAttachment =
new MailAttachment(pAttachmentPath);
myMail.Attachments.Add(MyAttachment);
myMail.Priority = System.Web.Mail.MailPriority.High;
}

System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
System.Web.Mail.SmtpMail.Send(myMail);
return true;
}
catch (Exception ex)
{
throw;
}
}
}

Saturday, November 27, 2010

Working with LINQ TO SQL Example

LINQ to SQL Example:
1) In Microsoft Visualstudio2008, Select FileàNew àProject and select ASP.NET Web Application and give name as LINQQQ.
2) In Default.aspx page design the webpage as given below.
3) Create the database named “linqsamples” and create the table employee with the required field given below.
    
Turn off the Identity Specification to “NO”.
4) After creating the Database next we have to create dbml in our application. To do this , following the steps given below.
     a) choose Project menuà Add New Item and select “LINQ to SQL Classes” and give name as employee.dbml.
     b) In Solution Explorer double click the “employee.dbml” and in that file drag oue employee table and drop it.
    

c) In Default.aspx.cs, type the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LINQQQ
{
    public partial class _Default : System.Web.UI.Page
    {
       
         DAL dal = new DAL();       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindGrid();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            employee emp = new employee();

            emp.ID = int.Parse( txtID.Text);
            emp.name = txtName.Text;
            emp.description = txtDesc.Text;
            dal.SaveEmployee(emp);
            BindGrid();
        }

        private void BindGrid()
        {
            gvEmployees.DataSource = dal.GetAllEmployees();
            gvEmployees.DataBind();
        }

        protected void gvEmployees_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            hdnID.Value = e.CommandArgument.ToString();
            if (e.CommandName == "EditEmployee")
            {
                //employee emp = new employee();
               employee emp = GetEmployee(Convert.ToInt32(hdnID.Value));
                txtName.Text = emp.name;
                txtDesc.Text = emp.description;
                btnSave.Visible = false;
                btnUpdate.Visible = true;
            }
            else if (e.CommandName == "DeleteEmployee")
            {
                dal.DeleteEmployee(Convert.ToInt32(hdnID.Value));
                BindGrid();
            }
        }

      
       private employee GetEmployee(int ID)
        {
           employee emp = dal.GetEmployees(ID);
            return emp;
        }
       

        private void ClearScreen()
        {
            txtName.Text = string.Empty;
            txtDesc.Text = string.Empty;
        }

       protected void btnUpdate_Click(object sender, EventArgs e)
        {
            employee emp = new employee();
            emp.ID = Convert.ToInt32(hdnID.Value);
            emp.name = txtName.Text;
            emp.description = txtDesc.Text;
            dal.UpdateEmployee(emp);
            BindGrid();
        }
    }
   }

d) Now you have to create a new class file named DAL.cs.
   Choose ProjectàAddNewItem and select class file and give name as “DAL.cs”
“DAL.cs” class file is mainly used to create the methods for Inserting, Updating and Deleting records in a nice manner.
    BY way of creating object to the class we have to access the methods in the class.
   Ex:
         DAL dal=new DAL();

Now in DAL.cs Class file type the following code:

DAL.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LINQQQ
{
    public class DAL
    {
        employeeDataContext context = new employeeDataContext();
        public List<employee> GetAllEmployees()
        {
            Open();
            var Res = context.employees.ToList();
            Close();
            return Res;
        }
        private void Open()
        {
            context.Connection.Open();
        }

        private void Close()
        {
            context.Connection.Close();
        }
        public List<employee> GetEmployees(string Search)
        {
            Open();
            var Res = (from emp in context.employees
                       where emp.name.Contains(Search)
                       select emp).ToList();
            Close();
            return Res;
        }
        public void SaveEmployee(employee emp)
        {
            Open();
            this.context.employees.InsertOnSubmit(emp);
            this.context.SubmitChanges();
            Close();
        }
        public void UpdateEmployee(employee emp)
        {
            Open();
            var employee = (from em in this.context.employees
                            where em.ID == emp.ID
                            select em).First();
            employee.name = emp.name;
            employee.description = emp.description;
            this.context.SubmitChanges();
            Close();
        }
        public void DeleteEmployee(int ID)
        {
            Open();
            var emp = (from em in this.context.employees
                       where em.ID == ID
                       select em).First();
            this.context.employees.DeleteOnSubmit(emp);
            this.context.SubmitChanges();
            Close();
        }
        public employee GetEmployees(int ID)
        {
            Open();
            var emp = (from em in this.context.employees
                       where em.ID == ID
                       select em).First();
            Close();
            return emp;

        }
    }
}

   e) Now run the project LINQ works perfect..
       All the Best... J

Introduction to DotNet ...

.NET framework is an essential component of the windows operating system and helps create applications by integrating different programming languages, such as Visual C#, Visual Basic, Visual C++, and so on. .NET Framework consists of a virtual execution syatem called the common language runtime(CLR) and a set of class libraries. CLR is a Microsoft product of the Common Language Infrastructure(CLI), which is an industrial standard and a basis for creating execution and development environmentss in which languages and libraries work together. Microsoft introduced .NET to bridge the gap and ensure interoperability between application created in different languages. .NET framework is used to integrate the business logic of an application implemented in different programming languages and services. Consequently, it induces significant improvements in code reusability, code specialization, resource management, development of applications in multiple programming languages, security, deployment, and administration of programs developed in multiple programming languages..

Why .NET?

Why .NET? Mainly .NET is the competitor for JAVA. . Its an environment or platform. It contains collection of services for application development and application execution. It supports different type of applications development. ex: CUI, GUI, console, web based,mobile applications Main thing is .NET is network & Internet based application development.It provides a good development environment. ex: Drag and Drop design - IntelliSense features - Syntax highlighting and auto-syntax checking - Excellent debugging tools - Integration with version control software such as Visual Source Safe (VSS) - Easy project management

Evaluation of .NET:

Around 1995, Java was gaining popularity because of its platform-independent approach and Sun Microsyatem's open source policy. Later in 2002, Sun Microsystems released the enterprise edition of Java. ie., Java 2 Enterprise edition(J2EE), which is a Java Platform to develop and execute distributed Java Applications based on the N-tier architecture. The advent of J2EE eventually led to the decline of, Microsoft's Market share. Consequently, Microsoft started a project called NEXT GENERATION WINDOWS SERVICE(NGWS) to regain the market share . It tooks more than three years to develop the product, Which is Known as .NET. Microsoft released the first version of .NET with the name .NET Framework 1.0 on february 13,2002, along with the Visual studio .NET 2002 integrated development environment(IDE). .NET's Second revised version took nearly a year to release; and it was known as .NET framework 1.1 Microsoft Visual studio .NET, bettre known as Visual studio .NET2003, was also a part of the second release. The next version of .NET framework, .NET Framework 2.0, was released with Visual studio .NET 2005 on november 07,2005. .NET framework 3.0 formerly called WinFX, was released on novenber 06,2006. Finally the latest version of .NET framework, known as .NET framework 3.5, was released with Visual studio .NET2008 on november 19,2007.

Flavors of .NET:


Contrary to general belief .NET is not a single technology. Rather it is a set of
technologies that work together seamlessly to solve your business problems. The
following sections will give you insight into various flavors and tools of .NET and what kind of applications you can develop.
• What type of applications can I develop?
When you hear the name .NET, it gives a feeling that it is something to do only with internet or networked applications. Even though it is true that .NET provides
solid foundation for developing such applications it is possible to create many other types of applications. Following list will give you an idea about various
types of application that we can develop on .NET.
1. ASP.NET Web applications:
These include dynamic and data driven browser
based applications.
2. Windows Form based applications:
These refer to traditional rich client applications.
3. Console applications:
These refer to traditional DOS kind of applications like
batch scripts.
4. Component Libraries:
This refers to components that typically encapsulate
some business logic.
5. Windows Custom Controls:
As with traditional ActiveX controls, you can develop your own windows controls.
6. Web Custom Controls:
The concept of custom controls can be extended to
web applications allowing code reuse and modularization.
7. Web services:
They are “web callable” functionality available via industry standards like HTTP, XML and SOAP.
8. Windows Services:
They refer to applications that run as services in the
background. They can be configured to start automatically when the system boots up.
As you can clearly see, .NET is not just for creating web application but for almost all kinds of applications that you find under Windows.

Feature Of .NET

Features of .NET

Now that we know some basics of .NET, let us see what makes .NET a wonderful

platform for developing modern applications.

• Rich Functionality out of the box

.NET framework provides a rich set of functionality out of the box. It contains hundreds of classes that provide variety of functionality ready to use in your applications. This means that as a developer you need not go into low level details

of many operations such as file IO, network communication and so on.

Easy development of web applications

ASP.NET is a technology available on .NET platform for developing dynamic and data driven web applications. ASP.NET provides an event driven programming model (similar to Visual Basic 6 that simplify development of web

pages (now called as web forms) with complex user interface. ASP.NET server controls provide advanced user interface elements (like calendar and grids) that save lot of coding from programmer’s side.

• OOPs Support

The advantages of Object Oriented programming are well known. .NET provides a fully object oriented environment. The philosophy of .NET is – “Object is mother of all.” Languages like Visual Basic.NET now support many of the OO

features that were lacking traditionally. Even primitive types like integer and characters can be treated as objects – something not available even in OO languages like C++.

• Multi-Language Support

Generally enterprises have varying skill sets.
For example, a company might have people with skills in Visual Basic, C++, and Java etc. It is an experience that
whenever a new language or environment is invented existing skills are outdated.

This naturally increases cost of training and learning curve. .NET provides something attractive in this area. It supports multiple languages. This means that if you have skills in C++, you need not throw them but just mould them to suit
.NET environment. Currently four languages are available right out of the box namely – Visual Basic.NET, C# (pronounced as C-sharp), Jscript.NET and
Managed C++ (a dialect of Visual C++). There are many vendors that are working on developing language compilers for other languages (20+ language compilers are already available). The beauty of multi language support lies in the
fact that even though the syntax of each language is different, the basic capabilities of each language remain at par with one another.

• Multi-Device Support

Modern lift style is increasingly embracing mobile and wireless devices such as PDAs, mobiles and handheld PCs. . . .NET provides promising platform for programming such devices. .NET Compact Framework and Mobile Internet Toolkit are step ahead in this direction.

• Automatic memory management

While developing applications developers had to develop an eye on system resources like memory. Memory leaks were major reason in failure of applications. .NET takes this worry away from developer by handling memory on its own. The garbage collector takes care of freeing unused objects at appropriate intervals.

• Compatibility with COM and COM+

Before the introduction of .NET, COM was the de-facto standard for componentized software development. Companies have invested lot of money and efforts in developing COM components and controls. The good news is – you can still use COM components and ActiveX controls under .NET. This allows you to use your existing investment in .NET applications. .NET still relies on COM+ for features like transaction management and object pooling. In fact it provides enhanced declarative support for configuring COM+ application right from your source code. Your COM+ knowledge still remains as a valuable asset.

• No more DLL Hell

If you have worked with COM components, you probably are aware of “DLL hell”. DLL conflicts are a common fact in COM world. The main reason behind this was the philosophy of COM – “one version of component across machine”.

Also, COM components require registration in the system registry. .NET ends this DLL hell by allowing applications to use their own copy of dependent DLLs.

Also, .NET components do not require any kind of registration in system registry.

• Strong XML support

Now days it is hard to find a programmer who is unaware of XML. XML has gained such a strong industry support that almost all the vendors have released some kind of upgrades or patches to their existing software to make it “XML compatible”. Currently, .NET is the only platform that has built with XML right into the core framework. .NET tries to harness power of XML in every possible way. In addition to providing support for manipulating and transforming XML
documents, .NET provides XML web services that are based on standards like HTTP, XML and SOAP.

• Ease of deployment and configuration

Deploying windows applications especially that used COM components were always been a tedious task. Since .NET does not require any registration as such,
much of the deployment is simplified. This makes XCOPY deployment viable.

Configuration is another area where .NET – especially ASP.NET – shines over traditional languages. The configuration is done via special files having special
XML vocabulary. Since, most of the configuration is done via configuration files,

there is no need to sit in front of actual machine and configure the application manually. This is more important for web applications; simply FTPing new configuration file makes necessary changes.

• Security

Windows platform was always criticized for poor security mechanisms. Microsoft has taken great efforts to make .NET platform safe and secure for enterprise applications. Features such as type safety, code access security and role based
authentication make overall application more robust and secure.