Download presentation
Presentation is loading. Please wait.
1
Dynamic Web Pages with ASP.NET
UNIT - IV Dynamic Web Pages with ASP.NET Web Based Application Development on .NET
2
Main Characteristics of ASP.NET
What is ASP .Net? 1. ASP.NET has better language support, a large set of new controls, XML-based components, and better user authentication. 2. ASP.NET provides increased performance by running compiled code. 3. ASP.NET code is not fully backward compatible with ASP. Main Characteristics of ASP.NET Successor of Active Server Pages (ASP), object-oriented event-based allows rapid application development (RAD) rich library of GUI elements (web controls) users can define their own GUI elements separation of layout (HTML) and logic (C#) efficient (compiled server scripts) automatic state management authorisation / authentication
3
Differences between ASP and ASP.Net
ASP.NET can be written in several .NET compliant languages like C#, VB.NET and business logic can be clearly separated from Presentation logic. ASP is mostly written using VB Script and HTML intermixed. Presentation and business logic is intermixed ASP.NET using .NET framework classes which has more than 2000 in built classes. ASP had maximum of 4 built in classes like Request, Response, Session and Application ASP.NET offers several server based components like Button, TextBox etc. and event driven processing can be done at server. ASP does not have any server based components ASP.NET supports Page level transactions. ASP did not support Page level transactions ASP.NET offers web development for mobile devices which alters the content type (wml or chtml etc) based on the device. ASP does not development for the mobile devices. ASP.NET uses languages which are fully object oriented languages like c# and also supports cross language support. ASP uses languages which are partially object oriented languages. ASP.NET offers support for Web Services and rich data structures like DataSet which allows disconnected data processing. ASP offers only support for ADO, so smaller data structure like Row Set which allows Connected data processing ASP.NET is the Compiler Translator. Such as VB.Net, C#, J#, etc ASP is the Interpreter Translator. Such as VBScript and JScript
4
What is Web Application?
A web application is any application that uses a web browser as a client. The application can be as simple as a message board or a guest sign-in book on a website, or as complex as a word processor or a spreadsheet. What are the benefits of a web application? 1. A web application relieves the developer of the responsibility of building a client for a specific type of computer or a specific operating system. Since the client runs in a web browser, the user could be using an IBM-compatible or a Mac. 2. They can be running Windows XP or Windows Vista. They can even be using Internet Explorer or Firefox, though some applications require a specific web browser. 3. Web applications commonly use a combination of server-side script (ASP, PHP, etc) and client-side script (HTML, Javascript, etc.) to develop the application. 4. The client-side script deals with the presentation of the information while the server side script deals with all the hard stuff like storing and retrieving the information.
5
What is purpose of the Web forms?
What is Web form? 1. Web Forms are the heart and soul of ASP.NET. 2. Web Forms are the User Interface (UI) elements that give your Web applications their look and feel. 3. Web Forms are similar to Windows Forms in that they provide properties, methods, and events for the controls that are placed onto them. 4. However, these UI elements render themselves in the appropriate markup language required by the request, e.g. HTML. 5. If you use Microsoft Visual Studio® .NET, you will also get the familiar drag-and- drop interface used to create your UI for your Web application. What is purpose of the Web forms? Web Forms and ASP.NET were created to overcome some of the limitations of ASP. These new strengths include: Separation of HTML interface from application logic A rich set of server-side controls that can detect the browser and send out appropriate markup language such as HTML
6
What are the three types of ASP. Net Control?
Less code to write due to the data binding capabilities of the new server-side .NET controls Event-based programming model that is familiar to Microsoft Visual Basic® programmers Compiled code and support for multiple languages, as opposed to ASP which was interpreted as Microsoft Visual Basic Scripting (VBScript) or Microsoft Jscript® Allows third parties to create controls that provide additional functionality What are the three types of ASP. Net Control? 1. HTML Controls 2. Server Side Controls 3. Validation Server Side Controls.
7
What are the uses of Server side Control?
1. In ASP.Net you have server side controls apart from the ordinary html controls that are used in the web page. 2. The server side controls are executed on the server and they have an attribute runat=”server”. 3. This attribute that is found in the control indicates that it is a server side control. 4. By using the object oriented programming model of the server side control you can even create complex server side controls. 5. They have rich set of properties, methods, and events.
8
What are the Html Controls Available in ASP.Net
Description Web Form Code Example Button A normal button that you can use to respond to Click events <input type=button runat=server> Reset Button Resets all other HTML form elements on a form to a default value <input type=reset runat=server> Submit Button Automatically POSTs the form data to the specified page listed in the Action = attribute in the FORM tag <inpu type=sumit runat=server> Text Field Gives the user an input area on an HTML form <input type=text runat=server> Text Area Used for multi –line input on an HTML form <input type=textarea runat=server> Password Field An input area on an HTML form, although any character typed into this field are displayed as asterisks <input type=password runat=server> CheckBox Gives the user a check box that they can select or clear <input type=checkbox runat=server> Radio Button Used two or more to a form, and allows the user to choose one of the controls <input type=radio runat=server> Table Allows you to present information in a tabular format <table runat=server></table>
9
Commonly Used Server – Side Events
Control Description Web Form Code Example Image Displays an image on an HTML form <img src=“FileName” runat=server> ListBox Displays a list of items to the user, You can set the size from two or more to specify how many items you wish show. If there are more items that will fit within this limit, a scroll bar is automatically assed to this control. <select size=2 runat=server></select> Dropdown Displays a list of items to the user, but only one item at a time will appear. The user can click a down arrow from the side of this control and a list of items will be displayed. <select><option></option></select> Horizontal Rule Displays a horizontal line across the HTML page. <hr> 2. What are the Server side Controls used ASP .Net and Web forms? Control Description Commonly Used Server – Side Events Web Form Code Example Label Displays text on the HTML page None <asp:Lable id=Label1 runat=“server”>Label</asp:Label> TextBox Gives the user an input area on an HTML form TextChanged <asp:TextBox id=TextBox1 runat=“server”></asp:TextBox>
10
Commonly Used Server – Side Events
Control Description Commonly Used Server – Side Events Web Form Code Example Button A normal button control used to respond to click events on the server. You are allowed to pass additional information by setting the CommandName and CommandArguments properties Click, Command <asp:Button id=Button1 runat=“server” Text=“Button”></asp:Button> LinkButton Like a button in that it posts back to a server, but the button looks like a hyperlink <asp:LinkButton id=LinkButton1 runat=“server”>LinkButton</asp:LinkButton> ImageButton Can display a graphical image, and when clicked, posts back to the server command information such as the mouse coordinates within the image when clicked Click <asp:ImageButton id=ImageButton1 runat=“server”></asp:ImageButton> Hyperlink A normal hyperlink control that responds to a click event None <asp:HyperLink id=HyperLink1 runat=“server”>HyperLink</asp:HyperLink> DropDownList A normal dropdown list control like the HTML control, but can be data bound to a data source SelectedIndexChanged <asp:DropDownList id=DropDownList1 runat=“server”></asp:DropDownList>
11
Commonly Used Server – Side Events
Control Description Commonly Used Server – Side Events Web Form Code Example ListBox A normal ListBox control like the HTML control, but can be data bound to a data source SelectedIndexChanged <asp:ListBox id=ListBox1 runat=“server”></asp:ListBox> DataGrid Like a <Table>, you bind a data source to this control and it displays all of the column information you can also perform paging, sorting, and formatting very easily with this control. CancelCommand, EditCommand, DeleteCommand, ItemCommand, SelectedIndexChanged, PageIndexChanged, SortCommand, UpdateCommand, ItemCreated ItemDataBound <asp:DataGrid id=DataGrid1 runat=“server”></asp:DataGrid> DataList Allows you to create a not – tabular type of format for data. You can bind the data to template items, which are like bits of HTML put together in a specific repeating format. CancelCommand, EditCommand, DeleteCommand, ItemCommand, SelectedIndexChanged, UpdateCommand, ItemCreated, ItemDataBound <asp:DataList id=DataList1 runat=“server”></asp:DataList> Repeater Allows you to create a non – tabular type of format for data. You can bind the data to template items, which are like bits of HTML put together in a specific repeating format. ItemCommand, ItemCreated, ItemDataBound <asp:Repeater id=Repeater1 runat=“server></asp:Repeater>
12
Commonly Used Server – Side Events
Control Description Commonly Used Server – Side Events Web Form Code Example CheckBox Very Similar to the normal HTML Control CheckChanged <asp:Checkbox id=CheckBox1 runat=“server”></sp:Checkbox> CheckBoxList Displays a group of check boxes that all work together SelectedIndexChanged <asp:CheckBoxList id=CheckBoxList1 runat=“server”></asp:CheckBoxList> RadioButton Very Similar to the normal HTML control that displays a button for the user to check or uncheck <asp:RadioButton id=RadioButton1 runat=“server”></asp:RadioButton> RadioButtonList Displays a group radio button controls that all work together <asp:RadioButtonList id=RadioButtonList1 runat=“server”></asp:RadioButtonList> Image Very Similar to the normal HTML control that displays an image within the page None <asp:Image id=Image1 runat=“server”></asp:Image> Panel Used to group other controls <asp:Panel id=Panel1 runat=“server”>Panel</asp:Panel> PlaceHolder Acts as a Location where you can dynamically add other server – side controls at run time <asp:PlaceHolder id=“PlaceHolder1” runat=“server”></asp:PlaceHolder> Calendar Creates an HTML version of a calendar you can set the default date, Move forward and backward through the calendar SelectionChanged, VisibleMonthChanged, DayRender <asp:Calendar id=Calendar1 runat=“server”></asp:Calendar>
13
Commonly Used Server – Side Events
Control Description Commonly Used Server – Side Events Web Form Code Example AdRotator Allows you to specify a list of ads to display, Each time the user re-displays the page, the display rotates through the series of ads/ AdCreated <asp:AdRotator id=AdRotator1 runat=“server”></asp:AdRotator> Table Very Similar to the normal HTML Control None <asp:Table id=Table1 runat=“server”></asp:Table> XML Used to display XML documents within the HTML, It can also be used to perform an XSLT transform prior to displaying the XML <asp:Xml id=“Xml1 runat=“server”></asp:Xml> Literal Like a label in that it displays a literal, but allows you to create new literals at runtime and place them into this control <asp:Literal id=“Literal1” runat=“server”></asp:Literal>
14
What are the five types of the ASP.Net Validation Controls?
1. RequiredField Validation control 2. Range Validation control 3. Comparison Validation control 4. RegularExpression Validation control 5. Custom Validation control Postback versus nonpostback events Postback events are those that cause the form to be posted back to the server immediately. These include click – type events, such as the Button Click event. Many Events are considered nonpostback in that form isn’t poseted back to the server immediately. Instead, these events are cached by the control unit the next time a postback event occurs.
15
Web Form Life Cycle Every request for a page made to a web server cause a chain of events at the server. These events, from beginning to end, constitute the life cycle of the page and all its components. The life cycle begins with a request for the page, which caused the server to load it. When the request is complete, the page is unloaded Form one end of the life cycle to the other, the goal is to render appropriate HTML output back to the requesting browser; The life cycle of a page is marked by the following event. 1. Initialize 2. Load ViewState 3. Process Postback Data 4. Load 5. PreRender 6. Render 7. Dispose
16
Initialize Initialize is the first phase in the life cycle for any page or control. It is here that any settings needed for the duration of the incoming request are initialized. 2. Load ViewState The ViewState property of the control is populated, The View State information comes from hidden variable on the control, used to persist the state across round trips to the server. The input string from this hidden variable is parsed by the page framework, and the ViewState property is set. This can be modified via the LoadViewState() method. 3. Process Postback Data During this phase, the data sent to the server in the posing is processed. If any of this data results in a requirement to update the ViewState, the update is performed via the LoadPostData() method.
17
4. Load CreateChildControls() is called, if necessary, to create an initialize server controls in the control tree. State is restored, and the form controls contain client side data, You can modify the load phase by handling the load event with the OnLoad() method. 5. PreRender This is you last change to modify the output prior to rendering using the OnPreRender() method. 6. Render This is where the output to be sent back to the client browser is generated, you can orverride it using the Render method. CreateChildControls() is called, if necessary, to create and initialize server controls in the control tree. 7. Dispose This is the last phase of the life cycle. It gives you an opportunity to do any final cleanup and release references to any expensive resources, such as database connection. You can modify it using the Displose() method.
18
WEB FORM LIFE CYCLE – PROGRAM IMPLEMENTATION
Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Create_Controls.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server" oninit ="On_Init" onload ="On_Load" onclick ="On_Click" onprerender ="On_Prerender" ondisposed ="On_Disposed"> </form> </body> </html> using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Create_Controls { public partial class WebForm1 : System.Web.UI.Page protected void On_Init(object sender, EventArgs e) Response.Write("Initialize the Web Form"); }
19
protected void On_Load(object sender, EventArgs e)
{ Response.Write("Loading the Web Form"); } protected void On_Click(object sender, EventArgs e) Response.Write("Clicking the Web Form"); protected void On_Prerender(object sender, EventArgs e) Response.Write("Pre - Rendering the Web Form"); protected void On_Disposed(object sender, EventArgs e) Response.Write("Disposed the Web Form");
20
Static Web Pages My.html Server Browser (IIS) Pure HTML <html>
<head> <title>Simple HTML page</title> </head> <body> <h1>Welcome</h1> You are visitor number 1! </body> </html> My.html Browser Server (IIS) Request("My.html") Response(My.html) My.html
21
Dynamic ASPX Pages Counter.aspx <%@ Page Language="C#" %>
Import Namespace="System" %> <html> <head> <title>Page counter</title> </head> <body> <h1>Welcome</h1> You are visitor number <% int i = 6; Response.Write(n); %> ! </body> </html>
22
What Happens Behind the Scene?
client (browser) server (IIS) request ("Counter.aspx") .NET framework response (*.html) *.html page class preprocessor, compiler loader page object Counter.aspx "Counter.aspx" ASP .NET
23
Code in Script Tags Counter.aspx <%@ Page Language="C#" %>
Import Namespace="System" %> <html> <head> <title>Page counter</title> <script Language="C#" Runat="Server"> int CounterValue() { int n = 10; retrun n; } </script> </head> <body> <h1>Welcome</h1> You are visitor number <%=CounterValue()%> ! </body> </html> Counter.aspx short form for Response.Write(CounterValue());
24
Code Behind Counter.aspx CounterPage.cs
Page Language="C#" Inherits="CounterPage" CodeFile="CounterPage.cs" %> <html> <head> <title>Page counter</title> </head> <body> <h1>Welcome</h1> You are visitor number <%=CounterValue()%> ! </body> </html> public partial class CounterPage : System.Web.UI.Page { public int CounterValue() int n = 10; } CounterPage.cs
25
Web Forms in ASP.NET Adder.aspx
Page Language="C#" Inherits="AdderPage" CodeFile="Adder.aspx.cs"%> <html> <head> <title>Account</title> </head> <body> <form Runat="server"> <b>Balance:</b> <asp:Label ID="total" Text="0" Runat="server"/> Euro<br><br> <asp:TextBox ID="amount" Runat="server"/> <asp:Button ID="ok" Text="Enter" Runat="server" /> </form> </body> </html> Adder.aspx.cs using System; public partial class AdderPage : System.Web.UI.Page { public void ButtonClick (object sender, EventArgs e) { int totalVal = Convert.ToInt32(total.Text); int amountVal = Convert.ToInt32(amount.Text); total.Text = (totalVal + amountVal).ToString(); }
26
General Notation for Web Controls
<asp:ClassName PropertyName="value" ... Runat="server" /> Example <asp:Label ID="total" Text="Hello" ForeColor="Red" Runat="server" /> All web control classes are in the namespace System.Web.UI Alternative Notation <asp:Label ID="total" ForeColor="Red" Runat="server" > Hello </asp:Label>
27
Advantages of Web Forms
The page is an object one can access all its properties and methods: page.IsPostBack, page.User, page.FindControl(), ... All GUI elements are objects one can access all their properties and methods: amount.Text, amount.Font, amount.Width, ... One can implement custom GUI elements Web pages can access the whole .NET library databases, XML, RMI, ... The state of all GUI elements is retained amount.Text does not need to be set before the page is sent back
28
Kinds of Events Control Event When does the event occur? all Init Load
PreRender Unload after the control was created after the data that were sent by the browser have been loaded into the control before HTML code for this control is generated before the control is removed from memory Button Click when the button was clicked TextBox TextChanged when the contents of the TextBox changed CheckBox CheckedChanged when the state of the CheckBox changed ListBox SelectedIndexChanged when a new item from the list has been selected
29
Round Trip of a Web Page Client Server round trip event Page
+ page state Label TextBox Click Button 1. Creation create page object and its controls Client Server
30
Round Trip of a Web Page Client Server round trip event Init Page
+ page state Label Init TextBox Init Click Button Init 2. Initialisation - raise Init events Client Server
31
Round Trip of a Web Page Client Server round trip event Page
3. Loading - load controls with the values that the user has entered (page state) - raise Load events Load Click round trip event + page state Page Label TextBox Button
32
Round Trip of a Web Page Client Server Page Label TextBox Button
4. Action handle event(s) (Click, TextChanged, ...) Client Server
33
Round Trip of a Web Page Client Server PreRender Page Label PreRender
TextBox PreRender HTML <html> ... <input type="text" ...> <input type="button" ...> </html> Button PreRender + page state 5. Rendering - raise PreRender events - call Render methods of all controls, which render the controls to HTML Client Server
34
Round Trip of a Web Page Client Server Unload Page Label Unload
TextBox Unload <html> ... <input type="text" ...> <input type="button" ...> </html> Button Unload 6. Unloading - raise Unload events for cleanup actions Client Server
35
EVENT HANDLING LIFE CYCLE – PROGRAM IMPLEMENTATION
Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Create_Controls.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" <head runat="server"> <title>Event Handling Life Cycle</title> </head> <body> <form id="form1" runat="server"> <asp:Button ID="Button1" Text ="Click Here" runat ="server" OnInit ="Button1_Init" OnLoad ="Button1_Load" OnClick ="Button1_Click" OnPreRender ="Button1_Prerender" OnUnload ="Button1_Unload" /> </form> </body> </html>
36
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Create_Controls { public partial class WebForm1 : System.Web.UI.Page protected void Button1_Init(object sender, EventArgs e) Response.Write("Initialize the Button "); } protected void Button1_Load(object sender, EventArgs e) Response.Write("Loading the Button "); protected void Button1_Click(object sender, EventArgs e) Response.Write("Clicking the Button "); protected void Button1_Prerender(object sender, EventArgs e) Response.Write("Prerendering the Button "); protected void Button1_Unload(object sender, EventArgs e) Response.Write("Unloading the Button "); } } }
37
How to create the Event handling in different Web Controls
Button – OnClick( ) Default.aspx Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Create_Controls._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <asp:Button ID = "Button1" Text = "Click Here" runat ="server" OnClick ="Click_Button1" /> using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Create_Controls { public partial class _Default : System.Web.UI.Page protected void Click_Button1(object sender, EventArgs e) Response.Write("Welcome to CCET"); } } } Default.aspx.cs
38
TextBox – OnTextChanged( ) and Label – OnTextChanged( )
Default.aspx Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Create_Controls._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <asp:TextBox ID="Text1" text ="" runat ="server" OnTextChanged ="Text1_Changed" AutoPostBack ="true"></asp:TextBox> <asp:TextBox ID ="Text2" Text ="" runat ="server AutoPostBack ="true"></asp:TextBox> using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Create_Controls { public partial class _Default : System.Web.UI.Page protected void Text1_Changed(object sender, EventArgs e) Text2.Text = Text1.Text; } } }
39
Checkbox – OnCheckedChanged and Radiobutton - OnCheckedChanged
Default.aspx Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Create_Controls._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <asp:TextBox ID="Text1" Text="" runat ="server"></asp:TextBox><br /> <asp:CheckBox ID="Checkbox1" Text="Example Selected" runat ="server" OnCheckedChanged ="Checkbox_Changed" AutoPostBack ="true" /><br /> <asp:RadioButton ID="RadioButton1" Text ="Example Selected" runat ="server" OnCheckedChanged ="Radiobox_Changed" AutoPostBack ="true" /> Default.aspx.cs namespace Create_Controls { public partial class _Default : System.Web.UI.Page protected void Checkbox_Changed(object sender, EventArgs e) Text1.Text = "Selected Checkbox"; } protected void Radiobox_Changed(object sender, EventArgs e) Text1.Text = "Selected Radio Button";
40
ListBox – OnSelectedIndexChanged() and DropDownList – OnSelectedIndexChanged()
Default.aspx Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Create_Controls._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <asp:TextBox ID="Text1" Text="" runat ="server"></asp:TextBox><br /> <asp:ListBox ID="Listbox1" runat ="server" OnSelectedIndexChanged ="List1_Selected" AutoPostBack ="true"> <asp:ListItem Text="IN" Value ="India"></asp:ListItem> <asp:ListItem Text="USA" Value ="United States America"></asp:ListItem> <asp:ListItem Text ="UK" Value ="United Kingdon"></asp:ListItem> </asp:ListBox><br /><br /> <asp:DropDownList ID="Listbox2" runat ="server" OnSelectedIndexChanged ="List2_Selected" AutoPostBack ="true"> <asp:ListItem Text ="In" Value ="India"></asp:ListItem> <asp:ListItem Text ="USA" Value ="United States of America"></asp:ListItem> <asp:ListItem Text ="UK" Value ="United Kingdom"></asp:ListItem> </asp:DropDownList> </asp:Content>
41
Default.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Create_Controls { public partial class _Default : System.Web.UI.Page protected void List1_Selected(object sender, EventArgs e) Text1.Text = Listbox1.SelectedItem.Text.ToString (); } protected void List2_Selected(object sender, EventArgs e) Text1.Text = Listbox2.SelectedItem.Text.ToString();
42
Calendar – OnSelectionChanged( )
Default.aspx Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Create_Controls._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <asp:TextBox ID ="Text1" runat ="server" Text =""></asp:TextBox> <asp:Calendar ID="Calendar1" runat ="server" OnSelectionChanged="Calendar1_Select"></asp:Calendar> Default.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Create_Controls { public partial class _Default : System.Web.UI.Page protected void Calendar1_Select(object sender, EventArgs e) Text1.Text = Calendar1.SelectedDate.ToString (); } } } }
43
How to Create the Web Controls in ASP. NET
Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Create_Controls._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <br /> <asp:Button ID = "Button1" Text ="Click Here" ForeColor ="Red" BackColor ="Green" runat ="server" /> <asp:Label ID = "Label1" Text ="Enter the Value" ForeColor ="Brown" BackColor ="Yellow" runat ="server"></asp:Label> <asp:TextBox ID = "Text1" Text ="Enter the Text Here" BackColor ="Yellow" ForeColor ="Red" runat ="server"></asp:TextBox> <asp:CheckBox ID = "Checkbox1" Text ="Add" runat ="server" /> <asp:RadioButton ID = "Radiobutton" Text = "Sub" runat ="server" /> <br /><br />
44
<asp:ListBox ID ="Listbox1" runat ="server">
<asp:ListItem Text ="In" Value ="India"></asp:ListItem> <asp:ListItem Text ="USA" Value ="Unitated States of America"></asp:ListItem> <asp:ListItem Text ="UK" Value ="Unitated Kingdom"></asp:ListItem> </asp:ListBox> <br /> <asp:DropDownList ID ="DropDwonList1" runat ="server"> <asp:ListItem Text ="USA" Value ="Unitated States of Americal"></asp:ListItem> </asp:DropDownList> <asp:GridView ID ="Gridview1" runat ="server"></asp:GridView> <asp:Calendar ID ="Calendar" runat ="server"></asp:Calendar> </asp:Content>
45
Answer NOTE: ASP.NET Database application similar to the Windows Application
46
Addition of the Two Numbers using ASP .NET
Default.aspx Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" > <head runat="server"> <title>Create a Simple Web Application</title> </head> <body> <form id="form1" runat="server"> <div> <center><h1>Addition of the Two Numbers</h1></center> <asp:Label ID="label1" Text="Enter the A Value" runat ="server"></asp:Label> <asp:TextBox ID="text1" Text ="" runat ="server"></asp:TextBox><br /> <asp:Label ID="label2" Text="Enter the B Value" runat ="server"></asp:Label> <asp:TextBox ID="text2" Text ="" runat ="server"></asp:TextBox><br /> <asp:Label ID="label3" Text ="Addition of the Two Numbers" runat ="server"></asp:Label> <asp:TextBox ID="text3" Text="" runat ="server" ></asp:TextBox> <asp:Button ID="button1" Text="Click Addition" runat ="server" OnClick="Button1_Click" /> </div> </form> </body> </html>
47
Output using System; Default.aspx.cs using System.Web;
using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) int a, b, c; a = int.Parse(text1.Text); b = int.Parse(text2.Text); c = a + b; text3.Text = c.ToString(); } Default.aspx.cs Output
48
Button (Command Event)
useful if multiple buttons on a page should be handled by the same event handler <form Runat="server"> <asp:Label ID="label" Text="100.00" Runat="server" /> <br><br> <asp:Button Text="+ 10%" CommandName="add" CommandArgument="0.1" OnCommand="DoCommand" Runat="server" /> <asp:Button Text="- 5%" CommandName="sub" CommandArgument="0.05" </form> public void DoCommand (object sender, CommandEventArgs e) { double total = Convert.ToDouble(label.Text); if (e.CommandName == "add") total += total * Convert.ToDouble(e.CommandArgument); else if (e.CommandName == "sub") total -= total * Convert.ToDouble(e.CommandArgument); label.Text = total.ToString("f2"); }
49
Class TextBox Class CheckBox
<asp:TextBox Text="sample" Runat="server" /> <asp:TextBox TextMode="Password" MaxLength="10" Runat="server" /> <asp:TextBox TextMode="MultiLine" Rows="2" Columns="15" Wrap="true" Runat="server" /> line 1 line 2 line 3 </asp:TextBox> Class CheckBox <form Runat="server"> <asp:CheckBox ID="apples" Text="Apples" Runat="server" /><br> <asp:CheckBox ID="pears" Text="Pears" Runat="server" /><br> <asp:CheckBox ID="bananas" Text="Bananas" Runat="server" /><br> <asp:Button Text="Buy" OnClick="DoClick" Runat="server" /> <br><br> <asp:Label ID="label" Runat="server" /> </form> void DoClick (object sender, EventArgs e) { label.Text = "You bought: "; if (apples.Checked) label.Text += "Apples "; if (pears.Checked) label.Text += "Pears "; if (bananas.Checked) label.Text += "Bananas "; }
50
Class RadioButton all radio buttons of the same group must have the same group name <form Runat="server"> <p>Select method of payment:</p> <asp:RadioButton ID="cash" Text="cash" GroupName="payment" OnCheckedChanged="RadioChanged" AutoPostBack="true" Runat="server" /><br> <asp:RadioButton ID="cheque" Text="cheque" GroupName="payment" <asp:RadioButton ID="card" Text="credit card" GroupName="payment" Runat="server" /><br><br> <asp:Label ID="label" Runat="server" /> </form> void RadioChanged (object sender, EventArgs e) { label.Text = "Method of payment: "; if (cash.Checked) label.Text += cash.Text; if (cheque.Checked) label.Text += cheque.Text; if (card.Checked) label.Text += card.Text; }
51
Class ListBox <form Runat="server">
<asp:ListBox ID="list" Rows="3" Runat="server" > <asp:ListItem Text="United States" Value="USA" Runat="server" /> <asp:ListItem Text="Great Britain" Value="GB" Runat="server" /> <asp:ListItem Text="Germany" Value="D" Runat="server" /> <asp:ListItem Text="France" Value="F" Runat="server" /> <asp:ListItem Text="Italy" Value="I" Runat="server" /> </asp:ListBox><br><br> <asp:Button OnClick="ButtonClick" Text="Show" Runat="server" /><br> <asp:Label ID="lab" Runat="server" /> </form> void ButtonClick (object sender, EventArgs e) { lab.Text = "The selected country has the international car code "; if (list.SelectedItem != null) lab.Text += list.SelectedItem.Value; }
52
ListBox (Dynamically Specified List)
<form Runat="server"> <asp:ListBox ID="list" Rows="3" AutoPostBack="true" OnSelectedIndexChanged="Show" Runat="server" /> <br><br> <asp:Button Text="Fill" OnClick="Fill" Runat="server" /> <br><br> <asp:Label ID="lab" Runat="server" /> </form> void Fill (object sender, EventArgs e) { SortedList data = new SortedList(); data["United States"] = "USA"; data["Great Britain"] = "GB"; data["France"] = "F"; data["Italy"] = "I"; list.DataSource = data; list.DataTextField = "Key"; // take the text from the Key property of the items list.DataValueField = "Value"; // take the value from the Value property of the items list.DataBind(); } void Show (object sender, EventArgs e) { lab.Text = "The selected country has the international car code "; if (list.SelectedItem != null) lab.Text += list.SelectedItem.Value;
53
ListBox (List Generated From a Database)
<form OnInit="PageInit" Runat="server"> <asp:ListBox ID="list" DataTextField="LastName" DataValueField="EmployeeID" OnSelectedIndexChanged="HandleSelect" AutoPostBack="true" Runat="server" /><br> <asp:Label ID="label" Runat="server" /> </form> public partial class BasePage : System.Web.UI.Page { public void PageInit (object sender, EventArgs e) DataSet ds = new DataSet(); SqlConnection con = new SqlConnection("data source=localhost\\SQLEXPRESS; initial catalog=Northwind; " + "persist security info=True; integrated security=True; pooling=False"); string cmdString = "SELECT * FROM Employees"; SqlDataAdapter adapter = new SqlDataAdapter(cmdString, con); adapter.Fill(ds, "Employees"); list.DataSource = ds.Tables["Employees"].DefaultView; list.DataBind(); } public void HandleSelect (object sender, EventArgs e) label.Text = "employee number = "; if (list.SelectedItem != null) label.Text += list.SelectedItem.Value;
54
Class DropDownList statically specified DropDownList
<form Runat="server"> <asp:DropDownList ID="list" OnSelectedIndexChanged="HandleSelect" AutoPostBack="true" Runat="server" > <asp:ListItem Text="United States" Value="USA" /> <asp:ListItem Text="Great Britain" Value="GB" /> <asp:ListItem Text="Germany" Value="D" /> <asp:ListItem Text="France" Value="F" /> <asp:ListItem Text="Italy" Value="I" /> </asp:DropDownList><br> <asp:Label ID="lab" Runat="server" /> </form> void HandleSelect (object sender, EventArgs e) { lab.Text = "The selected country has the international car code "; if (list.SelectedItem != null) lab.Text += list.SelectedItem.Value; } DropDownList can also be filled dynamically (like ListBox)
55
ASP.NET DataGrid Control
APNSoft DataGrid is an ASP.NET server control with AJAX support to display data in a tabular format with options of choice, sorting and editing entries. DataGrid component has been designed in a way to reduce development time at the utmost and require no specific knowledge from developers. You do not need to learn a complex API to accomplish a task; our Grid represents an obvious, easily understandable model - a set of columns and rows, and a set of options for their interaction. "Smart" component Our DataGrid component is a "Smart" one which loads data on demand, pages it, scrolls the list up to the selected entry, automatically displays scrollbars, saves its state after PostBack.
56
Processing speed Operates perfectly with tables, containing tens of thousands entries, loads data on demand, automatically checks loaded data in order to avoid extra requests by using client-side caching. AJAX Support Built-in AJAX support provides independence from additional components and frameworks. Data check Our component checks the state of data source and displays relevant data without reloading the page. Appearance APNSoft DataGrid is very flexible in customization. Skin support allows professional appearance to be easily created; there are ready-to-use skins. The form for editing entries can be configured by developer independently.
57
Flexible templates Flexible structure of templates allows combining data from different fields, processing conditional formatting and creating calculated columns. By using templates you can create complete integrated solutions on the basis of single DataGrid component. Data formatting Universal Multilanguage support allows formatting and displaying data in several languages simultaneously. Intuitive model APNSoft DataGrid represents an obvious, easily understandable model - a set of columns and rows, and a set of options for their interaction.
58
DataGrid (Simple Example)
<form OnInit="PageInit" Runat="server"> <asp:DataGrid ID="grid" Runat="server" /> </form> public partial class BasePage : System.Web.UI.Page { public void PageInit (object sender, EventArgs e) DataSet ds = new DataSet(); SqlConnection con = new SqlConnection("data source=localhost\\SQLEXPRESS; initial catalog=Northwind; " + "persist security info=True; integrated security=True; pooling=False"); string sqlString = "SELECT EmployeeID, FirstName, LastName FROM Employees"; SqlDataAdapter adapter = new SqlDataAdapter(sqlString, con); adapter.Fill(ds, "Employees"); grid.DataSource = ds.Tables["Employees"].DefaultView; grid.DataBind(); grid.HeaderStyle.Font.Bold = true; grid.AlternatingItemStyle.BackColor = System.Drawing.Color.LightGray; }
59
DataGrid (Example With ButtonColumn)
<form OnLoad="PageLoad" Runat="server"> <asp:DataGrid ID="grid" Runat="server“ AutoGenerateColumns="false“ CellPadding="3“ HeaderStyle-BackColor="#aaaadd“ AlternatingItemStyle-BackColor="LightGray“ OnDeleteCommand="DeleteRow“ OnSelectedIndexChanged="SelectRow" > <Columns> <asp:BoundColumn HeaderText="ID" DataField="EmployeeID"> <ItemStyle HorizontalAlign="Right" /> </asp:BoundColumn> <asp:BoundColumn HeaderText="First Name" DataField="FirstName" /> <asp:BoundColumn HeaderText="Last Name" DataField="LastName" /> <asp:ButtonColumn ButtonType="LinkButton" Text="delete" CommandName="Delete" /> <asp:ButtonColumn ButtonType="LinkButton" Text="select" CommandName="Select" /> </Columns> </asp:DataGrid><br> <asp:Label ID="label" Runat="server" /> </form>
60
DataGrid (Code Behind for the Previous Example)
public partial class BasePage: System.Web.UI.Page { DataView dataView; public void PageLoad (object sender, EventArgs e) DataSet ds; if (!IsPostBack) ... // load ds from the database Session["Data"] = ds; } else ds = (DataSet)Session["Data"]; dataView = ds.Tables["Employees"].DefaultView; grid.DataSource = dataView; grid.DataBind(); public void DeleteRow (object sender, DataGridCommandEventArgs e) dataView.Delete(e.Item.DataSetIndex); // deletes data only in the DataSet grid.DataSource = dataView; // but not in the database
61
public void SelectRow (object sender, EventArgs e)
{ grid.SelectedItemStyle.BackColor = System.Drawing.Color.Gray; label.Text = grid.SelectedItem.Cells[1].Text + " " + grid.SelectedItem.Cells[2].Text; }
62
WEB AUTHENTICATION
63
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default
Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <html xmlns=" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="Enter the User Name" Width="224px"></asp:Label> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /> <asp:Label ID="Label2" runat="server" Text="Enter the Password" Width="224px"></asp:Label> <asp:TextBox ID="TextBox2" runat="server" TextMode="Password" Width="152px"></asp:TextBox><br /> <br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" /> <asp:Button ID="Button2" runat="server" Text="Reset" /></div> </form> </body> </html> WebAuthentication.aspx
64
using System; using System.Data; using System.Data.OleDb; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { public OleDbConnection con; public OleDbCommand com; public OleDbDataAdapter adp; public OleDbDataReader rs; WebAuthentication.aspx.cs
65
protected void Page_Load(object sender, EventArgs e)
{ con = new OleDbConnection(); con.ConnectionString = "provider=Microsoft.JET.OLEDB.4.0; " + "data source = z:\\CSHARP\\STUD.mdb"; con.Open(); com = new OleDbCommand(); com.Connection = con; adp = new OleDbDataAdapter(com); Response.Write("Connection Successfully Established"); } protected void Button1_Click(object sender, EventArgs e) string s1 = "", s2 = ""; com.CommandText = "select * from MARK"; rs = com.ExecuteReader(); if (rs.Read()) s1 = rs.GetValue(0).ToString(); s2 = rs.GetValue(1).ToString();
66
if (TextBox1.Text.Equals(s1) && TextBox2.Text.Equals(s2))
{ this.Response.Redirect("Default2.aspx"); } else Response.Write("Invalid User name and Password");
67
Programming Web Services
68
What is Web Services? What are Web Services?
Web services are open standard ( XML, SOAP, HTTP etc.) based Web applications that interact with other web applications for the purpose of exchanging data Web Services can convert your existing applications into Web-applications. What are Web Services? Web services are XML-based information exchange systems that use the Internet for direct application-to-application interaction. These systems can include programs, objects, messages, or documents. A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards.
69
Components of Web Services
The basic Web services platform is XML + HTTP. All the standard Web Services works using following components SOAP (Simple Object Access Protocol) UDDI (Universal Description, Discovery and Integration) WSDL (Web Services Description Language) How Does it Work? You can build a Java-based Web Service on Solaris that is accessible from your Visual Basic program that runs on Windows. You can also use C# to build new Web Services on Windows that can be invoked from your Web application that is based on JavaServer Pages (JSP) and runs on Linux. An Example Consider a simple account-management and order -processing system. The accounting personnel use a client application built with Visual Basic or JSP to create new accounts and enter new customer orders. The processing logic for this system is written in Java and resides on a Solaris machine, which also interacts with a database to store the information.
70
The steps illustrated above are as follows:
1. The client program bundles the account registration information into a SOAP message. 2. This SOAP message is sent to the Web Service as the body of an HTTP POST request. 3. The Web Service unpacks the SOAP request and converts it into a command that the application can understand. The application processes the information as required and responds with a new unique account number for that customer. 4. Next, the Web Service packages up the response into another SOAP message, which it sends back to the client program in response to its HTTP request. 5. The client program unpacks the SOAP message to obtain the results of the account registration process. For further details regarding the implementation of Web Services technology, read about the Cape Clear product set and review the product components.
71
Benefits of using Web Services
Exposing the existing function on to network A Web service is a unit of managed code that can be remotely invoked using HTTP, that is, it can be activated using HTTP requests. So, Web Services allows you to expose the functionality of your existing code over the network. Once it is exposed on the network, other application can use the functionality of your program. Connecting Different Applications ie Interoperability: Web Services allows different applications to talk to each other and share data and services among themselves. Other applications can also use the services of the web services. For example VB or .NET application can talk to java web services and vice versa. So, Web services is used to make the application platform and technology independent. Standardized Protocol: Web Services uses standardized industry standard protocol for the communication. All the four layers (Service Transport, XML Messaging, Service Description and Service Discovery layers) uses the well defined protocol in the Web Services protocol stack. This standardization of protocol stack gives the business many advantages like wide range of choices, reduction in the cost due to competition and increase in the quality.
72
Web services characteristics
Low Cost of communication: Web Services uses SOAP over HTTP protocol for the communication, so you can use your existing low cost internet for implementing Web Services. This solution is much less costly compared to proprietary solutions like EDI/B2B. Beside SOAP over HTTP, Web Services can also be implemented on other reliable transport mechanisms like FTP etc. Web services characteristics XML-based Web Services uses XML at data representation and data transportation layers. Using XML eliminates any networking, operating system, or platform binding. So Web Services based applications are highly interoperable application at their core level. Loosely coupled A consumer of a web service is not tied to that web service directly. The web service interface can change over time without compromising the client's ability to interact with the service. A tightly coupled system implies that the client and server logic are closely tied to one another, implying that if one interface changes, the other must also be updated. Adopting a loosely coupled architecture tends to make software systems more manageable and allows simpler integration between different systems.
73
Supports Remote Procedure Calls (RPCs)
Web services allow clients to invoke procedures, functions, and methods on remote objects using an XML-based protocol. Remote procedures expose input and output parameters that a web service must support. Component development through Enterprise JavaBeans (EJBs) and .NET Components has increasingly become a part of architectures and enterprise deployments over the past couple of years. Both technologies are distributed and accessible through a variety of RPC mechanisms. A web service supports RPC by providing services of its own, equivalent to those of a traditional component, or by translating incoming invocations into an invocation of an EJB or a .NET component. Supports document exchange One of the key advantages of XML is its generic way of representing not only data, but also complex documents. These documents can be simple, such as when representing a current address, or they can be complex, representing an entire book or RFQ. Web services support the transparent exchange of documents to facilitate business integration.
74
.NET Namespaces System.Web.Services
for developing Web services (e.g.: WebService, WebMethod) System.Web.Services.Configuration for extending SOAP System.Web.Services.Description for creating and manipulating WSDL descriptions System.Web.Services.Discovery for using DISCO System.Web.Services.Protocols for implementation of communication protocols (e.g. SOAP -HTTP) System.Xml.Serialization for XML serialization
75
Web Services Architecture
76
There are two ways to view the web service architecture.
1. The first is to examine the individual roles of each web service actor. 2. The second is to examine the emerging web service protocol stack. 1. Web Service Roles There are three major roles within the web service architecture: Service provider: This is the provider of the web service. The service provider implements the service and makes it available on the Internet. Service requestor: This is any consumer of the web service. The requestor utilizes an existing web service by opening a network connection and sending an XML request. Service registry: This is a logically centralized directory of services. The registry provides a central place where developers can publish new services or find existing ones. It therefore serves as a centralized clearinghouse for companies and their services.
77
2. Web Service Protocol Stack
A second option for viewing the web service architecture is to examine the emerging web service protocol stack. The stack is still evolving, but currently has four main layers. Service transport This layer is responsible for transporting messages between applications. Currently, this layer includes hypertext transfer protocol (HTTP), Simple Mail Transfer Protocol (SMTP), file transfer protocol (FTP), and newer protocols, such as Blocks Extensible Exchange Protocol (BEEP). XML messaging This layer is responsible for encoding messages in a common XML format so that messages can be understood at either end. Currently, this layer includes XML-RPC and SOAP. Service description This layer is responsible for describing the public interface to a specific web service. Currently, service description is handled via the Web Service Description Language (WSDL). Service discovery This layer is responsible for centralizing services into a common registry, and providing easy publish/find functionality. Currently, service discovery is handled via Universal Description, Discovery, and Integration (UDDI).
78
Web Services Components
XML-RPC This is the simplest XML based protocol for exchanging information between computers. XML-RPC is a simple protocol that uses XML messages to perform RPCs. Requests are encoded in XML and sent via HTTP POST. XML responses are embedded in the body of the HTTP response. XML-RPC is platform-independent. XML-RPC allows diverse applications to communicate. A Java client can speak XML-RPC to a Perl server. XML-RPC is the easiest way to get started with web services. SOAP SOAP is an XML-based protocol for exchanging information between computers. SOAP is a communication protocol SOAP is for communication between applications SOAP is a format for sending messages
79
SOAP is designed to communicate via Internet
SOAP is platform independent SOAP is language independent SOAP is simple and extensible SOAP allows you to get around firewalls SOAP will be developed as a W3C standard WSDL WSDL stands for Web Services Description Language WSDL is an XML based protocol for information exchange in decentralized and distributed environments. WSDL is the standard format for describing a web service. WSDL definition describes how to access a web service and what operations it will perform. WSDL is a language for describing how to interface with XML-based services. WSDL is an integral part of UDDI, an XML-based worldwide business registry. WSDL is the language that UDDI uses. WSDL was developed jointly by Microsoft and IBM.
80
UDDI UDDI is an XML-based standard for describing, publishing, and finding Web services. UDDI stands for Universal Description, Discovery and Integration. UDDI is a specification for a distributed registry of Web services. UDDI is platform independent, open framework. UDDI can communicate via SOAP, CORBA, Java RMI Protocol. UDDI uses WSDL to describe interfaces to web services. UDDI is seen with SOAP and WSDL as one of the three foundation standards of web services. UDDI is an open industry initiative enabling businesses to discover each other and define how they interact over the Internet.
81
WebService_1.asmx http://localhost:1126/WebSite1/Service.asmx
Create Simple Web Service Application Step 1: Create Web Service in ASP.Net WebService_1.asmx using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; [WebService(Namespace = " [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Service : System.Web.Services.WebService { [WebMethod] public string Example() return "Welcome to Chettinad College of Engineering and Technology"; } Step 2: The Web Service file is executed and copy for the URL of Web Service
82
WebService_2.aspx Step 3: Create ASP.Net file
Step 4: Add the Web References to the ASP.Net file Step 5: Add the Label, Textbox and Button to Webform WebService_2.aspx Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Height="24px" Text="The String Name is" Width="264px"></asp:Label> <asp:TextBox ID="TextBox1" runat="server" Width="512px"></asp:TextBox> <br /> <br /> <asp:Button ID="Button1" runat="server" Text="Click String" OnClick="Button1_Click" /><br /> </div> </form> </body> </html>
83
WebService_2.aspx.cs Output
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) localhost.Service ls = new localhost.Service(); TextBox1 .Text = ls.Example().ToString (); } WebService_2.aspx.cs Output
84
Arithmetic Operation using Web Service Application
Step 1: Create Web Service in ASP.Net WebService_1.asmx using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; [WebService(Namespace = " [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Service : System.Web.Services.WebService { [WebMethod] public int addition(int a, int b) return (a + b); } public int subtraction(int a, int b) return (a - b);
85
Step 3: Create ASP.Net file
[WebMethod] public int multiplication(int a, int b) { return (a * b); } public int division(int a, int b) return (a / b); Step 2: The Webservice file is executed and copy for the URL of Webservice Step 3: Create ASP.Net file Step 4: The above Web Services is Add the Web References to the ASP.Net file
86
WebService_1.aspx Step 5: Creating a Arithmetic Operation in Webform
Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" > <head runat="server"> <title>Create a Simple Web Application</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="label1" Text ="Computring of the Two Numbers is" runat ="server"></asp:Label> <asp:TextBox ID="text1" Text ="" runat ="server"></asp:TextBox><br /> <asp:Button ID="b1" Text ="Click String" runat ="server" OnClick ="Button_Click" /> <asp:Button ID="b2" Text ="Click String" runat ="server" OnClick ="Button_Click" /> <asp:Button ID="b3" Text ="Click String" runat ="server" OnClick ="Button_Click" /> <asp:Button ID="b4" Text ="Click String" runat ="server" OnClick ="Button_Click" /> </div> </form> </body> </html>
87
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { public void Button_Click(Object o, EventArgs e) localhost.Service ls = new localhost.Service(); if (b1.Equals(o)) text1.Text = ls.addition(10, 20).ToString(); else if (b2.Equals(o)) text1.Text = ls.subtraction(67, 34).ToString(); else if (b3.Equals(o)) text1.Text = ls.multiplication(20, 10).ToString(); else if (b4.Equals(o)) text1.Text = ls.division(20, 10).ToString(); }
88
Output
89
Create Simple Calculator using Web Service
Step 1: Create Web Service in ASP.Net WebSite_2.asmx using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; [WebService(Namespace = " [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Service : System.Web.Services.WebService { [WebMethod] public int addition(int a,int b) return (a + b); } public int subtraction(int a, int b) return (a - b); public int multiplication(int a, int b) return (a * b);
90
[WebMethod] public int division(int a, int b) { return (a / b); } public int modulodivision(int a, int b) return (a % b); public int squareroot(int a) return squareroot (a); public int power(int a) return power (a); Step 2: The Webservice file is executed and copy for the URL of Webservice
91
WebSite_2.aspx Step 3: Create ASP.Net file
Step 4: Add the Web References to the ASP.Net file WebSite_2.aspx Step 5: Creating a Calculator Webform Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="Simple Calculator" Width="120px"></asp:Label><br /> <br /> <asp:TextBox ID="t1" runat="server" Width="112px"></asp:TextBox> <br /> <asp:Button ID="bt1" runat="server" Text="1" OnClick="btsubmit_Click" /> <asp:Button ID="bt2" runat="server" Text="2" OnClick="btsubmit_Click"/> <asp:Button ID="bt3" runat="server" Text="3" OnClick="btsubmit_Click"/> <asp:Button ID="btclear" runat="server" OnClick="btsubmit_Click" Text="Clear" Width="56px" />
92
<asp:Button ID="bt4" runat="server" Text="4" OnClick="btsubmit_Click"/>
<asp:Button ID="btaddition" runat="server" OnClick="btsubmit_Click" Text="+" /> <asp:Button ID="btmultiplication“ runat="server" Text="*" Click="btsubmit_Click"/> <asp:Button ID="btpercentage" runat="server” Text="%" /><br /> <asp:Button ID="bt7" runat="server" Text="7" OnClick="btsubmit_Click"/> <asp:Button ID="bt8" runat="server" Text="8" OnClick="btsubmit_Click"/> <asp:Button ID="bt9" runat="server" Text="9" OnClick="btsubmit_Click"/> <asp:Button ID="bt0" runat="server“ Text="0" OnClick="btsubmit_Click"/> <asp:Button ID="btsubtraction" runat="server" Text="-" OnClick="btsubmit_Click"/> <asp:Button ID="btdivision“ runat="server" Text="/" OnClick="btsubmit_Click"/><br /> <asp:Button ID="btsubmit" runat="server" OnClick="btsubmit_Click" Text="=" /></div> </form> </body> </html>
93
WebSite_2.aspx.cs using System; using System.Data;
using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { string s1 = ""; string s2 = ""; string op = ""; localhost.Service ls = new localhost.Service(); protected void btsubmit_Click(object sender, EventArgs e) if (sender.Equals(bt0)) t1.Text += "0"; } else if (sender.Equals(bt1)) t1.Text += "1"; else if (sender.Equals(bt2)) t1.Text += "2";
94
else if (sender.Equals(btaddition))
{ t1.Text += "3"; } else if (sender.Equals(bt4)) t1.Text += "4"; else if (sender.Equals(bt5)) t1.Text += "5"; else if (sender.Equals(bt6)) t1.Text += "6"; else if (sender.Equals(bt7)) t1.Text += "7"; else if (sender.Equals(bt8)) t1.Text += "8"; else if (sender.Equals(bt9)) t1.Text += "9"; else if (sender.Equals(btaddition)) { Session.Add("Inp1",t1.Text); Session.Add("Op1", btaddition.Text); t1.Text = ""; op = btaddition.Text; } else if (sender.Equals(btsubtraction)) Session.Add("Inp1", t1.Text); Session.Add("Op1", btsubtraction.Text); op = btsubtraction.Text; else if (sender.Equals(btmultiplication)) Session.Add("Op1", btmultiplication.Text); op = btmultiplication.Text;
95
else if (sender.Equals(btdivision))
{ Session.Add("Inp1", t1.Text); Session.Add("Op1", btdivision.Text); t1.Text = ""; op = btdivision.Text; } else if (sender.Equals(btpercentage)) Session.Add("Op1", btpercentage.Text); op = btpercentage.Text; else if(sender.Equals (btsubmit )) { if (Session["Op1"].ToString().Equals("+")) t1.Text = ls.addition(int.Parse(Session["Inp1"].ToString()), int.Parse (t1.Text)).ToString (); } if (Session["Op1"].ToString().Equals("-")) t1.Text = ls.addition(int.Parse(Session["Inp1"].ToString()), int.Parse(t1.Text)).ToString(); if (Session["Op1"].ToString().Equals("*"))
96
if (Session["Op1"].ToString().Equals("/"))
{ t1.Text = ls.addition(int.Parse(Session["Inp1"].ToString()), int.Parse(t1.Text)).ToString(); } if (Session["Op1"].ToString().Equals("%")) if (Session["Op1"].ToString().Equals("SQRT")) if (Session["Op1"].ToString().Equals("POW")) protected void Button13_Click(object sender, EventArgs e) t1.Text = "";
97
THE END
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.