86
ASP.NET Around 1996 and 1997, a new platform called Active Server Pages (ASP) was introduced to the world. ASP allowed users to execute code written in a scripting language VB Script or Jscript on the server, which could access databases and programmatically created web pages that could be delivered to the web browser. ASP Versions : Version Operating System Year 1.0 Windows NT Service Pack 3 1996 2.0 Windows NT Service Pack 4 1997 With IIS 4.0 Personal Web Server for NT 4.0 Workstation and Win9x 3.0 IIS 5.0 in Windows 2000 ASP.Net .NET Framework Software Development kit 2 ASP is not a language; it’s a platform that can host scripting languages like VBScript and Jscript. This platform runs on a web server typically IIS or PWS, but ASP is also available from third-party vendors for use on other web servers. ASP : To create dynamic web pages. To create web pages on the fly. The HTML form data is sent to ASP page, wherein we can use that data to do whatever you need. Problems with Older Versions of ASP 1) The server code is mixed in with the HTML and client-side code. It’s hard to believe that this has become an acceptable method of programming large-scale enterprise applications. 2) Due to the HTML behavior, many of the ASP development environments required the creation of tables, and nested tables, in order to obtain the desired position of controls such as text boxes and buttons. 1

asP.NET NOTES using c#

  • Upload
    reena-b

  • View
    587

  • Download
    7

Embed Size (px)

Citation preview

Page 1: asP.NET NOTES using c#

ASP.NET

Around 1996 and 1997, a new platform called Active Server Pages (ASP) was introduced to the world. ASP allowed users to execute code written in a scripting language VB Script or Jscript on the server, which could access databases and programmatically created web pages that could be delivered to the web browser.

ASP Versions :

Version Operating System Year

1.0 Windows NT Service Pack 3 19962.0 Windows NT Service Pack 4 1997

With IIS 4.0

Personal Web Server for NT 4.0Workstation and Win9x

3.0 IIS 5.0 in Windows 2000

ASP.Net .NET Framework Software Development kit 2

ASP is not a language; it’s a platform that can host scripting languages like VBScript and Jscript. This platform runs on a web server typically IIS or PWS, but ASP is also available from third-party vendors for use on other web servers.

ASP : To create dynamic web pages. To create web pages on the fly. The HTML form data is sent to ASP page, wherein we can use that data to do whatever you need.

Problems with Older Versions of ASP

1) The server code is mixed in with the HTML and client-side code. It’s hard to believe that this has become an acceptable method of programming large-scale enterprise applications.

2) Due to the HTML behavior, many of the ASP development environments required the creation of tables, and nested tables, in order to obtain the desired position of controls such as text boxes and buttons.

3) Another problem with traditional ASP programming is that the code is interpreted rather than compiled, resulting in slower performance.

4) ASP exposed an object called the session object. This object was very easy to use, but programmers often ran into problems when an additional web server was added, thereby creating a web farm. The problem is that session state is not shareable within a web farm environment.

5) ASP also uses late binding when making calls to compiled COM components, resulting in slower performance.

Benefits of ASP.NET

1

Page 2: asP.NET NOTES using c#

It represents an exciting new platform for creating web sites with the .net framework, using any .net language. The benefits are,

1) Structure : ASP.NET brings structure back into programming by offering a code-behind page, which separates the client-side script and HTML from the server-side code.

2) Layout control : Using web forms in ASP.NET and positioning controls such as textboxes and buttons is easy, and VS.NET will create the appropriate HTML code for the target browser that is selected. For instance, to be compatible with most browsers, VS.NET will create tables, and nested tables to obtain the desired positioning of the controls. If the application only needs to be compatible with the latest version of Internet Explorer, then VS.NET will position the controls using DHTML.

3) Compiled Code : ASP.NET solves the problem of running interpreted script by compiling the server-side code into IL (Intermediate Language). IL code is significantly faster than interpreted script.

4) Early binding : ASP.NET also uses early binding when making calls to COM components, resulting in faster performance.

5) Security : ASP.NET has an enhanced security infrastructure that can be quickly configured and programmed to authenticate and authorize Web site users.

6) Performance : ASP.NET contains performance enhancements, such as page and data caching.

7) Diagnostics : ASP.NET offers an enhanced tracing and debugging option, which will save time when you are ready to get the system running.

8) Session State : ASP.NET has an improved session object. Session state can be configured to be shared among all servers in a web farm.

9) .NET Framework : Since ASP.NET uses the .NET framework, ASP.NET also inherits the features of the .NET Framework, such as:

Automatic memory cleanup via garbage collection Cross language inheritance A large object-oriented base class library The use of ADO.NET to access database

10) Web Services : ASP.NET also provides the web service infrastructure. It is possible to create a web service with very few lines of code.

Web Forms

It is an exciting part of the ASP.NET platform. It gives the developer the ability to drag and drop the ASP.NET server controls onto the form and easily program the events that are raised by the control. Web Forms have the following benefits:

2

Page 3: asP.NET NOTES using c#

Rendering: Web forms are automatically rendered in any browser. In addition, Web Forms can be tweaked to work on a specific browser to take advantage of its features.

Programming: Web Forms can be programmed using any .NET language, and Win32 API calls can be made directly from ASP.NET code.

.NET Framework: Web Forms are part of the .NET framework; therefore web forms provide the benefits of the .NET framework, such as performance, inheritance, type safety, structured error handling, automatic garbage collection, and xcopy deployment.

Extensibility: User controls, mobile controls, and other third-party controls can be added to extend Web Forms.

WYSIWYG: VS.NET provides the WYSIWYG editor for creating web forms by dragging and dropping controls onto the web forms.

Code Separation: Web Forms provide a code-behind page to allow the separation of HTML content from program code.

State Management: Provides the ability to maintain the view state of controls across web calls.

c:\inetpub\wwwrootTwo ASP.NET Programming Models

1) Single file for each page. – In this type the server code and the client-side tags and code are placed in the same file with an .aspx file extension.

2) Two file for each page – This model offers the ability to use an .aspx page for the client-side presentation logic and a C# code-behind file with a .aspx.cs file extension for the server-side code.

Server Controls

A Server control is a control that is programmable by writing server-side code. They automatically maintain their state between calls to the server. Server controls can be easily identified by their runat =”server” attribute. A Server control must have an ID attribute to be referenced in code. ASP.NET provides two types of server controls; HTML and Web.

HTML Controls

These are traditional HTML controls, except they have a runat=”server” attribute. This type of control is used when migrating older ASP pages to ASP.NET.

Common Properties :

Forecolor : To set foreground color.BackColor : To set background color. Text : To type or to get text.

3

Page 4: asP.NET NOTES using c#

Textbox

Textmode : single line/multiline/passwordAutopostback : true/false : If True, it Submits Form.(Refreshes the Page)Readonly : True/False. By default false. If you make True we can’t type data at runtime.Maxlength : To set maximum no. of characters to be entered.

Button

PostBackURL:Specify FileName to go. It submits the form data and sends to control specified file.

UseSubmitBehaviour: True/ False :- If True, it works like a Submit Button. OnClientClick: Specify JavaScript Function name which can be called.

Link Button

It works just like submit button. However looks like hyperlink.

Text : Type your text here.PostBackURL:Specify Filename to go OnClientClick: Specify JavaScript Function name which can be called.

Image Button

It looks like image however works like submit button.

ImageURL : Specify image filename.PostBackURL:Specify FileName to go OnClientClick: Specify JavaScript Function name which can be called.

HyperLinkTo create hyperlinks.

ImageUrl : Specify image filename.NavigateUrl : Specify the .aspx or .htm filename.Text : Specify text to be displayed as hyper text.

CheckBox Text:

TextAlign:- Left/ RightAutoPostBack:- true/false : If True, it Submits Form.(Refreshes the Page)Checked : true/false.

In the checkbox event :if (CheckBox1.Checked==true){Response.Write(CheckBox1.Text);string a= CheckBox1.Text;}

RadioButton

4

Page 5: asP.NET NOTES using c#

Text: TextAlign:- Left/Right GroupName:- specify common name (variable) for all the radiobuttons. AutoPostBack:- true/false : If True, it Submits Form.(Refreshes the Page)

In the radiobutton event :

Response.Write(RadioButton1.Text);string a= RadioButton1.Text;

DropDownList

AutoPostBack : True/False. If it is set to True the form will be submitted as soon as you select any item from it, also its event SelectedIndexChanged shall be fired. If it is set to False, its selected value will be displayed upon submitting form.

SelectedItem : To read selected value from dropdownlist.

SelectedValue : To read selected value from dropdownlist. To be used when you connect with database.

SelectedIndex : It returns selected items index.

Items: To add items.

DataSourceId : Specify datasource Name.

DataTextField : Specify Column Name.

DataValueField : Specify Column Name.

DropDownList1.Items.Add(“Nagpur”) : To add items at runtime.

DropDownList1.Items.Remove(“Nagpur”) : To remove item.

DropDownList1.Items.Clear() : To remove all items.

DropDownList1.Items.Count() : To find out total no. of items.

DropDownList1.Items.Insert(2, "bbc") : To insert item.

DropDownList1.Items.RemoveAt(0) : To remove item.

DropDownList1.Items.AddRange(arrayname) : To add items from array.

Response.Write(DropDownList1.SelectedIndex.ToString()); Response.Write(DropDownList1.SelectedItem);

ListBox

5

Page 6: asP.NET NOTES using c#

AutoPostBack : True/False. If it is set to True the form will be submitted as soon as you select any item from it, also its event SelectedIndexChanged shall be fired. If it is set to False, its selected value will be displayed upon submitting form.

SelectedItem : To read selected value from listbox.

SelectedValue : To read selected value from listbox. To be used when you connect with database.

SelectedIndex : It returns selected items index.

Selection : Single/Multiple. Select any one. By default Single.

Items: To add items.

DataSourceId : Specify datasource Name.

DataTextField : Specify Column Name.

DataValueField : Specify Column Name.

Response.Write(ListBox1.SelectedIndex);Response.Write(ListBox1.SelectedItem);

// for multiple Items :int a;string b=””;for(a=0;a<ListBox1.Items.Count;a++){ if (ListBox1.Items[a].Selected)

{ // Response.Write(ListBox1.Items[a].Text + "<br>");

b=b+ ListBox1.Items[a].Text+” “; }}Response.Write(“b=”+b);

CheckBoxList/RadioButtonList

AutoPostBack : True/False. If it is set to True the form will be submitted as soon as you select any item from it, also its event CheckedChanged shall be fired. If it is set to False, its selected value will be displayed upon submitting form.

Items : To add text for multiple checkboxes/radiobutton.

RepeatDirection : Horizontal/Vertical.

RepeatColumns : type No.

RepeatLayout : table/flow.

6

Page 7: asP.NET NOTES using c#

DataSource : Specify datasource Name.

DataTextField : Specify Column Name.

DataValueField : Specify Column Name.

string b=””;protected void button1_Click(object sender, System.EventArgs e) { int a; for (a=0;a<CheckBoxList1.Items.Count;a++)

{ if (CheckBoxList1.Items[a].Selected)

{ // Response.Write(CheckBoxList1.Items[a].Text + "<br>");

b=b+ CheckBoxList1.Items[a].Text+” “;}

}Response.Write(“b=”+b);

}

To print radiobuttonlist contents :string c;

Response.Write(RadioButtonList1.Text);c=RadioButtonList1.Text;

Image

ImageUrl : Specify image filename..Height : type no.Width : type no.

Changing/displaying image at runtime :

Image1.ImageUrl = "cyan-ball.gif";

Table

Rows: To add rows (Click on Add Button -> Click on Cells ->Add->type coloumn data in text property (Repeat) ->OK

For second row: (Click on Add Button -> Click on Cells ->Add type coloumn data in text property (Repeat)…….Ok.

We can create table also from Table Menu->Insert Table and give all the settings(row, col….)->O.K.

7

Page 8: asP.NET NOTES using c#

We can also insert a ready-made table in the form which looks like a frame(No Border).A hyperlink can be included. It’s target and NavigateURL properties can be given so that the file opens in a iframe in the table.

Bulletedlist

To create bulleted/numbered list.

Items : to add text which will appear as bullet/number text.BulletStyle : select anyone.

BulletImageUrl : Specify image file name. works with (custom image).FirstbulletNumber : specify no.Displaymode : text/Hyperlink(type filename in items property for bullet text)/Linkbutton(same page will be refreshed).Target : specify framename or _blank.

ImageMap

It displays a image, and divides the image into various areas so that we can use that area as a hyperlink.

ImageURL:- Specufy the image file name.

HotSpots:- To specify the area /portion of the image to be treated as hyperlink. They are Circle, Rectangle, Polygon Hotspots.For Circle Hotspot, specify the X,Y coordinates and the radius. For the rectangular hotspots, specify the top,left,bottom,right coordinates. For the Polygon hotspots, type the X,Y axis Coordinates separated by comma, in even no in Coordinates Property.

NavigateUrl : Specify the .aspx or .htm filename.

PostBackURL : Specify the .aspx or .htm filename.

HiddenField

To send data from one page to another page w/o showing it. The data will go to subsequent page when postback event occurs. Using Request.Form[] we can read.

Value : Type data.Literal

To type plain or text with html tags.

Text : Type text with html tags. e.g. <b>concourse</b>

FileUpLoad

It is used to specify filename to be uploaded, or to attach.

8

Page 9: asP.NET NOTES using c#

It will display a textbox, button (Browse). Upon clicking on the button open file dialog box will appear, from there you can select any file, that file name will appear in the textbox.

FileName : Returns the filename.

FileContent : Returns type of the file.

FileBytes.Length : Returns size of the file.

protected void Button1_Click(object sender, EventArgs e) { string a, b; int p; a = FileUpload1.PostedFile.FileName;

p= a.LastIndexOf("\\"); if (p > 0 ) {

b = a.Substring(p + 1); } else

{b=a;

} FileUpload1.PostedFile.SaveAs(Server.MapPath(b)); FileUpload1.PostedFile.SaveAs("d:\\neha\\" + b); }

Panel

To group components. After grouping we can hide/show all the components. Also to specify backgroundcolor or backgroundimage to a particular portion of area.

GroupingText : Type any text.Direction : L to R/R to LScrollBars : Select any one.

In page_load event :

TextBox t2 = new TextBox(); t2.Text = "era"; Panel1.Controls.Add(t2);

PlaceHolder

It is used as a container to store web server controls on the web page that were added at run-time.

In page_load event :

TextBox t1 = new TextBox();t1.Text = "sekhar";

9

Page 10: asP.NET NOTES using c#

t1.Style["position"] = "absolute"; t1.Style["top"] = “300px”; t1.Style["left"] = “200px”; PlaceHolder1.Controls.Add(t1);

We can’t add any control at runtime without using Panel or Placeholder.

AdRotator

Advertisement Rotator. It displays various images one by one just like how advertisement appears in a TV. Upon clicking on the image the particular specified web site is opened.

Procedure :

1) Create an .xml file (called avertisements file). Click on WebSite->Add New Item->XML File->Type filename->Add. (ads.xml)

2) Take Adrotator control->Set Width, Height.3) Specify the .xml file in AdvertisementFile property.

Creating Advertisement file.

<Advertisements> <Ad> <ImageUrl>Follow.jpg</ImageUrl> <NavigateUrl>http://www.rediff.com</NavigateUrl> <AlternateText>Rediff</AlternateText> <Impressions>100</Impressions> </Ad> <Ad> <ImageUrl>autumn.jpg</ImageUrl> <NavigateUrl>http://www.Google.com</NavigateUrl> <AlternateText>Google</AlternateText> <Impressions>50</Impressions> </Ad> <Ad> <ImageUrl>Ascent.jpg</ImageUrl> <NavigateUrl>http://www.yahoo.com</NavigateUrl> <AlternateText>yahoo</AlternateText> <Impressions>10</Impressions> </Ad></Advertisements>

Calendar controlTo display calendar.

SelectedDate : Returns date selected.SelectedDates : Returns all the selected dates.SelectionMode : Select any one.

Single Date :

10

Page 11: asP.NET NOTES using c#

string a;protected void Calendar1_SelectionChanged(object sender, EventArgs e){

Response.Write(Calendar1.SelectedDate.ToString()); a= Calendar1.SelectedDate.ToString();}

Multiple Dates :

Select Day, Week or Day, Week, Month from SelectionMode property.

protected void Button1_Click(object sender, EventArgs e){ foreach(DateTime dt in Calendar1.SelectedDates) { Response.Write(dt.ToShortDateString()); }}

Restricting a Date :

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e) { if (e.Day.Date.Day == 15 && e.Day.Date.Month == 8) { Label l = new Label(); l.Text = "<br>Independence Day"; e.Cell.Controls.Add(l); e.Day.IsSelectable = false; } }

Validation Controls

All are basically label controls, if error occurs they will appear.

RequiredFieldValidator : It checks for the given value if it is equal it will display error message.

ControlToValidate : Select the textbox for whom you like to do validation.

ErrorMessage : Specify error message to be displayed.

InitialValue : Specify text to be compared with the textbox data. If you leave it blank then it checks textbox data for blank or not. If blank error will be displayed. If you type any data in this, it will compare textbox data with this data if both are same then it gives error otherwise no error.

CompareValidator : It compares data of textbox with the specified value at design time.

ControlToValidate : Select the textbox for whom you like to do validation.

11

Page 12: asP.NET NOTES using c#

ErrorMessage : Specify error message to be displayed.

Type : Select data type.

Operator : Select operator.

ValueToCompare : Type the data to be compared along with textbox data.

Comparing One TextBox data with another textbox :

ControlToValidate : Select the textbox for whom you like to do validation.

ErrorMessage : Specify error message to be displayed.

Type : Select data type.

Operator : Select operator.

ControlToCompare : Select the textbox with whom you like to compare.

RegularExpressionValidator : For comparing e-mail address, url, phone number, postal code, social security code etc.

ControlToValidate : Select the textbox for whom you like to do validation.

ErrorMessage : Specify error message to be displayed.

ValidationExpression : Select the type of validation you want.

\d{5} for comparing 5 digits, \w{5} for comparing 5 digits or 5 alphabets.

RangeValidator : It checks whether the entered data is in between two given datas.

ControlValidate : Select the textbox for whom you like to do validation.

ErrorMessage : Specify error message to be displayed.

Type : Select data type.

MaximumValue : Type maximum value.

MinimumValue : Type minimum value.

CustomValidator : To do our own validation.

ControlToValidate : Select the textbox for whom you like to do validation.

ErrorMessage : Specify error message to be displayed.

12

Page 13: asP.NET NOTES using c#

ClientValidationFunction : Specify function name to be called. Type the function under source view in VB Script.

<script language=”VBScript”>function test(source,args) if (args.value=10) then args.IsValid=trueelseargs.IsValid=falseend if end function</script>

Also we can write the code in the CustomValidator_ServerValidate event. At that time don’t set ClientValidationFunction property. For this double click on the CustomValidator control.

Even though error occurs page will be submitted but other validation control does not Submit page if error occurs.

Sample custom validation for checking whether textbox contains no. 10 or not :

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args){ if (args.Value == "10") { args.IsValid = true; } else { args.IsValid = false; }}

Sample custom validation for checking only alphabets entered or not :

string check;protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args){ string a = args.Value; int l = a.Length,j,b,f=0; char c; for (j = 0; j < l; j++) { c = Convert.ToChar(a.Substring(j, 1)); b = (int)c; if ((b > 64 && b < 91) || (b > 96 && b < 123)) { f = 1; }

13

Page 14: asP.NET NOTES using c#

else { f = 0; break; } }

if (f == 1) { args.IsValid = true; } else { args.IsValid = false; } }

ValidationSummary : It displays all the errors occurred either in bulleted list, ordinary list or in paragraph style.

DisplayMode : Bulleted/List/Paragraph.

ShowMessageBox : True/False. If it is true summary will come using message box.

ShowSummary : True/False. If it is true summary will appear in bulletted list/ordinary list/paragraph mode, if false summary will not appear.

Menu

To create menus. Click on Edit Menu Items->Add Root(set its properties Text, Popoutimageurl, Separator image url) or click on Child->Set Navigate URL, ImageURL, , Text, Tooltip, Target (_new/_blank to open in new browser)->Ok.

Orientation : Horizontal/Vertical.

Also we can specify SiteMap as Data Source for Menu. For this create a web.sitemap enter all the url’s which you like to use as hyperlinks, create SiteMapDataSource using web.sitemap then specify SiteMapDataSource as DataSource for the menu.

Treeview

To display text in tree fashion.

Click on Edit Nodes or Nodes (from properties window)->Click on Add root node->Click on add child node->Type node text in text property, select image file name for ImageUrl property, select filename for navigation in NavigateUrl property, Select true/false from ShowCheckbox property, Select true/false from Checked property, Type _blank in Target property for opening the file in new window, Select true/false from Expanded property (for root item).

14

Page 15: asP.NET NOTES using c#

Also we can specify SiteMap as Data Source for treeview. For this create a web.sitemap enter all the url’s which you like to use as hyperlinks, create SiteMapDataSource using web.sitemap then specify SiteMapDataSource as DataSource for the treeview.

Adding nodes at runtime :

TreeNode t1=new TreeNode(); t1.Text = "Shivram";

t1.NavigateUrl = "default2.aspx"; t1.Target = "_blank";

TreeNode t2=new TreeNode(); t2.Text = "Prabhakar";

t2.NavigateUrl = "default3.aspx"; t2.Target = "_new";

TreeNode t3=new TreeNode(); t3.Text = "Vasant";

t3.NavigateUrl = "default4.aspx"; t3.Target = "_new";

TreeNode t11=new TreeNode(); t11.Text = "Swati"; t11.NavigateUrl = "default5.aspx"; t11.Target = "_new";

TreeNode t12=new TreeNode(); t12.Text = "Ravi";

TreeNode t13=new TreeNode(); t13.Text = "Vasant1";

// adding root node

TreeView1.Nodes.Add(t1); // adding child nodes (Prabhakar, Vasant in Shivram)

TreeView1.Nodes[0].ChildNodes.Add(t2); TreeView1.Nodes[0].ChildNodes.Add(t3);

// adding swati in prabhakar TreeView1.Nodes[0].ChildNodes[0].ChildNodes.Add(t11);

// adding ravin in vasant TreeView1.Nodes[0].ChildNodes[1].ChildNodes.Add(t12);

15

Page 16: asP.NET NOTES using c#

// adding vasant1 in swati

TreeView1.Nodes[0].ChildNodes[0].ChildNodes[0].ChildNodes.Add(t13); If (! Page.IsPostBack){

}SitemapPath

It displays navigation structure of website. To use this control first of all we have to create sitemap. Site map is a file which contains url’s, titles of the pages available in your web site. Using this url’s, titile’s sitemap path displays navigation structure of the web page. For this it displays the title on navigation bar containing current page title and previous pages titles.

Creating Site Map file :

1) Click on website -> add new item -> select site map -> click on add.2) Type URL name, in URL property, page title in title property in the file

created(Websitemap in step1).3) Double click on site map datasource to create sitemapdatasource.4) Double click on sitemappath control, it immediately displays the navigation

structure on the page.

Sample Navigation structures :

Style 1 :

Home Page > 2nd pageHome Page > 3rd pageHome Page > 4th page

For the above structure we have to create sitemap file like below :

<?xml version="1.0" encoding="utf-8" ?><siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > <siteMapNode url="default.aspx" title="Home Page" description="123"> <siteMapNode url="default2.aspx" title="2nd page" description="456" /> <siteMapNode url="default3.aspx" title="3rd page" description="789" /> <siteMapNode url="default4.aspx" title="4th page" description="789" /> </siteMapNode></siteMap>

Style 2 :

main > first > aaaamain > first > bbbbmain > second > aaamain > second > bbb

16

Page 17: asP.NET NOTES using c#

Here main is the home page title, first and second are sub pages of main, aaaa, bbbb are sub-sub pages of first, aaa, bbb are sub-sub pages of second.

If I am in bbb, sitemap path will show like this.

main > second > bbb

<?xml version="1.0" encoding="utf-8" ?><siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > <siteMapNode url="default.aspx" title="main" description=""> <siteMapNode url="default2.aspx" title="first" description="" > <siteMapNode url="default3.aspx" title="aaaa" description="" /> <siteMapNode url="default4.aspx" title="bbbb" description="" /> </siteMapNode> <siteMapNode url="default5.aspx" title="second" description="second" > <siteMapNode url="default6.aspx" title="aaa" description="" /> <siteMapNode url="default7.aspx" title="bbb" description="" /> </siteMapNode>

</siteMapNode></siteMap>

Built-in ASP.Net Objects1) Response2) Request

1) Response : To send response/output to client from server.

Response.Write(“message” / variable / “message” + variable) : To print output on clients browser.

Response.End() : To stop sending output to clients browser.

protected void Page_Load(object sender, EventArgs e) { DateTime dt = DateTime.Now; if (dt.DayOfWeek.ToString().Equals("Monday")) {

Response.Write("<font color='red' size=20>Today is holiday</font>"); Response.End(); }

}

Response.Redirect(“Filename.aspx/.html/.asp”) : To send client to another file.

Response.Buffer=true/false : If it is true the output will be saved in buffer on server. At the end the whole output will be sent to client. We have to set it to false.

17

Page 18: asP.NET NOTES using c#

Response.Clear() : It clears the contents of the buffer.

Response.Expires=30 : It caches the output of the page in cache memory for 30 minutes, if the same user revisits the page it displays the output from cache otherwise it executes the web page then saves the output in cache and displays on the page.

Response.ExpiresAbsolute=Date : It saves the output of the web page till the expiry of the given date & time.

Response.Flush() : It sends all the data buffered to the client and clears it.

Response.status=100/200/300/400/500 : We can set or get the status of code of the page. After processing of the web page server sends the status code along with http headers to the client indicating the status of the web page.

100 series status code indicates informational.200 : indicates the request is processed successfully, the output followed by the 200 will be interpreted by the browser.300 (redirect) : It indicates that some other processsing is required.400 : It indicates that the web page requested is not availble.500 : It indicates that the server is busy.

Variable=Response.status : To get the value.

To set the status code write in the Page_Load() event of an empty page the below statement :

Response.StatusCode=400;

2) Request : To read from client.

Variable = Request.Form[“html variable”] : if method is post.

Variable = Request.QueryString[“html variable”] : if method is get.

Variable=Request.Url : Returns the url being requested.

Variable=request.UrlReferrer : Returns the url name from where client has come.

Variable=request.UserAgent : Returns the browser name.

Variable=request.UserHostAddress : Returns the i/p address of the host.

Variable=request.UserHostName : Returns the name of the computer of host.

Response.Write("<br>"+Request.Url.ToString()); Response.Write("<br>"+Request.Url.AbsolutePath);

Response.Write("<br>"+Request.UrlReferrer); Response.Write("<br>" + Request.UserAgent.ToString());

18

Page 19: asP.NET NOTES using c#

Response.Write("<br>" + Request.UserHostAddress.ToString()); Response.Write("<br>" + Request.UserHostName.ToString());

string[] l = Request.UserLanguages; foreach (string i in l) Response.Write("<br>" + i);

string[] a = Request.AcceptTypes; foreach (string i in a) Response.Write("<br>" + i);

Response.Write("<br>" + Request.ApplicationPath.ToString()); Response.Write("<br>" + Request.Browser.BackgroundSounds); Response.Write("<br>" + Request.ContentLength); Response.Write("<br>" + Request.ContentType); Response.Write("<br>" + Request.Path); Response.Write("<br>" + Request.PathInfo); Response.Write("<br>" + Request.ServerVariables[0].ToString()); Response.Write("<br>" + Request.TotalBytes);

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load{ string a, b, c, d, e1, f, g; a = Request.Form["TextBox1"]; b = Request.Form["CheckBox1"]; c = Request.Form["CheckBox2"]; d = Request.Form["gender"]; f = Request.Form["DropDownList1"]; g = Request.Form["ListBox1"]; if (b == "on") b = "mca"; if (c == "on") c = "bca"; if (d == "RadioButton1") d = "Male"; if (d == "RadioButton2") d = "female"; Response.Write("<br>a=" + a);If (b!=””) Response.Write("<br>b=" + b);If (b!=””) Response.Write("<br>c=" + c); Response.Write("<br>d=" + d); Response.Write("<br>f=" + f); Response.Write("<br>g=" + g);}

State Management

19

Page 20: asP.NET NOTES using c#

Maintaing or finding the state of a user is called state management. This can be done in 3 ways.

1) Application2) Session3) Cookies

1) Application : To create and maintain application scope variables. These variables will never die until you stop the web site from web server. These variables are created first time when you open web site. These are created on web server but can be used in any page.

2) Session : To create and maintain session scope variables. These are created every time a user opens the web site and they are destroyed automatically when user closes the browser or changes the web site. These variables are created individually for every user.

Session variables can be created at two places :

1) While using same variable in recurring events. i.e. the variable does not hold previous value because the variable shall die after the event execution is over hence we should use session variable.

2) Storing a value in a variable in a page and using it in a new page.

Session.SessionID : Returns session ID.

Session.Timeout=no. : To set session timeout in minutes. By default 20 minutes.

Session.Abandon() : Cancels the session.

Session.Count : Returns no. of items in the session state.

Session.IsNewSession : Returns true if new session otherwise false.

The main use of Session object is to create and maintain session variables.

Variables created in a page will lost their values once the page execution is over. To avoid create session variables.

Variables created under Session scope can be used in multiple pages.

int i; protected void Page_Load(object sender, EventArgs e) { if (! IsPostBack) { Session["j"] = 0;

Application["c"] = 0; } } protected void Button1_Click(object sender, EventArgs e)

20

Page 21: asP.NET NOTES using c#

{‘ ordinary page scope variable

i= i + 1; Response.Write("<Br>ordinary variable i=" + i);

// session scope variable int a = Convert.ToInt32(Session["j"]);

a = a + 1; Session["j"] = a; Response.Write("<Br>session variable j=" + Session["j"]);

Response.Write("<Br>application variable c=" + Application["c"]);}

Example of creating session variables & sessionid in one Page & using in another page:

Coding of default4.aspx:

protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { Session["b"] = 0;

Application["c"]= ‘’oncourse’’; } } protected void Button1_Click(object sender, EventArgs e) {

Response.Write("Sessionid=" + Session.SessionID);Session[“a”]=TextBox1.Text;

}

Coding of default5.aspx page :

protected void Page_Load(object sender, EventArgs e){

// application variable Response.Write("<Br>application variable c=" + Application["c"]);

if (Session["b"] == null) Response.Redirect("~/default4.aspx"); else Response.Write("b=" + Session["b"]); }

Cookie : It is small amount of info stored by web server on client machine.

21

Page 22: asP.NET NOTES using c#

Types of cookie :

                a- temperary cookie (the info will be lost when user closes the browser or logout)                b- permanent cookie(persistent cookie) : the info will be stored on client machine till the time specified)

user name

Password

protected void Button1_Click(object sender, EventArgs e) { // temporary cookie creation HttpCookie cook = new HttpCookie("conco"); DateTime dt = DateTime.Now; cook.Values.Add("currentdatetime", dt.ToString()); cook.Values.Add("username", TextBox1.Text); cook.Values.Add("password", TextBox2.Text); Response.Cookies.Add(cook); Label1.Text = "temp cookie created"; }

protected void Button2_Click(object sender, EventArgs e) { // permanent cookie creation HttpCookie cook = new HttpCookie("conco"); DateTime dt = DateTime.Now; cook.Values.Add("currentdatetime", dt.ToString()); cook.Values.Add("username", TextBox1.Text); cook.Values.Add("password", TextBox2.Text); //for permanant cook.Expires = dt.AddMinutes(10); Response.Cookies.Add(cook); Label1.Text = "perm cookie created"; }

protected void Button3_Click(object sender, EventArgs e) { // reading cookie HttpCookie cook = Request.Cookies["conco"]; if (cook != null) { string d, u, p;

d = cook.Values["currentdatetime"].ToString(); u = cook.Values["username"].ToString(); p = cook.Values["password"].ToString(); System.Text.StringBuilder sb = new System.Text.StringBuilder();

22

Temp cookie Perm cookie Read cookie

Page 23: asP.NET NOTES using c#

sb.Append("date time of creation of cookie is " + d + "<br>"); sb.Append("user name is " + u + "<br>"); sb.Append("password is " + p + "<br>"); Label1.Text = sb.ToString(); } else { Label1.Text = "no cookie present"; } }

             Creating Web User Controls

1) Create a web site.2) Add new web page->at that time select web user control->change the name as

per your wish.3) .ascx is the extension name for web user control.4) Take the control required, set its properties, go to code window, type the

properties, functions, events etc.

Using already created user control :

1) Create a web page.2) Drag the .ascx file from Solution Explorer, it will register the control and writes the

following tag in source window.

<%@ Register src="lg.ascx" tagname="lg" tagprefix="uc1" %>

3) Also it places the necessary tag for the above control. Here tag name is lg its prefix is uc1.

<uc1:lg ID="lg1" runat="server" />

4) Now in the code winow using tb1 object you can use all its properties, functions etc. in the normal way.

Ajax Scripting (Asynchronous JavaScript XML)

To update the contents of web page without refreshing/round trip we can use ajax scripting controls.

Common things to be done :

1) Take ScriptManager control, 2) Take UpdatePanel Control.

Displaying Time on screen continuously without refreshing the page, the label,timer is in UpdatePanel.

1. Take Label.2. Take scriptmanager control.

23

Page 24: asP.NET NOTES using c#

3. Take UpdatePanel control.4. Take Timer control, set 1000 in interval property.5. Take Label control.6. Place the Timer, Label2 in updatepanel.

In timer1_tick event type the following :

Label2.Text=DateTime.Now.ToString();

Adding items in a dropdownlist after selecting a particular item from another dropdownlist.

1. Take scriptmanager control.2. Take UpdatePanel control.3. Take dropdownlist1 control.4. Take dropdownlist2 control. Place both the dropdownlist controls inside update

panel.

In DropDownList1_selectedindexchange event type the code :

if (DropDownList1.SelectedIndex==0){

DropDownList2.Items.Add(“Nagpur”);DropDownList2.Items.Add(“Mumbai”);

}

Displaying Time on screen continuously without refreshing the page, the label is in updatepanel.

1. Take Label.2. Take scriptmanager control.3. Take Timer control.4. Take UpdatePanel control.5. Place label in updatepanel.6. Click on UpdatePanelControl->go to properties window->click on triggers->click

on add and select asynchronouspostbacktrigger->select the control id you like to use->select its event.

In timer1_tick event type the following :

Label2.Text=DateTime.Now.ToString();

UpdateProgress control : It shows progress of a task.

Adding items in a dropdownlist after selecting a particular item from another dropdownlist.

1. Take scriptmanager control.2. Take updateprogress control.3. Take label, type in text property Getting Data…..4. Take UpdatePanel control.

24

Page 25: asP.NET NOTES using c#

5. Take dropdownlist1 control.6. Take dropdownlist2 control. Place both the dropdownlist controls inside update

panel.

In DropDownList1_selectedindexchange event type the code :

System.Threading.Thread.Sleep(1000);DropDownList2.Items.Clear();if (DropDownList1.SelectedIndex==1){

DropDownList2.Items.Add(“Nagpur”);DropDownList2.Items.Add(“Mumbai”);

}

After selecting state from DropDownList1, it will display Getting Data….. for 1 second after that the cities will be displayed in DropDownList2.

Using readymade ajax controls :

Alwaysvisiblecontrol extender : It displays the given text at the bottom/top of the window when you scroll using scroll bar.

Take a label->Click on its arrow which is displayed on top, right side->Add Extender->Always Visibile Control Extender->Set its properties like Horizontal Offset, Horizontal Side, Vertical Side, Use Animation, Scroll Effect Duration.

CalendarExtender : It is used to display/input date, time etc.

Take a textbox->Click on its arrow which is displayed on top, right side->Add Extender->Click on Calendar Extender->Set its properties Format->type d or the required format specifier you like. In format property d-date.

ColorPickerExtender : It is used to select color.

Take a textbox->Click on its arrow which is displayed on top, right side->Add Extender->Click on Colorpicker Extender->After selecting any color the color is displayed in the textbox, from the textbox use the color where ever you require.

FilteredTextBoxExtender : It does not allow the specified characters or typing in that textbox.

Take a textbox->Click on its arrow which is displayed on top, right side->Add Extender->Click on FilteredTextBoxExtender->Set its properties like FilterType (Numbers, Lowercase alphabets, Uppercase alphabets, which ever option you select that type of characters will be accepted). If you select FilterType custom then select ValidChars/InvalidChars from FilterMode. If you take ValidChars type ValidChars in ValidChars property, If you take InValidChars type InValidChars in InValidChars property.

MaskedEditExtender : It also allows you to enter proper data.

25

Page 26: asP.NET NOTES using c#

Take a textbox->Click on its arrow which is displayed on top, right side->Add Extender->Click on MaskType->Select Number/Date/Time/DateTime from Masktype property, Type the format in which you want to enter nos. in Mask property (9,99,999.99). Type the format in which you want to enter dates in Mask property (99/99/9999 or 99:99:99 or 99/99/9999 99:99:99). Also you can select the format for dates from UserDateFormat and for times from UserTimeFormat.

PasswordStrength : It is used to display the strength of the password.

Take a textbox->Set its TextMode to Password->Click on its arrow which is displayed on top, right side->Add Extender->Click on PasswordStrength.

TextboxWaterMarkExtender : It is used to display a default text in the textbox. When user clicks in that textbox the default text vanishes, textbox becomes blank.

Take a textbox-> ->Click on its arrow which is displayed on top, right side->Add Extender->Click on TextboxWatermarkExtender->Set its property WaterMarkText with your text.

PagingBulletedListExtender : It displays First letter of all alphabets on the screen, after clicking on any alphabet it displays all the remaining words using that alphabet.

Take BulletedList control->Add items starting with a, b, c, d etc.->Click on Top,Right arrow->Click on Add Extender->Select PagingBulletedExtender.

ADO.NET

.NET uses ADO.NET (Activex Data Objects) as its primary data access and manipulation protocol. It works with connected as well as disconnected databases.

Database programming can be done thru Controls and Coding.

Database Programming can be done using MS Access, Oracle, SQL Server or any ODBC Complaint Database. (Open Database Connectivity).

Steps for database programming :

1) Establish connection with database using respective provider and driver.2) Open database.3) Store, Delete, Modify or Read data.4) Show/Process the data5) Close database.

Namespaces :

ACCESS – System.Data.OledbOracle – System.Data.OracleClient

26

Page 27: asP.NET NOTES using c#

SQL Server – System.Data.SqlClientODBC – System.Data.ODBC

Classes :

Access Oracle Sql Server ODBC

OledbConnectionOracleConnection

SqlConnection

OdbcConnection

OledbDataAdapter

OracleDataAdapter

SqlDataAdapter OdbcDataAdapter

OledbDataReader

OracleDataReader

SqlDataReader OdbcDataReader

OledbCommand

OracleCommand

SQLCommand OdbcCommand

DataSet DataSet DataSet DataSet

Sequence :

1) Oledbconnection, OledbdataAdapter, Dataset - disconnected

2) Oledbconnection, OledbdataReader, Oledbcommand - connected

Access :

OledbConnection : To establish connection with database.

Physical path:

Oledbconnection con = new Oledbconnection (“Provider=Microsoft.jet.oledb.4.0;Data Source= drivename:\\foldername\\databasename.mdb”);

Logical Path :

Oledbconnection con = Oledbconnection (“Provider=Microsoft.jet.oledb.4.0;Data Source=” + Server.MapPath(“\\databasename.mdb”));

Functions :

con.Open() : To open database.con.close() : To close database.

Oledbdataadapter : To read data from table. However data stored in it is temporary, because the same adapter we can use to retrieve data from other tables also. Also data stored in adapter can’t be read directly we have to store the data in DataSet for further usage.

oledbdataadapter oda;oda=new oledbdataadapter(“sql statement”,connection object);

or

27

Page 28: asP.NET NOTES using c#

oledbdataadapter oda = new oledbdataadapter(“sql statement”,connection object);

DataSet : To store data retrieved using dataadapter. Also we can store data of multiple tables.

Dataset ds = new Dataset();

oda.fill(ds) : To store data in dataset.

OledbDataReader : To read data from table. The read data stored in this object. Directly we can operate on data using this object, no need to fill the data in dataset.

OledbCommand : It is used to execute SQL queries, stored procedure, to implement transactions.

oledbcommand cmd = new oledbcommand();cmd.connection=con;cmd.commandtext=”sql query”;

cmd.executenonquery() -> Except select query it executes all other queries.

oledbdatareader dr;dr=cmd.executereader(); -> Executes only select query

Oracle Connectivity :

OracleConnection ora1 = new OracleConnection(“User id/uid=scott;Password/Pwd=tiger;Data Source=hoststring/SID”);SQL Server Connectivity :

Sql Server Authentication :

SqlConnection sql1 = new SqlConnection(“User id/uid=sa;password/Pwd=secret;Data Source=server name/(local);initial catalog=database name”);

Windows Authentication :

SqlConnection sql1 = new SqlConnection(“Integrated security=true; Data Source=server name/(local);initial catalog=database name”);

Adding, updating, deleting, selecting data of gridview, detailsview, formview, listview

1) Make a column of database table as primary key.2) Take SqlDataSource control, click on configure data source, specify server

name, database name, select table name, click on Advanced, click on Generate Insert, Update,Delete,Select coding, click on Optimum Concurrency->Ok->Next->Finish.

3) Now .net will add all the coding required for adding, updating, deleting, selecting automatically to sqldatasource control.

28

Page 29: asP.NET NOTES using c#

4) Give the sqldatasource to any control which ever you like to use. For this click on right side top arrow->specify sqldatasource1 in choose data source property, Check Enable Selection, Enable Deletion, Enable Insertion, Enable Updation.

5) If any column is blank we can’t edit or delete that record.

Displaying images in GridView

1. Store image file names, in the table.2. Copy all the images to your working folder.3. Select GridView->Columns/ Click on arrow of GridView->Click on EditColumns,

Select ImageField, Click on Add. 4. Select ImageField, select col.name which contains image filename for

DataImageUrlField property, Specify Width & Height in Control Style property.

Displaying images in DetailsView

1. Store image file names, in the table.2. Copy all the images to your working folder.3. Click on arrow of Details View->Click on Edit Fields, Select ImageField, Click on

Add. 4. Select ImageField, select col.name which contains image filename for

DataImageUrlField property, Specify Width & Height in Control Style property.

Displaying hyperlinks in GridView

1. Select GridView->Columns, Select HyperlinkField, Click on Add. 2. Select HyperlinkField, select colname for DataNavigateUrlField property, select

col.name for DataTextField property.

Displaying hyperlinks in DetailsView

1. Click on arrow of DetailsView->click on Edit Fields, Select HyperlinkField, Click on Add.

2. Select HyperlinkField, select colname for DataNavigateUrlField property, select col.name for DataTextField property.

Displaying images in DataList, ListView, FormView, Repeater

The below statements to be written in ItemTemplate :

If you have images in a folder under website folder :

<asp:Image runat="server" Width="150" Height="100" id="pimg" ImageUrl='<%# Eval("photo","/images/{0}") %>' />

Console.WriteLine(“a={0}b={1}”,a,b);Console.WriteLine(“a=”+a+”b=”+b);

If you have images in website folder :

29

Page 30: asP.NET NOTES using c#

<asp:Image runat="server" Width="150" Height="100" id="Image1" ImageUrl='<%# Eval("photo") %>' />

Displaying hyperlinks in FormsView, ListView, DataList, Repeater

1) Take FormsView or DataList or Repeater, choose sqldatasource.2) Click on Source Tab, then type ItemTemplate, type a hyperlink, specify one column to click as hypertext, second column for opening the required web page. i.e. first col. should contain id/rollno etc., 2nd col. should contain webpage filename to be opened.

<asp:FormView ID="FormView1" runat="server" DataSourceID="SqlDataSource2" AllowPaging="True"> <ItemTemplate>

<asp:HyperLink runat="server" ID="h1" NavigateUrl='<%# Eval("link")%>'><%# Eval(“rno”) %>

</asp:HyperLink>

</ItemTemplate> </asp:FormView>

Caching

A) Page output caching :

In this type of caching the entire page will be cached for specified time. After the expiry of the specified time only the page will be refreshed. For this click on source tab->type the following tag, the duration is in seconds.

<%@ OutputCache Duration="30" VaryByParam="None" %>

In Page_Load event type the below :

Label1.Text=DateTime.Now.ToString();

B) Data Caching :

1) creating object in cache for lifelong :

Cache["objectname/variable"]="data"/objectname;

Cache["a"]=15;Cache["b"]="sekhar";Cache["c"]=TextBox1.Text;Cache["d"]=ds;

Retriving data from Cache :

int a1;string b1;

30

Page 31: asP.NET NOTES using c#

string c1;DataSet d1;

a1=Convert.ToInt32(Cache["a"]);b1=Cache["b"].ToString();c1=Cache["c"].ToString();Response.Write(“a1=”+a1);Response.Write(“<br>b1=”+b1);Response.Write(“<br>c1=”+c1);

d1=new DataSet();d1=Cache["d"];

Note : The cached data of one website. can’t be used in another website.

2) Saving a object in catch till a specified time (absolute expiration) :

Cache.Insert("mydata1", dv1, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero);

mydata1 will be cached for 1 minute, after expiry of 1 minute system will get data from database table, displays it and then stores in a object called mydata1 which is available in cache.

3) Saving a object in catch using silding time expiration :

Cache.Insert("mydata2", dv1, null, DateTime.MaxValue, TimeSpan.FromMinutes(2));

mydata2 will be cached for 2 minutes, after expiry of 2 minutes system will get data from database table, displays it and then stores in a object called mydata2 which is available in cache. If anybody retrieves the same page before expiry of 2 minutes the difference time will be added to the 2 minutes, the data is stored in the cache till the expiry.

It is called Sliding Expiration Time because the time left in the previous expiry is added to the current expiry like that the expiration time increases. If the time to expire is continuously increases it is called sliding, hence it is called sliding expiration time.

protected void Button1_Click(object sender, EventArgs e){ SqlConnection con = new SqlConnection("data source=(local);initial catalog=vilasdb; integrated security=true"); DataSet ds=new DataSet();

SqlDataAdapter sda=new SqlDataAdapter("Select * from student",con); //if (Cache["mydata3"] == null) if (Cache["mydata1"] == null) //if (Cache["mydata2"] == null) { Label1.Text = "Data retrieved from table"; sda.Fill(ds);

31

Page 32: asP.NET NOTES using c#

GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); DataView dv1 = new DataView(ds.Tables[0]); //Cache["mydata3"] = dv1; Cache.Insert("mydata1", dv1, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero);/// Cache.Insert("mydata2", dv1, null, DateTime.MaxValue, TimeSpan.FromMinutes(2)); } else { Label1.Text = "Data retrieved from cache"; // DataView dv = (DataView)Cache["mydata3"]; DataView dv = (DataView)Cache["mydata1"]; // DataView dv = (DataView)Cache["mydata2"]; GridView1.DataSource = dv; GridView1.DataBind(); } }

Creating Web Services

Services available on internet are called Web Services. Normally every web service contains various functions with or with out arguments, does some processing and returns data to the user. For this first of all we have to add web reference to your web site/project, then create object and call the function by sending arguments to it, display the resultant value.

.asmx : Is the extension name for the web service file.

Procedure for creating web service :

1) Create ASP.NET Web Service Project.2) It will a display a page having class name as Service. It contains all the

web methods. This class is inherited from WebService class, there will be a sample method HelloWorld for your reference. Write all your methods below this. While writing every method add [WebMethod] attribute before the function.

[WebMethod]public int sum(int a, int b){

return a+b;}

3) Now test the web service created by pressing F5 or Ctrl+F5.4) It will display all the function names on screen. Click on any one name,5) If it takes arguments, it will ask you for data using the parameters defined,

enter proper data then click on Invoke button. Immediately output will appear in another internet explorer in the form of xml tags.

or

32

Page 33: asP.NET NOTES using c#

6) If function does not take argument directly it will display Invoke button, click on it, immediately the output will appear in another internet explorer in the form of xml tags.

Using Web Service in a web site :

1) Create a Web Site2) Design the form as per your need.3) Click on Website->Add Web Reference->

Start Browsing for Web Services

Use this page as a starting point to find Web services. You can click the links below, or type a known URL into the address bar.

Browse to:

Web services in this solution Web services on the local machine

Browse UDDI Servers on the local network Query your local network for UDDI servers.

4) Click on Web Services on the local machine.5) It will search in the iis, displays all the files as hyper link, click on required

hyperlink, it will display its functions, displays localhost in webreferencename textbox. If you want you can change web reference name-> Click on Add Reference. Now you can find from Solution Explorer, Add Web References, under it the localhost details.

6) Now create the object of loalhost.Service, then using object call the functions available in web service.

Example :

protected void Button1_Click(object sender, EventArgs e){

localhost.Service l1 = new localhost.Service();int a = l1.sum(Convert.ToInt32(TextBox1.Text),

Convert.ToInt32(TextBox2.Text)); Label1.Text = a.ToString();}protected void Button2_Click(object sender, EventArgs e){ Label4.Text = l1.mul(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text)).ToString();}

Using Web Service in windows project :33

Page 34: asP.NET NOTES using c#

1) Create a Windows Project 2) Design the form as per your need.3) Click on Project->Add Service Reference->type

http://localhost/foldername/Service.asmx->Click on Go.4) It will search in the iis, displays all the files as hyper link, displays

ServiceReference1 in ServiceReferenceName textbox. If you want you can change service reference name-> Click on Add Service Reference. Now you can find from Solution Explorer, Add Services References, under it the ServiceReference1 details.

5) Now create the object of ServiceReference1.ServiceSoapClient(), then using object call the functions available in web service.

Example :

ServiceReference1.ServiceSoapClient l1 = new ServiceReference1.ServiceSoapClient();

protected void Button1_Click(object sender, EventArgs e){ int a = l1.sum(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text)); label1.Text = a.ToString();}protected void Button2_Click(object sender, EventArgs e){ label4.Text = l1.mul(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text)).ToString();}

Configuring A Web Application

Configuring can be done in 2 files.

1. Machine.Config2. Web.Config

1. Machine.Config : It is an xml file. It can be found in the path C:\windows\microsoft.net\framework\v.1.xxxx\config\machine.config, where ‘xxxx’ is the build number of the .net CLR. This file decides the configurations for all the applications that reside on that machine.

2. Web.config : It is also xml file, that can be found in the web application directory. It sets the configuration for one website only.

Note: The web.config file will override the settings of the machine.config file.

1. appSettings: The application settings allow the user to set the application configuration details. It enables the user to store and retrive information as key-value pairs.

You have to type the following after <configuration> in web.config file.this tag <appSettings/> is available, remove it and type the below :

34

Page 35: asP.NET NOTES using c#

<appSettings> <add key="cs" value="Data Source=Home-1;initial catalog=pubs;uid =sa; pwd=secret"/>

</appSettings>

In the program read the cs variable value :

string cs1 = System.Configuration.ConfigurationManager.AppSettings["cs"].ToString();

Now use the cs1 variable in sqlconnection class.

SqlConnection con=new SqlConnection(cs1); -> C#.net

2) Also we can do the same in <connectionStrings/> tag :

this <connectionStrings/> tag is availabe, remove it and type the below :

<connectionStrings> <add name="2to3ConnectionString" connectionString="Data Source=LAB-387;Initial Catalog=2to3;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings>

To read connectionstring data in the Prg. :

string cs1 = System.Configuration.ConfigurationManager.ConnectionStrings["2to3ConnectionString"].ToString();

Now use the cs1 variable in sqlconnection class.

SqlConnection con=new SqlConnection(cs1); -> C#.net

3) Authentication : The Process of validating username and password is called authentication.

4) Authorization : After setting the authentication settings for an application we have to set access rights as to who can access the application. This can be done using the authorization.

Login controls

To enter username, password for validation. We can also create new user, change passwords, recover passwords, making log in, log out, displaying user login-names etc.

To use login controls first of all we have to configure a database. There are two procedures to configure database.

Procedure 1 :

35

Page 36: asP.NET NOTES using c#

If you sql server 2005 express edition then no need to anything, automatically .net has got provision to use the database. It creates aspnetdb.mdf in Sql Server 2005 express edition, adds that database in your web site app_data folder, tables and uses it.

Procedure 2 :

If external database is installed on machine like Microsoft Sql Server 2000/2005 then we have to configure it manually.

a) Create a database.b) Go to .net command prompt (Click on Start->All Programs->Microsoft Visual

Studio 2008->Visual Studio Tools->.Net Command Prompt)c) type aspnet_regsql->Next->Next->Type/select servername->Click on Windows

Authentication->Select previously created database->Next->Next->Finish.d) Open Web.Config file, add connection string.

Under <configuration> type the following :

<connectionStrings><clear/> <add name="localsqlserver" connectionString="server=(local);Database=sekharlogin;Integrated Security=True" providerName="System.Data.SqlClient"/>

</connectionStrings>

e) Click on Web Site->Asp.net configuration->Security->Select Authentication Type->Click on From Internet->Done. In web.config the authentication is changed like this <authentication mode="Forms"/>

Under <authentication mode="Forms"> type the following :

<authentication mode="Forms"> <forms loginUrl="login.aspx" name="l1" /></authentication><authorization> <deny users="?"/>

</authorization>

1) Create Page giving name login.aspx, place login control. Specify any page name in DestinationPageUrl property for successful login display page.

CreateUserIconUrl : Specify image file name.CreateUserText : Type any text which will be used as a hyperlink.CreateUserUrl : Specify filename to be opened if the above hyperlink is clicked (CreateUserText).DestinationPageUrl : Specify filename to be opened upon successful login.FailuteText : Specify text to be displayed if login fails.LoginButtonImageUrl : Specify image filename.

36

Page 37: asP.NET NOTES using c#

LoginButtonText : Specify text.LoginButtonType : Select button type.PasswordRecoveryText :PasswordRecoveryURL :

2) Create a page, give name changepassword.aspx, place ChangePassword control. In the continue step specify login.aspx for continuedestinationpageurl property.

3) Create a page, give name forgotpassword.aspx, place PasswordRecovery control. In the continue step specify login.aspx for SuccessPageUrl property.

go to property window

click on plus sign of mail definationset the properties of from ([email protected], subject, priority), etc

now go administer siteclick on application tabclick on configure smtp email settingsset the values of servername etc.click on save button and ok buttonclose the administer site

now in desktopright click on mycomputerselect manageselect services and applicationsexpand internet information serverexpand default smtp virtual serverr c on domainsselect new domainselect aliastype computername.com (dc-6.com)click on finish button

now run the default pageselect forgot password

check the new temp passwordin windows exploreropen c:\inetpub\mailroot\drop foldercheck the email received.

4) Create a page, give name createuser.aspx, place CreateUserWizard control. In the continue step specify login.aspx for continuedestinationpageurl property.

5) Create a page, place hyperlinks for login, changing password, forgot password, creating user and connect with proper files.

Adding roles to a user :

37

Page 38: asP.NET NOTES using c#

1) Create a folder in your web site, Create one pages in it.2) In the web site folder create a page.

In the create user wizard,

1) add a new step, move this step above complete step.2) Place a listbox.3) Go to source window, type onactivate="activatestep" ondeactivate="deactivatestep" in WizardStep tag.4) Go to code window, create functions for activatestep, deactivatestep, type the following :

protected void activatestep(object sender, EventArgs e){ ListBox1.DataSource = Roles.GetAllRoles(); ListBox1.DataBind();}protected void deactivatestep(object sender, EventArgs e){ Roles.AddUserToRole(User.Identity.Name, ListBox1.SelectedValue.ToString());}

5) Click on Asp.net configuration wizard.

6) Click on enable roles->click on create or manage roles->create admin and student roles.

7) Now restrict the users while accessing the admin folder pages. For this click on asp.net configuration wizard->click on go to security tab->select create access rules->select admin folder->select role admin->and then select allow radio button->and then click ok button.

8) once again click on create access rule->select all user radio button->select deny radio button->click on ok button->close the admin site.

9) Now while creating user select admin or student as his role.

10) create two hyperlinks for accessing the pages created in admin folder.

11) Now log-in using username, password of admin role user, click on the hyperlinks you will be taken to that page.

12) Now log-in using username, password of student role user, click on the hyperlinks the hyperlinks will not work.

38

Page 39: asP.NET NOTES using c#

Using Resources for Localization with ASP.NET :

An effective way to create localized Web pages is to use resources for your page's text and controls based on the user's language and culture. By using properties placed in resource objects, ASP.NET can select the correct property at run time according to the user's language and culture. The process is straightforward :

A resource file (.resx) stores values.

In your page, you indicate that controls should use resources for their property

values.

At run time, the controls' property values are derived from the resource file.

Implicit Localization with ASP.NET

In this section, you will work with implicit localization. In implicit localization, you specify that control properties should automatically be read from a resource file, but you do not need to explicitly specify which properties are localized. Then, you create a resource file with localized values for specific properties. At run time, ASP.NET examines the controls on the page. If the control is marked to use implicit localization, ASP.NET looks through the resource file for the page. If it finds property settings for the marked control, ASP.NET substitutes the values in the resource file for those in the control.

In this example of implicit localization, you use a combination of the designer and the Resource Editor to generate a default resource file that you will use as a starting point for localization in two languages. Visual Web Developer will generate a resource file based only on the controls on your page. For this reason, it is a good idea to generate the resource file after you have completed your page's control layout, including simple controls such as buttons, labels, and text boxes.

Steps :

1) Create a file system Web site.

2) Place a label, textbox, and button.3) Change their text to English Label, English TextBox, English Button.

After creating the page and adding the controls, you can use a Visual Web Developer command to generate a local resource file for this page. The local resource file will contain the resource strings for the controls on the page. Visual Web Developer generates a resource string for each property that is designated internally in the control as localizable. Each control can have different properties designated as localizable, although most text-based properties are marked that way.

To automatically generate a resource file :

1. Click the designer surface or a control.

2. On the Tools menu, click Generate Local Resource.

39

Page 40: asP.NET NOTES using c#

Visual Studio creates a new folder named App_LocalResources, and within the App_LocalResources folder, a new file named Default.aspx.resx. If you named your page something other than Default.aspx, the .resx file will reflect whatever name you chose. When using implicit localization, resource file names are based on individual page names.

3. Switch to Source view to see the changes to your control declarations.

Visual Studio has added an attribute to your controls to retrieve their values from your newly created resource file. For example, the Button control's markup has a new meta:resourcekey attribute.

<asp:Button ID="Button1" Runat="server" meta:resourcekey="ButtonResource1"

Text="English Button" />

When a browser sends a request to Web server, the request can include information about the current language and culture. For example, a browser might send the string "en-us" to indicate it has been set to use United States English; another browser might send the string "en-gb" to indicate it has been set to use British English.

The resource file is used as the default resource file for all requests. (It is the resource file for the fallback culture.) If no culture is specified by the browser, or if the browser request includes a language or culture that you do not support, resource values are pulled from this default file.

Now that the resource file is created, you can place localized text within it by using the Resource Editor.

To edit the resource file by using the Resource Editor

1. In Solution Explorer, open Default.aspx.resx.

In the Resource Editor, under Value, are the Text properties for each of the

controls that you placed onto your page. Changing the value here will change the

value for the default culture.

2. Set ButtonResource1.Text to Edited English Text.

3. Save the file.

Now you can test the page.

To test the page Press CTRL+F5 to run the page.

40

Page 41: asP.NET NOTES using c#

The text you provided in the Resource Editor is shown as the label for Button1.

When using implicit localization, syntax properties in resource files will override

properties specified in the page itself.

 Adding Other Cultures

Each language and culture combination requires a unique resource file. To add other cultures, you can use your default file as a starting point. You can create resource files for different cultures and locales by creating new resource files in which the ISO language codes are part of the file name (for example, en-us, fr-ca, and en-gb). These ISO codes are placed between the page name and the .resx file name extension, as in Sample.aspx.en-us.resx. To specify a culturally neutral language, you would eliminate the country code, such as Sample.aspx.fr.resx for the French language.

Note:

When using implicit localization syntax, you must create a separate series of resource files for each page.

To create a culturally neutral French language file

1. In Solution Explorer, right-click the Default.aspx.resx file, and then click Copy.

2. Right-click the App_LocalResourcesfolder, and then click Paste.

Visual Studio creates a file named Copy of Default.aspx.resx.

3. Right-click the Copy of Default.aspx.resx file, click Rename, and then type

Default.aspx.fr.resx.

Default.aspx.fr.resx indicates a file for culturally neutral French language text.

4. Open Default.aspx.fr.resx.

5. For the Button, Label, and TextBox controls, set Text to French Button,

French Label, and French TextBox, respectively.

6. Save the file.

Testing with an Alternate Language Setting

Before you can see if this new resource file is used by ASP.NET, you must alter your browser settings to request the desired culture.

To change your browser's language settings :

1. In Microsoft Internet Explorer, on the Tools menu, click Internet Options.

41

Page 42: asP.NET NOTES using c#

2. Click Languages.

3. In the Language Preference dialog box, click Add.

4. In the Add Language dialog box, under Languages, click French (France) [fr],

and then click OK.

5. Click Add and add Spanish (Mexico) [es-mx] to the list of languages.

6. Click Add and add Arabic (Egypt) [ar-eg] to the list of languages. Click Add and add Hindi [hi] to the list of languages.

You will use Spanish and Arabic for testing later.

7. In the Language Preference dialog box, under Language, click French

(France) [fr], click Move Up, and then click OK. If you move up Hindi [hi] to top.

automatically the text will be displayed in hindi.

Internet Explorer is now set to pass fr as the language setting for any request. With the culture set to auto in the Sample.aspx page, ASP.NET will attempt to locate a resource file and its corresponding values to assemble the page according to your language and culture preferences.

To test the page In Visual Studio, press CTRL+F5 to run the page.

The page is refreshed with values from the localized French language file instead

of the English version.

Also you can set UICulture property of Page to required language. At that time it studies the .resx for the equivalent values then displays accordingly in that language.

 Explicit Localization with ASP.NET :

In the first part of this walkthrough, you used ASP.NET implicit localization to have controls display localized text. You generated a resource file with property values in it, and in the process, you added an attribute to each control that instructed it to fill its property values, if any, from the resource file. Implicit localization works automatically, in that you do not need to specify property by property how to read information from a resource file.

However, at times you want to have more direct control over how properties are set. For this, instead of using implicit localization, you can use explicit localization. With explicit localization, you set the value of a property by using an expression pointing to a resource file. When the page runs, the expression is evaluated, the value is read from the specified resource file, and then the value is used to set the property.

Explicit localization is useful when you have large bodies of text or custom messages you want to localize, in addition to controls and labels. For example, you could develop a series of localized welcome and thank you messages for an e-commerce site, and use explicit declarative expressions to place this text on your pages. Additionally,

42

Page 43: asP.NET NOTES using c#

explicit localization allows you to maintain a single set of localized resource files rather than maintaining a separate set of files for each page.

In this section, you will create resource files manually and reference them by using ASP.NET declarative expression syntax. You will create a resource file for a simple thank you message. Unlike using the designer, a separate resource file is not required for each ASP.NET page.

The base name of your resource file will be Resource1. For each language you want to localize, you will create another file with the appropriate language code (and optionally the culture code) as part of the file name. For example, for U.S. English you would create a file named LocalizedText.resx. For the French language in Canada, you would create a file named LocalizedText.fr-ca.resx. Both files would be placed under the Resources directory of your Web application. Unlike the implicit example previously, you do not need to maintain a resource file for each .aspx page; instead, you can maintain a single series of files for each language or culture you support.

To create a resource file

1. In Solution Explorer, right-click the root of your Web site, click Add ASP.NET

Folder, and then click App_GlobalResources.

2. Right-click the App_GlobalResources folder, and then click Add New Item.

3. Under Visual Studio installed templates, click Resource File.

4. In the Name box, type Resource1.resx, and then click Add.

The Resource1.resx file will act as the resource for the fallback culture.

5. Create a second .resx file and name it Resource1.fr.resx.

The string "fr" identifies the file as the resource to use if the browser's language

is set to French (regardless of culture).

6. Create a third .resx file and name it Resource1.es-mx.resx.

The string "es-mx" identifies the file as file as the resource to use if the browser's

language is set to Spanish (Mexico).

7. Open the Resource1.resx file.

8. In the first row under the Name column type Msg1.

9. In the first row under the Value column, type Hello.

10.Save the file and close it.

43

Page 44: asP.NET NOTES using c#

11.Open the Resource1.fr.resx, create a resource string named Msg1, assign it the

value Bon jour. When you are finished, save and close the file.

12.Open the Resource1.es-mx.resx, create a resource string named Msg1, assign

it the value Buenos días. When you are finished, save and close the file.

Note:

To insert the letter with acute (í), type ALT+0237 on the numeric keypad with Number Lock on.

13.You have created three values for the resource named Msg1. ASP.NET will read

the value out of the appropriate resource file based on what language the

browser is set to.

Now that your resource file is created, you can return to the page and add controls that will reference the resource.

To add a Label control to the page

1. Switch to Default.aspx, and then switch to Design view.

2. Drag another Label control onto the page.

3. Right-click the Label control, click Properties, and then click the ellipsis (…)

button in the Expressions box.

The Expressions dialog box appears.

4. In the Bindable Properties list, click Text.

5. In the Expression Type list, select Resources.

6. Under Expression Properties, set ClassKey to Resource1 and ResourceKey

to Msg1.

7. Click OK.

8. Switch to Source view.

Your label's text attribute now has an explicit expression stating the base file from

which to retrieve the resource and the key to select.

44

Page 45: asP.NET NOTES using c#

Copy Code

<asp:Label ID="Label2" Runat="server" Text="<%$ Resources:Resource1, Msg1

%>">

Note:

The LocalizedText attribute has no language indicator, culture indicator, or .resx extension because it is not the actual file name. Instead, LocalizedText represents the base resource class. Depending on the culture sent by the browser, ASP.NET will select the resource out of the file with the appropriate language or culture code within its file name, such as Resource1.fr.resx, Resource1-mx.resx, or if no matching language is found, Resource1.resx.

With the resource file completed, and the declarative expression added, you can test the page. After the last test, your browser was set to report French as its language preference. During the testing, you will change the browser's language several times.

To test the page

1. Press CTRL+F5 to run the page.

The French-language version of the text you provided in the Resource Editor is

shown as the text for the Label control.

2. In Microsoft Internet Explorer, on the Tools menu, click Internet Options.

3. Click Languages.

4. In the Language Preference dialog box, move Spanish (Mexico) [es-mx] to the

top of the list of languages. When you are finished, click OK and close the

Internet Options dialog box.

5. Press F5 to refresh the browser.

The Spanish version of the text is displayed.

6. Change the language to Arabic and then press F5 to refresh the page again.

This time, the text is displayed in the language you used in the fallback resource

file. Because you did not create a file LocalizedText.ar-eg.resx, ASP.NET was

not able to locate text that matched the language and culture reported by the

browser, so it used the fallback resource file.

7. When you are finished testing the page, set the language back to the language

your preferred language.

45

Page 46: asP.NET NOTES using c#

Profiles

They are used to store per user settings on web server. ie if we login in yahoo and want to store some personal info on web server, so that when i login next time i can see or retreive my personal info.

steps to create a profile.

1- create a web site, create a database and configure it.

2- for creating profile go to web.config file

3 - and write the code in <system.web> tag to create profile

<connectionStrings>

<clear/>

<add name="LocalSqlServer" connectionString="server=(local);integrated security=true;database=sekharlogin"/>

</connectionStrings>

<system.web>

<anonymousIdentification enabled="true"/>

<profile>

<properties>

<add name="companyname" defaultValue="concourse" allowAnonymous="true"/>

<add name="companyaddress" defaultValue="dhp nagpur" allowAnonymous="true"/>

<add name="favcolor" defaultValue="yellow" allowAnonymous="true"/>

<add name=”mytheme” defaultValue=”Theme1” allowAnonymous=”true”/>

</properties></profile>

save and build the project

now go to default.aspx design view

and place 3 textbox and one button control.

46

Page 47: asP.NET NOTES using c#

and in page load event write the code to get the profile values .

if (!Page.IsPostBack) {

TextBox1.Text = Profile.companyname; TextBox2.Text = Profile.companyaddress; TextBox3.Text = Profile.favcolor; }

To save values in Profile variables :

Profile.companyname=TextBox1.Text;Profile.companyaddress=TextBox2.Text;Profile.favcolor = TextBox3.Text;

Themes

are used to change the look and feel of your web sites.

it contains

1- skin file - which contains code to change the look and feel of web server controls.(ie label , button ,textbox etc.)

2- css file - which contains code for html tags

Steps to create a theme :

1- right click on solution explorer

2- select add asp.net folder

3- select theme

4- give name as conco1

5- right click on conco1

6- select add new item

7- select skin file

and write the code in skin file

<asp:textbox runat="server" backcolor="gray" forecolor="white"/>

<asp:button runat="server" backcolor="blue" forecolor="white"/>

47

Page 48: asP.NET NOTES using c#

now go to default page

place labels , textbox and button controls

to apply theme to page

go to source view (in the bottom)

and at the top write the theme attribute in page directive

<%@ Page Theme="conco1" Language="VB"

now go to theme folder and right click on conco1 folder

and right click on it and select add new item

select css file

and write code for html tags

right click on body tag

and select build style

body{

font-family: Arial, Helvetica, sans-serif; color: #FF00FF; font-size: xx-large;}

h1{ background-color: #00FFFF; font-family: 'Times New Roman' , Times, serif;

font-size: xx-large;}

similarly create another theme named conco2, now you want that user can select the appropriate theme

go to setting page and place one dropdown list control and add items conco1, conco2

now go to web .config page and create a profile

write page_preinit event in default.aspx as well as setting.aspx page

48

Page 49: asP.NET NOTES using c#

protected void Page_PreInit(object sender, EventArgs e){

Page.Theme = Profile.mytheme;}and in button 1 click on setting page write

protected void button1_click(object sender, EventArgs e){

Profile.mytheme = DropDownList1.SelectedItem.ToString();

Response.Redirect(“~/default.aspx”);}

ADO.Net Programs

Program for inserting, deleting, updating, displaying data in textboxes (single & all records).

Adding data in combobox, tree view, selecting from combobox, treeview and showing in textboxes.

49

Page 50: asP.NET NOTES using c#

// declare the below inside class

SqlConnection con = new SqlConnection("data source=LAB-387;initial catalog=2to3;integrated security=true"); SqlDataReader dr; SqlCommand cmd = new SqlCommand(); int r,r1; string qry,fname;

// type the below in page load event :

if (! Page.IsPostBack) { con.Open(); cmd.Connection = con; cmd.CommandText = "select * from student"; dr = cmd.ExecuteReader(); TreeNode t1;

50

Page 51: asP.NET NOTES using c#

TreeNode t2=new TreeNode(“Roll No”); TreeView1.Nodes.Add(t2); DropDownList1.Items.Add(“Select any Roll No”); ListBox1.Items.Add(“Select any Roll No”);

string rno; while (dr.Read()) { rno= dr.GetValue(0).ToString(); DropDownList1.Items.Add(rno); ListBox1.Items.Add(rno);

t1=new TreeNode(); t1.Text =rno; TreeView1.Nodes.Add(t1); TreeView1.Nodes[0].ChildNodes.Add(t1); } con.Close(); } // drop down list event coding :

try { r = int.Parse(DropDownList1.SelectedItem.Text); r1 = r; qry = "select * from student where rno=" + r; //MessageBox.Show(qry); con.Open(); cmd.Connection = con; cmd.CommandText = qry; dr = cmd.ExecuteReader(); if (dr.Read()) { textBox1.Text = dr.GetValue(0).ToString(); textBox2.Text = dr.GetValue(1).ToString(); textBox3.Text = dr.GetValue(2).ToString(); textBox4.Text = dr.GetValue(3).ToString(); textBox5.Text = dr.GetValue(4).ToString(); fname = dr.GetValue(5).ToString(); if (File.Exists(fname)) pictureBox1.Image = Image.FromFile(fname); } } con.Close();

Inserting, Updating, Deleting data thru Parameter Passing

1) Create objects of SqlConnection, SqlCommand.2) Create objects of SqlParameter class, specify data to its Value property.3) Add the Parameters to the command object.4) Specify connection object to command object Connection property.

51

Page 52: asP.NET NOTES using c#

5) Open the connection.6) Store the sql query in command obejct CommandText property.7) Execute the query.8) Close the connection.

// type the code in side class

SqlConnection con = new SqlConnection("server=lab-387;integrated Security=true;initial catalog=2to3"); SqlCommand com = new SqlCommand(); // type the code in button1 event

SqlParameter sp1 = new SqlParameter("@rno", SqlDbType.Int); sp1.Value = int.Parse(textBox1.Text);

SqlParameter sp2 = new SqlParameter("@sname", SqlDbType.VarChar); sp2.Value = (textBox2.Text);

SqlParameter sp3 = new SqlParameter("@m1", SqlDbType.Int); sp3.Value = int.Parse(textBox3.Text);

SqlParameter sp4 = new SqlParameter("@m2", SqlDbType.Int); sp4.Value = int.Parse(textBox4.Text);

SqlParameter sp5 = new SqlParameter("@m3", SqlDbType.Int); sp5.Value = int.Parse(textBox5.Text);

SqlParameter sp6 = new SqlParameter("@photo", SqlDbType.VarChar); sp6.Value = (textBox6.Text); com.Parameters.Clear(); com.Parameters.Add(sp1); com.Parameters.Add(sp2); com.Parameters.Add(sp3); com.Parameters.Add(sp4); com.Parameters.Add(sp5); com.Parameters.Add(sp6);

com.CommandText = "insert into student values(@rno,@sname,@m1,@m2,@m3,@photo)"; com.Connection = con; con.Open(); com.ExecuteNonQuery(); con.Close(); Response.Write("Record is added");

//com.CommandText = "update student set sname=@sname, m1=@m1, m2=@m2, m3=@m3, photo=@photo where rno=@rno";

//com.CommandText="delete from student where rno=@rno";

52

Page 53: asP.NET NOTES using c#

//com.CommandText="select * from student where rno=@rno";

Displaying data in GridView :

// type the below code inside class

SqlConnection con = new SqlConnection("data source=(local);initial catalog=2to3;integrated security=true"); SqlDataAdapter sda; DataSet ds = new DataSet(); // type the below code in button click event

sda = new SqlDataAdapter("select * from student", con);

sda.Fill(ds, "student1"); GridView1.DataSource = ds; GridView1.DataMember = "student1";

GridView1.DataBind();

//sda.Fill(ds, "student"); //GridView1.DataSource = ds.Tables["student"]; GridView1.DataBind();

//sda.Fill(ds); //GridView1.DataSource = ds.Tables[0]; GridView1.DataBind();

53

Page 54: asP.NET NOTES using c#

Displaying multiple tables in DataGridView :

// type the below code inside class

SqlConnection con = new SqlConnection("data source=LAB-387;initial catalog=2to3;integrated security=true"); SqlDataAdapter sda; DataSet ds = new DataSet();

// type the below code in button2 click event

GridView1.DataSource = ds.Tables["emp"]; GridView1.DataBind();

// type the below code in button1 click event

GridView1.DataSource = ds.Tables["student"]; GridView1.DataBind();

// in page load event

sda = new SqlDataAdapter("select * from student", con); sda.Fill(ds, "student");

sda = new SqlDataAdapter("select * from emp", con); sda.Fill(ds, "emp");

54

Page 55: asP.NET NOTES using c#

Displaying data in DropDownList / Listbox / RadioButtonList :

// type the below code inside class

SqlConnection con = new SqlConnection("data source=LAB-387;initial catalog=2to3;integrated security=true"); SqlDataAdapter sda; DataSet ds = new DataSet(); DataSet ds1 = new DataSet();

// in page load event

if (! Page.IsPostBack){ sda = new SqlDataAdapter("select * from student", con); sda.Fill(ds, "student");

DropDownList1.DataSource=ds.Tables[“student”];DropDownList1.DataTextField=”rno”;DropDownList1.DataValueField=”rno”;DropDownList1.DataBind();

ListBox1.DataSource=ds.Tables[“student”];ListBox1.DataTextField=”rno”;ListBox1.DataValueField=”rno”;ListBox1.DataBind();

RadioButtonList1.DataSource=ds.Tables[“student”];RadioButtonList1.DataTextField=”rno”;RadioButtonList1.DataValueField=”rno”;RadioButtonList1.DataBind();

}

// type the below in DropDownListSelectedIndexChanged event :

try{ int r = int.Parse(DropDownList1.SelectedItem.ToString());

string qry = "select * from student where rno=" + r; ds1.Clear(); sda = new SqlDataAdapter(qry, con); sda.Fill(ds1); Label1.Text = ds1.Tables[0].Rows[0].ItemArray[1].ToString(); Image1.ImageUrl= ds1.Tables[0].Rows[0].ItemArray[5].ToString();

}catch (Exception e1){ }

// type the below in ListBoxSelectedIndexChanged event :

try

55

Page 56: asP.NET NOTES using c#

{ int r = int.Parse(ListBox1.SelectedItem.ToString());

string qry = "select * from student where rno=" + r; ds1.Clear(); sda = new SqlDataAdapter(qry, con); sda.Fill(ds1); Label1.Text = ds1.Tables[0].Rows[0].ItemArray[1].ToString(); Image1.ImageUrl= ds1.Tables[0].Rows[0].ItemArray[5].ToString();

}catch (Exception e1){ }

// type the below in RadioButtonListSelectedIndexChanged event :

try{ int r = int.Parse(RadioButtonList1.Text);

qry = "select * from student where rno=" + r; ds1.Clear(); sda = new SqlDataAdapter(qry, con); sda.Fill(ds1); Label1.Text = ds1.Tables[0].Rows[0].ItemArray[1].ToString(); Image1.ImageUrl= ds1.Tables[0].Rows[0].ItemArray[5].ToString();

}catch (Exception e1){ }

Displaying data in CheckboxList :

// type the below code inside class

SqlConnection con = new SqlConnection("data source=LAB-387;initial catalog=2to3;integrated security=true"); SqlDataAdapter sda; DataSet ds = new DataSet();

// in page load event

if (! Page.IsPostBack){ sda = new SqlDataAdapter("select * from student", con); sda.Fill(ds, "student");

CheckBoxList1.DataSource=ds.Tables[“student”];CheckBoxList1.DataTextField=”rno”;CheckBoxList1.DataValueField=”rno”;CheckBoxList1.DataBind();

}

// type in button click event

56

Page 57: asP.NET NOTES using c#

string s1=””,s2=””,s3;for (int i=0;i<CheckBoxList1.Items.Count;i++){

if (CheckBoxList1.Items[i].Selected)s1=s1+”’”+CheckBoxList1.Items[i].Text+”’”+”,”; // if strings1=s1+CheckBoxList1.Items[i].Text+”,”; // if numeric

}

int l=s1.length;s2=s1.Substring(0,l-1);s3=”select * from student where rno in (“+s2+”)”;Response.Write(“s1=”+s1);Response.Write(“<br>s2=”+s2);Response.Write(“<br>s3=”+s3);SqlDataAdapter sda1=new SqlDataAdapter(s3,con);DataSet ds1=new DataSet();sda1.fill(ds1);GridView1.DataSource = ds1.Tables[0];GridView1.DataBind();

Displaying Records one by one :

57

Page 58: asP.NET NOTES using c#

// type the below code in class

SqlConnection con = new SqlConnection("data source=LAB-387;initial catalog=2to3;integrated security=true"); SqlDataAdapter sda; DataSet ds = new DataSet(); int cr, tr;

// in page load event

if (! Page.IsPostBack){ Session[“cr”] = 0;}

sda = new SqlDataAdapter("select * from student", con); sda.Fill(ds); Session[“tr”] = ds.Tables[0].Rows.Count - 1;

public void display() {

cr=Convert.ToInt32(Session[“cr”]); Label1.Text = ds.Tables[0].Rows[cr].ItemArray[0].ToString();

Label2.Text= ds.Tables[0].Rows[cr].ItemArray[1].ToString(); }

// first private void button1_Click(object sender, EventArgs e) { Session[“cr”] = 0; display(); }

// last private void button3_Click(object sender, EventArgs e) { Session[“cr”] = Session[“tr”]; display(); }

// next private void button2_Click(object sender, EventArgs e) {

cr=Convert.ToInt32(Session[“cr”]); cr = cr + 1;

Session[“cr”]=cr; tr=Convert.ToInt32(Session[“tr”]);

if (cr > tr) Session[“cr”] = 0; display(); }

58

Page 59: asP.NET NOTES using c#

// previous private void button4_Click(object sender, EventArgs e) {

cr=Convert.ToInt32(Session[“cr”]); cr = cr - 1;

Session[“cr”]=cr; if (cr < 0) Session[“cr”] = Session[“tr”]/0; display(); } }}

Calling Stored Procedures of SQL Server from .NET

Retriving total no. of rows based on particular data :

-- stored procedure for counting total no. of records according to a given condition

create procedure sp11 @a int, @b int outputasbeginselect @b=m1+m2+m3 from student where rno=@a end

// button click event coding :

SqlConnection con = new SqlConnection("Data Source=lab-387;integrated Security=true;initial catalog=2to3");

59

Page 60: asP.NET NOTES using c#

SqlCommand testCMD = new SqlCommand("sp11",con);

testCMD.CommandType = CommandType.StoredProcedure; testCMD.Parameters.Clear();

SqlParameter sp1 = testCMD.Parameters.Add("@a", SqlDbType.Int); sp1.Direction = ParameterDirection.Input;

SqlParameter sp2 = testCMD.Parameters.Add("@b", SqlDbType.Int); sp2.Direction = ParameterDirection.Output;

sp1.Value=Convert.ToInt32(textBox1.Text);

con.Open(); SqlDataReader myReader = testCMD.ExecuteReader(); myReader.Close(); textBox2.Text=sp2.Value.ToString(); con.Close();

Inserting data in table thru Stored Procedure

create procedure insertdata @a int, @b varchar(50), @c int, @d int, @e int, @f varchar(500)as begininsert into student values (@a,@b,@c,@d,@e,@f)end

// type the below code in button click event : SqlConnection con = new SqlConnection("Data Source=lab-387;integrated Security=true;initial catalog=2to3"); SqlCommand testCMD = new SqlCommand("insertdata", con); testCMD.CommandType = CommandType.StoredProcedure;

testCMD.Parameters.Clear(); SqlParameter p1 = testCMD.Parameters.Add("@a", SqlDbType.Int); p1.Direction = ParameterDirection.Input; SqlParameter p2 = testCMD.Parameters.Add("@b", SqlDbType.VarChar);

60

Page 61: asP.NET NOTES using c#

p2.Direction = ParameterDirection.Input; SqlParameter p3= testCMD.Parameters.Add("@c", SqlDbType.Char); p3.Direction = ParameterDirection.Input; SqlParameter p4 = testCMD.Parameters.Add("@d", SqlDbType.VarChar); p4.Direction = ParameterDirection.Input; SqlParameter p5= testCMD.Parameters.Add("@e", SqlDbType.Int); p5.Direction = ParameterDirection.Input; SqlParameter p6 = testCMD.Parameters.Add("@f", SqlDbType.Int); p6.Direction = ParameterDirection.Input; SqlParameter p7 = testCMD.Parameters.Add("@f", SqlDbType.Int); P7.Direction = ParameterDirection.Input; SqlParameter p8 = testCMD.Parameters.Add("@g", SqlDbType.VarChar); P8.Direction = ParameterDirection.Input; SqlParameter p9 = testCMD.Parameters.Add("@h", SqlDbType.VarChar); p9.Direction = ParameterDirection.Input; SqlParameter p10 = testCMD.Parameters.Add("@i", SqlDbType.VarChar); P10.Direction = ParameterDirection.Input; p1.Value = Convert.ToInt32 (textBox1.Text); p2.Value = (textBox2.Text); p3.Value = (textBox3.Text); p4.Value = (textBox4.Text); p5.Value = Convert.ToInt32 (textBox5.Text); p6.Value = Convert.ToInt32 (textBox6.Text); p7.Value = Convert.ToInt32 (textBox7.Text); p8.Value = (textBox8.Text); p9.Value = (textBox9.Text); p10.Value = (textBox10.Text); con.Open(); testCMD.ExecuteNonQuery(); Response.Write("Record added"); con.Close();

Storing Data of table in XML file

XML stands for Extensible Markup Language. It is completely in tag based format like html. It is the most widely used format for data interchange. The structure of XML file is as below :

<?xml version=”1.0” standalone=”Yes”><NewDataSet><Table><colname>data</colname><colname>data</colname><colname>data</colname></Table><Table><colname>data</colname><colname>data</colname><colname>data</colname></Table></NewDataSet>

61

Page 62: asP.NET NOTES using c#

// type inside the class SqlConnection con = new SqlConnection("data source=lab-387;initial catalog=2to3;integrated security=true"); SqlDataAdapter sda; DataSet ds = new DataSet();

private void Page_Load(object sender, EventArgs e) { sda = new SqlDataAdapter("select * from student", con); sda.Fill(ds); ds.WriteXml(“d:\\table1.xml”); }

Reading Data from XML file and displaying in DataGridView

// type inside the class DataSet ds = new DataSet(); private void Page_Load(object sender, EventArgs e) {

ds.ReadXml(“d:\\table1.xml”); GridView1.DataSource=ds.Tables[0]; Gridview1.DataBind(); }

Implementing Transactions

Group of sql statements is called Transaction. If you want to execute set of sql statements at a time we have to implement transactions. Thru transactions we can find out whether all the queries executed or not. If all the queries successfully execute the transaction is said to be completed and it is committed, otherwise it is rolled back to previous state.

1) Create objects of SqlConnection, SqlCommand.2) Declare object of SqlTransaction class.3) Create object of SqlTransaction class using SqlConnection class object by calling

its BeginTransaction() method.4) Specify SqlTransaction class object to SqlCommand Transaction property.5) Execute the queries.6) If any error occurs then call rollback() or call commit() of SqlTransaction class.7) Close the connection.

62

Page 63: asP.NET NOTES using c#

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Data.SqlClient;namespace transactions{

public partial class Form1 : Form { public Form1() { InitializeComponent(); } SqlConnection con=new SqlConnection("Data Source=home-1;initial catalog=pubs;integrated security=true"); SqlCommand cmd = new SqlCommand();

63

Page 64: asP.NET NOTES using c#

SqlTransaction st; private void button1_Click(object sender, EventArgs e) { try { con.Open(); cmd.Connection = con; st = con.BeginTransaction(); cmd.Transaction = st;

// 1st query cmd.CommandText = "insert into student values(1,'sekhar',55,66,77,’abc.jpg’)"; cmd.ExecuteNonQuery();

// 2nd query cmd.CommandText = "insert into student values('sekhar',2,55,66,77,’bb.jpg’)"; cmd.ExecuteNonQuery();

st.Commit(); Response.Write("Data is inserted successfully"); } catch (Exception e1) { Response.Write("Error occurred"); st.Rollback(); } con.Close(); } }}

Crystal Report

It is used to generate reports which can be printed on paper.

1) Click on Project->Add New Item->Reporting->Click on Crystal Report icon->Add.2) It will display Crystal Report Gallery->Select Using the Report Wizard->Ok.3) Expand Create New Connection->Expand OLEDB ADO->Select Microsoft

OLEDB Provider for SQL Server->Next->Type or select Server Name, Database name, Usr name, Password or Click on Integrated Security->Next->Finish.

4) Expand Database, dbo, tables->Click on your tablename->Click on > icon->Next.5) Selecting Fields->Expand tablename->Click on Fieldname and > icon->Next.6) Grouping option->Click on col.name and > icon on which you want group data-

>Select ascending/descending order->Next.7) If grouping is done, it displays automatically summary fields using numeric

columns available in your table.8) Select which groups to be displayed (Top/Bottom) or select None->Next.9) Chart options->Click on type of chart you require->Next.10) Subset options->Next.11) Select report style->Finish.12) The report will be created, by clicking on Main Report Viewer you can see the

output of the crystal report.

64

Page 65: asP.NET NOTES using c#

13)You can modify the crystal report contents according to your requirement.

Displaying the Crystal Report created on Form :

1) Add a new form.2) Take CrystalReportViewer control from Reporting tab.3) Set ReportSource property by specifying the complete path.4) Call the Show() method of CrystalReportViewer.

private void Form1_Load(object sender, EventArgs e){//Showing all the records of table

crystalReportViewer1.ReportSource = "d:\\juhi\\windowsformsapplication3\\crystalreport1.rpt";crystalReportViewer1.Show();

CrystalReport1 cr=new CrystalReport1();crystalReportViewer1.ReportSource =cr;crystalReportViewer1.Show(); }

Displaying required records thru crystal report :

1) Create CrystalReport in normal way by specifying database, table etc.2) Take 1 textbox, button, crystalreportviewer control.3) In the button click event get data from database table using sqldataadapter, fill it

in dataset object, create object of crystalreport2, set datasource of crystalreport object to the table which is filled in dataset object, give crystalreport object as crystalreportviewer source.

private void button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=LAB-387;Integrated Security=True;Initial Catalog=mk"); SqlDataAdapter sda=new SqlDataAdapter("select * from category where catid="+int.Parse(textBox1.Text),con); DataSet ds = new DataSet(); sda.Fill(ds); CrystalReport1 cr = new CrystalReport1(); cr.SetDataSource(ds.Tables[0]); crystalReportViewer1.ReportSource = cr; }

65

Page 66: asP.NET NOTES using c#

Storing connection string in web.config file and reading :

1) Search <connectionStrings/> tag and replace with the below :

<connectionStrings> <add name="cs1" connectionString="data source=(local); initial catalog=adventureworks;integrated security=true"/> </connectionStrings>

2) In the program read connectionstring contents :

protected void Button1_Click(object sender, EventArgs e) { string cs = ConfigurationManager.ConnectionStrings["cs1"].ToString(); SqlConnection con = new SqlConnection(cs);

SqlDataAdapter sda = new SqlDataAdapter("select * from humanresources.employee", con);

DataSet ds = new DataSet(); sda.Fill(ds); GridView1.DataSource = ds.Tables[0]; GridView1.DataBind();

}

66