Part 2
Part 2
HARSHA VARDHAN
Click on ―Submit‖.
Then it shows the security question, which is given at the time of user registration.
Enter the proper answer. Ex: green
To solve this problem, you have to configure the ―SMTP settings‖ in your web site. After
you configure, this control works properly.
So, let us continue with configuring the SMTP Settings.
ASP.NET
Close the browser and come back to the Visual Studio. Configuration
Open Solution Explorer and select the web site name. (Click here)
Click on OK.
Close the browser and come back to Visual Studio.
Then the necessary changes will be made in the ―web.config‖ file.
To see those changes, double click on ―web.config‖ file in the Solution Explorer.
But still, it won‘t work, because the mail domain (peerstech.com), which you are using
in the above mentioned mail address doesn‘t exist actually.
So that we have to create a alias domain (dummy domain), with the name of
―peerstech.com‖.
To create it, click on ―Start‖ – ―Run‖.
Then type ―inetmgr‖ and click on OK.
Click on Next.
Specify the name as ―peerstech.com‖.
Click on Finish.
Then it will be added to the existing domains list.
If you configure the ―Outlook Express‖ properly, the e-mail will be sent automatically to
the Inbox of the user.
Anyway, you can find the password, which is given as an encrypted value in the e-mail.
Ex: dgJfi^cdx=>d]h
The user has to use this above password, to login. Of course, after next login, the user
can change the password.
To test it, run the web site, and try to login with above given encrypted password (you
can copy the password and paste it directly in the password textbox, at the login page).
After that try to change the password using ―Change Password‖ option.
WebParts Controls
The WebParts controls allow the user to change the web page content dynamically at run
time, though the browser.
This is a concept of personalization, which remembers your settings automatically, based
your login information (username and password). If you run the web site later (after few
days or months also), the same settings will be loaded.
Important WebParts Controls:
1. WebPartManager
2. WebPartZone
Re-size the WebPartZone controls and set the auto-format styles, as per your desire.
Rename the ―WebPartZone1‖ as ―FirstZone‖ using ID property.
Rename the ―WebPartZone2‖ as ―SecondZone‖ using ID property.
Rename the ―WebPartZone3‖ as ―ThirdZone‖ using ID property.
Drag the drop any controls (like labels, buttons, textboxes, checkbox, calendars etc.) into
the web part zones.
(Continued…)
Note: If you minimize any control, you can restore it later. If you close it, you can‘t
restore it again.
Close the browser and come back to Visual Studio.
Drag and drop a ―DropDownList‖ control.
Select it and click on ―>‖ symbol. Click on ―Enable AutoPostBack‖ option.
Click on OK.
Double click on the DropDownList1 control and write the code:
Default.aspx.css
using System.Web.UI.WebControls.WebParts;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex == 0)
WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode;
else
WebPartManager1.DisplayMode = WebPartManager.DesignDisplayMode;
}
The query string is the string attached to URL, which is displayed in the browser‘s
address bar. The query string starts with ―?‖ symbol.
When you want to pass one or more values from one page to another page as
arguments, you can send them with the ―Query String‖, in the following format.
Syn: http://localhost:portno/WebSiteName/WebPage.aspx?parameter=value
Ex: http://localhost:portno/WebSiteName/WebPage.aspx?n=100
When you want to pass multiple values with the query string, use the following format:
Syn: http://localhost:portno/WebSiteName/WebPage.aspx?parameter1=value1&
parameter2=value2
Ex: http://localhost:portno/WebSiteName/WebPage.aspx?n1=140&n2=98
To get the parameter value in the next page, use this syntax:
Syn: Request.Params[―parameter name‖]
Ex: Request.Params[―n‖]
The above syntax gets the value of the given parameter, in string format.
Default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string s = TextBox1.Text;
Response.Redirect("display1.aspx?uname=" + s);
}
display1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Request.Params["uname"];
Label1.Text = "Welcome, " + s;
}
No security is available, because the argument names and values will be displayed in the
browser‘s title bar. You can‘t pass the values in hidden mode.
The values can be sent from one page to another page only. But, the values can‘t be
retrieved from other pages, forwarded from the second page.
You can share only string values or numerical values among multiple pages. Of course,
even though you pass the numerical values, it treats the value as a string value only.
Anyhow, you can‘t pass ―objects”.
Note: To overcome the above first two limitations, ―Cookies‖ concept is introduced.
Cookies
A cookie can be used to share values among two or multiple web pages.
Cookies are stored at client system only.
A cookie will be created as a text file in the ―c:\Documents And
Settings\Username\Cookies‖ folder on the client system. These files will be created
dynamically at run time.
When compared with ―Query String‖, the advantage of cookies is, it doesn‘t display the
values in the address bar. The value can be passed in hidden mode.
Another advantage of ―Cookies‖ is, cookies alive among multiple web pages, not only
between one page to another page. That means you can access the values stored in the
cookies from any other pages, navigated from the current page.
According to the OOP standards in ASP.NET, every cookie is an object for a pre-defined
class called ―HttpCookie‖.
Implementation:
A. Assign value to the Cookie:
Create cookie object:
HttpCookie obj = new HttpCookie(―variable_name‖, ―value‖);
Assign the cookie object to Response:
Response.Cookies.Add(obj);
B. Get value from the Cookie:
Request.Cookies[―variable_name‖].Value
Demo:
Default.aspx.cs
protected void Button2_Click(object sender, EventArgs e)
{
string s = TextBox1.Text;
HttpCookie ck = new HttpCookie("uname", s);
Response.Cookies.Add(ck);
Response.Redirect("display2.aspx");
}
display2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Request.Cookies["uname"].Value;
Label1.Text = "Welcome, " + s;
}
Limitations of “Cookies”
Cookies will be stored in the form of text files during run time in the client system. Those
files can be easily visible by other users. It is easy to modify or delete the cookie files. It
is easy to hack the cookie files from remote systems also. So, cookies are not much
secured.
Cookie files will not be deleted automatically. So that, it leads to waste of hard disk
memory.
It doesn‘t supports to share ―objects‖ among multiple pages. It supports to share strings
or numerical values only.
Finally, now-a-days, cookies are out-dated. To overcome the limitations of cookies, we use
―Sessions‖.
Session State
Whenever a client (browser) is connected, the ―Session‖ state will be created
automatically; and the session will be closed automatically whenever the client (browser)
is disconnected.
Here, ―state‖ means some memory, at web server.
For every client (browser), a separate session will be created. For example, your web site
is being opened by 100 users (from 100 browsers). That means there will be 100
sessions.
Similar to Cookies, the ―Session state‖ is used to share values among multiple pages. For
example, between login and logout, the current user name, user id number and
password will be stored in the session state.
Now-a-days, ―Cookies‖ are outdated. Instead of cookies, sessions are used.
The main difference between cookies and session state is: a cookie will be saved on the
client system; and the session will be saved at web server.
Sessions are more secured, when compared with ―Cookies‖, as sessions will be saved at
web server.
Sessions will not be saved in the form of any files. Those are stored as logical objects in
the web server memory.
Sessions are able to share values and objects also.
Implementation of ―Session state‖ is easier, when compared with ―Cookies‖.
To access the session state, you can use the implicit object called ―Session‖. That means
you don‘t require to create the ―Session‖ it is commonly available for all the web pages
by default.
The ―Session‖ object always represents current session, in which the web page is being
executed.
Implementation:
A. Assign value to the Session:
Session[―name‖] = value;
B. Get value from the Session (gets the session variable value in “Object”
type):
Session[―name‖]
C. Clear all the values in the current session:
Session.Clear();
Demo:
Default.aspx.cs
protected void Button3_Click(object sender, EventArgs e)
{
Session["uname"] = TextBox1.Text;
Response.Redirect("display3.aspx");
}
display3.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Convert.ToString(Session["uname"]);
Label1.Text = "Welcome, " + s;
}
Application State
Another state available in ASP.NET is ―Application‖ state. Similar to ―Session state‖, the
―Application state‖ holds the data values or objects among multiple web pages in the
web site.
Similar to ―Session state‖, the ―Application state‖ also will be stored at web server. It
offers much security.
The only difference between ―Session‖ and ―Application‖ states is: ―The Session state
data will be lost automatically whenever the browser is closed. But the Application state
data will not be lost even after the browser is closed. It will remain until you stop the
web server‖.
In other words, the session is limited to single client. Individual sessions are created for
every client. But for all the clients, ―Application‖ state is accessible.
Conclusion: When you want to store any data value, that is related one user, you
prefer to use ―Session‖ state. Whenever your data value is to be accessible from other
users also, then you prefer ―Application‖ state.
Implementation:
A. Assign value to the Application:
Application[―name‖] = value;
B. Get value from the Application (gets the application state variable value in
“Object” type):
Application[―name‖]
Demo:
Default.aspx.cs
protected void Button4_Click(object sender, EventArgs e)
{
Application["uname"] = TextBox1.Text;
Response.Redirect("display4.aspx");
}
display4.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Convert.ToString(Application["uname"]);
Label1.Text = "Welcome, " + s;
}
View State
―View State‖ is a state that keeps the current state of the web page, during post back.
Post Backing: The web page gets re-loaded automatically, whenever the user performs
an event at run time. Here, the page will be submitted to the same page itself. This
process is called as ―Post Backing‖. For example, if the user clicks on a button, the page
will be posted back.
At the time of post backing, the web page will be closed and the same web page will be
re-loaded. In fact, the textbox values / list box selections etc., would not be re-loaded, if
―View State‖ concept is not implemented.
Because of ―View State‖, ASP.NET is able to get the web page to the previous state, as it
is submitted at the time of post back.
As a part of this ―View State‖, at the time of Post Backing, ASP.NET automatically saves
the current values of the controls in a separate string temporarily. After re-loading the
page, the controls values will be re-stored to its previous state, based on the values in
view state string.
In fact, the ―View State‖ is maintained automatically by ASP.NET, you don‘t require
implementing it manually.
Demo
Open the previous demo web site.
Add ―viewstatedemo.aspx‖ page and design it as shown.
Open Solution Explorer; right click on ―viewstatedemo.aspx‖ and click ―View in Browser‖.
Enter some values.
Click on the button. Then the ―post backing‖ will be done. But the no values will be lost.
Global.asax
This file contains the events, related to entire web site.
Here is the list of events, written in global.asax file:
1. Application_Start: This event executes automatically, whenever the
―Application State‖ is created. The Application State will be created automatically,
whenever the web server is started.
Demo
Open the previous demo web site.
Open Solution Explorer. Right click on the web site name and click on ―Add New Item‖ –
select ―Global Application Class‖ – Click on ―Add‖.
It generates the following events automatically.
Global.asax
<%@ Application Language="C#" %>
<script runat="server">
Response.Redirect("errorpage.aspx");
}
</script>
usercountpage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
int n = Convert.ToInt32(Application["usercount"]);
Label1.Text = "This web site is viewed by " + n + " users.";
}
Copy the URL from the address bar; open another browser; and paste the URL.
Note: Every time you run the page, the user count will be incremented automatically.
errortestpage.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
int[] a = { 10, 20, 30, 40 };
int x = a[5];
Response.Write(x);
}
Open Solution Explorer; Right click on ―errortestpage.aspx‖ and select ―View in Browser‖.
CSS
(Cascading Style Sheets)
This is to overcome the limitations of HTML and also to apply common style among
several controls on the same or different web pages.
This can also be called as ―DHTML‖ (Dynamic Hypertext Markup Language).
DHTML offers better designing features, which are not supported by classic HTML.
This also used to implement common design styles among different types of controls.
It contains no new tags. It contains several attributes for better designing.
In fact, CSS is not only related to ASP.NET. It is the generalized web page designing
concept, which is available in PHP and J2EE etc., also.
In ASP.NET, these styles can be applied for both HTML tags and ASP.NET controls also.
Ex:
<asp:TextBox ID="TextBox4" runat="server" Style="font-family:Broadway;
border-color:Red; text-align:right;" Text="hello"></asp:TextBox>
2) Internal Styles:
Syn:
<head>
<style type=‖text/css‖>
tag
{
attribute1:value1; attribute2:value2;….
}
</style>
</head>
Description: The CSS styles can be applied for every instance of the specified
tag in the current page.
Ex:
<style type="text/css">
h2
{
color:Blue;
font-family: Tahoma;
font-size: 30px;
}
</style>
Invoke it:
<h2>hello</h2>
3) External Styles:
Syn: (“xxxxxx.css” file)
tag
{
attribute1:value1; attribute2:value2;….
}
Description: The CSS styles can be applied for every instance of the specified
tag in every page, that is linked with the ―.css‖ file.
To link the ―.css‖ file, write the following tag in the page.
<head>
<link href=‖css file path‖ rel=‖Stylesheet‖ type=‖text/css‖ />
</head>
Instead, you also drag and drop the ―.css‖ file from Solution Explorer into the
web page. Then Visual Studio automatically generates the above ―<link>‖ tag in
the ―<head>‖ tag automatically.
CSS Classes
In the ―Internal Styles‖ and ―External Styles‖, common styles will be applied for every
instance of particular tag. Instead, you can have a choice for applying the CSS styles for
the required instances only, with the concept called ―CSS classes‖.
Finally, the ―CSS Classes‖ concept can be used in two situations:
1) To apply common CSS styles for selective instances of a tag.
2) To apply common CSS styles for selective instances of multiple tags.
To create a CSS class, follow the syntax:
.classname
{
attribute1:value1; attribute2:value2;….
}
To apply the CSS style for the required html tag, follow the syntax:
<tag class=‖classname‖>
To apply the css style for the required server tag, follow the syntax:
<asp:tag CssClass=‖classname‖>
Ex:
<head runat="server">
<style type="text/css">
.mytextbox
{
color:Red;
font-family: Tahoma;
font-size: 30px;
border-style: double;
}
</style>
</head>
Open Solution Explorer – right click on the web site name and click on ―Add New Item‖.
Select ―Style Sheet‖.
Enter the any file name. Ex: StyleSheet.css
Click ―Add‖.
Then the screen looks like this:
Remove that body tag and make file empty, because we don‘t require it now.
On the screen, you can observe ―Style Sheet‖ toolbar.
If you don‘t find it, click on ―View‖ menu – ―Toolbars‖ – ―Style Sheet‖ option. Then the
toolbar will be there.
Then click on the first button called ―Add Style Rule‖.
Click on ―Class name‖ option and enter the any class name. Ex: MyTextBox.
It automatically generates the Style rule preview as ―.MyTextBox‖ (as you know already
that, every CSS class name should start with . (dot)).
Click on OK.
Then it generates CSS class syntax in the code.
Then click on the class name (MyTextBox) and click on ―Build Style‖ option in the toolbar.
Click on OK.
Then it automatically generates the style sheet code as below:
Themes
As you know in the previous concept, the CSS styles are used to apply common design
styles. But the limitation of CSS is, CSS styles are always executed at client level.
The CSS styles can‘t be applied at sever level. So that, using CSS, you can set the
general properties like font styles, colors, cursors, borders etc., but you can‘t set the
special properties related to the server controls.
For example, you can‘t set the ―ReadOnly‖ property of a textbox using CSS. In the same
way, you can‘t set the ―NavigateUrl‖ property of a hyperlink using CSS.
In this case, to replace the usage of ―CSS styles‖, the ―Themes‖ are introduced.
The advantage of themes is: those can set the any property of the server controls. For
example, you can do the above two examples using ―Themes‖.
One more advantage is: you don‘t require setting any property like ―CssClass‖, if you are
using ―Themes‖. The style will be applied commonly for all the controls, that you have
mentioned in the skin file.
The themes can be implemented in a ―skin file‖ (with .skin extension), and placed in the
―App_Themes‖ folder.
When you create a theme, its skin file is placed in the ―App_Themes‖ folder.
Note: The themes are completely dynamic. Its effect would not be displayed in the
―Design‖ view.
Implementation of Themes:
First, add a skin file by clicking on ―Web Site‖ menu – ―Add New Item‖ – ―Skin File‖.
Enter the name of the theme. Ex: MyTheme.skin
Click on ―Add‖.
It asks a confirmation, to create ―App_Themes‖ folder. Click on ―Yes‖.
Then the skin file will be created as follows:
In the skin file, you can write the tags for server controls like <asp:Label> etc., along
with few properties. The tag should contain runat=server attribute.
Ex: <asp:Label runat=‖server‖ BackColor=‖Pink‖ />
To impose the theme in the required .aspx page, simply write the Theme=”theme
name” attribute the <%@ Page> directive.
Note: If the property values are clashed between the control and the theme, the theme
properties only be applied at run time.
Note: To disable the themes for a specific tag instance, simply use EnableTheming=”false”
attribute for the required tag.
Demo:
Open Solution Explorer; right click on the web site name and click on ―Add New Item‖.
Select ―Skin File‖.
Delete all the commented code and type the code manually as follows:
MyTheme.skin
<asp:Label runat="server" Font-Bold="True" Font-Name="Tahoma" ForeColor="Green"
Font-Size="14px" />
<asp:TextBox runat="server" Font-Bold="True" Font-Name="Lucida Handwriting"
BackColor="DarkGreen" ForeColor="Yellow" Font-Size="14px" />
<asp:Button runat="server" Font-Bold="True" Font-Name="Comic Sans MS"
BackColor="DarkRed" ForeColor="Yellow" Font-Size="14px"/>
IMP Note: While you are typing the above code, no help
can be given by Visual Studio. You have to take care about
casing and all other things. If you don‘t type it in proper
casing, it won‘t work. It causes some errors.
Come back to the ―themesdemo.aspx‖ page.
Open the properties window and choose ―DOCUMENT‖
option from the list, which is displayed at the top of the
properties window.
Select the ―Theme‖ property as ―MyTheme‖ from the list.
Select the ―Label3‖ and set the following property:
EnableTheming: False
Then run the web site.
At run time, the theme will be applied, and the page looks
like this on the browser:
Limitations of Themes:
As per the default nature of themes, for all the controls, common styles will be applied
automatically.
Suppose if you want to apply one type of style for few controls on the page, and another
type of style for few other controls on the page, it not possible.
Solution: Use ―Skins‖.
Skins
Skins are similar to CSS classes.
Similar to CSS class, the skin has a name.
It can be written in the ―.skin‖ file.
One skin file may contain any no. of skins.
Implementation:
Create the tag designs with “SkinID” attribute (in the skin file):
<tag runat=‖server‖ property=‖value‖ SkinID=‖skin name‖ />
Access the Skin with “SkinID” attribute (in the aspx page):
<tag runat=‖server‖ SkinID=‖skin name‖ />
Demo:
Open Solution Explorer; right click on the web site name and click on ―Add New Item‖.
Select ―Skin File‖.
Enter the file name as ―MyTheme2.skin‖.
Click on ―Add‖.
It asks a confirmation, whether you want to place the skin file in the ―App_Themes‖
folder or not. You click on ―Yes‖.
Then the screen looks like this:
Delete all the commented code and type the code manually as follows:
MyTheme2.skin
<asp:TextBox runat="server" Font-Bold="True" Font-Name="Comic Sans MS"
BackColor="Pink" ForeColor="Red" Font-Size="20px" SkinID="PinkAndRed" />
<asp:TextBox runat="server" Font-Bold="True" Font-Name="Comic Sans MS"
BackColor="Bisque" ForeColor="Blue" Font-Size="20px" SkinID="BisqueAndBlue" />
Note: If you don‘t apply the SkinID property, no style will be applied.
So finally, we have few textboxes with one style, and few other textboxes with another
style.
This is possible using Skins.
Demo:
Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Aboutus.aspx‖ – Click on Add.
Design the ―Aboutus.aspx‖ as follows:
Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Contactus.aspx‖ – Click on Add.
Design the ―Contactus.aspx‖ as follows:
Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―registration.aspx‖ – Click on Add.
Design the ―registration.aspx‖ as follows:
Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―login.aspx‖ – Click on Add.
Design the ―login.aspx‖ as follows:
Open solution explorer; right click on the web site name and choose ―Add New Item‖.
Select ―Web User Control‖.
Enter any name. Ex: WebUserControl.ascx
Note: ascx stands for Active Server Control Extended.
Click on ―Add‖.
Design it as shown:
In the same way, drag and drop the ―WebUserControl.ascx‖ into all other pages also.
After designing the user control, the pages looks like this:
Note: To avoid the repetition of design like above example, you can use another concept called
as ―Master Pages‖.
Master Pages
Similar to ―User Controls‖, the common design can be shared among multiple web pages
using ―Master Pages‖ concept.
A master page is similar to web page, but it‘s not a web page.
The master page file extension is ―.master‖.
It also contains some design and code in the ―.cs‖ file.
It can be executed on the browser directly.
This is meant for re-usability only.
That means the master page content can be re-usable by other web pages (.aspx
pages).
Demo:
Caching
Caching (pronounced as ―Cashing‖), is one of the most powerful concept of ASP.NET.
This is introduced to reduce the stress on web server.
If your application is being executed simultaneously from two or more browser windows
on the same system, or it is being executed simultaneously from two or more client
systems on the network, or it is being executed simultaneous from two or more web
clients on internet, on each post back of the page, a new request to the web server
would be passed. So that, the entire page is to be refreshed. That means the contents of
the web page would be re-loaded and the code will be executed every time. This causes
heavy stress on the web server.
For example, there is a submit button on your web page. If the submit button is clicked
on one client, it is not a much stress on the web server. You suppose that the button is
clicked from 20 client systems at-a-time. So that 20 requests will be passed to the web
server. The web server should respond to the 20 clients. So this leads to slow-up the
execution, because of heavy stress on the web server.
To avoid this kind of problems, ―Caching‖ concept is introduced.
According to this, you can store the page and its output in the cache memory up to a
certain time.
If any request is sent to the web server, within the time limitation, the page will not be
re-loaded / re-executed. No code will be executed. Simply the previously cached web
page will be sent to the client as response.
After completion of the specified time limit, the cached page will be removed
automatically.
If any request is sent to the web server after the time limit, the page will be re-loaded as
usual.
Generally, it is recommended to store most frequently used web pages in the cache
memory, using ―Caching‖ concept.
At this same time, it is not recommended to store the web pages in the cache memory,
which pages content can be frequently changed dynamically at run time. Ex: Inbox page,
cricket scores page, examination results page.
Types of Caching:
1. Output Caching:
The output of the web page will be stored in the cache memory, for a while (based
on the time limit that you have given).
Syntax: Write the following tag in the ―Source‖ view, after Page directive:
<%@ OutputCache Duration="seconds" VaryByParam="none" %>
2. Fragment Caching:
This is also one kind of output caching.
But instead of storing the full page output in the cache memory, partial page (part of
the page) output only be stored.
To implement this, you have to implement the ―OutputCache‖ in the Web User
Control.
After that, drag and drop the ―WebUserControl‖ into the web page.
That‘s all. Then finally it will be fragment caching.
3. Data Caching:
This is used to store the frequently used database data, in the cache memory.
For the first time, when the user opens the web page, you connect with the database
and get the data from the database; and store it in the cache memory.
Later, you can get the cached data on the same page or another page also, without
contacting the database.
Default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
Label2.Text = DateTime.Now.ToLongTimeString();
}
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<%@ OutputCache Duration="30" VaryByParam="none" %>
Note: The attribute ―VaryByParam‖ can be used for the pages, having the parameters in the
query string. When you want to use this, you write it as VaryByParam=”*”. Whenever you
write like this, separate copies will be created in the cache for the page, having different query
strings. If there are no changes in the query string, then cached output will be given as response
to the user.
To continue the demo application with ―Fragment caching‖, open the solution explorer,
right click on the web site name and choose ―Add New Item‖.
Select ―Web User Control‖.
Enter the name as ―WebUserControl.ascx‖.
Click on ―Add‖.
Design the ―WebUserControl.ascx‖ as shown:
WebUserControl.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
WebUserControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"
Inherits="WebUserControl" %>
<%@ OutputCache Duration="30" VaryByParam="none" %>
fragmentcachingdemo.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
Drag and drop the ―WebUserControl.ascx‖ from solution explorer, into the page.
Then the screen looks like this:
To continue the demo application with ―Data caching‖, add the ―datacachingdemo.aspx‖
and design it as shown:
datacachingdemo.aspx.cs
using System.Data.SqlClient;
using System.Data;
DataTable dt;
dt = ds.Tables[0];
Cache["mydata"] = dt;
Label1.Text = "Data Loaded from Database";
}
else
{
Label1.Text = "Data Loaded from Cache";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//some code for displaying the data...
DataTable dt = (DataTable)Cache["mydata"];
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Demo:
Add the ―myad.aspx‖ page and design it as follows with an image control:
Select the ―DOCUMENT‖ properties in the ―properties window‖ and set the following
property:
Title: Ad
Type the <body> tag as follows:
<body leftmargin=0 rightmargin=0 topmargin=0 bottommargin=0>
Run the web site and click on the button. It shows the popup ad automatically.
2) Confirmation Boxes:
Syntax: window.confirm("message");
Demo:
dialogboxes.aspx.cs
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("confirmationmessage.aspx");
}
Note: When the user clicks on ―OK‖ button at run time, the ―confirmationmessage.aspx‖ page
will be displayed, because the confirm() method returns ―true‖ value. Otherwise, no action will be
done, because the confirm() method returns ―false‖ value.
Demo:
LINQ
LINQ (pronounced link) stands for ―Language Integrated Query‖.
This concept is introduced in .NET Framework 3.5.
This is a ―query writing technology‖.
This is most useful while working large amount of data in the live projects.
Introduction:
In relational database system, data is organized in the form of tables, on which you can
write SQL queries to retrieve the required data according to the requirement in the
application.
In the modern world, the data sources are not only the databases. The application can
access the data from various other data sources like XML files, SAP, CSV (Comma
Separated Values) files etc.
But you can‘t write a query on the non-database data, which in the form of objects, XML
etc. There, you can write the queries using the new concept called ―LINQ‖.
You can write queries on arrays, objects, tables, xml using LINQ.
Note: Before writing the LINQ queries, you should import the ―System.Linq‖ namespace.
//ling query
var result = from n in numbers where n < 10 select n;
//output
foreach (var x in result)
Response.Write(x + ", ");
}
In the above application, the array contains few numbers. After executing the query, you
got only the numbers, which are less than 10. In this manner, you can write the queries
on various data sources.
LINQ Syntax:
Mandatory clauses:
from clause
in clause
select clause
Understanding Clauses:
1. from clause: This is used to specify the range variable name. At run time, the one-by-
one element (in a loop) will be assigned to this range variable and based on this range
variable other clauses like where, let, order by etc., will be executed..
2. in clause: This is used to specify the data source for the query, from where data comes
to execute the query.
3. let clause (optional): This is used to declare a new identifier with a value, that is to be
used during the query execution.
4. where clause (optional): This is most frequently used optional clause, using which
you can specify the condition in the query.
5. orderby clause (optional): This is used to specify the sorting expression if required. It
supports to have both ascending and descending order.
6. select clause: This is used to specify the object, which is required in the query results.
In general, we give
7. group by (optional): This is similar to ―group by‖ clause in SQL. This retrieves grouped
data, based on a column.
Note: The LINQ query returns the result in the form of IEnumerable<data type> type.
IEnumerable is an interface.
Library: System.Collections.Generic.IEnumerable
Student.cs
//constructor
public Student(int StudentID, string Name, string Course, int Marks)
{
this.StudentID = StudentID;
this.Name = Name;
this.Course = Course;
this.Marks = Marks;
}
}
linqtoobjectsdemo.aspx.cs
Response.Write("<font face=Tahoma>");
//linq query with where clause
var result1 = from s in stu where s.Course == "MCA" select s;
Response.Write("MCA Students:" + "<br>");
foreach (Student r in result1)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");
Response.Write("</font>");
}
}
Run the web site and the output will be like this:
goes to
linqwithlambda.cs
Response.Write("<font face=Tahoma>");
Response.Write("</font>");
}
}
LINQ to SQL
This is to get the database data and perform LINQ queries on database data.
linqtosqldemo.aspx.cs:
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = from c in db.Customers where c.Gender == "Female" select c;
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton4_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.OrderBy(c => c.Amount);
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton5_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.OrderByDescending(c => c.Amount);
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton6_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.Take(2);
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton7_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.Skip(2);
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton8_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist1 = db.Customers.Where(c => c.Amount >= 4000 && c.Amount <=
5000);
var customerslist2 = db.Customers.Where(c => c.Amount >= 6000 && c.Amount <=
8000);
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton9_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist1 = db.Customers.Where(c => c.Gender == "Male");
var customerslist2 = db.Customers.Where(c => c.Amount >= 6000 && c.Amount <=
8000);
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton10_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist1 = db.Customers.Where(c => c.Gender == "Male");
var customerslist2 = db.Customers.Where(c => c.Amount >= 6000 && c.Amount <=
8000);
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton11_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = from cust in db.Customers
join ord in db.Orders
on cust.CustomerID equals ord.CustomerID
select new { cust.CustomerID, cust.CustomerName, cust.Gender,
cust.Amount, ord.OrderID, ord.ProductID, ord.Price, ord.OrderDate };
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
GridView1.DataSource = null;
GridView1.DataBind();
}
XML
XML stands for ―Extensible Markup Language‖.
It is also a markup language, just like HTML, which contains tags.
But unlike HTML, the XML contains no pre-defined tags. It contains only user-defined
tags.
This xml code can be written in a file with ―.xml‖ file.
This is used to describe the data in a structured format.
The xml files can be used as ―secondary databases‖.
Generally, xml documents are portable, in order to share the data among two projects
developed in different languages.
Ex: employees.xml
employees.xml
Default.aspx.cs
using System.Data;
Note: The ReadXml() method reads the data from the xml file and stores it into dataset.
Run the web site.
Output:
Strict Caution: Don‘t make any changes, without proper knowledge; because it makes
ASP.NET malfunction in your system.
The xml document starts with XML prologue, which specifies the xml version.
<configuration>
………..
</configuration>
The next important section is <appSettings>. This is used to store or configure the
application settings, which are related to entire web site. For example, you want to
display the company‘s phone number in several web pages. So that, if you write the
phone number in each page it will be much difficult to change it later, because you
require to change it in all the required pages.
Instead, you try to store it (write it) in the web.config file, at the <appSettings> section.
Then later if you want to change it, you can change it easily, without changing any code
in all the pages.
To take a demonstration, change the <appSettings/> tag as follows:
<appSettings>
<add key="CompanyLocation" value="Hyderabad"/>
<add key="PhoneNo" value="040-23923020"/>
</appSettings>
using System.Configuration;
That means, at run the opens the web.config file automatically, then the company
location and phone number will be taken from <appSettings> tag and will be displayed
in the labels.
Suppose, you want to the change the company location and phone number now. Where
we need to change? You have to change in the <appSettings> tag; and no changes in
your code of the page.
Just for a demo, change the company location and phone number in the web.config file
as follows:
<appSettings>
<add key="CompanyLocation" value="Banglore"/>
<add key="PhoneNo" value="9993999790"/>
</appSettings>
Run the web site. These values will be affected in the output directly.
In the similar way, you are strongly recommended to store the connection strings in the
web.config file, at <connectionStrings> tag; because there may be some changes in the
connection string in future.
<connectionStrings>
<add name="MyConn" connectionString="data source=localhost;user
id=sa;password=123;initial catalog=demo"/>
</connectionStrings>
Come back to Default.aspx and add a button called ―Connect to SQL Server‖ as shown.
using System.Data.SqlClient;
<compilation debug="true">
When it is set to ―true‖, it shows the code, when the exceptions occur; break points also
work.
When it is set to ―false‖, it shows a default error message page, when the exceptions
occur; break points won‘t work.
By default, when you create the web site, it will be ―false‖. After you run the web site for
the first time, it will be automatically changed as ―true‖.
It is recommended to set it as ―true‖, when the development process in under progress.
It is recommended to set it as ―false‖, before you publish it on the internet; because you
won‘t show the code to the user, when an exception occurs.
The next thing you have to observe is <authentication> tag.
This tag specifies the mode of ASP.NET security. The modes are:
A. None
B. Windows
C. Forms
D. Passport
The default mode is ―Windows‖.
<authentication mode="Windows"/>
We discuss more about this ASP.NET Security concepts and authentication modes later.
The next thing you have to observe is <customErrors> tag.
CustomError means customized errors.
Note: By default, the above code will be under commented mode. You have to un-
comment it, by moving the --> tag to up.
These custom errors are used to display required web pages, when some special type of
error occurs at run time.
For example, whenever the user tries to open a non-existing filename, there will be one
type of error at server. That error code is ―404‖.
Observe the following tag:
According to the above tag, whenever 404-error occurs, ASP.NET automatically redirects
the execution flow to the above specified html page called ―FileNotFound.htm‖.
To test this functionality, do like this:
Run the web site as follows:
In the above screen, the user has tried to open the ―abc.aspx‖ page, which is not there
in our web site. So that ASP.NET is showing the default error message as above.
In the above screen, you can observe the error code as ―HTTP 404‖.
Anyway, using <customErrors> tag, you can display another page, at this case.
To do so, close the browser and come back to Visual Studio.
Open the Solution Explorer; right click on the web site name and choose ―Add New
Item‖.
Select ―HTML Page‖.
Run the web site and enter the non-existing file name as follows: