0% found this document useful (0 votes)
66 views

VB Unit4&5

4 and 5

Uploaded by

Ravi Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

VB Unit4&5

4 and 5

Uploaded by

Ravi Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

VB.

Net Programming

Introduction
Web applications are created by adding web forms to the application and placing controls to the
forms and respond to user interaction with the forms. The visual studio .NET is used to create a
web application. It is used to create different types of web application and web services provide
access to data. ASP.NET is a compiled programming environment that uses the .NET framework
to create an application.

Creating an ASP.NET Web Application


 Click on Start and the start menu will be displayed.

 Select the programs and then select Microsoft Visual Studio.NET.

 The submenu will be displayed. Click the visual studio.NET.

 After opening the visual studio.NET applications click the file and the file menu is
displayed. Place the mouse to new and click the project in the submenu.

 Then the new project will open and select the visual basic project folder and a set of
templates are displayed.

 Select the ASP.NET web application and give the name for the web application.

 Set the location of the web application during naming the web application and the new
project is created in a particular location in the Visual Studio.NET.

Naming the Form


 The blank web form is created in the web project and the name of the project can be
changed. By default, the web form is named WebForm1.aspx.

 Right-click the name of the form in solution explorer and select rename in the short
menu.

 Clear the name of the form and name the new name and name the form with the
extension of .aspx.

 Clicks enter and the name of the web form will be changed.

Changing class with the web form


 The class name of the web form and the name of the web form are the same.

 Change the name of the class by double-clicking on the form in the design view and the
code will open.

 Change the name of the class.


 The class name in the @page directive of the web form is also changed. Change the name
of the class in the @page directive.

SHASHI RAJ, BMSCW /Page 1


VB.Net Programming

Adding a web form


 A web application can contain many web forms and there is a default form and many
forms can be added to it in the same project.

 Right-click the name of the project and move the mouse to add and select add web form
in the add submenu.

 Name the web form in the name text box.

 Select open to create a new form.

 The class name should be the same as the web form name.
Grid Layout
It uses the absolute position controls to the web forms. Depending on the size of the form the
position of the control will never change. Grid Layout is used when the size of the control is
known.

Flow Layout
It will not position the controls to the forms and is determined automatically on the screen. If
control is placed the next control is placed based on the previous control width and height. The
flow layout is used when the size of the control is not known.

Adding Controls
Controls are added to the form instead of using the HTML tags in it. The toolbox is used in the
Visual Studio .NET to perform table operation instead of using the table HTML tags.

 Open the form.

 Click label control in the options of the toolbox and the label control is selected in it.

 Click the control required in the toolbox to the form and place it.

 Right-click the label control and select the properties in the menu.

The controls are customized in the properties menu by renaming the field or changing the color
of the text in the form. Many Controls can be added to the webform. Buttons can also be added
to the web form.

SHASHI RAJ, BMSCW /Page 2


VB.Net Programming

Examples using standard controls in asp.net


Common Server Control
Label control
Label control and the Literal control are used to display text in a page. Literal control only
supports text property, but the Label control has a number of formatting properties.
By default, a Label control renders its content in an HTML <span> tag. After executing your
application, you can see the respective label <span> tag by using view source on the browser.

The Label control displays text at a particular position on a Web page. Generally Label control is

used as the caption of a TextBox.


<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Literal control

It is light weight control. The Literal Control is similar to the Label Control but it does not
support properties like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, etc. Also
you cannot apply a style to a literal control. It is used to display static text on a Web page
without adding additional properties or HTML tags.

<asp:Literal ID="Literal1" runat="server">It is a Literal Control</asp:Literal>

TextBox control

The TextBox control is frequently used and one of the most important control. It is used to
collect information from a user. It is an input control which is used to input the data.
The TextBox control contains an important property called TextMode. By using this property
you can set textbox as

 SingleLine
 MultiLine
 Password
 SingleLine mode is default mode of textbox control and allows the user to enter data in a
single line of text.
 Password mode masks (text is hidden) the values entered by the user.
MultiLine mode enables user to enter text in more than one line. You can use MultiLine mode,
in combination with the Columns and Rows properties. Column specifies the number of columns
(Width) and rows specify the number of rows (Height) to display.
Another important property of textbox control is MaxLength. It sets the limit on the number of
character that a user can enter into textbox.

TextBox control supports the following event:


TextChanged: It fires, when you change the content or text of the textbox control. TextChanged
event only fire, when AutoPostBack property has the value True. By default AutoPostBack
property has the value false.

SHASHI RAJ, BMSCW /Page 3


VB.Net Programming

If you change the text of the TextBox control and press tab key from the keyboard, the form is
automatically posted back to the server.

Button Controls

There are three types of button control available in ASP.NET:


 Button
 Link Button
 Image Button
Button control
Button control postbacks the web page to webserver, when user clicks the button. A Button
control can be used as a submit button (default) or a command button.

You can also use Button control as a command button. It is useful when you want to group a set
of buttons. Button control has property called CommandName. Assign unique CommandName
value for each button. Create a single command event handler explicitly, that will handle the
event of all command buttons.
Suppose that you have four buttons as given below and want to create all buttons as a command
button.

CausesValidation property: It checks the page validation. By default this property is true for
button control. If you set CauseValidation value to false, then it will bypass the page validation.

LinkButton

LinkButton control displays a link instead of a push button. By default, a LinkButton control is a
Submit button.
Some of the important properties of LinkButton Control are:

CausesValidation: If this property is set as true then validation will be performed when
Linkbutton is be clicked. Otherwise it will bypass the validation.

PostBackUrl: It posts a form to a particular page when the LinkButton control is clicked.

ValidationGroup: The group of controls when the LinkButton control causes posts back to the
server.

OnClick: Attach a server side method that will fire when this button will be clicked.

OnClientClick: You can attach a client-side script that executes when the LinkButton is clicked.

ImageButton
The ImageButton control is similar to Button and LinkButton controls but it always displays an
image. It works as a clickable image. Most of the properties are same as Button or LinkButton.
The main difference is ImageUrl and AlternateText property. ImageUrl Gets or Sets the location
of the image. AlternateText property provides alternate text for the image.

SHASHI RAJ, BMSCW /Page 4


VB.Net Programming

CheckBox Control
A CheckBox control is used to select a single or multiple options from the available choices. For
example a person can select more than one cities for travelling.

Important Properties of the CheckBox Control

Checked: It is used to check if the check box is checked or not. This is a boolean property.
Text: It is used to get or set the text associated with the check box control. This is a string
property.
TextAlign: It enables you to set the text right or left of the check box. By default TextAlign
property is set to right.
AutoPostBack: If you want that when you change the status of checkbox (check or uncheck),
then set AutoPostBack property true. By default this property is set to false.

Methods:
Focus(): It sets the input focus, to a specific checkbox. Call this method for that check box
control.

Events:
CheckedChanged: This event is fired when the checked status of the checkbox control is
changed. AutoPostBack property should be set as true to fire this event.

NOTE: For Example Refer web application program

Using HTML controls in asp.net

HTML server controls are HTML elements that contain attributes to accessible at server side. By
default, HTML elements on an ASP.NET Web page are not available to the server. These
components are treated as simple text and pass through to the browser. We can convert an
HTML element to server control by adding a runat="server" and an id attribute to the
component.
Now, we can easily access it at code behind.

Example
<input id="UserName" type="text" size="50"runat="server" />

All the HTML Server controls can be accessed through the Request object.

SHASHI RAJ, BMSCW /Page 5


VB.Net Programming

HTML Components
The following table contains commonly used HTML components.
Controls Description
Name
Button It is used to create HTML button.
Reset Button It is used to reset all HTML form elements.
Submit It is used to submit form data to the server.
Button
Text Field It is used to create text input.
Text Area It is used to create a text area in the html form.
File It is used to create a input type = "file" component which is used to upload file to the
server.
Password It is a password field which is used to get password from the user.
CheckBox It creates a check box that user can select or clear.
Radio Button A radio field which is used to get user choice.
Table It allows us to present information in a tabular format.
Image It displays an image on an HTML form
ListBox It displays a list of items to the user. You can set the size from two or more to
specify how many items you wish to show.
Dropdown It displays a list of items to the user in a dropdown list.
Horizontal It displays a horizontal line across the HTML page.
Rule

Example

Here, we are implementing an HTML server control in the form.

// htmlcontrolsexample.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="htmlcontrolsexample.aspx.cs"

Inherits="asp.netexample.htmlcontrolsexample" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Text1" type="text" runat="server"/>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"/>
</div>
</form>
</body>
</html>

SHASHI RAJ, BMSCW /Page 6


VB.Net Programming

This application contains a code behind file.


// htmlcontrolsexample.aspx.cs
using System;
namespace asp.netexample
{
public partial class htmlcontrolsexample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string a = Request.Form["Text1"];
Response.Write(a);
} }}
Output:

When we click the button after entering text, it responses back to client.

SHASHI RAJ, BMSCW /Page 7


VB.Net Programming

Validating form input controls using validation controls in asp.net

Validation can be performed at the client-side as well as server-side.

 Client-side validation makes the process fast as there is less number of hits to the server.
 Server-side validation is used to remove the limitation of client browsers dependencies
and scripting language support.

Types of Validation
Validation can be classified into two types based on client and server validation:

1. Client side Validation


2. Server side Validation

1. Client side Validation

 Validations performed at Client-Side i.e., browser.


 User gets information immediately as validation performed before a request is sent to the
server.

2. Server-side Validation

 Server-side validation takes place before data processing in the database.


 This type of validation is used, where client browser dependencies are involved.

Validation Controls used in ASP.NET


The Validation controls used in APS.NET Web Form are as follows:

1. Validation Summary
2. RequiredFieldValidator
3. RangeValidator
4. CompareValidator
5. RegularExpressionValidator
6. CustomValidator

Validation Controls can be used at the client-side as well as server-side.

1. Validation Summary Control :

ValidationSummary Control is used to summarize the entire error message at one place in the
list, bullet, or single message form.Some important properties of ValidationSummary Control
are DisplayMode, ShowMessageBox, ShowSummary,

2. RequiredFieldValidator Control:

 Control used to make web form input control required i.e. it cannot be left empty.
 User will have to enter some input without which form will not be transferred to the
server.

SHASHI RAJ, BMSCW /Page 8


VB.Net Programming

Code for aspx page


<h1>ASP.NET Validation Controls</h1>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<p>
First Name :
<asp:TextBox ID="txtFirstName" runat="server" CausesValidation="True">
</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Please Provide First Name" ControlToValidate="txtFirstName"> Required
</asp:RequiredFieldValidator>
</p>
<p>
Last Name:
<asp:TextBox ID="txtLastName" runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ErrorMessage="Please Provide Last Name" ControlToValidate="txtLastName"> Required
</asp:RequiredFieldValidator>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Submit" />
</p>

InitialValue : The property of RequiredFieldValidation control will check in the associated


control to validate whether the value is same as InitialValue or not. If a value matches
to IntitalValue, it is invalid, value other than InitialValue is Valid.

SHASHI RAJ, BMSCW /Page 9


VB.Net Programming

3. RangeValidator Control

 RangeValidator Control is used to apply some upper and lower limit for associated
input control.
 Value in input control is checked with Maximum and Minimum property values.
 Type property of RangeValidator Control defines which type of comparison takes place.

<tr>
<td style="height: 25px">Age:</td>
<td style="height: 25px">
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ErrorMessage="Age must be between 18 and 50 " ControlToValidate="txtAge"
MaximumValue="50" MinimumValue="18" Type="Integer">
</asp:RangeValidator>
</td>
</tr>

4. CompareValidator Control

 CompareValidator is used to compare some value of control with some constant value
or any value within different control.
 When we have to compare the value of one input control to others, we need to provide
value for CotrolToCompare property.
 If the value is to be compared with some constant, ValueToCompare must be given.

Some important properties of CompareValidator are ControlToCompare , ControlToValidate


, Type , Operator ,Display etc.

SHASHI RAJ, BMSCW /Page 10


VB.Net Programming

<tr>
<td>Password:</td>
<td>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="height: 25px">Confirm Password:</td>
<td style="height: 25px">
<asp:TextBox ID="txtConfirmtxtPassword" runat="server">
</asp:TextBox>

<asp:CompareValidator ID="CompareValidator1" runat="server"


ErrorMessage="Please ensure the password and confirm password is same"
ControlToValidate="txtConfirmtxtPassword" ControlToCompare="txtPassword">*
</asp:CompareValidator>
</td>
</tr>

5. RegularExpressionValidator Control

 RegularExpression Validator is used when the input from the user is in


a standard pattern, and that pattern must be followed to prevent wrong entry to the
database.
 The pattern specified in ValidationExpression property is validated then only process
proceeds.

SHASHI RAJ, BMSCW /Page 11


VB.Net Programming

<tr>
<td>Email ID
</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" runat="server"
ErrorMessage="Please enter valid email" ControlToValidate="txtEmail">
</asp:RegularExpressionValidator>
</td>
</tr>

6. CustomValidator Control
CustomValidator is used when the validation is performed to match the user’s defined
standards.
CustomValidator allows you to perform validation from both the client-side as well as server-
side.
<tr>
<td>Message</td>
<td>
<asp:TextBox ID="txtMessage" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Text must be
exactly 10 characters long!" ControlToValidate="txtMessage"
OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
</td> </tr>
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{

SHASHI RAJ, BMSCW /Page 12


VB.Net Programming

if (args.Value.Length == 10)
args.IsValid = true;
else
args.IsValid = false;
}

Understanding application and state


Application State is a state management technique. Application State is stored in the memory of
the the server and is faster than storing and retrieving information in a database. Session sate is
specific for a single user session, but Application State is for all users and sessions. Application
State does not have a default expiration period. When we close the worker process the
application object will be lost. Technically the data is shared amongst users by a
HTTPApplcationState class and the data can be stored here in a key/value pair.
It can also be accessed using the application property of the HTTPContext class.

Application State Life Cycle


Step 1: When the Browser sends a request to the web server and the server receives the request it
first checks the extension to determine whether or not it is ISAPI because this request can only
be handled by the ISAPI extension; if the extension is different than the request is handled by the
server itself.

SHASHI RAJ, BMSCW /Page 13


VB.Net Programming

Step 2: After receiving the request the Application Manager creates an application domain. In
the application domain an instance of the class Hosting Environment is created that provides
access to information about all application resources.

Step 3: After creating the application domain, ASP.NET initializes the basic objects as HTTP
Context, HTTP Request and HTTP Response. HTTP Context holds objects to the specific
application request as HTTP Request and HTTP Response. HTTP Request contains all the
information regarding the current request like cookies, browser information and so on and the
HTTP Response contains the response that is sent to the client.

Step 4: Here all the basic objects are being initialized and the application is being started with
the creation of the HTTP Application class.

Step 5: Then events are executed by the HTTP Application class for any specific requirement.
Here is a list of events:

SHASHI RAJ, BMSCW /Page 14


VB.Net Programming

Global.asax file: the Global.asax file is used for handling application events or methods. It
always exists in the root level. Events are one of the following of the 2 types in the Global
application:
1. Events that will be raised on a certain condition.
2. Events that will be raised on every request.

The application will be started only once; if 10 users send a request then 10 user sessions are
created. The events of the Global.asax file are:

1. Application_Start() : This method is invoked initially when first application domain is


created.
2. Session_Start() : This method is called every time a session is start.
3. Application_BeginRequest() : After an application has started the first method
Application_BeginRequest() is executed for every user.
4. Application_AuthenticateRequest() : It checks to determine whether or not the user is
valid.
5. Application_Error() : Whenever an unhandled exception occurs then this event will be
called.
6. Session_End() : When a user session is ended and all the data related to a specific user is
cleared then the Session_End() event is called.
7. Application_End() : This method is called before the application ends. This can take place if
IIS is restarted or the application domain is changing.
8. Application_Disposed() : This event is called after the application will be shut down and the
.NET GC is about to reclaim the memory it occupies. Although this is very late to perform
any clean-up but we can use it for safety purposes.

SHASHI RAJ, BMSCW /Page 15


VB.Net Programming

Important points of Application State variables


1. Application State variables are available across all pages and all sessions. Application State
variables are like multi-user Global data.
2. Application variables are stored on a web server.
3. Application State variables are cleared, only when the process hosting the application is
restarted, that is when the application is ended.
4. Application State variables do not support web farms and web gardens: Application State
variables are not supported be web farms.

A client sends a request and the request goes to the load balancer and the load balancer sends
a request to web server1 and the Application State variables are stored in a web server1. If the
subsequent request is sent by the client again and the load balancer sends a request to web
server2 and the Application State variables are not stored in web server2 then something.
Web servers do not share application state variables.
5. Application State variables have a concurrency problem so we need to synchronize the
method by using the lock and unlock methods. So multiple thread problems are resolved
since only one thread can do the work.
6. An application variable is used only when the variable needs to have global access and when
you need them for the entire time, during the lifetime of an application.

APPLYING STYLES IN ASP.NET


Introduction

CSS means Cascading Style Sheet. The World Wide Web Consortium (W3C) created CSS. CSS
describes the style of an HTML document.
CSS describes how HTML elements should be displayed.
Description
External stylesheets are stored in CSS files. CSS is used to define the styles for your Web pages,
which includes the design, layout and the variations in display for the different devices and the
screen sizes.

SHASHI RAJ, BMSCW /Page 16


VB.Net Programming

Steps: Part1
Create a CSS file named Styles.css.

1. body {
2. font-family: Arial;
3. }
4.
5. table {
6. font-family: arial, sans-serif;
7. border-collapse: collapse;
8. width: 70%;
9. }
10.
11. .button {
12. background-color: #4CAF50;
13. border: none;
14. color: white;
15. padding: 15px 32px;
16. text-align: center;
17. text-decoration: none;
18. display: inline-block;
19. font-size: 14px;
20. margin: 4px 2px;
21. cursor: pointer;
22. }
23.
24. .button4 {border-radius: 14px;}
25.
26. .textbox {
27. height: 50px;
28. padding: 0 10px;
29. border: none;
30. background: Orange;
31. background: Orange;
32. box-shadow: inset 0 0 10px rgba(255, 255, 255, 0.5);
33. font-family: 'Montserrat', sans-serif;
34. text-indent: 10px;
35. color: blue;
36. text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
37. font-size: 20px;
38. width: 470px;
39. }
40. .textbox:focus {
41. box-
shadow: 0 1px 0 rgba(255, 255, 255, 0.2), inset 0 1px 1px rgba(0, 0, 0, 0.1), 0 0 0 3px rgba(2
55, 255, 255, 0.15);
42. outline: none;
43. background: Orange;
44. background: Orange;
45. outline: solid 1px yellow;
46. }

SHASHI RAJ, BMSCW /Page 17


VB.Net Programming

Description of Part1
To apply design and layout to ASP.NET button controls, the button background color should be
Green and the text on button should be White.

1. .button {
2. background-color: #4CAF50;
3. border: none;
4. color: white;
5. padding: 15px 32px;
6. text-align: center;
7. text-decoration: none;
8. display: inline-block;
9. font-size: 14px;
10. margin: 4px 2px;
11. cursor: pointer;
12. }
13.
14. .button4 {border-radius: 14px;}

For table design and layout, the table width should be 70%.

1. table {
2. font-family: arial, sans-serif;
3. border-collapse: collapse;
4. width: 70%;
5. }

For textbox design and layout, the textbox background color is Orange and Text is in blue.

1. .textbox {
2. height: 50px;
3. padding: 0 10px;
4. border: none;
5. background: Orange;
6. background: Orange;
7. box-shadow: inset 0 0 10px rgba(255, 255, 255, 0.5);
8. font-family: 'Montserrat', sans-serif;
9. text-indent: 10px;
10. color: blue;
11. text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
12. font-size: 20px;
13. width: 470px;
14. }
15. .textbox:focus {
16. box-
shadow: 0 1px 0 rgba(255, 255, 255, 0.2), inset 0 1px 1px rgba(0, 0, 0, 0.1), 0 0 0 3px rgba(2
55, 255, 255, 0.15);
17. outline: none;
18. background: Orange;
19. background: Orange;
SHASHI RAJ, BMSCW /Page 18
VB.Net Programming

20. outline: solid 1px yellow;


21. }

Part2

Add a Webform named Default.aspx.

1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits=


"_Default" %>
2.
3. <!DOCTYPE html>
4.
5. <html xmlns="http://www.w3.org/1999/xhtml">
6. <head runat="server">
7. <title>Satyaprakash Wcf Concept</title>
8. <link href="Styles.css" rel="stylesheet" />
9. <script language="javascript" src="../Validation.js" type="text/javascript"></script>
10. <script language="javascript" type="text/javascript">
11. function Validation() {
12. if (Required('<%=txtname.ClientID%>', ' Name'))
13. if (Required('<%=txtGender.ClientID%>', ' Gender'))
14. if (Required('<%=txtsalary.ClientID%>', ' Salary'))
15. return true;
16. return false;
17. }
18. </script>
19. </head>
20. <body>
21. <form id="form1" runat="server">
22. <div>
23. <h2 style="background-color: Yellow;color: Blue; text-align: center; font-
style: oblique">SATYAPRAKASH's WCF CONCEPT</h2>
24. <fieldset>
25. <legend style="font-
family:Arial Black;color:orangered">WCF INSERT USING STORED PROCEDURE</lege
nd>
26. <table align="center" border="1" cellpadding="4" cellspacing="4">
27. <tr><td align="center"><asp:TextBox ID="txtname" class="textbox" runat="server"
placeholder="Enter Name.."></asp:TextBox></td></tr>
28. <tr><td align="center"> <asp:TextBox ID="txtGender" class="textbox" runat="serve
r" placeholder="Enter Gender.." ></asp:TextBox></td></tr>
29. <tr><td align="center"><asp:TextBox ID="txtsalary" class="textbox" runat="server"
placeholder="Enter Salary.."></asp:TextBox></td></tr>
30. <tr><td align="center">
31. <asp:Button ID="btnsave" runat="server" Text="Save" class="button button4" On
Click="btnsave_Click" OnClientClick="javascript:return Validation();" />
32. <asp:Button ID="btnreset" runat="server" Text="Reset" class="button button4" O
nClick="btnreset_Click"/>
33. </td></tr>
34. </table>
35. </fieldset>
SHASHI RAJ, BMSCW /Page 19
VB.Net Programming

36. </div>
37. <footer>
38. <p style="background-color: Yellow; font-weight: bold; color:blue; text-
align: center; font-
style: oblique">© <script> document.write(new Date().toDateString()); </script></p>
39. </footer>
40. </form>
41. </body>
42. </html>

Description of Part2

How to apply CSS classes in Server controls of ASP.NET Web page.

To apply CSS in button , proceed as shown below.

1. <asp:Button ID="btnsave" runat="server" Text="Save" class="button button4" OnClick="bt


nsave_Click" OnClientClick="javascript:return Validation();" />
2. <asp:Button ID="btnreset" runat="server" Text="Reset" class="button button4" OnClick="b
tnreset_Click"/>

To apply CSS in TextBoxes, proceed as shown below.

1. <asp:TextBox ID="txtname" class="textbox" runat="server" placeholder="Enter Name.."></


asp:TextBox>
2. <asp:TextBox ID="txtGender" class="textbox" runat="server" placeholder="Enter Gender.."
></asp:TextBox>
3. asp:TextBox ID="txtsalary" class="textbox" runat="server" placeholder="Enter Salary.."></
asp:TextBox>

To apply CSS in tables, proceed, as shown below.

1. table {
2. font-family: arial, sans-serif;
3. border-collapse: collapse;
4. width: 70%;
5. }

1. <table align="center" border="1" cellpadding="4" cellspacing="4">

Here CSS classes table of CSS file is added.

The output of TextBoxes of ASP.NET Web page is given below.

SHASHI RAJ, BMSCW /Page 20


VB.Net Programming

The output of buttons of ASP.NET Web page is given below.

The output of table of ASP.NET Web page is given below.

THEMES AND SKINS


Themes are set of elements like skins, Cascading Style Sheet, images and other resources like
script files. Optionally, Theme should consist of minimum skin files. Themes are defined in
special directory called App_Themes in application hierarchy. You can add this special directory
by right-clicking on your project in Visual Studio and Selecting Add Folder->Theme folder.
Within the App_Themes folder, you create an additional theme folder for each and every theme
that you might use in your application. Here in our example we defined single Theme1 theme.
You can define multiple themes to make your site customized for different users.
Themes go further than CSS, in that they allow applying styles, graphics and even CSS files
themselves to the pages of your application. You can apply ASP.NET themes at the application,
page, or server control level.

SHASHI RAJ, BMSCW /Page 21


VB.Net Programming

App_Themes folder

Differences between Themes and CSS


o CSS usually deals with HTML code. You cannot apply CSS to certain ASP.NET specific
server controls which are not present in HTML.
o You can apply Themes and skins to all ASP.NET controls with less effort. Themes and
skins can be uniformly applied on both windows and asp.net applications.
o You can apply single theme to each page where as multiple style sheets can be applied to
each page.
o Themes don't override or cascade style definitions by default the way CSS generally do.
But you can selectively override local property settings for a control using
StyleSheetTime attribute in Themes.
o You can include CSS files in Themes which is applied as part of Theme structure but not
vice-versa.
You can apply theming for only those properties that have ThemeableAttribute attribute set to
true in their control class.

Skins
Generally, Themes contain skins. A skin file contains style definitions for the individual server
controls. You can define skin settings for a control using similar markup which we use to add
server controls to web page. Only difference you may find between skinned versions of control is
that skinned version do not include ID attribute for control. You should retain properties for
which you want to configure through Themes. We create .skin files in Theme folder. We can
also mix all server controls style definition in a single skin file. Make sure all style definition
files like CSS, skin files, Image files and other resources are included in Themes folder in your
application directory.
<asp:button runat="server" BackColor="lightblue" BorderColor="AliceBlue" Font-
Bold ="true" ForeColor="black"/>
Skin file
There are two types of control skins based on their scope. They are:
Default Skins: Control skin for which SkinID attribute is not set which means control skin is
applied automatically for the controls of same type. For example: if you create a default skin for
button then default button control skin will be applied for all the buttons on the page. The scope
of default skin depends on where you define default skin.
Named Skins: Named Skins will have SkinID property set which means you can use named
skins with a control only by setting control's SkinID property to specific named skinID. Named
Skins do not apply for the controls by type.

SHASHI RAJ, BMSCW /Page 22


VB.Net Programming

How to apply themes

There are 3 different options to apply themes to our website:


1. Setting the theme at the page level: the Theme attribute is added to the page directive of the
page.
1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inher
its="Default" Theme="Theme1"%>
2. Setting the theme at the site level: to set the theme for the entire website you can set the
theme in the web.config of the website. Open the web.config file and locate the <pages>
element and add the theme attribute to it:

1. <pages theme="Theme1">
2. ....
3. ....
4. </pages>
3. Setting the theme programmatically at runtime: here the theme is set at runtime through
coding. It should be applied earlier in the page's life cycle ie. Page_PreInit event should be
handled for setting the theme. The better option is to apply this to the Base page class of the
site as every page in the site inherits from this class.

Page.Theme = Theme1;
Uses of Themes
1. Since themes can contain CSS files, images and skins, you can change colors, fonts,
positioning and images simply by applying the desired themes.
2. You can have as many themes as you want and you can switch between them by setting a
single attribute in the web.config file or an individual aspx page. Also you can switch
between themes programmatically.
3. Setting the themes programmatically, you are offering your users a quick and easy way to
change the page to their likings.
4. Themes allow you to improve the usability of your site by giving users with vision problems
the option to select a high contrast theme with a large font size.
Example
Create 2 themes for the page – one with red background (Theme1) and another with an image as
a background (Theme2). When the user selects a particular theme from the ListBox then that
theme should be applied dynamically for the page.

1. Solution Explorer -> Right click -> Add ASP.NET folder -> Themes.
A new folder App_Themes is added to the Solution Explorer and a new folder Theme1 is
added inside it.
2. Theme1 -> Right click -> Add new item -> Stylesheet -> name it as Theme1.css
3. Inside Theme1.css
SHASHI RAJ, BMSCW /Page 23
VB.Net Programming

1. body
2. {
3. background-color:Red;
4. }
4. Again add a new file.

App_Themes -> Right click -> Add ASP.NET folder -> Themes

A new folder Themes2 is created.

5. Themes2 -> Right click -> Add new item -> Stylesheet -> name it as Theme2.css

6. Create an Images folder inside Theme2 and add a picture file pic1.jpg inside this. File
Theme2.css contains –

1. body
2. {
3. background-image:url(Images/pic1.jpg);
4. }
7. Now create a default.aspx as follows. Add a heading and a list box having AutoPostBack to
True.

1. <body>
2. <form id="form1" runat="server">
3. <div>
4. <h3>Select your page Theme : </h3>
5. <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" Height="41px"
onselectedindexchanged= "ListBox1_SelectedIndexChanged" Width="175px">
6. <asp:ListItem>Theme1</asp:ListItem>
7. <asp:ListItem>Theme2</asp:ListItem>
8. </asp:ListBox>
9. <br />
10. </div>
11. </form>
12. </body>
8. Inside the default.aspx.cs file a static variable themeValue is defined which saves the value
of current theme. In the Page_PreInit event of the page, selected theme from the ListBox is
applied to the page and inside the constrctor of the page this PreInit event is provided a
EventHandler.

1. public partial class default : System.Web.UI.Page


2. {
3. static string themeValue;
4.
5. public ThemeTest()
6. {
7. this.PreInit+=new EventHandler(Page_PreInit);
8. }
9.
10. private void Page_PreInit(object sender, EventArgs e)
SHASHI RAJ, BMSCW /Page 24
VB.Net Programming

11. {
12. Page.Theme = themeValue;
13. }
14.
15. protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
16. {
17. themeValue = ListBox1.SelectedItem.Value;
18. Response.Redirect(Request.Url.ToString());
19. }
20. }
9. Now run the page. When we select the Theme from the ListBox, immediately the page is
automatically applied with the theme.

NOTE : THEMES AND SKIN EXAMPLE VIDEO SENT

Creating a layout using master pages in asp.net

A master page provides the layout and functionality to other pages. Creating a master
page in ASP.NET is very easy. Let's start creating master page step by step.

Step 1: Open new project in visual studio

New project->Installed->Web->ASP.NET Web Application (shown in the picture),

After clicking OK button in the Window, select Empty (shown in the picture),

SHASHI RAJ, BMSCW /Page 25


VB.Net Programming

After clicking OK button, project "masterpage" opens but no file is there (shown in the
picture),

Step 2: Add new file in to our project.

Add the master page into our project.

Right click Project->Add->New item (shown in the picture),

After clicking on new item, Window will open, select Web Form->Web Forms Master
Page (shown in the picture),

SHASHI RAJ, BMSCW /Page 26


VB.Net Programming

After clicking the add button, master page 'site1.master' adds to our project.

Click on site1.master into Solution Explorer (shown in the picture),

Step 3: Design the master page, using HTML.

SHASHI RAJ, BMSCW /Page 27


VB.Net Programming

HTML code of my master page is,

1. <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.ma


ster.cs" Inherits="masterpage.Site1" %>
2.
3. <!DOCTYPE html>
4.
5. <html xmlns="http://www.w3.org/1999/xhtml">
6. <head runat="server">
7. <title>c# corner</title>
8. <link href="css/my.css" rel="stylesheet" />
9. <asp:ContentPlaceHolder ID="head" runat="server">
10. </asp:ContentPlaceHolder>
11. </head>
12. <body>
13. <!DOCTYPE html>
14. <html>
15. <head>
16. <title>my layout</title>
17. <link rel="stylesheet" type="text/css" href="my.css">
18. </head>
19. <body>
20. <header id="header">
21. <h1>c# corner</h1>
22. </header>
23. <nav id="nav">
24. <ul>
25. <li><a href="home.aspx">Home</a></li>
26. <li><a href="#">About</a></li>
27. <li><a href="#">Article</a></li>
28. <li><a href="#">Contact</a></li>
29. </ul>
30. </nav>
31. <aside id="side">
32. <h1>news</h1>
33. <a href="#"><p>creating html website</p></a>
34. <a href="#"><p>learn css</p></a>
35. <a href="#">learn c#</a>
36. </aside>
37.
38.
39. <div id="con">
40. <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="s
erver">
41.
42. </asp:ContentPlaceHolder>
43. </div>
44.
45.
46. <footer id="footer">
SHASHI RAJ, BMSCW /Page 28
VB.Net Programming

47. copyright @c# corner


48. </footer>
49. </body>
50. </html>
51. <form id="form1" runat="server">
52.
53. </form>
54. </body>
55. </html>

CSS Code

1. #header{
2. color: #247BA0;
3. text-align: center;
4. font-size: 20px;
5. }
6. #nav{
7. background-color:#FF1654;
8. padding: 5px;
9. }
10. ul{
11.
12. list-style-type: none;
13. }
14. li a {
15. color: #F1FAEE;
16. font-size: 30px;
17. column-width: 5%;
18. }
19. li
20. {
21. display: inline;
22. padding-left: 2px;
23. column-width: 20px;
24. }
25. a{
26. text-decoration: none;
27. margin-left:20px
28. }
29. li a:hover{
30. background-color: #F3FFBD;
31. color: #FF1654;
32. padding:1%;
33. }
34. #side{
35. text-align: center;
36. float: right;
37. width: 15%;
38. padding-bottom: 79%;
39. background-color: #F1FAEE;
SHASHI RAJ, BMSCW /Page 29
VB.Net Programming

40. }
41. #article{
42. background-color: #EEF5DB;
43. padding: 10px;
44. padding-bottom: 75%;
45. }
46. #footer{
47. background-color: #C7EFCF;
48. text-align:center;
49. padding-bottom: 5%;
50. font-size: 20px;
51. }
52. #con{
53. border:double;
54. border-color:burlywood;
55. }

Our master page is designed. Move to the next step.

Step 4: Add web form in to our project.

Right click on the project->Add->New item (shown in the picture),

Select Web form with the master page.

SHASHI RAJ, BMSCW /Page 30


VB.Net Programming

After clicking on that, add the button Window, open the selected masterpage-
>site1.master and click OK.

Now, design our homepage.

Here, we write home page only,

SHASHI RAJ, BMSCW /Page 31


VB.Net Programming

Home.aspx

1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" Auto


EventWireup="true" CodeBehind="home.aspx.cs" Inherits="masterpage.ho
me" %>
2. <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server
">
3. </asp:Content>
4. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1
" runat="server">
5. <h1>Home page</h1>
6. </asp:Content>

Finally, our Master page is created; build and run the project.

The master page looks as shown in the picture:

SHASHI RAJ, BMSCW /Page 32


VB.Net Programming

BINDING TO DATABASE USING CONTROLS


Every ASP.NET web form control inherits the DataBind method from its parent Control class,
which gives it an inherent capability to bind data to at least one of its properties. This is known
as simple data binding or inline data binding.
Simple data binding involves attaching any collection (item collection) which implements the
IEnumerable interface, or the DataSet and DataTable classes to the DataSource property of the
control.
On the other hand, some controls can bind records, lists, or columns of data into their structure
through a DataSource control. These controls derive from the BaseDataBoundControl class. This
is called declarative data binding.
The data source controls help the data-bound controls implement functionalities such as, sorting,
paging, and editing data collections.
The Base DataBound Control is an abstract class, which is inherited by two more abstract
classes:
 DataBound Control
 Hierarchical DataBound Control
The abstract class DataBound Control is again inherited by two more abstract classes:
 List Control
 Composite DataBound Control
The controls capable of simple data binding are derived from the ListControl abstract class and
these controls are:
 Bulleted List
 CheckBox List
 DropDown List
 List Box
 RadioButton List
The controls capable of declarative data binding (a more complex data binding) are derived from
the abstract class Composite DataBound Control. These controls are:
 Details View
 Form View
 Grid View
 Record List

Simple Data Binding

Simple data binding involves the read-only selection lists. These controls can bind to an array list
or fields from a database. Selection lists takes two values from the database or the data source;
one value is displayed by the list and the other is considered as the value corresponding to the
display.
Create a web site with a bulleted list and a SqlDataSource control on it. Configure the data
source control to retrieve two values from your database
Choosing a data source for the bulleted list control involves:
 Selecting the data source control
 Selecting a field to display, which is called the data field

SHASHI RAJ, BMSCW /Page 33


VB.Net Programming

 Selecting a field for the value

When the application is executed, check that the entire title column is bound to the bulleted list
and displayed.

Declarative Data Binding

Data bound controls capable of displaying and manipulating data in a tabular manner are the
DetailsView, FormView, and RecordList control.
However, the data binding involves the following objects:
 A dataset that stores the data retrieved from the database.
 The data provider, which retrieves data from the database by using a command over a
connection.
 The data adapter that issues the select statement stored in the command object; it is also
capable of update the data in a database by issuing Insert, Delete, and Update statements.
Relation between the data binding objects:

SHASHI RAJ, BMSCW /Page 34


VB.Net Programming

DATA MANAGEMENT WITH ADO.NET

Introduction

ADO.NET is the framework that is integrated within the Microsoft .NET framework that allows
programmers the ability to write software applications that interact with data storage models. It is
a component based platform for developing distributed, heterogeneous, interoperable
applications aimed at manipulating any type of data over any network under any operating
system and any programming language.

ADO.NET Concept
When using ADO.NET there are two ways it interacts with data. The data is first retrieved from
a Data Provider. The Data Provider is the component that connects with a Database Management
System to retrieve data. This data is then transformed into a data set. The data set is a
disconnected memory resident representation of the data. In other words, it contains the tables,
columns, rows, relationships, and constraints in the internal memory and is working with that
data on the machine itself and not in a live environment using the DBMS.

Data Provider Objects

In order to use ADO.NET correctly, it must support a specific set of objects to support the ability
to manipulate data. These objects include:

 Connection - Defines the data source used, server name, database, ect
 Command - SQL code to be executed within a database connection. Used to interact with
data between client and server.
 DataReader - Read Only instance to retrieve data sequencally
 DataAdapter - Used to manage a DataSet Object. Allows modifications to data
 DataSet - In-Memory representation of the data
 DataTable - Representation of the data in a tabular format. Allows for the enforcement of
entity integrity.
Support with Visual Studio

Microsoft Visual Studio has the ability to utilize ADO.NET because it is integrated within the
IDE of Visual Studio

Supported Database Applications

Microsoft SQL Server:


The SqlConnection Object is Handling the part of physical communication between the
ASP.NET application and the SQL Server Database . An instance of the SqlConnection class in
ASP.NET is supported the Data Provider for SQL Server Database.

Dim connectionString As String


connectionString = ConfigurationManager.ConnectionStrings("SQLDbConnection").ToString

When the connection is established , SQL Commands will execute with the help of the
Command Object and retrieve or manipulate the data in the database. Once the Database
activities is over , Connection should be closed and release the Data Source resources .

SHASHI RAJ, BMSCW /Page 35


VB.Net Programming

The Close() method in SqlConnection Class is used to close the Database Connection. The Close
method rolls back any pending transactions and releases the Connection from the SQL Server
Database.

OLEDB Connection

The ASP.NET OleDbConnection instance takes Connection String as argument and pass the
value to the Constructor statement. An instance of the ASP.NET OleDbConnection class is
supported the OLEDB Data Provider .

Dim connectionString As String


Dim connection As OleDbConnection
connectionString = ConfigurationManager.ConnectionStrings("OLEDbConnection").ToString
connection = New OleDbConnection(connectionString)

When the connection is established betweenASP.NET application and the specified Data Source,
SQL Commands will execute with the help of the Command Object and retrieve or manipulate
data in the database. Once the Database activities is over Connection should be closed and
release from the data source resources .

The Close() method in the OleDbConnection class is used to close the Database Connection. The
Close method Rolls Back any pending transactions and releases the Connection from the
Database connected by the OLEDB Data Provider.

ODBC Connection

An instance of the OdbcConnection Class in ASP.NET is supported the ODBC Data Provider.
The OdbcConnection instance takes Connection String as argument and passes the value to the
Constructor statement. When the connection is established between ASP.NET application and
the Data Source the SQL Commands will execute with the help of the Command Object and
retrieve or manipulate data in the database.

Dim connectionString As String


Dim connection As OdbcConnection
connectionString = ConfigurationManager.ConnectionStrings("ODBCConnection").ToString
connection = New OdbcConnection(connectionString)

Once the Database activity is over you should be closed the Connection and release the Data
Source resources . The Close() method in OdbcConnection Class is used to close the Database
Connection. The Close method rolls back any pending transactions and releases the Connection
from the Database connected by the ODBC Data Provider .

Creating A Site Navigation Hierarchy


We can manage our site by using the ASP.NET site navigation, its features include;

 Sitemaps – These ‘maps’ are used to describe how your site looks like or in other words, the
structure of your site. As your site grows, you can modify the sitemaps and add or remove pages.
This is helpful since you won’t need to modify hyperlinks for all your WebPages.

SHASHI RAJ, BMSCW /Page 36


VB.Net Programming

 ASP.NET Controls – The controls come in handy whenever you want to display navigation
menus for your site.

 Site Navigation
Using site navigation, you describe the structure of your site as a hierarchy. You start by defining
the hierarchy of your website in an XML file. You can choose to use
the SiteMapPath, TreeView or Dynamic Menu control to display a navigation path (also called a
breadcrumb or eyebrow). The breadcrumb shows the current page and also displays links as a
path that leads back to the homepage.

Rules For Creating A Sitemap File

The XML file should have a <sitemap> tag surrounding the content.

The <sitemap> tag should only have one child node (<siteMapNode>) in the homepage
section.Each node (<siteMapNode>) can have several child nodes or web pages.Each node
should have attributes defining the web page title and the URL.

For example, a SiteMapPath may look something like the following;

Home > Services > Training

As for the TreeView control, it would display a tree-like structure which shows links to different
pages on your site. It uses nodes which can be expanded or collapsed when clicked. An example
of a TreeView structure is;

Home
– Services
+ Training

An example of its code is;

<asp:SiteMapDataSource id="nav1" runat="server" />

<form runat="server">

<asp:TreeView runat="server" DataSourceId="nav1" />

</form>
The <asp:SiteMapDataSource> connects to the Web.sitemap file.

Finally, the Dynamic Menu control shows an expandable menu that users can use to get to
different areas in your site. Just, like the TreeView control it uses nodes, but in this case, when
SHASHI RAJ, BMSCW /Page 37
VB.Net Programming

the cursor hovers over the menu item, the nodes are expanded. An example of a dynamic menu
code is;

<asp:SiteMapDataSource id="nav1" runat="server" />

<form runat="server">

<asp:Menu runat="server" DataSourceId="nav1" />

</form>

Navigation Controls in ASP.NET


There are three navigation control in ASP.NET:

 SiteMapPath
 Menu Control
 TreeView

1. SiteMapPath Control
Site maps are XML files which are mainly used to describe the logical structure of the web
application. It defines the layout of all pages in web application and how they relate to each
other. Whenever you want you can add or remove pages to your site map there by managing
navigation of website efficiently. Site map files are defined with .sitemap extension. <sitemap>
element is the root node of the sitemap file.

It has three attributes:

 Title: It provides textual description of the link.


 URL: It provides the location of the valid physical file.
 Description: It is used for tooltip of the link.

SiteMapPath control displays the navigation path of the current page. The path acts as click able
links to previous page. The sitemap path control uses the web. This control creates the navigation
mechanism which is linear path defining where the user is currently located in navigation
arrangement. It helps end user to know his location in relation to the rest of the site.

Properties of SiteMapPath Control:

 PathSeparator: This property is to get or set the out separator text.


 NodeStyle: This property is used to set the style of all nodes that will be displayed.
 RootNodeStyle: This property is used to set the style on the absolute root node.
 PathDirection: This property is used to set the direction of the links generated in the
output.
 CurrentNodeStyle: This property is used to set the style on node that represent the
current page.
 ShowToolTips: This property is used to set the tooltip for the control. Default value is
true.
 PathSeparatorStyle: This property ja used to set the style of path separator.

SHASHI RAJ, BMSCW /Page 38


VB.Net Programming

2. Menu Control
Menu is an another navigation control in ASP.NET which is used to display menu in web page.
This control is used in combination with SiteMapDataSource control for navigating the web Site.
It displays two types of menu static menu and dynamic menu. Static menu is always displayed in
menu Control, by default only menu items at the root levels are displayed. Dynamic menu is
displayed only when the use moves the mouse pointer over the parent menu that contains a
dynamic sub menu.

Properties of Menu Control:

 DataSourceID: This property is used to specify the data source to be used using sitemap
file as data source.
 CssClass: This property is used to specify the CSS class attribute for the control.
 ImgeUrl: This property is used to specify the image that appear next to the menu item.
 Orientation: This property is used to specify the alignment of menu control. It can be
horizontal or vertical.
 Tooltip: This property is used to specify the tooltip of the menu item when you mouse
over.
 Text: This property is used to specify the text to display in the menu.
 NavigateUrl: This property is used to specify the target location to send the user when
menu item is clicked.
 Target: This property is used to specify the target page location. It can be in new
window or same window.
 Value: This property is used to specify the unique id to use in server side events.

3. TreeView Control
TreeView is an another navigation control used in ASP.NET to display the data in hierarchical
list manner. When TreeView is displayed for the first time, it displays all of its nodes. User can
control it by setting the property called ExpandDepth.

Properties of TreeView Control:

 DataSourceID: This property is used to specify the data source to be used using sitemap
file s data source.
 ShowLines: This property is used to specify the lines to connect the individual item in
the tree.
 CssClass: This property is used to specify the CSS class attribute for the control.
 ExpandDepth: This property is used to specify the level at which items in the tree are
expanded.

Membership and role management


Introduction

ASP.NET provides all the features we need to use a database to store all kinds of security, user,
and role membership details. It also provides a series of server controls that help we build the
pages that users need and that administrators require creating accounts, change passwords, and
maintain the login information and role membership for each user. The two features of ASP.NET
that support this are:
 The membership provider and the associated database tables and procedures

SHASHI RAJ, BMSCW /Page 39


VB.Net Programming

 The role manager and its associated database tables and procedures
Membership Provider Configuration

The ASP.NET membership provider manages the tables in the ASP.NET application database
that store details of the users we define for Web site. The <membership> section of web.config
defines the configuration of the membership provider, including the connection to the database
using <membership> element (located within the <system.web> section) and the content.

The <membership> element consists of a series of one or more <add> elements within the
<providers> section, each of which defines the parameters for a provider that will be available
for the membership system to use. By default, it includes just the first one, named AspNet-
SqlMembershipProvider. We have added two more to the list to demonstrate how we can choose
a different configuration for your providers, if required.

The connectionStringName attribute refers to a value in the <connectionStrings> section of this


web.config file, or a value defined in a web.config file nearer the root folder of this application.
The remaining attributes set specific properties of the provider that control how ASP.NET pages
and controls can interact with it.

<system.web>
...
<membership>
<providers>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, ..."
connectionStringName="LocalSqlServer"
applicationName="/"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression="" />
<!-- following added to use SQL Server 2005 database ->
<add name="Sql2005MembershipProvider"
type="System.Web.Security.SqlMembershipProvider, ..."
connectionStringName="SqlServer2005"
... />
<!-- following uses remote SQL Server attached database ->
<add name="Sql2005RemoteMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, ..."
connectionStringName="Sql2005Remote"
... />
</providers>
</membership>
...
</system.web>

SHASHI RAJ, BMSCW /Page 40


VB.Net Programming

Role Manager Configuration

Having looked at the configuration of the built-in membership provider in ASP.NET, we will not
be surprised to discover that the built-in role provider follows much the same pattern.

The <roleManager> section of web.config defines a list of providers that are available. It
contains, by default, two providers:
1. The SqlRoleProvider uses the same database as the membership provider to hold details of
the roles and role membership, and we can configure the roles and members using the
ASP.NET Web Site Administration Tool.

2. The WindowsTokenRoleProvider is a read-only provider, and exposes information about


roles for a specific Windows user account. It takes this information from the account groups
held in Active Directory or on your server or local machine, depending on the configuration.
We cannot create, add, or delete roles with this provider.

<system.web>
...
<roleManager>
<providers>

<add name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider ..."
connectionStringName="LocalSqlServer"
applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider, ..."
applicationName="/" />
<!-- following added to use SQL Server 2005 database ->
<add name="Sql2005RoleProvider"
type="System.Web.Security.SqlRoleProvider, ..."
connectionStringName="SqlServer2005"
applicationName="/" />
<!-- following uses remote SQL Server attached database ->t;
<add name="Sql2005RemoteRoleProvider"
type="System.Web.Security.SqlRoleProvider, ..."
connectionStringName="Sql2005Remote"
applicationName="/" />
</providers>
</roleManager>
...
</system.web>

SHASHI RAJ, BMSCW /Page 41


VB.Net Programming

Login Control
The ASP.NET login controls provide a robust login solution for ASP.NET Web applications
without requiring programming. By default, login controls integrate with ASP.NET membership
and forms authentication to help automate user authentication for a Web site. It provides you
with a ready-to-use user interface that queries the user name and password from the user and
offers a Log In button for login. It validate user credentials against the membership API and
encapsulating the basic froms authentication functionality like redirecting back to the original
requested page in a restricted area of you application after the successful login.

The Login control displays a user interface for user authentication. The Login control contains
text boxes for the user name and password and a check box that allows users to indicate whether
they want the server to store their identity using ASP.NET membership and automatically be
authenticated the next time they visit the site.

The Login control has properties for customized display, for customized messages, and for links
to other pages where users can change their password or recover a forgotten password. The
Login control can be used as a standalone control on a main or home page, or you can use it on a
dedicated login page. If you use the Login control with ASP.NET membership, you do not need
to write code to perform authentication. However, if you want to create your own authentication
logic, you can handle the Login control's Authenticate event and add custom authentication code.

Whenever user hits the Log In button, the control automatically validates the user name and
password using the membership API function Membership.ValidateUse() and then calls
FormAuthentication.redirectFromLoginPage() if the validation was successful. All options on
the UI of the LoginControl affect the input delivered by the control to these methods. For
Example, if you click the "Remember me next time" check box, it passes the value true to the
createPresistentCookie parameter of the RedirectFromLoginPage() method. Therefore, the
FormAuthenticateModule creates a persistent cookie.

There are three Login Tasks by default.

 Auto Format - you can select default schemes.


 Convert To Template - You can edit content of Login Control.
 Administer Website - You can configure Web Site Administration Tools, Like Security,
Application, and Provider.

SHASHI RAJ, BMSCW /Page 42


VB.Net Programming

Securing applications
Implementing security in a site has the following aspects:
 Authentication : It is the process of ensuring the user's identity and authenticity. ASP.NET
allows four types of authentications:
o Windows Authentication
o Forms Authentication
o Passport Authentication
o Custom Authentication
 Authorization : It is the process of defining and allotting specific roles to specific users.
 Confidentiality : It involves encrypting the channel between the client browser and the web
server.
 Integrity : It involves maintaining the integrity of data. For example, implementing digital
signature.

Implementing Forms-Based Security

To set up forms-based authentication, you need the following:


 A database of users to support the authentication process
 A website that uses the database
 User accounts
 Roles
 Restriction of users and group activities
 A default page, to display the login status of the users and other information.
 A login page, to allow users to log in, retrieve password, or change password

Caching for performance

Caching is a technique of storing frequently used data/information in memory, so that, when the
same data/information is needed next time, it could be directly retrieved from the memory
instead of being generated by the application.
Caching is extremely important for performance boosting in ASP.NET, as the pages and controls
are dynamically generated here. It is especially important for data related transactions, as these
are expensive in terms of response time.
Caching places frequently used data in quickly accessed media such as the random access
memory of the computer. The ASP.NET runtime includes a key-value map of CLR objects
called cache. This resides with the application and is available via the HttpContext and
System.Web.UI.Page.
In some respect, caching is similar to storing the state objects. However, the storing information
in state objects is deterministic, i.e., you can count on the data being stored there, and caching of
data is nondeterministic.
The data will not be available in the following cases:
 If its lifetime expires,
 If the application releases its memory,
 If caching does not take place for some reason.
You can access items in the cache using an indexer and may control the lifetime of objects in the
cache and set up links between the cached objects and their physical sources.

SHASHI RAJ, BMSCW /Page 43


VB.Net Programming

Caching in ASP.Net

ASP.NET provides the following different types of caching:


 Output Caching : Output cache stores a copy of the finally rendered HTML pages or part
of pages sent to the client. When the next client requests for this page, instead of
regenerating the page, a cached copy of the page is sent, thus saving time.
 Data Caching : Data caching means caching data from a data source. As long as the cache
is not expired, a request for the data will be fulfilled from the cache. When the cache is
expired, fresh data is obtained by the data source and the cache is refilled.
 Object Caching : Object caching is caching the objects on a page, such as data-bound
controls. The cached data is stored in server memory.
 Class Caching : Web pages or web services are compiled into a page class in the assembly,
when run for the first time. Then the assembly is cached in the server. Next time when a
request is made for the page or service, the cached assembly is referred to. When the source
code is changed, the CLR recompiles the assembly.
 Configuration Caching : Application wide configuration information is stored in a
configuration file. Configuration caching stores the configuration information in the server
memory.
WORKING WITH XML
The Extensible Markup Language (XML) is a markup language much like HTML or SGML.
This is recommended by the World Wide Web Consortium and available as an open standard.
The System.Xml namespace in the .Net Framework contains classes for processing XML
documents. Following are some of the commonly used classes in the System.Xml namespace.

Sr.No. Class & Description


1
XmlAttribute
Represents an attribute. Valid and default values for the attribute are
defined in a document type definition (DTD) or schema.

2
XmlCDataSection
Represents a CDATA section.

3
XmlCharacterData
Provides text manipulation methods that are used by several classes.

4
XmlComment
Represents the content of an XML comment.

5
XmlConvert
Encodes and decodes XML names and provides methods for converting
between common language runtime types and XML Schema definition
language (XSD) types. When converting data types, the values returned are

SHASHI RAJ, BMSCW /Page 44


VB.Net Programming

locale independent.

6
XmlDeclaration
Represents the XML declaration node <?xml version='1.0'...?>.

7
XmlDictionary
Implements a dictionary used to optimize Windows Communication
Foundation (WCF)'s XML reader/writer implementations.

8
XmlDictionaryReader
An abstract class that the Windows Communication Foundation (WCF)
derives from XmlReader to do serialization and deserialization.

9
XmlDictionaryWriter
Represents an abstract class that Windows Communication Foundation
(WCF) derives from XmlWriter to do serialization and deserialization.

10
XmlDocument
Represents an XML document.

XML Parser APIs

The two most basic and broadly used APIs to XML data are the SAX and DOM interfaces.
 Simple API for XML (SAX) − Here, you register callbacks for events of interest and then
let the parser proceed through the document. This is useful when your documents are large
or you have memory limitations, it parses the file as it reads it from disk, and the entire file
is never stored in memory.
 Document Object Model (DOM) API − This is World Wide Web Consortium
recommendation wherein the entire file is read into memory and stored in a hierarchical
(tree-based) form to represent all the features of an XML document.
SAX obviously can't process information as fast as DOM can when working with large files. On
the other hand, using DOM exclusively can really kill your resources, especially if used on a lot
of small files.
SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs
literally complement each other there is no reason why you can't use them both for large projects.
For all our XML code examples, let's use a simple XML file movies.xml as an input −
<?xml version = "1.0"?>

<collection shelf = "New Arrivals">


<movie title = "Enemy Behind">
<type>War, Thriller</type>
<format>DVD</format>

SHASHI RAJ, BMSCW /Page 45


VB.Net Programming

<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about a US-Japan war</description>
</movie>

<movie title = "Transformers">


<type>Anime, Science Fiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>8</stars>
<description>A schientific fiction</description>
</movie>

<movie title = "Trigun">


<type>Anime, Action</type>
<format>DVD</format>
<episodes>4</episodes>
<rating>PG</rating>
<stars>10</stars>
<description>Vash the Stampede!</description>
</movie>

<movie title = "Ishtar">


<type>Comedy</type>
<format>VHS</format>
<rating>PG</rating>
<stars>2</stars>
<description>Viewable boredom</description>
</movie>
</collection>

Parsing XML with SAX API

In SAX model, you use the XmlReader and XmlWriter classes to work with the XML data.
The XmlReader class is used to read XML data in a fast, forward-only and non-cached manner.
It reads an XML document or a stream.

Example 1

This example demonstrates reading XML data from the file movies.xml.
Take the following steps −
 Add the movies.xml file in the bin\Debug folder of your application.
 Import the System.Xml namespace in Form1.vb file.
 Add a label in the form and change its text to 'Movies Galore'.
 Add three list boxes and three buttons to show the title, type and description of a movie
from the xml file.
 Add the following code using the code editor window.
Imports System.Xml
SHASHI RAJ, BMSCW /Page 46
VB.Net Programming

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


ListBox1().Items.Clear()
Dim xr As XmlReader = XmlReader.Create("movies.xml")
Do While xr.Read()
If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "movie" Then
ListBox1.Items.Add(xr.GetAttribute(0))
End If
Loop
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click


ListBox2().Items.Clear()
Dim xr As XmlReader = XmlReader.Create("movies.xml")
Do While xr.Read()
If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "type" Then
ListBox2.Items.Add(xr.ReadElementString)
Else
xr.Read()
End If
Loop
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click


ListBox3().Items.Clear()
Dim xr As XmlReader = XmlReader.Create("movies.xml")
Do While xr.Read()
If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "description" Then
ListBox3.Items.Add(xr.ReadElementString)
Else
xr.Read()
End If
Loop
End Sub
End Class
Execute and run the above code using Start button available at the Microsoft Visual Studio tool
bar. Clicking on the buttons would display, title, type and description of the movies from the file.

SHASHI RAJ, BMSCW /Page 47


VB.Net Programming

The XmlWriter class is used to write XML data into a stream, a file or a TextWriter object. It
also works in a forward-only, non-cached manner.

Using crystal reports in web forms

Crystal Reports in ASP.NET


Crystal Reports is the standard reporting tool for Visual Studio .NET used to display data of
presentation quality. Crystal Reports display multiple-level totals, charts to analyze data, and
much more in Crystal Reports. Creating a Crystal Report requires minimal coding since it is
created in Designer interface.

To create crystal reports example in asp.net.

To implement crystal reports first design the table in database and give name UserInfomation

ColumnName DataType
UserId Int(set identity property=true)
UserName varchar(50)
FirstName Varchar(50)
LastName varchar(50)
Location varchar(50)

After completion of table creation enter some dummy data because we need to use that data to
populate reports.

 Now Open visual studio and create new website after that right click on your website and
select Add new item in that select Crystal Report and click Add

SHASHI RAJ, BMSCW /Page 48


VB.Net Programming

 After that add crystal report then it will prompt Crystal Report Gallery window in that
select blank solution and click OK

 A blank report will create in our application now click on CrystalReports menu under that
select Database under that select Database Expert

SHASHI RAJ, BMSCW /Page 49


VB.Net Programming

 After click on Database Expert now Database Expert wizard will open in that
select Create New Section >> select OLE DB (ADO) >> in that click on + sign of OLE
DB (ADO)

 Now select Microsoft OLE DB Provider for SQL Server and click Next (Here we can
select SQL Native client option also but sometimes during deployment if servers not
contains this native client it will throw error).

SHASHI RAJ, BMSCW /Page 50


VB.Net Programming

 Now enter SQL Server name, username, password and required database and click Next

 After enter credentials for your required database click Next then click Finish (Here for
my database I didn’t set any credentials for that reason I didn’t enter userid and password
details don’t get confused).

 After click Finish now our database loaded in OLEDB (ADO) section >> select your
database >> select dbo >> select required tables

SHASHI RAJ, BMSCW /Page 51


VB.Net Programming

 Now open tables in that select required table and move to selected tables section and
click OK

 After that Database Fields in Field Explorer populated with our required data table now
drag and drop the required fields from data table to reports Details section

SHASHI RAJ, BMSCW /Page 52


VB.Net Programming

 Now open your Default.aspx page drag and drop CrystalReportViewer control from
Reporting tab.

 Now select CrystalReportViewer and click on smart tag in right hand side and Choose
new Report Source

 Whenever we click on New report source one window will open in that select crystal
report for Report Source from the available reports in dropdownlist and click OK.

SHASHI RAJ, BMSCW /Page 53


VB.Net Programming

After assign available report to CrystalReportViewer control check your code that would be like
this

<%@ Register Assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral,


PublicKeyToken=692fbea5521e1304" Namespace="CrystalDecisions.Web" TagPrefix="CR" %
>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Crystal Report Sample</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="True" R
eportSourceID="CrystalReportSource1" />
<CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
<Report FileName="CrystalReport.rpt">
</Report>
</CR:CrystalReportSource>
</div>
</form>
</body>
</html>

VB.NET Code

Imports CrystalDecisions.CrystalReports.Engine

Partial Class Default2


Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object,
e As EventArgs) Handles Me.Load
Dim reportdocument As New ReportDocument()

SHASHI RAJ, BMSCW /Page 54


VB.Net Programming

reportdocument.Load(Server.MapPath("CrystalReport.rpt"))
reportdocument.SetDatabaseLogon("", "", "SureshDasari", "MySampleDB")
CrystalReportViewer1.ReportSource = reportdocument
End Sub
End Class
Now run your application and check your output that would be like this

SHASHI RAJ, BMSCW /Page 55


VB.Net Programming

Unit 5: Databases

Introduction
ASP.NET allows the following sources of data to be accessed and used:
 Databases (e.g., Access, SQL Server, Oracle, MySQL)
 XML documents
 Business Objects
 Flat files
ASP.NET hides the complex processes of data access and provides much higher level of classes
and objects through which data is accessed easily. These classes hide all complex coding for
connection, data retrieving, data querying, and data manipulation.
ADO.NET is the technology that provides the bridge between various ASP.NET control objects
and the backend data source.

Retrieve and display data

It takes two types of data controls to retrieve and display data in ASP.NET:
 A data source control - It manages the connection to the data, selection of data, and other
jobs such as paging and caching of data etc.
 A data view control - It binds and displays the data and allows data manipulation.

Using SQL to work with database

SQL manages a large amount of data, especially if there is a lot of data that is being written
simultaneously and there are too many data transactions.

There are different versions and frameworks for SQL, the most commonly used is MySQL.
MySQL is an open-source solution that helps facilitate SQL’s role in managing back-end data for
web applications. Companies such as Facebook, Instagram, WhatsApp, etc. all use SQL for
back-end data storage and data processing solutions. When an SQL query is written & run (or
parsed), it is processed by a query optimiser. The query reaches SQL server, where it compiles in
three phases; Parsing, Binding and Optimisation.

 Parsing – A process to check the syntax


 Binding – A process to check the query semantics
 Optimisation – A process to generate the query execution plan

SQL Uses

This programming language has various uses for data analysts & data science professionals. It is
particularly helpful because it can:

 Execute queries against a database


 Retrieve data from a database
 Insert records into a database
 Update records in a database

SHASHI RAJ, BMSCW /Page 56


VB.Net Programming

 Delete records from a database


 Create new databases, or new tables in a database
 Create stored procedures & views in a database
 Set permissions on tables, procedures, and views

SQL - CREATE Table


Creating a basic table involves naming the table and defining its columns and each column's data
type.
The SQL CREATE TABLE statement is used to create a new table.

Syntax

The basic syntax of the CREATE TABLE statement is as follows −


CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
CREATE TABLE is the keyword telling the database system what you want to do. In this case,
you want to create a new table. The unique name or identifier for the table follows the CREATE
TABLE statement.
Then in brackets comes the list defining each column in the table and what sort of data type it is.
The syntax becomes clearer with the following example.
Example
The following code block is an example, which creates a CUSTOMERS table with an ID as a
primary key and NOT NULL are the constraints showing that these fields cannot be NULL while
creating records in this table −
SQL> CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

You can verify if your table has been created successfully by looking at the message displayed
by the SQL server, otherwise you can use the DESC command as follows –

SHASHI RAJ, BMSCW /Page 57


VB.Net Programming

Now, you have CUSTOMERS table available in your database which you can use to store the
required information related to customers.

SQL - DROP or DELETE Table


The SQL DROP TABLE statement is used to remove a table definition and all the data, indexes,
triggers, constraints and permission specifications for that table.
NOTE − You should be very careful while using this command because once a table is deleted
then all the information available in that table will also be lost forever.

Syntax

The basic syntax of this DROP TABLE statement is as follows −


DROP TABLE table_name;

Example

Let us first verify the CUSTOMERS table and then we will delete it from the database as shown
below –

This means that the CUSTOMERS table is available in the database, so let us now drop it as
shown below.
SQL> DROP TABLE CUSTOMERS;
Query OK, 0 rows affected (0.01 sec)
Now, if you would try the DESC command, then you will get the following error −

SHASHI RAJ, BMSCW /Page 58


VB.Net Programming

SQL> DESC CUSTOMERS;


ERROR 1146 (42S02): Table 'TEST.CUSTOMERS' doesn't exist

SQL - INSERT Query


The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Syntax
There are two basic syntaxes of the INSERT INTO statement which are shown below.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
Here, column1, column2, column3,...columnN are the names of the columns in the table into
which you want to insert the data.
You may not need to specify the column(s) name in the SQL query if you are adding values for
all the columns of the table. But make sure the order of the values is in the same order as the
columns in the table.
The SQL INSERT INTO syntax will be as follows −
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Example
The following statements would create six records in the CUSTOMERS table.
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (6, 'Komal', 22, 'MP', 4500.00 );
You can create a record in the CUSTOMERS table by using the second syntax as shown below.
INSERT INTO CUSTOMERS
VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
All the above statements would produce the following records in the CUSTOMERS table as
shown below.

SHASHI RAJ, BMSCW /Page 59


VB.Net Programming

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

SQL - SELECT Query


The SQL SELECT statement is used to fetch the data from a database table which returns this
data in the form of a result table. These result tables are called result-sets.

Syntax

The basic syntax of the SELECT statement is as follows −


SELECT column1, column2, columnN FROM table_name;
Here, column1, column2... are the fields of a table whose values you want to fetch. If you want
to fetch all the fields available in the field, then you can use the following syntax.
SELECT * FROM table_name;

Example

Consider the CUSTOMERS table having the following records −

SHASHI RAJ, BMSCW /Page 60


VB.Net Programming

SQL - WHERE Clause


The SQL SELECT statement is used to fetch the data from a database table which returns this
data in the form of a result table. These result tables are called result-sets.

Syntax

The basic syntax of the SELECT statement is as follows −


SELECT column1, column2, columnN FROM table_name;
Here, column1, column2... are the fields of a table whose values you want to fetch. If you want
to fetch all the fields available in the field, then you can use the following syntax.
SELECT * FROM table_name;

Example

Consider the CUSTOMERS table having the following records −

Working with ado.net

ADO.NET makes it possible to establish a connection with a data source, send queries and
update statements to the data source, and process the results.

ADO.NET has several key components:

SHASHI RAJ, BMSCW /Page 61


VB.Net Programming

Application or component: processes and calls ADO.NET functions to submit SQL statements
and retrieve results.

DataSet : is in-memory cache of data which functions like a disconnected XML data cache. The
overall functions of the DataSet closely recall those of an in-memory database. The DataSet is
designed to run in the application space wherever the logic requires local data. This helps
increase scalability of systems by reducing load on the major database backends and enabling
local processing of data across whatever tier the application requires. For flexibility, the DataSet
provides XML and relational interfaces of the data to the developer.

DataReader; which provides a direct, read-only SQL interface to the backend. The DataReader
is a component of the data provider.

ADO.NET Data Provider; connects an ADO.NET application to the backend data store. The
data provider comprises the Connection, Command, DataReader and DataAdapter objects. The
data provider supplies connection information through the Connection object.

The following figure shows a scenario in which the application and the ADO.NET data
provider are both built with managed code. The application can connect to a database using
either a DataSet and a DataAdapter or using a DataReader.

The architecture of ADO.NET:


The ADO.NET Architecture comprises of 6 important components. They are as follows:
1. Connection
2. Command
3. DataReader
4. DataAdapter
5. DataSet

SHASHI RAJ, BMSCW /Page 62


VB.Net Programming

6. DataView
From the above components, two components are compulsory. One is the command object and
the other one is the connection object. Irrespective of the operations like Insert, Update, Delete
and Select, the command and connection object you always need. For better understanding,
please have a look at the following image.

Let us understand each of the components in detail.


Connection:
The first important component is the connection object. The connection object is required to
connect with your backend database which can be SQL Server, Oracle, MySQL, etc. To create a
connection object, you need at least two things. The first one is where is your database located
i.e. the Machine name or IP Address or someplace where your database is located. And the
second thing is the security credentials i.e. whether it is a windows authentication or user name
and password-based authentication. So, the first is to create the connection object and the
connection is required to connect to the backend data source.
Command:
The second important component is the command object. When we talk about databases like
SQL Server, Oracle, MySQL, then understand SQL. The command object is the component
where you go and write your SQL queries. Later you take the command object and execute it
over the connection. Then you can fetch data or send data to the database using the command
object and SQL queries.
Note: From the command object onwards, you can go in two different ways. One is you can go
with the DataSet way and the other is, you can go with the DataReader way. Which way you
need to choose, basically it will depend on the situation.
DataReader:
DataReader is a read-only connected recordset that helps us to read the records only in the
forward mode. Here, you need to understand three things i.e. read-only, connected, and forward
mode.

SHASHI RAJ, BMSCW /Page 63


VB.Net Programming

DataSet:
It is a disconnected recordset that can be browsed in both i.e. forward and backward. It is also
possible to update via dataset. DataSet gets filled by somebody called DataAdapter.
DataAdapter:
The DataAdapter acts as a bridge between the command object and the dataset. What the
DataAdapter does, it takes the data from the command object and fills the data set.
DataView Class
A DataView enables you to create different views of the data stored in a DataTable, a capability
that is often used in data-binding applications. Using a DataView, you can expose the data in a
table with different sort orders, and you can filter the data by row state or based on a filter
expression.

ASP.NET DATA CONTROLS


One of the important goals of the Asp.net language is code minimization. Data controls play an
important role in this purpose. Data controls used to display the records in the form of reports.

Some of the Data controls are:


1. Repeater data control
2. Detailsview data control
3. GridView data control
4. DataList data control
5. FormView data control

1. GridView data control:


This control displays the data in tabular form.
It not only support the editing and deleting of data, it also support sorting and paging of data.
Example:

2. DetailsView data control:


This control displays single record of data at a time. It supports updating, insertion or deletion of
the record.It can be used in conjunction with the GridView control to provide a master-detail
view of your data.
Example:

SHASHI RAJ, BMSCW /Page 64


VB.Net Programming

3. FormView data control:


This control displays a single record of data at a time like DetailsView control and supports the
editing of record. This control requires the use of template to define the rendering of each item.
Developer can completely customize the appearance of the record.
Example:

4. DataListView control:
This control displays data as items in a list. Presentation of the data can be customized via
templates. Inline editing and deleting of data is supported by this control.
Example:

5. Repeater Data control:


This control is used to display the repeated list of the items that are bound to the control. It
provides complete flexibility in regards to the HTML presentation. A Repeater has five templates
to format it:

SHASHI RAJ, BMSCW /Page 65


VB.Net Programming

 HeaderTemplate
 AlternatingItemTemplate
 Itemtemplate
 SeoperatorTemplate
 FooterTemplate
Example

ASP.NET DATA SOURCE CONTROLS


The data source control provides data to the controls without complex coding. The actions like
insert, update, delete and sort is possible using the data control. There are various data source
controls in ASP.NET.
The model allows user to create user data source control which can interact with various data
sources. The different data sources used in ASP.NET are as mentioned below.

1. LinqDataSource: The Language Integrated Query in an ASP.NET web page is possible


using the markup. The insert, update, select, delete commands are supported. Filtering,
sorting and paging of the data are possible.
2. ObjectDataSource: User can work with the objects using the object data source.
3. SqlDataSource: User can work with Microsoft SQL Server, Oracle, OLEDB and Oracle
databases. The sorting, filtering, paging of the data is possible using the data source.
4. AccessDataSource: Working with Microsoft Access Database is possible using the data
source.
5. XmlDataSource: User can work with the XML file when the hierarchical structure needs
to be used as data source.
6. SiteMapDataSource: Site navigation data.

Data Source views

The Data Source view is the base class for all the source view classes. User can sort, filter,
update and delete the data using the data source view.

Properties of the Data source view control:


1. CanInsert: A value stating the object is related with the current source object supports the
ExecuteInsert operation.
2. CanDelete: A value stating the object related with the current source object supports the
ExecuteDelete operation.
3. CanSort: State the sorted view for the data source.
4. CanUpdate: A value stating that the object related with the current source object supports
ExecuteUpdate operation.
5. Events: The event handler delegates for the data source view are listed.
6. Name: The name of the data source view is displayed.

SHASHI RAJ, BMSCW /Page 66


VB.Net Programming

Some of the methods of the Data source view control are:


1. Delete: The asynchronous delete operation on the data for the view object is performed.
2. Finalize: The object can free the resources and the cleanup operation is performed.
3. CanExecute: It decides whether the command can be executed
4. ExecuteSelect: The data from the data source is retrieved
5. Insert: An asynchronous insert operation is performed on the data represented by the
view object
6. MemberwiseClone: A shallow copy of the current object is created
7. Update: An asynchronous update is performed on the list of data.
8. GetHashCode: The default hash function is provided

ObjectDataSource control

The ObjectDataSource control is used for connecting the data bound controls to the logic. The
control is used in combination with the data bound controls for modifying and displaying the
data on a web page.
User can easily access the data from the business objects using the ObjectDataSource control.
Some of the properties of the ObjectDataSource control are as listed below:
1. SelectMethod: The method or the function used for retrieving the data is assigned or
accessed.
2. TypeName: The name of the class is identified
3. SelectParameters: The parameters collection consisting of the parameters used through
the SelectMethod property.
4. InsertMethod: The method or function is used for inserting the data.
5. UpdateMethod: The method or function is used for updating the data.
6. UpdateParameters: The parameters collection used by the UpdateMethod property
7. DeleteMethod: The method or function is used for deleting the data
8. DeleteParameters: The parameters collection is used by the DeleteMethod property

Consider the following code snippet to demonstrate the use of ObjectDataSource control.
Code:
<asp:objectdatasource id="objectsource1" runat="server" selectmethod="GetResult"
typename="StudentInfo">
<SelectParameters>
<asp:querystringparameter name="StudID" querystringfield="studid" />
</SelectParameters>
</asp:objectdatasource>
In the above snippet, the SelectMethod is used to set the GetResult method. The Typename is
used to define the class name. The <SelectParameters> element passes the studid as a parameter.

SqlDataSource control

The SqlDataSource control is used to access data from the SQL relational database. The control
is used along with the data controls for accessing the data from the relational database. The data
can be modified.

Some of the properties of the SqlDataSource control are as listed below.


1. ConnectionString: The connection string used for connecting the data source is assigned

SHASHI RAJ, BMSCW /Page 67


VB.Net Programming

2. ProviderName: The name for the provider used for connecting the data source object is
assigned
3. SelectCommand: The SQL string used for accessing the information from the data source
is defined
4. InsertCommand: Used for inserting the data in the data source object
5. DeleteCommand: The string used for deleting the data from the data source
6. UpdateCommand: Used for updating the data in the data source
7. FilterParameters: Used for filtering the string and parameters
The following code shows the SqlDataSource control is used for manipulating the data source
control.
Code
<asp:SqlDataSource ID="SqlSource1" runat="server"
ConnectionString="<%$ConnectionStrings:LibraryConnectionString%>"
SelectCommand="SELECT * FROM Library"
UpdateCommand="UPDATE Library SET BOOKNAME = @bname"
DeleteCommand = “DELETE FROM Library WHERE BOOKID = @bid"
</asp:SqlDataSource>

AccessDataSource control

The AccessDataSource control is used along with the Microsoft Access databases. The SQL
queries are used for accessing the data. User can set the location of the Access file (.mdb) in the
DataFile property. The database to be accessed must be placed in the App_Data directory. The
relative path is used for referencing the data.

Some of the properties of the AccessDataSource control are as mentioned.


1. BindingContainer: The control consisting the data binding is defined
2. CacheDuration: The time in seconds for the data source control is defined
3. ConnectionString: The connection string used for connecting the Access database
4. DeleteCommand: The string uses the delete data from the corresponding database.
5. Events: The list of event handlers as the delegate for the control.
6. ID: The identifier assigned to the control
7. InsertCommand: The string used for adding data to the data source control
8. ProviderName: The .NET data provider used for connecting the Access database
9. UpdateCommand: The string used for updating the data in the database.
10. ViewState: The state information used for saving the view state of a server through
different requests for the similar page.

Methods of AccessDataSource control

1. ApplyStyleSheetSkin: The style properties are defined in the style sheet for the control is
defined.
2. ClearChildControlState: The control state information is removed for the server controls
child control
3. DataBind(): The data source is bounded to the server control.
4. Delete: The delete operation is performed using the DeleteCommand.
5. GetType: The type of the current instance is retrieved
6. MapPathSecure: The physical path to be mapped is retrieved
7. OpenFile: The Stream is used for reading the file
SHASHI RAJ, BMSCW /Page 68
VB.Net Programming

Consider the following example to demonstrate the AccessDataSource control.


Code :
<asp:AccessDataSource ID="Access1" runat="server" DataFile="~/App_Data/Northwind.mdb"
SelectCommand="SELECT StudID, StudName FROM Students" >
</asp:AccessDataSource>

XmlDataSource control

The XMLDataSource control states the XML data to the data bound controls. It is used to show
data in tabular or hierarchical type. The data is loaded from the XML file specified using the
DataFile property.

Some of the properties of the XmlDataSource control are as listed below.


1. DataFile: The filename of the XML file used for bounding the data source control is
defined.
2. Controls: The ControlCollection object represents the child controls for the specified
server control
3. Data: The block of xml data used for bounding the XmlDataSource control in string
format.
4. Events: The list of event handler delegates for the control is defined
5. Parent: The reference to the server controls parent control in the page control structure is
defined
6. TransformFile: The file name of Extensible Stylesheet Language files defining the XSLT
transformation.
7. XPath: An XPath expression to be applied to the XML data present in the Data property.

Consider the following example to demonstrate the XMLDataSource control in ASP.NET.


Code:
<asp:XmlDataSource ID="xml1" runat="server" DataFile="student.xml" />

In the above code, the datafile defines the XML file used in the control.

SiteMapDataSource control
The SiteMapDataSource control is used for navigating the data to the controls. The site map
contains the navigation data. It contains data about title, description, URL, location and
navigation hierarchy. The menu and tree view controls are used for binding the data.

Properties of the SiteMapDataSource control are as listed below.

1. ShowStartingNode: The value stating whether the starting node is accessed or displayed
2. StartFromCurrentNode: The value states that the site map node tree is accessed from the
current page.
3. SiteMapProvider: The name of the provider is set
4. StartingNodeUrl: A node in the site map node tree is accessed using the node to show the
current page.

SHASHI RAJ, BMSCW /Page 69


VB.Net Programming

5. StartingNodeOffset: The positive or negative integer offset from the starting node stating
the root hierarchy is defined.
The SiteMapDataSource control in an ASP.NET application is as mentioned below.
Code:

<asp:SiteMapDataSource ID="sitemap1" runat="server" SiteMapProvider="EmployeeSiteMap"


/>
Deploying the website
There are two categories of ASP.NET deployment:
 Local deployment : In this case, the entire application is contained within a virtual
directory and all the contents and assemblies are contained within it and available to the
application.
 Global deployment : In this case, assemblies are available to every application running on
the server.
There are different techniques used for deployment, however, we will discuss the following most
common and easiest ways of deployment:
 XCOPY deployment
 Copying a Website
 Creating a set up project

XCOPY Deployment

XCOPY deployment means making recursive copies of all the files to the target folder on the
target machine. You can use any of the commonly used techniques:
 FTP transfer
 Using Server management tools that provide replication on a remote site
 MSI installer application
XCOPY deployment simply copies the application file to the production server and sets a virtual
directory there. You need to set a virtual directory using the Internet Information Manager
Microsoft Management Console (MMC snap-in).

Copying a Website

The Copy Web Site option is available in Visual Studio. It is available from the Website -> Copy
Web Site menu option. This menu item allows copying the current web site to another local or
remote location. It is a sort of integrated FTP tool.
Using this option, you connect to the target destination, select the desired copy mode:
 Overwrite
 Source to Target Files
 Sync UP Source And Target Projects
Then proceed with copying the files physically. Unlike the XCOPY deployment, this process of
deployment is done from Visual Studio environment. However, there are following problems
with both the above deployment methods:
 You pass on your source code.
 There is no pre-compilation and related error checking for the files.
 The initial page load will be slow.

SHASHI RAJ, BMSCW /Page 70


VB.Net Programming

Creating a Setup Project

In this method, you use Windows Installer and package your web applications so it is ready to
deploy on the production server. Visual Studio allows you to build deployment packages. Let us
test this on one of our existing project, say the data binding project.
Open the project and take the following steps:
Step (1) : Select File -> Add -> New Project with the website root directory highlighted in the
Solution Explorer.
Step (2) : Select Setup and Deployment, under Other Project Types. Select Setup Wizard.

Step (3) : Choosing the default location ensures that the set up project will be located in its own
folder under the root directory of the site. Click on okay to get the first splash screen of the
wizard.

Step (4) : Choose a project type. Select 'Create a setup for a web application'.

Step (5) : Next, the third screen asks to choose project outputs from all the projects in the
solution. Check the check box next to 'Content Files from...

Step (6) : The fourth screen allows including other files like ReadMe. However, in our case there
is no such file. Click on finish.

Step (7) : The final screen displays a summary of settings for the set up project.

Step (8) : The Set up project is added to the Solution Explorer and the main design window
shows a file system editor.

Step (9) : Next step is to build the setup project. Right click on the project name in the Solution
Explorer and select Build.

Step (10) : When build is completed, you get the following message in the Output window:

LINQ

Language-Integrated Query (LINQ) is a powerful set of technologies based on the integration


of query capabilities directly into the C# language. LINQ Queries are the first-class language
construct in C# .NET, just like classes, methods, events. The LINQ provides a consistent
query experience to query objects (LINQ to Objects), relational databases (LINQ to SQL),
and XML (LINQ to XML).

LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve
data from different sources and formats. It is integrated in C# or VB, thereby eliminating the
mismatch between programming languages and databases, as well as providing a single
querying interface for different types of data sources.

For example, SQL is a Structured Query Language used to save and retrieve data from a
database. In the same way, LINQ is a structured query syntax built in C# and VB.NET to
retrieve data from different types of data sources such as collections, ADO.Net DataSet, XML
Docs, web service and MS SQL Server and other databases.
SHASHI RAJ, BMSCW /Page 71
VB.Net Programming

LINQ queries return results as objects. It enables you to uses object -oriented approach on the
result set and not to worry about transforming different formats of results into objects.

The following example demonstrates a simple LINQ query that gets all strings from an array
which contains 'a'.

Example: LINQ Query to Array

// Data source
string[] names = {"Bill", "Steve", "James", "Mohan" };

// LINQ Query
var myLinqQuery = from name in names
where name.Contains('a')
select name;

// Query execution
foreach(var name in myLinqQuery)
Console.Write(name + " ");

In the above example, string array names is a data source. The following is a LINQ query
which is assigned to a variable myLinqQuery.

from name in names


where name.Contains('a')
select name;

The above query uses query syntax of LINQ.

LINQ query can be execute in multiple ways, here we used foreach loop to execute our
query stored in myLinqQuery. The foreach loops executes the query on the data source and
get the result and then iterates over the result set.

SHASHI RAJ, BMSCW /Page 72


VB.Net Programming

Thus, every LINQ query must query to some kind of data sources whether it can be array,
collections, XML or other databases. After writing LINQ query, it must be executed to get the
result.

LINQ - Query Operators


A set of extension methods forming a query pattern is known as LINQ Standard Query
Operators. As building blocks of LINQ query expressions, these operators offer a range of query
capabilities like filtering, sorting, projection, aggregation, etc.
LINQ standard query operators can be categorized into the following ones on the basis of their
functionality.
 Filtering Operators
 Join Operators
 Projection Operations
 Sorting Operators
 Grouping Operators
 Conversions
 Concatenation
 Aggregation
 Quantifier Operations
 Partition Operations
 Generation Operations
 Set Operations
 Equality
 Element Operators

Filtering Operators

Filtering is an operation to restrict the result set such that it has only selected elements satisfying
a particular condition.
Description VB Query
Operator Expression
Syntax

where Filter values based on a predicate Where


function
OfType Filter values based on their ability to Not
be as a specified type Applicable

Join Operators

Joining refers to an operation in which data sources with difficult to follow relationships with
each other in a direct way are targeted.

SHASHI RAJ, BMSCW /Page 73


VB.Net Programming

Operator Description VB Query


Expression
Syntax
Join The operator join two From x In
sequences on basis of …, y In …
matching keys Where x.a
= y.a
GroupJoin Join two sequences and group Group Join
the matching elements … In …
On …

Projection Operations

Projection is an operation in which an object is transformed into an altogether new form with
only specific properties.

Operator Description VB Query


Expression
Syntax

Select The operator projects values on basis of a Select


transform function
SelectMany The operator project the sequences of values Use
which are based on a transform function as multiple
well as flattens them into a single sequence From
clauses

Sorting Operators

A sorting operation allows ordering the elements of a sequence on basis of a single or more
attributes.

Operator Description VB Query


Expression
Syntax

OrderBy The operator sort values in Order By


an ascending order
OrderByDescending The operator sort values in a Order By
descending order ...
Descending

ThenBy Executes a secondary Order By


sorting in an ascending …, …
order

SHASHI RAJ, BMSCW /Page 74


VB.Net Programming

ThenByDescending Executes a secondary Order By


sorting in a descending …, …
order Descending

Reverse Performs a reversal of the Not


order of the elements in a Applicable
collection

Grouping Operators

The operators put data into some groups based on a common shared attribute.

Operator Description VB Query


Expression
Syntax

GroupBy Organize a sequence of items in groups Group …


and return them as an IEnumerable By … Into
collection of type IGrouping<key, …
element>
ToLookup Execute a grouping operation in which a Not
sequence of key pairs are returned Applicable

Conversions

The operators change the type of input objects and are used in a diverse range of applications.

Operator Description VB Query


Expression
Syntax

AsEnumerable Returns the input typed as Not


IEnumerable<T> Applicable

AsQueryable A (generic) IEnumerable is converted Not


to a (generic) IQueryable Applicable

Cast Performs casting of elements of a From …


collection to a specified type As …

OfType Filters values on basis of their , Not


depending on their capability to be Applicable
cast to a particular type
ToArray Forces query execution and does Not
conversion of a collection to an array Applicable

SHASHI RAJ, BMSCW /Page 75


VB.Net Programming

ToDictionary On basis of a key selector function set Not


elements into a Dictionary<TKey, Applicable
TValue> and forces execution of a
LINQ query
ToList Forces execution of a query by Not
converting a collection to a List<T> Applicable

ToLookup Forces execution of a query and put Not


elements into a Lookup<TKey, Applicable
TElement> on basis of a key selector
function

Concatenation

Performs concatenation of two sequences and is quite similar to the Union operator in terms of
its operation except of the fact that this does not remove duplicates.

Operator Description VB Query


Expression
Syntax

Concat Two sequences are concatenated for the Not


formation of a single one sequence. Applicable

Aggregation

Performs any type of desired aggregation and allows creating custom aggregations in LINQ.

Operator Description VB Query


Expression
Syntax
Aggregate Operates on the values of a collection to Not
perform custom aggregation operation Applicable
Average Average value of a collection of values is Aggregate
calculated … In … Into
Average()
Count Counts the elements satisfying a predicate Aggregate
function within collection … In … Into
Count()
LonCount Counts the elements satisfying a predicate Aggregate
function within a huge collection … In … Into
LongCount()
Max Find out the maximum value within a Aggregate
collection … In … Into
Max()
Min Find out the minimum value existing within a Aggregate
collection … In … Into

SHASHI RAJ, BMSCW /Page 76


VB.Net Programming

Min()

Sum Find out the sum of a values within a Aggregate


collection … In … Into
Sum()

Quantifier Operations

These operators return a Boolean value i.e. True or False when some or all elements within a
sequence satisfy a specific condition.

Operator Description VB Query


Expression
Syntax

All Returns a value ‘True’ if all elements of a sequence Aggregate


satisfy a predicate condition … In …
Into
All(…)

Any Determines by searching a sequence that whether any Aggregate


element of the same satisfy a specified condition … In …
Into Any()

Contains Returns a ‘True’ value if finds that a specific element is Not


there in a sequence if the sequence doe not contains that Applicable
specific element , ‘false’ value is returned

Partition Operators

Divide an input sequence into two separate sections without rearranging the elements of the
sequence and then returning one of them.

Operator Description VB Query


Expression
Syntax
Skip Skips some specified number of elements within a Skip
sequence and returns the remaining ones
SkipWhile Same as that of Skip with the only exception that Skip While
number of elements to skip are specified by a
Boolean condition
Take Take a specified number of elements from a sequence Take
and skip the remaining ones
TakeWhile Same as that of Take except the fact that number of Take While
elements to take are specified by a Boolean condition

SHASHI RAJ, BMSCW /Page 77


VB.Net Programming

Generation Operations

A new sequence of values is created by generational operators.

Operator Description VB Query


Expression
Syntax

DefaultIfEmpty When applied to an empty sequence, Not


generate a default element within a sequence Applicable

Empty Returns an empty sequence of values and is Not


the most simplest generational operator Applicable

Range Generates a collection having a sequence of Not


integers or numbers Applicable

Repeat Generates a sequence containing repeated Not


values of a specific length Applicable

Set Operations

There are four operators for the set operations, each yielding a result based on different criteria.

Operator Description VB Query


Expression
Syntax

Distinct Results a list of unique values from a collection by Distinct


filtering duplicate data if any

Except Compares the values of two collections and return the Not
ones from one collection who are not in the other Applicable
collection
Intersect Returns the set of values found t be identical in two Not
separate collections Applicable

Union Combines content of two different collections into a single Not


list that too without any duplicate content Applicable

Equality

Compares two sentences (enumerable) and determine are they an exact match or not.

SHASHI RAJ, BMSCW /Page 78


VB.Net Programming

Operator Description VB Query


Expression
Syntax
SequenceEqual Results a Boolean value if two sequences are Not
found to be identical to each other Applicable

Element Operators

Except the DefaultIfEmpty, all the rest eight standard query element operators return a single
element from a collection.
Operator Description VB Query
Expression
Syntax

ElementAt Returns an element present within a specific Not


index in a collection Applicable

ElementAtOrDefault Same as ElementAt except of the fact that it Not


also returns a default value in case the specific Applicable
index is out of range
First Retrieves the first element within a collection Not
or the first element satisfying a specific Applicable
condition
FirstOrDefault Same as First except the fact that it also returns Not
a default value in case there is no existence of Applicable
such elements
Last Retrieves the last element present in a Not
collection or the last element satisfying a Applicable
specific condition
LastOrDefault Same as Last except the fact that it also returns Not
a default value in case there is no existence of Applicable
any such element
Single Returns the lone element of a collection or the Not
lone element that satisfy a certain condition Applicable

SingleOrDefault Same as Single except that it also returns a Not


default value if there is no existence of any Applicable
such lone element
DefaultIfEmpty Returns a default value if the collection or list Not
is empty or null Applicable

Introduction of LINQ to Objects

Queries in LINQ to Objects return variables of type usually IEnumerable<T> only. In short,
LINQ to Objects offers a fresh approach to collections as earlier, it was vital to write long coding

SHASHI RAJ, BMSCW /Page 79


VB.Net Programming

(foreach loops of much complexity) for retrieval of data from a collection which is now replaced
by writing declarative code which clearly describes the desired data that is required to retrieve.

There are also many advantages of LINQ to Objects over traditional foreach loops like more

 readability,
 powerful filtering,
 capability of grouping,
 enhanced ordering with minimal application coding.

Such LINQ queries are also more compact in nature and are portable to any other data sources
without any modification or with just a little modification.
Imports System.Collections.Generic
Imports System.Linq

Module Module1

Sub Main(ByVal args As String())

Dim account As New Department With {.Name = "Account", .DepartmentId = 1}


Dim sales As New Department With {.Name = "Sales", .DepartmentId = 2}
Dim marketing As New Department With {.Name = "Marketing", .DepartmentId = 3}

Dim departments As New System.Collections.Generic.List(Of Department)(New


Department() {account, sales, marketing})

Dim departmentList = From d In departments

For Each dept In departmentList


Messagebox.show("Department Id = {0} , Department Name = {1}", dept.DepartmentId,
dept.Name)
Next

Messagebox.show(vbLf & "Press any key to continue.")

End Sub

Class Department
Public Property Name As String
Public Property DepartmentId As Integer
End Class

End Module
When the above code of VB is compiled and executed, it produces the following result −
Department Id = 1, Department Name = Account
Department Id = 2, Department Name = Sales
Department Id = 3, Department Name = Marketing
Press any key to continue.

SHASHI RAJ, BMSCW /Page 80


VB.Net Programming

Introduction of LINQ to XML

While using LINQ to XML, loading XML documents into memory is easy and more easier is
querying and document modification. It is also possible to save XML documents existing in
memory to disk and to serialize them. It eliminates the need for a developer to learn the XML
query language which is somewhat complex.
LINQ to XML has its power in the System.Xml.Linq namespace. This has all the 19 necessary
classes to work with XML. These classes are the following ones.
 XAttribute
 XCData
 XComment
 XContainer
 XDeclaration
 XDocument
 XDocumentType
 XElement
 XName
 XNamespace
 XNode
 XNodeDocumentOrderComparer
 XNodeEqualityComparer
 XObject
 XObjectChange
 XObjectChangeEventArgs
 XObjectEventHandler
 XProcessingInstruction
 XText

Read an XML File using LINQ

Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq

Module Module1

Sub Main(ByVal args As String())

Dim myXML As String = "<Departments>" & vbCr & vbLf &


"<Department>Account</Department>" & vbCr & vbLf &
"<Department>Sales</Department>" & vbCr & vbLf &
"<Department>Pre-Sales</Department>" & vbCr & vbLf &
"<Department>Marketing</Department>" & vbCr & vbLf &
"</Departments>"

Dim xdoc As New XDocument()


xdoc = XDocument.Parse(myXML)

Dim result = xdoc.Element("Departments").Descendants()

SHASHI RAJ, BMSCW /Page 81


VB.Net Programming

For Each item As XElement In result


Messagebox.show("Department Name - " + item.Value)
Next

Messagebox.show(vbLf & "Press any key to continue.")

End Sub

End Module
When the above code of VB is compiled and executed, it produces the following result −
Department Name - Account
Department Name - Sales
Department Name - Pre-Sales
Department Name - Marketing

Press any key to continue.

LINQ Query Syntax

There are two basic ways to write a LINQ query to IEnumerable collection or IQueryable data
sources.

1. Query Syntax or Query Expression Syntax


2. Method Syntax or Method Extension Syntax or Fluent

Query Syntax

Query syntax is similar to SQL (Structured Query Language) for the database. It is defined
within the VB code.

// string collection

IList<string> stringList = new List<string>() {


"C# Tutorials",
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
};

// LINQ Query Syntax


var result = from s in stringList
where s.Contains("Tutorials")
select s;

c# tutorials
vb.net tutorials
mvc tutorials

The following figure shows the structure of LINQ query syntax.

SHASHI RAJ, BMSCW /Page 82


VB.Net Programming

LINQ Query Syntax

Query syntax starts with a From clause followed by a Range variable. The From clause is
structured like "From rangeVariableName in IEnumerablecollection". In English, this means,
from each object in the collection. It is similar to a foreach loop: foreach(Student s in
studentList).

After the From clause, you can use different Standard Query Operators to filter, group, join
elements of the collection. There are around 50 Standard Query Operators available in LINQ.

LINQ query syntax always ends with a Select or Group clause. The Select clause is used to
shape the data. You can select the whole object as it is or only some properties of it. In the
above example, we selected the each resulted string elements.

Example: LINQ Query Syntax in VB.Net


// Student collection
Dim studentList = New List(Of Student) From {
New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13},
New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21},
New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18},
New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20},
New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15}
}

// LINQ Query Syntax to find out teenager students


Dim teenAgerStudents As IList(Of Student) = (From s In studentList _
Where s.Age > 12 And s.Age < 20 _
Select s).ToList()

LINQ Method Syntax

Method syntax (also known as fluent syntax) uses extension methods included in
the Enumerable or Queryable static class, similar to how you would call the extension method
of any class.

The compiler converts query syntax into method syntax at compile time.

Example: LINQ Method Syntax in C#


// string collection
IList<string> stringList = new List<string>() {
"C# Tutorials",

SHASHI RAJ, BMSCW /Page 83


VB.Net Programming

"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
};

// LINQ Method Syntax


var result = stringList.Where(s => s.Contains("Tutorials"));

The following figure illustrates the structure of LINQ method syntax.

LINQ Method Syntax Structure

As you can see in the above figure, method syntax comprises of extension methods and
Lambda expression. The extension method Where() is defined in the Enumerable class.

Example: Method Syntax in VB.Net


// Student collection
Dim studentList = New List(Of Student) From {
New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13},
New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21},
New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18},
New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20},
New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15}
}

// LINQ Method Syntax to find out teenager students


Dim teenAgerStudents As IList(Of Student) = studentList.Where(Function(s) s.Age > 12 And
s.Age < 20).ToList()
LINQ to SQL Stored Procedure
In LINQ to SQL, we can use stored procedures with or without parameters to get the required
data from database tables.

Before we start using LINQ to SQL with a stored procedure, we need to create a database with
required tables and map those tables to LINQ to SQL file (.dbml).
Once our database is ready with the required tables, we will create a simple stored procedure to
get employee details from the EmployeeDetail table.

Write stored procedures like as shown below and execute them in your database.

CREATE PROCEDURE [dbo].[GetEmployeeDetails]


@EmpId int = 0
AS
IF (@EmpId >0)
SELECT * FROM EmployeeDetails WHERE EmpId=@EmpId

SHASHI RAJ, BMSCW /Page 84


VB.Net Programming

ELSE
SELECT * FROM EmployeeDetails
Once we execute the above stored procedure in the database, that will be like as shown below.

Now drag and drop that stored procedure on the right-hand pane of the LINQ to SQL dbml class,
as shown below.

Once we create and map required tables and stored procedures to the .dbml file now, we will
show data in our application for that Right click on the application à select Add à New
Item à Select Web Form à Give name as Default.aspx and click OK button.

Now open the Default.aspx page and write the code as shown below.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>LINQ to SQL with Stored Procedure Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="gvDetails"></asp:GridView>

SHASHI RAJ, BMSCW /Page 85


VB.Net Programming

</div>
</form>
</body>
</html>
Now open the code behind file and write the code as shown below.
VB.NET Code

Public Class WebForm1


Inherits System.Web.UI.Page
Private db As New EmployeeDBDataContext()
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
BindGridview(0)
End If
End Sub
Protected Sub BindGridview(ByVal id As Integer)
Dim result = db.GetEmployeeDetails(id)
gvDetails.DataSource = result
gvDetails.DataBind()
End Sub
End Class
If you observe the above example, we are using stored procedure “GetEmployeeDetails” with
parameters in LINQ to SQL to get data from the database.

Result of LINQ to SQL with Stored Procedure

Following is the result of LINQ to SQL with a stored procedure to get data from the database.

This is how we can use LINQ to SQL with stored procedures to get the required data from the
database in vb.net.

SHASHI RAJ, BMSCW /Page 86

You might also like