You are on page 1of 22

ASP.Net ASP.NET (Active Server Page .Network Enabled Technology) ASP.NET and the .NET Framework ASP.

NET is part of the Microsoft .NET Framework. To build ASP.NET pages. The .NET Framework is an environment for building, deploying, and running Web applications and Web Services. Microsoft's previous server side scripting technology ASP (Active Server Pages) is now often called classic ASP. ASP 3.0 was the last version of classic ASP. ASP.NET is an entirely new technology for server-side scripting. It was written from the ground up and is not backward compatible with classic ASP. ASP+ is just an early name used by Microsoft when they developed ASP.NET. You need to take advantage of the features of the .NET Framework. The .NET Framework consists of two parts: the Framework Class Library and the Common Language Runtime. The .NET Framework contains thousands of classes that you can use when building an application. .NET Framework contains almost 13,000 classes. Microsoft divided the classes in the Framework into separate namespaces. A namespace is simply a category. For example, all the classes related to working with the file system are located in the System.IO namespace. All the classes for working a Microsoft SQL Server database are located in the System.Data.SqlClient namespace. After you import a particular namespace, you can use all the classes in that namespace without qualifying the class names. <%@ Import Namespace=System.Net.Mail %> You are using a namespace in multiple pages in your application, then you can configure all the pages. A web configuration file is a special type of file that you can add to your application to configure your application. Be aware that the file is an XML file and, therefore, all the tags contained in the file are case sensitive. Understanding Assemblies An assembly is the actual .dll file on your hard drive where the classes in the .NET Framework are stored. For example, all the classes contained in the ASP.NET Framework are located in an assembly named System.Web.dll. CLR When you write an application for the .NET Framework with a language such as C# or Visual Basic .NET, your source code is never compiled directly into machine code. Instead, the C# or Visual Basic compiler converts your code into a special language named MSIL (Microsoft Intermediate Language). MSIL looks very much like an object-oriented assembly language. However, unlike a typical assembly language, it is not CPU specific. MSIL is a low-level and platform-independent language. When your application actually executes, the MSIL code is just-in-time compiled into machine code by the JITTER (the Just-In-Time compiler). Normally, your entire application is not compiled from MSIL into machine code. Instead, only the methods that are actually called during execution are compiled. .NET Framework includes compilers for these languages that enable you to compile your code into MSIL. MSIL MSIL stands for Microsoft Intermediate Language. We can call it as Intermediate Language (IL) or Common Intermediate Language (CIL). During the compile time , the compiler convert the source code into Microsoft Intermediate Language (MSIL) .Microsoft Intermediate Language (MSIL) is a CPU-independent set of instructions that can be efficiently converted to the native code. During the runtime the Common Language Runtime (CLR)'s Just In Time (JIT) compiler converts the Microsoft Intermediate Language (MSIL) code into native code to the Operating System. When a compiler produces Microsoft Intermediate Language (MSIL), it also produces Metadata. The Microsoft Intermediate Language (MSIL) and Metadata are contained in a portable executable (PE) file . Microsoft Intermediate Language (MSIL) includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations Just In Time Compiler(JIT) The .Net languages , which is conforms to the Common Language Specification (CLS), uses its corresponding runtime to run the application on different Operating Systems . During the code execution time, the Managed Code compiled only when it is needed, that is it converts the appropriate instructions to the native code for execution just before when each function is called. This process is called Just In Time (JIT) compilation, also known as Dynamic Translation . With the help of Just In Time Compiler (JIT) the Common Language Runtime 1

(CLR) doing these tasks.The Common Language Runtime (CLR) provides various Just In Time compilers (JIT) and each works on a different architecture depending on Operating System. That is why the same Microsoft Intermediate Language (MSIL) can be executed on different Operating Systems without rewrite the source code. Just In Time (JIT) compilation preserves memory and save time during application initialization. Just In Time (JIT) compilation is used to run at high speed, after an initial phase of slow interpretation. Just In Time Compiler (JIT) code generally offers far better performance than interpreters. Page Render Block:- The final part of the page is called the page render bloack, which contain everything rendered to the browser. Render block include every thing between <html> tags. When a ASP page is open then it is look like this:<%@ 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> </div> </form> </body> </html> The first line Contain a Directive which always begin with <%@ and end with the character %>. Directives are used to provide the compiler information it need to compile the page. Page Language="C#" For example, the directive in above example indicates that the code contained in the page is C# code. The page is compiled by the C# compiler. AutoEventWireup="true" Means all the events that are automatically rises when page is loading. if AutoeventWireUp=false then we have to manually write events and delegates like this public _Default() // ctor { Load += new EventHandler(Page_Load); PreInit += new EventHandler(Page_PreInit); } CodeFile="Default.aspx.cs" Name of C# file which contain C# code. ASP.NET pages are often called web form pages because they almost always contain a server-side form element. <form id="form1" runat="server"> Task Pane :A Task Pane is a new feature to dock or undock the window. Overview of ASP.NET Controls:<form id="form1" runat="server"> This is an example of an ASP.NET control. Because the tag includes a runat=server attribute, the tag represents an ASP.NET control that executes on the server means it is server-side control. Controls declaration look like the declaration for an HTML tag. Control is a .NET class that execute on the server and not in the web 2

browser. Prefix asp: indicate the namespace for the control. All the standard ASP.NET control are in System.web.UI namespace. Every control must have a unique ID. The ASP.NET Framework contains over 70 controls. These controls can be divided into eight groups: Standard Controls The standard controls enable you to render standard form elements such as buttons, input fields, and labels. Validation Controls The validation controls enable you to validate form data before you submit the data to the server. For example, you can use a RequiredFieldValidator control to check whether a user entered a value for a required input field. Rich Controls The rich controls enable you to render things such as calendars, file upload buttons, rotating banner advertisements, and multi-step wizards. Data Controls The data controls enable you to work with data such as database data. For example, you can use these controls to submit new records to a database table or display a list of database records. These controls are discussed in detail in Navigation Controls The navigation controls enable you to display standard navigation elements such as menus, tree views, and bread crumb trails. Login Controls The login controls enable you to display login, change password, and registration forms. HTML Controls The HTML controls enable you to convert any HTML tag into a server-side control. Standard Controls Label:To Display Text on web page void Button1_Click(object sender, EventArgs e) { Label1.Text += "<h1>Button Click</h1>"; } void Page_Load() { Label1.Text = "Current Time is "+ DateTime.Now; } TextBox:-Used to input data or receive output Properties. Textmode SignleLine , MultileLine , Password Focus:- It is a method used to set the control on a specific text box. txtFirstName.Focus(); Button:Used to design submit, ok button. OnClientClick :-To use a JavaScript Function when click on the Button. PostBackURL:- To use Button as Submit control in html. If data is post to second page then receive data with Request or PreviousPage.FindControl method. 3

Label1.text=Request[TextBox1]; TextBox t1=(TextBox)PreviousPage.FindControl(TextBox1); Label1.text=t1.text; Button Event MyClick to Multiple Button Protected void Button_click(object sender,EventArgs e) { Button btn=(Button)sender; Label1.Text=btn.Text; } Command Argument :All three Button controls support both the Click event and the Command event. The difference between these events is that you can pass a command name and command argument to a Command event handler but not to a Click event handler. If same Label to text then use Command Event which send the Argument with it using Command Argument property Protected void Button_command(object sender, CommandEventArgument e) { Label1.Text=e.CommandArgument.ToString(); }

Control Event Handling:protected void Button_Click(object sender, EventArgs e) { Button btn = (Button)sender; btn.Text = (Int32.Parse(btn.Text) + 1).ToString(); } void Page_Load() { Label1.Text = DateTime.Now.ToString(); }

Image Button:When click event ocure then send left and top cordinates of mouse position. protected void btnElephant_Click(object sender, ImageClickEventArgs e) { Label1.Text = e.X.ToString(); Label2.Text = e.Y.ToString(); } protected void btnTarget_Click(object sender, ImageClickEventArgs e) { if ((e.X > 90 && e.X < 110) && (e.Y > 90 && e.Y < 110)) lblResult.Text = "You hit the target!"; else lblResult.Text = "You missed!"; 4

} To Change run time image when click on the image protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { string str = ImageButton1.ImageUrl; if (str == "1.jpg") ImageButton1.ImageUrl = "2.jpg"; else ImageButton1.ImageUrl = "1.jpg"; } List Box:- To Multiple choice and user can select from given list. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ListBox1.Items.Add("Mango"); ListBox1.Items.Add("Grapes"); ListBox1.Items.Add("Orange"); } } Code to display all value of List control in Label. protected void Button1_Click(object sender, EventArgs e) { Label1.Text = ""; foreach (ListItem str in ListBox1.Items) Label1.Text = Label1.Text + str; } Properties. AutoposBack :- if it is set true then data post back to server when any item is selected. Selection Mode :- Single and Multiple foreach(ListItem list in ListBox1.Items) { if(list.Selected) Label1.Text="<li>"+list+"</li>"; } protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) { if (ListBox1.SelectedValue == "One") Label1.Text = "ONE"; else if (ListBox1.SelectedValue == "Two") Label1.Text = "TWO"; else if (ListBox1.SelectedValue == "Three") Label1.Text = "Three"; } Drop Down List:void Page_Load() {

if (!Page.IsPostBack) // Create collection of items { ArrayList items = new ArrayList(); items.Add("Apples"); 5

items.Add("Oranges"); // Bind to DropDownList DropDownList1.DataSource = items; DropDownList1.DataBind(); } }

Using Button List Control:void Page_Load() { for (int i = 0; i < 100; i++) bltList.Items.Add("Item " + i.ToString()); } protected void Button1_Click(object sender, EventArgs e) { Label1.Text = DropDownList1.SelectedItem.Text; } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { if(DropDownList1.SelectedValue=="Male") Label1.Text = "Male"; else if (DropDownList1.SelectedValue == "FeMale") Label1.Text = "Female"; } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { if (DropDownList2.SelectedValue == "Mango")

Label1.Text = "Your favourite fruit is Mango"; else if (DropDownList2.SelectedValue == "Apple") Label1.Text = "Your favourite fruit is Apple"; else if (DropDownList2.SelectedValue == "Orange") Label1.Text = "Your favourite fruit is Orange"; } Image Control:Used to display image. The Image control supports the following properties. AlternateText:Alternate text for the image DescriptionUrl:Enables you to provide a link to a page that contains a detailed description of the image. ImageAlign:Enables you to align the image. ImageUrl:Enables you to specify the URL to the image. ImageMap Control:ImageMap control enables you to create a client-side image map. An image map displays an image. When you click different areas of the image. HotSpotModeTo specify the behavior of the image map. CircleHotSpot:To define a circular region in an image map. 6

PolygonHotSpot:Enables you to define an irregularly shaped region in an imagemap. RectangleHotSpot:To define a rectangular region in an image map. Properties: AccessKey:Enables you to specify a key that navigates to the ImageMap control. AlternateText: Enables you to provide alternate text for the image DescriptionUrl: Enables you to provide a link to a page which contains a detailed description of the image ImageUrl:To specify the URL to the image. TabIndex:Enables you to specify the tab order of the ImageMap control. Target:Enables you to open a page in a new window. The ImageMap control also supports the following method: Focus:Enables you to set the initial form focus to the ImageMap control. Finally, the ImageMap control supports the following event: Click:Raised when you click a region Panel Control The Panel control enables you to work with a group of ASP.NET controls. For example, you can use a Panel control to hide or show a group of ASP.NET controls. DefaultButton:Enables you to specify the default button in a Panel. The default button is invoked when you press the Enter button. Direction:Enables you to get or set the direction in which controls that display text are rendered. Possible values are NotSet, LeftToRight, and RightToLeft. GroupingText:Enables you to render the Panel control as a fieldset with a particular legend. . HorizontalAlign: Enables you to specify the horizontal alignment of the contents of the Panel. Possible values are Center, Justify, Left, NotSet, and Right. . ScrollBars: Enables you to display scrollbars around the panels contents. Possible values are Auto, Both, Horizontal, None, and Vertical Using the HyperLink Control The HyperLink control enables you to create a link to a page. Unlike the LinkButton control, the HyperLink control does not submit a form to a server. Enabled:Enables you to disable the hyperlink. ImageUrl:Enables you to specify an image for the hyperlink. NavigateUrl:Enables you to specify the URL represented by the hyperlink. Target:Enables you to open a new window. Text:Enables you to label the hyperlink. 7

HiddenField:Used to pass value from one page to another it has no graphical output at runtime. protected void Page_Load(object sender, EventArgs e) { String str = Request["HiddenField1"]; Response.Write(str); } Literal:You can have HTML code in your Label as well as your Literal. A Literal control is much more light weight than a Label.. it's meant to write out text/html directly to the browser. But literal may be use to pass the html tag as without rendering using it mode property value encode. FileUpload:Used to upload a file on server maximum size of 4mb. String path = MapPath("~/" + FileUpload1.FileName); FileUpload1.SaveAs(path); AdRotator:Used to display any advertisiong on web page. For that create a xml file as given below. <Advertisements> <Ad> <ImageUrl>1.jpg</ImageUrl> <NavigateUrl>http://www.asp.net</NavigateUrl> <AlternateText>First Advetising</AlternateText> <Keyword>A</Keyword> <Impressions>Technology</Impressions> <Caption>This is the caption for</Caption> </Ad> </Advertisements> MultiView and View Control :protected void Menu1_MenuItemClick(object sender, MenuEventArgs e) { if (Menu1.SelectedValue == "View1") MultiView1.SetActiveView(View1); MultiView1.SetActiveView(View2);

if (Menu1.SelectedValue == "View2") } Substitution Control:-

it is used to call a function as substitute of calling statement the function must be static and return a string. Eg:- static int x = 45; public static string SHOW(HttpContext ht) { x= x + 10; return ""+x; } Function is called by the Method name property of substitution control Validation Control Note: Both server- and client-side validation are performed unless the browser does not support client-side validation or the EnableClientScript property is set to false.

Note: The validation will not fail if the input control is empty. Use the RequiredFieldValidator control to make the field required. Control ToValidate :-Id of the Control to validate EnableClientScripting:Display:y y y

Boolean value that specifies whether client side Validation is enable or not The display behavior for the validation control. Legal values are:

None (the control is not displayed. Used to show the error message only in the ValidationSummary control) Static (the control displays an error message if validation fails. Space is reserved on the page for the message even if the input passes validation. Dynamic (the control displays an error message if validation fails. Space is not reserved on the page for the message if the input passes validation

ErrorMessage: text to display in the Validation Summary control when validation fail isValid:- Set true if condition is valid otherwise false. if(args.value.Length<3) { CustomValidator1.ErrorMessage="Error"

args.IsValid=false; }

Data Base ADO.NET ADO.NET is the .NET technology for interacting with data sources. You have several Data Providers, which allow communication with different data sources, depending on the protocols they use or what the database is. Regardless, of which Data Provider used, you'll use a similar set of objects to interact with a data source. The SqlConnection object lets you manage a connection to a data source. SqlCommand objects allow you to talk to a data source and send commands to it. To have fast forward-only read access to data, use the SqlDataReader. If you want to work with disconnected data, use a DataSet and implement reading and writing to/from the data source with a SqlDataAdapter. Introduction ADO.NET is an object-oriented set of libraries that allows you to interact with data sources. Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet, or an XML file. ADO.NET provides a relatively common way to interact with data sources, but comes in different sets of libraries for each way you can talk to a data source. These libraries are called Data Providers and are usually named for the protocol or data source type they allow you to interact with. table 1 lists some well known data providers, the API prefix they use, and the type of data source they allow you to interact with.

The SqlConnection Object To interact with a database, you must have a connection to it. The connection helps identify the database server, the database name, user name, password, and other parameters that are required for connecting to the data base. A connection object is used by command objects so they will know which database to execute the command on. The SqlCommand Object The process of interacting with a database means that you must specify the actions you want to occur. This is done with a command object. You use a command object to send SQL statements to the database. A command object uses a connection object to figure out which database to communicate with. You can use a command object alone, to execute a command directly, or assign a reference to a command object to an SqlDataAdapter, which holds a set of commands that work on a group of data as described below. The SqlDataReader Object Many data operations require that you only get a stream of data for reading. The data reader object allows you to obtain the results of a SELECT statement from a command object. For performance reasons, the data returned from a data reader is a fast forward-only stream of data. This means that you can only pull the data from the stream in a sequential manner. This is good for speed, but if you need to manipulate data, then a DataSet is a better object to work with. The DataSet Object DataSet objects are in-memory representations of data. They contain multiple Datatable objects, which contain columns and rows, just like normal database tables. You can even define relations between tables to create parent-child relationships. The DataSet is specifically designed to help manage data in memory and to support disconnected operations on data, when such a scenario make sense. The DataSet is an object that is used by all of the Data Providers, which is why it does not have a Data Provider specific prefix. The SqlDataAdapter Object Sometimes the data you work with is primarily read-only and you rarely need to make changes to the underlying data source. Some situations also call for caching data in memory to minimize the number of database calls for data that does not change. The data adapter makes it easy for you to accomplish these things by helping to manage data in a disconnected mode. The data adapter fills a DataSet object when reading the data and writes in a single batch when persisting changes back to the database. A data adapter contains a reference to the connection object and opens and closes the connection automatically when reading from or writing to the database. Additionally, the data adapter contains command object references for SELECT, INSERT, UPDATE, and DELETE operations on the data. You will have a data adapter defined for each table in a DataSet and it will take care of all communication with the database for you. All you need to do is tell the data adapter when to load from or write to the database. using System.Data.SqlClient; namespace Hemant { public partial class Form1 : Form { SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Krishan\Documents\Visual Studio 2008\Projects\Hemant\Hemant\college.mdf;Integrated Security=True;User Instance=True"); SqlDataReader rdr; SqlCommand cmd; public Form1() { InitializeComponent(); } 10

private void Form1_Load(object sender, EventArgs e) { conn.Open(); cmd = new SqlCommand("Select * from student", conn); rdr = cmd.ExecuteReader(); rdr.Read(); textBox1.Text = "" + rdr["Name"]; textBox2.Text = "" + rdr["roll"]; textBox3.Text = "" + rdr["dob"]; } private void button1_Click(object sender, EventArgs e) { if (rdr.Read() == true) { textBox1.Text = "" + rdr["Name"]; textBox2.Text = "" + rdr["roll"]; textBox3.Text = "" + rdr["dob"]; } } } } The ExecuteReader() in C# SqlCommand Object sends the SQL statements to the Connection Object and populate a SqlDataReader Object based on the SQL statement. The SqlDataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data it contains. The SqlDataReader cannot be created directly from code, they can created only by calling the ExecuteReader method of a C# Command Object. ExecuteNonQuery : ExecuteNonQuery used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected. The ExecuteScalar() in C# OleDbCommand Object uses to retrieve a single value from the Database after the execution of SQL Statements or Stored Procedures.The ExecuteScalar() executes SQL statements or Stored Procedure and returned a scalar value on first column of first row in the returned Result Set. If the Result Set contains more than one columns or rows , it will return only the first column of the first row value and ignore all other values . If the Result Set is empty it will return a NULL reference. Data Base Using MS.ACCESS using System.Data.OleDb; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) {

OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("College.accdb")); OleDbDataReader rdr; conn.Open();

OleDbCommand cmd = new OleDbCommand("Select * from student", conn); rdr = cmd.ExecuteReader(); rdr.Read(); Response.Write("id is " + rdr[0]); 11 Response.Write("<br>Name is " + rdr[1]);

Response.Write("<br>Roll is " + rdr[2]); rdr.Close(); } } conn.Close();

protected void Page_Load(object sender, EventArgs e) { OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath("school.mdb")); OleDbDataReader rdr; conn.Open(); OleDbCommand cmd = new OleDbCommand("Select * from student", conn); rdr = cmd.ExecuteReader(); rdr.Read(); Response.Write("id is " + rdr[0]); Response.Write("<br>Name is " + rdr[1]); Response.Write("<br>Roll is " + rdr[2]); rdr.Close(); conn.Close(); }

Generic handler Code to Print a file:<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; using System.Data; using System.Data.SqlClient; public class Handler : IHttpHandler { const string constr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\photogallary.mdf;Integrated Security=True;User Instance=True"; public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Hello World"); SqlConnection con = new SqlConnection(constr); SqlCommand cmd = new SqlCommand("Select Data from data where id=@id", con); cmd.Parameters.AddWithValue("id", context.Request["id"]); 12

using (con) { con.Open(); byte[] filedata = (byte[])cmd.ExecuteScalar(); context.Response.BinaryWrite(filedata); } } public bool IsReusable { get { return false; } } } <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" onitemcommand="Repeater1_ItemCommand"><ItemTemplate> <tr><td> <%#Eval("Name") %> </td> <td> <asp:HyperLink ID="HyperLink1" NavigateUrl='<%#Eval("id","Handler.ashx?id={0}")%>' runat="server">VIEW</asp:HyperLink> </td> </tr> </ItemTemplate> </asp:Repeater>

DataBase Using Class using System.Data.SqlClient; using System.Collections.Generic; public class Krishan { private static string constr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Krishan\Documents\Visual Studio 2008\WebSite17\App_Data\School.mdf;Integrated Security=True;User Instance=True"; int roll; string name; public int Roll { get { return roll; } set { roll = value; } } public String Name { get { return name; } set {name = value; } } public List<Krishan> getdata() 13

{ SqlConnection conn = new SqlConnection(constr); List<Krishan> l1 = new List<Krishan>(); conn.Open(); SqlCommand cmd = new SqlCommand("select * from student", conn); SqlDataReader rdr; rdr = cmd.ExecuteReader(); while (rdr.Read()) { Krishan s1 = new Krishan(); s1.Roll = int.Parse(""+rdr["Roll"]); s1.Name =""+rdr["Name"]; l1.Add(s1); } return (l1); } } ================== Multiple Table Data================== protected void Page_Load(object sender, EventArgs e) { List<Krishan.Student> m1 = new List<Krishan.Student>(); List<Krishan.Exam> m2 = new List<Krishan.Exam>(); Krishan.getdata(m1, m2); GridView3.DataSource=m1; GridView3.DataBind(); GridView2.DataSource=m2; GridView2.DataBind(); }

Multiple Table Data using System.Collections.Generic; public class Krishan { private static string constr = @"Data Source=.\SQLEXPRESS; AttachDbFilename=\School.mdf;Integrated Instance=True"; public class Student { int roll; string name; public int Roll { get { return roll; } set { roll = value; } } public String Name { get { return name; } set { name = value; } } } public class Exam { int roll; int ph,che; public int Roll { get { return roll; } set { roll = value; } } public int Ph 14

{ get { return ph; } set { ph = value; } } public int Che { get { return che; } set { che = value; } } } public static void getdata(List<Krishan.Student> m1,List<Krishan.Exam> m2) { SqlConnection conn = new SqlConnection(constr); List<Krishan> l1 = new List<Krishan>(); conn.Open(); SqlCommand cmd = new SqlCommand("select * from student;Select * from Exam", conn); SqlDataReader rdr; rdr = cmd.ExecuteReader(); while (rdr.Read()) { Student s1 = new Student(); s1.Roll = int.Parse(""+rdr["Roll"]); s1.Name =""+rdr["Name"]; m1.Add(s1); } rdr.NextResult(); while (rdr.Read()) { Exam s2 = new Exam(); s2.Roll = int.Parse("" + rdr["Roll"]); s2.Ph = int.Parse("" + rdr["Ph"]); s2.Che = int.Parse("" + rdr["Che"]); m2.Add(s2); } }} Upload and Display Image using folder protected void btnAdd_Click(object sender, EventArgs e) { if (upImage.HasFile) { if (CheckFileType(upImage.FileName)) { String filePath = "~/UploadImages/" + upImage.FileName; upImage.SaveAs(MapPath(filePath)); } } } bool CheckFileType(string fileName) { string ext = Path.GetExtension(fileName); switch (ext.ToLower()) { case ".gif": return true; case ".png": return true; case ".jpg": return true; case ".jpeg": return true; default: return false; } 15

} void Page_PreRender() { string upFolder = MapPath("~/UploadImages/"); DirectoryInfo dir = new DirectoryInfo(upFolder); dlstImages.DataSource = dir.GetFiles(); dlstImages.DataBind(); } Use of Datalist for Image :<asp:DataList id="dlstImages" RepeatColumns="3" runat="server"> <ItemTemplate> <asp:Image ID="Image1" ImageUrl='<%# Eval("Name", "~/UploadImages/{0}") %>' style="width:200px" Runat="server" /> <br /> <%# Eval("Name") %> </ItemTemplate> </asp:DataList>

XML DataBase <?xml version="1.0" encoding="utf-8" ?> <college> <studentRow Column1="Ram" Column2="101" Column3="78.29" Column4="7/8/91" /> <studentRow Column1="Geeta" Column2="102" Column3="98.29" Column4="3/8/91" /> <studentRow Column1="Saloni" Column2="106" Column3="88.29" Column4="5/2/91" /> <studentRow Column1="Priyanka" Column2="103" Column3="78.29" Column4="6/8/91" /> </college> Using Culture 16

For culture info ObjectDataSource Type Name Property System.Globalization.CultureInfo Select Method Name GetCultures(CultureTypes),return CultureInfo[] Parameter Source None DefaultValue SpecificCultures DropDown List Box ChouseDatasource ObjectDataSource1 DisplayName Name protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { Culture = DropDownList1.SelectedValue; Label1.Text = DateTime.Now.ToString("F"); }

Session Session provides that facility to store information on server memory. It can support any type of object to store along with our custom object. For every client Session data store separately, means session data is stored as per client basis. Advantages :
y y y y

It helps to maintain user states and data to all over the application. It can easily be implemented and we can store any kind of object. Stores every client data separately. Session is secure and transparent from user.

Disadvantages :
y y

Performance overhead in case of large volume of user, because of session data stored in server memory. Overhead involved in serializing and De-Serializing session Data. because In case of StateServer and SQLServer session mode we need to serialize the object before store.

Storing and Retrieving values from Session Session["EmployeeID"] = "11"; Session["EmployeeName"] = "Jenny Jones"; Session["City"] = "Rome"; Label1.Text = "Session read...<br />"; 17

Label1.Text += "Employee ID :" + Session["EmployeeID"]; Label1.Text += "<br />Employee Name :" + Session["EmployeeName"]; Session.Remove("EmployeeName"); Label1.Text += "<br /><br />Now remove the item [EmployeeName]"; Label1.Text += "<br />Employee ID :" + Session["EmployeeID"]; Label1.Text += "<br />Employee Name :" + Session["EmployeeName"]; Cookies A Cookie is a small text file that the browser creates and stores on the hard drive of your machine. Cookie is just one or more pieces of information stored as text strings. A Web server sends you a cookie and the browser stores it. The browser then returns the cookie to the server the next time the page is referenced. The most common use of a cookie is to store information about the user and preferences the user makes. Most browsers support cookies of up to 4096 bytes. Because of this small limit, cookies are best used to store small amounts of data, or better yet, an identifier such as a user ID. The user ID can then be used to identify the user and read user information from a database or other data store Users can clear the cookies on their computer at any time. Even if you store cookies with long expiration times, a user might decide to delete all cookies Response.Cookies["userName"].Value = "patrick"; Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1); Cookies with More Than One Value Response.Cookies["userInfo"]["userName"] = "patrick"; Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString(); Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1); HttpCookie aCookie = new HttpCookie("userInfo"); aCookie.Values["userName"] = "patrick"; aCookie.Values["lastVisit"] = DateTime.Now.ToString(); aCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(aCookie); Limiting Cookie Domain Scope Response.Cookies["domain"].Value = DateTime.Now.ToString(); Response.Cookies["domain"].Expires = DateTime.Now.AddDays(1); Response.Cookies["domain"].Domain = "support.contoso.com"; Reading Cookies if(Request.Cookies["userName"] != null) Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value); if(Request.Cookies["userName"] != null) { HttpCookie aCookie = Request.Cookies["userName"]; Label1.Text = Server.HtmlEncode(aCookie.Value); } 18

E-mail Code :private void btnSend_Click(object sender, System.EventArgs e) { MailMessage msg = new MailMessage(); msg.To = txtTo.Text; msg.From = txtFrom.Text; msg.Subject = txtSubject.Text; msg.Body = txtContent.Value; lblStatus.Text = "Sending..."; SmtpMail.Send(msg); lblStatus.Text = "Sent email (" + txtSubject.Text + ") to " +txtTo.Text; } To upload a website Configure the web config file:Set compilation debug false<compilation debug="false">

Remove all assemblies - <assemblies> ----------- </assemblies> Set authentication mode forms <authentication mode="Forms"/> Set CustomErrors mode off writting customerror tag usrself <customErrors mode="Off"></customErrors> Web services:Web services are components on a Web server that a client application can call by making HTTP requests across the Web. ASP.NET enables you to create custom Web services or to use built-in application services, and to call these services from any client application. Web Services can convert your application into a Web-application, which can publish its function or message to the rest of the world. Web Services are essentially methods that you can call over the internet and that can optionally return data to the calling code. This makes then ideal for exchanging data between different systems. Because Web Services are based on the solid and well-understood standards, they make it easy to exchange data between different types of platforms. For example a web services can exchange data between ASP.NET and web site running on Microsoft windows and PHP based site running on Linux. Web services platform elements:
y y y

SOAP (Simple Object Access Protocol) UDDI (Universal Description, Discovery and Integration) WSDL (Web Services Description Language)

Creating Web Service in Web Service file public class Student : System.Web.Services.WebService { public Student() { } [WebMethod] public string Speak() { return "Student speak during study "; } 19

<%@ WebService Language="C#" CodeBehind="~/App_Code/Service.cs" Class="Student" %> protected void Button1_Click(object sender, EventArgs e) { College.Student s1 = new College.Student(); string str = s1.Speak(); Label1.Text = str; } When control in gride view Template lid = ((Label)DataList1.Items[i].FindControl("lbl_Id")).Text; ((DropDownList)DataList1.Items[0].FindControl("DropDownList1")).SelectedItem.ToString()

using using using using using using using using using using using using

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

public partial class _Default : System.Web.UI.Page { SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"); SqlCommand cmd; SqlDataReader rdr; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { conn.Open(); cmd = new SqlCommand("Select distinct(type) from Table1", conn); rdr = cmd.ExecuteReader(); while (rdr.Read()) { DropDownList1.Items.Add("" + rdr[0]); } rdr.Close(); conn.Close(); 20

} } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { string t = DropDownList1.SelectedValue; conn.Open(); cmd = new SqlCommand("Select * from Table1 where type='"+t+"'", conn); //Label1.Text = cmd.ToString(); rdr = cmd.ExecuteReader(); while (rdr.Read()) { Response.Write("<br>" + rdr[0]); Response.Write(" " + rdr[1]); Response.Write(" " + rdr[2]); } conn.Close(); } }

Sending Grid View Data to any other programe protected void Button1_Click(object sender, EventArgs e) { Response.Clear(); // Response.AddHeader("Contentdisposition","attachment;filename=report.doc"); Response.AddHeader("Content-disposition", "attachment;filename=report.xls"); StringWriter str = new StringWriter(); HtmlTextWriter ht = new HtmlTextWriter(str); GridView1.RenderControl(ht); Response.Write(str.ToString()); Response.End(); } Using authentication <authentication mode="Windows"/> When using Login Control <authentication mode="Forms"></authentication> To restrict anonymous user us Authorization tag <authentication mode="Windows"/> <authorization> <deny users="?"></deny> </authorization> To allow user for folder or file </connectionStrings> <location path="default2.aspx"> <system.web> <authorization> 21

<allow users="?"></allow> </authorization> </system.web> </location> <system.web> Using Custom control <%@ Register Src="~/WebUserControl.ascx" TagName="fil" TagPrefix="kri" %>

public partial class WebUserControl : System.Web.UI.UserControl { string _filepath="~/"; public string Filepath { get { return _filepath; } set { _filepath = value; } } protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { String path=MapPath(_filepath)+FileUpload1.FileName; FileUpload1.SaveAs(path); } }
Using Skin file :Create a skin file and modify any control do not use id tag with control

<asp:Button runat="server" Text="Button" BorderColor="Blue" BorderStyle="Inset" ForeColor="#FF3300" ToolTip="Click" /> <asp:TextBox runat="server" BackColor="White" BorderColor="Blue" BorderStyle="Inset" ForeColor="#FF3300"></asp:TextBox> Use theme tag where use the skin file
<%@ Page Language="C#" Theme="SkinFile" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

Changing Master Dynamical:protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); if(Session["MasterColor"]!=null) MasterPageFile = Session["MasterColor"].ToString() + ".master"; } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { Session["MasterColor"] = DropDownList1.SelectedValue; Response.Redirect("Default2.aspx"); }

22

You might also like