Asp.Net

Embed Size (px)

DESCRIPTION

Asp.NetAsp.NetAsp.NetAsp.NetAsp.NetAsp.Net

Citation preview

Benefits of ASP.NET

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:

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\wwwroot

Two 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.

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 cant 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

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

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 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.

We can also insert a ready-made table in the form which looks like a frame(No Border).A hyperlink can be included. Its 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. concourse

FileUpLoad

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

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";t1.Style["position"] = "absolute"; t1.Style["top"] = 300px; t1.Style["left"] = 200px; PlaceHolder1.Controls.Add(t1);

We cant 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.

Follow.jpg http://www.rediff.com Rediff 100 autumn.jpg http://www.Google.com Google 50 Ascent.jpg http://www.yahoo.com yahoo 10

Calendar controlTo display calendar.

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

Single Date :

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 = "
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.

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.

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

function test(source,args) if (args.value=10) then args.IsValid=trueelseargs.IsValid=falseend if end function

Also we can write the code in the CustomValidator_ServerValidate event. At that time dont 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; } 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 urls 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).

Also we can specify SiteMap as Data Source for treeview. For this create a web.sitemap enter all the urls 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);

// 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 urls, titles of the pages available in your web site. Using this urls, titiles 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 :

Style 2 :

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

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

2 | Page