Dot Net
Dot Net
Dot Net
THOOTHUKUDI
R.AME RAYAN,
ASSISTANT PROFESSOR,
DEPARTMENT OF COMPUTER SCIENCE
ASP.NET
Chapter 1 : The .Net Platform and the web
AWeb Server : software that fulfils the client’s requests for content.
■ Packets transmitted along sockets arrive at the destination in exactly the order in
which it is transmitted.
■ Web applications communicates over the socket using higher level protocol – HTTP
02.07.2020
■ HTTP – is a command response system used for communication on the web.
■ The commands sent by the client are request for files(HTML documents and
images).
■ HTTP – stateless (when the client request is completed, the web server normally
closes the socket connection with the browser and forgets the details of the
exchange.
■ The first version of HTTP (version 0.9) – implemented one client command – the
08.07.2020
GET method.
■ The content was static text only (no multimedia).
Application
1. Customized logging
2. Advance security system
3. On- the- fly decryption
4. Modification of o/p stream.
20.07.2020
Overview of ASP.NET
Arrays are collection of data elements that all have the same data type.
Arrays have dimensionality which refers to the number of subscription to access each element in the array.
All arrays have at least one dimension and it can support upto sixty dimensions.
Arrays also have defined minimum and maximum for the subscriptions used to reference the array elements.
Array dimensions usually begin with zero.
Eg:
Dim a(5) as string
Dim s(10,10) as boolean
30.07.2020
R.Ame Rayan, Holy Cross Home Science College, Thoothukudi.
ReDim:
The redim statement is used to change the size of an array
after it has been declared using Dim
Eg:
ReDim ar(15) as string
Note :
when ReDim is used all the data contained in the array are
lost however to retain the contents of an array Preserve
keyword is used after the ReDim command
Eg:
ReDim Preserve ar(24) as string
Asize = Ubound(ar)
30.07.2020
To initialize the contents of an array at the time of array declaration
30.07.2020
the value of the constants do not change throughout the execution of the programme..
VB.NET provides a number of predefined constants.
Date and time constants are enclosed within pound signs (#)
Eg:
Const a as Date =#6/4/2020 3:30 AM#
Arithmetic Operators:
Syntax
variable = numeric expression1+ numeric expression2
Assignment operators
= - to assign value
^=. *=, /-,\=, +=, &=(concatenate two strings)
Bitwise operators
And,Or,Not, Xor
BitAnd
BitOr
BitNot
BitXor
Logical operators
And,or,not,Xor
Comparison
Operator
03.08.2020
Pattern matching characters in VB.NET
To invoke a function
Dim a as double
A= area(3,8)
Console.Writeline(a)
If expression then
statement1
Elseif (expression2)
statement2
Else
statement3
End if
Eg:
Dim a as integer =5
If a >0 and a<=10 then
console.writeline(“it is within the range”,a)
Else
console.writeline(“it is out of the range”,a)
End if
04.08.2020
R.Ame Rayan, Holy Cross Home Science College, Thoothukudi.
Select case statement
To check the value of an expression against several values and execute the code
based on each of those choices.
end select
04.08.2020
R.Ame Rayan, Holy Cross Home Science College, Thoothukudi.
Flow Control Statements
Definition
Eg:
Sub cp(Byval p as string)
if p <> “123” then
Exit sub
else
console.writeline(“Welcome”)
End if
End sub
04.08.2020
Goto Statements:
Sub eg()
console.writeline(“Welcome”)
goto h
console.writeline(“first”)
h:
console.writeline(“Second”)
End if
End sub
07.08.2020
Loops
Do ……..Loop loops
It can be executed in two ways :
(i) it executes the statement until test expression is true (Do until). This type of
loop is called as top driven loop.
Eg:
Do While i >30
console.writeline(i)
loop
(ii)it executes the statement as long as test expression is true (Do while). This
type of loop is called as bottom driven loop.
Eg:
Do
console.writeline(i)
Loop While i >30
07.08.2020
For ……Next
Sub demo()
Dim i as integer
For I = 1 to 5
console.wrtiteline(“Hello”)
next
End sub
•There is a optional keyword for the For… Next statement called step, which controls how
the counter variable is incremented or decremented..
•If no counter variable is specified then VB.NET assumes that it should be incremented by
1.
•By using the step clause, the loop is controlled in both in direction and the amount the
Eg:
07.08.2020
Sub demo()
For I = 1 to 10 step2
console.write(i)
next
End sub
o/p
0 2 4 6 8 10
Dim i as integer
For I = 10 to 0 step-1
console.write(i)
next
End sub
o/p
10 9 8 7 6 5 4 3 2 1 0
07.08.2020
For Each ….Next Loops
For Each I in a
console.writeline(a)
Next
Eg:
while demo(i<4)
console.writeline(i)
07.08.2020
R.Ame Rayan, Holy Cross Home Science College, Thoothukudi.
Handling Errors and Exceptions
Error are noticed during the execution of the program.
There are two types of error handling
(1) unstructured error handling.
(2) structured exception handling.
this is a simple type of error handling where a function is called and the return value if
checked. If the return value corresponds to a defined error result code, then an error
message is displayed.
Dim a as integer = 1
Dim b as integer = 2
Dim c as integer = 0
Dim r as integer
r = b/a
r=a/c
Done :
exit sub
Err_des:
console.writeline(Err.Description)
Goto Done
End sub
10.08.2020
Eg:
Try
if i >=1000 then
Throw New Exception(“ x is out of range”)
End if
Catch
console.writeline(“Error!)
Finally
console.writeline(“excecuting finally block”)
End Try.
Structured Exception Handling
10.08.2020
•Astructured error handler begins with Try keyword known as Try block.
•Each catch has an associated exception type and its declaration follows the Catch
keyword.
Eg: DivideByZeroException
•The error handling code includes the display of error message, resetting the
variables , exiting the function etc.,
•After all the exceptions have been tested and caught, code in the Finally block is
executed.
•The code if the Finally block can contain a success message or another
terminating message.
2. Compiled Code
When the user request a web page with ASP.NET code, ASP.NET compiles the code embedded in
that web page. This not only provides great speed enhancement but allows other features such as
strong variable typing and early binding of objects. ASP.NET can cache data for faster delivery through
special API’s.
ASP.NET provides various security measures. Users are authenticated using traditional methods
provided by IIS like BASIC and Windows and newer methods like Microsoft passport. Protecting site files
can be done by assigning user and group access to the individual files and directories.
Modern web applications usually consist of HTML and executable codes integrated within the HTML.
Web programs are sometimes supplemented by low level programs that interact with the web server
through tight integration.
* it begins with the plain text file that has .aspx extension.
• The contents in the .aspx file are called the pages.
• ASP.NET has the ability to store application code in a separate file rather than grouping it with
the HTML. This concept is called code behind.
• when a ASP.NET class is compiled , a new class that derives from the page class is
automatically generated.
• The .aspx file contains three new items
(i) ASP.NET page directives
(ii) the runat = “server” attribute
(iii) web controls.
The web applications use request-response model of communication : the web browser
request a document from the web server and the web server responds with the data from that
document.
The web application also contain HTML forms, which allow for user input.
The web browser must package up the data entered in the input form before sending it to the
server.
11.08.2020
• The data in the form can then be used as input for an ASP.NET program,
The page load event is fired when the page and all its control are rendered.
The page unload event is fired when the page is about to be discarded.
Web forms are used to provide dynamic web pages with ASP.NET.
Advantages :
(i) They provide event based programming model. Eg: click event in a button.
(ii) It allows a separation of application logic from content.
(iii)Its Integrated Development environment provide a easy design time environment.
(iv) The benefits of Rapid Application Development (RAD) combines event based programming with form
design tools.
VS.NET WEB APPLICATIONS AND OTHER IDE BASICS
14. 08.2020
R.Ame Rayan, Holy Cross Home Science College, Thoothukudi.
• VS.NET offers an easy way to create new ASP.NET web application projects.
• File->new ->projects from the menu bar and clicking the ASP.NET web application button.
• To add new web form to the application select add - >add web form.
• Then select the web form icon in the template section of the screen and give your new web
form a file name.
• The new web form is saved and become a part of the current solution.
• Whenever the user wants to view the code or when the user wants to place a web control on
the web form for the first time, a new code module is added to the solution that serves as the
code module for the web form.
• The code – behind module defines a new class for the web form and created plumbing code.
14.08.2020
SEPARTING CONTENT AND CODE – THE CODE BEHIND FEATURE
APPLICATION CONFIGURATION
• Applications in ASP.NET are comprised of a virtual web and pages, files and assemblies contained
within the directory and subdirectories.
• Those events are associated with the beginning and ending of the user sessions and ASP.NET
application.
17.08.2020
USING HTML CONTROLS
<a id="programmaticID"
href="linkurl"
name="bookmarkname"
OnServerClick="onserverclickhandler"
target="linkedcontentframeorwindow"
title="titledisplayedbybrowser"
runat="server" >
linktext
</a>
To display the new Web page by using the Target property. Target values must begin with a
letter in the range from a to z (case insensitive), except the following special values that begin
with an underscore: _blank, _self, _parent, and _top.
The HTML title attribute text serves as the floating tool tip test for the anchor.
18.08.2020
(iii) The HTMLButton control
<button
id="programmaticID"
OnServerClick="onserverclickhandler"
runat="server" >
buttontext, image, or control
</button>
Cascading style sheets (CSS) styles changes the appearance of the button.
<button runat="server">
style="font: 8pt verdana;
background-color:lightgreen;
border-color:black;
height=30;
width:100"
</button>
18.08.2020
(iv) The HTMLGenericControl control
Creates a server-side control that maps to the <img> HTML element and allows you to display
an image.
<img id="programmaticID"
alt="alttext"
align= top | middle | bottom | left | right
border="borderwidth"
height="imageheight"
src="imageURL"
width="imagewidth"
Thisrunat="server"
control allows you
> to dynamically set and retrieve the image's source, width, height, border width,
alternate text, and alignment by using the Src, Width, Height, Border, Alt, and Align properties, respectively.
When a user clicks an HtmlInputButton control, input from the form that the control is embedded on is
posted to the server and processed. A response is then sent back to the requesting browser.
<input type=button | submit | reset
By providing a custom event handler for the ServerClick event, you can perform a specific set of instructions when the control is clicked.
id="programmaticID"
Note OnServerClick="onserverclickhandler"
A reset button does not support the ServerClick event.
When a reset button>is clicked, all input controls on the page are not necessarily cleared.
runat="server"
Instead, they are returned to their original state when the page was loaded.
<input type=checkbox
id="programmaticID"
checked
runat="server" >
The HtmlInputCheckBox control does not post back to the server when it is clicked. The state of the
check box is sent to the server for processing when you use a control that posts back the server, such as
the HtmlInputButton control. To determine whether the check box is selected, test
the Checked property of the control.
<input type=file
id="programmaticID"
accept="MIMEencodings"
maxlength="maxfilepathlength"
size="widthoffilepathtextbox"
postedfile="uploadedfile"
runat="server" >
The HtmlInputFile control can be used to easily design a page that allows users to upload binary or text files from a browser
to a directory that you designate on your Web server.
File upload is enabled in all HTML 3.2 and later Web browsers.
Note You must set the enctype attribute of the form to "multipart/form-data".
19.08.2020
Web controls for displaying and formatting data
<asp:Label id="Label1"
Text="label"
runat="server"/>
or
<asp:Label id="Label1"
runat="server">
Text
</asp:Label>
Eg:
borderstyle, unit.
Panel control :
web pages can contain many different elements and controls and they can be contained in one group.
Provides a container for other controls. This control is rendered as an HTML <div> element.
<asp:Panel id="Panel1"
BackImageUrl="url"
HorizontalAlign="Center|Justify|Left|NotSet|Right"
Wrap="True|False"
runat="server">
</asp:Panel>
24.08.2020
R.Ame Rayan, Holy Cross Home Science College, Thoothukudi.
The Panel control is a container for other controls. It is especially useful for generating controls
programmatically and displaying and hiding groups of controls.
You can display an image in the background of the Panel control by setting
the BackImageUrl property.
Using the HorizontalAlignment property, you can specify the horizontal alignment of the items
contained in the control.
The Wrap property lets you determine whether items in the control automatically continue on the
next line when a line is longer than the width of the panel.
24.08.2020
(iii) TABLE, TABLEROW AND TABLE CELL CONTROLS
<asp:Table id="Table1"
BackImageUrl="url"
CellSpacing="cellspacing"
CellPadding="cellpadding"
GridLines="None|Horizontal|Vertical|Both"
HorizontalAlign="Center|Justify|Left|NotSet|Right"
runat="server">
<asp:TableRow>
<asp:TableCell>
Cell text
</asp:TableCell>
</asp:TableRow>
</asp:Table>
24.08.2020
The Table class allows you to build an HTML table and specify its characteristics. A table can be
built at design time with static content, but the Table control is often built programmatically
Each Table control is made up of rows (represented by instances of the TableRow class)
stored in the Rows collection of the control.
Each row is made up of cells (represented by instances of the TableCell class) stored in
the Cells collection of the each TableRow.
The spacing between individual cells is controlled by the CellSpacing property. You can
specify the amount of space between the contents of a cell and the cell's border by setting
the CellPadding property.
To display the cell borders, set the GridLines property. You can display the horizontal lines,
vertical lines, or both horizontal and vertical lines.
WEB CONTROLS FOR CREATING BUTTONS
25.08.2020
All the buttons in ASP.NET cause a post-back to the server.
The button control renders the regular push button, the most common type of button seen is the HTML
button.
<asp:Button id="MyButton"
Text="label"
Command="command"
CommandArgument="commandargument"
CausesValidation="true | false"
OnClick="OnClickMethod"
runat="server"/>
Unique properties:
• The text properties specifies the text ot display on the button itself, such as “Submit Form”.
• The “On-click” property sets the procedure name to call when the button is clicked.
• Command – The event fired by the child control event can be bubbled up to the parent the message
contained in the command property.
• Command Arguments : an optional command parameter is passed in the CommandArgument property.
25.08.2020
ImageButton Control :
<asp:ImageButton id="ImageButton1"
ImageUrl="string"
Command="Command"
CommandArgument="CommandArgument"
CausesValidation="true | false"
OnClick="OnClickMethod"
runat="server"/>
• The ImageButton control is used to display an image that responds to mouse clicks.
• Specify the image to display in the control by setting the ImageUrl property.
• Both the Click and Command events are raised when the ImageButton control is clicked.
25.08.2020
The LinkButton Control
<asp:LinkButton id="LinkButton1"
Text="label"
Command="Command"
CommandArgument="CommandArgument" Specify the text to display in
CausesValidation="true | false" the LinkButton control by either setting
OnClick="OnClickMethod" the Text property or placing the text
runat="server"/> between the opening and closing tags of
or the LinkButton control.
<asp:LinkButton id="LinkButton1"
Command="Command"
CommandArgument="CommandArgument"
CausesValidation="true | false"
OnClick="OnClickMethod"
runat="server"/>
Text
</asp:LinkButton>
25.08.2020
Web Controls for Inputting Text
<asp:TextBox id="value"
AutoPostBack="True|False"
Columns="characters"
MaxLength="characters"
Rows="rows"
Text="text"
TextMode="SingleLine | MultiLine | Password"
Wrap="True|False"
OnTextChanged="OnTextChangedMethod"
runat="server"/>
• The TextMode property is set to SingleLine, which creates a text box with only one line.
• Set the property to MultiLine or Password. MultiLine creates a text box with more than one line.
• Password creates a single-line text box that masks the value entered by the user.
25.08.2020
• The display width of the text box is determined by its Columns property.
Selection control includes Radio Button and CheckBoxes, which allow users to select from a series of
predefined values.
These selection controls are grouped together to represent choices in the same property.
Radio Buttons, like checkboxes, allow users to select from the list of options, one choice in a category is
selected.
Each checkbox can have a label, which appear to the right or left of the checkbox, according to the
TextAlign property.
25.08.2020
The default state of the checkbox and its current state are indicated by the Checked property.
RadioButton control
These controls are used when web controls are generated dynamically from the data source.
The data source may contain fairly large amount of data.
<asp:CheckBoxList id="CheckBoxList1"
AutoPostBack="True|False"
CellPadding="Pixels"
DataSource='<% databindingexpression %>'
DataTextField="DataSourceField"
DataValueField="DataSourceField"
RepeatColumns="ColumnCount"
RepeatDirection="Vertical|Horizontal"
RepeatLayout="Flow|Table"
TextAlign="Right|Left"
OnSelectedIndexChanged="OnSelectedIndexChangedMethod
"
runat="server">
<asp:ListItem value="value"
selected="True|False">
Text
</asp:ListItem>
</asp:CheckBoxList>
Properties of CheckBoxList and RadioButton Controls
26.08.2020
R.Ame Rayan, Holy Cross Home Science College, Thoothukudi.
Checkbox List: <asp:CheckBoxList id="CheckBoxList1"
AutoPostBack="True|False"
Creates a multiselection check box group. CellPadding="Pixels"
This control supports binding to a data source.DataSource='<% databindingexpression %>'
DataTextField="DataSourceField"
DataValueField="DataSourceField"
RepeatColumns="ColumnCount"
RepeatDirection="Vertical|Horizontal"
RepeatLayout="Flow|Table"
TextAlign="Right|Left"
OnSelectedIndexChanged="OnSelectedIndexChangedMethod"
runat="server">
<asp:ListItem value="value"
selected="True|False">
Text
</asp:ListItem>
</asp:CheckBoxList>
The CheckBoxList control creates a multiselection check box group that can be dynamically
26.08.2020
generated using data binding.
The CheckBoxList control also supports data binding. To bind the control to a data source, first
create a data source, such as a System.Collections.ArrayList object, that contains the items to
display in the control.
Next, use the Control.DataBind method to bind the data source to the CheckBoxList control.
Use the DataTextField and DataValueField properties to specify which field in the data source to
bind to the Text and Value properties of each list item in the control, respectively.
The CheckBoxList control will now display the information from the data source.
27.08.2020
R.Ame Rayan, Holy Cross Home Science College, Thoothukudi.
To determine the selected items in the CheckBoxList control, iterate through the Items collection and
test the Selected property of each item in the collection.
You can specify the way the list is displayed by using the RepeatLayout and RepeatDirection properties.
If RepeatLayout is set to RepeatLayout.Table (the default setting), the list is rendered within a table.
Radiobuttonlist Control
Creates a group of radio buttons. This control supports binding to a data source.
27.08.2020
<asp:RadioButtonList id="RadioButtonList1"
<asp:ListItem Text="label"
Value="value"
Selected="True|False" />
</asp:RadioButtonList>
The RadioButtonList control allows you to create a single-selection radio button group that can
27.08.2020
be dynamically generated by binding to a data source. To specify the items that you want to
appear in the RadioButtonList control, place a ListItem element for each entry between the
The RadioButtonList control also supports data binding. To bind the control to a data source, first
create a data source, such as a System.Collections.ArrayList object, that contains the items to
display in the control. Next, use the Control.DataBind method to bind the data source to
the RadioButtonList control.
Use the DataTextField and DataValueField properties to specify which field in the data source to
bind to the Text and Value properties, respectively, of each list item in the control.
The RadioButtonList control will now display the information from the data source.
You can specify the rendering of the list with the RepeatLayout and RepeatDirection properties.
If RepeatLayout is set to RepeatLayout.Table (the default setting), the list will be rendered within
a table. If it is set to RepeatLayout.Flow, the list will be rendered without any tabular structure. By
default, RepeatDirection is set to RepeatDirection.Vertical. Setting this property
to RepeatDirection.Horizontal will render the list horizontally.
27.08.2020
ListBox Control
<asp:ListBox id="Listbox1"
DataSource="<% databindingexpression %>"
DataTextField="DataSourceField"
DataValueField="DataSourceField"
AutoPostBack="True|False"
Rows="rowcount"
SelectionMode="Single|Multiple"
OnSelectedIndexChanged="OnSelectedIndexChangedMethod"
runat="server">
</asp:ListBox>
28.08.2020
Use the ListBox control to create a list control that allows single or multiple item selection. Use
the Rows property to specify the height of the control. To enable multiple item selection, set
To specify the items that you want to appear in the ListBox control, place a ListItem element for
each entry between the opening and closing tags of the ListBox control.
The ListBox control also supports data binding. To bind the control to a data source, first create
a data source, such as a System.Collections.ArrayList, that contains the items to display in the
control. Next, use the Control.DataBind method to bind the data source to the ListBox control.
Use the DataTextField and DataValueField properties to specify which field in the data source
to bind to the Text and Value properties, respectively, of each list item in the control.
The ListBox control will now display the information from the data source.
The index can then be used to retrieve the item from the Items collection.
28.08.2020
Image Control
Use the Image control to display an image on the Web Forms page.
Setting the ImageUrl property specifies the path to the displayed image. You can specify the text
to display in place of the image when the image is not available by setting
the AlternateText property.
The ImageAlign property specifies the alignment of the image in relation to other elements on
the Web Forms page.
29.08.2020
ASP .NET PAGE DIRECTIVES
The Page directive defines the attributes specific to the page file for the page parser and
the compiler.
28.08.2020
Attributes Description
AutoEventWireup The Boolean value that enables or disables page events
This could appear either in the global.asax file for application-wide linking, in the page file,
a user control file for linking to a page or user control.
The basic syntax of Assembly directive is:
<%@ Assembly Name ="myassembly" %>
The attributes of the Assembly directive are:
Attributes Description
@outputCache
The OutputCache directive controls the output caching policies of a web page or a user control.
The basic syntax of OutputCache directive is:
<%@ OutputCache Duration="15" VaryByParam="None" %>
01.09.2020
ASP.NET RICH CONTROLS
Syntax
<asp:Calendar id="Calendar1"
runat="server">
Property Description Style class
01.09.2020
DayHeaderStyle The style for the section of the calendar where TableItemStyle
the names of the days of the week appear.
<asp:AdRotator
id="Value"
AdvertisementFile="AdvertisementFile"
KeyWordFilter="KeyWord"
Target="Target"
OnAdCreated="OnAdCreatedMethod"
runat="server"/>
• The AdRotator control uses a separate XML advertisement file to store the advertisement
information, such as the location of the image to display and the URL of the page to link to.
• The AdvertisementFile property of the AdRotator control specifies the path to this file.
When creating the advertisement file, opening and closing <Advertisements> tags mark the
beginning and the end of the file, respectively.
• Opening and closing <Ad> tags delimit each advertisement. All advertisements are nested
between the opening and closing <Advertisements> tags.
• If the file contains multiple <Advertisements> tags, only the first set of <Advertisements> tags in
02.09.2020
the file will be parsed by the AdRotator control.
• The data elements for each advertisement are nested between the opening and closing <Ad> tags.
• Although certain data elements are predefined (such as ImageUrl and NavigateURL), you can place
custom elements between the <Ad> tags.
• These elements will be read by the AdRotator control when it parses the file. The information is then
passed to the AdCreated event in the AdProperties dictionary property.
Property Description
Advertisement File sets the relative paths to the advertisement data file (in Xml)
Keyword Filter Designates a keyword to use that filters the advertisements. If specified, only
banner ads that have a keyword that maches the value in keywordfilter are eligible for display.
Target specifies the name of the browser window or frame in which to display the
advertisement. Keywords such as _TOP, _NEW,_CHILD,_SELF,_PARENT,_BLANK can be used.
02.09.2020
The impression feature allows to make a particular banner ads appear more often than others.
It defines an error called OnAdcreated. This event is raised upon the next post-back to the server whenever
the advertisement changes.
It is useful for adjusting the content of the rest of the page based on which based on the add the Adrotator
control is picked.
•RequiredFieldValidator
•RangeValidator
•CompareValidator
•RegularExpressionValidator
•CustomValidator
•ValidationSummary
BaseValidator Class
The validation control classes are inherited from the BaseValidator class hence they inherit its
properties and methods. Therefore, it would help to take a look at the properties and the methods of
this base class, which are common for all the validation controls:
Members Description
ControlToValidate Indicates the input control to validate.
ValidationGroup The logical group of multiple validators, where this control belongs.
Validate() This method revalidates the control and updates the IsValid property.
RequiredFieldValidator Control
The RequiredFieldValidator control ensures that the required field is not empty.
It is generally tied to a text box to force input into the text box.
The syntax of the control is as given:
<asp:RequiredFieldValidator ID="rfvcandidate" runat="server" ControlToValidate ="ddlcandidate"
</asp:RequiredFieldValidator>
RangeValidator Control
The RangeValidator control verifies that the input value falls within a predetermined range.
It has three specific properties:
The syntax of the control is as given:
<asp:RangeValidator ID="rvclass" runat="server"
ControlToValidate="txtclass" ErrorMessage="Enter your class (6 - 12)"
MaximumValue="12" MinimumValue="6" Type="Integer"> </asp:RangeValidator>
Properties Description
Type It defines the type of the data. The available
values are: Currency, Date, Double, Integer, and
String.
MinimumValue It specifies the minimum value of the range.
MaximumValue It specifies the maximum value of the range.
CompareValidator Control
The CompareValidator control compares a value in one control with a fixed value or a value in another control.
It has the following specific properties:
The basic syntax of the control is as follows:
<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="CompareValidator">
</asp:CompareValidator>
Properties Description
Type It specifies the data type.
ControlToCompare It specifies the value of the input control to compare with.
The RegularExpressionValidator allows validating the input text by matching against a pattern of a regular expression.
The regular expression is set in the ValidationExpression property.
The following table summarizes the commonly used syntax constructs for regular expressions:
Apart from single character match, a class of characters could be specified that can be matched, called the metacharacters.
Character Description
Escapes
\b Matches a backspace.
\t Matches a tab.
\r Matches a carriage return.
\v Matches a vertical tab.
The syntax of the control is as given:
\f Matches a form feed.
<asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string"
\n Matches a new line. ValidationExpression="string" ValidationGroup="string">
The CustomValidator control allows writing application specific custom validation routines for both the client side and the server side validation.
The client side validation is accomplished through the ClientValidationFunction property.
The client side validation routine should be written in a scripting language, such as JavaScript or VBScript, which the browser can understand.
The server side validation routine must be called from the control's ServerValidate event handler. The server side validation routine
should be written in any .Net language, like C# or VB.Net.
The basic syntax for the control is as given:
</asp:CustomValidator>
Data List Control
The Web controls that produce list are called List Controls.
The data for the list controls can come from a variety of sources they are:
Flat files, XML, relational databases.
A list header, list item and list footer can each have different styles.
The Repeater Control uses the following syntax :
<HeaderTemplate>
Header template HTML
</HeaderTemplate>
<ItemTemplate>
Item template HTML
</ItemTemplate>
<AlternatingItemTemplate>
Alternating item template HTML
</AlternatingItemTemplate>
<SeparatorTemplate>
Separator template HTML
</SeparatorTemplate>
<FooterTemplate>
FooterTemplate HTML
</FooterTemplate>
<asp : Repeater>
HTML is specified for rows, headers and footers for a particular list.
Template Description
AlternatingItemTemplate HTML to render for alternating rows in the list
FooterTemplate HTML to render at the end of all the rows in the
list
HeaderTemplate HTML to render before any rows in the list are
rendered
ItemTemplate HTML to render for each row to the list
SeparatorTemplate HTML to render between rows in the list.
User Control
• The ASP.NET controls allows to build most web applications with ease.
• This code is likely to be reused many times and in many different projects.
• When ASP.NET code is packaged up as a user control, it makes reuse of the code
as another web form as easy as supplying a new page directive at the top of the
Web form and placing the User Control in the page.
• User controls are used within a Web Form similar to other web controls are used.
ASP.NET provides an option to save state across page requests without saving any information on the
server.
ViewState is a static object of type StateBag that can be used to store arbitrary values across page
requests.
Properties
Methods:
Add – adds a new StateItem object to the StateBag object. If the item already exists in the StateBag object
Add updates the value of the item.
GetEnmerator – returns an enumerator that iterates over all the key-value pairs of the StateItem ibjects stored
in the StateBag object.
IsItemDirty –checks StateItem object stored in the StateBag object to evaluvate whether it has been modified
since the call to Control.TrackViewState.
Remove – removes the specified StateItem object from the StateBag Object.
Every webform has access to the ViewState object, which is a static object that is not declared explicitly.
Any value can be stored in the ViewState Collection.
Eg:
Writing to viewstate
ViewState(“a”) = “Test”
Def : It is a set of objects in the ASP.NET that provides low level access to web application protocols and
frameworks.
We can directly work with CGI,HTTP stream and session management capabilities of ASP.NET.
It also provides compatibility with the classic ASP, this is the only to provide webserver functionality
through program code.
This is responsible for retrieving information sent in an HTML form. The HTML form data can be sent using
two methods : HTTP GET and HTTP POST.
The CGI encoding scheme is used to encode data as name-value pair, where name is the name of the
HTML form and value is the data associated with the form element.
The HttpResponse object methods programmatically control the HTTP output stream.
Using HttpResponse
The HttpServerUtility object contains some miscellaneous utility functions and accesses properties on the
web server
With the HttpServerServer object,performs HTML/URL encoding, resolve physical pathnames on the server
and create instances of COM software components.
It is used to store application – persistent data available for all users of the web application to access.
The HttpApplicationState Object stores all of its application variables in collection.
Application(“a”)=value
The value assigned to the application variable can be of any type, including string, numeric and other
variable.
HttpSessionState class van be used to declare variables that have session scope.
This can be also used to find the left time of the user
Example:
Imports System
Imports System.Collections
Imports Microsoft.VisualBasic
Module Module1
Sub Main()
DisplayStackContents(UndoStack)
End Function
Sub DisplayStackContents(By Ref UndoStack As Stack)
Dim strphrase As String
Dim aryStandardArray As Object()
Dim intIndex As Integer
Console.Write(“Current contents:”)
aryStandardArray = UndoStack.ToArray
End Sub
End Module
➢ The AddPhrase() function handles pushing and
popping.
➢ Peek()method:allows the user to look at the value
before it is popped off the stack.
➢ Pop()function:it removes from the top of the pop.
➢ Push()method:to add an element.
➢ ToArray()method:to obtain a string array
representation of the data in the stack.
Imports System
Imports System.Collections
Imports Microsoft.VisualBasic
Module Module1
Public Class DocRecord
Public DocTitle As String
Public DocOwner As String
Public DateTimeSubmitted As Date
Sub New(Optional ByVa1 DTitle = “ ”,
Optional ByVa1 Downer =“”)
DocTitle = DTitle
DocOwner = Downer
End Sub
End Class
Function InitializeQueue() As Queue
Dim objDocQueue As New Queue()
Dim objDoc As DocRecord
Dim intIndex As Integer
For intIndex = 1 To 5
objDoc = New DocRecord()
With objDoc
.DocOwner = “joe”
.DocTitle = “Document #” &
intIndex.ToString()
End With
objDocQueue.Enqueue(objDoc)
Next
InitializeQueue = objDocQueue
End Function
Sub AddDocToQueue(ByVa1 DocQueue As Queue,
ByVa1 Doc As DocRecord)
DocQueue.Enqueue(Doc)
Console.WriteLine(“{0} submitted to queue”,
Doc.DocTitle)
End Sub
Imports System
Imports System.Collections
Imports Microsoft.VisualBasic
Module Module1
End Class
If Not objContact Is Nothing Then
Console.WriteLine(
“Contact info: “ & ControlChars.Crlf &
“Last Name: {0}” & ControlChars.Crlf &
“First Name: {1}” & ControlChars.Crlf &
“Age: {2}” & ControlChars.Crlf &
objContact.m-strLastName,
objContact.m-strFirstName,
objContact.m-intAge. ToString())
Else
Console.WriteLine(“Contact not found”)
End If
End Sub
End Sub
Sub Main
Dim objMyContacts As New Hashtable()
AddContact(objMyContacts)
AddContact(objMyContacts)
AddContact(objMyContacts)
ListContacts(objMyContacts)
QueryContacts(objMyContacts)
End Sub
End Module
The Item() method is used to search an object in the hashtable.
A unique key value must be used to insert a new object into a hashtable.
The key value for each contact is randomly generated.
Handling file input/output :
File input/output plays key role in all application. The file class encapsulates
various operation that can be performed on a single file such as, creating,
copying, deleting, moving, opening.
The methods of the file class return special classes that are
used to read & write, this is collectively known as stream
classes.
Module modul=1
Sub main()
Try
ObjstreamReader =file .Opentext(“test.txt”)
Catch E as exception
End try
End sub
End module
Writing text files:
We can write a text file using the streamWritter class. The
streamWritter class can write data to the stream in number
of ways they are , writing a single character , a character
array , an object, a subset of a character array, simple
data types( boolean, decimal, integer, long, double)
Reading binary files:
The MP3ID3VI class contains member variable for each of the IB3VI segment that
occur at different offsets in the file
The overloaded new () constructor calls the function that reads the song
information
The work of reading that ID3V1 block begins with opening the file by creating
a new filestream object in line.
writing Binary files:
● Description
● Gets the character encoding
● Returns the stream object
Properties of StreamWritter class:
● Property
● Aut of Tusb
● BaseSteam
● Encoding
● Format provider ( Textwritter)
● New line
● Description
● All output bound for the stream to be witten immediately when the value is true
● Returns the underlying stream object
● Gets the encoding in which the output is written
● Gets an object that contains formatting
● Gets or sets the line string used by the current Textwritter class
Performing file operations :
The file class helps you whenever you wish to change characteristics manage
files
The open Text() method to return a filestream object for writing text files
Object factory for stream object the class can be used to rename, delete,
move snd copy files
The files class methods are static so it has no constructor and it's available
at any time in the program
The file Info class offers instance method of the same functionally as the file
class
Copying, moving & Renaming files :
To make a copy of a file and rename it using the copy To () method and the move
To () method
( Refer program in the book)
Deleting files:
We delete a file using the staticdelete () method of the file class
( Refer program in the book)
Using binary file I/O with the filestream object:
Graphic images, contain binary data that is the bytes in the files extend
beyond what can be represented using text encoding method such as
ASCII
The stream Reader & StreamWritter classes are designed to handle
only text data for reading binary files the filestream and binary reader
objects should be used for writting binary file use the binarywritter object
together with the filestream object.
4.5 USING THE WINDOWS EVENT LOG ( System.diagnostics)
● The first version of windows NT , a comman event log has been used as a tool to
record application errors and events.
● Windows event log and it’s common repository that all applications use to record
application events.
● The contents of the windows event log are viewed using the event viewer
application.
● To launch the event viewer in windows 2000 , right click on the my computer icon
and select manage.
● Computer Management → System Tools → Event Viewer.
● The event viewer is comprised of 3 different logs : 1. Application log 2. Security log
3. System log.
● These are used to record program events , security events and audits , and low
level device and system events respectively.
● The type column describes the type of the event.
● This is usually information warning are error.
● The date and time columns indicate the date and time respectively , that the event
was posted to the log.
● The EventLog object is very versatile and provides facilities to read , write and
query events
● This programs writes a string to the application log and read the current entries
from the same log.
SAMPLE PROGRAM:-
Imports system
Imports system.Diagnostics
Import Microsoft.VisualBasic
Module Module1
Sub main()
Dim strLogstr As String
Console.Write(“Enter a string”)
strLogStr = Console.ReadLine()
WriteToLog(strLogStr)
ReadApplicationLog()
End Sub
End Module
● We proceed to line where we create a new EventLog object.
● We set the log and MachineName properties with the values
“Application” and “.” , respectively.
● With those properties set we are ready to retrieve information about the
log.
● We start a For ….Each loop to iterate the collection of EventLogEntry
object in entries.
4.6 Working with Active Directory Services
(System.DirectoryServices)
➢ The term directory, as it relates to Active Directory Services is
a general one.
➢ It does not specifically refer to directories on your file
systems(folders) but instead to any data stored in a hierarchical
manner.
➢ Examples of directories include a name and address book, an
employee roster, and a store of account information on
multiuser computer system.
➢ Each of these directories is referred to as a namespace.
➢ A name space is a root node in the directory service.
➢ The children of these nodes are called container objects.
➢ Container object is can contain other container objects and also
leaf objects.
The following released providers can be used with Active
Directory Services:
❖ Windows NT 4.0 Directory Services: This is the most
widely used directory service. Windows NT 4.0 Directory Services
allow you to completely administer a Windows 2000/NT server or
domain. You can control Windows 2000/NT services, including
starting, stopping, and setting the start up status.
❖ Lightweight Directory Access Protocol (LDAP) and
Exchange Server: LDAP is an Internet standard protocol for
communicating with a wide variety of directory services. One
application for LDAP is to provide access to data on Microsoft
Exchange Server. Active Directory Services allows access to items
such as message stores and recipient data.
❖ Internet Information Server (IIS) : With the IIS provider, we can
perform many administrative tasks relating to IIS. For example, you can
manage virtual directories in the Web server filespace, set up other Internet
services like FTP, manage log files, and configure settings for the servers.
❖ Novell Directory Services (NDS): Active Directory Services also
allows access to NDS.
Imports System
Imports System.IO
Imports System.DirectoryServices
Imports Microsoft.VisualBasic
Module Modulel
Public Sub GetADInfo(ByVal ADPath As String)
Dim strKey As String
Dim objValue As Object
Dim objDirEnt As DirectoryEntry
Try
objDirEnt = New DirectoryEntry(ADPath)
End Sub
Sub Main()
GetADInfo(“WinNT://mdevbiz01”)
Console.WriteLine(“----------------------------”)
GetADInfo(“WinNT://rmdevbiz01/matt”)
End Sub
End Module
In the example above, we use the name of a computer on the
network,RMDEVBIZ01, to construct new DirectoryEntry object in line. After
the constructor executes and the node is located, the properties of the
DirectoryEntry object are populated in the code block beginning in line.
Nodes in Active Directory Services can contain any number of properties.
These properties are housed in a PropertyCollection object. Ther propertyNames
and value properties of the propertyCollection object are of particular interest.
They are both collections that contain the names and values, respectively, of the
node. Each value in the ProptertyNames collection can contain one or more
values objects. So, with that in mind, we use two nested For…Each loops to visit
each value in the PropertyCollectilon object. The outer loop that begins in line.
Obtains all the names of the properties. Each Property name is then used as an
index into the Properties collection to obtain individual values for the property in
the inner loop that starts in line.
OUTPUT:
Name = RMDEVBIZ01
Path = WinNT://rmdevbiz01
SchemaClassName = Computer
Properties:
OperatingSystem =
windows NT
OperatingSystemVersion =
5.0
Owner =
SampleOwner
Division =
SampleDivision
ProcessorCount =
Uniprocessor Free
Processor =
x86 Family 6 Model Stepping 2
Searching Active Directory Services Contents:
➢ Sometimes we need to locate a particular item in Active Directory Services
by using a searching mechanism.
➢ Often personnel directories are kept in an LDAP store made publically
available.
➢ LDAP is also a very popular way to locate individuals on the Internet.
Example
Public Sub SearchAd(ByVal LastName As String)
objSearchRScoll = objADSearch.FindAll()
For Each objADSearchResult In objSearchRScoll
objTmpDirEnt = _
objADSearchResult.GetDirectoryEntry()
Console.WriteLine(objTempDirEnt.Name)
Next
Catch E As Exception
Console.WriteLine(“ERROR: “ & E.Message)
End Try
End Sub
In the DirectoryEntry object’s constructor, we supply a URL to the
LDAP SERVER In the form LDAP://yourserverhere . Com.
The code then moves on to next line, where the DirectorySearcher object is
created.
Next Line executes the actual search. Since more than one user in the LDAP
directory might match the query, the results are returned in the form of a
SearchResultCollection object that implemtns the Icollection interface.
Inside the For…Each loop, notice jthe call to the GetDirectoryEntry() method
in line. This method of the SearchResult class is used to obtain a DirectoryEntry
object for each SearchResult object in the objSearchRSColl
SearchResultCollection.
After this DirectoryEntry object is retrieved, we can display information
about it, such as its Name property. This returns the LDAP common name (cn)
for the object, which usually contains the person’s full name.
Properties of the SearchResult Class
Property Description
Method Description
GetDirectoryEntry Gets the DirectoryEntry object that matches with the SearchResult object.
Properties of the SearchResultsCollection Class
Property Description
Try
If Not MessageQueue. Exists (“.\” & Qname ) Then
objQueue = MessageQueue. Create (“.\” & Qname )
Else
objQueue = New MessageQueue (“.\” & Qname )
End If
CreatePublicQueue = objQueue
Catch E As Exception
Console.Writing (“Error: “& E.Message)
End Try
End Function
SENDING A MESSAGE TO A QUEUE:
▪ Sending a message to queue is simple.
● The following example sends a String object to the queue, you can send any
object type ( System.Object) to the queue using the Send () method.
Public Sub SendMessageToQueue(
Byval Q As MessageQueue, Byval Msg As String )
Q. Send( Msg)
End Sub
DEQUEUING A MESSAGE:
o Dequeuing a message is done by calling the
Receive() method.
o This method returns a Message object, which
contains the body of the message queue plus many
different message characteristics.
Public Function Dequeue (ByVal Q As MessageQueue )
As String
Dim objQMsg As Message
objQMsg = Q.Receive()
Dequeue = objQMsg.Body
End Function
Communicating with server on the internet
▪ The system.NET . Sockets namespace contain classes and types for establishing connection using TCP and also UDP
(User Datagram Protocol) another method of network Communication on the internet.
▪ The Microsoft.NET Framework system .Net . Sockets class wraps function of the windows Sockets API, which was the
standard way for writing Internet application software.
) another method of network Communication was the standard way for writing Internet application software.
4.8 A simple TCP client application
• The TcpClient class contains functionally to open and close connection and to obtain
stream object on which to send and receive data.
• This Example implement a very Simple Web Client.
• HTTP Get command is sent over the socket connection and the response from the server is
received and then displayed.
A simple TCP server application
• The .NET Framework system .Net . Socket classes also allow you to
write TCP server.
• A program for a rudimentary TCP server that is displays incoming
data as it is received.
• The smallserver below listen for connection request and display
incoming data from the TCP client.
n for connection request and display incoming data from the TCP client.
Properties of the Tcplistener class
Server • Gets or sets a value that Indicates
• Active whether the listener’s socket has
been bound to a port started
listening.
• Server • Gets or sets the underlying
network societ.
HTTP communication
• The TCP client example showed how you can use the TcpClient class
to retrieve documents from the Web server using HTTP commands.
• Two classes in the .Net Framework, system .Net .WebRequest and
System .Net .WebResponse, handle the most of the low-level
details of HTTP based network communication.
• To implement yourself if you resorted to using the System .Net .
Sockets classes.
Method of WebResponse class
4.9 Manipulating XML Data
❖ So much has been said lately about XML that it may soon become a
household name
❖ Rightfully so because XML is the technology that drives efficient data
exchanges
❖ XML based enables elegant modelling of data
❖ .NET framework has extensive support for manipulating XML data
❖ The .NET framework includes two different XML parsers
1. A tree based parser
2. A stream based parser
Creating tree based XML documents
▪The tree XML based parser reads an entire XML document
▪Memory to construct a tree data structure ture representation of the XML data
Example
GGHITREWSEYRERTYUUTRETYTYREGGGGG
Xml Vali dating reader (objXml textreader)
Objxmldoc.load(objxmlvalidatingreader)
Displaynode (objxmldoc.childnodes)
Catch E As Exception
Console.writline(“ERROR:”&E.message)
End Try
End sub
Searching XML Nodes
❖ XML Node list object that contains the items that matched the query
❖ The query is expressed in a language called X path
❖ World wide web standard for searching the XML DOM
EXAMPLE
]>
<Songs>
<song format =“MP3”>
<title>Eh cumpar</title>
<artist>Julius LaRosa</artist>
<length>149<?length>
<category>Italian-American</category>
</song>
<song format=“co”>
<title>plasticity</title>
<artist>front line assembly </artist>
<length>486</length>
<category>industrial<category>
</song>
</songs>
Reading XML Data with validation
● The XmlTextReader class is the mechanism used for reading XML data in a stream-
based fashion.
● There are many properties and methods to this class.
Here’s an example:
Imports System
Imports System.Xml
Module Module1
Sub Main()
Dim objReader As XmlTextReader = Nothing
Try
objReader = New XmlTextReader (“Songs.xml”)
while objReader.Read()
select Case objReader.NodeType
Case XmlNodeType.Element
Console.WriteLine(“<{0}>”, objReader.Name)
Case XmlNodeType.Text
Console.WriteLine(objReader.Value)
Case XmlNodeType.XmlDeclaration
Console.WriteLine(“<?xml version=‘1.0’?>”)
Case XmlNodeType.EndElement
Console.WriteLine(“</{0}>”, objReader.Name)
End select
End While
Finally
if not (objReader Is Nothing) Then
objReader.Clode()
End if
End Try
End sub
End Module
✓ Document declarations
✓ Text nodes
writer.Formating = Formating.Intended
writer.WriteStartElement (“Songs”)
writer.WriteStartElement (“Song”)
writer.WriteStartElement (“title”)
writer.WriteString (“Plasticity”)
writer.writeEndElement()
writer.WriteStartElement (“artist”)
writer.WriteString (“Front line assembly”)
writer.writeEndElement()
writer.WriteStartElement (“category”)
writer.WriteString (“Industrial”)
writer.writeEndElement()
writer.WriteStartElement (“length”)
writer.WriteString (“406”)
writer.writeEndElement()
writer.WriteEndElement ()
writer.WriteEndElement ()
writer.Flush()
writer.Close()
Console.Write(doc.InnerXml)
End sub
➢ This functions begins with creating a new XmlTextWriter object in line.
➢ The default behaviour of the XmlTextWriter class is not to include any of the white
space.
➢ The behaviour can be changed by setting the Formatting property as shown in line.
➢ A comment block to the file with the writeComment() method in a line.
➢ XML file to begin a code is WriteStartElement() and to end a code with
WriteEndElement().
➢ Like the beginning and ending, WriteStartElement() and WriteEndElement(), we use
WriteEndAttribute() method in line and WriteEndAttribute() method in line.
➢ The text of the attribute is added with WriteString() method in line.
FORMATTING XML DATA FOR DISPLAY:
● XML is great for representing structured data, but it cant be displayed to the
user in any meaningful way.
● XML is human-readable.
● It would be useful to transform XML data into a more convenient format for
display.
● One can accomplish this by using XSLT (Extensible Stylesheet
Transformation) and XslTransform class.
Here’s a small program to demonstrate
Imports System
Imports System.Xml
Imports System.Xml.Xsl
Module Module1
Sub Main()
Dim objXSLT As XslTransform()
Try
objXSLT.Load(“songs.xsl”)
objXSLT.Transform(“c:\songs.xml”,”songs.html”)
Catch E As Exception
Console.WriteLine(“ERROR:“ & E.Message)
End Try
End Sub
End Module
Sending Internet E-mail
The Syetem.Web.Mail namespace offers classes that support Internet E-mail messages
using the Simple Mail Transfer Protocol(SMTP).
E-mail message can be sent as plain text or HTML format and can include file attachments.
The server must grant appropriate permission to the sender of the e-mail for the message to
be properly routed to its destination.
The server can include any host from LAN or on the Internet.
The System.Web.Mail namespace has three classes that provide all the SMTP functionality
to send messages:
(i) SMTPMail
(ii)MailMessage (no methods)
(iii) MailAttachment (no methods)
Property of SmtpServer
SmtpServer – the host name of smtp server. If it is omitted, IIS 5.0 SMTP service
naming on the local machine is used.
BCC – a semicolon delimited list of e-mail address that receive a blind carbon copy of
the e-mail message.
UrlcontentBase – The base URL to use for all relative links included in the
body of the e-mail message.
UrlContentLocation – Gets or sets the Content – Location HTTP header for the e-mail message.
Properties of MailAttachment
Encoding – The encoding used to encode the e-mail attachment : either MailEncoding.Bse64 or
MailEncoding.UUEncode.
• HTTP is the substrate for all communications between components and clients of those components.
• HTTP network traffic flows across firewalls since it uses the same network port as other web traffic.
• The payload of these communications is contained inside a special XML data format called the Simple Object Access
Protocol(SOAP)
• Web services form a communication method that allows components to communicate with clients and each other.
• Components using different architecture can talk with each other using web services.
Separation of Data from presentation
• Websites are used by many people for day to day task.
• Though the information are provided to the user by mouse clicks, the limitation is that the data is tied to an HTML page, which in turn
to the computer and a web browser.
• As the demand grows devices such as PDA, cell phones , notebook computers , home refrigerator have wireless capabilities and can
access internet sites.
• As the size of the screen is small, only few lines of text can be displayed and they cannot display graphics. This makes the
traditional browsing impossible.
• Traditional applications that attempt to use services provided by websites also has limitations.
• If the websites are exposed that look functionality as the web service, it would return only the relevant data.
Overview of Web Services
Def:
web services are compiled classes that are contained within .asmx file.
• The .asmx file contains code, such as Visual Basic, that is compiled into a class.
• This file contains a special page directive and identifies the file to the compiler as a web service.
• Another page directive specifies the name of the web service class.
Eg:
End Class
Explanation
The class starts by inheriting from System.Web.Services.WebService - is the class which supports web services.
It exposes ASP.NET intrinsic object such as those used for session and state management
<WebMethod> - Specifies that the member function will be publicly exposed through the web service.
This attribute class allows to define an optional description for the web method and specify additional parameters that can alter the
behaviour of the web method.
Web Service Description Language
Web Services have the ability to describe themselves, ie, they can tell clients how to call their
methods , what the parameters and types are and what data types to expect as return values from
those methods.
This is done by describing the web service through an XML data format called web service
description language(WSDL)
WSDL describes the methods of a web service , the data type definitions, the parameter definitions
of each method the supported wire formats for calling the web service, the URL where the web
service is located and other supporting information.
Web Service Discovery:
Discovery files, provide information about the location of web services and their
corresponding WSDL.
The web service framework provides two method for discovering web services
Static discovery
It allows to group together the location of web services into a logical unit.
Web services can use ASP.NET state management using the Session and Application objects
Web service class contains many of the same objects that ASP.NET uses.
httpSessionState class is used to maintain a count of how many times the web service is used during a session.
Using Transactions in web services
Web services can participate in a COM+ component services transaction by
specifying a TransactionOption in the WebMethod() attributee
The two preliminary requirements for using a transaction in a web service are
Imports System
Imports System.Web.Services
Imports System.EnterpriseServices
2. The transaction option must be set for web methods that will execute as part of
a transaction.
Flat files
Before relational database management systems(DBMS) were widely used, data were stored in flat files.
Flat files refers to any kind of data existing in files and they are not a part of DBMS.
Fixed - length files store their data in records separated by a terminating character.
Each element of data in the record occupies to fixed number of characters, padded with white-space
characters as needed to fill the fixed length.
Flat files are not very flexible as a data-storage solution for several resons
• Flat files limit the kind of data that can be stored in them since, they can contain only textual data
• Flat files don’t work well in multiuser situation because the operating systems typically limit the amount
of streams that can be opened on a file.
• Problems with dat integrity arise out of concurrent updates with flat files.
Some companies wants to keep pace with the web revolution. So they need a way to expose the data to the
web in a way that is minimally intrusive.
This process is known as screen scraping, it retrieves data from a virtual terminal session with the
mainframe.
This virtual terminal session is triggered by server side code invoked from a web page.
The program controlling the terminal session, in turn passes the “scraped” data back to the browser.
Proprietary Database API’s
Database systems are shipped with an API that was specific to that particular database system.
SQL is the primary language used to describe queries to a database but the underlying programming
models used to access data from application code are fragmented.
Some language compilers support embedded SQL, which allows programmers to place SQL
Statements inline with the host language.
STANDARD API’S
Standard API for data access was done with the help of Open Database Connectivity(ODBC).
For a database to be ODBC complaint, the database vendor should provide ODBC Driver software that
translated the ODBC API calls into the native database query language.
Drawbacks of ODBC
With the introduction of COM and its language independent architecture, a new technology called OLE DB
came into existence.
OLE-DB communicates with a data provider , which is the software that provides access to the physical
data.
The data provider enables programmers to write OLE – DB Code which communicates with ODBC data
sources using the COM methodology.
ADO
It provides an easy programming interface to data sources.
It unifies the functionality of previous data access methods and reduces the number of objects in the
programming interface.
ADO passed data to its component using TCP/IP protocol. But ports were blocked by
firewall. This hampered interoperability, which is the key platform behind .NET platform.
HTTP can easily ferried across firewalls along with the normal web traffic.
XML is a open standard , so even non-Microsoft platform can be used to retrieve data.
ADO.NET Programming Objects and Architecture
DataSet object is used to manipulate data that originated from a variety of formats. The .NET Managed Data
provider handles connecting to a database, execution of queries and retrieval of results. These result populate
the DataSet object.
.NET Managed Data provider is made up of four base classes. They are:
(i) The Connection class : it is used to provide a connection to a database and controlling manual
transaction.
(ii) The Command class : this object executes queries and stored procedure.
(iii) The DataReader class: this object provides fast, forward only, read only access to data. This is useful to
process a large number of records from a database but don’t need to update the data or have random
access to it.
(iv) The DataAdapter class: This object’s job is to populate DataSet objects with data retrieved from the
database.
(i) The SQL Server .NET Managed Data Provider: This provider is used for connecting to Microsoft SQL
Server 7.0/2000 and Microsoft MSDE (Microsoft Data Engine)database servers.
(ii) The OLE-DB .NET Managed Data Provider: This provider is designed to connect to Microsoft SQL Server
6.5 or earlier Oracle and Microsoft Access.
(iii) The ODBC .NET Managed Data Provider : This driver is used when connecting to database systems that
provide only in ODBC driver as an interface.
Displaying Database Data
IDataReader Interface
(System.Data.IDataReader)
It is a part of System.Data namespace. Some of the other interface included in this namespace is
IDataAdapter,IDbConnection, and IDbCommand.
ADO.NET allows the .NET Managed data provider code to implement the various interfaces.
For Eg:
The SQL Server .NET Managed Data Provider provides an implementation of the IDataReader
interface with a class in the System.Data.SqlClient namespace called SQLDataReader database
Properties and methods of IDataReader interface
Properties
Methods
ConnectionString – specifies the connection string to be used for opening an SQL Server database
ConnectionTimeout - sets the maximam time( in seconds) to wait for successful connection
Database – specifies the name of the database to which to connect
DataSource – specifies the SQLinstance to which to connect.
PacketSize – sets the size of network packets to use when communicating with SQL Server
ServerVersion –specifies the Version of the server
State – gets the current state of the connection : BROKEN, CLOSED,CONNECTING,EXECUTING,FETCHING
OR OPEN.
WorkstationId – specified the identifier of the database client.
Methods of SqlConnection class
(ii) Constructing commands using SqlParameter objects to supply parameter to Transt-SQL statements.
SqlParameter objects:
SqlParameter Class
Namespace:
System.Data.SqlClient
Assembly:
System.Data.SqlClient.dll
Represents a parameter to a SqlCommand and optionally its mapping to DataSet columns. This class cannot be inherited.
Whenever a name is specified for the ParameterName property of the SqlParameter object it is in
the following form :
@parameter_name
After creating the SqlParameter object we need to assign values to the class properties.
ParameterName property assigns the corresponding parameter name specified in the CommandText
string.
DbType is set with the data type of the parameter
The template column can contain child controls, eg, Label, textbox etc.,
DataKeyField states which field is to be used as key for updating edited rows.
EditCommand event
Syntax
Private Sub MyDataGrid_EditCommand( ByVal Source As Object, ByVal e As
DataGridCommandEventArgs) Handles MyDataGrid.EditCommand
The Handles keyword is used to designate which event is written for event handler.
Event handling function consists of the Object parameter and the DataGridCommandEventArgs parameter.
Which row is going to be edited can be determined by the specifics in the DataGridCommandEventArgs
parameter.
The DataGrid can be set to edit mode by assigning the EditItemIndex property of the DataGrid Control to
the index of the row that was selected.
CancelCommand
Canceling an edit is done by setting the EditItemIndex to -1
UpdateCommand
the parameters which is to be updated is attached to the SQL UPDATE command and then the
ExecuteNonQuery() method is used to execute the update.
New concepts are introduced in ADO.NET for data access. The use of system resource is decreased by this
new concept.
4. The client then proceeds to query and update this downloaded data.
5. When the changes have been completed, the client uploads the changed data to the server.
6. The server then reconciles any changes to the database automatically.
ADO.NET can represent table, columns,keys and relations in memory.
The DataSet Class Summary
ADO.NET provides manual transactions using SqlTransaction class and the SqlConnection class.
1. Rollback()
2. Rollback(ByVal transactionName As String)
Save - creates a svepoint in the transaction to which a roll back can return
Many of the classes in the .NET framework can be extended through inheritance.
The DataSet is one such class. By creating a new application- specific class that inherit from the DataSet
class, can access table, column, and row information in a strongly typed fashion( the object can be
referenced by name rather than using a collection based index.
Productivity enhancement can achieved using VS.NET IDE. The editor offers help through Intellisense with
method property names for the typed DataSet object.
Securing .NET Applications
Protecting the site comes down to two tasks for a site administrator
1. Provide a way to restrict site access so that only authenticated users can visit the site.
2. Make sure that the data transmitted between the web user and the web server cannot be intercepted by a third
party.
Authentication:
It is the process by which the system determines a user’s identity. The most common type of authentication
is the combination of user name and password. Other means of authentication includes biometric devices, retinal
scans, voice prints etc. It is the first step in any diligent security process.
Authorization:
It is the process of determining which resources an authenticated user can access and how those resources can
be used. Users in a multiuser system have varying levels of privileged use assigned to them. The most common type of
authorization deals with how files can be accessed.Eg: some person may be able to read a particular file but not write
to it.
Impersonation :
It is the process of taking a user’s identity and having it assume the identity of another user or entity. This simplifies
the work required in the authentication of public servers. It removes the need to assign user accounts to anonymous users
since you have a shared account for public use.
Windows Security
The windows operating system is designed in such a way that any action you perform on the computer involves a
security check.
It follows that whenever the user is working inside the windows environment and the user should have an
identity.
This is the user account. These user names are stored in user accounts database.
1. Server – whenever a user attempt to gain access to the server. The security check is performed against the database
residing on the server. The accounts in this database is called as local user accounts.
2. PDC (Primary Domain Controller) - it is used to authenticate users on a local area network. The local area network may
have many servers. These servers are grouped to form a domain. The PDC provides a centralized area for authentication
to occur for the machines in the domain. If the server wished to gain access to a particular server’s resource within
The domain, the user need to log into PDC.
Any object on windows system contains priveleges associated with it in an access control list(ACL)
The ACL contains a list of security identifiers(SID’s) that correspond to a user account.
whenever a request is made , the currently logged in user is matched against the user SID in the ACL for the
resource. The system then decides whether to grant access or not.
Windows NT stores files in file allocation table (FAT) method. Since windows NT has multiuser operating system , it requires
security protections of a multiuser system. Different security attributes are assigned to files which includes the users who
are allowed to access which files and in what ways(read, write and execute)
IIS implements its own authentication mechanisms and controls how to authenticate users.
Anonymous Access
IIS provides the ability for an anonymous user to access files on the web server without having to supply his or her
credentials.
By default, IIS enables this type of access. When it is not enabled, the user’s web browser would pop up a dialog box
asking for a user name and password.
With anonymous access enabled, IIS performs retrieval of files by using special windows user account , called as web
guest. It has privileges to access files. This account is created upon installation of IIS. It is named IUSR machine name,
where machine name is the name of the windows server.
The password is also configured automatically,making the entire authentication process transparent to the user.
The following are the reasons why the anonymous users do not gain access
1. The IUSR_machine name account is assigned guests permissions only. Which indicates that the anonymous access
account is a member of default windows guest account.
IIS allows web users to view files in the virtual directory spaces only. A web user cannot specify a URL that points to a
directory outside of this virtual directory space to gain access to a file.
Using cracking techniques of If the unauthorized user does know the path of a protected file, the permission set on the
file will not include accounts in the guest group. Thus, the system will deny access.
BASIC Authentication:
BASIC Authentication uses the HTTP response headers to signal that a user name and password are required to access
the web page.
How it works:
1. A request is made for a document, so an HTTP GET command is issued by the browser that looks like:
GET /passed.aspx HTTP/1.0
2. IIS sees that the file, passwd.aspx is protected from guest access. So it return a 401 status code in the HTTP response.
The 401 status code indicated that password authorization is required to access the file.
3. The 401 HTTP triggers a password dialog box to appear in the user’s browser. Now the user needs to send the user
name and password information. When this information is entered the username and the password are concatenated
into a single string separated by a colon (:).
5. The encoded string is placed inside the HTTP header with the following request.
Base64encoded string contains the Base64-encoded version of the user name and password string.
If the user name and password given match the user credentials, the user is grated access. A normal 200 status code is
returned along with the contents of the request.
Though the password is encoded using Base64 encoding algorithm, it can be easily decoded using any cracking tool. The
authentication used can be changed by the web server by using IIS configuration tools.
Integrated Windows Authentication:
Using this method the username and the password are not transmitted over the network. The user’s web
browser does not prompt for username and password , instead the browser uses the user name and password
used by the user when logging into the local workstation.
1. Internet Explorer is the only browser that supports Integrated Windows Authentication.
2. Many internet users have internet access only through firewall / prox. This may create problem with the
network connection used for the authentication.
It is very useful in an intranet setting where persistent connection are more reliable.
Digital Authentication
It involves authentication using hashes. A hash is a fixed – length value that is derived from a chunk of data
using a secret data string.
Implementing Data Encryption
The .NET Framework SDK includes classes for performing data encryption.
These classes are part of System.Security.Cryptography namespace.
RC2CryptoServiceProvider object provides a wrapper for the windows cryptographic server provider.
BlockSize – gets or sets the block size (in bits) of the cryptographic operation
EffectiveKeySize – gets or sets the effective size O(in bits) of the secret key used by the RC2 algorithm,
FeedbackSize – gets or sets the feedback size (in bits) of the cryptographic operation
Key – gets or sets the secret key for the symmetric algorithm
KeySize – gets or sets the size of the secret keyused by the RC2 algorithm
Mode – gets or sets the mode for operation of the symmetric algorithm
KeySize property is inherited from the RC2 and the other properties are inherited from symmetric algorithm.
Eg:
RC2CryptoServiceProvider class inherits much of the functionality from the base class RC2 which inturn inherits from
SymmetricAlgorithm class.
ValidKeySize – determines whether the specified key size is valid for the current algorithm.
The encryption process begins by reading the contents of the input file into a byte array.
The write() method of the CryptoStream Object is used to dump the contents of the input Byte array to the output file
(encrypted) file.
Properties of CryptoStream class
FlushFinalBlock – updates the underlying data source or repository with the current state of the buffer, then
clears the buffer.
There are three different authentication providers Forms-Based, Windows, and Passport.
Whenever the user requests the privileged resource for which the current use credentials do not suffice, a client-side
redirection to an HTML form can be made.
The user credentials are collected for the resource at the login page.
For each request to a protected web site, ASP.NET checks to see if there is an authentication ticket attached to the request.
An expiration time is set on the authentication ticket which is useful if a user logs in and then leaves his or her desk.
The time out period will expire and the user will need to repeat the login process.
The data contained in the authentication ticket is also usually encrypted , which prevents another indomitable user from
accessing the contents.
Steps
1. Configure a special file called the web.config file.
2. The web.config file resides in the root of the ASP.NET application.
3. There is only one web.config file per application, and its use is optional.
4. It is a XML file used to store security settings for ASP.NET application.
5. There are two sessions they are <authentication> and <authorization>
6. The mode attribute designates which authentication provider to use.
7. In form-base authentication it is the forms.
8. Below the authentication node is the form node.
9. The name attribute is the name assigned to the authenticated ticket.
10. The path attribute specifies the virtual path for which the authentication ticket is valid.
11. A particular directory within the site or the entire site can be specified as members only by using “/”. This protects the
entire site.
12. The loginurl attribute specifies where the login page is located.
13. It requires a minimum of two text fields one for user name and one for password.
14. The protection attribute specifies how much security is applied for authentication ticket. Eg: All :indicated that the
authentication ticket should be encrypted and that data validation should be performed on the ticket based on
specific optional settings.
15. Time out attribute specifies how long the authentication ticket is valid. It is expressed in minutes.
16. The <credentials> node contains the user accounts information, which are pair of username and password.
Passport is a centralized authentication service that allows users to visit multiple web sites and be authenticated on each of
them by logging in only once.
Using passport services requires additional software downloads and they require fee for it.