Introduction to ASP Unit 4
Introduction to ASP Unit 4
Introduction to ASP-unit 4
Introduction to ASP.NET
ASP.NET is an entirely new framework from Microsoft for building Next Generation Web Applications.
ASP.NET is component-based and modularized. Every page, object, and HTML element in ASP.NET can be
accessed at runtime as a component. The key component of the new .NET framework has the potential to save
organizations time and money by allowing them to establish object-oriented frameworks for the web
applications. Microsoft has done an excellent job by automating common web development tasks. But more
importantly they have created a tool that gives developers the ability to handle any business problem.
ASP.NET is Microsoft corporation's propitiatory frontend language. It means "Active Server Pages". In the
name itself, it's saying I'm active. The ASP code will run in the client machine and used to represent the data
which is returning from the server.
ASP.NET is a web development platform, which provides a programming model, a comprehensive software
infrastructure and various services required to build up robust web applications for PC, as well as mobile
devices. ASP.NET works on top of the HTTP protocol, and uses the HTTP commands and policies to set a
browser-to-server bilateral communication and cooperation.
ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled codes, written using the
extensible and reusable components or objects present in .Net framework. These codes can use the entire
hierarchy of classes in .Net framework.
The ASP.NET application codes can be written in any of the following languages:
• C#
• Visual Basic.Net
• Jscript
• J#
ASP.NET is used to produce interactive, data-driven web applications over the internet. It consists of a large
number of controls such as text boxes, buttons, and labels for assembling, configuring, and manipulating code
to create HTML pages.
ASP.NET Architecture
This section provides an overview of the ASP.NET infrastructure and the subsystem relationships. These
relationships are shown in the following illustration: Figure 1.3 Web Clients Windows 2000 Operating System
As shown, all Web clients communicate with ASP.NET applications through IIS. IIS deciphers the request,
authenticates, and finds the requested resource (such as an ASP.NET application). If authorized, it returns the
appropriate resource to the client. In addition to the built-in ASP.NET security features, an ASP.NET
application can use the Common Language Runtime low-level security features.
a) Integrating with IIS: This release of ASP.NET uses IIS 5.0 as the primary host environment. When
considering ASP.NET authentication, the interaction with IIS authentication services must be understood.
There are three different kinds of authentication in IIS 5.0: Basic, Digest, and Integrated Windows
Authentication. The type of authentication used can be set in the IIS administrative services. If a URL
containing an ASP.NET application is requested, both the request and information about authentication get
handed over to the application. ASP.NET provides two additional types of authentication: Cookie
authentication and Passport authentication.
b) Cookie-Based Authentication: Cookie authentication is a process that allows the application to collect
credentials directly from the client requestor (usually name and password), and determine their authenticity.
IIS authentication is not used by the application however, the IIS authentication settings are important to the
ASP.NET cookie authentication process. Unless the IIS “Anonymous Access” setting is enabled, requests
that do not meet the criteria for IIS authentication will be rejected and never reach the ASP.NET application.
c) Passport Authentication:: Passport authentication is a centralized authentication service provided by
Microsoft that offers a single sign-in and core profile services for member sites.
When a page is requested, it is loaded into the server memory, processed, and sent to the browser. Then it is
unloaded from the memory. At each of these steps, methods and events are available, which could be
overridden according to the need of the application. In other words, you can write your own code to override
the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except
the directives, are part of this control tree. You can see the control tree by adding trace= "true" to the page
directive. We will cover page directives and tracing under 'directives' and 'event handling'.
The page life cycle phases are:
• Initialization
• Instantiation of the controls on the page
• Restoration and maintenance of the state
• Execution of the event handler codes
• Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the
page life cycle. It also helps in writing custom controls and initializing them at right time, populate their
properties with view-state data and run control behavior code.
At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is
basically a function or subroutine, bound to the event, using declarative attributes such as Onclick or handle.
Following are the page life cycle events:
• PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack property and determines
whether the page is a postback. It sets the themes and master pages, creates dynamic controls, and gets
and sets profile property values. This event can be handled by overloading the OnPreInit method or
creating a Page_PreInit handler.
• Init - Init event initializes the control property and the control tree is built. This event can be handled by
overloading the OnInit method or creating a Page_Init handler.
• InitComplete - InitComplete event allows tracking of view state. All the controls turn on view-state
tracking.
• LoadViewState - LoadViewState event allows loading view state information into the controls.
• LoadPostData - During this phase, the contents of all the input fields are defined with the <form> tag are
processed.
• PreLoad - PreLoad occurs before the post back data is loaded in the controls. This event can be handled
by overloading the OnPreLoad method or creating a Page_PreLoad handler.
• Load - The Load event is raised for the page first and then recursively for all child controls. The controls
in the control tree are created. This event can be handled by overloading the OnLoad method or creating a
Page_Load handler.
• LoadComplete - The loading process is completed, control event handlers are run, and page validation
takes place. This event can be handled by overloading the OnLoadComplete method or creating a
Page_LoadComplete handler
• PreRender - The PreRender event occurs just before the output is rendered. By handling this event,
pages and controls can perform any updates before the output is rendered.
• PreRenderComplete - As the PreRender event is recursively fired for all child controls, this event
ensures the completion of the pre-rendering phase.
• SaveStateComplete - State of control on the page is saved. Personalization, control state and view state
information is saved. The HTML markup is generated. This stage can be handled by overriding the
Render method or creating a Page_Render handler.
• UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all
controls recursively and lastly for the page itself. Final cleanup is done and all resources and references,
such as database connections, are freed. This event can be handled by modifying the OnUnLoad method
or creating a Page_UnLoad handler.
We are using Visual studio 2017 to create web project. It includes the following steps:
Click on the file menu from the menu bar and select new -> project.
After selecting project types, now, it asks for the type of template that we want to implement in our application.
Here, we are selecting Web Forms as because we are creating a Web Forms application.
After clicking ok, it shows project in solution explorer window that looks like the below.
This project contains a default.aspx file which is a startup file. When we run the project this file executes first
and display a home page of the site.
We can see its output on the browser by selecting view in browser option as we did below.
Here, we are using the project that we created in last topic. To add a new web form in our existing project, first
select project then right click and add new item.
Select web forms option in left corner and then select web form and hit add button.
Now click on the add button and this form will add to our project.
After adding form, we can see that this is now in our project as we have shown in the below image.
00:00/05:29
59.6M
1.1K
Double click on this form and this will show some auto generated code like this:
// user-form.aspx
If we run this file on the browser, it does not show any output. So, let's print some message by this form.
// user-form.aspx
ASP.NET provides web forms controls that are used to create HTML components. These controls are
categories as server and client based. The following table contains the server controls for the web forms.
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.
Example
All the HTML Server controls can be accessed through the Request object.
ListBox It displays a list of items to the user. You can set the size from
Example
// htmlcontrolsexample.aspx
// htmlcontrolsexample.aspx.cs
using System;
namespace asp.netexample
{
public partial class htmlcontrolsexample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string a = Request.Form["Text1"];
Response.Write(a);
}
}
}
Output:
When we click the button after entering text, it responses back to client.
• Validation is an important concept to get a correct output as the user gives the input to web form must
be in proper format then only the server will result in meaningful output.
• Data entered by the user must perform validation before sending to the server for processing.
Definition
“Validation is checking whether the user has entered correct data or input or not and then process the request
and send it to the server for output.”
Note
Validation can be performed at the client-side as well as server-side.
• Client-side validation makes the process fast as there is less number of hits to the server.
• Server-side validation is used to remove the limitation of client browsers dependencies and scripting
language support.
Types of Validation
Validation can be classified into two types based on client and server validation:
2. Server-side Validation
The Validation controls are used for validating the data entered in Text Box(input) controls. When any user
enters the data on a text Box (web page) and submits the page on the server ,then validation controls are used to
check the data field entered by the user .if any data entered by the user is invalid (not correct format) then
validation control displays an error message on the screen. All the error message is defined as properties values
of validation controls. All the validation controls comes under System.UI.Webcontrols Namespace.
There are some validation controls ,that are used in ASP.NET.Which are given below :
1. The RequiredField Validator control
2. The RangeValidator control
3. The RegularExpressionValidator control
4. The CompareValidator control
5. The customValidator control
6. The Validationsummary control
Note:- This is used to specify the preceded character, how many time used.
5) The CustomValidator control:-
This validation control is used to customize and implement data validation according to our condition and
requirement.
Ex.
Suppose, if we want to check given number is even or odd then we can not use our existing controls.so that ,to
Button click.....................
{
if(Page.IsValid)
{
Label1.text="No Error";
}
else
{
Label1.text="Error";
}
}
Step1:- First open yore visual studio-->File-->New-->project--> Select ASP.NET Empty Website-->OK--
>Solution Explorer-->Add New Web form-->and drag and drop Label,Text Box ,Button and Validation
controls as shown below:-
Step2:- Now change then following things which are given below for every control:-
Step3:- Now Run the Application (press F5)-->and enter the required field as shown below:-
Step4:- Now Click the validate button--> then you will see the following output.
• View State
• Control State
• Session State
• Application State
1) View State :The view state is the state of the page and all its controls. It is automatically maintained
across posts by the ASP.NET framework. When a page is sent back to the client, the changes in the properties
of the page and its controls are determined, and stored in the value of a hidden input field named
_VIEWSTATE. When the page is again posted back, the _VIEWSTATE field is sent to the server with the
HTTP request.
The view state could be enabled or disabled for:
• The entire application by setting the EnableViewState property in the section of web.config file.
• A page by setting the EnableViewState attribute of the Page directive, as
• A control by setting the Control.EnableViewState property. It is implemented using a view state object
defined by the StateBag class which defines a collection of view state items. The state bag is a data structure
containing attribute value pairs, stored as strings associated with objects.
The StateBag class has the following properties:
Properties Description
1) Add(name, value) : Adds an item to the view state collection and existing item is updated.
2) Clear : Removes all the items from the collection.
3) Equals(Object) :Determines whether the specified object is equal to the current object.
4) Finalize : Allows it to free resources and perform other cleanup operations.
5) GetEnumerator : Returns an enumerator that iterates over all the key/value pairs of the StateItem objects
stored in the StateBag object.
6) GetType : Gets the type of the current instance.
7) IsItemDirty : Checks a StateItem object stored in the StateBag object to evaluate whether it has been
modified.
8) Remove(name): Removes the specified item.
9) SetDirty : Sets the state of the StateBag object as well as the Dirty property of each of the StateItem
objects contained by it.
10)SetItemDirty : Sets the Dirty property for the specified StateItem object in the StateBag object.
11)ToString : Returns a string representing the state bag object.
Control State
Session State
When a user connects to an ASP.NET website, a new session object is created. When session state is turned on,
a new session state object is created for each new request. This session state object becomes part of the context
and it is available through the page. Session state is generally used for storing application data such as
inventory, supplier list, customer record, or shopping cart. It can also keep information about the user and his
preferences, and keep the track of pending operations. Sessions are identified and tracked with a 120-bit
SessionID, which is passed from client to server and back as cookie or a modified URL. The SessionID is
globally unique and random. The session state object is created from the HttpSessionState class, which defines
a collection of session state items.
Application State
The ASP.NET application is the collection of all web pages, code and other files within a single virtual
directory on a web server. When information is stored in application state, it is available to all the users. To
provide for the use of application state, ASP.NET creates an application state object for each application from
the HTTPApplicationState class and stores this object in server memory. This object is represented by class file
global.asax. Application State is mostly used to store hit counters and other statistical data, global application
data like tax rate, discount rate etc. and to keep the track of users visiting the site.
1) Item(name) : The value of the application state item with the specified name. This is the default property of
the HttpApplicationState class.
2) Count : The number of items in the application state collection.
A theme is a collection of property settings that allow you to define the look of pages and controls, and then
apply the look consistently across pages in a Web application, across an entire Web application, or across all
Web applications on a server.
Themes are made up of a set of elements: skins, cascading style sheets (CSS), images, and other resources. At a
minimum, a theme will contain skins. Themes are defined in special directories in your Web site or on your
Web server.
Skins
A skin file has the file name extension .skin and contains property settings for individual controls such
as Button, Label, TextBox, or Calendar controls. Control skin settings are like the control markup itself, but
contain only the properties you want to set as part of the theme. For example, the following is a control skin for
a Button control:
Copy
You create .skin files in the Theme folder. A .skin file can contain one or more control skins for one or more
control types. You can define skins in a separate file for each control or define all the skins for a theme in a
single file.
There are two types of control skins, default skins and named skins:
• A default skin automatically applies to all controls of the same type when a theme is applied to a page. A
control skin is a default skin if it does not have a SkinID attribute. For example, if you create a default skin
for a Calendar control, the control skin applies to all Calendar controls on pages that use the theme.
(Default skins are matched exactly by control type, so that a Button control skin applies to
all Button controls, but not to LinkButton controls or to controls that derive from the Button object.)
• A named skin is a control skin with a SkinID property set. Named skins do not automatically apply to
controls by type. Instead, you explicitly apply a named skin to a control by setting the
control's SkinID property. Creating named skins allows you to set different skins for different instances of
the same control in an application.
A theme can also include a cascading style sheet (.css file). When you put a .css file in the theme folder, the
style sheet is applied automatically as part of the theme. You define a style sheet using the file name extension
.css in the theme folder.
Introduction
ASP.NET pages in website required designing separately. Unlike Windows application, there is no way we can
define common UI layout for ASP.NET pages. Using master pages, I can actually create the common UI
elements for all the web pages and create a consistent look and feel for my whole website. (Dreamweaver also
provides a similar feature in the form of Templates).
Consistent UI is the key to good user interface. Before Master pages, the way we created consistent web pages
was by using custom controls, CSS and JavaScript. With master pages, ASP.NET relieves the developer from
the burden of creating the consistent web pages. Master pages not only provide the mechanism for creating
consistent web pages, but also give us a centralized way of changing the UI elements that need to be changed
across all the pages of the website.
To visualize the Master page - Content page relationship, let's look at the following picture:
We will be looking at how to use master pages in our website to provide consistent UI for our website.
• Creating a set of controls that are common across all the web pages and attaching them to all the web pages.
• A centralized way to change the above created set of controls which will effectively change all the web
pages.
• Dynamically changing the common UI elements on master page from content pages based on user
preferences.
Terminology
Let us look at the basic terminology that needs to be understood before jumping into master pages:
• Masterpage: Gives us a way to create common set of UI elements that are required on multiple pages of our
website.
• ContentPage: The ASP.NET web page that will use master page to have the common UI elements displayed
on rendering itself.
• ContentPlaceHolder: A control that should be added on the MasterPage which will reserve the area for the
content pages to render their contents.
• ContentControl: A control which will be added on content pages to tell these pages that the contents inside
this control will be rendered where the MasterPage's ContentPlaceHolder is located.
Creating a MasterPage
4. We will now add a menu bar on this master page on top of the page. This Menu bar will be common to all
the pages (since it is in Masterpage).
5. Once we have menubar added, we can have content pages use the master page.
6. Let's add few content pages like default.aspx, about.aspx, Contact.aspx. (We are simply creating some
dummy pages with no functionality as we want to see the masterpage working, but these content pages can
have any level of complex logic in them).
7. When we add these content pages, we need to remember to select the option of "Use master Page".
Now let's look at the stuff that is important. When we look at the MasterPage, we will see that masterpage has
a ContentPlaceHolder control. All the code that is common for the content pages is outside
the ContentPlaceHolder control (in our case, a simple menubar).
ASP.NET
<!--<span class="code-comment"> Here we have content place holder where all content pages
will render their controls --></span>
<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
</asp:contentplaceholder>
</div>
If we look at our content pages, we will find a simple Content control added to each content page. This is the
area where we will be adding our controls to be rendered along with the master page. (In our case, just
simple strings.)
ASP.NET
Copy Code
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
Once we have all the master pages and content pages ready, we can test run our website.
So the common set of controls and behavior has now been added to all the content pages. We can have any
number of controls and functionality on the master pages.
There are times when we need to change some properties of master pages based on the current content page.
These properties could be related to visible aspects of master page like UI elements or they could be of
behavior aspects. The best way to do that is to have public properties in master pages that the individual content
pages can use to customize the look/behavior of master page for that particular master page.
Let us, in our small test website, have a label in master page that will tell the user about the current page. Let's
think of this label as breadcrumbs (just to illustrate there is no way, breadcrumbs should be created like this).
This label will display the string that is set by the Content page so we need to have a public property in the
master page to accomplish that.
C#
Copy Code
Now we can use this property to set the PageName property of master page from content pages.
One important thing to mention here is that if we want to use this property from our content page, then we need
to have a @Mastertype declaration in our content pages. This declaration will enable the content pages to use
the public properties of Master Pages.
XML
Copy Code
<%@ MasterType VirtualPath="~/MasterPageOne.master" %>
and from our content pages, we can simply set the property of the master page.
C#
Copy Code
//default.aspx
protected void Page_Load(object sender, EventArgs e)
{
this.Master.PageName = "/Default.aspx";
}
//about.aspx
protected void Page_Load(object sender, EventArgs e)
{
this.Master.PageName = "/About.aspx";
}
//contact.aspx
protected void Page_Load(object sender, EventArgs e)
{
this.Master.PageName = "/Contact.aspx";
}
and now if we run the website, we can see the label on master page showing the appropriate page name which
is being set by the content page.
Now there are scenarios when we want the user to change the layout of the website. Since our website's layout
is defined by the masterpage, to accomplish this we need the ability to change the master pages dynamically
from the code.
So to do this, let us add one more master page to the website. This master page will have the menu vertically
aligned on the left side unlike the first which has it on top.
• We need to have the option of changing the master page - let's have a new page change.aspx, we will place
radio button on this page to be able to change master page for this page.
• We need to save the current selected master page - let's save it in a session variable.
• Change the master page on the fly - We need to do it in Page_PreInit of content Page Change.aspx.
//global.asax
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["master"] = "~/MasterPageOne.master";
}
//change.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
RadioButtonList1.SelectedValue = Session["master"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["master"] = RadioButtonList1.SelectedValue;
//lets reload to see the change
Response.Redirect("Change.aspx");
}
Every ASP.NET web form control inherits the DataBind method from its parent Control class, which gives it an
inherent capability to bind data to at least one of its properties. This is known as simple data binding or inline
data binding.
Simple data binding involves attaching any collection (item collection) which implements the IEnumerable
interface, or the DataSet and DataTable classes to the DataSource property of the control.
On the other hand, some controls can bind records, lists, or columns of data into their structure through a
DataSource control. These controls derive from the BaseDataBoundControl class. This is called declarative
data binding.
The data source controls help the data-bound controls implement functionalities such as, sorting, paging, and
editing data collections.
The BaseDataBoundControl is an abstract class, which is inherited by two more abstract classes:
• DataBoundControl
• HierarchicalDataBoundControl
The abstract class DataBoundControl is again inherited by two more abstract classes:
• ListControl
• CompositeDataBoundControl
The controls capable of simple data binding are derived from the ListControl abstract class and these controls
are:
• BulletedList
• CheckBoxList
• DropDownList
• ListBox
• RadioButtonList
The controls capable of declarative data binding (a more complex data binding) are derived from the abstract
class CompositeDataBoundControl. These controls are:
• DetailsView
• FormView
• GridView
• RecordList
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.
Let us take up a small example to understand the concept. 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 (we
use the same DotNetReferences table as in the previous chapter).
Choosing a data source for the bulleted list control involves:
Example
Let us take the following steps:
Step (1) : Create a new website. Add a class named booklist by right clicking on the solution name in the
Solution Explorer and choosing the item 'Class' from the 'Add Item' dialog box. Name it as booklist.cs.
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace databinding
{
public class booklist
{
protected String bookname;
protected String authorname;
public booklist(String bname, String aname)
{
this.bookname = bname;
this.authorname = aname;
AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
<tr>
<td style="width: 228px; height: 40px;">
<asp:Label ID="lbllistbox" runat="server"></asp:Label>
</td>
<tr>
<td style="width: 228px; height: 21px">
</td>
<tr>
<td style="width: 228px; height: 21px">
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
AutoPostBack="True" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
</td>
<tr>
<td style="width: 228px; height: 21px">
<asp:Label ID="lblrdlist" runat="server">
</asp:Label>
</td>
</div>
</form>
Step (3) : Finally, write the following code behind routines of the application:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
IList bklist = createbooklist();
if (!this.IsPostBack)
{
this.ListBox1.DataSource = bklist;
this.ListBox1.DataTextField = "Book";
this.ListBox1.DataValueField = "Author";
this.DropDownList1.DataSource = bklist;
this.DropDownList1.DataTextField = "Book";
this.DropDownList1.DataValueField = "Author";
this.RadioButtonList1.DataSource = bklist;
this.RadioButtonList1.DataTextField = "Book";
this.RadioButtonList1.DataValueField = "Author";
this.CheckBoxList1.DataSource = bklist;
this.CheckBoxList1.DataTextField = "Book";
this.CheckBoxList1.DataValueField = "Author";
this.DataBind();
}
}
return allbooks;
}
Navigation controls
Navigation controls are very important for websites.Navigation controls are basically used to navigate the user
through webpage .It is more helpful for making the navigation of pages easier .There are three controls in
ASP.NET ,Which are used for Navigation on the webpage.
1. TreeView control
2. Menu Control
3. SiteMapPath control
There are some Namespaces, which are used for above Navigation controls which are given below:
Using.System.Web.UI.WebControls.TreeView ;
Using.System.Web.UI.WebControls.Menu ;
Using.System.Web.UI.WebControls.SiteMapPath ;
Step 1: First open your visual studio-->File-->New-->Website-->Select ASP.NET Empty Website -->OK--
>open solution explorer-->Add New Web Form-->Drag and Drop TreeView control from Toolbox as sown
below:
Step 2: Now go properties of TreeView control-->Click Nodes-->Add Root and child Node as shown below:
output:
Step 2:Now Drag and drop TreeView control on the Web Form --> Now Choose Data Source from TreeView
control-->Select New data source as shown below:
Step 5: Now click Edit TreeNode DataBindings..-->Select each page one by one -->and click Add button --
>set TextField =title from right side for each page-->click Apply as sown below:
Step 2: Open web.sitemap file and write the following codes.which are given below-->Save
</siteMap>
Step 3: Now drag and drop TreeView control on the Form-->Now choose Data Source-->select New data
source-->Select SiteMap as sown below:
▪ Static menu:- It is used to display the parent menu items and their sub menu items on the page. Means
it is used to display the entire structure of the static menu.
▪ Dynamic menu:- It is used to display the static menu as well as dynamic menu on the site.it
Means when user passes the mouse over the menu then it will appear on the site.
2.1 ) Static Menu:-
We can display site structure vertically as well as horizontally through static menu control on the site.There are
some steps to implement the static menu control on the Web Form.Which are given below:Step 1: First Add a
New Web Form in solution Explorer -->drag and drop menu control on the Form-->now select Views =
static as shown below:
Step 2: Now click Edit Menu Items...-->Add parent and child nodes as shown below:
Step 1: First Add a Web Form in the solution Explorer-->Drag and drop menu control on the Form -->choose
Data Source -->Select XML File-->OK-->Browse XML File-->OK.
Step 2: Now click Edit TreeNode DataBindings..-->Select each page one by one -->and click Add button --
>set TextField =title from right side for each page-->click Apply as sown below:
</siteMap>
Step 2:Now drag and drop SiteMapPath control on the web Form (SiteMap.aspx)-->Now drag and
drop HyperLink control on the Form as shown below:
Step 3: Now Add three more Web Form (page1.aspx ,page2.aspx, page3.aspx) in Solution Explorer--
>Go properties of HyperLink Button control -->set NavigateUrl-->Write Text Information ,as shown below:
Step 4: Now Go page1.aspx -->drag and drop SiteMapPath control and HyperLink control on the Form as
shown below-->Set the NavigateUrl of each HyperLink control as previous i have done.
Introduction
ASP.NET 2.0 provides built in controls to manage Membership in Web Applications. All these controls use
ASP.NET providers that are loaded via web.config file. Membership provider and Role provider allow a
complete system to maintain users information, authenticate and authorize the users. This article demonstrates
how to use and configure the default Member ship and Role provider.
Initially by using the Visual Studio 2005/2008/2010, create an ASP.NET website/web application. If you are
using Visual Studio 2010, login and registration pages are available by default in the application. Create
Registration page and then drag the Create User Wizard control from the Login controls section of the Toolbox.
Now to store the user information, we need to create the database in the SQL Server. Follow the steps given
below to use built in user store schema for maintaining the user information.
1. Go to Visual Studio, Visual Studio tools and then open the Visual Studio Command Prompt.
2. Use the aspnet_regsql.exe command to run the ASP.NET SQL Server Setup Wizard.
3. Check the option “Configure SQL Server for application services”.
4. Select the Server Instance and the database name for the application, if the database name is not
provided, default aspnetdb database is created.
5. Click the confirm settings and finish button to create the database store.
Step 1:
Step 2:
Step 3:
Step 4:
Step 5:
Preparing to build the security system for use in application, we need to configure the membership provider
in web.config file. The following settings for Forms Authentication, Membership and Role provider are applied
in the web.config file.
The authentication mode under system.web tag is set to “Forms” and the elements included in
are loginUrl, defaultUrl, timeout, cookieless and protection which specifies the login page URL, default page
URL, cookie expiration time and protection level respectively. The settings in web.config file would look
similar to the code shown below:
<authentication mode="Forms">
<forms cookieless="UseCookies" defaultUrl="HomePage.aspx"
loginUrl="UnAuthorized.aspx" protection="All" timeout="30">
</forms>
</authentication>
Some of the important elements to be considered in the Membership provider are name – name of the provider,
type – namespace of the provider, connectionStringName – name of the connectionstring and the most
important password format. The password format is available in three formats, Hashed, Encrypted and Clear.
Hashed format provides one way of storing password in encrypted format which cannot be brought back to
original state, whereas Encrypted format provides both to encrypt and decrypt the password.
<membership defaultProvider="Demo_MemberShipProvider">
<providers>
<add name="Demo_MemberShipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="cnn"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="5"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10" passwordStrengthRegularExpression="">
</providers>
</membership>
The similar way is to specify the settings for default Provider under system.web tag of the web.config file as
shown below. The settings are simple and self explanatory.
In the login.aspx and Registration.aspx pages, we need to use the providers to complete the membership system
for the application.
Registration page for the users can be easily created by using the available create user wizard and the following
event handlers:
The users can be authenticated by using the login_Authenticate event of the Login control. The code to
authenticate users goes here:
In the Admin Panel, the features to Add, Edit, Delete and Assign Roles to users are provided to the
administrator.
BindRoles
The BindRoles method is used to bind the available roles in the store to the user control.
BindUsers
The BindUsers method is used to bind the available users in the store to the user control.
The available roles can be assigned to the user in the following way:
else
{
Label1.Text = "Role(s) Already Assigned To User";
}
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
You can remove the user from a role in the following manner:
Delete Roles
The code is used to delete the existing Roles, if they are not in use.
Restrict the users depending on the roles by using web.config settings as follows:
<authorization
<allow roles ="Admin"/>
<deny users ="*"/>
</authorization>
In the above code, if you write deny users =”*” and then allow roles =”Admin”, there seems to be no
difference, but the code wouldn’t work for you because writing the deny user =”*” at the beginning would even
restrict the admin to access the folders.
if (Roles.IsUserInRole("Admin"))
{
Menu1.Items[0].Text = "Admin";
}
else
{
Menu1.Items[0].Text = "";
}
Introduction :- You already Know ,Internet is emerging as the most widely used medium for performing
various tasks,such as online shopping ,Data exchanging and bank transactions etc. All this Information and data
need to be secured against unauthorized access from malicious and illegal sources . For this purpose, we use
authentication and authorization process. You can learn more from below about authentication and
authorization in asp.net application.
▪ Windows Authentication
▪ Form Based Authentication
You already know, we need to write large piece of code to create forms and user interfaces for authenticating
the user and displaying the desired page based on the roles or rights given to the user.But It is very time
consuming so that Microsoft developed a new series of server controls ,called login controls.
To use login controls in your website. You just need to drag and drop them on the web page.
There is no need to write more codes in the codes-behind file.The Login controls have built in functionality for
authentication and authorization of users.Microsoft were introduced (started) this services with ASP.NET 2.0.
This control help to build the registration and login application without writing any code-behind codes and
database.
1. Login
2. LoginView
3. LoginStatus
4. Loginname
5. PasswordRecovery
6. ChangePassword
7. CreateUserWizard
1) The Login Control:-
The Login control provides a user interface which contains username and password, that authenticate the
usernaMe and password and grant the access to the desired services on the the basis of the credentials.
There are used some methods ,properties and events in this Login control,You can check manually after drag
and drop this control on your web form as given below:-
▪ Anonymous Template :- This template (default of all) will be displayed when any user just open the
web page but not logged in.
▪ LoggedInTemplate:- This Template (page)will be displayed when the user in logged in.
▪ RoleGroups:- This template will be displayed when user logged in, that is the member of the specific
role (defined role group).
You can drag and drop Loginview Control on the web page from toolbox as shown below:-
Note:- You can do so, by adding any server controls such as Label ,Hyperlink and TextBox, to the empty
region on the loginview control.
Note :-
▪ To retrieve and reset password you must set some properties inside the asp.net Membership services.
▪ You can can learn its methods ,properties and events from PasswordRecovery class yourself.
6) CreateUserWizard control:-
This control uses the membership service to create a new user in the membership data store.The
CreateUserWizard control is provides by the CreateUserWizard class and can be customized by using
template and style properties .Using this control any user can easily create an account and login to the web
page.
You can drag and drop CreateUserWizared control on the web page as shown below:-
There are some steps to use Login controls concepts in ASP.NET Application as given below:-
Step 1 :- First open your visual studio -->File -->New -->Select ASP.NET Empty website --> OK -->Open
Solution Explorer -->Add a New web form (login.aspx) -->Now drag and Drop Login control and and
LoginView control on the page from toolbox --> Add a Hyperlink control in LoginView 's blank space as
shown below:-
Step 2 :- Now open Solution Explorer --> Add a New web Form (Registrationpage.aspx) --> Drag and drop
CreateUserWizard and LoginView controls on the page --> Put a Hyperlink control inside blank space in
LoginView control as shown below:-
▪ Now select Complete from createUserWizard Tasks as shown above --> Now double click on
Continue button and write the following c# codes for Navigation as given below:-
c# codes:-
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
}
protected void ContinueButton_Click(object sender, EventArgs e)
{
Response.Redirect("login.aspx");
}
}
NOTE :- You can set this Navigation URL from the properties of Continue button also instead of this above
codes.
Step 3 :- Now Add a New Web Form (welcomwpage.aspx) --> drag and drop LoginName,LoginStatus and
LoginView Controls on the page from toolbox as shown below:-
Step 4 :- Now Add again a New Web Form (changepassword.aspx)-->drag and drop ChangePassword control
on the page from toolbox as shown below:-
Step 5 :- Now Add a New web form (PasswordRecovery.aspx) -->drag and drop Passwordrecovery control
from toolbox as shown below:-
Step 6 :- Now open web.config file and write the following codes as given below:-
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl ="login.aspx"
defaultUrl = "Welcomepage.aspx" />
</authentication>
<authorization>
<allow users="*"/>
</authorization>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
</configuration>
Step 7 :- Now Run the Application (Press F5) --> Now create a account first for access the website --> Press
Create User button --> After that Press Continue button as shown below:-
Step 8 :- After step 7, login.aspx page will be opened --> Now put login credentials such as username and
password --> Press login button --> You will see the following output as shown below:-
Note :-
▪ If you want to change old password , you can change it. I have already built it in this application.
▪ If you want to recover your password then you can dot it also.
▪ You can download this whole application from below and run it on your visual studio.
▪ In Next tutorial , I will put administrative and role based security in this application,First learn this whole
concepts otherwise you can face some problems in next tutorial.
▪ You can also customize this application according to you .
Securing Applications
Implementing security in a site has the following aspects:
1) Authentication : It is the process of ensuring the user's identity and authenticity. ASP.NET allows four
types of authentications:
• Windows Authentication
• Forms Authentication
• Passport Authentication
• Custom Authentication
2) Authorization : It is the process of defining and allotting specific roles to specific users.
3) Confidentiality : It involves encrypting the channel between the client browser and the web server.
4) Integrity : It involves maintaining the integrity of data. For example, implementing digital signature.
Forms-Based Authentication
Traditionally, forms-based authentication involves editing the web.config file and adding a login page with
appropriate authentication code.
Observe that the FormsAuthentication class is responsible for the process of authentication. However, Visual
Studio allows you to implement user creation, authentication, and authorization with seamless ease without
writing any code, through the Web Site Administration tool. This tool allows creating users and roles. Apart
from this, ASP.NET comes with readymade login controls set, which has controls performing all the jobs for
you.
Step 1 : Choose Website -> ASP.NET Configuration to open the Web Application Administration Tool.
Step 3 : Select the authentication type to 'Forms based authentication' by selecting the 'From the Internet' radio
button.
Step 4 : Click on 'Create Users' link to create some users. If you already had created roles, you could assign
roles to the user, right at this stage.
Step 5 : Create a web site and add the following pages: Welcome.aspx Login.aspx CreateAccount.aspx
PasswordRecovery.aspx ChangePassword.aspx
Step 6 : Place a LoginStatus control on the Welcome.aspx from the login section of the toolbox. It has two
templates: LoggedIn and LoggedOut. In LoggedOut template, there is a login link and in the LoggedIn
template, there is a logout link on the control. You can change the login and logout text properties of the control
from the Properties window.
Step 7 : Place a LoginView control from the toolbox below the LoginStatus control. Here, you can put texts and
other controls hyperlinks, buttonsetc. , which are displayed based on whether the user is logged in or not. This
control has two view templates: Anonymous template and LoggedIn template. Select each view and write some
text for the users to be displayed for each template. The text should be placed on the area marked red.
Step 8 : The users for the application are created by the developer. You might want to allow a visitor to create a
user account. For this, add a link beneath the LoginView control, which should link to the CreateAccount.aspx
page. Step
9 : Place a CreateUserWizard control on the create account page. Set the ContinueDestinationPageUrl property
of this control to Welcome.aspx.
Step 10 : Create the Login page. Place a Login control on the page. The LoginStatus control automatically
links to the Login.aspx. To change this default, make the following changes in the web.config file. For
example, if you want to name your log in page as signup.aspx, add the following lines to the section of the
web.config:
Step 11 : Users often forget passwords. The PasswordRecovery control helps the user gain access to the
account. Select the Login control. Open its smart tag and click 'Convert to Template'. Customize the UI of the
control to place a hyperlink control under the login button, which should link to the PassWordRecovery.aspx.
Step 12 : Place a PasswordRecovery control on the password recovery page. This control needs an email server
to send the passwords to the users.
Step 13 : Create a link to the ChangePassword.aspx page in the LoggedIn template of the LoginView control in
Welcome.aspx.
Step 14 : Place a ChangePassword control on the change password page. This control also has two views. Now
run the application and observe different security operations. To create roles, go back to the Web Application
Administration Tools and click on the Security tab. Click on 'Create Roles' and create some roles for the
application. Click on the 'Manage Users' link and assign roles to the users.
IIS Authentication:
SSL The Secure Socket Layer or SSL is the protocol used to ensure a secure connection. With SSL enabled, the
browser encrypts all data sent to the server and decrypts all data coming from the server. At the same time, the
server encrypts and decrypts all data to and from browser. The URL for a secure connection starts with HTTPS
instead of HTTP. A small lock is displayed by a browser using a secure connection. When a browser makes an
initial attempt to communicate with a server over a secure connection using SSL, the server authenticates itself
by sending its digital certificate. To use the SSL, you need to buy a digital secure certificate from a trusted
Certification Authority CA and install it in the web server. Following are some of the trusted and reputed
certification authorities: www.verisign.com www.geotrust.com www.thawte.com SSL is built into all major
browsers and servers. To enable SSL, you need to install the digital certificate. The strength of various digital
certificates varies depending upon the length of the key generated during encryption. More the length, more
secure is the certificate, hence the connection. Strength Description 40 bit Supported by most browsers but easy
to break. 56 bit Stronger than 40-bit. 128 bit Extremely difficult to break but all the browsers do not support it.
What is Caching?
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.
Caching in ASP.Net
The OutputCache directive has the following attributes, which helps in controlling the behaviour of the output
cache:
Location
Any Any: page may be cached
anywhere.
Client
Client: cached content remains
Downstream
at browser.
Server
Downstream: cached content
None stored in downstream and server
both.
Server: cached content saved
only on server.
None: disables caching.
Let us add a text box and a button to the previous example and add this event handler for the button.
protected void btnmagic_Click(object sender, EventArgs e)
{
Response.Write("<br><br>");
Response.Write("<h2> Hello, " + this.txtname.Text + "</h2>");
}
Change the OutputCache directive:
<%@ OutputCache Duration="60" VaryByParam="txtname" %>
When the program is executed, ASP.NET caches the page on the basis of the name in the text box.
Data Caching
The main aspect of data caching is caching the data source controls. We have already discussed that the data
source controls represent data in a data source, like a database or an XML file. These controls derive from the
abstract class DataSourceControl and have the following inherited properties for implementing caching:
• CacheDuration - It sets the number of seconds for which the data source will cache data.
• CacheExpirationPolicy - It defines the cache behavior when the data in cache has expired.
• CacheKeyDependency - It identifies a key for the controls that auto-expires the content of its cache
when removed.
• EnableCaching - It specifies whether or not to cache the data.
Example
To demonstrate data caching, create a new website and add a new web form on it. Add a SqlDataSource control
with the database connection already used in the data access tutorials.
For this example, add a label to the page, which would show the response time for the page.
<asp:Label ID="lbltime" runat="server"></asp:Label>
Apart from the label, the content page is same as in the data access tutorial. Add an event handler for the page
load event:
protected void Page_Load(object sender, EventArgs e)
{
lbltime.Text = String.Format("Page posted at: {0}", DateTime.Now.ToLongTimeString());
}
The designed page should look as shown:
When you execute the page for the first time, nothing different happens, the label shows that, each time you
refresh the page, the page is reloaded and the time shown on the label changes.
Next, set the EnableCaching attribute of the data source control to be 'true' and set the Cacheduration attribute
to '60'. It will implement caching and the cache will expire every 60 seconds.
The timestamp changes with every refresh, but if you change the data in the table within these 60 seconds, it is
not shown before the cache expires.
<asp:SqlDataSource ID = "SqlDataSource1" runat = "server"
ConnectionString = "<%$ ConnectionStrings: ASPDotNetStepByStepConnectionString %>"
ProviderName = "<%$ ConnectionStrings: ASPDotNetStepByStepConnectionString.ProviderName %>"
SelectCommand = "SELECT * FROM [DotNetReferences]"
EnableCaching = "true" CacheDuration = "60">
</asp:SqlDataSource>
Object Caching
Object caching provides more flexibility than other cache techniques. You can use object caching to place any
object in the cache. The object can be of any type - a data type, a web control, a class, a dataset object, etc. The
item is added to the cache simply by assigning a new key name, shown as follows Like:
Cache["key"] = item;
ASP.NET also provides the Insert() method for inserting an object to the cache. This method has four
overloaded versions. Let us see them:
Overload Description
Cache.Insert((key, value); Inserts an item into the cache with the key
name and value with default priority and
expiration.
Sliding expiration is used to remove an item from the cache when it is not used for the specified time span. The
following code snippet stores an item with a sliding expiration of 10 minutes with no dependencies.
Cache.Insert("my_item", obj, null, DateTime.MaxValue, TimeSpan.FromMinutes(10));
Example
Create a page with just a button and a label. Write the following code in the page load event:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
lblinfo.Text += "Page Posted Back.<br/>";
}
else
{
lblinfo.Text += "page Created.<br/>";
}
if (Cache["testitem"] == null)
{
lblinfo.Text += "Creating test item.<br/>";
DateTime testItem = DateTime.Now;
lblinfo.Text += "Storing test item in cache ";
lblinfo.Text += "for 30 seconds.<br/>";
Cache.Insert("testitem", testItem, null,
DateTime.Now.AddSeconds(30), TimeSpan.Zero);
}
else
{
lblinfo.Text += "Retrieving test item.<br/>";
DateTime testItem = (DateTime)Cache["testitem"];
lblinfo.Text += "Test item is: " + testItem.ToString();
lblinfo.Text += "<br/>";
lblinfo.Text += "<br/>";
}
When the page is loaded for the first time, it says:
Page Created.
Creating test item.
Storing test item in cache for 30 seconds.
If you click on the button again within 30 seconds, the page is posted back but the label control gets its
information from the cache as shown
XML - Overview
XML stands for Extensible Markup Language. It is a text-based markup language derived from Standard
Generalized Markup Language (SGML).
XML tags identify the data and are used to store and organize the data, rather than specifying how to display it
like HTML tags, which are used to display the data. XML is not going to replace HTML in the near future, but
it introduces new possibilities by adopting many successful features of HTML.
There are three important characteristics of XML that make it useful in a variety of systems and solutions −
• XML is extensible − XML allows you to create your own self-descriptive tags, or language, that suits your
application.
• XML carries the data, does not present it − XML allows you to store the data irrespective of how it will
be presented.
• XML is a public standard − XML was developed by an organization called the World Wide Web
Consortium (W3C) and is available as an open standard.
XML Usage
What is Markup?
XML is a markup language that defines set of rules for encoding documents in a format that is both human-
readable and machine-readable. So what exactly is a markup language? Markup is information added to a
document that enhances its meaning in certain ways, in that it identifies the parts and how they relate to each
other. More specifically, a markup language is a set of symbols that can be placed in the text of a document to
demarcate and label the parts of that document.
Following example shows how XML markup looks, when embedded in a piece of text −
<message>
<text>Hello, world!</text>
</message>
This snippet includes the markup symbols, or the tags such as <message>...</message> and <text>... </text>.
The tags <message> and </message> mark the start and the end of the XML code fragment. The tags <text>
and </text> surround the text Hello, world!.
A programming language consists of grammar rules and its own vocabulary which is used to create computer
programs. These programs instruct the computer to perform specific tasks. XML does not qualify to be a
programming language as it does not perform any computation or algorithms. It is usually stored in a simple
text file and is processed by special software that is capable of interpreting XML.
How to Create Crystal Reports in ASP.NET Webforms
We are using Visual Studio 2013 and SAP Crystal Reports for Developer Edition to Visual Studio.
In the Previous Tutorial, we learnt how to use OLE DB (ADO) connection. For this example let us
choose ADO.NET Dataset. To use ADO.NET Dataset we need to create a dataset in our project. To do that
follow the following steps
Dataset Designer
This will bring up Choose your data connection wizard. The drop-down will display the already created
connections. To Create a new connection, click on the New Connection
Add Connection
The next dialogue box is Add Connection dialogue box. The first Option in this screen is data source which,
is as you can see is displayed as Microsoft SQL Server (SQL Client). If you wish to change it to some other
provider then, click on Change. That will take you to the list of available Data Source Select the appropriate
one for your project and Click OK
Since we are connecting to the SQL server database let us choose to cancel
1. In Server Name field enter name of your SQL Server Instance Name
2. Under authentication, you can either choose windows authentication or specify user ID & Password. I
will choose Windows Authentication
3. Select database Name. Select NorthWInd
4. Click on Test Connection to verify Connection
5. Click on OK to finish
We are taken back to the Choose your data Connection window
Connection Added
The new connection which we created in the previous step appears on drop down. Expand the plus right below
connection drop-down see the connection string
Save
the connection
You will be prompted to whether you wish to add this connection to the web.config file. Select yes and
click Next. This will bring up Choose your Command Type Dialog Box
Choose your Command Type
Here you are given three options to select the Command Type
Here you are prompted for the SQL statement. Enter our query as
Click on Next. This will take us to the Choose methods to Generate dialogue box
Now we have created our dataset. We are now ready to connect this dataset to our crystal report
Reference Added
1. CrystalDecisions.CrystalReports.Engine
2. CrystalDecisions.ReportSource
3. CrystalDecisions.Shared
4. Bind the Dataset to Crystal Report and Add Fields
Database Expert
Now we need to connect this report to the dataset we created. Locate and Open the crystal
Report rptCustomerList. To Connect to the dataset do the following
Attach Dataset
Add
Fields to the Report
The next step is to add the fields to the report. To do this follow these steps
1. Go to Fields Explorer.
You will notice that the customer table which has added here appears here with all the fields.
The next step is to create a web form to show the report. To do this follow these steps
1. Go to Project Right-click
2. Click on Add
3. Click on New Item
4. Add New Wizard Appears
5. Select Web
6. Select Webform
7. Name it as default.aspx
Click on add to create the form
Add a Button
The next step is to add crystal Viewer control to our form. To do this
2 Using CrystalDecisions.CrystalReports.Engine;
3 Using CrystalDecisions.Shared;
First, We need to Fill the data table with the Customers data. To do that Create an instance of Table Adapter
CustomersTableAdapter and invoke the Fill Method to Fill the data.
Create the rpt object, which is an instance of our rptCustomerList. Note the rptCustomerList is the name of
the Crystal Report, which we had created in step 3. Assigning the Dataset ds to Report using the
method SetDataSource. The object rpt is our Report.
Crystal Report Viewer control’s job is to display the report. All we need to do is to assign the report to
the ReportSource Property of the Crystal Report Viewer Control (CrystalReportViewer.ReportSource = rpt).
Now our Crystal Report Viewer is ready to display our report.
Finally, store our Report in the Session using Session.Add(“report”, rpt). The Report object is retrieved from
the Session and assigned to the ReportSource Property of the CrystalReportViewer Control when the page is
refreshed or user navigates from one page to another. This is done from the Page_Init event.
Finally, our code looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
namespace CrWebFormsApp {
rptCustomerList rpt;
if (Session["report"] != null)
CrystalReportViewer1.ReportSource
=(rptCustomerList)Session["report"];
CustomerTableAdapters.CustomersTableAdapter
da = new
CustomerTableAdapters.CustomersTableAdapter();
Customer.CustomersDataTable
dt=(Customer.CustomersDataTable)
ds.Tables["Customers"];
da.Fill(dt);
rpt.SetDataSource(ds);
CrystalReportViewer1.ReportSource = rpt;
Session.Add("report", rpt);
Source Code
You can download the source code from the GitHub. The Source code is made using Visual Studio 2015
Community Edition and SAP Crystal Reports Developer Edition for Visual Studio Service Pack 17
The sample database Northwind can found from CodePlex
Run Crystal Reports Under 64 Bit IIS.
Go to Tools -> Option then select Project and Solutions -> Web Projects and tick on the option “Use the 64-bit
version of IIS Express for web sites and projects”