VB Unit4&5
VB Unit4&5
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.
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.
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.
Change the name of the class by double-clicking on the form in the design view and the
code will open.
Right-click the name of the project and move the mouse to add and select add web form
in the add submenu.
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.
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.
The Label control displays text at a particular position on a Web page. Generally Label control is
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.
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.
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
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.
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.
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.
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.
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
// htmlcontrolsexample.aspx
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>
When we click the button after entering text, it responses back to client.
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:
2. Server-side Validation
1. Validation Summary
2. RequiredFieldValidator
3. RangeValidator
4. CompareValidator
5. RegularExpressionValidator
6. CustomValidator
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.
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.
<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>
5. RegularExpressionValidator Control
<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)
{
if (args.Value.Length == 10)
args.IsValid = true;
else
args.IsValid = false;
}
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:
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:
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.
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.
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. }
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
Part2
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
1. table {
2. font-family: arial, sans-serif;
3. border-collapse: collapse;
4. width: 70%;
5. }
App_Themes folder
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.
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
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.
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.
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.
After clicking OK button in the Window, select Empty (shown in the picture),
After clicking OK button, project "masterpage" opens but no file is there (shown in the
picture),
After clicking on new item, Window will open, select Web Form->Web Forms Master
Page (shown in the picture),
After clicking the add button, master page 'site1.master' adds to our project.
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. }
After clicking on that, add the button Window, open the selected masterpage-
>site1.master and click OK.
Home.aspx
Finally, our Master page is created; build and run the project.
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
When the application is executed, check that the entire title column is bound to the bulleted list
and displayed.
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:
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.
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
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 .
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 .
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.
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 .
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.
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.
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.
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
<form runat="server">
</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;
<form runat="server">
</form>
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.
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.
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.
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.
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.
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
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.
<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>
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.
<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>
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.
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.
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.
Caching in ASP.Net
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
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.
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"?>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about a US-Japan war</description>
</movie>
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
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.
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
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
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).
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
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
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.
After assign available report to CrystalReportViewer control check your code that would be like
this
VB.NET Code
Imports CrystalDecisions.CrystalReports.Engine
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
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.
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.
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.
SQL Uses
This programming language has various uses for data analysts & data science professionals. It is
particularly helpful because it can:
Syntax
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 –
Now, you have CUSTOMERS table available in your database which you can use to store the
required information related to customers.
Syntax
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 −
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
Syntax
Example
Syntax
Example
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.
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.
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.
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.
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:
HeaderTemplate
AlternatingItemTemplate
Itemtemplate
SeoperatorTemplate
FooterTemplate
Example
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.
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.
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.
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
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.
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.
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.
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:
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.
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
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'.
// 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.
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.
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.
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
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.
Projection Operations
Projection is an operation in which an object is transformed into an altogether new form with
only specific properties.
Sorting Operators
A sorting operation allows ordering the elements of a sequence on basis of a single or more
attributes.
Grouping Operators
The operators put data into some groups based on a common shared attribute.
Conversions
The operators change the type of input objects and are used in a diverse range of applications.
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.
Aggregation
Performs any type of desired aggregation and allows creating custom aggregations in LINQ.
Min()
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.
Partition Operators
Divide an input sequence into two separate sections without rearranging the elements of the
sequence and then returning one of them.
Generation Operations
Set Operations
There are four operators for the set operations, each yielding a result based on different criteria.
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
Equality
Compares two sentences (enumerable) and determine are they an exact match or not.
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
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
(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
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.
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
Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq
Module Module1
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
There are two basic ways to write a LINQ query to IEnumerable collection or IQueryable data
sources.
Query Syntax
Query syntax is similar to SQL (Structured Query Language) for the database. It is defined
within the VB code.
// string collection
c# tutorials
vb.net tutorials
mvc tutorials
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.
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.
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
};
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.
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.
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>
</div>
</form>
</body>
</html>
Now open the code behind file and write the code as shown below.
VB.NET Code
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.