With C#
With C#
NET Notes
ASP.NET AND C#
UNIT – I
Overview of ASP.NET framework, Understanding ASP.NET Controls,
Applications, Web servers, installation of IIS. Web forms, web form
controls -server controls, client controls, web forms & HTML, Adding
controls to a web form ,Buttons, Text Box , Labels, Checkbox, Radio
Buttons, List Box, etc.
Running a web Application, creating a multiform web project.
UNIT-II
Form Validation: Client side validation, server Side validation, Validation
Controls : Required Field Comparison Range. Calendar control, Ad rotator
Control, Internet Explorer Control.
State management- View state, Session state, Application state,
UNIT-III
Architecture of ADO.NET, Connected and Disconnected Database, Create
Connection using ADO.NET Object Model, Connection Class, Command
Class, DataAdapter Class, Dataset Class. Display data on data bound
Controls and Data Grid.
Database Accessing on web applications: Data Binding concept with web,
creating data grid, Binding standard web server controls. Display data on
web form using Data bound controls.
UNIT-IV
Writing datasets to XML, Reading datasets with XML. Web services:
Introduction, Remote method call using XML, SOAP, web service
description language, building & consuming a web service, Web
Application deployment.
UNIT-V
Overview of C#, C# and .NET, similarities & differences from JAVA,
Structure of C# program. Language features: Type system, boxing and
unboxing, flow controls, classes, interfaces, Serialization, Delegates,
Reflection.
P a g e |1
ASP.NET Notes
UNIT – I
P a g e |2
ASP.NET Notes
Overview of ASP.NET framework:
.NET is short name of Microsoft Visual Studio 2003, 2005, 2008, 2010,
2013, 2015. It is not a language but service provider for software
development. Web developer uses ASP.NET for designing web sites,
C#.NET for programming and ADO.NET for database connectivity. All
these services are supported by .NET Framework. Without .NET
Framework, application cannot be designed, coded and connected to data
base. .NET Framework is consisting using following three parts.
P a g e |3
ASP.NET Notes
Web Servers and Web Browser:
This client-server architecture to access web items from one place to many
places can be shown as.
Web servers:
A computer on which web pages and web services are stored called web
server. In Microsoft Windows system, IIS (Internet Information Services)
software is used to create web server to host website into "Initpub" folder.
Web server accept an URL request for from client side then search into
Initpub folder, process it using .NET Framework and finally response to
client in HTML+CSS+JScript code.
Web Browser:
At client side, user made a request in URL form then accept its response in
HTML+CSS+JScript form with the help of an application software called
web browser. for example Internet Explorer, Crome, Mozila etc.
Installation of IIS:
A computer called web server on which IIS software is installed. IIS is
supported on Microsoft operating system like WindowsXP, Windows3,
Windows7 etc.
To install IIS we perform following action.
1. Open control panel.
2. click on Programs.
3. select "Turn windows features on or off"
4. To turn on Internet Information Services, select checkbox.
5. Press Ok button.
P a g e |4
ASP.NET Notes
After some time installation process of IIS will be completed. We get a
folder Inetpub in C drive. When we type localhost on address bar of
browser and press enter key then we get a default web page. It means IIS
have installed successfully.
Web forms:
A web page that contains <form> tag called web forms.
For example:
<html>
<head>
<title>Home page</title>
</head>
<body>
<form method="GET/POST"
action="http://lrsir.net/scriptpage.aspx.cs">
Place all web control here
</form>
</body>
</html>
Above html code is processed at client side. When user click on button
control then form data are send to scriptpage.aspx.cs file at server side using
GET or POST method. GET method send form data through querystring
(http://lrsir.net/scriptpage.aspx.cs?uid=lrsir&pwd=12345)and
POST method send form data in the http header in hidden form. Every web
page is defined at least in above format.
P a g e |5
ASP.NET Notes
<type="text" name="uid" id="text1"></text>
It shows textbox on webpage to input data at client side by browser.
Web form is a web page in which all server side / client side controls are
written inside <form></form> tag called web form.
P a g e |6
ASP.NET Notes
P a g e |7
ASP.NET Notes
7. Design Section: This middle section shows the layout of controls on
web form before running website.
Using toolbox we can add required ASP.NET and HTML controls on web
page. Controls can be added using following steps.
1. Open web page from solution explore.
2. Choose source / design tab from bottom of web page.
3. Set position of control at desired place.
4. Select control from toolbox.
5. Hold, Drag and Drop at desired position on web page.
We can also type any control's code in source section of web page.
P a g e |8
ASP.NET Notes
18. CssClass: To apply css class on control.
19.SkinId: To apply preset formatting.
20. EnableTheming: To apply format of them on control or not.
(True/False)
21. EnableViewState: If it is true then data on control persist after
redirecting to same page on browser.
22. AutoPostBack: By default it is false. When it is true then
automatically posts the form whenever a change is made to the
content of control. Most applicable for DropDownList when we select
any item.
It is used to show non editable message on web page and it can be modify
using code.
Syntax:
<asp:Label ID="Label1" runat="server"/>
Important Properties:
- Text: Gets or sets the text displayed by the Label control.
Methods:
- None
Events:
- None
Example: Display LRsir.net on Label control
Webpage: Showtime.aspx
<%@ Page Language="C#" %>
<script runat="server">
void Page_Load()
P a g e |9
ASP.NET Notes
{
Label1.Text = "LRsir.net";
}
</script>
<html >
<head><title>Show Label</title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" />
</div>
</form>
</body>
</html>
TextBox control
In this control, user can type data to make input on web form.
Syntax:
<asp:TextBox ID="TextBox1" runat="server"/>
Important Properties:
- Text: Gets or sets the text displayed by the TextBox control.
- TextMode: It can accepts following three values:
i. SingleLine—Displays a single-line input field.
ii. MultiLine—Displays a multi-line input field.
iii. Password—Displays a single-line input field in which the text
is hidden.
- MaxLength: The maximum number of characters that can be entered.
- ReadOnly: True mean text cannot be changed in textbox.
- Rows: If TextMode property is MultiLine then it sets the number of
lines.
- Columns: It sets number of columns to display.
- Wrap: True / False for wrapping text or not when TextMode is
MultiLine.
Methods:
- Focus: To set focus on that control.
Events:
- TextChanged: Raised on server when user made changes in
textbox.(AutoPostBack property must be true for this event)
P a g e | 10
ASP.NET Notes
Example1: Display TextBox for single line, multiline and password using
ASP.NET code of TextBox.
CheckBox control
P a g e | 11
ASP.NET Notes
Using this control, we display message along with check box. One or more
CheckBoxs can be selected.
Syntax:
<asp:CheckBox ID="CheckBox1" runat="server"/>
Important Properties:
- Text: Gets or sets the text displayed by the CheckBox control.
- Checked: True/False. True for select and False for unselect.
Methods:
- Focus: To set focus on that control.
Events:
- CheckedChanged: Raised on server when user made checked or
unchecked in check box. (AutoPostBack property must be true for
this event)
Example1: Display two CheckBoxs for Hobbies using ASP.NET code.
P a g e | 12
ASP.NET Notes
}
</script>
<html>
<head> <title>Show CheckBox Page</title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBox ID="CheckBox1" runat="server"
Text="Footboll" AutoPostBack="true"
OnCheckedChanged="CheckBox1_CheckedChanged"/>
</div>
</form>
</body>
</html>
Remark: By default, a CheckBox control renders its contents in an HTML
<Input Type="checkbox"> tag.
RadioButton control
This control always use in group. Only one radio button can be checked in
one group of radio buttons.
Syntax:
<asp:RadioButton ID=" RadioButton1" runat="server"/>
Important Properties:
- Text: Gets or sets the text displayed by the RadioButton control.
- Checked: True/False. True for select and False for unselect.
- GroupName: Group that any radio button belongs to.
Methods:
- Focus: To set focus on that control.
Events:
- CheckedChanged: Raised on server when user made checked or
unchecked in RadioButton. (AutoPostBack property must be true for
this event)
Example1: Display two groups of RadioButtons using ASP.NET code.
P a g e | 13
ASP.NET Notes
<asp:RadioButton ID="RadioButton1" runat="server"
GroupName="status" Text="Married" />
<asp:RadioButton ID="RadioButton2" runat="server"
GroupName="status" Text="Unmarried" />
<br />
<asp:RadioButton ID="RadioButton3" runat="server"
GroupName="sex" Text="Male" />
<asp:RadioButton ID="RadioButton4" runat="server"
GroupName="sex" Text="Female" />
P a g e | 14
ASP.NET Notes
</div>
</form>
</body>
</html>
Remark: By default, a RadioButton control renders its contents in an
HTML <Input Type="radio"> tag.
HyperLink control
This control creates a link to a web page to navigate another web page. This
control does not submit form to a server.
Syntax:
<asp:HyperLink ID=" HyperLink1" runat="server"/>
Important Properties:
- Text: Gets or sets the text displayed by control.
- NavigateUrl: To specify URL.
- ImageUrl: To specify Image for link.
- Target: The target frame for NavigetUrl.(_blank, _parent)
Methods:
- none
Events:
- none
P a g e | 15
ASP.NET Notes
Image control
This control is used to display image.This control does not submit form to a
server.
Syntax:
<asp:Image ID="Image1" runat="server"/>
Important Properties:
- AlternateText: Display text when image is unavailable.
- ImageUrl: To specify Image URL that shown.
- ImageAlign: To specify alignment of Image.
Methods:
- none
Events:
- none
Example1: Show Image to a web page using ASP.NET code.
<asp:Image ID="Image1" runat="server"
AlternateText="LRsir.net" ImageUrl="~/visiting2.jpg" />
P a g e | 16
ASP.NET Notes
When we click Button Control then control is push down and web form is
submitted to the server so that we can process C# code.
Syntax:
<asp:Button ID="Button1" runat="server"/>
Important Properties:
- Text: The text to be shown on button.
- CommandArgument: Argument that passed to Command event of
button.
- CommandName: Specify a command name that is passed to
command event.
- PostBackUrl: Url for after click button.
- UseSubmitBehavior: (true/false) Indicate whether the button render
as a submit button.
- OnClientClick: The client side script that is executed on client-side
OnClick.
Methods:
- Focus: To set focus on that control.
Events:
- Click: Raised when button control is clicked.
- Command: Raised when button control is clicked. The command
name and command argument passed to this event.
Example: Display current time to a Label control when button control is
clicked, also pass argument to command name.
P a g e | 17
ASP.NET Notes
{
Response.Write("visits: " + e.CommandArgument);
}
}
</script>
<html>
<head>
<title>Show Button control Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server"
Text="Click for date & time"
CommandArgument="www.LRsir.net"
CommandName="website"
OnClick="Button1_Click"
OnCommand="Button1_Command"/>
<asp:Label ID="Label1" runat="server"/>
</div>
</form>
</body>
</html>
Remark: By default, a Button control renders its contents in an HTML
<Input Type="submit"> tag.
LinkButton control
Methods:
- Focus: To set focus on that control.
P a g e | 18
ASP.NET Notes
Events:
- Click: Raised when button control is clicked.
- Command: Raised when button control is clicked. The command
name and command argument passed to this event.
Example: Display current time when LinkButton control is clicked.
ImageButton control
P a g e | 19
ASP.NET Notes
Important Properties:
- AlternateText: The text displayed when image cannot be shown.
- ImageUrl: The URL of image to be shown.
- ImageAlign: for the alignment of image.
- CommandArgument: Argument that passed to Command event of
button.
- CommandName: Specify a command name that is passed to
command event.
- PostBackUrl: URL for after click button.
- OnClientClick: The client side script that is executed on client-side
OnClick.
Methods:
- Focus: To set focus on that control.
Events:
- Click: Raised when button control is clicked.
- Command: Raised when button control is clicked. The command
name and command argument passed to this event.
Example: Display current time when ImageButton control is clicked.
P a g e | 20
ASP.NET Notes
ImageUrl="ImgBtn.jpg"
OnClick="ImageButton1_Click" /></div>
</form>
</body>
</html>
Remark: By default, a ImageButton control renders its contents in an
HTML <Img> tag.
List Controls:
(DropDownList, ListBox, RadioButtonList, CheckBoxList, BulletedList)
These controls are used to display a list of items in different views. All these
controls share a common set of properties and methods.
Display a list of items:
A list of items in such controls can be display using ListItem class in
following manners.
<asp:ListControlName ID="ListControlName1 runat="server">
<asp:ListItem Text="Item1" Value="value1" Selected="False"/>
<asp:ListItem Text="Item2" Value="value2" Selected="True"/>
</asp: ListControlName>
- Text: To display item on list control.
- Value: To specify hidden value associated with list item.
- Selected: True for select and False for unselect.
- Enabled: True for enable and false for disable.
ListControlName: DropDownList, ListBox, RadioButtonList,
CheckBoxList and BulletedList.
Binding to a Data source:( using C#)
We can show a list of items from database programmatically using
following two propeties of List controls.
- DataTextField: To set Text property of each item.
- DataValueField: To set Value property of each item.
Determining the Selected List Item: (using C#)
All List controls support three properties that can use to determine the
selected list item:
- SelectedIndex: Gets or sets the index of the selected list item.
- SelectedItem: Gets the first selected list item and set to ListItem.
- SelectedValue: Gets or sets the value of the first selected list item.
- SelectedItem.Text: Gets the first selected list item's text item.
ListItem item=ListControlName1.SelectedItem;
Adding item into ListItem of List Control:(C# code)
ListItem item=new ListItem("NewText","NewValue");
ListControlName1.Items.Add(item);
Removing item from ListItem of List Control:(C# code)
P a g e | 21
ASP.NET Notes
ListControlName1.Items.Remove(ListItem item);
To clear selection of item: (C# code)
ListControlName1.ClearSelection();
AutoPostBack property: True means page is automatically post back to
the server when we select item from list control. (except BulettedList)
SelectedIndexChanged event: Raised when we made selection and
AutoPostBack property is true.
DropDownList control:
This control can hold a list of items but display any one of them. When we
click on arrow button of this control then we get a list of items to select any
one item for further processing using C# code.
Syntax:
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
Display a list of items:
<asp: DropDownList ID=" DropDownList1 runat="server">
<asp:ListItem Text="Item1" Value="value1"/>
<asp:ListItem Text="Item2" Value="value2"/>
</asp: DropDownList>
ListBox control:
This control can display more items in list form and we can select multiple
items.
Syntax:
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
Display a list of items:
P a g e | 22
ASP.NET Notes
P a g e | 23
ASP.NET Notes
void Button2_Click(object sender, EventArgs e)
{
ListBox1.Items.Add(DropDownList1.SelectedItem);
ListBox1.ClearSelection();
DropDownList1.Items.Remove(DropDownList1.SelectedItem);
}
<html>
<head><title>ShowDropDownList Page</title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click" Text=">>" />
<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged>
</asp:DropDownList>
<asp:Button ID="Button2" runat="server" Text=">>"
OnClick="Button2_Click" />
<asp:Button ID="Button3" runat="server"
OnClick="Button3_Click" Text="<<" />
<asp:ListBox ID="ListBox1" runat="server">
</asp:ListBox></div>
</form>
</body>
</html>
Practical Task: Get multi select items from CheckBoxList / ListBox
control.
P a g e | 24
ASP.NET Notes
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected)
{
str += "<li>"+item.Text;
}
}
Response.Write(str);
}
</script>
<html>
<head><title>Get multiselect Page</title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Text="Item1" Value="Value1" />
<asp:ListItem Text="Item2" Value="Value2" />
<asp:ListItem Text="Item3" Value="Value3" />
<asp:ListItem Text="Item4" Value="Value4" />
</asp:CheckBoxList>
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click" Text="Get" /></div>
</form>
</body>
</html>
When it runs on web server then all the server side contents are first
executed at server side by .NET framework then reassemble web forms
content and response to request user's browser using IIS.
Before running a web application first do following things for first starting
web page among others.
P a g e | 25
ASP.NET Notes
Creating a multiform web project:
A web site is a collection of interlinking web pages for a specific purpose. A
web project may have multiple web forms. In ASP.NET we can add many
web forms in current web project using following procedure.
All above steps are follows when we create multiple pages. All these pages
are inlinking using navigate controls like HyperLinking.
P a g e | 26
ASP.NET Notes
UNIT-II
Form Validation:
Client side validation
Server Side validation
Validation Controls:
Required Field
Comparison
Range
Regular Expression
Summary
Custom
Calendar control
Ad rotator Control
Internet Explorer Control
State management:
View state
Session state
Application state,
P a g e | 27
ASP.NET Notes
Form Validation:
A web form has many input controls like TextBoxs. These controls should
have right type of data before submitting form at server side for data
processing. Thus checking the input controls called form validation.
Form validation includes-
1. Check control has required value.
2. Check value of control falls between minimum and maximum value.
3. Compare value of control against another value.
4. Check value of control is match with given format.
For example: If data is not input into TextBox then an error message should
be display. It is done using RequiredFieldValidator control.
Validation Controls:
ASP.NET provides following set of validation controls that may validate
value of form control at client side (default) or server side.
1. RequiredFieldValidator
2. RangeValidator
3. CompareValidator
4. RegularExpressionValidator
5. CustomeValidator
6. ValidationSummary
P a g e | 28
ASP.NET Notes
These validation controls can be apply on any control that has decorated
with ValidationProperty attribute.
RequiredFieldValidator control:
This validation control checks to required value is input or not into specified
input control before submitting the form. This control needs to link any one
input control like TextBox.
Syntax:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" />
Important Properties:
- ControlToValidate: ID of control to be validate.
- Text: text to display for the validator when the validated control is
invalid.
- ErrorMessage: Message to display in a ValidationSummary when
the validated control is invalid.
- ToolTip: The tooltip displayed when the mouse is over the control.
- EnableClientScript: If it is true then validation is performed at client
side by browser otherwise performed at server side.
P a g e | 29
ASP.NET Notes
ErrorMessage="Your Name is empty"
ToolTip="Input Your Name"
Text="(Required)" />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
<asp:Button ID="Button2" runat="server" Text="Cancel"
CausesValidation="False" />
</div>
</form>
</body>
</html>
RangeValidator control:
This validation control checks input value falls between a certain minimum
and maximum value. This control needs to link any one input control like
TextBox.
Syntax:
<asp:RangeValidator ID="RangeValidator1" runat="server" />
Important Properties:
- ControlToValidate: ID of control to be validate.
- MinimumValue: The minimum value for the control being validated.
- MaximumValue: The maximum value for the control being
validated.
- Type: Data type of values for comparison. (String / Integer / Double /
Date / Currency)
- Text: text to display for the validator when the validated control is
invalid.
- ErrorMessage: Message to display in a ValidationSummary when
the validated control is invalid.
- ToolTip: The tooltip displayed when the mouse is over the control.
- EnableClientScript: If it is true then validation is performed at client
side by browser otherwise performed at server side.
P a g e | 30
ASP.NET Notes
<%@ Page Language="C#" %>
<html>
<head>
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Your Age
<asp:TextBox ID="TextBox1" runat="server" />
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="TextBox1"
Type="Integer"
MinimumValue="18"
MaximumValue="60"
Text="(Out of 18-60)"
ToolTip="Input value between 18-60"
ErrorMessage="Out of range(18-60)" />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
<asp:Button ID="Button2" runat="server" Text="Cancel"
CausesValidation="False" />
</div>
</form>
</body>
</html>
CompareValidator control:
P a g e | 31
ASP.NET Notes
- Text: text to display for the validator when the validated control is
invalid.
- ErrorMessage: Message to display in a ValidationSummary when
the validated control is invalid.
- ToolTip: The tooltip displayed when the mouse is over the control.
- EnableClientScript: If it is true then validation is performed at client
side by browser otherwise performed at server side.
P a g e | 32
ASP.NET Notes
<%@ Page Language="C#" %>
<html>
<head><title>Untitled Page</title></head>
<body>
<form id="form1" runat="server">
<div>
Your age
<asp:TextBox ID="TextBox1" runat="server"/>
<asp:CompareValidator ID="CompareValidator1"
runat="server"
ControlToValidate="TextBox1"
Operator="GreaterThan"
Type="Integer"
ValueToCompare="18"
Text="(Input more than18)" />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
<asp:Button ID="Button runat="server" Text="Cancel"
CausesValidation="False" />
</div>
</form>
</body>
</html>
Example3: Compare input password to confirm password.
P a g e | 33
ASP.NET Notes
Operator="Equal"
Text="(Password Not matched)" />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
<asp:Button ID="Button runat="server" Text="Cancel"
CausesValidation="False" />
</div>
</form>
</body>
</html>
RegularExpressionValidator control:
P a g e | 34
ASP.NET Notes
<%@ Page Language="C#" %>
<html>
<head><title>Untitled Page</title></head>
<body>
<form id="form1" runat="server">
<div>
Your Email ID
<asp:TextBox ID="TextBox1" runat="server"/>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1"
ValidationExpression=
"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
Text="(Invalid EmailID format" />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
<asp:Button ID="Button runat="server" Text="Cancel"
CausesValidation="False" />
</div>
</form>
</body>
</html>
ValidationSummary control:
This control display a list of all validation errors which are given in
ErrorMessage of each validation control.
Syntax:
<asp:ValidationSummary ID=" ValidationSummary1"
runat="server" />
Important Properties:
- DisplayMode: Format for error summary display. (BulletList /
SingleParaGraph / List)
- HeaderText: To display header text on the top of summary control.
- ShowMessageBox: True means display a popup alert box.
- ShowSummary: False then summary hides.
P a g e | 35
ASP.NET Notes
P a g e | 36
ASP.NET Notes
ErrorMessage="Invalid Email ID Format"
ValidationExpression=
"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
Text="*" />
<br />
<asp:Button ID="Button1" runat="server"
Text="Submit" />
<asp:Button ID="Button2" runat="server"
Text="Cancel" CausesValidation="False" />
</div>
</form>
</body>
</html>
CustomValidator control:
If none of the other validation controls perform the type of validation that
we need then we can use CustomValidator control. In this control, we can
associate function for a custom validation.
Syntax:
<asp:CustomValidator ID="CustomValidator1"
runat="server" />
Important Properties:
- ControlToValidate: ID of control to be validate.
- Text: text to display for the validator when the validated control is
invalid.
- ErrorMessage: Message to display in a ValidationSummary when
the validated control is invalid.
- ServerValidate(Event): This event raised when the CustomValidator
performs validation.
P a g e | 37
ASP.NET Notes
<%@ Page Language="C#" %>
<script runat="server">
void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
if (args.Value.Length <= 10)
args.IsValid = true;
else
args.IsValid = false;
}
</script>
<html>
<head><title>Custome Validation Page</title></head>
<body>
<form id="form1" runat="server">
<div>
Input string of 10 character
<asp:TextBox ID="TextBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1"
runat="server" ControlToValidate="TextBox1"
OnServerValidate="CustomValidator1_ServerValidate"
Text="(String Length is greater than 10) />
<br />
<asp:Button ID="Button1" runat="server"
Text="Submit" />
</div>
</form>
</body>
</html>
P a g e | 38
ASP.NET Notes
Basics of Regular expression
d (for digits)
w (for character)
{n} (n is exact number of allowed digits or character)
[a-z](match any one specified character)
+ (for one or more d/w)
\ (flow of d/w)
for example:
P a g e | 39
ASP.NET Notes
Calendar control:
The Calendar control displays a calendar that can use as a date picker or to
display a list of upcoming events.
Syntax:
<asp:Calendar ID="Calendar1" runat="server"/ >
Properties:
- Caption: The caption associated with calender.
- DayNameFormat: To set day name as(Mon/Monday/Mo/M.
- FirstDayOfWeek:Which day of week display first. (Sun/Mon/Tue..).
- NextMonthText: To set text for next month Button.(> for >).
- PrevMonthText: To set text for previous month Button. (< for <).
- NextPrevFormat: To set format for Next and Previous month
navigation buttons.(ShortMonth / FullMonth/ CustomText).
- SelectedDate: To get or set selected date.
- SelectedDates: To get multiple dates(C#).
- ShowDayHeader: If false then dayname becomes hides.
- ShowNextPrevMonth: If false then next and previous month hides.
- ShowTitle: If false then title of calender hides.
- TitleFormat: Set Month or Month Year.
- VisibleDate: Set the month of calender.
- SelectionMode: To set selection day/week/month.
Events:
- DayRender: Raised as each day is rendered.
- SelectionChanged: Raised when a new day, week, or month is
selected.
- VisibleMonthChanged: Raised when the next or previous month link
is clicked.
P a g e | 40
ASP.NET Notes
<%@ Page Language="C#" %>
<script runat="server">
void Button1_Click(object sender, EventArgs e)
{
BulletedList1.DataSource = Calendar1.SelectedDates;
BulletedList1.DataBind();
}
</script>
<html>
<head><title>Get Selected Dates Page</title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Calendar ID="Calendar1" runat="server"
SelectionMode="DayWeekMonth"></asp:Calendar>
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click" Text="Submit" />
<asp:BulletedList ID="BulletedList1" runat="server"
DataTextFormatString="{0:d}"></asp:BulletedList>
</div>
</form>
</body>
</html>
AdRotator control:
P a g e | 41
ASP.NET Notes
Procedure to add advertisements on AdRotator control using XML file.
<Ad>
<ImageUrl>~/AdImage/Ad2.jpg</ImageUrl>
<AlternateText>Advance College</AlternateText>
<NavigateUrl>www.advcol.com</NavigateUrl>
<Impressions>20</Impressions>
<Keyword>banner</Keyword>
<Width>400</Width>
<Height>200</Height>
</Ad>
</Advertisements>
6) Attach adXML.xml file to AdvertisementFile property and add
Keyword value to KeywordFilter property.
<asp:AdRotator ID="AdRotator1" runat="server"
KeywordFilter="banner"
AdvertisementFile="~/AdXMLFile.xml" />
P a g e | 42
ASP.NET Notes
Menu control: Internet Explorer Control
This control is used to create vertical and horizontal list of link in drop
down menu format.
Syntax:
<asp:Menu ID="Menu1" runat="server"/>
Properties:
- Orientation: To set Vertical / Horizontal menu.
- Items: To add collection of links.
P a g e | 43
ASP.NET Notes
ASP.NET State Management:
When user request same page or different page then server cleans up all the
created variable and object after serving that page to the user. State
management is the process by which we store information between multiple
requests for the same page or different pages.
P a g e | 44
ASP.NET Notes
</script>
<html>
<head><title>ViewState Page</title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="ok"
OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
Session:
It is a server side state management technique i.e. as long as the user is on
current page or next page, state is always available and when user idles up
to specified session time then session state lost. The server maintains the
state of user information by using a session ID.
When user makes a request without a session ID, ASP.NET creates a
session ID and sends it with every request and response to the same user.
Syntax: Session["Variable_Name"]
Session Events: We can executes codes when session starts or end using
Session_Start and Session_End events. Session events are
defining in Global.asax file that creates into root folder of website.
P a g e | 45
ASP.NET Notes
The Session_End event is raised when session ends either because of a time
out expiry or explicitly by using Session.Abandon().
Set Session Time: Add <sessionState> into web.config file of root folder.
<configuration>
<system.web>
<sessionState timeout="10" mode="InProc" />
</system.web>
</configuration>
The Session_End event is raised only in the case of InProc mode not
in the state server and SQL Server modes.
Example: Assign name into one page and display into next page. Set 1
minute for session time.
1. Global.aspx
void Session_Start(object sender, EventArgs e)
{
Session["username"] = "none";
}
2. web.config
<sessionState timeout="10" mode="InProc" />
3. session.aspx
<%@ Page Language="C#" %>
<script runat="server">
Button1_Click(object sender, EventArgs e)
{
Session["username"] = TextBox1.Text;
Response.Redirect("~/nextPage.aspx");
}
</script>
<html>
<head><title>Session Page</title></head>
<body>
<form id="form1" runat="server">
<div>
Input Name
<asp:TextBox ID="TextBox1" runat="server" />
<asp:Button ID="Button1" runat="server"
Text="Submit" OnClick="Button1_Click" />
</div>
P a g e | 46
ASP.NET Notes
</form>
</body>
</html>
4. nextpage.aspx
<%@ Page Language="C#" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
Label1.Text = Session["username"].ToString();
}
</script>
<html>
<head><title>Next Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" />
</div>
</form>
</body>
</html>
Application:
Application state is a server side state management technique. The data
stored in application state is common for all users of that particular
ASP.NET application and can be accessed anywhere in the application. It is
also called application level state management. Data stored in the
application should be of small size.
Syntax: Application["Variable_Name"]
Application Events:
Application events are defining in Global.asax file that creates into root
folder of website.
P a g e | 47
ASP.NET Notes
Application_End: It is raised just before the domain ends, server
restart, when the first request is made using domain(www.LRsir.net) of web
site.
1. Global.aspx
void Application_Start(object sender, EventArgs e)
{
Application["count"] = 0;
}
2. Application.aspx
<%@ Page Language="C#" %>
<script runat="server">
void Button1_Click(object sender, EventArgs e)
{
int i=Convert.ToInt32(Application["count"]) + 1;
Application["count"] = i.ToString();
Label1.Text = i.ToString();
}
</script>
<html>
<head><title>Application State Page</title></head>
<body>
<form id="form1" runat="server">
<div>
Total clicks by all users
<asp:Label ID="Label1" runat="server"/>
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click" Text="Submit" />
P a g e | 48
ASP.NET Notes
</div>
</form>
</body>
</html>
P a g e | 49
ASP.NET Notes
UNIT-III
Architecture of ADO.NET
Connected and Disconnected Database
Create Connection using ADO.NET Object Model
Connection Class
Command Class
DataAdapter Class
Dataset Class
Database Accessing on web applications:
Data Binding concept with web
Creating data grid
Binding standard web server controls
Display data on web form using Data bound controls.
P a g e | 50
ASP.NET Notes
Architecture of ADO.NET:
The full form of ADO.NET is ActiveX Data Object.Net. Basically it is container of all
the standard classes which are responsible for database connectivity of .net application to
the any kind of third party database software like Ms Sql Server, Ms Access, MySql,
Oracle or any other database software.
All classes belongs to ADO.NET are defined and arrange in “System.Data” namespace.
The architecture of ADO.NET is following.
P a g e | 51
ASP.NET Notes
5. Dataset: This component is the main source of records for .net control
like GridView. It has capability to generate a number of tables to hold
records retrieved from DataAdapter or XML.
using System.Configuration;
After then we declare a string variable to store connection string that getting
from web.config file. It is written as.
string constr1= ConfigurationManager.
ConnectionStrings["constr"]. ConnectionString;
P a g e | 52
ASP.NET Notes
such connection string will enable connection with “Database.mdf” file
that created using MS-SQL Server database software.
Establishing Connection:
We need to connect our .NET application with required database file before
data communication. For this operation the connection must be opened and
connection will be open by Connection Class provided by ADO.NET. To
estblising connection with different database file, we need Connection
Class.
Working with Connection Class:
Step 1: Create a connection string in web.config file.
Step 2: Include namespace: System.Data.SqlClient.
Step 3: Get Connection String in required Code Behind.
Step 4: Create Object of Connection Class and pass connection string to this
object.
Step 5: Open connection.
Step 6: Perform data access operation.
Step 7: Close active connection.
Above steps can be implemented as.
Namespace: If we want to connect a Database.mdf file that created under
MS-Sql Server Software then Code Behind must included following
namespace.
using System.Data.SqlClient;
Connection Class:
This namespace support following Connection Class to establishing
connection.
SqlConnection
Before establishing connection, we need to create an connection object and
passing connection string to the constructor of Connection class like this-
SqlConnection con= new SqlConnection(constr1);
here:
con = Connection object
constr1= a string variable that contain Connection String
Opening Connection: When Connection Object is created then by calling
Open() method of Connection Class, we can create an active connection.
Like-
con.Open();
P a g e | 53
ASP.NET Notes
When this method executes then connection will be establised with required
database file.
Closing Connection: When all data communication has been performed
over this active connection, then connection must be dis connected so that
connection object can be further used with same database file or different
database file. Like-
con.Close();
Command Class:
This is one of component of ADO.NET. With the help of this componenet
we can assign SQL command and execute on database software using
active connection.
SqlCommand
It is command class for MS-SQL Server Database.
Working process with Command Class:( for MS-SQL Server database)
Step1: Include ADO.NET namespace in code behind.
Ex: using System.Data.SqlClient ;
Step2: Open Database Connection.
Ex:
SqlConnection con=new SqlConnection(constr1);
con.Open();
Here constr1 is Connection String for required database connectivity.
Step3: Write Required SQL command like INSERT / UPDATE / DELETE
in string formate.
Ex:
To add new record
string sql= "INSERT INTO Book (BookName, Price)
VALUES('ASP.NET', 500)";
To update new record
string sql= "UPDATE Book SET BookName= 'C#.NET',
Price='400' WHERE BookID=1";
To delete any record
string sql= "DELETE FROM Book WHERE BookID=1";
Step4: Create Object of Command Class then Pass Sql Command and
Active Connection to the Constructor of command class.
P a g e | 54
ASP.NET Notes
Ex:
SqlCommand cmd = new SqlCommand(sql, con);
Here-
sql= SQL Command in string form.
con= Active Connection.
Step5: Execute INSERT / UPDATE / DELETE Command using
ExecuteNonQuery() method of Command class.
Ex:
cmd.ExecuteNonQuery();
When all above steps are complete then required sql command will be
executed on active connection sucessfully.
DataReader Class:
Data Reader class in one of ADO.NET’s components. The purpose of this
class is to hold the reference of records that retived after executing SELECT
command using ExecuteReader() method of Command Class.
SqlDataReader
It is a DataReader class for MS-SQL Server Database. Read() method of
DataReader class will return true value if records found otherwise false.
Using index value(0,1,..) of DataReader object, we can retieved column
value of records.
Working process with DataReader Class:( for MS-SQL Server database)
Step1: Include ADO.NET namespace in code behind.
Ex: using System.Data.SqlClient ;
Step2: Open Database Connection.
Ex:
SqlConnection con = new SqlConnection(constr1);
con.Open();
Here constr1 is Connection String for required database connectivity.
Step3: Write Required SELECT SQL command in string formate.
Ex:
string sql= "SELECT * FROM Book WHERE BookID=1";
Step4: Create Object of Command Class then Pass Sql Command and
Active Connection to the Constructor of command class.
P a g e | 55
ASP.NET Notes
Ex: SqlCommand cmd = new SqlCommand(sql, con);
Here-
sql= SQL Command in string form.
con= Active Connection.
Step5: Create Object reference of DataReader class.
Ex: SqlDataReader dr;
Step6: Execute SELECT sql Command using ExecuteReader() method of
Command class and assign reference of retrieved records to the DataReader
object reference.
Ex: dr=cmd.ExecuteReader();
Step7: Check availability of retirieved records in to DataReader using
Read() method. If found then retrives column's value into controls using
idex value.
Ex:
if(dr.Read()==true)
{
TextBox1.Text=dr[0].ToString(); // First Column Value
TextBox2.Text=dr[1].ToString(); // Second Column Value
TextBox3.Text=dr[2].ToString(); // Third Column Value
}
When all above steps are complete then required SELECT sql command
will be executed on active connection sucessfully and records will be shown
on destination control.
P a g e | 56
ASP.NET Notes
papulated by records from any source then records of Dataset can be shown
on any Data bind control like GridView.
Working process with DataAdapter and Dataset Class:( for MS-SQL
Server database)
Step1: Include ADO.NET namespace in code behind.
Ex: using System.Data.SqlClient ;
Step2: Open Database Connection.
Ex:
SqlConnection con = new SqlConnection(constr1);
con.Open();
Here constr1 is Connection String for required database connectivity.
Step3: Write Required SELECT SQL command in string formate.
Ex:
string sql= "SELECT * FROM Book";
Step4: Create Object of Command Class then Pass Sql Command and
Active Connection to the Constructor of command class.
Ex: SqlCommand cmd = new SqlCommand(sql, con);
Here-
sql= SQL Command in string form.
con= Active Connection.
Step5: Create Object of DataAdapter class then pass object of Command
Class to its Constructur.
Ex: SqlDataAdapter da = new SqlDataAdapter (cmd);
Step6: Create Object of Dataset class.
Ex: Dataset ds = new Dataset();
Step7: Call Fill() method of DataAdapter class and pass object of Dataset to
fill retrived records.
Ex: da.Fill(ds);
Here-
da= DataReader
ds= Dataset
When all above steps are complete then required SELECT sql command
will be executed on active connection sucessfully and records will befillup
into Dataset.
P a g e | 57
ASP.NET Notes
Data Bound Control and Data Grid ( GridView Control):
Any control of ASP.NET that can be used to show records of any data
source like MS-SQL Server called Data Bound Control. To Bind records on
Data Bound control, DataSource property and DataBind() method is used
of that control.
Data Grid or GridView Control is one most papular and important Data
bound control. Using this control we can show records on table form. The
Data source of GridView control is Dataset.
Let GridView1 is one Databound control of GridView Control then to bind
Records of Dataset we have to apply DataSource property and DataBind()
method like.
GridView1.DataSource = ds;
GridView1.DataBind();
Here
ds= Dataset with Records.
Working process with DataBound Control ( DataGrid / GridView)
First add GridView Control on web page using following asp.net code.
<asp: GridView ID= “GridView1” runat= “server” />
Now apply following steps on page load event of web page.
Step1 to Step7 are same as DataAdpter and Dataset.
Step8: Set Data source of GridView control that is Dataset.
Ex: GridView1.DataSource=ds;
Step9: Bind GridView control so that data can be shown on control.
Ex: GridView1.DataBind();
When all above steps are completed then data of Dataset can be bindup to
the data bound control like GridView.
P a g e | 58
ASP.NET Notes
UNIT-IV
Writing datasets to XML
Reading datasets with XML
Web Application deployment
Web services: Introduction
Remote method call using XML
SOAP
Web service description language
Building & consuming a web service
.
P a g e | 59
ASP.NET Notes
Working with XML Data:
- XML(Extensible Markup Language) has the standard format to
represent information on the web.
- XML files (or streams of data) are self-describing nature that is each
value has a label.
- XML is case-sensitive.
- XML files can be created, read, and revised using ASP.NET 2.0.
Example: XML format to represent data:
Let we have following data about any book in tabular form as-
Bid BookName Price
1 ASP.NET 600
2 Java 400
3 AI 500
Now the XML format for above table can be represented as-
<Books>
<Book>
<Bid>1</Bid>
<BookName>ASP.NET</BookName>
<Price>600</Price>
</Book>
<Book>
<Bid>2</Bid>
<BookName>Java</BookName>
<Price>400</Price>
</Book>
<Book>
<Bid>3</Bid>
<BookName>AI</BookName>
<Price>500</Price>
</Book>
</Books>
Here
<Books> Represent name of Database
<Book> Represent Each Row
<Bid>,<BookName> and <Price> Represent Field Names that
repeats for each row with different values.
P a g e | 60
ASP.NET Notes
using System.Xml;
This namespace contains all the necessary classes that capable to work with
XML file.
If we want to write data of dataset to the XML format file then we call
WriteXml() method of Dataset object.
Dataset ds=new Dataset();
ds.WriteXml(Server.MapPath("xmlfile.xml"));
Process of Writing Dataset content to XML:
1. First of all we read table data from database and fill to the Dataset
2. Write Dataset content to the XML file.
using System.XML;
using System.Data.OleDb;
void btnWrite_Click(object sender, EventArgs e)
{
//Step 1:
//Establish connection string
OleDbConnection con = new OleDbConnection
("provider=microsoft.jet.oledb.4.0; data source=
|datadirectory|database.mdb");
con.Open();
//Getting data from database
string sql="select * from student";
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
// Create new Dataset and fill
DataSet ds = new DataSet();
da.Fill(ds);
//Step 2:
//Write Dataset content to XML file
ds.WriteXml(Server.MapPath("xmlfile.xml"));
Response.Write("Dataset contents has write to the XML");
}
When above code will be implement on any event like button click and
event occurs at run time then contents of Dataset will be save in XML form
to the xmlfile.xml.This file store dataset content in following form:
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Table>
<ID>1</ID>
<sname>lokesh</sname>
<age>35</age>
</Table>
<Table>
<ID>2</ID>
<sname>jahnavi</sname>
<age>3</age>
P a g e | 61
ASP.NET Notes
</Table>
</NewDataSet>
From above explanation it is clear that we can write dataset content to the
XML file.
P a g e | 62
ASP.NET Notes
When web page executes then XML content via Dataset into data grid will
be shown as
Bid BookName Price
1 ASP.NET 600
2 Java 400
3 AI 500
From above explanation it is clear that we can read the dataset with XML
file content.
Step2: After then make sure that web application actually compiles and
runs.
Main menu: Debug🡪Start debugging (F5).
Step3: Convert Web application only in executable mode by following-
Main menu: Select Build🡪Publish web site.
Step4: We get a window. Choose target location and press ok button.
Step5: Copy web application from target location to an application folder of
remote hosting computer (server).
P a g e | 63
ASP.NET Notes
Web Services:
Basic Means: Web Services allow a consumer site (local) to obtain
information from a provider site.
For example: Any local web site can display real-time data using web
services provided by the Main site(www.Ford.com), but keep the user on
the page of the local site.
Features of Web Services:
- ASP.NET 2.0 offers a complete web-services solution.
- Web services are a method of making information available that
could be accessed by any developer’s application over the Web.
- Web services can form a library of information that could be anything
like a mathematical function calculator.
- A web service is not an local web application and does not rendered
as web pages, nor as executable files (.exe); It is just like a user
interface.
- The information contained in the web service is wrapped up as an
XML document (in other words, plain text).
- Web services communicate using open protocols like SOAP.
- Web services are self-contained and self-describing mechanism.
- HTTP and XML is the basis for Web services.
- Web services can be published, found, and used on the Web.
- Web services use XML to code and to decode data, and SOAP to
transport it (using open protocols).
Benefits:
- Web Developer can use easily web services and integrate them into
web applications.
- Web services save the time of developer and effort by reducing code
duplication.
Way of using web services:
They can be used in one of two ways.
1. You can create a web service that is exposed to the web, to share with
other developers and other applications. Or
2. you can search for a web service that can be added to your own
application. (They are similar to plug-ins in that respect.)
Components of Web Services:
Everything to do with web services is standardized:
- the method of transmission
P a g e | 64
ASP.NET Notes
- the method used to wrap the web service up
- the way the web service is defined
All have clear W3C standards associated with the technologies involved.
And all these standards are based on XML. So they’re quick and easy to
download, and even easier to use.
< types>
data type definitions........
< /types>
< message>
definition of the data being communicated....
< /message>
< portType>
set of operations......
< /portType>
< binding>
protocol and data format specification....
< /binding>
< /definitions>
A WSDL document can also contain other elements, like extension
elements, and a service element.
ASP.NET Notes
SOAP: (Simple Object Access Protocol)
Basic Concepts: SOAP provides a way to communicate between
applications running on different operating systems, with different
technologies and programming languages. It is important for application
development to allow Internet communication between programs.
Need of SOAP: Today's applications communicate using Remote Procedure
Calls (RPC) between objects like DCOM and CORBA, but HTTP was not
designed for this. RPC represents a compatibility and security problem;
firewalls and proxy servers will normally block this kind of traffic.
Solution: SOAP was created to accomplish this for better way to
communicate between applications over HTTP, because HTTP is supported
by all Internet browsers and servers.
General Features of SOAP :
SOAP is a communication protocol
SOAP is for communication between applications.
SOAP is a format for sending messagesl
SOAP communicates via Internet.
SOAP is platform independent.
SOAP is language independent.
SOAP is based on XML.
SOAP is simple and extensiblel
SOAP is a W3C recommendation in 24. June 2003.
SOAP Building Blocks:
A SOAP message is an ordinary XML document containing the following
elements:
Skeleton SOAP Message
< ?xml version="1.0"?>
< soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-
envelope" soap:encodingStyle= "http://www.w3.org/2001/12/
soap-encoding">
< soap:Header>
...
< /soap:Header>
< soap:Body>
...
ASP.NET Notes
<soap:Fault>
...
</soap:Fault>
< /soap:Body>
< /soap:Envelope>
Here-
An Envelope element: that identifies the XML document as a SOAP
message.
A Header element: that contains header information.
A Body element: that contains call and response information
A Fault element: containing errors and status information
All the elements above are declared in the default namespace for the SOAP
envelope.
ASP.NET Notes
UNIT-V
Overview of C#
C# and .NET
Similarities & differences from JAVA
Structure of C# program
Language features:
Type system
Flow control
Boxing and unboxing
Classes
Interfaces
Serialization
Delegates
Reflection.
ASP.NET Notes
Overview of C#:
- C# is Microsoft’s programming language for .NET development.
- C# was created at Microsoft late in the 1990s and It was first released
in its alpha version in the middle of 2000. C#’s chief architect was
Anders Hejlsberg. Different version of C# are 1.0, 1.1, 2.0,3.0.
- The Source code of C# converts into 16 bits MSIL code(Microsoft
Intermediate Language) and executed by .NET Framework.
- C# is directly related to C, C++, and Java. From C, C# derives its
syntax, many of its keywords, and its operators. From C++, C#
builds upon and improves the object model.
- C# and Java both descended from C and C++ that shares the C/C++
syntax and object model.
- C# support properties, methods, and events.
C# v/s C, C++ and Java:
- C was invented by Dennis Ritchie in the 1972 based on the Procedure
Oriented programming. Using C, large programs were difficult to write.
- C++ was invented by Bjarne Stroustrup beginning in 1979 based on
Object oriented Model. Using C++, large programs were easy to handle.
- C and C++, always compiled machine dependent executable code and
not support internet based programs.
C# Java
C# was created at Microsoft late in Java was invented by James
the 1990s by Anders Hejlsberg. Gosling team in 1991 at Sun
Microsystems. Initially called
Oak.
C# is a structured, object-oriented Java is also a structured, object-
language with a syntax and oriented language with a syntax
philosophy derived from C and and philosophy derived from C
C++. and C++.
C# achieved portability by Java achieved portability by
translating a program’s source code translating a program’s source
into an intermediate language called code into an intermediate
MSIL code(Microsoft Intermediated language called byte code. This
language). This MSIL code was byte code was then executed by
then executed by the .Net the Java Virtual Machine (JVM).
Framework.
A C# program could run only in an A Java program could run in any
ASP.NET Notes
environment where MS.NET environment for which a JVM
framework is available. was available.
C# code is neither upwardly nor Java code is also neither upwardly
downwardly is compatible with C or nor downwardly is compatible
C++, its syntax sufficiently similar. with C or C++, its syntax
sufficiently similar.
C# has successfully portable in the Java has also successfully
Internet environment along with portable in the Internet
ASP.NET. environment.
C# includes features that directly Java has also supported.
support the constituents of
components, such as properties,
methods, and events.
C#’s has ability to work in a secure, Java work only in one language
mixed-language Environment. environment.
// Namespace Declaration
using System;
// Program start class
class WelcomeCSS
{
// Main begins program execution.
static void Main()
{
// Write to console
Console.WriteLine("www.LRsir.net");
}
}
// Other user define class
ASP.NET Notes
Remark: C# is case-sensitive. The C# program has 4 primary elements:
1. A namespace declaration
2. A class
3. A Main method and
4. A program statement.
csc.exe Welcome.cs
Description:
The C# data types: Variables are declared using following C# data types.
Example: int a;
string name="LRsir.net"
ASP.NET Notes
The Array Type: Array can be thought of as a container that has a list of
storage locations for a specified type. When declaring an Array, specify the
type, name, dimensions, and size.
Example:
using System;
class Array
{
public static void Main()
{
string[] myStrings = new string[3];
myStrings[0] = "Joe";
myStrings[1] = "Matt";
myStrings[2] = "Robert";
……………
}
}
C# Operators:
Results are computed by combining variables and operators together into
statements. The following table describes the allowable operators, their
precedence and associativity.
Flow Controls:
The if statements.
The switch statement with break.
Loop: while, do, for, foreach
When condition evaluates to true, the statement in the if block are executed;
when false, the statements in the else block are executed.
The switch block follows one or more choices. When the result of the switch
expression matches one of these choices, statements of the matching choice
are executed. After then jumps out from switch block using break. If none
of the other choices match, then the default choice is taken and its
statements are executed, although the use of default label is optional.
The while Loop: A while loop will check a condition and then continues to
execute a block of code as long as the condition evaluates to a boolean value
of true.
Syntax:
while (Condition)
{
statements
}
Once the statements have executed, control returns to the beginning of the
while loop to check the boolean expression again.When the boolean
expression evaluates to false, the while loop statements are skipped.
The do Loop: A do loop is similar to the while loop, except that it checks its
condition at the end of the loop. This means that the do loop is guaranteed to
execute at least one time. On the other hand, a while loop evaluates its
boolean expression at the beginning.
Syntax:
do
{
Statements
}while (Condition);
The for Loop: A for loops are appropriate when you know exactly how
many times you want to perform the statements within the loop.
ASP.NET Notes
Syntax: The contents within the for loop parentheses hold three sections
separated by semicolons.
Condition: Once the initializer has been evaluated, the for loop gives control
to condition. When the condition evaluates to true, the statements within the
curly braces of the for loop are executed.
Update Initializer: After executing for loop statements, control moves to the
top of loop and executes updater, after then control transfer to condition
part.
The foreach Loop: A foreach loop is used to iterate through the items in a
list. It operates on arrays or collections such as ArrayList, which can be
found in the System.Collections namespace.
Syntax:
Introduction to Classes:
Classes are declared by using the keyword class followed by the class name
and a set of class members surrounded by curly braces.
// Instance Method
public void printString()
{
Console.WriteLine("{0}", myString);
}
// Destructor
~OutputClass()
{
// Some resource cleanup routines
}
}
Interfaces:
interface MyInterface
{
void MethodToImplement();
}
This method does not have an implementation because the interface only
specifies the methods that must implement in class.
Using an Interface:
class UseInterface : MyInterface
{
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
static void Main()
{
UseInterface oi = new UseInterface();
oi.MethodToImplement();
}
}
Delegates:
A delegate is an object that can reference a method just like a function
pointer used in C or C++. Therefore, when you create a delegate, you are
creating an object that can hold a reference to a method. Furthermore, the
method can be called through this reference.
In other words, a delegate can invoke the method to which it refers.
Creating Delegate:
delegate ret-type delegateName(parameter-list);
//delegate is a keyword
Example: delegate int Dx(int,int);
Here Dx is such delegate that can hold reference of any method whose
return type is int and has two arguments of int and int type.
Holding method reference to Delegates:
delegateName objectName=new
delegateName(Clsobject.MethodName);
delegateObject(list of arguments);
The object is serialized to a stream, which carries not just the data, but
information about the object's type, such as its version, culture, and
assembly name. From that stream, it can be stored in a database, a file, or
memory.
Uses: Its main purpose is to save the state of an object in order to be able to
recreate it when needed. Through serialization, a developer can perform
actions like sending the object to a remote application by means of a Web
Service, passing an object from one domain to another, etc.
Reflection:
Reflection is the feature that enables you to obtain information about a type.
Using this information, you can construct and use objects at runtime. This
feature is very powerful because it lets a program add functionality
dynamically, during execution.
System.Reflection namespace must be included before using classes of
reflection.
Ex:
// Analyze methods using reflection.
using System;
using System.Reflection;
class MyClass
{
Class-members
}
ASP.NET Notes
class ReflectDemo
{
static void Main()
{
MyClass obj=New MyClass();
Type t = typeof(obj); // get a Type of object obj
Console.WriteLine("Class Type of obj is:" + t.Name);
}
}
Output: Class Type of obj is: MyClass
Here typeof returns a Type object that represents the specified type, which
in this case is MyClass.