You are on page 1of 353

ASP.NET 3.

5 With C#

Pragati Software Pvt. Ltd.


312, Lok Center, Marol-Maroshi Road Andheri (East), Mumbai 400 059, India. Tel.: +91-22 3091 0000 (100 Lines) www.pragatisoftware.com

265.03.01

ASP.NET 3.5 With C#


Pragati Software Pvt. Ltd. www.pragatisoftware.com

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

Index
Module 1 Module 2 Module 3 Module 4 Module 5 Module 6 Module 7 Module 8 Module 9 Module 10 Module 11 Module 12 Module 13 Module 14 : Introduction to ASP.NET 2008 : WebForm Controls : Validation Controls : ADO.NET Architechture : DataSource Controls : DataBound Controls : Navigation Controls : Themes and Master Pages : State Management : Caching : Security : Login controls and Membership API : Configuration, Administration, and Deployment : Web Services
2

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

Module 1: Introduction to ASP.NET 2008


Overview
What is Web Application? What is Web Server - IIS? Visual Studio IDE 2008 Response / Request Model

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

What is a Web Application?


Web application is the one that runs on a web server and is made available to the entire world. ASP.NET is the technology which is used to create a web application.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

What is Web Server IIS?


Web server is the one that hosts the application. IIS (Internet Information Services) is the web server required to host asp.net web applications.
IIS (Web Server) .Net Framework

Browser (Client)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

IIS (Internet Information Services): It is a web server required to host ASP.NET web applications. The .NET Framework registers ASP.NET in IIS automatically if IIS already exists on the system. If not then we require a tool called as aspnet_regiis.exe to register ASP.NET in IIS. A virtual directory exists which is mapped to a physical directory Drive:\Inetput\wwwroot.

Visual Studio 2008 IDE

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

To create a new website in Visual Studio 2008 IDE, go to File -> New -> Web Site. The above dialog box will be displayed. We need to specify the following things: a)Location: The location option allows to choose the types of website can be created with .NET. a) File System:This is the option where built in Web Server provided by microsoft with Visual Studio 2008 IDE is used. The web application is directly created in file system folders. One need not to have IIS installed on the machine. But this will run the web site locally. It can not run it on other systems. It is meant for testing pages. b) HTTP: This option creates a website on local IIS Web Server. The pages and folders are stored in to the folder created under the default web site which is physically mapped to [drive]:\Inetpub\wwwroot. We need not to do any configuration settings for ASP.NET websites with IIS as they are automatically done by Visual Studio. One requires administrative privileges to run the website on an IIS Web Server. If we want to create our websites in the folder on a different drive then we can create a virtual directory that maps to the physical folder. c) FTP: One can create a web site on FTP server on which read / write permissions are available. b)Language: We can choose either Visual Basic or Visual C# to create a website.

Html Source View

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

When a web site will be created, this is the way a web page will be displayed. By default, a web page or a web form with the name Default.aspx will get created. There are three views of a web page. 1)Design View where one can drag and drop controls available from the Tool Box and design the Web Page. 2)Source View where the HTML Source of the web page is available. Whatever control is dropped on the web form, html source for the same is generated automatically in the source view. 3)Split View that divides the screen in two parts showing both the views. Html source of a web page contains a Page Directive. The following is the code for it. <%@Page Language="C# AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> Explanation for Page Directive: The @Page directive specifies the settings used by the web page. Language Attribute: Specifies the language used when compiling all the inline codes and code declaration blocks. Only one language can be used per page. We can use any .NET Framework supported language. AutoEventWireup attribute: This tells that whether page events are wired up automatically or not. By default this attribute has true value. CodeFile Attribute: This attribute refers to the code behind file associated with the page. It takes the name of code behind file as a value. It is used together with Inherits attribute. Inherits Attribute: It defines the code behind class for a page to inherit.

Design View

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

(Source: Module1\01Intro.aspx) (Source: Module1\01Intro.aspx.cs)

Code View

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

The code file will be carrying the name as Default.aspx.cs for Csharp and Default.aspx.vb for Visual Basic.

Running Web Application

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

10

To run the web site either go to Debug > Start Debugging or press F5 key. When we will run the web application for the first time, we will get this dialog box asking us to enable the debugging for the web site. By default, it is disabled in the Web.Config file. To enable the first option is selected and to run the website without debugging second option is selected. We can run our website without debugging by pressing Ctrl+F5 combination key.

10

Web Page Code Models


Code Behind Model Single File Code Model

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

11

11

Web Page Code Models Contd(Single File)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

12

(Source: Module1\02SingleFileCodeModelEg.aspx) In the Single File Code model the HTML Markup, Server Control markup and code are placed into one single file. This file has the extension .aspx.

12

Web Page Code Models Contd(Code Behind)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

13

In this model, HTML markup and Server Control markup appears in .aspx file and the code appears in .aspx.cs or .aspx.vb file.

13

Request
Client sends a Request to the Server.

Request

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

14

14

Response
Server gives response to the clients

Response

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

15

15

ASP.NET Compilation
Multiple languages are supported. Automatic Compilation. Deployment

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

16

Compilation: ASP.NET applications are compiled into MSIL (Microsoft Intermediate Language) and files are generated with the extensions .dll. It has certain features: Multiple Language Support: To create ASP.NET applications, we can use languages like VB, C#. We can also have code written in different languages into one application. They get compiled into different assemblies. To separate the code written in different languages, we need to create different sub folders for different languages. ASP.NET gives a folder called as App_Code to store all code files for the application. Automatic Compilation: The application code and any other dependencies gets automatically compiled when user requests the page for the first time. It creates an assembly for each application directory and one for the main directory. Separate assemblies are created for the code written in different languages. Deployment: ASP.NET provides PreCompilation option to compile the website before it has been deployed or after it gets deployed but before the first user requests it. Precompilation provides certain benefits like it improves the performance as the compiled version already exists when the first user requests it. It also helps to debug the errors before it is requested which otherwise would have arrived on the first request.

ASP.NET Folders Overview


ASP.NET provides applications folders which help organize the website. The Folders such as:
App_Browsers App_Code App_Data App_GlobalResources App_LocalResources App_Themes App_WebReferences Bin

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

17

Application Folders available with ASP.NET: App_Browsers: It contains browser definitions that allows users to identify different browser capabilities. App_Code: It stores the source code i.e. business objects created with either VB or C#. App_Data: It is used to store data files like .mdb for MsAccess or .mdf for SQL Server to work with SQLExpress, the in built data server. App_GlobalResources: Stores resource files such as .rsex or .resources files that are compiled in to assemblies with global scope. App_LocalResources: It stores resource files for individual pages or user controls. App_Themes: Themes are used to give consistent look to the controls on the web pages. They store .skin files which contain formatting instructions for different applications. App_WebReferences: Contains references to web services. Bin: Contains compiled assemblies for controls, components or the code that is referred into the assembly.

Module 2: WebForm Controls


Overview
Using HTML Controls ASP.NET Server Controls IsPostBack Property List controls AutoPostBack Property

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

18

18

ASP.NET Server Controls


HTML Controls Web Server Controls User Controls

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

19

HTML Controls: Represents HTML elements in the form of a control. Used when the HTML pages are migrated. Especially used when old version ASP application is migrated to ASP.NET. All HTML control classes reside under the namespace called as System.Web.UI.HtmlControls. Web Server Controls: They are feature rich controls than HTML controls. They are used when we want to bind the data, creating templates etc. The classes for Web Server Controls are available in the namespace System.Web.UI,WebControls. User Controls: It is used to create a custom control which provides reusability.

19

IsPostBack Property

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

20

(Source Code: Module2\01IsPostBack.aspx) When the user submits the data and sends it back to the server is called as PostBack. And when the page is posted back, the page is generated again and it fires load event. The code written for this event is executed again. Due to this the data loss may happen. IsPostBack property is given by the Page class. This is used to check whether the page is loaded for the first time or because of PostBack to the server. It is a boolean property. Using this property we can decide upon whether the code will be executed only once on the first load or on every post back. Controls taken for design: Label : It is used to display a static text on the page. Button : Has the submit behavior. When user clicks the button, the page is sent to the server automatically.

Controls Label

Properties ID Text

Value lblDisplay (Blank)

20

IsPostBack Property Example Contd


public partial class _01IsPostBackEg : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { lblDisplay.Text = System.DateTime.Today.ToString(); Response.Write("Welcome to The site"); } else { Response.Write("Postback event fired <br>"); } } protected void btnClick_Click(object sender, EventArgs e) { Response.Write("Submit button clicked"); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 21

(Source Code: Module2\01IsPostBack.aspx.cs)

21

Login Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

22

(Source: Module2\02LoginPageEg.aspx) Options for TextMode property: SingleLine: Default mode Multiline: Multiple lines of text can be written. Text box will appear with the scroll bar. Password: To encrypt a password by some character. This character is browser dependent.

Controls Label Label

Properties ID Text ID Text ID Text ID Text

Value lblUserName User Name lblPassword Password lblDisplay (Blank) btnLogin Login

Label

Button

22

Login Example Contd


public partial class _02LoginPageEg : System.Web.UI.Page { protected void btnLogin_Click(object sender, EventArgs e) { string uname; string pass; uname = txtUserName.Text; pass = txtPassword.Text; if (uname == "Pragati" & pass == "admin") { lblDisp.Text = "Valid user; } else { lblDisp.Text = "Invalid user; } } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 23

(Source Code: Module2\02LoginPageEg.aspx.cs)

23

List Controls
DropDownList Control Example (AutoPostBack Property)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

24

(Source: Module2\03DropDownListEg.aspx) We have got another set of controls called as List Controls that contains: DropDownList: We can store a list of items but at a time only one item is displayed. ListBox: We can store a list of items. We can also select multiple items with the help of Shift and Ctrl key combinations. CheckedListBox: Listbox appear with check boxes. RaioButtonListBox: Listbox appear with radio buttons. By default, all list controls contain one property called as EnableAutoPostBack to automatically send the selected data to the server to get the desired output. The event that is attached with list controls is SelectedIndexChanged which gets fired on selection of an item in the list.

Controls Label Label

Properties ID Text ID Text ID EnableAutoPostBack

Value lblSelectCountry Select Country lblDisplay (Blank) ddlCountry True

DropDownList

24

List Controls Contd


public partial class _03DropDownListEg : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { ddlCountry.Items.Add("India"); ddlCountry.Items.Add("USA"); ddlCountry.Items.Add("Australia"); } } protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) { lblDisp.Text = "Selected country is " + ddlCountry.SelectedItem.Text; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

25

(Source Code: Module2\03DropDownListEg.aspx.cs)

25

List controls Contd


ListBox Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

26

(Source: Module2\04ListBoxEg.aspx) ListBox control is used to display multiple items. These items can be selected using Shift and control key combinations.

Control Label1 ListBox Button Label2

Property ID Text ID SelectionMode ID Text ID Text

Value lblSelectBooks Select Books lstBooks Multiple btnSelect Select Books lblDisp (Blank)

26

List Controls Contd

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

27

(Source Code: Module2\04ListBoxEg.aspx.cs)

27

Module 3: Validation Controls


Overview
RequiredField Validator Compare Validator Range Validator Required Field Validator Validation Summery Custom Validator Validation Group

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

28

28

Validation Controls Example


Custom Validator Compare Validator Range Validator RegularExpression Validator

Validation Summary RequiredFieldValidato r

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

29

(Source: Module3\01ValidationControlsEg.aspx) Validation Controls: In web applications, the user inputs is accepted only when some condition is satisfied. To check whether the inputs are according to those conditions, we need to put validations. This task has become easy as Asp.Net introduces Validation Controls. Validation Controls provide simple mechanism to check some standard validations such as, checking whether user has given the value for the fields or kept them empty, the length of the password is between some range, email id is according to the standard mail address or not etc.. Let s discuss the controls in detail. 1)RequiredFieldValidator: The type of validation which is performed by this control is Required Entry. This ensures that user doesnt skip the field from providing input. The user input is compulsory. The slide shows that all the fields are compulsory. 2)CompareValidator: The type validation this control performs is Comparison To a Value. The value entered by the user for one field is compared with the value of the other field, the constant or a specific data type. In the slide, the field for Confirm Password is compared with the field for Password as retyped password need to be the same as of actual password. 3)RangeValidator: The type of validation performed by this control is Range Checking. This controls checks whether the value entered by the user is between the specified range or not. The range can be within pair of numbers or alphabets or dates. 4)RegularExpressionValidator: The type of validation performed by this control is Pattern Matching. This control matches the value entered by the user with that of the pattern specified. Patterns can be specified for email addresses, site addresses, postal codes, telephone numbers etc. 5)CusomValidator: The type of validation performed by this control is User Defined. In the above all the controls the validation logic is already given but for custom validator the code of logic need to be written.

29

Validation Controls Example Contd

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

30

(Source Code: Module3\01ValidationControlsEg.aspx.cs) Validation Summary: This control is used to display all the error messages either in the form of a list or in the form of a message box. It tracks the error message property of all the validation controls. We have two properties: Show Summary and Show Message Box.

Control RequiredFieldValidator

Property ID ControlToValidate ID ControlToValidate ControlToCompare ID ControlToValidate MaximumValue MinimumValue ID ControlToValidate ValidationExpression ID ControlToValidate ClientValidationFunction

Value rfvUserName txtAge cvConfirmPassword txtConfirmPwd txtPassword rvAge txtAge 60 18 revEmail txtEmail \w+([-+.']\w+)*@\w+([.]\w+)*\.\w+([-.]\w+)* csvPassword txtPassword Validate

CompareValidator

RangeValidator

RegularExpressionValidator

CustomValidator

30

Validation Group

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

31

(Source: Module3\02ValidationGroupEg.aspx) Validation Group: The example in the slide accepts user name and password and also an email id if the user has forgot the password. RequiredFieldValidatior is kept for all the three fields. If user forgets to provide user name or password then the validation happens not only for these two controls but also for the one that accepts mail id. Which should not be the case. To separate validations, we need logical groupings for validation. We need to set the ValidationGroup property for the textboxes, RequiredFieldValidators and button to login together to a particular group. And textbox for email id, RequiredFieldValidator and button to get the password into another group. Benefits of Validation Controls: 1.Validation controls are rendered on the Client Side. 2.One need not to write a code. The logic is provided by the controls itself.

31

Module 4: ADO.NET Architecture


Overview
Introduction to ADO.NET Disconnected Model Connected Model Example on connected and disconnected model

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

32

32

Introduction to ADO.NET
ADO.NET is a technology that allows access to the data. It provides a set of classes to access database either in connected environment or disconnected environment. Strong XML Integration provided.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

33

33

Connected Model

Provider Client Application


Connection Command Data Reader

Database

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

34

Connection: It provides a connection with the database. It provides following methods and properties. Properties / Methods of Connection: Methods: Open(): To open the connection with the database to allow to perform operations with the data. Close(): To close the connection with the database. Properties: ConnectionString: We need to set this property to provide the following information. Server or DataSource Database or Initial Catelog User id and Password for SQL Authentication Integrated Security for Windows Authentication Provider Name (Optional for Sql Server Provider) Data Command: These are the commands or quries to be fired on the database to perform operations with the database. The following properties and methods are given by command classes. Properties / Methods of Data Command: Methods: ExecuteNonQuery(): To execute manipulation statements on the database. It returns an integer value. ExecuteScalar(): It is used to return a single value. When a result set is retrieved, this method returns First Row First Column value. ExecuteReader(): Used to return a Data Reader reference to get Read Only Forward Only access to the data.

34

Disconnected Model
Provider Client Application
Connection

Database
Data Adapter
DataSet

Select Command Insert Command Update Command Delete Command

DataSet
XML

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

35

Properties of DataCommand: CommandText: To specify the query statement to be fired on the database. CommandType: To mention which type of command to be fired on the database. It takes 3 options. Text option is used to specify the query statement and it is the default. StoredProcedure option is used to specify that the command to be fired is a stored procedure and not a simple text. TableDirect is used to specify the name of the table for which select statement is generated automatically. Data Reader: It provides Read Only Forward Only access to the data. It stores only one row at a time into the memory and retrieves the data as soon as requested. It speeds up the performance. Methods: Read(): Advances the reader to the next record. Disconnected Model: This is an Offline access to the data where the client is disconnected from the database. There is no direct connection between an application and the database. Data is accessed through DataSet. Dataset is an in - memory representation of data or cached set of data. It stores the data in the form of DataTable Objects and Datatable in turn stores it in the form of DataRow and DataColumn objects. DataAdapter: It is an intermediary between Dataset and the Application. It opens the connection with the database, fetches the data by firing commands, brings the data into the dataset and closes the connection with the database. It also updates the data with corressponding changes made into the dataset.

35

.NET Framework Data Providers


Data Provider for SQLServer
Used for Microsoft SQL Server Version 7.0 onwards. Namespace used is System.Data.SqlClient.

Data Provider for Oracle


Used with Oracle version 8i or later. Namespace used is System.Data.OracleClient.

Data Provider for OLEDB


Used with any database. Namespace used is System.Data.Oledb.

Data Provider for ODBC


Used with ODBC data. Namespace used is System.Data.Odbc.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

36

Properties / Methods of DataAdapter: Methods: Fill(): This method is used to open the connection with the database, fire the command on the database, retrieve the data into the dataset and close the connection with the database. Update(): This method is used to reflect the changes made in the dataset to the Database. For this it requires corresponding commands to be fired. It uses certain properties to achieve this task. Properties: SelectCommand, InsertCommand, UpdateCommand, DeleteCommand: These properties are required to be set if we want to perform modifications to the database through data adapter.

36

Disconnected Code

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

37

(Source: Module4\01DisconnectedCode.aspx)

37

Disconnected Code Contd


using System.Data.SqlClient; using System.Data..Oledb; using System.Data.OracleClient; public partial class _01DisconnectedCode : System.Web.UI.Page //For Connecting SQL Server SqlConnection sqlcon; SqlDataAdapter sqlda; //For Connecting Access Database OleDbConnection olecon; OleDbDataAdapter oleda; //For Connecting Oracle OracleConnection oracon; OracleDataAdapter orada;

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

38

(Source Code: Module4\01DisconnecteCode.aspx.cs)

38

Disconnected Code (SQL Server)


//For all connections. DataSet ds; protected void btnDiscon_Click(object sender, EventArgs e) { sqlcon = new SqlConnection("server=PSPL2939\\SA1;database=northwind;integrated security=true;"); sqlda = new SqlDataAdapter("select * from products", sqlcon); ds = new DataSet(); sqlda.Fill(ds); grid.DataSource = ds; grid.DataBind(); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

39

(Source Code: Module4\01DisconnecteCode.aspx.cs)

39

Disconnected Code (Access)


protected void btnDataFrmAccess_Click(object sender, EventArgs e) { olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\NWIND.MDB;Persist Security Info=True;"); oleda = new OleDbDataAdapter("select * from Categories", olecon); ds = new DataSet(); oleda.Fill(ds); grid.DataSource = ds.Tables[0]; grid.DataBind(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

40

(Source Code: Module4\01DisconnecteCode.aspx.cs)

40

Disconnected Code (Oracle)


protected void btnDataFrmOracle_Click(object sender, EventArgs e) { oracon = new OracleConnection("Data Source=ORADB;User ID=scott;Password=tiger;Unicode=True"); orada = new OracleDataAdapter("select * from Emp", oracon); ds = new DataSet(); orada.Fill(ds); grid.DataSource = ds.Tables[0]; grid.DataBind(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

41

(Source Code: Module4\01DisconnecteCode.aspx.cs)

41

Connected Code

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

42

(Source: Module4\02ConnectedCode.aspx)

42

Connection String From Configuration File


<?xml version="1.0"?> <configuration> <connectionStrings> <add name="NorthwindConnectionString" connectionString="Data Source=PSPL2939\SA1;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/> </connectionStrings> </configuration>

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

43

One can specify connection string in Web.config file. It is an XML based configuration file for web application. The benefits are: 1.We need not write it again on every page. 2.If we want to make any changes, they need to be done at one place i.e. config file only. They will be reflected automatically at every places. To refer to connection string written in config file, we need to have a reference to System.Configuration namespace in code file. The class used is ConfigurationManger which contains ConnectionStrings collection. From this collection, we can identify each connection string by the name of it.

43

Connected Code Contd


using System.Data.SqlClient; public partial class _02ConnectedCode : System.Web.UI.Page { SqlConnection sqlcon; SqlCommand sqlcmd; protected void btnCon_Click(object sender, EventArgs e) { sqlcon = new SqlConnection("ConfigurationManager.ConnectionStrings["Northwin dConnectionString"].ConnectionString ); sqlcmd = new SqlCommand("select * from categories", sqlcon); sqlcon.Open(); grid.DataSource = sqlcmd.ExecuteReader(); grid.DataBind(); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

44

(Source Code: Module4\02ConnectedCode.aspx.cs)

44

Data Controls
Data Controls

DataBound Controls Grid View Details View Form View Repeater DataList

DataSource Controls SqlDataSource AccessDataSource ObjectDataSource XMLDataSource SiteMapDataSourc e

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

45

Data Controls are divided into two: DataBound controls: Helps to bind i.e. associate the controls with data DataSource Controls: These controls encapsulates the logic for connecting to data, fetching and manipulating data and then bound to DataBound controls.

45

Module 5: DataSource Controls


Overview SQL Data Source Control Object Data Source Control Example Retrieve, Insert, update, Delete data using Data Source DataSet Filtering DataSet Using CommandBuilder StoredProcdure (In and Out parameters) Transactions DataRelations BulkCopy Batch Updates MARS Provider Factories Data From XML Using XML DatqaSource LINQ Datasource
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 46

46

SqlDataSource
Allows to work with SQL Server, Oracle, SQLExpress, ODBC and OleDb databases. It is a layer between the bound controls and the database.
Select() Grid View Control Insert() DataBase Update() Delete()

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

47

The SqlDataSource control uses ADO.NET classes to work with the database. It can work with any databases that are supported by ADO.NET. It takes ConnectionString information, the query statement or a stored procedure to be fired. During rin time it opens the connection automatically, fires the required statement, performs corresponding operation on the database and closes the connection. Connecting SqlDataSource to a Database: We need to set the ProviderName, ServerName, Authentication (Windows or SQL), and Database name to connect. This connection can be saved in the Web.Config file. Issuing Data Commands with the SqlDataSource Control We can set the commands such as Select, Insert, Update, Delete with SqlDataSource. We have got two options to set this. Either we select the table from the list of tables and then select the columns or we write the query by our own. The datasource control executes the commands when corresponding Select(), Insert(), Update() and Delete() method is called. When the data is bound to the control, it automatically calls the select method. Even after performing manipulation operations, it calls the select method. We can also call these method explicitly. Returning DataReader or DataSet: It can either return a datareader or a dataset for which we need to specify a property called as DataSourceMode. DataSet allows filter, sorting , paging, caching, manipulation to the data whereas datareader provides read only, forward only access to the data. Filtering with SqlDataSource control: We can filter the data by providing a where clause with the datasource control. Sorting with SqlDataSource Control: We can sort the data by providing an Order By clause with the control.

47

SQL DataSource Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

48

(Source: Module4\03SQLDataSourceControlEg.aspx) Steps to Configure SqlDataSource Control 1) Drag an SqlDataSource Control. From the smart tag, select Configure Data Source.

48

SQL DataSource Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

49

(Source: Module4\03SQLDataSourceControlEg.aspx) 2) We need to choose the data connection. Click New Connection button.

49

SQL DataSource Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

50

(Source: Module4\03SQLDataSourceControlEg.aspx)

3) We need to specify the Data Source to which we want to connect. For our example, we will select Microsoft Sql Server and .NET Framework Data Provider for SQL Server which is default.

50

SQL DataSource Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

51

(Source: Module4\03SQLDataSourceControlEg.aspx) 4) After selecting the data source, we need to give the server name to connect. We also need to select the way of loging on to the server i.e. using Windows Authentication or SQL Server Authentication. Then provide the database name and test the connection.

51

SQL DataSource Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

52

(Source: Module4\03SQLDataSourceControlEg.aspx) 5) Once the connection string is generated, we need to save the connection string to the Web.Config file for reusability purpose.

52

SQL DataSource Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

53

(Source: Module4\03SQLDataSourceControlEg.aspx) 6) We will select the table and columns of that table by using the option : Selecting columns from a table or view. On this wizard page, to retrieve Unique rows, we need to check the checkbox for Return only unique rows. We can provide Where clause to filter the data. We can order the data by columns using Order By option. By clicking on Advanced, we can generate Insert, Update and Delete queries.

53

SQL DataSource Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

54

(Source: Module4\03SQLDataSourceControlEg.aspx) 7) After setting required option, test the query.

54

SQL DataSource Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

55

(Source: Module4\03SQLDataSourceControlEg.aspx) 8) Finally the data would be bound to the control through SQLDataSource control. We will get checkboxes like Enable Paging, Enable Sorting and Enable Selection. If we have generated manipulation statements, then we will also have options like Enable Editing, Enable Deleting. This is explained in the next two slides.

55

Modifying Data with SqlDataSource

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

56

(Source: Module4\04SQLDataSourceControlEg.aspx) Check Generate INSERT, UPDATE and DELETE statements checkbox to generate manipulation statements for the data.

56

Modification through GridView

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

57

(Source: Module4\04SQLDataSourceControlEg.aspx) The gridview control provides the smart tag where in we have the properties to enable editing, and enable deleting for performing modifications through grid view.

57

Modifying Through Code

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

58

(Source: Module4\05ModifyingDataWithSQLDataSource_Code.aspx) In the above example, we are going to modify the data using SqlDataSource. We will be binding it to list controls and textbox controls. For this purpose, we need to set certain properties with SqlDataSource control such as SelectQuery, UpdateQuery, InsertQuery, and DeleteQuery.

58

Setting Select Parameter

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

59

(Source: Module4\05ModifyingDataWithSQLDataSource_Code.aspx) We need to set the queries parameters to corresponding control ID to which we will pass during run time.

59

Setting Update Parameter

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

60

(Source: Module4\05ModifyingDataWithSQLDataSource_Code.aspx) For updating the data, we need to set UpdateQuery property of SqlDataSource control. We need to set parameters to corresponding controls.

60

Setting Insert Parameters

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

61

(Source: Module4\05ModifyingDataWithSQLDataSource_Code.aspx) To insert data, InsertQuery property of SqlDataSource control.

61

Setting Delete Parameter

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

62

(Source: Module4\05ModifyingDataWithSQLDataSource_Code.aspx) We need to set DeleteQuery property of SqlDataSource control.

62

Modifying Through Code contd


protected void Page_Load(object sender, EventArgs e) { getTotalProducts(); } protected void ddlProducts_SelectedIndexChanged(object sender, EventArgs e) { DataView dv = (DataView)sdcProducts.Select(DataSourceSelectArguments.Empty); txtProductName.Text = dv[0]["ProductName"].ToString(); txtUnitPrice.Text = dv[0]["UnitPrice"].ToString(); } protected void btnInsert_Click(object sender, EventArgs e) { sdcProducts.Insert(); ddlProducts.DataBind(); getTotalProducts(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

63

(Source Code: Module4\05ModifyingDataWithSQLDataSource_Code.aspx.cs) After setting the parameters, we need to call methods to fetch as well as manipulate the data. Here, in the SelectedIndexChanged event handler, Select() method on datasource. It selects the required rows from the database. It takes one parameter of type DataSourceSelectArguments and returns IEnnumerable which has been typecasted to dataview and assigned to a dataview reference. In the btnInsert_Click event handler, we have called Insert() method on datasource. It returns an integer. It inserts a new record into the products table. After inserting records, we are calling DataBind() method on the dropdownlist so as to refresh the control with newly generated productid.

63

Modifying Through Code contd


protected void btnUpdate_Click(object sender, EventArgs e) { sdcProducts.Update(); } protected void Delete_Click(object sender, EventArgs e) { sdcProducts.Delete(); ddlProducts.DataBind(); getTotalProducts(); } private void getTotalProducts() { DataView dv = (DataView)sdcProductID.Select(DataSourceSelectArguments.Empty); int count = dv.Table.Rows.Count; lblTotalProducts.Text = count.ToString(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

64

(Source Code: Module4\05ModifyingDataWithSQLDataSource_Code.aspx.cs) In the btnUpdate_Click event handler, we are calling Update() method on datasource to update values for selected productid. In the btnDelete_Click event handler, we are calling Delete() method on datasource to delete values for selected productid. We are again calling DataBind() method on the dropdownlist so as to reflect the changes. We also have created one user defined private method that counts total number of products.

64

ObjectDataSource
It is used in N-tier approach. Communicates with objects or collection of objects.

Select() Grid View Control Insert() DataBase Update() Delete()

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

65

Object Data Source is introduced to provide a Business Logic Layer to the application. With other datasource controls, we can achieve two tier architecture where presentation layer has too much information about the database. To isolate presentation layer from the data layer, we will create set of classes which will communicate with the database, bring the data to the application, perform manipulation. We are going to create a class that contains all the methods to communicate with the database. In our example, we are going to create a class that contains all the information related to the fields of the database by creating properties and another class that contains all the manipulation methods. When we create properties for the fields of the database their name should match with the names of the fields in database.

65

Object DataSource Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

66

(Source: Module4\06ObjectDataSourceControlEg.aspx) We have taken DetailsView control to be bound to ObjectDataSource control. DetailsView control displays details of Single record at a time. It also allows paging, modifying, inserting the data. Lets create the classes. We need to keep certain things in mind before we create business objects for ObjectDataSource control. They are as follows: I.We will write four methods for fetching, inserting, updating and deleting data. II.All the methods need to be public and static. III.Method for selecting data would return a DataSet or DataReader IV.Other methods would return an integer but it is optional. We will create three classes: one for Connection, one for storing all the fields of the table i.e. Employee and the last one to store methods to work with the data i.e. EmployeeStore.

66

The Connection Class


using System.Data.SqlClient; public class Connection { static SqlConnection con; public static SqlConnection getConnection() { con = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"]. ConnectionString); return con; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

67

(Source Code: Module4\App_Code\Connection.cs)

67

The Employee Class

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

68

Source Code: Module4\App_Code\Employee.cs)

68

The EmployeeStore Class


using System.Data.SqlClient; public class EmployeeStore { static SqlConnection sqlCon; static SqlCommand sqlCmd; public static DataSet getData() //To Fetch the data and return a DataSet { sqlCon = Connection.getConnection(); SqlDataAdapter sqlDa = new SqlDataAdapter("select firstname, lastname,employeeid from employees", sqlCon); DataSet sqlDs = new DataSet(); sqlDa.Fill(sqlDs, "Employees"); return sqlDs; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

69

(Source Code: Module4\App_Code\EmployeeStore.cs)

69

The EmployeeStore Class


public static int insertData(Employee emp) //To Insert data { //The method is referring to Employee class reference for the fields to be //inserted string insertStatement; int retval; insertStatement = "insert into employees(firstname,lastname) values(" + "" + "'" + emp.FirstName + "'" + "," + "'" + emp.LastName + "'" + ")"; retval = executeQuery(insertStatement); return retval; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

70

(Source Code: Module4\App_Code\EmployeeStore.cs)

70

The EmployeeStore Class


public static int updateData(Employee emp) //Update Data returning an Integer { string updateStatement; int retval; updateStatement = "update employees set firstname=" + "" + "'" + emp.FirstName + "'" + "," + "lastname=" + "'" + emp.LastName + "'" + " where employeeid= " + emp.EmployeeID; retval = executeQuery(updateStatement); return retval; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

71

(Source Code: Module4\App_Code\EmployeeStore.cs)

71

The EmployeeStore Class


public static int deleteData(Employee emp) //Delete Data and returning an Integer. { string deletestatement; int retval; deletestatement = "delete employees where employeeid=" + emp.EmployeeID; retval = executeQuery(deletestatement); return retval; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

72

(Source Code: Module4\App_Code\EmployeeStore.cs)

72

The EmployeeStore Class


public static int executeQuery(string statement) { //This method performs all the common task to be performed for all //manipulations. int retval; try { sqlCon = Connection.getConnection(); sqlCmd = new SqlCommand(statement, sqlCon); sqlCon.Open(); retval = sqlCmd.ExecuteNonQuery(); if (retval > 0) { return retval; } else { return 0; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

73

(Source Code: Module4\App_Code\EmployeeStore.cs)

73

The EmployeeStore Class


catch (Exception ex) { return 0; } finally { sqlCon.Close(); } } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

74

(Source Code: Module4\App_Code\EmployeeStore.cs)

74

Configure Data Source

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

75

(Source: Module4\06ObjectDataSourceControlEg.aspx) To configure the ObjectDataSource, we need to choose the class that contains all the manipulation methods for the option Choose your business object.

75

Set Select Method

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

76

(Source: Module4\06ObjectDataSourceControlEg.aspx) The next step is setting the methods. In the above slide we are selecting getData() method for Select operation.

76

Set Update Method

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

77

(Source: Module4\06ObjectDataSourceControlEg.aspx) Here we are selecting updateData(Employee emp) for Update operation.

77

Set Insert Method

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

78

(Source: Module4\06ObjectDataSourceControlEg.aspx) Here we are selecting insertData(Employee emp) for Insert operation.

78

Set Delete Method

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

79

(Source: Module4\06ObjectDataSourceControlEg.aspx) Here we are selecting deleteData(Employee emp) for Delete operation. Click on fininsh and execute the code. After we are finished with the configuration, we need to bind this ObjectDataSource control to the desired control.

79

Output Of ObjectDataSource Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

80

(Source: Module4\06ObjectDataSourceControlEg.aspx)

80

DataSet
DataSet is an in memory representation of data. It contains multiple tables and information about the tables such as constraints, order, relations if any. To populate the dataset a DataAdapter is used.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

81

DataSet: It is an in memory representation or cached set of the data. It can store data from multiple sources i.e. a dataset is not provider specific. DataSet contains tables in the form of a collection which can be related by using DataRelation objects. We can also enforce integrity like UniqueConstraint or ForeignKeyConstraint. DataSet provides disconnected model. DataAdapter is used to fill the data of the database in to the dataset. It stores data in xml format.

81

DataSet Object Model


DataSet

DataTable

DataRelation

DataRow

DataColumn

Constraints

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

82

DataSet Object Model: DataSet stores tables and relations amongst the tables in the form of collections called as DataTableCollection and DataRelationCollection. Each table in the collection is represented by DataTable objects and each relation in the collection is represented by DataRelation objects. DataTable stores rows and columns in DataRowCollection and DataColumnCollection. To refer to a single record and a column in the collection, we have DataRow and DataColumn objects. Apart from rows and columns we can also enforce constraints like primary key, unique key, foreign key on the data.

82

Types of DataSet
DataSet

Typed DataSet

UnTyped DataSet

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

83

83

Filtering DataSet

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

84

(Source : Module4\07Filter_DataSet.aspx) Applying Filters on DataSets: Once the data is retrieved into the dataset, the connection to the database will get closed. Now, if we want to have filtered data we again are required to fire queries to the database and retrieve a different set of data every time. Instead of firing multiple queries on the database, we can apply filters on DataSet as well. We have got two methods to filter the dataset data. One is through Select method and the other is through DataView object. Select method returns an array of DataRow objects for specified criteria and sort order. DataView allows different views of the data stored in the data table. It is similar to the database views where we can apply different filter and sort criteria and can have different views of data. However, it has got certain limitations like it cant have data from joined tables, cant append computational column, cant exclude any column existing in the source table.

84

Code
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { SqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"]. ConnectionString); SqlCmd = new SqlCommand("select categoryid from categories", SqlCon); SqlCon.Open(); SqlDr = SqlCmd.ExecuteReader(); while (SqlDr.Read()) { ddlCategories.Items.Add(SqlDr["CategoryID"].ToString()); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

85

(Source Code: Module4\07Filter_DataSet.aspx.cs)

85

Code
} } private DataTable GetData() { SqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"]. ConnectionString); SqlCmd = new SqlCommand("select productid, productname, unitprice, categoryid from products", SqlCon); SqlCon.Open(); SqlDr = SqlCmd.ExecuteReader(); dt = new DataTable(); dt.Load(SqlDr); return dt; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 86

(Source Code: Module4\07Filter_DataSet.aspx.cs)

86

Code For Select Method


protected void btnSelectMethod_Click(object sender, EventArgs e) { lstProductName.Items.Clear(); if (ddlCategories.SelectedIndex > -1) { dt = new DataTable(); dt = GetData(); DataRow[] dr = dt.Select("CategoryID=" + ddlCategories.SelectedItem.Text); for (int i = 0; i < dr.Length; i++) { lstProductName.Items.Add(dr[i]["ProductName"].ToString()); } } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 87

(Source Code: Module4\07Filter_DataSet.aspx.cs)

87

Code For DataView


protected void btnDataView_Click(object sender, EventArgs e) { if (ddlCategories.SelectedIndex > -1) { dt = new DataTable(); dt = GetData(); dt.TableName = "Products"; DataView dv = new DataView(); dv.Table = dt; dv.RowFilter = "CategoryID=" + ddlCategories.SelectedItem.Text; grid.DataSource = dv; grid.DataBind(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 88

(Source Code: Module4\07Filter_DataSet.aspx.cs)

88

Using Command Builder to Update data in Disconnected Architecture

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

89

(Source Code: Module4\08SqlCommandBuilder.aspx) Command Builder: Command Builder is used to generate manipulation commands automatically. To generate the commands it requires select statement which must retrieve a primary key or a unique key column. Command Builder is required in the case when the dataset is generated during run time. This dataset doesnt have any information related to the manipulation commands. If we want to manipulate such dataset and the database later through such dataset then we need to provide the statements of modifications during run time. Command Builder suffices this purpose. System.Data.SqlClient namespace provides SqlCommandBuilder class to generate the commands. The constructor of this class takes SqlDataAdapter reference as a parameter.

89

Add Columns

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

90

(Source Code: Module4\08SqlCommandBuilder.aspx) For working with command builder, we need to add bound columns as well as command fields to the gridview control. To add it, Select the grid and from the smart tag select Edit Columns option. The dialog box displayed in the slide will appear. Select a BoundField from Available Fields list and click on add button. It will get added to the selected fields list. Select the field, Property page will be displayed. We need to specify the following properties: HeaderText: The heading of the column DataField: The name of the field which will be mapped with that of database column during run time. This has to be exactly same as the database field. ReadOnly: True ( For the columns which dont take part in modifications e.g. Primary Key Column). We also need to code the events gerated by the gridview control for manipulation. In the above example, as we will be only updating the data, we have generated RowEditing, RowUpdating and RowCancelingEdit

90

Code Using CommandBuilder


SqlConnection sqlcon; SqlDataAdapter sqlda; DataSet ds; SqlCommandBuilder sqlcmdbuilder; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ds=FillGrid(); grid.DataSource = ds.Tables["Products"]; grid.DataBind(); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

91

(Source Code: Module4\08SqlCommandBuilder.aspx.cs)

91

Code Using CommandBuilder Contd


private DataSet FillGrid() { sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"]. ConnectionString); sqlda = new SqlDataAdapter("select productid, productname, unitprice from products", sqlcon); ds = new DataSet(); sqlda.Fill(ds, "Products"); DataColumn[] pk=new DataColumn[1]; //Manually adding Primary Key pk[0] = ds.Tables["Products"].Columns["ProductID"]; ds.Tables["Products"].PrimaryKey = pk; sqlcmdbuilder = new SqlCommandBuilder(sqlda); return ds; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 92

(Source Code: Module4\08SqlCommandBuilder.aspx.cs)

92

Code Using CommandBuilder Contd


protected void grid_RowEditing(object sender, GridViewEditEventArgs e) { grid.EditIndex = e.NewEditIndex; ds=FillGrid(); grid.DataSource = ds.Tables["Products"]; grid.DataBind(); } protected void grid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { grid.EditIndex = -1; ds=FillGrid(); grid.DataSource = ds.Tables["Products"]; grid.DataBind(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 93

(Source Code: Module4\08SqlCommandBuilder.aspx.cs)

93

Code Using CommandBuilder Contd

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

94

(Source Code: Module4\08SqlCommandBuilder.aspx.cs)

94

Master Details Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

95

(Source: Module4\09MasterDetailEg.aspx)

95

Master Details Example Contd


using System.Data.SqlClient; SqlConnection sqlcon; SqlDataAdapter sqlda; DataSet ds; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { sqlcon = new SqlConnection("server=PSPL2939\\SA1;database=northwind;integrated security=true;"); sqlda = new SqlDataAdapter("select Categoryid, categoryname from categories", sqlcon); ds = new DataSet(); sqlda.Fill(ds); gridParent.DataSource = ds.Tables[0];
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 96

(Source Code: Module4\09MasterDetailEg.aspx.cs)

96

Master Details Example Contd


gridParent.DataBind(); } } protected void gridParent_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) { GridViewRow row = gridParent.Rows[e.NewSelectedIndex]; int cid = int.Parse(row.Cells[0].Text); sqlcon = new SqlConnection("server=PSPL2939\\SA1;database=northwind;integrated security=true;"); sqlda = new SqlDataAdapter("select Productid, productname, unitprice,categoryid from products where categoryid=" + cid, sqlcon); ds = new DataSet(); sqlda.Fill(ds); gridChild.DataSource = ds.Tables[0]; gridChild.DataBind(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 97

(Source Code: Module4\09MasterDetailEg.aspx.cs)

97

Stored Procedure (In Parameter)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

98

(Source: Module4\10SPIN.aspx) We can also use stored procedure to manipulate the data. A stored procedure can accept data as well as can return data. When a procedure accepts some values, they are called as input parameters. It can also return data either as output parameters or return values.

98

Stored Procedure (In Parameter) Contd


using System.Data.SqlClient; public partial class _10SPIN : System.Web.UI.Page { SqlConnection sqlcon; SqlCommand sqlcmd; SqlDataAdapter sqlda; DataSet ds; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { FillGrid(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 99

(Source: Module4\10SPIN.aspx.cs) Create the following procedure in SQLServer Database. create proc InsertEmployee @fname nvarchar(10), @lname nvarchar(20) as employees(firstname, lastname) values (@fname, @lname) insert into

99

Stored Procedure (In Parameter) Contd


private void FillGrid() { sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"]. ConnectionString); sqlda = new SqlDataAdapter("select Employeeid, firstname, lastname from employees", sqlcon); ds = new DataSet(); sqlda.Fill(ds, "Employees"); grid.DataSource = ds.Tables["Employees"]; grid.DataBind(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

100

(Source: Module4\10SPIN.aspx.cs)

100

Stored Procedure (In Parameter) Contd


protected void btnInsert_Click(object sender, EventArgs e) { try { sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"]. ConnectionString); sqlcmd = new SqlCommand("InsertEmployee", sqlcon); sqlcmd.CommandType = CommandType.StoredProcedure; sqlcmd.Parameters.AddWithValue("@fname", txtFirstName.Text); sqlcmd.Parameters.AddWithValue("@lname", txtLastName.Text); sqlcon.Open(); sqlcmd.ExecuteNonQuery();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

101

(Source: Module4\10SPIN.aspx.cs)

101

Stored Procedure (In Parameter) Contd


FillGrid(); } catch (Exception ex) { Response.Write(ex.Message); } finally { sqlcon.Close(); } } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

102

(Source: Module4\10SPIN.aspx.cs)

102

Stored Procedure (Out Parameter)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

103

(Source : Module4\11SPOUT.aspx)

103

Stored Procedure (Out Parameter) Contd


SqlConnection sqlcon; SqlDataAdapter sqlda; DataSet ds; SqlCommand sqlcmd; decimal totalprice=0; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"]. ConnectionString);

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

104

(Source : Module4\11SPOUT.aspx.cs) Create the following procedure in SQLServer Database: create proc GetTotalPrice @catid int, @total money output as select @total=sum(unitprice) from products where categoryid=@catid

104

Stored Procedure (Out Parameter) Contd


sqlda = new SqlDataAdapter("select categoryid, categoryname from categories", sqlcon); ds = new DataSet(); sqlda.Fill(ds, "Categories"); lstCategory.DataSource = ds; lstCategory.DataTextField = ds.Tables[0].Columns["CategoryName"].ToString(); lstCategory.DataValueField = ds.Tables[0].Columns["CategoryID"].ToString(); lstCategory.DataBind(); } } protected void btnSelect_Click(object sender, EventArgs e) { int[] indices = lstCategory.GetSelectedIndices(); for (int i = 0; i <indices.Length; i++)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

105

(Source : Module4\11SPOUT.aspx.cs)

105

Stored Procedure (Out Parameter) Contd


{sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionSt ring"].ConnectionString); sqlcmd = new SqlCommand("GetTotalPrice", sqlcon); sqlcmd.CommandType = CommandType.StoredProcedure; sqlcmd.Parameters.AddWithValue("@catid", lstCategory.Items[indices[i]].Value); sqlcmd.Parameters.Add("@total", SqlDbType.Money); sqlcmd.Parameters["@total"].Direction = ParameterDirection.Output; sqlcon.Open(); int num=sqlcmd.ExecuteNonQuery(); totalprice+=decimal.Parse(sqlcmd.Parameters["@total"].Value.ToString()); lblDisplay.Text = totalprice.ToString(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 106

(Source : Module4\11SPOUT.aspx.cs)

106

Transactions

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

107

(Source: Module4\12Transaction.aspx) Transactions: It is a set of operations, wherein either all the operations must be successful or must fail so as to maintain the consistency of the database. For e.g. if we are transferring amount from one account to the other, then the amount should be added to one and deducted from the other. If deduction is successful but addition is not then the data will go in inconsistent state. Therefore we need to put these operations inside a transaction so that if one is successful but the other is not then the entire transaction will fail. Transactions follows certain guidelines i.e. ACID properties. Atomicity: Isolation: Durability: hard disk data can All the operations in the transactions should either succeed or fail together. All operations happen independently. None of the operations affect each other. Whenever manipulation happen to the data, the modified data is stored on some storage like before the transaction is declared as successful. So, if the transaction fails then the original be brought back to the database.

Consistency: The database have a consistent state after modifications.

When all the operations in the transactions are successful they are committed i.e. save permanently in the database. If they fail then they are rolled back i.e. discarded permanently.

107

Example
SqlConnection sqlcon; SqlCommand sqlcmd; SqlTransaction sqltran; SqlDataReader sqldr; decimal curBal = 0.0M, dbBal=0.0M; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"]. ConnectionString); sqlcmd = new SqlCommand("select accid from accounts", sqlcon);

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

108

(Source: Module4\12Transaction.aspx.cs) Create the following table for the above example: Create Table Accounts ( AccID int Identity(1,1) Primary Key, AccName nvarchar(50) NOT NULL, Balance money NOT NULL )

108

Example Contd
sqlcon.Open(); sqldr = sqlcmd.ExecuteReader(); while (sqldr.Read()) { ddlFromAccID.Items.Add(sqldr["AccID"].ToString()); ddlToAccID.Items.Add(sqldr["AccID"].ToString()); } sqldr.Close(); sqlcon.Close(); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

109

(Source: Module4\12Transaction.aspx.cs)

109

Example Contd
protected void btnTransaction_Click(object sender, EventArgs e) { sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"]. ConnectionString); sqlcmd = new SqlCommand("select balance from accounts where accid="+ddlFromAccID.SelectedItem.Text ,sqlcon); sqlcon.Open(); sqldr = sqlcmd.ExecuteReader(); curBal = decimal.Parse(txtAmtTransfer.Text); sqldr.Read(); dbBal=decimal.Parse(sqldr["Balance"].ToString()); if (dbBal < curBal) {
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 110

(Source: Module4\12Transaction.aspx.cs)

110

Example Contd
Response.Write("Insufficient balance. Cannot transfer"); sqldr.Close(); sqlcon.Close(); } else { try { //sqlcon.Open(); sqldr.Close(); sqlcmd = new SqlCommand(); sqlcmd.Connection = sqlcon; sqlcmd.CommandText = "select balance from accounts where accid=" + ddlToAccID.SelectedItem.Text;

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

111

(Source: Module4\12Transaction.aspx.cs)

111

Example Contd
sqldr = sqlcmd.ExecuteReader(); sqldr.Read(); decimal toBal = decimal.Parse(sqldr["Balance"].ToString()); sqldr.Close(); sqltran = sqlcon.BeginTransaction(); sqlcmd.Transaction = sqltran; sqlcmd.Connection = sqlcon; sqlcmd.CommandText = "Update accounts set balance="+ (dbBal - decimal.Parse (txtAmtTransfer.Text)) + " Where accid=" + ddlFromAccID.SelectedItem.Text; sqlcmd.ExecuteNonQuery(); sqlcmd.CommandText = "Update accounts set balance="+(toBal + decimal.Parse (txtAmtTransfer.Text)) + " where accid=" + ddlToAccID.SelectedItem.Text; sqlcmd.ExecuteNonQuery(); sqltran.Commit();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

112

(Source: Module4\12Transaction.aspx.cs)

112

Example Contd
Response.Write("Transfer of funds successful"); } catch (Exception ex) { Response.Write("Error occurred: "+ex.Message); sqltran.Rollback(); } finally { sqlcon.Close(); } } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

113

(Source: Module4\12Transaction.aspx.cs)

113

Data Relations

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

114

(Source: Module4\13DataRelations.aspx) Data Relations: Datasets can represent relational data by using DataRelation object. Whenever a database is created manually, we need to add relations between the tables by creating an object of DataRelation class.

114

Data Relations Example


SqlConnection sqlcon; SqlDataAdapter sqldaCat, sqldaProd; DataSet ds; decimal total=0.0M; protected void Page_Load(object sender, EventArgs e) { sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"]. ConnectionString); sqldaCat = new SqlDataAdapter("select categoryid, categoryname from categories", sqlcon); sqldaProd = new SqlDataAdapter("select productid, productname, unitprice, categoryid from products", sqlcon);

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

115

(Source: Module4\13DataRelations.aspx.cs)

115

Data Relations Example Contd


ds = new DataSet(); sqldaCat.Fill(ds, "Categories"); sqldaProd.Fill(ds, "Products"); DataRelation rel = new DataRelation("CatProd", ds.Tables[0].Columns["CategoryID"], ds.Tables[1].Columns["CategoryID"]); ds.Relations.Add(rel); foreach (DataRow parentrow in ds.Tables[0].Rows) { lstRelations.Items.Add("CategoryID: " + parentrow["CategoryID"]); lstRelations.Items.Add("CategoryName: " + parentrow["CategoryName"] + " "); lstRelations.Items.Add("-----------------------------------------------------------------"); foreach (DataRow childrow in parentrow.GetChildRows("CatProd")) { lstRelations.Items.Add("ProductID: "+childrow["ProductID"]);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 116

(Source: Module4\13DataRelations.aspx.cs)

116

Data Relations Example Contd


lstRelations.Items.Add("ProductName: "+childrow["ProductName"]); lstRelations.Items.Add("UnitPrice: "+childrow["UnitPrice"]+" "); total += decimal.Parse(childrow["UnitPrice"].ToString()); } lstRelations.Items.Add("================================================ ======================"); lstRelations.Items.Add("Total: " + total.ToString()); lstRelations.Items.Add("================================================ ======================"); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

117

(Source: Module4\13DataRelations.aspx.cs)

117

Bulk Copy

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

118

(Source: Module4\14BulkCopy.aspx) Bulk Copy: It help copying data from various sources such as text files, csv files, XML, or other databases to SQL server. Whenever we copy the data, the table in which we want to copy should exist into the database. The data types of the columns in the table should match with that of the data to be copied. The class used for this purpose is SqlBulkCopy.

118

Bulk Copy Example


Create a table for Bulk Copy:
create table prod(ProdID int primary key, ProdName varchar(50)not null,UnitPrice money)

Code
SqlConnection sourcecon, destcon; SqlCommand cmd; SqlDataReader dr; string constring; protected void btnBulkCopy_Click(object sender, EventArgs e) { constring = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionStri ng; sourcecon = new SqlConnection(constring); destcon = new SqlConnection(constring);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 119

(Source: Module4\14BulkCopy.aspx.cs)

119

Bulk Copy Example


cmd = new SqlCommand("select productid, productname,unitprice from products", sourcecon); sourcecon.Open(); destcon.Open(); SqlBulkCopy bcp = new SqlBulkCopy(destcon); bcp.DestinationTableName = "prod"; bcp.ColumnMappings.Add("ProductID", "ProdID"); bcp.ColumnMappings.Add("ProductName", "ProdName"); bcp.ColumnMappings.Add("UnitPrice", "UnitPrice"); try { dr = cmd.ExecuteReader(); bcp.WriteToServer(dr); Response.Write("Data copied"); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 120

(Source: Module4\14BulkCopy.aspx.cs)

120

Bulk Copy Example


catch (Exception ex) { Response.Write(ex.Message); } finally { dr.Close(); destcon.Close(); } sourcecon.Close(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

121

(Source: Module4\14BulkCopy.aspx.cs)

121

Batch Updates

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

122

(Source: Module4\15BatchUpdates.aspx)

122

Batch Updates Example


SqlDataAdapter empda; DataTable empdt; SqlConnection selectcon, updatecon; SqlCommand selectcmd, updatecmd; protected void btnUpdate_Click(object sender, EventArgs e) { selectcon = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"]. ConnectionString); updatecon = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"]. ConnectionString); selectcon.Open(); selectcmd = new SqlCommand();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

123

(Source: Module4\15BatchUpdates.aspx.cs)

123

Batch Updates Example Contd


selectcon.Open(); selectcmd = new SqlCommand(); selectcmd.CommandText = "select * from emp1"; selectcmd.CommandType = CommandType.Text; selectcmd.Connection = selectcon; updatecmd = new SqlCommand(); updatecmd.CommandText = "update emp1 set address=@address, " + "city=@city, Region=@region, Country=@country"; updatecmd.CommandType = CommandType.Text; updatecmd.Connection = updatecon; updatecmd.Parameters.Add(new SqlParameter("@address", SqlDbType.NVarChar, 120, "Address")); updatecmd.Parameters.Add(new SqlParameter("@city", SqlDbType.NVarChar, 30, "City"));
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 124

(Source: Module4\15BatchUpdates.aspx.cs)

124

Batch Updates Example Contd


updatecmd.Parameters.Add(new SqlParameter("@region", SqlDbType.NVarChar, 30, "Region")); updatecmd.Parameters.Add(new SqlParameter("@country", SqlDbType.NVarChar, 30, "Country")); empda = new SqlDataAdapter(); empda.SelectCommand = selectcmd; empda.UpdateCommand = updatecmd; empdt = new DataTable(); empda.Fill(empdt); selectcon.Close();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

125

(Source: Module4\15BatchUpdates.aspx.cs)

125

Batch Updates Example Contd


foreach (DataRow row in empdt.Rows) { row["Address"] = "4445 W 77th Street, Suite 140"; row["City"] = "Edina"; row["Region"] = "Minnesota"; row["Country"] = "USA"; } empda.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated); lblDisp.Text = ""; empda.UpdateBatchSize = 3; updatecmd.UpdatedRowSource = UpdateRowSource.None;

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

126

(Source: Module4\15BatchUpdates.aspx.cs)

126

Batch Updates Example Contd


try { updatecon.Open(); empda.Update(empdt); } catch (Exception ex) { lblDisp.Text += ex.Message + "<br>"; } finally { if (updatecon.State == ConnectionState.Open) { updatecon.Close(); } } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 127

(Source: Module4\15BatchUpdates.aspx.cs)

127

Batch Updates Example Contd


private void OnRowUpdated(object sender, SqlRowUpdatedEventArgs e) { lblDisp.Text += "Batch is processed till row number = " + e.RowCount.ToString() + "<br>"; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

128

(Source: Module4\15BatchUpdates.aspx.cs)

128

MARS

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

129

(Source: Module4\16MARS.aspx)

129

MARS Example
SqlCommand cmd; SqlConnection con; SqlDataReader orderdr; protected void Page_Load(object sender, EventArgs e) { con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString.To String()); cmd = new SqlCommand("select customers.companyname, customers.contactname, orders.orderid, orders.orderdate, orders.requireddate, orders.shippeddate from orders,customers where orders.customerid=customers.customerid order by customers.companyname, customers.contactname", con);

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

130

(Source: Module4\16MARS.aspx.cs) MARS: It stands for Multiple Active Result Sets. For activating MARS feature, we just need to add one attribute to the connection string i.e. MultipleActiveResultSets=True. <connectionStrings> <addname="constr InitialCatalog=Northwind; connectionString="DataSource=PSPL2939\SA1; MultipleActiveResultSets=True;

IntegratedSecurity=True; providerName="System.Data.SqlClient"/> </connectionStrings>

130

MARS Example Contd


con.Open(); orderdr = cmd.ExecuteReader(); grid.DataSource = orderdr; grid.DataBind(); con.Close(); } protected void grid_RowDataBound(object sender, GridViewRowEventArgs e) { IDataRecord ordrecord; Label lorderdetail; //type conversion ordrecord = e.Row.DataItem as IDataRecord; lorderdetail = e.Row.FindControl("lblOrderDetail") as Label;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 131

(Source: Module4\16MARS.aspx.cs)

131

MARS Example Contd


if ((ordrecord == null) || (lorderdetail == null)) { return; } SqlCommand cmd = new SqlCommand(); SqlDataReader orderdetaildr; cmd.CommandText = "select products.productname,[order details].unitprice, [order details].quantity, [order details].discount from [order details], products where [order details].productid=products.productid and [order details].orderid= " + Convert.ToString(ordrecord["OrderID"]); cmd.CommandType = CommandType.Text;

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

132

(Source: Module4\16MARS.aspx.cs)

132

MARS Example Contd


cmd.Connection = con; orderdetaildr = cmd.ExecuteReader(); while (orderdetaildr.Read()) { lorderdetail.Text += orderdetaildr[0].ToString() + "<br>"; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

133

(Source: Module4\16MARS.aspx.cs)

133

Provider Factories

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

134

(Source: Module4\17ProviderFactories.aspx) Provider Factories: It provides set of abstract classes that can work with multiple providers. It is used to write common code independent of any specific provider. The namespace that provides factory classes is System.Data.Common. The class DbProviderFactory is used to expose different providers. All the providers that are exposed by DbProviderFactory have their configuration information into the Machine.config file. We need to pass provider information to the instance of DbProviderFactory class, it determines the strongly typed connection object and returns it.

134

Provider Factories Example


using System.Data.Common; DataTable table; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { table = DbProviderFactories.GetFactoryClasses(); lstProviderFactories.Items.Add("The following data provider factories are available..."); lstProviderFactories.Items.Add(""); lstProviderFactories.DataTextField = table.Columns["InvariantName"].ToString(); lstProviderFactories.DataValueField = table.Columns["InvariantName"].ToString(); lstProviderFactories.DataSource = table; lstProviderFactories.DataBind(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 135

(Source: Module4\17ProviderFactories.aspx.cs)

135

Provider Factories Example Contd


protected void lstProviderFactories_SelectedIndexChanged(object sender, EventArgs e) { string provider = lstProviderFactories.SelectedValue.ToString(); if (provider == "System.Data.SqlClient") { DbProviderFactory factory = DbProviderFactories.GetFactory(provider); using (DbConnection conn = factory.CreateConnection()) { conn.ConnectionString = "data source=.\\sa1; initial catalog=northwind; integrated security=true"; conn.Open();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

136

(Source: Module4\17ProviderFactories.aspx.cs)

136

Provider Factories Example Contd


DbCommand cmd = factory.CreateCommand(); cmd.CommandText = "select * from customers"; cmd.Connection = conn; DbDataReader reader = cmd.ExecuteReader(); DataTable custtable = new DataTable(); custtable.Load(reader); conn.Close(); grid.DataSource = custtable; grid.DataBind(); } } else if (provider == "System.Data.OleDb") { DbProviderFactory factory = DbProviderFactories.GetFactory(provider); using (DbConnection conn = factory.CreateConnection())
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 137

(Source: Module4\17ProviderFactories.aspx.cs)

137

Provider Factories Example Contd


{ conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\NWIND.MDB;Persist Security Info=True;"; conn.Open(); DbCommand cmd = factory.CreateCommand(); cmd.CommandText = "select * from Categories"; cmd.Connection = conn; DbDataReader reader = cmd.ExecuteReader(); DataTable categorytable = new DataTable(); categorytable.Load(reader); conn.Close(); grid.DataSource = categorytable; grid.DataBind(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

138

(Source: Module4\17ProviderFactories.aspx.cs)

138

Data From XML

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

139

(Source: Module4\18XML.aspx)

139

XML File
<?xml version="1.0" encoding="utf-8" ?> <Books> <Book bookid="1"> <Name>Professional Asp.Net 2.0</Name> <Description>Learning Advance features of Asp.Net 2.0</Description> <Price>350</Price> <Author>Bipin Joshi</Author> </Book> <Book bookid="2"> <Name>Complete Reference to Java 1.5</Name> <Description>Learning Basic features of Java </Description> <Price>450</Price> <Author>Herbert Schildt</Author> </Book> </Books>
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 140

(Source: Module4\Books.xml)

140

Code
protected void btnXMLData_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); ds.ReadXml(Server.MapPath("Books.xml")); grid.DataSource = ds; grid.DataBind(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

141

(Source: Module4\18XML.aspx.cs)

141

Using XMLDataSource

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

142

(Source: Module4\19XMLDataSource.aspx) XMLDataSource: Uses an XML file as data source. It is especially used in binding hierarchical data to the navigation controls but can also be used with the GridView control. Whenever we bind the xml data to the grid, by default all the attributes specified into the file are automatically treated as Columns. But if we want that elements in the file also should be considered as columns then we need to add template columns in to the grid. Add label to the Item Template and bind it to the elements of the XML file. To bind XML data, we need to use a special function called XPath(string Expression). XPath expressions are used to traverse the xml tree, filter the data of xml.

142

LINQ DataSource

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

143

(Source: Module4\20LinqDataSourceEg.aspx) .NET Framework 3.5 introduces a new feature called LINQ (Language Integrated Query) which gives a query syntax for retrieving data from various sources such as an array, collection, dataset, object, xml.

143

LINQ DataSource Example


using System.Data.Linq.Mapping; [Table(Name="Products")] public class Product { private int id; private string prodName; private Nullable<decimal> unitPrice; [Column (Name="ProductID",DbType="int NOT NULL IDENTITY", IsDbGenerated=true,Storage="id",IsPrimaryKey=true)] public int ProductID { get { return id; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

144

(Source Code: Module4\App_Code\Product.cs)

144

LINQ DataSource Example Contd


set { id = value; } } [Column (Name="ProductName",DbType="nvarchar",Storage="prodName")] public string ProductName { get { return prodName; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

145

(Source Code: Module4\App_Code\Product.cs)

145

LINQ DataSource Example Contd


set { prodName = value; } } [Column (Name="UnitPrice",DbType="money",Storage="unitPrice, UpdateCheck=UpdateCheck.Never)] public Nullable<decimal> UnitPrice { get { if (unitPrice.HasValue) {

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

146

(Source Code: Module4\App_Code\Product.cs)

146

LINQ DataSource Example Contd


return unitPrice; } else { return unitPrice.GetValueOrDefault(0); } } set { unitPrice = value; } } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

147

(Source Code: Module4\App_Code\Product.cs)

147

LINQ DataSource Example Contd


using System.Data.Linq; public class ProductContext:DataContext { public Table<Product> products; public ProductContext():base(ConfigurationManager.ConnectionStrings["NorthwindConnection String"].ConnectionString) { // // TODO: Add constructor logic here // } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

148

(Source Code: Module4\App_Code\ProductContext.cs)

148

Configuring LINQ Data Source

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

149

149

Configuring LINQ Data Source

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

150

150

Module 6: DataBound Controls


Overview
GridView Paging Sorting Bound Field CommandButton Field Template Field Details View FormView DataList Repeater ListView

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

151

151

GridView Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

152

GridView Control: Displays more than one columns data. Can be bound to SqlDataSource and ObjectDataSource controls. It allows us to add various types of fields like ButtonField, BoundField, TemplateField etc. It fires events whenever any operation is performed on data through the control.

152

Column Types
Types of Columns available with the GridView:BoundField ButtonField ImageField HyperLinkField CheckBoxField CommandField TemplateField

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

153

153

Bound Field

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

154

(Source: Module5\01BoundFieldsEg.aspx) Bound Field is used to bind one column data to one column of the grid view control. For this purpose we need to add a BoundField from the available fields. It will then appear into the SelectedFields. The properties we need to set are: DataField > the field name as specified into the database and HeaderText > Name of the field for display. We can also set ReadOnly to true if the field is a primary key.

154

Template Field

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

155

(Source: Module5\02TemplateFieldEg.aspx) Template Fields are used to present customized data like displaying computed data or combined data. When the field is added, it appears as a container. It contains multiple templates where in we can put other controls and bound them to the data. Various templates are discussed in the next slide.

155

Types Of Templates
Header Template Item Template Alternating Item Template EditItem Template Pager Template Footer Template

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

156

(Source: Module5\02TemplateFieldEg.aspx) The different templates are: Header Template: It is the template where in we display the column names. HeaderText is the property which need to be set for displaying names on the header template. Item Template: It is the template where actual data is displayed. Data is bound to the controls put in it is with the method Eval(string expression) which is a one way binding. Alternating Item Template: It is the same as Item Template. It is just used to display data in different format for alternating template. EditItemTemplate: This template is produced only when we want to manipulate the data and we have generated manipulation statements with the datasource. Here the Bind(string Expression) method is used to bind the controls kept in it. This produces two way data binding. Pager Template: Used for paging. Footer Template: Used to display data like Grand Total or summary on footer. ShowFooter is the property with the GridView control that need to be set to display footer.

156

Template Field Example

Template Field

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

157

(Source: Module5\02TemplateFieldEg.aspx)

157

Adding control to the Template

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

158

(Source: Module5\02TemplateFieldEg.aspx)

158

Binding control to the expression

decimal.Parse(Eval("UnitPrice").ToString())*int.Parse(Eval("UnitsInStock").ToString())

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

159

(Source: Module5\02TemplateFieldEg.aspx)

159

Adding Command Field

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

160

(Source: Module5\03CommandFieldEg.aspx)

160

Enabling Manipulation

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

161

(Source: Module5\03CommandFieldEg.aspx)

161

DetailsView Control
Can be bound to any Data Source Displays single record details at a time. Allows paging and manipulation to the data.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

162

(Source: Module5\04DetailsViewEg.aspx)

162

FormView
It is a Template based control. Its view is similar to the Details view. It also allows paging and manipulation to the data.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

163

(Source: Module5\05FormViewControlEg.aspx)

163

Form View Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

164

(Source: Module5\05FormViewControlEg.aspx)

164

Form View after Binding

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

165

(Source: Module5\05FormViewControlEg.aspx)

165

Templates of Form View

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

166

(Source: Module5\05FormViewControlEg.aspx)

166

DataList Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

167

(Source: Module5\06DataListEg.aspx)

167

DataList Control after binding Data

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

168

(Source: Module5\06DataListEg.aspx)

168

DataList Control at run time

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

169

(Source: Module5\06DataListEg.aspx)

169

Repeater Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

170

(Source: Module5\07RepeaterEg.aspx)

170

Repeater Control Contd


<asp:Repeater ID="rpCategories" runat="server" DataSourceID="sdsCategories"> <HeaderTemplate><h1>Category Details</h1></HeaderTemplate> <ItemTemplate> Category ID: <b><%#Eval("CategoryID") %></b><br /> Category Name: <b><%#Eval("CategoryName") %></b> <br /> <asp:HyperLink runat="server" NavigateUrl='<%# "~/06ProductsInfo.aspx?catid="+ Eval("CategoryID").ToString()%>'>Products Information</asp:HyperLink> </ItemTemplate>

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

171

(Source: Module5\07RepeaterEg.aspx)

171

Repeater Control Contd


<AlternatingItemTemplate> Category ID: <b><font color="teal"><%#Eval("CategoryID") %></font></b><br /> Category Name: <b><font color="maroon"><%#Eval("CategoryName") %> </font></b> <br /> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# "~/06ProductsInfo.aspx?catid= +Eval(" CategoryID ").ToString()%>'>Products Information</asp:HyperLink> </AlternatingItemTemplate> <SeparatorTemplate><hr /></SeparatorTemplate> <FooterTemplate> <hr><h3>Thanks!!!</h3></FooterTemplate> </asp:Repeater>

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

172

(Source: Module5\07RepeaterEg.aspx)

172

Repeater Control Contd

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

173

(Source: Module5\07RepeaterEg.aspx)

173

Add Where Clause

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

174

(Source: Module5\07RepeaterEg.aspx)

174

Query

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

175

(Source: Module5\07RepeaterEg.aspx)

175

Product Details Page

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

176

(Source: Module5\08ProductsInfo.aspx)

176

Output

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

177

177

ListView Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

178

(Source: Module5\09ListViewControl.aspx) ListView Control: It is a new control introduced by .NET 3.5. It is a template based control. We can bind data to this control either through DataSourceID property or DataSource property. DataSourceID property helps bind a control to DataSourceControls. This gives all the capabilities of sorting, paging, modifying the data. DataSource property helps bind a control to DataSet, DataReader, Collections. But then to perform sorting, paging, and modifications we need to write the code.

178

Configuring ListView Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

179

(Source: Module5\09ListViewControl.aspx)

179

ListView Control Contd

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

180

(Source: Module5\09ListViewControl.aspx)

180

Module 7: Navigation Controls


Overview
About Navigation TreeView Menu SiteMapPath XMLDataSource SiteMapDataSource

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

181

181

About Navigation
Site navigation is used to provide the way to navigate the site. Provides tools to easily access the web pages. The controls such as TreeView, Menu and SiteMapPath is used for this purpose.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

182

182

TreeViewControl

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

183

(Source: Module7\01TreeViewEg.aspx) TreeView control displays the data in tree structure. The first node is the root node. It has parent nodes and leaf nodes that dont contain any further nodes. We can bind the tree view control to xml datasource and sitemap datasource controls. XMLDataSource control requires XML file as data and SiteMapDataSource requires sitemap file.

183

Using XMLDataSourceControl

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

184

(Source: Module7\01TreeViewEg.aspx)

184

Courses.xml file for Navigation Controls


<?xml version="1.0" encoding="utf-8" ?> <Courses> <Subject name="ASP.NET"> <Course name="Programming ASP.NET" url="~/Courses/aspnet1.aspx"/> <Course name="Developing Web Services" url="~/Courses/aspnet2.aspx"/> <Course name="Custom Control Development" url="~/Courses/aspnet3.aspx"/> </Subject> <Subject name="Windows Forms"> <Course name="Programming Windows Forms" url="~/Courses/winforms1.aspx"/>

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

185

(Source: Module7\01TreeViewEg.aspx)

185

Courses.xml file for Navigation Controls


<Course name="Developing Custom Controls" url="~/Courses/winforms2.aspx"/> <Course name="Database Programming in Windows Forms" url="~/Courses/winforms3.aspx"/> </Subject> <Subject name="Components"> <Course name="Understanding Remoting" url="~/Courses/remoting.aspx"/> <Course name="COM+ and .NET" url="~/Courses/complus.aspx"/> <Course name="Multithreading" url="~/Courses/threading.aspx"/> </Subject> </Courses>

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

186

(Source: Module7\01TreeViewEg.aspx)

186

Specifying Data File

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

187

(Source: Module7\01TreeViewEg.aspx) We need to provide xml file name as data file.

187

Select XML File

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

188

(Source: Module7\01TreeViewEg.aspx)

188

TreeView Example contd

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

189

(Source: Module7\01TreeViewEg.aspx) After providing the file, the nodes will not display proper text. We need to bind it by setting properties

189

Editing TreeNode Bindings

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

190

From the smart tag, we will choose Edit TreeNode DataBindings option. We will get the above screen. We will select subject and click on Add. Once it is added to the selected databindings, we will choose the property TextField. We will set it to the name attribute of the XML file.

190

Editing TreeNode Bindings

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

191

(Source: Module7\01TreeViewEg.aspx) After adding subject, add course. Set TextField to the name attribute of the course element and NavigateUrlField to url attribute of the course element.

191

TreeView After Editing TreeNode Bindings

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

192

(Source: Module7\01TreeViewEg.aspx) Once set the properties, the treeview would look like given in the slide.

192

Binding TreeNodes Mannually

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

193

(Source: Module7\02TreeView_Mannual.aspx) We can also bind treenodes manually. For this, Select TreeView control > Select Smart Tags > click Edit Nodes.

193

Adding Nodes

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

194

(Source: Module7\02TreeView_Mannual.aspx)

194

Specifying Url to Nodes

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

195

(Source: Module7\02TreeView_Mannual.aspx)

195

TreeView after Binding

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

196

(Source: Module7\02TreeView_Mannual.aspx)

196

Showing Checkboxes

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

197

(Source: Module7\03TreeView_CheckBox.aspx) To display checkboxes to the treeview, set the following property:

Control TreeView

Property ID ShowCheckBoxes ShowLines DataSourceID

Value tvCourse Leaf True XMLDataSource

197

Selecting Checked Items


protected void btnSelect_Click(object sender, EventArgs e) { foreach (TreeNode node in tvCourse.CheckedNodes) { lblSelect.Text += node.Text; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

198

(Source: Module7\03TreeView_CheckBox.aspx.cs)

198

Menu Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

199

(Source: Module7\04MenuEg.aspx)

199

Menu Control Contd

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

200

(Source: Module7\04MenuEg.aspx)

200

SiteMapPath Control Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

201

(Source: Module7\05SiteMapEg.aspx)

201

Adding SiteMap file

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

202

(Source: Module7\05SiteMapEg.aspx) To work with SiteMapPath control and SiteMapDataSource control, we need to add Web.sitemap file to the application. It is an xml based file. It contains the node hierarchy. We need to set the attributes given in the file to the required values.

202

Web.SiteMap file

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

203

(Source: Module7\web.sitemap) This slide shows the structure of sitemap file. It contains siteMapNode element and has three attributes namely url, title and description. The url attribute need to be set to the url of the file, title attribute to the text to be displayed to the user, and description will appear as a tool tip when the mouse pointer will be moved on the controls text.

203

SiteMapPath Control Example contd

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

204

(Source: Module7\05SiteMapEg.aspx) After creating the file,We need not to bind it explicitly to either SiteMapDataSource control or SiteMapPath control. When we just add any one of these, the file would be bound automatically. After adding SiteMapPath DataSource control, we need to drag the control on each file that we have set to the value of url attribute. As we want to create home, about us, contact us and branches pages, to the corresponding pages we will add the SiteMapPath control. It is shown in the next slide. This slide shows the home page.

204

Adding SiteMapPath control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

205

(Source: Module7\05SiteMapEg.aspx) (Source: Module7\sitemapfiles\about.aspx) (Source: Module7\sitemapfiles\contact.aspx) (Source: Module7\sitemapfiles\addresses.aspx)

205

Module 8: Themes and Master Pages


Overview
Themes Using properties and applying Themes Master Pages Creating and applying Master Pages

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

206

206

Themes
Adding a Skin File

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

207

(Source Code: Module8/01UsingThemeProperty.aspx) Themes are used to provide consistent look for the controls of the web pages. They can be set for individual pages or as global to all the pages in the Web.config file. Themes are stored into the special folders called as App_Theme. App_Theme is a special folder that stores all the themes. To store themes, we require skin files. Skin file stores the formats that we want to apply to the individual controls. We can either create individual skin files for individual controls or create one file for all the controls. Here we are creating Button.skin file to the application. It will add App_Themes.

207

Skin File

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

208

(Source Code: Module8/01UsingThemeProperty.aspx) The slide shows the skin file where we have stored the format for Button control. This format will be applied to all the buttons.

208

Setting Theme property

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

209

(Source Code: Module8/01UsingThemeProperty.aspx) Theme can be applied at page level or at application level. To apply it at page level, we need to add Theme property to the page directive of the individual page. It is to be set to the name of the folder which contains the skin file for the controls.

209

Using Theme property

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

210

(Source Code: Module8/01UsingThemeProperty.aspx) After setting the Theme property of the page, the control will not display the format during design. It will be applied during run time.

210

Adding multiple skins

Default Skin

Named Skin

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

211

(Source Code: Module8/02UsingSkinID.aspx) We can add multiple format instructions for a single control. When we add multiple formats for the same control, we need to bifurcate them by keeping one format instruction as default skin and other as a named skin. To define a named skin, we need to provide skin id. If we dont then we will get an error as default skin already exist.

211

Setting SkinID property

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

212

(Source Code: Module8/02UsingSkinID.aspx)

212

Applying Theme at Application level


Add the following line to the Web.config file to apply the theme at application level.
<pages theme="MyTheme"/>

Once applied, controls on all the pages will have the same format.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

213

(Source Code: Module8/03UsingGlobalTheme.aspx)

213

Disabling Theme

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

214

(Source Code: Module8/04EnableThemingPropertyEg.aspx) By default, themes are enabled as a property EnableThemining property is set to true. If we set it to false, the control will not be getting the format specified into the theme.

214

Master Pages
Master pages act as a template to the web pages. It provides consistent layout to the web pages. Contains placeholder to hold the content page data. It is a solution to User Controls.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

215

(Source Code: Module8/ExampleMasterPage1.master)

215

Content Page After adding Master Page

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

216

(Source Code: Module8/05UsingMasterPage.aspx)

216

Master Page Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

217

(Source Code: Module8/ExampleMasterPage2.master)

217

Content Page

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

218

(Source Code: Module8/06AccessingMasterPageControl.aspx)

218

Content Page Code


protected void Page_Load(object sender, EventArgs e) { Label lbl = (Label)Master.FindControl("lblDisplay"); lbl.Text = "My Content Page."; } protected void btnFill_Click(object sender, EventArgs e) { Response.Write("Setting control's text from content page"); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

219

(Source Code: Module8/06AccessingMasterPageControl.aspx.cs)

219

Module 9: State Management


Overview
What is State Management? Client Side State Mangement
ViewState QueryString Cookies

Server Side State Management


Application Session Database

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

220

220

State Management
State Management Techniques

Client - Side

Server - Side

View State Query String Cookies

Application State Session State Database

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

221

What is State Management? The standard transfer protocol (HTTP) is a stateless protocol. Web pages are regenerated when they are sent to the server. So, the information associated with the page is lost during round trip. To maintain this State Management techniques are provided by .NET Framework.

221

Client Side State Management


It doesnt use server resources to store page information. Fast server performance as it reduces the load on the server. But minimal on security. Techniques:
View State Query String Cookies

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

222

222

Maintaining View State


Used to retain page and control information between multiple requests for the same page. Maintained as a Hidden Field.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

223

Due to the stateless nature of the standard protocol, the information need to be maintained between round trips. So, whatever information is set to the controls during run time need to be retained. For this, we have View State that is enabled on almost all the controls to retain the value. To enable view state for a control, there is a property EnableViewState which need to be set to true. It maintains this information in a hidden field called as _VIEWSTATE. This hidden field stores control information in hashed, encrypted format. When the page is posted back to the server, the information stored in view state string is checked and restored to the controls.

223

Maintaining View State Eg

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

224

(Source Code: Module9/01ViewStateEg.aspx) Property to be set for the Label for view state: EnableViewState = True

224

Maintaining View State


protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { lblDisplay.Text = System.DateTime.Now.ToString(); Response.Write("Page loaded<br>"); } else { Response.Write("Postback event fired.<br>"); } } protected void btnSubmit_Click(object sender, EventArgs e) { Response.Write("Button Clicked"); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 225

(Source Code: Module9/01ViewStateEg.aspx.cs) Run the code. Make the EnableViewState property to false and try running the program. Disadvantages of ViewState: It affects the performance: As it is stored within the page it self, if large values are stored then it may slow down the load of the page as values stored in view state need to be loaded. They are not much secured: Though data stored in view state is in hashed format, it can be tempered with. They can be viewed directly leads to security issue.

225

Query String Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

226

(Source Code: Module9/02QueryStringEg.aspx) (Source Code: Module9/02_QueryString_Testing.aspx) Query String: It is the string appended with the URL of the page. It is used to pass information from one page to another. This is another way of maintaining state on client side. The information is passed from one page to another page with the URL. For e.g. www.shoppingmall.com\cart.aspx?productid=1. It is simple to implement. No server resources are required to maintain it. It requires HTTP Get method to submit the page.

226

Query String Example


using System.Data.SqlClient; public partial class _02QueryStringEg : System.Web.UI.Page { protected void btnSubmit_Click(object sender, EventArgs e) { Response.Redirect("~/02_QueryString_Testing.aspx?name=" + txtName.Text); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

227

(Source Code: Module9/02QueryStringEg.aspx.cs)

227

Retrieving Query String Value


string strName; protected void Page_Load(object sender, EventArgs e) { strName = Request.QueryString["name"]; lblName.Text += strName; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

228

(Source Code: Module9/02_QueryString_Testing.aspx.cs)

228

Query String Output

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

229

(Source Code: Module9/02QueryStringEg.aspx) (Source Code: Module9/02_QueryString_Testing.aspx) Limitations of Query String: 1.Visible in the browser: It is easily visible in the address bar of the browser, so anybody can easily temper with it. A user can bookmark the url and can send it to another user along with the query string. 2.Limited capacity: Limited data can be sent through query string. Some browsers may allow only 255 characters of data to be passed through query string. 3.Advantage of query string can not be availed if the page is passed using HTTP POST method.

229

Cookies
Text files used to store user information. It is light weight, stores data in key/value pair. Information is stored with the request to the server. Can be temporary or permanent.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

230

(Source Code: Module9/03Cookies.aspx) Cookies: Cookies are used to store user information. They are light weight and stores information in key and value pair. Whenever user accesses the web page of a site for the first time, some user specific information is stored in a text file and sent to the client. Next time when user visits the same page, the information is picked up from the text file and used to render the pages. Cookies can be temporary that remains on client machine till the user session is active. Cookies can be permanent that remains on the client machine for a specific duration.

230

Cookie Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

231

(Source Code: Module9/03Cookies.aspx)

231

Cookie Example
Creating Cookie
protected void btnWriteCookie_Click(object sender, EventArgs e) { HttpCookie cookie = new HttpCookie("MyCookie"); cookie.Expires = System.Convert.ToDateTime("10/31/2005"); cookie.Value = System.DateTime.Now.ToString(); Response.Cookies.Add(cookie); Response.Write("Cookie Written"); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

232

(Source Code: Module9/03Cookies.aspx.cs)

232

Cookie Example
Retrieving a Cookie.
protected void btnReadCookie_Click(object sender, EventArgs e) { HttpCookie cookie = Request.Cookies.Get("MyCookie"); if (cookie != null) { Response.Write(cookie.Value); } else { Response.Write("Cookie doesnot exist"); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

233

(Source Code: Module9/03Cookies.aspx.cs) Limitations of Cookies: 1.Size limitations: Limited amount of data can be stored. Around 4096 bytes data can be stored. 2.Restrictions on client browsers: Client may disable the cookies then this functionality will not be available. Client may delete the cookie. 3.Security risk: Cookies can be tempered with as it is visible to the users.

233

Server Side State Management


Page information is maintained on server. Provides high security to the information. State Management options:
Application State Session State Database

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

234

234

Application State
Stores the information that is available to all the pages of the website. The information is stored with the application state variables in the form of key and value pair. Data is shared by multiple sessions.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

235

(Source Code: Module9/04ApplicationState.aspx) (Global.asax) Application State is an instance of HTTPApplicationState class. It stores data in key / value pair. Application state is stored on server memory and is faster to retrieve data. Application state is applicable to all users. Global.asax file: It is a Global Application Class file that stores server events that are fired for application and sessions. The events available are: Application_Start, Application_End, Application_Error, Session_Start, Session_End. Application_Start event is fired when application is hit for the first time. Happens only once. Session_Start event is fired when each user session is started. Session_End is fired either with session timeout or on the call of Abandon() method of session. Application_End evnt is fired on server crash or server shut down.

235

Application State Management Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

236

(Source Code: Module9/04ApplicationState.aspx)

236

Application State Management Example


protected void Page_Load(object sender,System.EventArgs e) { lblCount.Text="No of Hits: " + Application["Count"].ToString(); lblSessionId.Text = "Session ID: " + Session.SessionID; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

237

(Source Code: Module9/04ApplicationState.aspx.cs)

237

Application State Management Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

238

(Source Code: Module9/04ApplicationState.aspx) Limitation of Application State: Requires server resources and there by occupying space on the server and affecting the application scalability. It is volatile. It will be lost if the server process is distroyed.

238

Session State
Allows to store each user session specific value. Values are stored on the server.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

239

(Source Code: Module9/05SessionState.aspx) (Source Code: Module9/05Session_State_Testing.aspx)

239

Retrieving Session Data

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

240

(Source Code: Module9/05SessionState.aspx) (Source Code: Module9/05Session_State_Testing.aspx) Limitations of Session State are: Affects Performance: Session state can store single values as well as large amount of data like dataset. It stays in the server memory till it is removed or replaced. This slows down the performance of the server.

240

Session State Example Code


Setting Session Variable
protected void btnSetName_Click(object sender, EventArgs e) { Session["Name"] = txtName.Text; Response.Redirect("~/05Session_State_Testing.aspx"); }

Retrieving Session Variable:


protected void Page_Load(object sender, EventArgs e) { string name = Session["Name"].ToString(); lblName.Text += ": " +name; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

241

(Source Code: Module9/05SessionState.aspx.cs) (Source Code: Module9/05Session_State_Testing.aspx.cs)

241

Module 10: Caching


Overview
What is Caching? Types of Caching
Page output caching Data Caching

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

242

242

What is Caching?
Storing data which is accessed frequently and takes significant amount of processing time to improve performance. We can cache either the output displayed on the page or data retrieved from the database or some complex logic. Used to reduce server hits there by reducing the load on the server.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

243

243

Types of Caching
Page Output Caching
Page Caching Fragment Caching Post Cache Substitution

Data Caching
Invalidating Cache by using Expiration Policies
Absolute Expiration Sliding Expiration

Dependencies
File Dependency Sql Cache Dependency

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

244

Types of Caching: 1.Page Output Caching: 1. Page Caching: Here the entire page content remains into the memory for a specific duration. When the duration elapses, the cache is refreshed with the new data i.e. page content. For that specific duration, the page is retrieved from the cache there by avoiding recreation of page every time. 2. Fragment Caching: Only a part of the page is cached for specific duration. Rest of the page is rendered from the server. Web user control is used to achieve this. 3. Post Cache Substitution: It is an opposite of Fragment Caching. Here, only a part of the page is refreshed every time when page is retrieved. Rest of the page remains cached for specific duration. Substitution control is used to achieve this. 2.Data Caching: Asp.Net allows data to be cached in to the memory. Data can either be retrieved from the file or database. To save frequent database access, we cache the data. There is an inbuilt object available called as Cache that stores the data. To invalidate cache items we can either use Expiration Policies or Dependencies. 1. Expiration Policies: Cache can expire on the basis of Time Spans. There are two expiration policies available: 1. Absolute Expiration: For fixed duration the data will remain in the cache. Once that duration is elapsed, the cache will get invalidated, new data will be fetched and added to the cache. 2. Sliding Expiration: That is for how long the data will remain into the cache after it is last accessed. It is achieved through TimeSpan values. 2. Dependencies: The cache is dependent on some resource like database or a file. If any changes happen to these resources then the cache is refreshed. 1. File Dependency: The data can be cached based on file like XML file. Whenever changes are made to the file they are retrieved into the cache. 2. Sql Cache Dependency: The data in the cache is dependent on the database.

244

Page Caching

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

245

(Source Code: Module10/OutputCaching/01PageCaching.aspx) For page output caching, we need to add a directive as follows: <%@ OutputCache Duration="10" VaryByParam="none"%> Duration Attribute: Specifies the time span for which the page output will remain in the cache. VaryByParam Attribute: Specifies that whether cache will vary by a parameter passed to the page. In this page, it is set to none.

245

Page Caching
protected void Page_Load(object sender, EventArgs e) { lblTime.Text = System.DateTime.Now.ToString(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

246

(Source Code: Module10/OutputCaching/01PageCaching.aspx.cs)

246

VaryByParam Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

247

(Source Code: Module10/OutputCaching/02VaryByParamEg.aspx) (Source Code: Module10/OutputCaching/02_VaryByParamEg_Testing.aspx)

247

VaryByParam Example Testing

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

248

(Source Code: Module10/OutputCaching/02_VaryByParamEg_Testing.aspx)

Put this line of code in the html source: <%@ OutputCache Duration="10" VaryByParam="city"%>

248

Code
Passing Parameter:
protected void btnSubmit_Click(object sender, EventArgs e) { Response.Redirect("~/02_VaryByParamEg_Testing.aspx?city=" + txtCity.Text); }

Retrieving Parameter:
protected void Page_Load(object sender, EventArgs e) { lblTime.Text = System.DateTime.Now.ToString(); lblCity.Text ="City Entered: "+ Request.QueryString.Get("city"); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

249

(Source Code: Module10/OutputCaching/02VaryByParamEg.aspx.cs) (Source Code: Module10/OutputCaching/02_VaryByParamEg_Testing.aspx.cs)

249

Vary By Param Example Testing

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

250

(Source Code: Module10/OutputCaching/02VaryByParamEg.aspx) (Source Code: Module10/OutputCaching/02_VaryByParamEg_Testing.aspx)

250

Vary By Control Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

251

(Source Code: Module10/OutputCaching/03VaryByControl.aspx) The directive for this example would be as follows: <%@ OutputCache Duration="10" VaryByControl="txtColor" %> VaryByControl Attribute: The cache varies according to the changes made to the control. It takes control ID as a value.

251

Vary By Control Example


protected void Page_Load(object sender, EventArgs e) { lblTime.Text = System.DateTime.Now.ToString(); } protected void btnApply_Click(object sender, EventArgs e) { lblTime.BackColor = Color.FromName(txtColor.Text); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

252

(Source Code: Module10/OutputCaching/03VaryByControl.aspx.cs)

252

Fragment Caching
We need to use a web user control for fragment caching.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

253

(Source Code: Module10/OutputCaching/01WebCntPartialPageCaching.ascx) (Source Code: Module10/OutputCaching/04FragmentCaching.aspx)

253

Fragment Caching Contd(User Control)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

254

(Source Code: Module10/OutputCaching/01WebCntPartialPageCaching.ascx) (Source Code: Module10/OutputCaching/04FragmentCaching.aspx) Add OutputCache directive to the control. The control is saved with the extension .ascx.

254

Fragment Caching Contd


Code for Label on the user control:
protected void Page_Load(object sender, EventArgs e) { lblTime.Text ="Control Time: "+ System.DateTime.Now.ToString(); }

Code for Label on the Page:


protected void Page_Load(object sender, EventArgs e) { lblTimer.Text = "Main Page Time: " + System.DateTime.Now.ToString(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

255

(Source Code: Module10/OutputCaching/01WebCntPartialPageCaching.ascx.cs) (Source Code: Module10/OutputCaching/04FragmentCaching.aspx.cs)

255

Fragment Caching Contd (Main Page)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

256

(Source Code: Module10/OutputCaching/01WebCntPartialPageCaching.ascx) (Source Code: Module10/OutputCaching/04FragmentCaching.aspx) After creating the control, we need to add it on the page. For adding a control, the following directive is used. <%@ Register Src="~/01WebCntPartialPageCaching.ascx" TagName="WebCntPartialPageCaching" TagPrefix="ucl" %>

256

Fragment Caching Contd(Main Page Source)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

257

(Source Code: Module10/OutputCaching/01WebCntPartialPageCaching.ascx) (Source Code: Module10/OutputCaching/04FragmentCaching.aspx)

257

Post Cache Substitution

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

258

(Source Code: Module10/OutputCaching/05PostCacheSubstitution.aspx)

258

Post Cache Substitution


protected void Page_Load(object sender, EventArgs e) { lblTime.Text = System.DateTime.Now.ToString(); } public static string getTime(HttpContext context) { return "Page refreshed at " + System.DateTime.Now.ToString() + " by " + context.User.Identity.Name; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

259

(Source Code: Module10/OutputCaching/05PostCacheSubstitution.aspx.cs)

259

Data Caching

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

260

(Source Code: Module10/DataCaching/01SimpleDataCaching.aspx)

260

Data Caching Contd


SqlConnection con; SqlDataAdapter da; DataSet ds; protected void Page_Load(object sender, EventArgs e) { if (Cache.Get("SimpleData") == null) { con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString); da = new SqlDataAdapter("select productid,productname, unitprice from products where productid <=10", con); ds = new DataSet();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

261

(Source Code: Module10/DataCaching/01SimpleDataCaching.aspx.cs)

261

Data Caching Contd


da.Fill(ds, "Products"); Cache.Insert("SimpleData", ds); lblTime.Text = "Data retrieved at " + System.DateTime.Now.ToString(); } else { ds = (DataSet)Cache.Get("SimpleData"); lblTime.Text = "Data retrieved from Cache."; } gdvProducts.DataSource = ds.Tables[0]; gdvProducts.DataBind(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

262

(Source Code: Module10/DataCaching/01SimpleDataCaching.aspx.cs)

262

Absolute Expiration

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

263

(Source Code: Module10/DataCaching/02AbsoluteExpiration.aspx) Absolute Expiration: The cache will expire after a set period of time, irrespective of whether it is accessed by users or not.

263

Absolute Expiration Contd


SqlConnection con; SqlDataAdapter da; DataSet ds; protected void Page_Load(object sender, EventArgs e) { if (Cache.Get("AbsoluteData") == null) { con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString); da = new SqlDataAdapter("select productid,productname, unitprice from products where productid <=10", con); ds = new DataSet(); da.Fill(ds, "Products");

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

264

(Source Code: Module10/DataCaching/02AbsoluteExpiration.aspx.cs)

264

Absolute Expiration Contd


//Absolute Expiration Cache.Insert("AbsoluteData", ds,null,DateTime.Now.AddSeconds(10),TimeSpan.Zero); lblTime.Text = "Data retrieved at " + System.DateTime.Now.ToString(); } else { ds = (DataSet)Cache.Get("AbsoluteData"); lblTime.Text = "Data retrieved from Cache."; } gdvProducts.DataSource = ds.Tables[0]; gdvProducts.DataBind(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

265

(Source Code: Module10/DataCaching/02AbsoluteExpiration.aspx.cs)

265

Sliding Expiration

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

266

(Source Code: Module10/DataCaching/03SlidingExpiration.aspx) Sliding Expiration: It is to set that after what duration the cache will expire after it is last accessed.

266

Sliding Expiration Contd


SqlConnection con; SqlDataAdapter da; DataSet ds; protected void Page_Load(object sender, EventArgs e) { if (Cache.Get("SlidingData") == null) { con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString); da = new SqlDataAdapter("select productid,productname, unitprice from products where productid <=10", con); ds = new DataSet();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

267

(Source Code: Module10/DataCaching/03SlidingExpiration.aspx.cs)

267

Sliding Expiration Contd


da.Fill(ds, "Products"); //Sliding Expiration Cache.Insert("SlidingData", ds, null, DateTime.MaxValue, TimeSpan.FromSeconds(10)); lblTime.Text = "Data retrieved at " + System.DateTime.Now.ToString(); } else { ds = (DataSet)Cache.Get("SlidingData"); lblTime.Text = "Data retrieved from Cache."; } gdvProducts.DataSource = ds.Tables[0]; gdvProducts.DataBind(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

268

(Source Code: Module10/DataCaching/03SlidingExpiration.aspx.cs)

268

File Dependency

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

269

(Source Code: Module10/DataCaching/04FileDependency.aspx)

269

Courses.xml File
<?xml version="1.0" encoding="utf-8" ?> <Courses> <course> <name>ASP.NET 2.0</name> <duration>80Hrs</duration> </course> <course> <name>VB.NET 2.0</name> <duration>120Hrs</duration> </course> <course> <name>VB.NET 2.0</name> <duration>120Hrs</duration> </course> </Courses>
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 270

(Source Code: Module10/DataCaching/Courses.xml)

270

File Dependency Contd


using System.Web.Caching; public partial class _04FileDependency : System.Web.UI.Page { DataSet ds; CacheDependency cd; protected void Page_Load(object sender, EventArgs e) { if (Cache.Get("FileData") == null) { ds = new DataSet(); ds.ReadXml(Server.MapPath("courses.xml")); cd = new CacheDependency(Server.MapPath("courses.xml")); Cache.Insert("FileData", ds, cd); lblTime.Text = "Cache retrieved at: " + System.DateTime.Now.ToString(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 271

(Source Code: Module10/DataCaching/04FileDependency.aspx.cs)

271

File Dependency Contd


else { ds = (DataSet)Cache.Get("FileData"); lblTime.Text = "Data retrieved from Cache."; } gdvCourses.DataSource = ds; gdvCourses.DataBind(); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

272

(Source Code: Module10/DataCaching/04FileDependency.aspx.cs)

272

SQL Dependency

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

273

(Source Code: Module10/DataCaching/05SQLCacheDependency.aspx)

273

Command Line Utility

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

274

(Source Code: Module10/DataCaching/05SQLCacheDependency.aspx) In order to work with SQL Cache Dependency, we need to enable the database as well as the table for dependency. Asp.Net provides a command line utility for this purpose. On the visual studio command prompt we need to write the following line of code: To enable SQL Cache Dependency on the Database: >aspnet_regsql S PSPL2939\SA1 E d Northwind ed To enable SQL Cache Dependency on the Table: >aspnet_regsql S PSPL2939\SA1 E d Northwind Explanation for switches provided by the utility: -S : Provide server name -E : Trusted Connection -U : User Name -P : Password -d : Database -ed : Enable dependency on Database -t : Table -et : Enable dependency on Table. -lt : List tables -t Products et

274

Configuring Web.config
<caching> <sqlCacheDependency enabled="true"> <databases> <add name="Northwind" connectionStringName ="constr" pollTime=500"/> </databases> </sqlCacheDependency> </caching>

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

275

(Source Code: Module10/DataCaching/05SQLCacheDependency.aspx)

275

SQL Cache Dependency Example Contd


public partial class _05SQLCacheDependency : System.Web.UI.Page { SqlConnection con; SqlDataAdapter da; DataSet ds; SqlCacheDependency cd; protected void Page_Load(object sender, EventArgs e) { if (Cache.Get("SqlData")==null) { con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString); da = new SqlDataAdapter("select productid,productname, unitprice from products where productid <=10", con);

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

276

(Source Code: Module10/DataCaching/05SQLCacheDependency.aspx.cs)

276

SQL Cache Dependency Example Contd


ds = new DataSet(); da.Fill(ds, "Products"); cd = new SqlCacheDependency("Northwind", "Products"); Cache.Insert("SqlData", ds,cd); lblTime.Text = "Data retrieved at " + System.DateTime.Now.ToString(); } else { ds = (DataSet)Cache.Get("SqlData"); lblTime.Text = "Data retrieved from Cache."; } gdvProducts.DataSource = ds.Tables[0]; gdvProducts.DataBind(); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

277

(Source Code: Module10/DataCaching/05SQLCacheDependency.aspx.cs)

277

Module 11: Security


Overview
Authentication Authorization

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

278

278

Authentication
Three Authentication Modes are available:
Windows Authentication Forms Authentication Passport Authentication

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

279

Three Modes of Authentication: 1.Windows Authentication: It considers the user identity supplied by Internet Information Services for Authentication. It is the default authentication mode. 2.Forms Authentication: It allows user created credentials to be checked for authentication purpose. In this type of authentication, we need to create a login page to accept credentials. Whenever user requests any page of the web site, he/she will be taken to login page for authentication. After authentication he/she will be redirected to the requested page. 3.Passport Authentication: It is a centralized authentication service provided by Microsoft that helps users to use single logon for member sites.

279

Windows Authentication

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

280

(Source Code: Module11/WindowsAuthentication/01WindowsAuthenticationEg.aspx) We need to configure Web.config file. The following elements need to be added. <authentication mode="Windows"/> <authorization> <deny users="?"/> </authorization> By default authentication mode is Windows. Authorization helps to check whether user has got rights to access the page or not. <deny users=?/> here ? means anonymous access which can be allowed or denied by using element <allow> or <deny>

280

Windows Authentication Contd


protected void Page_Load(object sender, EventArgs e) { lblUserName.Text = User.Identity.Name; if (User.Identity.IsAuthenticated) { lblDisplayText.Visible = true; } else { lblDisplayText.Visible = false; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

281

(Source Code: Module11/WindowsAuthentication/01WindowsAuthenticationEg.aspx.cs)

281

Forms Authentication

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

282

(Source Code: Module11/FormsAuthentication/Login.aspx)

282

Configurations in Web.config
<authentication mode="Forms"> <forms name="Login" loginUrl=Login.aspx" defaultUrl=Index.aspx"/> </authentication> <authorization> <deny users="?"/> </authorization>

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

283

(Source Code: Module11/FormsAuthentication/web.config)

283

Login Page Code


protected void btnLogin_Click(object sender, EventArgs e) { if (ValidateUser(txtUserName.Text, txtPassword.Text)) { FormsAuthentication.SetAuthCookie(txtUserName.Text, chkRememberMe.Checked); string url = FormsAuthentication.GetRedirectUrl(txtUserName.Text, chkRememberMe.Checked); Response.Redirect(url); } } private bool ValidateUser(string user, string password) { SqlConnection con = new SqlConnection("data source=PSPL2939\\sa1;initial catalog=northwind;integrated security=true;"); con.Open();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

284

(Source Code: Module11/FormsAuthentication/Login.aspx.cs)

284

Login Page Code Contd


SqlCommand cmd = new SqlCommand("select userid from users where userid=@uid and password=@pwd", con); cmd.Parameters.AddWithValue("@uid", user); cmd.Parameters.AddWithValue("@pwd", password); object obj = cmd.ExecuteScalar(); if (obj != null) { return true; } else { return false; } con.Close(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 285

(Source Code: Module11/FormsAuthentication/Login.aspx.cs)

285

Index Page

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

286

(Source Code: Module11/FormsAuthentication/Index.aspx)

286

Index Page Code

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

287

(Source Code: Module11/FormsAuthentication/Index.aspx.cs)

287

Web site Administration Tool

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

288

Web Site Configuration: The site configuration is generally stored in Web.Config file. The administration tool allows to configure the settings through an Administration Tool without having to do it manually. This tool creates a configuration file, if it does not exist with the application. It also generates the required databases for memberships, roles, profiles etc. in App_Data folder. It is a tab based tool. It has the following tabs: Security Tab: Helps to manage authentication, membership, roles related to users. Application Tab: We can do application settings, take application offline, can do SMTP settings, debugging and tracing. Provider Tab: Allows to choose providers for membership, roles, profiles.

288

Security Tab

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

289

289

Create User

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

290

290

Manage Users

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

291

291

Application Tab

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

292

292

Provider Tab

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

293

293

Module 12: Login controls and Membership API


Overview
MemberShip API Membership Provider Asp.Net SQL Server Setup Wizard

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

294

294

Membership API
Membership deals with managing the users. It allows creation, validation of users. It simplifies the management of users as it provides built in methods to manipulate users.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

295

Membership provides following facilities: 1.Creation of a new user. 2.Authenticating a user by validating user credentails. 3.Storing user, membership related information in database. 4.Changing password. 5.Deleting users. 6.Retrieving password. It uses membership provider with the name AspNetSqlProvider to store all membership and user related data.

295

Membership Provider
<membership> <providers> <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="LocalSqlServer" enablePasswordRetrieval="false enablePasswordReset="true" requiresQuestionAndAnswer="true applicationName="/" requiresUniqueEmail="false passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" /> </providers> </membership>

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

296

Membership provides various features that can be configured in web.config file. The above slide shows the membership provider and the settings that can be applied to membership provider. These default settings are provided by machine.config file which can be overridden in web.config file.

296

Asp.Net SQL Server Setup Wizard

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

297

This set up wizard is used to create a database with the name aspnetdb that contains all the information related to membership, roles, users, profiles etc. For this purpose one need to run a command line utility aspnet_regsql.exe

297

Select Option

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

298

298

Server and Database

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

299

299

Name of the database

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

300

300

Configured the database

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

301

301

Configuration Settings
<connectionStrings> <remove name="LocalSqlServer"/> <add name="LocalSqlServer" connectionString="server=pspl2939\sa1;database=aspnetdb;integrated security=true" providerName="System.Data.SqlClient"/> </connectionStrings> <authentication mode="Forms"> <forms name="Login" loginUrl=Login.aspx" defaultUrl=Index.aspx"/> </authentication> <authorization> <deny users="?"/> </authorization>

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

302

(Source Code: Module12/MembershipAPI/web.config)

302

Login Controls

Login Control

Create User Control

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

303

(Source Code: Module12/LoginControlsEg/Login.aspx)

303

Login Controls Contd

LoginName LoginStatus

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

304

(Source Code: Module12/LoginControlsEg/Index.aspx)

304

Module 13: Configuration, Administration and Deployment of the Web Application Overview
Asp.Net Configuration System Structure of web.config Administrating Asp.Net web application Storing Database connection string in config file Web Site Administration Tool Deploying Asp.Net application

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

305

305

ASP.NET Configuration System


Has two configuration files, Machine.config and Web.config Machine.config is a master configuration file. Contains settings to be applied for all applications running on the machine where file is located Web.config exist for each application.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

306

306

Machine.config

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

307

Located at Drive>\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.config

307

Web.config

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

308

Web.config file has an inheritance behavior. It inherits the settings from Machine.config file. There can be one or more web.config files in one or more folders of the application. By default one web.config gets added per application. But a file kept in a sub folder takes precedence over the default web.config.

308

IIS Manager

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

309

309

Administering Asp.Net application

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

310

Instead of configuring settings mannually into web.config file, we can use a tool provided to make these changes.

310

The General Tab

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

311

The General Tab helps manage the connection strings and application settings for the application.

311

The Authentication Tab

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

312

312

Deploying Web Site


Compilation Models
Full runtime compilation

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

313

313

Create Web Setup

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

314

(Source Code: Module13\WebSetup_Test)

314

The File System Editor

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

315

(Source Code: Module13\WebSetup_Test) The file system editor shows Web Application Folder that shows what is to be installed on the target machine.

315

Add Existing Project

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

316

(Source Code: Module13\WebSetup_Test) Before we add any project to the web setup, we need to set compilation mode debug to false.

316

Add Output

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

317

Add Project Output Group

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

318

(Source Code: Module13\WebSetup_Test) After adding the project output, build the web setup project. Set the compilation mode to Release and not to Debug.

318

Start Installer

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

319

319

Select Path

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

320

320

Confirm Installation

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

321

321

Installation Complete

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

322

322

Running Deployed WebSite

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

323

323

Module 14: Web Services


Overview
Introduction to Web Services The SOAP protocol WSDL Create Web Service Test Web Service Consume Web Service

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

324

324

Introduction to Web Service


XML Web Service is a programmable logic accessible by standard web protocols
Allow applications to send and receive information across the internet Language and Platform independent

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

325

A web service exposes a number of methods that provide functionality that can be used by one or more applications, regardless of the programming languages, operating systems and hardware platforms used to develop them. The methods that provide such functionality are called web methods. Some of the use of XML Web Service Authentication Services Weather Reports Exchange Rate Stock Quotes Etc.

325

Components of Web Services


Communication through SOAP messages

Client Application

Web Service

Locate a Web Service

Describes

WSDL Document UDDI Registry

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

326

Web service is comprised of five fundamental components Delivery Medium Internet Delivery Protocol HTTP Message Formatting SOAP (Simple Access Object Protocol) Service Description WSDL (Web Service Description Language) Web Service Publication UDDI (Universal Description, Discovery and Integration)

326

The SOAP Protocol


SOAP (Simple Object Access Protocol) is a key to Web Services communication. It is a simple, lightweight and XML based protocol. Used to exchange XML based messages.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

327

327

WSDL
WSDL (Web Services Description Language) is used to locate web services. It describes the web service by containing links to the resources that define the web service.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

328

328

Create Web Service


Go to File > New > WebSite >ASP.NET Web Service

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

329

329

WebServiceHello Example
Service Class
[WebService(Namespace = "http://tempuri.org/")] public class ServiceHello : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

330

(Source Code: Module14\WebServiceHello\App_Code\ServiceHello.cs)

330

Testing Web Service

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

331

(Source Code: Module14\WebServiceHello\App_Code\ServiceHello.cs)

331

Adding Web Reference

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

332

(Source Code: Module14\WebServiceHelloTesting\01ServiceHelloTesting.aspx)

332

Select Web Service

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

333

(Source Code: Module14\WebServiceHelloTesting\01ServiceHelloTesting.aspx)

333

Add Reference

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

334

(Source Code: Module14\WebServiceHelloTesting\01ServiceHelloTesting.aspx)

334

Test Code
using TestService; public partial class _01ServiceHelloTesting : System.Web.UI.Page { ServiceHello hello; protected void Page_Load(object sender, EventArgs e) { hello = new ServiceHello(); Response.Write(hello.HelloWorld()); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

335

(Source Code: Module14\WebServiceHelloTesting\01ServiceHelloTesting.aspx.cs)

335

Test Service

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

336

(Source Code: Module14\WebServiceHelloTesting\01ServiceHelloTesting.aspx)

336

Exchange Rate XML File


<?xml version="1.0" encoding="utf-8" ?> <ExchangeRate> <ERate> <Country>Usa</Country> <Rate>41</Rate> </ERate> <ERate> <Country>Uk</Country> <Rate>70</Rate> </ERate> <ERate> <Country>Japan</Country> <Rate>120</Rate> </ERate> </ExchangeRate>

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

337

(Source Code: Module14\WebServiceExchangeRate\ExchangeRate.xml)

337

Service Class
public class ServiceExchangeRate : System.Web.Services.WebService { [WebMethod] public decimal GetExchangeRate(string country) { DataSet ds = new DataSet(); decimal rate; ds.ReadXml(Server.MapPath("~/ExchangeRate.xml")); DataRow[] row = ds.Tables[0].Select("Country='" + country + "'"); if (row != null) { rate = decimal.Parse(row[0]["Rate"].ToString()); return rate; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 338

(Source Code: Module14\WebServiceExchangeRate\App_Code\ServiceExchangeRate.cs)

338

Service Class
else { rate = 0; return rate; } } [WebMethod] public string[] GetCountries() { DataSet ds = new DataSet(); List<string> countryList = new List<string>(); ds.ReadXml(Server.MapPath("~/ExchangeRate.xml")); foreach (DataRow dr in ds.Tables[0].Rows) { countryList.Add(dr["Country"].ToString()); } return countryList.ToArray(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 339

(Source Code: Module14\WebServiceExchangeRate\App_Code\ServiceExchangeRate.cs)

339

Test Web Service

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

340

(Source Code: Module14\WebServiceExchangeRate\ServiceExchangeRate.asmx)

340

Invoke Web Method

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

341

(Source Code: Module14\WebServiceExchangeRate\ServiceExchangeRate.asmx)

341

XML Output

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

342

(Source Code: Module14\WebServiceExchangeRate\ServiceExchangeRate.asmx)

342

Testing Web Method with Parameter

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

343

(Source Code: Module14\WebServiceExchangeRate\ServiceExchangeRate.asmx)

343

Output

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

344

(Source Code: Module14\WebServiceExchangeRate\ServiceExchangeRate.asmx)

344

Consume Web Service - Design

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

345

(Source Code: Module14\WebServiceExchangeRateTest\01TestExchangeRateService.aspx)

345

Add Web Reference

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

346

(Source Code: Module14\WebServiceExchangeRateTest\01TestExchangeRateService.aspx) Go to Project Menu > Add Web Reference Select web Services on the Local Machine

346

Select Web Service

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

347

(Source Code: Module14\WebServiceExchangeRateTest\01TestExchangeRateService.aspx)

347

Crete Proxy

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

348

(Source Code: Module14\WebServiceExchangeRateTest\01TestExchangeRateService.aspx) Click on Add Reference.

348

Add Web Reference

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

349

(Source Code: Module14\WebServiceExchangeRateTest\01TestExchangeRateService.aspx) A folder with the name App_WebReferences would be added to the application which contains the reference we have added.

349

Consume Web Service - Code


public partial class _01TestExchangeRateService : System.Web.UI.Page { ExchangeRate.ServiceExch4``angeRate service = new ExchangeRate.ServiceExchangeRate(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { lstCountry.DataSource = service.GetCountries(); lstCountry.DataBind(); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

350

(Source Code: Module14\WebServiceExchangeRateTest\01TestExchangeRateService.aspx.cs)

350

Consume Web Service - Code


protected void lstCountry_SelectedIndexChanged(object sender, EventArgs e) { lblDisplayRate.Text = ""; decimal rate; if (lstCountry.SelectedIndex > -1) { rate = service.GetExchangeRate(lstCountry.SelectedItem.Text); lblDisplayRate.Text +="Exchange Rate: "+ rate.ToString(); } } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

351

(Source Code: Module14\WebServiceExchangeRateTest\01TestExchangeRateService.aspx.cs)

351

Test The Code

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

352

(Source Code: Module14\WebServiceExchangeRateTest\01TestExchangeRateService.aspx)

352

You might also like