Download presentation
Presentation is loading. Please wait.
1
Unit 4: The Server Tier (18 Hrs
Unit 4: The Server Tier (18 Hrs.) Web Server Concept, Creating dynamic content, Using control flow to control dynamic content generation, Sessions and State, Error Handling, Architecting Web Application, Using tag libraries, Writing tag libraries
2
Web server In 1989 Tim Berners-Lee proposed a new project to his employer CERN, with the goal of easing the exchange of information between scientists by using a hypertext system. The project resulted in Berners-Lee writing two programs in 1990: A browser called WorldWideWeb. The world's first web server, later known as CERN httpd, which ran on NeXTSTEP. In 1994 Tim Berners-Lee decided to constitute the World Wide Web Consortium (W3C) to regulate the further development of the many technologies involved (HTTP, HTML, etc.) through a standardization process. Web servers are computers that deliver (serves up) Web pages. a program that uses HTTP to serve files that create web pages to users in response to their requests. Every Web server has an IP address and possibly a domain name. Every web server has a unique address so that other computers connected to the Internet know where to find it. Web hosts rent out space on their web servers to people or businesses to set up their own websites. Any computer can be turned into a Web server by installing server software and connecting the machine to the Internet.
3
Common features Virtual hosting to serve many web sites using one IP address Large file support to be able to serve files whose size is greater than 2 GB on 32 bit OS Bandwidth throttling to limit the speed of responses in order to not saturate the network and to be able to serve more clients Server-side scripting to generate dynamic web pages, still keeping web server and website implementations separate from each other
4
Kernel-mode and user-mode web servers
A web server can be either implemented into the OS kernel, or in user space (like other regular applications). Load limits A web server (program) has defined load limits, because it can handle only a limited number of concurrent client connections (usually between 2 and 80,000, by default between 500 and 1,000) per IP address (and TCP port) and it can serve only a certain maximum number of requests per second depending on: its own settings, the HTTP request type, whether the content is static or dynamic, whether the content is cached, and the hardware and software limitations of the OS of the computer on which the web server runs. When a web server is near to or over its limit, it becomes unresponsive.
5
Symptoms of overload The symptoms of an overloaded web server are:
Requests are served with (possibly long) delays (from 1 second to a few hundred seconds). The web server returns an HTTP error code, such as 500, 502, 503, 504, 408, or even 404, which is inappropriate for an overload condition. The web server refuses or resets (interrupts) TCP connections before it returns any content. In very rare cases, the web server returns only a part of the requested content. This behavior can be considered a bug, even if it usually arises as a symptom of overload.
6
Anti-overload techniques
To partially overcome above average load limits and to prevent overload, most popular web sites use common techniques like: Managing network traffic, by using: Firewalls to block unwanted traffic coming from bad IP sources or having bad patterns HTTP traffic managers to drop, redirect or rewrite requests having bad HTTP patterns Bandwidth management and traffic shaping, in order to smooth down peaks in network usage Deploying web cache techniques Using different domain names to serve different (static and dynamic) content by separate web servers, i.e.: Using different domain names and/or computers to separate big files from small and medium sized files; the idea is to be able to fully cache small and medium sized files and to efficiently serve big or huge (over MB) files by using different settings Using many web servers (programs) per computer, each one bound to its own network card and IP address Using many web servers (computers) that are grouped together behind a load balancer so that they act or are seen as one big web server Adding more hardware resources (i.e. RAM, disks) to each computer Tuning OS parameters for hardware capabilities and usage Using more efficient computer programs for web servers, etc. Using other workarounds, especially if dynamic content is involved
7
Web Servers Types Two leading Web servers are Apache, the most widely installed Web server, and Microsoft's Internet Information Server (IIS).
8
Apache HTTP Server (FREE & Open Source)
most popular web server on the web since 1996. developed and maintained by the Apache Software Foundation. Apache is available for a range of operating systems, including Unix, Linux, Windows, Mac OS X, Solaris. Microsoft Internet Information Services (IIS) ( Proprietary ) second most popular web server on the web. IIS comes as an optional component of most Windows operating systems. The major purpose of it was to provide their OS to control internet-services.
9
Other Web Servers Lighttpd: Sun Java System Web Server:
pronounced lighty is also a free web server that is distributed with the FreeBSD operating system. This open source web server is fast, secure and consumes much less CPU power. Lighttpd can also run on Windows, Mac OS X, Linux and Solaris operating systems. Sun Java System Web Server: web server from Sun Microsystems is suited for medium and large websites. the server is free it is not open source. runs on Windows, Linux and Unix platforms. supports various languages, scripts and technologies required for Web 2.0 such as JSP, Java Servlets, PHP, Perl, Python, Ruby on Rails, ASP and Coldfusion etc.
10
3. Jigsaw Server: comes from the World Wide Web Consortium (W3C's Server). It is open source and free and can run on various platforms like Linux, Unix, Windows, Mac OS X Free BSD etc. Jigsaw has been written in Java and can run CGI scripts and PHP programs.
11
Static Content Static content is published to regular files on your server and handled using the simplest methods available to the web server. The advantages of static content are: it is the fastest and most efficient way to deliver content it does not require any code to execute or any databases to be accessed, which makes it the most secure way to deliver content it uses simple, clean URLs to address the content it takes best advantage of web caching systems, which further boosts performance it is compatible with every type of webserver technology
12
Disadvantages Of Static Content
it must be republished when it changes, or your viewers will not see the updates it cannot display differently to different viewers, depending on their login status or other factors
13
Dynamic Content Dynamic content is generated for you at the time you request the page. The document you view exists only for you at that moment; if viewed by someone else at the same time, or by you at a slightly different time, you could get something different. Dynamic content is good for: pages whose content changes too quickly to easily republish it pages that display viewer-specific content (eg. user profiles) pages that display content conditionally (ie. member-only pages)
14
Dynamic content has the following disadvantages:
it is resource-intensive compared to static pages. That means the number of dynamic pages your server can display per second will generally be much less than the number of static pages. This can be especially important if you are swamped with traffic, or generating thousands of dynamic page views for robots or other automated agents that you don't really care about. dynamic pages execute code on your server, and can read from and write to your database. If your website has any security problems, dynamic pages is where those problems will be exposed. in many typical default webserving configurations, the index page of a website is presumed to be a static page (eg. "index.html"). That means there are some places where it is impractical or more difficult to use dynamic pages than others.
15
Server-Side Scripting
To generate dynamic pages we use a server-side scripting language. There are different types of server-side scripting languages such as PHP, ASP, ASP.NET, ColdFusion, Java Server Pages, Perl and others. Each scripting languages is being interpreted by an application. The application which interprets the server-side script is installed on the sever just like any other application. Server-side scripting languages are operating systems dependent.
16
.NET an Overview: ASP.net and VB.net
ASP.NET stands for Active Server Pages .NET & it is a technology used to render dynamic web content. VB.NET stands for Visual Basic.NET which is simply a Programming Language. An ASP.NET web site is typically made up of code written in either VB.NET or C# (C Sharp).
17
Microsoft .net Package of software that consists of clients, servers, and development tools. includes many other subcomponents that allow software that has been written in different languages to work together by establishing rules for language independence. Using it as a base, software development toolmakers can create development tools for different languages such as COBOL or C++. Microsoft itself used the .NET Framework to create VS, which is a development tool used to create software using the VB or C# programming languages. also provides many common functions that previously needed to be built by the developer. This includes access to the file system, access to the registry, and easier development when using the Windows Application Programming Interfaces (API) to access operating system–level functionality. This allows developer to concentrate more on business problems, instead of worrying how to access low-level windows functionality.
18
The Common Language Runtime
CLR is one of the components within the .NET Framework. provides runtime services, including loading and execution of code. essentially takes the language-specific code that was written and translates it Microsoft Intermediate Language (MSIL) code. This is what allows code written with VB to work with code written in C# (the most important aspect of the .NET Framework). A single program, written in multiple languages, works mainly because the framework contains a set of common data types that must be used by all languages building applications with the .NET Framework. This set of data types is the Common Type System (CTS), which defines how types are declared, used, and managed. To accommodate the CLR, some of the data types within languages such as VB needed to be changed so they could work better with data types from other languages such as C++.
19
Assemblies the main component of a .NET Framework application and is a collection of all of the functionality for the particular application. is created as either a .dll file for web sites or an .exe file for Windows applications, and it contains all of the MSIL code to be used by the framework. Without the assembly there is no application. .NET Framework Software Development Kit (SDK) is used to create the assemblies and perform other tasks, which are automatically done by VS.
20
How Web Servers Execute ASP Files
21
Server-Side Compilation and Delivery Process
22
The process of compiling and delivering ASP
The process of compiling and delivering ASP.NET pages goes through the following stages: IIS matches the URL in the request against a file on the physical file system (hard disk) by translating the virtual path (for example, /site/ index.aspx) into a path relative to the site’s Web root (for example, d:\domains\thisSite\wwwroot\site\index.aspx). Once the file is found, the file extension (.aspx) is matched against a list of known file types for either sending on to the visitor or for processing. If this is first visit to the page since the file was last changed, the ASP code is compiled into an assembly using the Common Language Runtime compiler, into MSIL, and then into machine- specific binary code for execution. The binary code is a .NET class .dll and is stored in a temporary location. Next time the page is requested the server will check to see if the code has changed. If the code is the same, then the compilation step is skipped and the previously compiled class code is executed; otherwise, the class is deleted and recompiled from the new source. The compiled code is executed and the request values are interpreted, such as form input fields or URL parameters. If the developer has used Web forms, then the server can detect what software the visitor is using and render pages that are tailored to the visitors’ requirements, for example, returning Netscape specific code, or Wireless Markup Language (WML) code for mobiles. Any results are delivered back to the visitor’s Web browser. Form elements are converted into client side markup and script, HTML and JavaScript for Web browsers, and WML and WMLScript for mobiles, for example.
23
Classic ASP and ASP.net Microsoft's previous server side scripting technology ASP (Active Server Pages) is now often called classic ASP (ASP 3.0 was the last version of classic ASP). ASP.NET is the next generation ASP, but it's not an upgraded version of ASP. ASP.NET is a server side scripting technology that enables scripts (embedded in web pages) to be executed by an Internet server. ASP.NET is a Microsoft Technology. ASP.NET is a program that runs inside IIS (Internet Information Services) is Microsoft's Internet server. IIS is also a part of Windows 2000 and XP Professional and comes as a free component with Windows servers
24
The .NET Framework consists of 3 main parts:
Programming languages: C# (Pronounced C sharp) Visual Basic (VB .NET) J# (Pronounced J sharp) Server technologies and client technologies: ASP .NET (Active Server Pages) Windows Forms (Windows desktop solutions) Compact Framework (PDA / Mobile solutions) Development environments: Visual Studio .NET (VS .NET) Visual Web Developer
25
Features of ASP.net: ASP.NET Controls: Event Aware Controls:
contains a large set of HTML controls. almost all HTML elements on a page can be defined as ASP.NET control objects that can be controlled by scripts. also contains a new set of object-oriented input controls, like programmable list-boxes and validation controls. A new data grid control supports sorting, data paging, and everything you can expect from a dataset control. Event Aware Controls: All ASP.NET objects on a Web page can expose events that can be processed by ASP.NET code. Load, Click and Change events handled by code makes coding much simpler and much better organized.
26
5. User Accounts and Roles:
3. ASP.NET Components: ASP.NET components are heavily based on XML. 4. User Authentication: ASP.NET supports form-based user authentication, cookie management, and automatic redirecting of unauthorized logins. 5. User Accounts and Roles: ASP.NET allows user accounts and roles, to give each user (with a given role) access to different server code and executables. 6. High Scalability: Server-to-server communication has been greatly enhanced, making it possible to scale an application over several servers. One example of this is the ability to run XML parsers, XSL transformations and even resource hungry session objects on other servers.
27
7. Compiled Code: 8. Easy Configuration: 9. Easy Deployment:
The first request for an ASP.NET page on the server will compile the ASP.NET code and keep a cached copy in memory which result in highperformance. 8. Easy Configuration: Configuration of ASP.NET is done with plain text files. Configuration files can be uploaded or changed while the application is running. No need to restart the server. No more metabase or registry puzzle. 9. Easy Deployment: No more server-restart to deploy or replace compiled code. ASP.NET simply redirects all new requests to the new code. 10. Compatibility: ASP.NET is not fully compatible with earlier versions of ASP, so most of the old ASP code will need some changes to run under ASP.NET. To overcome this problem, ASP.NET uses a new file extension ".aspx". This will make ASP.NET applications able to run side by side with standard ASP applications on the same server.
28
Creating ASP.NET Application
<html> <body bgcolor="yellow"> <center> <h2>Hello World!</h2> </center> </body> </html> The simplest way to convert an HTML page into an ASP.NET page is to copy the HTML file to a new file with an .aspx extension If a browser requests an HTML page from the server, the server sends the page to the browser without any modifications. If a browser requests an ASP.NET page, the server processes any executable code in the page, before the result is sent back to the browser.
29
Dynamic Page in Classic ASP
<html> <body bgcolor="yellow"> <center> <h2>Hello World!</h2> <p><%Response.Write(now())%></p> </center> </body> </html> The code inside the <% --%> tags is executed on the server. Response.Write is ASP code for writing something to the HTML output stream. Now() is a function returning the servers current date and time. The code above illustrates a limitation in Classic ASP: The code block has to be placed where the output has to appear. With Classic ASP it is impossible to separate executable code from the HTML itself. This makes the page difficult to read, and difficult to maintain.
30
ASP.NET - Server Controls
ASP.NET has solved the "spaghetti-code" problem described above with server controls. Server controls are tags that are understood by the server. There are three kinds of server controls: HTML Server Controls - Traditional HTML tags Web Server Controls - New ASP.NET tags Validation Server Controls - For input validation
31
1. HTML Server Controls HTML server controls are HTML tags understood by the server as HTML elements in ASP.NET files are, by default, treated as text. To make these elements programmable, add a runat="server" attribute to the HTML element. This attribute indicates that the element should be treated as a server control. The id reference can be used to manipulate the server control at run time. All HTML server controls must be within a <form> tag with the runat="server" attribute.
32
<script runat="server">
Sub Page_Load link1.href=" End Sub </script> <html> <body> <form runat="server"> <a id="link1" runat="server">Visit XYZ!</a> </form> </body> Here HtmlAnchor server control is declared in an .aspx file. Then we manipulate the href attribute of the HtmlAnchor control in an event handler (an event handler is a subroutine that executes code for a given event). The Page_Load event is one of many events that ASP.NET understands.
33
2. Web Server Controls special ASP.NET tags understood by the server.
like HTML server controls, Web server controls are also created on the server and they require a runat="server" attribute to work. Web server controls do not necessarily map to any existing HTML elements and they may represent more complex elements. The syntax for creating a Web server control is: <asp:control_name id="some_id" runat="server" />
34
<script runat="server">
Sub submit(Source As Object, e As EventArgs) button1.Text="You clicked me!" End Sub </script> <html> <body> <form runat="server"> <asp:Button id="button1" Text="Click me!" runat="server" OnClick="submit"/> </form> </body> </html> Here a Button server control is declared in an .aspx file. Then we create an event handler for the Click event which changes the text on the button.
35
3. Validation Server Controls
Used to validate user-input. If the user-input does not pass validation, it will display an error message to the user. Each validation control performs a specific type of validation (like validating against a specific value or a range of values). By default, page validation is performed when a Button, ImageButton, or LinkButton control is clicked. We can prevent validation when a button control is clicked by setting the Causes Validation property to false. The syntax for creating a Validation server control is: <asp:control_name id="some_id" runat="server" />
36
<html> <body> <form runat="server"> <p>Enter a number from 1 to 100: <asp:TextBox id="tbox1" runat="server" /> <br /><br /> <asp:Button Text="Submit" runat="server" /> </p> <p> <asp:RangeValidator ControlToValidate="tbox1" MinimumValue="1" MaximumValue="100" Type="Integer" Text="The value must be from 1 to 100!" runat="server" /> </p> </form> </body> </html> Here we declare one TextBox control, one Button control, and one RangeValidator control in an .aspx file. If validation fails, the text "The value must be from 1 to 100!" will be displayed in the RangeValidator control:
37
ASP.NET Web Forms All server controls must appear within a <form> tag, and the <form> tag must contain the runat="server" attribute. The runat="server" attribute indicates that the form should be processed on the server. It also indicates that the enclosed controls can be accessed by server scripts: <form runat="server"> ...HTML + server controls </form> The form is always submitted to the page itself. If specifed an action attribute, it is ignored. If omited the method attribute, it will be set to method="post" by default. An .aspx page can only contain ONE <form runat="server"> control.
38
If we select view source in an
If we select view source in an .aspx page containing a form with no name, method, action, or id attribute specified, ASP.NET adds these attributes to the form. It looks something like this: <form name="_ctl0" method="post" action="page.aspx" id="_ctl0"> ...some code </form>
39
Maintaining the ViewState
Submitting a Form A form is most often submitted by clicking on a button. The Button server control in ASP.NET has the following format: <asp:Button id="id" text="label" OnClick="sub" runat="server" /> The id attribute defines a unique name for the button and the text attribute assigns a label to the button. The onClick event handler specifies a named subroutine to execute. A button click runs a subroutine which changes the text on the button Maintaining the ViewState When a form is submitted in classic ASP, all form values are cleared. When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. This is because ASP .NET maintains your ViewState. The status is defined through a hidden field placed on each page with a <form runat="server"> control.
40
The source could look something like this:
<form name="_ctl0" method="post" action="page.aspx" id="_ctl0"> <input type="hidden" name="__VIEWSTATE“ value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" /> .....some code </form> Maintaining the ViewState is the default setting for ASP.NET Web Forms. If you want to NOT maintain the ViewState, include the directive Page EnableViewState="false" %> at the top of an .aspx page or add the attribute EnableViewState="false" to any control.
41
The TextBox Control The TextBox control is used to create a text box where the user can input text. The example below demonstrates some of the attributes you may use with the TextBox control: <html> <body> <form runat="server"> A basic TextBox: <asp:TextBox id="tb1" runat="server" /> <br /><br /> A password TextBox: <asp:TextBox id="tb2" TextMode="password" runat="server" /> <br /><br /> A TextBox with text: <asp:TextBox id="tb4" Text="Hello World!" runat="server" /> <br /><br /> A multiline TextBox: <asp:TextBox id="tb3" TextMode="multiline" runat="server" /> <br /><br /> A TextBox with height: <asp:TextBox id="tb6" rows="5" TextMode="multiline" runat="server" /> <br /><br /> A TextBox with width: <asp:TextBox id="tb5" columns="30" runat="server" /> </form> </body> </html>
42
Add a Script In TextBox The contents and settings of a TextBox control may be changed by server scripts when a form is submitted. A form can be submitted by clicking on a button or when a user changes the value in the TextBox control.
43
<script runat="server"> Sub submit(sender As Object, e As EventArgs) lbl1.Text="Your name is " & txt1.Text End Sub </script> <html> <body> <form runat="server"> Enter your name: <asp:TextBox id="txt1" runat="server" /> <asp:Button OnClick="submit" Text="Submit" runat="server" /> <p><asp:Label id="lbl1" runat="server" /></p> </form> </body> </html> Here we declare one TextBox control, one Button control, and one Label control in an .aspx file. When the submit button is triggered, the submit subroutine is executed. The submit subroutine writes a text to the Label control
44
The Button Control The Button control is used to display a push button. The push button may be a submit button or a command button. By default, this control is a submit button. A submit button does not have a command name and it posts the page back to the server when it is clicked. It is possible to write an event handler to control the actions performed when the submit button is clicked. A command button has a command name and allows you to create multiple Button controls on a page. It is possible to write an event handler to control the actions performed when the command button is clicked.
45
The example below demonstrates a simple Button control:
<html> <body> <form runat="server"> <asp:Button id="b1" Text="Submit" runat="server" /> </form> </body> </html>
46
Data Binding The following controls are list controls which support data binding: asp:RadioButtonList asp:CheckBoxList asp:DropDownList asp:Listbox The selectable items in each of the above controls are usually defined by one or more asp:ListItem controls, like this: <html> <body> <form runat="server"> <asp:RadioButtonList id="countrylist" runat="server"> <asp:ListItem value="N" text="Norway" /> <asp:ListItem value="S" text="Sweden" /> <asp:ListItem value="F" text="France" /> <asp:ListItem value="I" text="Italy" /> </asp:RadioButtonList> </form> </body> </html>
47
However, with data binding we may use a separate source, like a database, an XML file, or a script to fill the list with selectable items. By using an imported source, the data is separated from the HTML, and any changes to the items are made in the separate data source. The ArrayList object is a collection of items containing a single data value. Items are added to the ArrayList with the Add() method. The following code creates a new ArrayList object named mycountries and four items are added: <script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("Norway") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") end if end sub </script>
48
By default, an ArrayList object contains 16 entries
By default, an ArrayList object contains 16 entries. An ArrayList can be sized to its final size with the TrimToSize() method: <script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("Norway") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() end if end sub </script>
49
An ArrayList can also be sorted alphabetically or numerically with the Sort() method:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("Norway") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() mycountries.Sort() end if end sub </script>
50
To sort in reverse order, apply the Reverse() method after the Sort() method:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("Norway") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() mycountries.Sort() mycountries.Reverse() end if end sub </script>
51
An ArrayList object may automatically generate the text and values to the following controls:
asp:RadioButtonList asp:CheckBoxList asp:DropDownList asp:Listbox
52
To bind data to a RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in an .aspx page: <script runat="server"> Sub Page_Load If Not Page.IsPostBack Then Dim mycountries = New ArrayList mycountries.Add("Norway") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() mycountries.Sort() rb.DataSource = mycountries rb.DataBind() End If end sub </script> <html> <body> <form id="Form1" runat="server"> <asp:RadioButtonList id="rb" runat="server" /> </form> </body> </html> The DataSource property of the RadioButtonList control is set to the ArrayList and it defines the data source of the RadioButtonList control. The DataBind() method of the RadioButtonList control binds the data source with the RadioButtonList control. The data values are used as both the Text and Value properties for the control.
53
Creating a HashTable The Hashtable object contains items in key/value pairs. The keys are used as indexes, and very quick searches can be made for values by searching through their keys. Items are added to the Hashtable with the Add() method
54
The following code creates a Hashtable named mycountries and four elements are added:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") end if end sub </script>
55
A Hashtable object may automatically generate the text and values to the following controls:
asp:RadioButtonList asp:CheckBoxList asp:DropDownList asp:Listbox
56
<script runat="server"> sub Page_Load
if Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("N", "Norway") mycountries.Add("S", "Sweden") mycountries.Add("F", "France") mycountries.Add("I", "Italy") rb.DataSource=mycountries rb.DataValueField="Key" rb.DataTextField="Value" rb.DataBind() end if end sub </script> <html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /> </form> </body> </html>
57
<script runat="server"> sub Page_Load. if Not Page
<script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("N", "Norway") mycountries.Add("S", "Sweden") mycountries.Add("F", "France") mycountries.Add("I", "Italy") rb.DataSource=mycountries rb.DataValueField="Key" rb.DataTextField="Value" rb.DataBind() end if end sub sub displayMessage(s as Object,e As EventArgs) lbl1.text="Your favorite country is: " & rb.SelectedItem.Text end sub </script> <html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" onSelectedIndexChanged="displayMessage" /> <p><asp:label id="lbl1" runat="server" /></p> </form> </body> </html> To bind data to a RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in an .aspx page. Then add the script that builds the list. Then we add a sub routine to be executed when the user clicks on an item in the RadioButtonList control. When a radio button is clicked, a text will appear in a label.
58
The SortedList object contains items in key/value pairs.
We cannot choose the sort order of the items added to the Hashtable. To sort items alphabetically or numerically, use the SortedList object. The SortedList object contains items in key/value pairs. A SortedList object automatically sort the items in alphabetic or numeric order. <script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycountries=New SortedList mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") end if end sub </script>
59
ASP .NET- XML Files <?xml version="1.0" encoding="ISO-8859-1"?>
<countries> <country> <text>Norway</text> <value>N</value> </country> <text>Sweden</text> <value>S</value> <text>France</text> <value>F</value> <text>Italy</text> <value>I</value> </countries>
60
Bind a XML DataSet to a List Control
Import the "System.Data" namespace. We need this namespace to work with DataSet objects. Include the following directive at the top of an .aspx page: Import Namespace="System.Data" %>
61
<%@ Import Namespace="System.Data" %>
<script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycountries=New DataSet mycountries.ReadXml(MapPath("countries.xml")) rb.DataSource=mycountries rb.DataValueField="value" rb.DataTextField="text" rb.DataBind() end if end sub </script> <html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" onSelectedIndexChanged="displayMessage" /> </form> </body> </html> create a DataSet for the XML file and load the XML file into the DataSet when the page is first loaded. To bind the DataSet to a RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in an .aspx page.
62
The Repeater Control The Repeater control is used to display a repeated list of items that are bound to the control. The Repeater control may be bound to a database table, an XML file, or another list of items. Here we will show how to bind an XML file to a Repeater control ("cdcatalog.xml"). <?xml version="1.0" encoding="ISO "?> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> ……. <title>Eros</title> <artist>Eros Ramazzotti</artist> <country>EU</country> <company>BMG</company> <price>9.90</price> <year>1997</year> </catalog>
63
Then we create a Repeater control in an .aspx page.
Next, create a DataSet for the XML file and load the XML file into the DataSet when the page is first loaded: <script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycdcatalog=New DataSet mycdcatalog.ReadXml(MapPath("cdcatalog.xml")) end if end sub </script> Then we create a Repeater control in an .aspx page.
64
The contents of the <HeaderTemplate> element are rendered first and only once within the output, then the contents of the <ItemTemplate> element are repeated for each "record" in the DataSet, and last, the contents of the <FooterTemplate> element are rendered once within the output. <html> <body> <form runat="server"> <asp:Repeater id="cdcatalog" runat="server"> <HeaderTemplate> ... </HeaderTemplate> <ItemTemplate> </ItemTemplate> <FooterTemplate> </FooterTemplate> </asp:Repeater> </form> </body> </html>
65
Then we add the script that creates the DataSet and binds the mycdcatalog DataSet to the Repeater control. We also fill the Repeater control with HTML tags and bind the data items to the cells in the<ItemTemplate> section with the <%#Container.DataItem("fieldname")%> method. Example Import Namespace="System.Data" %> <script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycdcatalog=New DataSet mycdcatalog.ReadXml(MapPath("cdcatalog.xml")) cdcatalog.DataSource=mycdcatalog cdcatalog.DataBind() end if end sub </script> <html> <body> <form runat="server"> <asp:Repeater id="cdcatalog" runat="server"> <HeaderTemplate>
66
<table border="1" width="100%"> <tr> <th>Title</th> <th>Artist</th> <th>Country</th> <th>Company</th> <th>Price</th> <th>Year</th> </tr> </HeaderTemplate> <ItemTemplate> <td><%#Container.DataItem("title")%></td> <td><%#Container.DataItem("artist")%></td> <td><%#Container.DataItem("country")%></td> <td><%#Container.DataItem("company")%></td> <td><%#Container.DataItem("price")%></td> <td><%#Container.DataItem("year")%></td> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </form> </body> </html>
67
Output
68
The DataList Control The DataList control is, like the Repeater control, used to display a repeated list of items that are bound to the control. However, the DataList control adds a table around the data items by default. The DataList control may be bound to a database table, an XML file, or another list of items. Here we will show how to bind an XML file to a DataList control.
69
<%@ Import Namespace="System
Import Namespace="System.Data" %> <script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycdcatalog=New DataSet mycdcatalog.ReadXml(MapPath("cdcatalog.xml")) cdcatalog.DataSource=mycdcatalog cdcatalog.DataBind() end if end sub </script> <html> <body> <form runat="server"> <asp:DataList id="cdcatalog" gridlines="both" runat="server"> <HeaderTemplate> My CD Catalog </HeaderTemplate> (cont…..)
70
<ItemTemplate> "<%#Container
<ItemTemplate> "<%#Container.DataItem("title")%>" of <%#Container.DataItem("artist")%> - $<%#Container.DataItem("price")%> </ItemTemplate> <FooterTemplate> Copyright Hege Refsnes </FooterTemplate> </asp:DataList> </form> </body> </html> OUTPUT:
71
Using SQL Server with ASP.NET
Microsoft SQL Server is based on the client/server architecture, in which data is stored on a centralized computer called a server. And the clients can access the data stored on the server through a network. The client/server architecture prevents data inconsistency. We can access data stored on a SQL server through Web Forms. To do so, we have to create Web applications that have data access controls. These data access Web controls present the data in a consistent manner irrespective of the actual source, such as Microsoft SQL Server or MS Access. Therefore, while creating a Web application, we do not need to worry about the format of the data.
72
However, before we can access or manipulate data from a SQL server, we need to perform the following steps in the specified sequence: Establish a connection with the SQL Server. Write the actual command to access or manipulate data. Create a result set of the data from the data source with which the application can work. This result set is called the data set and is disconnected from the actual source. The application accesses and updates data in the data set, which is later reconciled with the actual data source.
73
Selecting Data from Table
To achieve this functionality, we first need to import two namespaces, System.Data and System.Data.SqlClient, into your Web Forms page. The syntax is given as follows: Import Namespace="System.Data.OleDb" %> We need this namespace to work with Microsoft Access and other OLE DB database providers.
74
Example: Import Namespace="System.Data.OleDb" %> <script runat="server"> sub Page_Load dim dbconn dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & server.mappath("northwind.mdb")) dbconn.Open() end sub </script> Here, we will create the connection to the database in the Page_Load subroutine. We create a dbconn variable as a new OleDbConnection class with a connection string which identifies the OLE DB provider and the location of the database. The connection string must be a continuous string without a line break.
75
To specify the records to retrieve from the database
Import Namespace="System.Data.OleDb" %> <script runat="server"> sub Page_Load dim dbconn,sql,dbcomm dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; data source=" & server.mappath("northwind.mdb")) dbconn.Open() sql="SELECT * FROM customers" dbcomm=New OleDbCommand(sql,dbconn) end sub </script> Here, we will create a dbcomm variable as a new OleDbCommand class. The OleDbCommand class is for issuing SQL queries against database tables.
76
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server"> sub Page_Load dim dbconn,sql,dbcomm,dbread dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; data source=" & server.mappath("Bank.mdb")) dbconn.Open() sql="SELECT * FROM customers" dbcomm=New OleDbCommand(sql,dbconn) dbread=dbcomm.ExecuteReader() end sub </script> The OleDbDataReader class is used to read a stream of records from a data source. A DataReader is created by calling the ExecuteReader method of the OleDbCommand object.
77
Then we bind the DataReader to a Repeater control:
Import Namespace="System.Data.OleDb" %> <script runat="server"> sub Page_Load dim dbconn,sql,dbcomm,dbread dbconn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & Server.MapPath("Bank.mdb")) dbconn.Open() sql = "SELECT * From customer where Address='Mnr'" dbcomm=New OleDbCommand(sql,dbconn) dbread=dbcomm.ExecuteReader() customers.DataSource=dbread customers.DataBind() dbread.Close() dbconn.Close() end sub </script>
78
<html> <body> <form id="Form1" runat="server"> <asp:Repeater id="customers" runat="server"> <HeaderTemplate> <table border="1" width="100%"> <tr> <th>Customer_ID</th><th>Customer_name</th><th>Address</th><th>Age</th><th>Mobile</th><th> </th> </tr> </HeaderTemplate> <ItemTemplate> <td><%#Container.DataItem("Cid")%></td><td><%#Container.DataItem("CName")%></td> <td><%#Container.DataItem("Address")%></td><td><%#Container.DataItem("Age")%></td> <td><%#Container.DataItem("Mobile")%></td><td><%#Container.DataItem(" ")%></td> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </form> </body> </html>
79
Creating Table Import Namespace="System.Data.OleDb" %> <script runat="server"> sub Page_Load Dim dbconn, sql, dbcomm dbconn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & Server.MapPath("Bank.mdb")) dbconn.Open() sql = "Create Table Products (ProductID VarChar (4) Primary Key, ProductName VarChar (20), UnitPrice Money,QtyAvailable Integer)" dbcomm = New OleDbCommand(sql, dbconn) dbcomm.ExecuteNonQuery() dbconn.Close() end sub </script>
80
Inserting Data into Table
Import Namespace="System.Data.OleDb" %> <script runat="server"> sub Page_Load Dim dbconn, sql, dbcomm dbconn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;datasource=" & Server.MapPath("Bank.mdb")) dbconn.Open() sql = "Insert into customer dbcomm = New OleDbCommand(sql, dbconn) dbcomm.ExecuteNonQuery() dbconn.Close() end sub </script>
81
Deleting Data from Table
Import Namespace="System.Data.OleDb" %> <script runat="server"> sub Page_Load Dim dbconn, sql, dbcomm dbconn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & Server.MapPath("Bank.mdb")) dbconn.Open() sql = "Delete from customer where Cid=1" dbcomm = New OleDbCommand(sql, dbconn) dbcomm.ExecuteNonQuery() dbconn.Close() end sub </script>
82
ASP Cookies A cookie is often used to identify a user.
It is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With ASP, we can both create and retrieve cookie values. Cookies help Web sites store information about visitors. More generally, cookies are one way of maintaining continuity in a Web application—that is, of performing state management. Cookies are used for many purposes, all relating to helping the Web site remember users. For example, A site conducting a poll might use a cookie simply as a Boolean value to indicate whether a user's browser has already participated in voting so that the user cannot vote twice. A site that asks a user to log on might use a cookie to record that the user already logged on so that the user does not have to keep entering credentials.
83
Creating a Cookie The "Response.Cookies" command is used to create cookies. Note: The Response.Cookies command must appear BEFORE the <html> tag. Example: <% Response.Cookies("firstname")="Alex" Response.Cookies("firstname").Expires=#May 10,2012# %> Here we create a cookie named "firstname" and assign the value "Alex" to it and It is also possible to assign properties to a cookie, like setting a date when the cookie should expire.
84
Retrieving a Cookie Value
The "Request.Cookies" command is used to retrieve a cookie value. Example: <% fname=Request.Cookies("firstname") response.write("Firstname=" & fname) %> Output: Firstname=Alex Here we retrieve the value of the cookie named "firstname" and display it on a page
85
Session in ASP.net A session is defined as the period of time that a unique user interacts with a Web application. While using computer, it knows who you are. It knows when you open the application and when you close it. However, on the internet there is one problem: the web server does not know who you are and what you do, because the HTTP address doesn't maintain state. Active Server Pages (ASP) developers who wish to retain data for unique user sessions can use an intrinsic feature known as session state. Programmatically, session state is nothing more than memory in the shape of a dictionary or hash table, e.g. key-value pairs, which can be set and read for the duration of a user's session. ASP maintains session state by providing the client with a unique key assigned to the user when the session begins. This key is stored in an HTTP cookie that the client sends to the server on each request. The server can then read the key from the cookie and re-inflate the server session state.
86
The Session object stores information about, or change settings for a user session.
Variables stored in a Session object hold information about one single user, and are available to all pages in one application. Common information stored in session variables are name, id, and preferences. The server creates a new Session object for each new user, and destroys the Session object when the session expires.
87
When does a Session Start?
A session starts when: A new user requests an ASP file, and the Global.asa file includes a Session_OnStart procedure A value is stored in a Session variable A user requests an ASP file, and the Global.asa file uses the <object> tag to instantiate an object with session scope
88
When does a Session End? A session ends if a user has not requested or refreshed a page in the application for a specified period. By default, this is 20 minutes. If we want to set a timeout interval that is shorter or longer than the default, Timeout property is used. Eg: <% Session.Timeout=5 %> Abandon method used to end a session immediately. <% Session.Abandon %> The main problem with sessions is WHEN they should end. Waiting too long for an idle session uses up resources on the server, but if the session is deleted too soon the user has to start all over again because the server has deleted all the information. Finding the right timeout interval can be difficult!
89
Store and Retrieve Session Variables
The most important thing about the Session object is that we can store variables in it. The example below will set the Session variable username to "Donald Duck" and the Session variable age to "50": <% Session("username")="Donald Duck" Session("age")=50 %> When the value is stored in a session variable it can be reached from ANY page in the ASP application: Welcome <%Response.Write(Session("username"))%>
90
We can also store user preferences in the Session object, and then access that preference to choose what page to return to the user. The example below specifies a text-only version of the page if the user has a low screen resolution: <%If Session("screenres")="low" Then%> This is the text version of the page <%Else%> This is the multimedia version of the page <%End If%>
91
Remove Session Variables
The Contents collection contains all session variables. It is possible to remove a session variable with the Remove method. The example below removes the session variable "sale" if the value of the session variable "age" is lower than 18: <% If Session.Contents("age")<18 then Session.Contents.Remove("sale") End If %> To remove all variables in a session, use the RemoveAll method: <% Session.Contents.RemoveAll() %>
92
Loop Through the Contents Collection
if we dont know the number of items in the Contents collection, we can use the Count property: <% dim i dim j j=Session.Contents.Count Response.Write("Session variables: " & j) For i=1 to j Response.Write(Session.Contents(i) & "<br>") Next %> Result: Session variables: 2 Donald Duck 50
93
Exception Handling Only perfect programmers create perfect code from the beginning. Luckily for us Microsoft Visual Basic.NET offers two ways of handling exceptions: Unstructured (Like Visual Basic) Structured (Like C++) The terms, error and exception, are often used interchangeably. An error is the event and an exception is the object that the event creates. In fact, an error, which is an event that happens during the execution of code, interrupts or disrupts the code's normal flow and creates an exception object. When an error interrupts the flow, the program tries to find an exception handler — a block of code that tells it how to react — that will help it resume the flow. Factors that cause errors and subsequent exceptions include user error, resource failures, and failures of programming logic.
94
Structured versus Unstructured
Structured exception handling is simply that—using a control structure containing exceptions, isolated blocks of code, and filters to create an exception handling mechanism. it is significantly more versatile, robust, and flexible than unstructured. We cannot combine structured and unstructured exception handling in the same function. In unstructured exception handling, an On Error statement at the beginning of the code handles all exceptions. it is significantly less versatile, robust, and flexible than structured. If we use an On Error statement, we cannot use a Try...Catch statement in the same function.
95
Structured Exception Handling
It tests specific pieces of the code and, as exceptions occur, adapts our exception-handling code to the circumstances that caused the exception. It is significantly faster in large applications than unstructured exception handling and allows more flexible response to errors as well as greater application reliability. The Try...Catch...Finally control structure is fundamental to structured exception handling. It tests a piece of code, filters exceptions created by the execution of that code, and reacts differently based on the type of thrown exception.
96
The Try...Catch...Finally block
Try...Catch...Finally control structures test a piece of code and direct how the application should handle various categories of error. Each of the structure's three constituent parts plays a specific role in this process. The Try statement provides the code that is being tested for exceptions. Catch clauses identify blocks of code that are associated with specific exceptions. A Catch When block directs the code to execute under specific circumstances. A Catch without a When clause reacts to any exception. Therefore, our code might hold a series of specific Catch...When statements, each reacting to a specific type of exception, followed by a general Catch block that reacts to any exceptions that have not been intercepted by the preceding Catch...When clauses. The Finally statement contains code that executes regardless of whether or not an exception occurs within the Try block. A Finally statement will execute even after an Exit Try or Exit Sub. This code often performs clean- up tasks, such as closing files or clearing buffers.
97
What a Catch Clause Does
Can take three possible forms: Catch, Catch...As, and Catch...When. A Catch clause with no When keyword allows the associated statement block to handle any exception. The Try statement provides the code that is being tested for exceptions. Catch...As and Catch...When clauses catch a specific exception and allow the associated statement block to tell the application what to do. Catch clauses are checked in the order in which they appear in the code. Therefore, catch clauses should move from the specific to the general as they progress through the sequence of code. Check a type before checking its base type, for example.(cont…)
98
<script runat="server"> Sub Page_Load() Dim avseats, adtseats, nguests As Integer adtseats = 100 nguests = 100 Try avseats = adtseats - nguests Catch ex As Exception When avseats = 0 MsgBox("Auditorium lacks chairs!") Exit Sub Catch ex As Exception When avseats < 0 MsgBox("There are no more available seats.") Finally MsgBox("Thank you for your interest in our concert.") End Try End Sub </script> <html> <body> Exception Handling </body> </html>
99
<script runat="server"> Sub divide() Dim x, y, z As Integer
x = txtx.Text y = txty.Text Try z = x / y MsgBox("Division=" & z) Return Catch ex As ArithmeticException MsgBox(ex.Message) Catch ex As Exception End Try End Sub </script> <html> <body> <form id="frm" runat="server"> <asp:textbox ID="txtx" runat="server" /> <asp:textbox ID="txty" runat="server" /> <asp:button ID="btn" text="Divide" OnClick="divide" runat=server/> </form> </body> </html>
100
Unstructured Exception Handling
It is implemented using the Err object and three statements: On Error, Resume, and Error. The On Error statement establishes a single exception handler that catches all thrown exceptions; we can subsequently change the handler location, but we can only have one handler at a time. To generate a run-time error in your code, use the Raise method. Whenever an Exit Sub, Exit Function, Exit Property, Resume or Resume Next statement occurs within an error-handling routine, the Err object's properties are reset to zero or zero-length strings. Using any of these outside an error-handling routine does not reset its properties. If we need to do so , we can use the Clear method to reset the Err object.
101
The On Error GoTo Statement
The Error Object The values of the properties of the Err object are determined by the error that just occurred The following table details the properties and provides a short description of each. Description: Text message providing a short description of the error. Number: Numeric value specifying an error. Source: String expression representing the object or application that generated the error. The On Error GoTo Statement The On Error GoTo statement enables a routine for exception handling and specifies the location of that routine within the procedure. Used with a label or line number, it directs the code to a specific exception handling routine. Used with -1, it disables error handling within the procedure. Used with 0, it disables the current exception.
102
The Resume Next Statement
It resumes execution after an exception has occurred. It specifies that in the event of an exception, control passes to the statement immediately following the statement in which the exception occurred. Resume Next can be used to allow graceful failures; the statement causing the error fails, but the application continues to execute and allows the user to correct the error and continue. Similarly, Resume <label> passes control to a label specified in its line argument. Make sure that the line label is located in the same procedure as the code calling it, since it cannot span between functions.
103
Example: <script runat="server"> Sub Page_Load()
On Error GoTo Whoops Dim x, y, z As Integer x = 50 y = 5 z = x / y MsgBox("Division=" & z) Return Whoops: MsgBox("Unexpected Error:" & Err.Description) End Sub </script> <html> <body> Unstructured Exception Handling Demo </body> </html>
104
Authentication Authentication is the process of discovering a user’s identity and ensuring the authenticity of this identity. The process of authentication is analogous to checking in at a conference registration table. Example of authentication. First, you provide some credentials to prove your identity (such as a driver’s license or a passport). Second, once your identity is verified with this information, you are issued a conference badge, or token that you carry with you when you are at the conference. Anyone you meet at the conference can immediately determine your identity by looking at your badge, which typically contains basic identity information, such as your first and last name.
105
Anonymous Authentication
The <anonymousAuthentication> element controls how Internet Information Services (IIS) processes requests from anonymous users. We can modify the <anonymousAuthentication> element to disable Anonymous authentication, or we can configure Internet Information Services (IIS) to use a custom user account to process anonymous requests. Anonymous authentication gives users access to the public areas of your Web or FTP site without prompting them for a user name or password. An application is a grouping of files that delivers content or provides services over protocols, such as HTTP. When we create an application in IIS, the application's path becomes part of the site's URL. By default, IIS uses Anonymous authentication. To enable other authentication methods such as Basic or Windows authentication we must disable Anonymous authentication for any Web site, Web application, or Web service.
106
Imports Microsoft.Web.Administration Module Sample Sub Main()
Imports System Imports System.Text Imports Microsoft.Web.Administration Module Sample Sub Main() Dim serverManager As ServerManager = New ServerManager Dim config As Configuration = serverManager.GetApplicationHostConfiguration Dim anonymousAuthenticationSection As ConfigurationSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication", "Contoso") anonymousAuthenticationSection("enabled") = True anonymousAuthenticationSection("userName") = "Guest" anonymousAuthenticationSection("password") = serverManager.CommitChanges() End Sub End Module
107
Windows Authentication
Windows authentication isn’t built into ASP.NET. Instead, Windows authentication hands over responsibility of authentication to IIS. IIS asks the browser to authenticate itself by providing credentials that map to a Windows user account. If the user is successfully authenticated, IIS allows the web-page request and passes the user and role information onto ASP.NET. Why Use Windows Authentication? We would want to use Windows authentication for four main reasons: It involves little programming work on the developer’s part. It allows us to use existing user logins. It provides a single authentication model for multiple types of applications. It allows us to use impersonation and Windows security.
108
Why Would We Not Use Windows Authentication?
So, why would you not want to use Windows authentication? It’s tied to Windows users. It’s tied to Windows client machines. It doesn’t provide much flexibility or control and can’t be customized easily.
109
Mechanisms for Windows Authentication
When we implement Windows authentication, IIS uses one of three possible authentication strategies to authenticate each request it receives: Basic authentication: The user name and password are passed as clear text. This is the only form of authentication supported by all browsers as part of the HTML standard. Digest authentication: The user name and password are not transmitted. Instead, a cryptographically secure hash with this information is sent. Integrated Windows authentication: The user name and password are not transmitted. Instead, the identity of a user already logged into Windows is passed automatically as a token. This is the only form of authentication that takes place transparently (without user intervention).
110
Integrated Windows Authentication
Integrated Windows authentication is the most convenient authentication standard for WAN- based and LAN-based intranet applications, because it performs authentication without requiring any client interaction. When IIS asks the client to authenticate itself, the browser sends a token that represents the Windows user account of the current user. If the web server fails to authenticate the user with this information, a login dialog box is shown where the user can enter a different user name and password. For Integrated Windows authentication to work, both the client and the web server must be on the same local network or intranet. That’s because Integrated Windows authentication doesn’t actually transmit the user name and password information. Instead, it coordinates with the domain server or Active Directory instance where it is logged in and gets that computer to send the authentication information to the web server. The protocol used for transmitting authentication information is either NTLM (NT LAN Manager) authentication or Kerberos 5—depending on the operating system version of the client and the server. If both are running Windows 2000 or higher and both machines are running in an Active Directory domain, Kerberos is used as the authentication protocol; otherwise, NTLM authentication will be used. Both protocols are extremely secure (Kerberos is the most secure protocol currently available)
111
Authentication Based on Domain Names
IIS has the capability to allow or deny requests from IP address or domain from which request is generated. Web browser sends requests by using TCP/IP therefore IIS have access to IP and domain. Whenever request comes from restricted domain it generated 403 access denied error and thus prohibits user from accessing information in web server. We can use domain or IP based authentication when we have developed application for internal purpose and we want to prohibit outside requests. If we have developed application for sales department, we prohibit requests from other departments using domain based authentication.
112
Tag Libraries In a Web application, a common design goal is to separate the display code from business logic. Java tag libraries are one solution to this problem Tag libraries allow us to isolate business logic from the display code by creating a Tag class (which performs the business logic) and including an HTML-like tag in our JSP page. When the Web server encounters the tag within our JSP page, the Web server will call methods within the corresponding Java Tag class to produce the required HTML content. Microsoft® ASP.NET uses Web form controls to serve the same purpose as Java tag libraries. Similar to JSP tags, Web form controls are added to an ASP.NET Web page using an HTML-like syntax. Unlike JSP tags however, a Web form control is actually an object that is contained within your ASP.NET page.
113
Tag libraries were designed so that Java code could be executed within a JSP page without using Java script blocks, which clutter up the HTML and break the design goal of separating display code from business logic. Instead of script blocks, tag libraries allow us to create custom HTML- like tags that map to a Java class that performs the business logic. Instead of script blocks, tag libraries allow you to create custom HTML-like tags that map to a Java class that performs the business logic. Groups of these HTML-like tags are called tag libraries.
114
Creating and using a custom tag library involves three things:
One or more classes that implement the javax.servlet.jsp.tagext.Tag interface.The Tag interface defines six methods that allow our JSP page to use the class to create the desired HTML output. There are also classes/interfaces that implement/extend the Tag interface, such as TagSupport and BodyTagSupport, to make it easier for us to develop our custom tag. An XML document that describes your tag library. Tag library description files must conform to the JSP tag library description DTD, and generally have an extension of "tld". Importing the tag library to the JSP page using the taglib directive. Once the three requirements are met, we can use the tags in our tag library anywhere within our JSP page.
115
Custom tags are user-defined JSP language elements that encapsulate recurring tasks. Custom tags are distributed in a tag library, which defines a set of related custom tags and contains the objects that implement the tags. Custom tags have the syntax <prefix:tag attr1="value" ... attrN="value" /> or <prefix:tag attr1="value" ... attrN="value" > body</prefix:tag> where prefix distinguishes tags for a library, tag is the tag identifier, and attr attrN are attributes that modify the behavior of the tag.
116
To use a custom tag in a JSP page, we must
Declare the tag library containing the tag. Make the tag library implementation available to the web application.
117
Declaring Tag Libraries
To declare that a JSP page will use tags defined in a tag library, we include a taglib directive in the page before any custom tag from that tag library is used. If we forget to include the taglib directive for a tag library in a JSP page, the JSP compiler will treat any invocation of a custom tag from that library as static data and will simply insert the text of the custom tag call into the response.
118
The following taglib directive directly references a TLD file name:
Syntax: taglib prefix="tt" [tagdir=/WEB-INF/tags/dir | uri=URI ] %> Here the prefix attribute defines the prefix that distinguishes tags defined by a given tag library from those provided by other tag libraries. If the tag library is defined with tag files, we supply the tagdir attribute to identify the location of the files. The value of the attribute must start with /WEB-INF/tags/. A translation error will occur if the value points to a directory that doesn’t exist or if it is used in conjunction with the uri attribute. The uri attribute refers to a URI that uniquely identifies the tag library descriptor (TLD), a document that describes the tag library Tag library descriptor file names must have the extension .tld. TLD files are stored in the WEB-INF directory or subdirectory of the WAR file, or in the META-INF directory or subdirectory of a tag library packaged in a JAR. You can reference a TLD directly or indirectly. The following taglib directive directly references a TLD file name: taglib prefix="tlt" uri="/WEB-INF/iterator.tld"%>
119
File Handling A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream. The stream is basically the sequence of bytes passing through the communication path. There are two main streams: The input stream and The output stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation).
120
VB.Net I/O Classes The System.IO namespace has various classes that are used for performing various operations with files, like creating and deleting files, reading from or writing to a file, closing a file, etc. The following table shows some commonly used non-abstract classes in the System.IO namespace: BinaryReader Reads primitive data from a binary stream. BinaryWriter Writes primitive data in binary format. FileStream Used to read from and write to any location in a file. StreamReader Used for reading characters from a byte stream. StreamWriter Is used for writing characters to a stream. StringReader Is used for reading from a string buffer. StringWriter Is used for writing into a string buffer.
121
The FileStream Class The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream. We need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows: Dim <object_name> As FileStream = New FileStream(<file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>)
122
Dim <object_name> As FileStream = New FileStream(<file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>) Here, FileMode The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are: Append: It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist. Create: It creates a new file. CreateNew: It specifies to the operating system that it should create a new file. Open: It opens an existing file. OpenOrCreate: It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file. Truncate: It opens an existing file and truncates its size to zero bytes. FileAccess FileAccess enumerators have members: Read ReadWrite Write.
123
3. FileShare FileShare enumerators have the following members:
Inheritable: It allows a file handle to pass inheritance to the child processes None: It declines sharing of the current file Read: It allows opening the file for reading ReadWrite: It allows opening the file for reading and writing Write: It allows opening the file for writing
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.