copyright ©2004 virtusa corporation | confidential asp.net 2.0 architecture ruwan wijesinghe

83
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

Upload: leslie-goodwin

Post on 04-Jan-2016

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

ASP.NET 2.0 Architecture

Ruwan Wijesinghe

Page 2: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

2Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

ASP.NET Framework

WebBrowser IIS

ASP.NET ISAPIASP.NET ISAPI

IS API

Http Modules

Session

Authentication

etc.

.aspx, .asmx,

.ashx ,etc.

PageHandlerFactory

Http Handlers

ASPX Pages

.aspx

Page 3: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

3Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

ASPX Page (MyPage.aspx)

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> ID<asp:TextBox ID="TextBox1" runat="server" /><br /> Name<asp:TextBox ID="TextBox2" runat="server" /><br /> <asp:Button ID="Button1" runat="server" Text="Button"

OnClick="Button1_Click"/></div>

</form></body></html>

Page 4: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

4Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Code Behind File (MyPage.aspx.cs)

public partial class MyPage : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) {

if (!this.IsPostBack){

TextBox1.Text = "Hello";}

}

protected void Button1_Click(object sender, EventArgs e){

TextBox2.Text = TextBox1.Text;}

}

Page 5: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

5Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Some Facts about ASPX pages

Life Time

• New instances of a web page class and all its controls are created for each request.

• Page and all its controls are destroyed after producing the output, leaving resources to new requests.

State

• ViewState object is used to preserve the states of the page and its child controls during round-trips.

• ViewState object compress, encrypt and saves the data in a hidden variable of the client web page, which will be posted back in the next request

Page 6: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

6Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Page Events

• ASPX pages process the data, and generates the output as responses to a series of events

• These events occur in the following order• PreInit• Init• LoadState – Load view state• ProcessPostData – Load post back data to the controls• PreLoad• Load – call Page_Load method• Raise Changed Events – e.g. TextBox1_TextChanged• Raise Postback Events – e.g. Button1_Click• PreRender• SaveSate – Save view state• Render

Page 7: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

7Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

ASP.NET 2.0 Compilation Model

partial class Default(code behind file - Default.aspx.cs)

partial class Default(code behind file - Default.aspx.cs)

web page "Default.aspx"

web page "Default.aspx"

partial class Defaultpartial class Default

class ASP.Default_aspx(class which finally produces the output)

class ASP.Default_aspx(class which finally produces the output)Compiled

into

class Default

Inherit From

System.Web.UI.PageSystem.Web.UI.Page

Inherit From

Compiled into

Page 8: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

8Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Compilation

• Normal (used in ASP.NET 1.0)aspx files are compiled runtime and code behind files are deployed pre-compiled in to assemblies in /bin directory (Still used in ASP.NET 2.0, however not supported by the IDE)

• Fully Runtime CompilationBoth aspx files and code files are deployed uncompelled. aspx files and their code behind files (specified using “CodeFile” attribute of @Page tag) are compiled at the first request. All the code files copied into /app_code directory will be automatically compiled and reference to them will be automatically added to all the assemblies in the web application.

• Pre-Compiled DeploymentBoth aspx and code behind files will be fully compiled before deployment. The assembly containing the compiled code will be deployed to the /bin directory and stub files with the same name as aspx files will be created in appropriate directories just to represent their presence (This is required, as the physical location of aspx flies in the directory structure affects the security settings of the application). This can be done using “aspnet_compiler” tool or building the solution file with “MSBuild” tool

Page 9: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

9Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

.Net Installation Directory

Configuration File Structures

CONFIG

Machine.Config

Web Application Root Directory

Web.Config

Web.Config Web.Config

Web.Config

C:\Windows\Microsoft.Net\Framework\v<version number>

Page 10: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

10Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Http Context

• ASP.NET Framework expose some useful services to aspx pages and asmx web services through HttpContext object

• We can get the HttpContext object in the code (in aspx page or any library called by an aspx page) like this,

HttpContext context = HttpContext.Current;

• Some important objects exposed through HttpContext objects• Application• Session• Cache• Request• Response

• All these objects are available as the member variables in the System.Web.UI.Page class as well. So they can be directly access from the page class without using HttpContext.Current

Page 11: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

11Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Maintaining States

There are four objects which help to maintain state information in an web application. They are,

• ApplicationUsed to store application wide state information. These data can be accessed by any web form serving to any user.These data persists until the web server shouts down.

• SessionUsed to store session specific state information. These data consumes server resources (one copy per each user currently accessing the site) and reduces the scalability if the amount of information stored is height.

• ViewStateUsed to store state information of server controls in a web page. This information persists as a hidden variable in the client page. These information does not require any server resource. However they are transmitted over the network in each request and response.

• ProfileUsed to store user specific data needs to be persistent in an external storage like database, so that they are available for a long time, even if the server restarts. Introduced with ASP.NET 2.0

Page 12: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

12Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Session State

• In-process This is the default setting. This sessions cannot be used with web farms. Configuration file setting (under <system.web>) <sessionState mode="InProc" timeout="20" >

• State Server Need to install a session server as a service in a windows server. Configuration file setting (under <system.web>)

<sessionState mode =“sessionserver” stateConnectionString="tcpip=127.0.0.1:42424“>

• SQL Server Configuration file setting (under <system.web>) <sessionState mode=“SQLServer

sqlConnectionString="datasource=127.0.0.1;Trusted_Connection=yes“> To setup the server, run InstallSQLState.sql SQL script in .NET installation folder.

Page 13: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

13Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Accessing Session and ViewState Variables

const string Number1Key = "Number1";const int Number1DefaultValue = -1;

protected int Number1{

get{

object ob = ViewState[Number1Key];if (ob != null) {

return (int) ob;}else {

return Number1DefaultValue;}

}set{

ViewState[Number1Key] = value;}

}

Page 14: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

14Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Transferring to Another Page

• Hyperlinks• Direct hyperlinks can be hard-corded in ASPX page using <a> tag

• Use HyperLink control to have a programmable hyperlink target

• Hyperlink columns in GridView can be used to have hyperlinks that can be formatted using data (Generally the query string parameters are formatted using data)

• Response.Redirect(“MyPage2.aspx");• This method instruct the client browser to redirect to the given page

• Can be used to redirect to external page as followsResponse.Redirect(“http://www.google.com");

• Server.Trasfer(“MyPage2.aspx”);• This method do the redirection internally

• Cannot be used to redirect to external pages

• Cross page post back (ASP.NET 2.0 only)• Set the “PostbackURL” property of a Button control to the page that

you want to transfer. Then the button click will transfer data to this new URL

Page 15: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

15Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Transferring data between pages

• When transferred using Server.Transfer, the transfer is done internally and therefore the instance of the page which calls the Server.Transfer is available in the memory

• This page is accessible through “PreviousPage” property of the page

• Therefore any data available as public property or member variable in previous page is accessible from current page,

• e.g.MyPage1 prPage = (MyPage1) this.PreviousPage;string stFirstName = prPage.FirstName;

• If you want the PreviousPage property to be strongly typed, add the following tag in your page (.aspx file)

<%@ PreviousPageType VirtualPath="~/Default.aspx" %>

Then you can access it like,string stFirstName = this.PreviousPage.FirstName

Page 16: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

16Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Display & Edit Data in Presentation Tire

• Data can be displayed using four basic controls• GridView –

• Display multiple rows• Uses a table layout to render data.

• DetailsView• Display single row• Uses a table layout to render data.

• DataList• Display multiple rows• Uses customized templates to render data .

• FormsView• Display single row• Uses customized templates to render data .

• Repeater• Display multiple rows• Uses customized templates to render data .• Light weight• No design time support

Page 17: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

17Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Standard Data Binding

• Needs coding for all the basic operations like, retrieve, editing, filtering, sorting, paging, caching, etc.

E.g.• Page

<ul> <asp:Repeater ID="Repeater1" runat="server"> <ItemTemplate> <li><%# Eval("id") %> -<%# Eval("name")%></li> </ItemTemplate> </asp:Repeater> </ul>

• Codeif (!this.IsPostBack){ //Data is saved in ViewState once

boundedStudentsTableAdapter adp = new StudentsTableAdapter();Repeater1.DataSource = adp.GetData(); // Set the data

sourceRepeater1.DataBind(); // Populate the control with data

}

Page 18: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

18Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Localization

• In order to develop a localizable web application, we have to include everything that might change from culture to culture in resource files

• Culture is expressed as a combination of the language name and its variant name (e.g. For French spoken in Canada, the culture name is “fr-ca” )

• Localization of .Net Framework applications is done using two properties in the current thread. They are• Culture – Culture used to format strings (converting numbers,

currency, date, time, etc. into strings)

• UICulture – UI Culture is used to select the correct culture specific resource file.

Page 19: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

19Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Localization in ASP.NET

• In order to do the localization in ASP.NET, we have to add all strings and images to the ASPX page as ASP.NET server controls.

• Select the page that you want to localize and select the menu option• Tools Generate Local Resource

• If the page name is “Default.aspx”, then this command will generate a resource file with the name “Default.aspx.resx” in “App_LocalResources” folder in the web application directory (It creates one if the folder does not exists).

• This resource file contains entries for each localizable property in all the server controls in your web page

• This is called the culture neural resource file. Resources in this file is used when ever a culture specific resource file is not available for the current culture

• In order to create a localize version for, say Canadian French (“fr-ca”), make a copy of the resource file into the same folder and rename it as,• Default.aspx.fr-ca.resx

• Modify this resource file to mach with the Canadian French culture.

Page 20: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

20Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Localization in ASP.NET (Cont.)

• This is the fist line of an ASPX Page<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" Culture="auto" meta:resourcekey="PageResource1" UICulture="auto" %>

• Note that, Culture=“auto” and UICulture = “auto” lines

• These lines tells the IIS to obtain the current culture from you web browser settings

• If you want to set the culture of this page to a specific culture, say Canadian French, modify these two attributes as,

• Culture=“fr-ca” UICulture=“fr-ca”

Page 21: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

21Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Http Handlers

Can be used to implement low level processing like

• Generate simple html pages efficiently without the overhead of aspx event processing

• Generate and return none-html pages like xml, images and pdf, etc.

• Return files stored in the hard disk with a better control and monitoring

Page 22: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

22Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Http Handlers (Cont.)

<%@ WebHandler Language="C#" Class="MyHandler" %>

using System.Web;

public class MyHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = “html/plain";

string stHtml = " <html><body><h1>Hello World</h1><body></html>"

context.Response.Write(stHtml); } public bool IsReusable { get { return false;} }

}

Page 23: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

23Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Http Handlers (Cont.)

public void ProcessRequest (HttpContext context) { context.Response.ContentType = "xml/plain"; int id = context.Request.QueryString["id"]; string stXML = string.Format("<data><item

id='{0}'/></data>“,id); context.Response.Write(stXML); }

Page 24: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

24Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Data Access Tire Development

• Data Access in ASP.NET 2.0 is basically based on ADO.NET 2.0

• ADO.NET is the data access library comes with .Net Framework class library

• ADO.NET is designed for distributed application development. Therefore it uses a disconnected architecture.

• Data Access Tire basically contains three types of components• Data Access Logic Components – Data access logic (validation, etc.)

• Data Access Helper Components – Classes that does common basic functionality required for data access

• Stored Procedures

Page 25: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

25Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

ADO.NET 2.0 Basic Objects

• Separate Data Access from Data Manipulation.

DataSet

DbConnection

DbParameters

DbCommand

DbDataReader

DbDataAdapter

Select Command

Insert Command

Delete Command

Update Command

Fill

Update

Page 26: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

26Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Data Access Classes

• DbConnection• This is the link between the database and the application. • A connection string is used to identify the database to connect.

• DbCommand• This class is used to execute SQL commands, on the database.• This class uses connection object to access the database.

• DbDataReader• This class is used to retrieve data from a database. Data

access is read-only and forward-only.

• DbDataAdapter• This class is used to fill and update DataSets.• This class uses Command objects to send and receive data.

Page 27: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

27Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Get Factory Class for the Desired Provider

• ADO.Net Support for writing Database independent Database Access Code

• This is achieved using Factory classes

• All these database independent data access classes are defined in "System.Data.Commen" namespace

• Creating the Factory

DbProviderFactory factry = DbProviderFactories.GetFactory (stProvidername);

Provider Name for SQL client is, "System.Data.SqlClient", this is similar to the namespace name in which SQL client classes are defined.

Page 28: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

28Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Creating New Connections and Commands and Parameters

• Creating Connections

DbConnection conn = factry.CreateConnection();conn.ConnectionString = stConnectionString;

• Creating Commands

DbCommand cmd = factry.CreateCommand();cmd.Connection = conn;cmd.CommandType = CommandType.StoredProcedure;cmd.CommandText = stSPName;

• Creating Parameters

DbParameter para = factry.CreateParameter();para.ParameterName = "@id";para.DbType = DbType.Int32;para.Value = id;cmd.Parameters.Add(para);

Page 29: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

29Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Execute SQL Command that does not Return any Value

• Execute an SQL Command• Connections are maintained in a connection pool (one pool per connection

string)

• A connection is taken our from the pool when Open() method is called

• Connection is released back to the pool when Close() method is called

• Always try to minimize the connection holding time

• Release the connection in a finally block to make sure it will be released even if an exception occurred

• Use the same connection, if you want to maintain a transaction, or if you want to execute a series of commands consecutively (to eliminate the connection pool access overhead)

try{ conn.Open(); cmd.ExecuteNonQuery();

}finally{

conn.Close();}

Page 30: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

30Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Fill a DataTable

• Fill a DataTable Directly

DbDataAdapter adp = factory.CreateDataAdapter();adp.SelectCommand = cmd;DataTable dt = new DataTable();adp.Fill(dt);

• Fill a DataTable in a DataSet

DbDataAdapter adp = factory.CreateDataAdapter();adp.SelectCommand = cmd;DataSet ds = new DataSet();adp.Fill(ds,"Students");return ds;

Page 31: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

31Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Using Typed DataSets and TableAdapters

• We can use Visual Studio IDE to generate Typed DataSets, which can be used to do type verifications in compilation time.

• Typed DataSets generated using IDE has Typed DataTables to hold the data belongs to each table.

• Each Typed DataTable in a Typed DataSet has a separate TableAdapter class to operate on them.

• These TableAdapter classes includes methods to fill and update data in this Typed DataTables

• We can use IDE to include database direct (without using DataTables) database access methods (insert, delete and update) in to TableAdapters

• In addition to standard methods, we can add custom methods into TableAdapters to execute any kind of parameterized SQL command or Stored Procedure, using IDE

Page 32: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

32Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Using TableAdapters

• Returning a Typed DataTable

public DataSet.StudentsDataTable GetAllStudentsDT()

{ MyDataSetTableAdapters.StudentsTableAdapter adp =

new MyDataSetTableAdapters.StudentsTableAdapter();

return adp.GetData();}

• Filling a Typed DataTable in a Typed DataSet

MyDataSetTableAdapters.StudentsTableAdapter adp = new MyDataSetTableAdapters.StudentsTableAdapter();

MyDataSet ds = new MyDataSet();adp.Fill (ds.Students);

Page 33: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

33Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Using TableAdapters (cont.)

• Create an instance of the TableAdapter

MyDataSetTableAdapters.StudentsTableAdapter adp =

new MyDataSetTableAdapters.StudentsTableAdapter();

• Update a Row using DB Direct Methodsint original_id = 50; //the current id in the database (before update)

int new_id = 7; // the next value of the id (after update)string name = "aaa";double? height = null; //Leave this field blank (unassigned)adp.Update(new_id, name, height, original_id);

• Execute a custom commandadp.SetHeight( 7, 4.5);

Page 34: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

34Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Caching

• Data can be cached using the Cache object of HttpContext.

• Using Cache objectDataSet ds = null;if (Cache[ "MyDs" ] != null){

ds = (DataSet) Cache[ "MyDs" ];}else{

ds = new DataSet(); SqlDataAdapter1.Fill (ds); Cache[ "MyDs" ] = ds; // Cache indefinitely

}

• Set Expiration Time• Expire cache after two minutes

Cache.Insert (“MyDs”,ds,null, DateTime.Now.AddMinutes(2), TimeSpan.Zero);• Expires cache, if it is not accessed for ten seconds

Cache.Insert (“MyDs”,ds,null, DateTime.MaxValue, TimeSpan.FromSeconds(10));

• Remove the CacheCache.Remove("MyDs”)

Page 35: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

35Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

SQL Cache Invalidation

• Configuration File (under <system.web> tag)<caching>

<sqlCacheDependency enabled="true"><databases>

<add name="MyDb" pollTime="60000" connectionStringName="TestDBConnectionString"/>

</databases></sqlCacheDependency>

</caching>

• Configuring database to support SQL Cache invalidationstring stConn =

ConfigurationManager.ConnectionStrings["DBConnString"].ConnectionString;SqlCacheDependencyAdmin.EnableNotifications(stConn);SqlCacheDependencyAdmin.EnableTableForNotifications(stConn, “MyTable");

• Add data with SQL cache invalidationcache.Insert("StudentDS", tb, new SqlCacheDependency(stDbName, stTable));

//Here, stDbName is the name given in configuration file (“MyDb” in this example)

Page 36: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

36Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Paging

• Paging is automatically implemented by GridView with zero code, if you directly link presentation tire with data

• Otherwise we have to implement our own paging mechanism

• This can be done in three ways• Cache the whole DataSet (can be cached for a certain period of

time or use SQL cache invalidation) and extract only the required rows• Suitable for general data common for all the users• Table must not be too large to effectively cached• Easy to implement

• Save the whole DataSet in ViewState and extract only the required rows (This is the method used by DataGrids and GridViews)• Suitable for user specific data or dynamically queried, data if the

amount of data is very low• Easy to implement

• Retrieve only paged data directly from data base• Suitable for user specific data or dynamically queried data if the

amount of data is high• Suitable for very large tables

Page 37: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

37Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Paging (Cont.)

• Retrieve only paged data from the data base• This paging method can either implemented in

• Stored Procedure written in SQL• SQLCLR Stored Procedure written in C# or VB.NET• Data Access Tire method

• How to write a paging method(if the table containing the data to be paged is “Table1” and its primary key is “id”),

• Retrieve all the values in the “id” column (this is not a big performance hit, as this is the primary key). Retrieve these values to an array if in C# or to a temporary table if in SP

• Select the “id” column values for the required page• Retrieve all the records in “Table1”, where “id” column

contains the selected values. Use IN keyword if you are in C# or INNER JOIN if you are in SP

Page 38: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

38Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Data Access Security

• ASP.NET is executed under• “Network Service” account in Windows 2003 Server• Local machines “ASPNET” account for all other versions of

windows

• To configure web application to access database securely• Hard-cord a user name and the password of a user who has

minimum privileges to run the application successfully, in the connection string (this is not a very secure method)

• Grant minimum required privileges to access the data to ASP.NET account (ASPNET or “Network Service” account). This is the recommended approach.

• Use Windows integrated authentication and impersonate the user (tell ASP.NET to submit the user credentials instead of his own). Here, the access permissions to the database will vary based on the user who uses the application. This can be done by adding the following tag into the “<system.web>” tag of “web.config” file

<identity impersonate="true"/>

Page 39: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

39Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Middle Tire Development

• Middle Tire or Business Logic Tire is the Core of the application

• There are three kinds of objects used in this tire• Business Workflows

• Manage the business workflows• Handles distributed transactions• Long running workflows can be managed using BizTalk Server

• Business Components• Implements the business rules and performs business tasks• Handles simple transactions• These components can be accessed through workflow components

or directly by UI components• Business Entities

• Act as containers to transfer data between tires

• These middle tire components can be exposed to presentation tire• Directly as libraries• As services through a Service Interface

• Middle tire components can use “Service Agents” to access external services

Page 40: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

40Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Transaction Handling

• Simple Transaction Handling• SQL Stored Procedures

• ADO.NET Transaction object

• .Net Framework 2.0 Transactions

• Distributed Transaction Handling• COM+ Transactions

• .Net Framework 2.0 Transactions

• “System.Transactions.TransactionScope” object introduced in .Net Framework is capable of transparently transforming itself to a distributed transaction when needed without any significant performance loss.

Page 41: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

41Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Transaction Isolation Levels

• Chaos – No isolation level is used. It is not safe to use this level of isolation

• ReadUncommited - A transaction can read any data, even if it is being modified by another transaction. Any type of new data can be inserted during a transaction. This is the least safe isolation level but allows the highest concurrency.

• ReadCommitted - A transaction cannot read data that is being modified by another transaction that has not committed. Any type of new data can be inserted during a transaction. This is the default isolation level in Microsoft® SQL Server™.

• RepeatableRead - Data read by a current transaction cannot be changed by another transaction until the current transaction finishes. Any type of new data can be inserted during a transaction.

• Serializable - Data read by a current transaction cannot be changed by another transaction until the current transaction finishes. No new data can be inserted that would affect the current transaction. This is the safest isolation level, but allows the lowest level of concurrency.

Page 42: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

42Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

ADO.NET Transactions

DbTransaction trans = null;try {

conn.Open();trans = conn.BeginTransaction(IsolationLevel.ReadCommitted);cmd1.Transaction = trans;cmd2.Transaction = trans;cmd1.ExecuteNonQuery();cmd2.ExecuteNonQuery();trans.Commit();

}catch {

if (trans != null)trans.Rollback();

throw;}finally {

conn.Close();}

Page 43: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

43Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

COM+ Transaction (Auto Complete)

• .Net Framework will automatically register this assembly as a COM+ application when needed (First used).

• Transaction will be aborted if there is an exception• Transaction will be automatically committed otherwise

[assembly:ApplicationName("MyTestApp1")][assembly:ApplicationActivation(ActivationOption.Library)]

[ComVisible(true)][Transaction(TransactionOption.Required)]public class ComPluseTransTest:ServicedComponent{

[AutoComplete]public void TestMethod(){

//Any code runs under the transaction comes here}

}

Page 44: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

44Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

COM+ (Manually Controlled Transactions)

[assembly:ApplicationName("MyTestApp1")][assembly:ApplicationActivation(ActivationOption.Library)]

[ComVisible(true)][Transaction(TransactionOption.Required)]public class ComPluseTransTest:ServicedComponent{

public void TestMethod(){

try{ //Any code runs under the transaction comes here ContextUtil.SetComplete();}catch{ ContextUtil.SetAbort(); throw;}

}}

Page 45: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

45Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

.Net Framework 2.0 Transactions

• Transactions can be implemented very easily

• Transaction is rolled back if an exception occurred

• Transaction scope starts as a simple transaction (registered with Lightweight Transaction Manager)

• Transaction scope enlisted as a distributed transaction at Microsoft Distributed Transaction Coordinator if required, without a much overhead

using (TransactionScope tscope = new TransactionScope()){

// The code to execute Transaction tscope. Complete();

}

Page 46: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

46Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

.Net Framework 2.0 Transactions (Cont.)

• Transactions can be nestedE.g.

using (TransactionScope tscope = new TransactionScope()){

// The code to execute Transaction using (TransactionScope tscope = new TransactionScope()) {

// The code to execute Transaction tscope. Complete();

} tscope. Complete();

}

Page 47: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

47Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

.Net Framework 2.0 Transactions (Cont.)

• Transactions can be nested and change the scopeE.g.

using (TransactionScope tscope = new TransactionScope()){ // The code to execute Transaction

using (TransactionScope tscope = new TransactionScope(TransactionScopeOption.Suppress))

{ // The code to escape transaction tscope. Complete();

} // The code to execute Transaction

tscope. Complete(); }

Page 48: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

48Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Concurrency Handling

• There are two modes of Concurrency• Optimistic Concurrency

• No data will be locked• The initial state of the data will be saved somewhere• Data is modified during the UI process• Before committing the modified data into the database, check

if the actual data is equal to the saved data (this check is done in the WHERE clause of the UPDATE and DELETE commands).

• If so decide on how to process this data, based on the application

• Pessimistic Concurrency (Not supported by ADO.NET)• Lock the data row once it is read• Release the lock when we are done• Need the connection to be kept open• Reduce the performance and scalability of the application by

keeping the data locked and connections opened for a considerable durations

Page 49: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

49Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Concurrency Handling in ADO.NET

• ADO.NET DataTable objects keeps two versions of data rows, original and modified.

• We can make Visual Studio IDE to generate SQL commands or Stored Procedures to update the database with new data only if the original data is not modified

• Since this check is a part of the SQL command or SP, if there is a concurrency violation, the number of rows updated will be different from the number of rows to be updated.

• ADO.NET DataAdapter objects will throw an exception under this condition

• This can be prevented by overloading the “RowUpdated” method of the DataAdapter and and setting its status property to UpdateStatus.Continue

e.Status = UpdateStatus.Continue;

• Once the exception is blocked, we can test if the concurrency is violated, by testing the return value of the Update method of the DataAdpater (This method returns the number of rows affected. This value must be equal to the number of rows in the table if no concurrency violation).

Page 50: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

50Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Concurrency Handling in Table Adapters

• Table Adapters uses DataAdapters for data access• However this DataAdapter is not private to the Table Adapter• In order to prevent the exception in concurrency violations we have to write

another partial class for the Table Adapter is overload the RowUpdated method in that class

E.g.namespace CCDataSetTableAdapters{

public partial class StudentsTableAdapter{

public void StopCuncurrencyException(){

Adapter.RowUpdated += new

System.Data.SqlClient.SqlRowUpdatedEventHandler(Adapter_RowUpdated);}

void Adapter_RowUpdated(object sender,

System.Data.SqlClient.SqlRowUpdatedEventArgs e){

e.Status = UpdateStatus.Continue;}

}}

Page 51: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

51Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Concurrency Handling in ASP.NET

• The problem with optimistic concurrency Handling in ASP.NET is the fact that a new page instance is created for each roundtrip to the server. Therefore we loose the data saved in DataSets during Round trips.

• The solution is to,

• Load the data (into a DataSet object) in PageLoad event, if it is not a post back

• Initialize the controls with this data• Save the DataSet object in ViewSate

• Load the saved object in the next roundtrip• Modify its values, according to the new values of the controls• Update the database with the data in this DataSet• If there is a concurrency violation, handle it accordingly

Page 52: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

52Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Asynchronous Method Execution

• Using .Net Framework Threads• Using Thread class

• Using ThreadPool class

• Using delegates

• Using COM+ Queue Components• Executed Methods are recorded by an in-process proxy and

posts as a message to MSMQ (Microsoft Message Queue)

• A separate process runs as a COM+ service receives these recorded messages and execute them in a transaction

• Retry five times if the first time execution failed

• If all five times failed, the message is sent to dead letter queue

Page 53: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

53Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Delegates

• Delegates can be used to make asynchronous function calls.

• We can provide a callback method to be executed at the end of the method call.

E.g.

delegate string MyDelegate (int n);MyDelegate d = null;

public string DoAction1 (int n){

//Asynchronous operation}

public void DoAction1Asyc2(){

d = DoAction1;d.BeginInvoke(50 ,ActionComplete, null);

}

public void ActionComplete(IAsyncResult res){

string result = d.EndInvoke(res);// Process using results

}

Page 54: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

54Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Thread Class

• Thread class can be used to create our own managed threads, out of thread pool

• Create a thread is costly and therefore we have to use this only if we need the additional flexibility that we can get using this method

• This method can be used to create threads with• Different priorities (using ThreadPriority property)• Suspend and Resume threads (using Suspend and Resume

methods)• Suspend the execution of the calling thread, until the worker

thread is done (using Joint method)• Create foreground threads (using IsBackGroundThread property)

Note: .Net application is considered to be running if at least one of its foreground threads are running. When the last of its foreground thread is terminated, CLR terminates all other background threads and discarded the application domain

Page 55: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

55Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Create Thread with Thread Class

public void DoAction1(){

//Thread actions}

// Somewhere else in the code

Thread th = new Thread(DoAction1);th.Start();

Page 56: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

56Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Queued Components

• Queued components requires an interface to communication between server and the client.

• This has to be shared between both client and the server

E.g.

namespace DemoLogger{

[ComVisible(true)]public interface IMyLogger{

void Write(string msg);}

}

Page 57: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

57Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Queued Components (Cont.)

• This is the implementation class of the queued component

[assembly: ApplicationName(“DemoLoginSvr")][assembly: ApplicationActivation(ActivationOption.Server)][assembly: ApplicationQueuing(Enabled=true, QueueListenerEnabled=true)][assembly: ApplicationAccessControl(false)]

namespace DemoLogger{

[ComVisible(true)][InterfaceQueuing(Interface = "IMyLogger")]

public class MyLogger : ServicedComponent, IMyLogger {

public void Write (string msg){

//Method implementation comes here}

}}

Page 58: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

58Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Queued Components (Cont.)

• Add above interface and the class into a class library (say MyLoggerLibrary)• Sign the MyLoggerLibrary using a key file (strong name)• Build the library

• Register the library as a COM+ application using “regsvcs” tool comes with .Net Framework• Note that we have to manually register this, because it runs as a service• You have to use the Visual Studio Command Prompt to run this tool (otherwise

you have to give the fool path to the exe file)e.g

regsvcs MyLoggerLibrary.dll

• Go to COM+ Console (Component Service snap-in found in Administrative Tools), right click the application and select “Start” menu option to start the application

• Configure application to auto start under “System Account”, if necessary

Page 59: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

59Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Queued Components (Cont.)

Using in Client

private IMyLogger GetLogger(){

return (IMyLogger) Marshal.BindToMoniker("queue:/new:DemoLogger. MyLogger");

}

private void Release(IMyLogger logger){

Marshal.ReleaseComObject(logger);}

// Somewhere else in the codeIMyLogger logger= GetLogger();logger.Write("My Message 1");logger.Write("My Message 2");Release(logger);

Page 60: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

60Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Security

• Authentication• Windows Authentication• Forms Authentication (ASP.NET 2.0 Membership API)• Passport Authentication

• Authorization• Configuration File (web.config)• User Impersonation

• Auditing

• Profile management• ASP.NET 2.0 Membership API

• Ref: For ASP.NET 2.0 Security Guild Lineshttp://msdn.microsoft.com/library/en-us/dnpag2/html/PAGPractices0001.asp

Page 61: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

61Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

ASP.NET 2.0 Membership API

LoginLoginView

ChangePassword

CreateUser Wizard

etc.

Login Controls

Membership

Roles

Profile Provider

Membership Provider

Roles Provider

Page 62: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

62Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

ASP.NET 2.0 Membership API (Cont.)

• Login Controls – Provide controls to develop, user registration and authentication features into you application with zero code.

• Membership and Roles classes – Provide programmatic access to user management and authentication framework

• Providers – Classes that are responsible for persisting the membership, roles and profile information. • The provider classes can be configured using the configuration file

• Presently only SQL Server provider and the Active Directory Roles provider are shipped with Visual Studio 2005. However we can write our own providers by extending the following abstract base classes.

• MembershipProvider• RolesProvider• PersonalizationProvider

• If we want to use SQL server providers, however wants to use a different database, create a new provider with the same type, but with a different connection string

• We can create the database schema to store these information in an SQL server database using aspnet_regsql tool (this is a visual tool with a user friendly wizard)

Page 63: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

63Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Profile

• ASP.NET 2.0 user management framework automatically• creates a class to store user profile information (creating strongly

typed properties for each attribute)• Create an instance of this class, initialize it with the data obtained

through the ProfileProvider (if previously stored data is available) and make it available as a property of the web page class, during the creation of the page (in each request).

if profile is configured using the configuration file.

• A sample configuration file entry is given here (this must be placed under <system.web> tag,

<profile enabled="true"><properties>

<add name="Var1" type="System.String"/><add name="Var2" type="System.Int32"/>

</properties></profile>

Page 64: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

64Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Profile (Cont.)

• Using Profile Property in Code

Saving Values;Profile.Var1 = "samen";Profile.Var2 = 43;Profile.Save();

Retrieving Valuesstring var1 = Profile.Var1;

int var2 = Profile.Var2.ToString();

Page 65: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

65Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Authorization

• Web Configuration file.• We can have web.config files for each folder in the application to set

different security settings (authorization settings) for files in each folder.

• In addition to that, we can use <location> tag to set different security settings for each individual file.

• Settings of the root folder will be used if not overridden by the sub folder

• Note that we can use only one authentication method per application

• Impersonation• We can configure ASP.NET to impersonate authenticated users using

the configuration file. In this case, ASP.NET will use user credentials to access resources like database, active directory, etc. So the success of the operation depends on the privileges of the user. This method works only when windows authentication is used.

• ASP.NET uses “Network Services” account (in Windows Server 2003) or “ASPNET” account (for other windows versions) to access resources, if not impersonated.

Page 66: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

66Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Configuration

• ASP.NET configuration is basically done using “web.config” file

• Basically there are three configuration sections that are of the interest of general use,• appSettings – Contains the custom application settings

• connectionStrings – Contains the database connection strings used in the application

• system.web – Contain the ASP.NET configuration settings

Page 67: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

67Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

App Settings (Application Settings)

• web.config file setting

<appSettings><add key ="MySetting1" value="This is My Setting

1"/><add key ="MySetting2" value ="100"/>

</appSettings>

• How to use App Settings

string s1 = ConfigurationManager.AppSettings["MySetting1"];int s2 =

Convert.ToInt32(ConfigurationManager.AppSettings["MySetting2"]);

Page 68: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

68Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Connection Strings

• web.config file setting

<connectionStrings><add name=“MyConnection"

connectionString="Data Source=cl-ruwanw; Initial Catalog=TestDB;Integrated Security=True"

providerName="System.Data.SqlClient" /></connectionStrings>

• Note that these connection string settings are automatically generated when creating Type DataSets and Data Sources using IDE

• Using Connection String Settings in Code

string ConnString =

ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

string ProviderName =

ConfigurationManager.ConnectionStrings["MyConnection"].ProviderName;

Page 69: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

69Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Communication

Page 70: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

70Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Communication Mechanism Independent Application Design

Internal Components

Façade IMyService

Service AgentIMyService

Client

Client

Service

Proxy

Service Interface

Page 71: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

71Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Dynamic Type Binding

• Type names (class names) can be taken from configuration files, and instantiate at runtime. This makes the application highly configurable and expandable.

• Note that the Provider class must not maintain any state information

E.g.public class MyService{

private static IMyServiceProvider _myService;

static MyService(){

string ProviderClassName = GetProviderClassName();Type ProviderType = Type.GetType(ProviderClassName);_myService =

(IMyServiceProvider) Activator.CreateInstance(ProviderType);}

public static void DoSomething(){

_myService. DoSomething();}

}

Page 72: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

72Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Transferring Data between layers (and Services)

• DataSets• Can contains multiple tables, relationships and constraints• Contains lots of built-in methods to manipulate data• Data can be retrieved, modified and committed back to the database

easily and efficiently, using DataAdapter objects

• XML• Can contain hierarchical data in any format• Need a pre defined schema• Need some coding for serializing and de-serializing

• Entity Classes• Strongly typed (compile time type checking)• Light-Weight

• Typed-DataSets• Contains all the advantages of normal DataSets• Strongly Typed (compile time type checking)• Support zero code data access layer development through

TableAdapters

Page 73: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

73Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Communication (Cont.)

• Method bases Communication• Used in intra-application communication• Tightly coupled• Fine-grained• E.g.

• Direct Library call• .Net Remoting• COM+

• Message based Communication• Used in inter-application communication• Loosely coupled• Course-grained• E.g.

• Web Services• MSMQ (Microsoft Message Queue)• COM+ Queued Components

Page 74: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

74Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

.Net Remoting

• .Net remoting expose object outside application domain (application domain is the boundary of the .Net application)

• .Net remoting framework registers these objects to a URL

• Client can access these objects using these URLs

• This process (registration and retrieval) can be configured programmatically or using configuration files

• Communication can be done using three channels

• TCP Channels – Efficient for intra-net communication

• Http Channels – Suitable for communication across fire walls

• IPC Channels – Extremely efficient for communication between two applications running in the same machine (.Net Framework 2.0)

• Custom channels – Users can develop their own channels

• These channels can be secured using encryption (.Net Framework 2.0)

• Server applications can be hosted anywhere. However they are generally hosted in Windows Services

Page 75: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

75Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

.Net Remoting (Cont.)

• Objects are exposed in .Net Remoting in two ways• Marshal by Reference

• Object is created in the server side• Client receives a reference to the object• CLR creates a proxy class with this reference• Client code use this proxy to execute methods remotely• There are two types Marshal by Reference objects

– Server Activated – Object life time is managed by the server» Single call – new object is created for each call» Singleton – one instance will be used to server all requests

from any client– Client Activated – Object life time is managed by the client

» Object acquires some life time by birth and die after that» Client can extent this life time using life time lease

• Marshal by Value• Object is created in server side• It is serialized and passed to the client (data can be serialized

either as binary or SOAP)• CLR will create a similar object in the client side using the

serialized data

Page 76: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

76Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Web Services

• Web services uses XML based SOAP protocol to communicate with remote machines.

• Web services are the best option for interoperable communication

• Web Services are stateless

• Web service methods can be configured to perform a transaction• However the transaction context cannot be transferred with a web

service call

• WS-I is the web service standard which supports,• Security (Encryption and Signing)• Flow of transaction context• File Attachments

• Microsoft Implementation of WS-I is called WSE (Web Service Enhancements).

• The latest version of WSE is WSE 3.0 which comes with Visual Studio 2005

Page 77: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

77Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Web Services (Cont.)

• Visual Studio IDE can be used for rapid development of web services

• ASMX technology abstract Http and SOAP form the developer, and developer has to consider only on basic business logic.

• Visual Studio IDE and “wsdl.exe” tool comes with .Net Framework can be used to generate the proxy classes to access web services using WSDL.

• Consuming web services means just accessing the methods of the proxy class

• We can install WSE 3.0 to use the features introduces by WS-I

• This installs an adding to Visual Studio IDE using which we can create WSE 3.0 policy files using a GUI

Page 78: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

78Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

COM+

• COM+ (Serviced Components) is the most secure and simple method of interposes communication for .Net objects

• Its more efficient than Web Services

• It is secure than .Net remoting

• However COM+ is not interoperable with other technologies (e.g. Java)

• COM+ method calls enable the flow of user credentials and transaction context

• COM+ objects can be secured using Role based security

• COM+ objects can be easily managed with COM+ management console

• Note that, it is hard to convert into COM+ once the application is developed. Therefore always plan in advance, if you will ever have to port it to COM+ in future

Page 79: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

79Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

COM+(Cont.)

• In order to use with COM+, the objects have to be derived from the basic class, ServicedComponent

• The component classes and interfaces must be public and marked as COM visible using COMVisible attribute

• The assembly must be signed with a strong name

• The application name, activation type (library or service), GUID and other COM+ configurations can be marked with attributes

• Add a reference to this library to the client application

• Create instance of the COM+ component and use it

Page 80: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

80Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

COM+ (Cont.)

• If this is a library application, .Net framework will automatically install this as a COM+ application, when the assembly is first used

• If this is a server application, the assembly must be registered• using “regsvcs.exe” command line tool

• Adding as a COM+ component visually using COM+ console

• In order to access this from a remote machine, an installation to a proxy class to access this application can be exported using COM+ console

• This proxy class must be installed in the remote machine

• This proxy is installed at,<program files>\ComPluse Applications\<Application

GUID> directory

Page 81: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

81Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Enterprise Application Blocks

• Enterprise Application Block is a Framework that supports many features required for the successful implementation of .Net enterprise applications

• This is a .Net Community driven project

• This framework provides services like• Configuration• Logging• Exception Handling• Data Access• Encryption• Caching• Etc.

Page 82: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

82Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Enterprise Application Blocks (Cont.)

• The core features of the Enterprise application block are• Configurability• Expandability

• All the application blocks, belongs to enterprise application block uses “Configuration Application Block” to make them easily configurable.

• A configuration tool is shipped with the enterprise application block to configure the application block visually

• All the application blocks uses easily configurable provider modal to make them easily customizable

• All application blocks expose their functionality to the programmer using a simple small set of API

• These API are exposed as static methods

• The Real configuration of the application block is done through configuration files

Page 83: Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ASP.NET 2.0 Architecture Ruwan Wijesinghe

83Copyright ©2004 Virtusa Corporation | CONFIDENTIAL

Enterprise Application Blocks (Cont.)

• E.g.try{

//Code that might throw an exception}catch(Exception ex){

bool rethrow = ExceptionPolicy.HandleException(ex ,”Policy1”);

if (rethrow) throw;}

• This code decide what to do with the exception (log it, ignore it, rethrow it, etc. based on the exception type and the handling policy mentioned (“Policy1” in this example).

• All these can be configured using the configuration file, without changing a single line of code, at any time (even in run time)