Sei sulla pagina 1di 56

PART-I

.NET

Contents
INTRODUCTION TO WEB APPLICATIONS RESPONSE AND REQUEST OBJECT WITH EXAMPLE ASP.NET CONTROLS AND ASP.NET WEB FORMS A. Buttons, Textboxes B. Listbox controls C. Image, image button, image map VALIDATION CONTROLS WITH EXAMPLES D. Required field validator E. Range validator F. Compare validator G. Regular Expression Validator H. Custom Validator I. Dynamic Validator J. Validation summary ASP.NET DATABINDING K. LINQ datasource controls L. Ado.net entity datasource controls M. Presentation controls for database views ASP.NET CONFIGURATION N. Machine.config O. Web.config SENDING MAIL EXAMPLE ASP.NET AUTHENTICATION P. Windows authentication Q. Passport authentication R. Forms authentication LOGIN CONTROLS ASP.NET STATE S. Viewstate T. Sessions U. Cookies ASP.NET CACHING 2 3 5

10

14

29

31 33

41 45

53

DEPT OF CSE & IT

Page 2

.NET

INTRODUCTION Server Side Programming: Question: What is server side script? Answer: A program which is executed at server and which is independent of client is called as server side script in web applications. Every server side programs gets processed results in the form of client. Question: How server indentifies programs to run i.e., server side, client side and if server side which language/runtime/interpreter? Answer: Http handlers is one concept and which are programs who take care mainly to redirect the program to the required destinations. These handlers are totally based on extensions. Handlers are installed with web servers, s/s environment s/w and some other sources. As a .Net developer one should be aware of Asp.Net and Asp. ASP Active server pages and it is one of the successful Microsoft plat form for developing web apps. ASP is today classical and it is completely (component object model) COM based development. Todays development of web is completely based on Asp.Net. Asp.Net is modern in all aspects today and it is part of .Net. So to develop applications i.e web related apps if we install .net framework in the server where it is running we are ready for todays web apps. Asp.net programs are written with extension .aspx, Where as Asp are written with extension .asp. Today Asp.Net at server side is available in 3 different forms. Asp.Net web forms development Asp.Net AJAX development Asp.Net MVC(4.0) (today beta and important) .Net current release is 3.5spl. Note: Spl includes so many new concepts that it should have been a new release of .Net. .Net is available today in the form of Beta also which is .Net 4.0 (faster, simplier and standard development). Tools for developing applications are: Visual Studio.NET Microsoft Expression Studio (Expression web, Expression Blend, Expression Design, Expression Media) Visual Studio: Its a common IDE for all Ms.Net environment. Visual studio 2008 features are many like multitargetting .Net platform environment. (.Net 2.0/3.0/3.5) Split view for design and source is one addition in 2008. Java script intellisense and debugging in another big change . Now we can put break points even in java script code. No complexity will be found for any level of javascript users. Vs 2010 added another big feature i.e., snippets for html/ asp and javascript in source view. With this we can avoid typing id=, run at <script=every time

DEPT OF CSE & IT

Page 3

.NET By default Vs will create a website with one default .aspx page which is basically an asp.net page. We can add any type of page to our project and accordingly to project or item Vs.Net behavior reflects. Asp.Net provides different models for writing .aspx program. o Classical Asp model o New code behind/beside model o In page model Asp didnt had any environment for writing programs. Classical ASP model: <html> <head><title>Asp.Net.program</title></head> <body> <h1> Asp.Net demo</h1> <% Response .write(Hello all this is Asp.Net) %> </body> </html> <%---%> are called server side blocks. Inside these blocks we must write only aspx code Question: What is an aspx code? Answer: Asp.Net is collection of objects and this code blocks can contain its objects. .Net aspx libraries. As part of frame work we have libraries like system web.ul, system.web.* and some other libraries which are meant for web application development. These libraries code can also be present. Generally aspx code means the above 2 only and apart from this we can write the language specific code like C#, VB.Net etc Aspx code=asp.net objects+ aspx libraries Asp.Net objects (key for asp.net web development): Response Request Server Session Application Cache View state some other RESPONSE AND REQUEST OBJECT: During request and response of webapps lot of i/p and o/p flow. As an Asp.net developer we produce o/ps from an aspx page to client using Response object.(encapsulates Httpresponse). Also many objects of asp.net encapsulate the response object also. In order to receive data which is sent by client we have to use request object (encapsulates Http Response) many other object encapsulate again this request object also. Demo:Request/Response <html> <body> <form name=frm action=inbox.aspx> <h1>Mail Application </h1> <table bgcolor=cyan> DEPT OF CSE & IT Page 4

.NET <td>User Name </td> <td> <input type=text name=txt name> </td> <tr> <td> Password </td> <td> input type= password name=txt pwd> </d> <tr> <td>Register</td> <td> input type=submit name=s1 value = login> </table> </form> </body></html> inbox.aspx <% Response .write(<h1> Welcome:&Request (txtname) ) Response .write(You have 10 mails) %> Other models of Asp.Net for writing programs: Code behind(Beside model(New Model) In this model we will create two files for a single program. .aspx program which contains design code(Mainly html +js) .aspx.cs program which contains C# code for the created design. Design file i.e .aspx contains information about code file i.e .aspx.cs. Question: How is this information written? Answer: Using Directives in asp.net Question: What is a directive and page directive? Answer: A directive in asp.net is used to provide preprocessing information to asp.net runtime. Sample: <% page language=C# Codefile=default.aspx.cs %> A directive in asp.net should be written in %@.......% blocks All directives relavant to page are written using <%@ page..%> directive Directives should be the first statements of .aspx file. Some attributes of page directive are: Language = C#/VB Code file = code file name /* What directives are used in your project? Mention 5 directives in asp.net What attributes in page directive Mention few or 5 of them ..............................*/ In page technique model: In this model we create only single file with extension .aspx but we will split the file into two parts. [The most widely use code is code behind model. ] For every project we can add new items, using website and new item or from solution explorer right click on project and select add new item. DEPT OF CSE & IT Page 5

.NET If you want to add a new web form then select add new item select webform and also remove place code in separate file option from add new item dialogue box. This will create an aspx page in Inpage model visual studio.Net will support all the 3 models of writing aspx program.

ASP.NET CONTROLS AND ASP.NET WEB FORMS: Normally webapp user interface for both i/p and o/p are designed using html forms and html controls. For an Asp.Net developer asp.net provides asp.net web forms and controls. Some of the important reasons to use Asp.Net forms and controls. Every Asp.Net control is rich in properties and methods. Using these properties we can make our development faster and simplier.(also called simplified development feature of asp.net) Exclusive set of controls which provide rich functionality by including all html, javascript and also some server side code automatically. No comparision with html. Intelligent controls (smart controls). Every asp.net control/form produce o/p based on client who requested it. Like this we can produce o/p which are compatible with almost all browsers. Asp.Net performs a process called rendering which is a program that converts all asp.net states / ouyputs into html or browser understandable formats. Asp.Net performs this step as its last step@server. State management. Asp.Net provides better state management for its entire applications and especially every asp.net control has built in code for providing state. Question: Why or what is State Management? Answer: Http is base our apps. Http is pure stateless protocol. RAD (Rapid Application Development and Deployment.(RADD) All asp.net control comes with rich ide. Support like wtzards, smart tags, auto format autogenerate etc to make our development process faster. Question: Which controls are processed faster? Answer: HTML or Asp.Net Question: As a developer which control we have to used or preffered to use in development of asp.net web app. Asp.Net post back forms: What is post back form? In html when we submit the form to the same form that we requested as a request then that concept is called post back form concept. How Asp.Net is related to post back form concept? In Asp.Net every web form that we create implicity works as a post back form. As a user we donot specify any form action for asp.net forms and it is highly recommended to avoid any explicit behavior for a form. Why asp.net is implementing postback form concept? In order to (implement) / provide state management for asp.net controls and forms asp.net implicitly performs post back forms concept. Different ways of creating asp.net project?(very imp for mvc,azure,ado.net services) 1) Start New WebsiteFile System File system means develop asp.net website using another development web server called as Cassini web server. In Asp.Net 2.0 with vs 2005 microsoft added development web server DEPT OF CSE & IT Page 6

.NET so that people can develop applications without using lls. Another important thing in this option is we are creating a website instead of web application and this will give us a comfort of preparing .net assembly only for web pages that we run. 2) Start File New Project Web Asp.Net web application . In this method we create website only but as an application which results in every time creating a in the bin folder. 3) File New Website Location : http This means create website using US as our web server and this step automatically creates virtual directory followed by physical directory in lls <os drive>/Inet pub/www root/<application> Vista/2008/7 users. We must start vs in administrator mode otherwise we cannot use lls. We will get an error-no permissions/ privileges to access lls. Right click on vs and say Run as administrator. 4) Location ftp. (File transfer protocol) If we want to remotely publish or download the project no need to use third party ftp( file transfer protocol) software why because vs itself can do this for us.(added in asp.net2) List of Asp.Net Categories: 1) Standard or Intrinsic controls. 2) Validation controls. 3) Bound controls. 4) Data source controls. 5) Login controls. 6) Navigation controls. 7) Web parts controls. 8) AJAX controls. b.1 Windows Live Controls: - Windows Live Tools for Vs.Net.(asp.net/Microsoft.com/google.co.in b.2 Silver Light Controls - Silver light tools for Vs.net(asp.net/Silverlight.net) . b.3 Windows Azure Controls/SDK (Azure.com) - Azure SDK for Vs.Net --- (filenew project cloud services ) ------- then Azure is install in vs. b.4 Optional Asp.Net Extensions(asp.net) . b.5 AJAX Control Toolkit & Silver Light Control Toolkit .. Code C#: Label2.Text=Welcome, + TextBox1.Text; Demo 2: Code: Label2.Text= TextBox1.Text+is a +List Box1.selected value; Code : Label2.Text= TextBox1.Text+is a +List Box1.selected value; DEPT OF CSE & IT Page 7

.NET Response .Write(List Box2.Selected value); */

Server side code execution for Asp.Net controls: Every server side code is executed only when client submits the form. If client fails to perform a post back then server side code will not be executed. For example take check box and write check the changed event. Notice by default this event code is not executed because check box by default doesnt cause a post back Asp.Net provides a property called Auto Post Back. If we set this to true then check box itself can run with its own code and also other events code because it know perform post back In Asp.Net users cannot create an instance of page class an users as to request any page. Current page is always reffered in code window using page class page any property or method refers to current page. Page is also like a control and it contains methods properties and events one of the important event for page is load. This event is fired for every request that user makes for a page. Page.ISPOSTBACK is a property which returns true if the request is a post back request not first time request. This property is very useful to perform any start us tasks for Asp.Net page. In Asp.Net we always request a page to run but we cannot create any instance of Asp.Net page server implicity creates an instance of the page as part of its entire life cycle of a page. Public partial class defaults4: system.webu1.pass { Protected void page-load(object sender,event Arg1 e) { //sample for page-load and 1postback property of it If(1s post back) Response.write(Enter Details); else response.write(Welcome);//1st time Q) How to create Asp.Net controls? i. In markup using tag prefix* and tagname EX: <Asp:Button ID=b1 runat=server Other attributes/> Asp is called TagPrefix Button is called Tag Name <asp: TestBox ID=t1 runat=server Text =Hello ID and runat are mandatory HTML 1.0/2.0/3.0/4.0/X HTML 1.0 Runat=server is also mandatory this attributes makes a control as server side control. Question: What makes a control server side control? Answer: Attribute runat=server for html as well as for asp.net makes a control s/s. Question: Image related controls in Asp.Net? Html <img> Asp.Net <asp:/mage> Asp.Net <asp:/mage Button> Asp.Net <asp:/imageMap>*** Asp.Net SilverLight Images*** Web Resources: DEPT OF CSE & IT Page 8

.NET <HTML <img-drag drop, img src=writing. Image url: Image it is not postback control Image button it is postback control here when we click the image then post back that means it goes to server and display. Image map control. It is richest. Provides a map view for image and allows user to create hotspots so that users can select them. Handling multiple forms in web applications: In Asp.Net a webapplication is mainly collection of webforms and other resources with post back behavior user is kept always in a single form and when we want to navigate to other forms we have to explicitly use the following options. 1) Asp.Net 2.0 added cross page post back which allows user to submit the form along with its data to other forms (state is maintained ) we can do this using a property called postback controls. 2) Using response .redirect(<url>) Redirects the user to the specified url. This url can be local application page or any valid remote address when we use redirect the current page values are not accessible to the new page. If we want values of current page in new page we can use QueryString concept of Http. This is most used option while redirecting forms. /*response.redirect(default.aspx? a=+ TestBox.Text) Default.aspx use that text as in Page-Load Text Box1. Text=Request[ a ];*/ Syntax for Query String : (<program name> ? name=value & name=value&.) If(checkBox1.checked) Response.Redirect(default.aspx ? a=tx & b= Employed) Else Response.Redirect(default.aspx? a=+ Testbox1.Text+&b=unemployed) Default.aspx Text Box1.Text=Request[ a ]; Label3.Text=Request[ b ]; If(Request[a]==null) { } Else { } Link Button: Code { Response.Redirect(http://local host ); } 3) Server .Transfer(pagename) Also used to load other web forms in the project cannot load any outside project content can provide values of current page to new page. (if required)server.Transfer(default.aspx); 4) Hyperlink of Asp.Net (or) Hyperlink of HTML In Asp.Net: <asp: HyperLink ID=HyperLink 1 runat=server DEPT OF CSE & IT Page 9

.NET Navigate Url= ~/-.aspx In HTML <a href=Default cs.aspx > images</a> <br/> target=w1 We give open in image Even hyperlinks can take the benefit of QueryString List Controls: Used to handle values dynamically instead of creating controls dynamically it is always good practice to create list control once and then populate the content dynamically. In Asp.Net web applications and also in other applications we can follow the below approaches to fill list control values. Design time. Run time programmatically. Run time programmatically with data binding concept. To Add: Add, Add Range,Insert To Remove: Remove, Remove At, Clear. To Find: FindString, Find Exact String, Contains. Link .Button.// prog filling 2nd way of filling values. List Box1.Items .Clear( ); for(int i=0; i<10; i++) { List Box1.Items.Add(value+i.To String(1) ); } Runtime programmatically with data binding concept: Data binding is a concept where we prepare data object which contains data from any sources and then simply bind the control with data object. Dataobject + Control= Data Binding It contains data It not contain data Data object + Control=Data Binding not possible (DB Program)

How to prepare Data Object?

.Net has different objects that can store data System collections is a name space of .Net where classes that store data are available in different forms. System collections .Generic is another namespace added in 2.0 of .Net and highly recommened over old system.collections Example: Array list is one collection class that can store any type of data (Boxing/ unboxing) List <T> is one collection class that can store data of type T.(system.collections.genericsPrefered) (Avoid Boxing/UnBoxing) DEPT OF CSE & IT Page 10

.NET (Strong typed, good performed) In Link Button { ListBox1. Items.Clear( ); Array List Countries=Get Countries; List Box1.DataSource=Countries; List Box1.DataBind( ); } Private { ArrayList obj=new ArrayList( ); Obj.Add(India); Obj.Add(Australia); Obj.Add(U.S.A); Obj.Add(England); Return obj; } List box Check box list Radio button list Drop down list Bulleted list box These all are controls in intrinsic Here when we click list Drop Down List Drop Down List1. DataSource=Countries; DropDownList.DataBind( ); Check Box List1.DataSource=Countries; Check BoxList.DataBind( ); Radio ButtonList1.DataSource=Countries; Radio ButtonList1.DataBind( ); Bulleted List1.DataSource=Countries; Bulleted List1.DataBind( ); ASP.NET VALIDATION CONTROLS: In Asp.Net validation. Suppose we take text box Javascript is automatically created. Entire controls done we need not write java script. Normally validations are written using javascript for all client side validations the only preferred language is javascript writing javascript is complexity and also time consuming. To avoid writing javascript manually we can use asp.net validation controls. All these validation controls render java script and based on client and their browsers rendering will happen. Asp.Net uses Web Validation.UI.JS pre-coded library to perform all these validations. Asp .Net validation controls target clients as automatic which means based on browser (up level or down level) code will be generated. If uplevel first client then server. If downlevel only at server. List of Asp.Net validation controls: DEPT OF CSE & IT Page 11

.NET Required field validator Range validator Compare validator Regular Expression Validator Custom Validator Dynamic Validator Validation summary Required Field Validator: Use : To validate for null values within the control. The only control to check for null values means remaining validation controls ignore performing validation when null values are entered. Common properties for all validation controls: Control to validate Error Message * Display:Static/Dynamic/none Set focus on error: true/false Validation Group:<groupname> Enable Client Script: true/false Text : Static means initially place for control is reserved and on erroreous data it will appear. Dynamic means no place for control is reserver on error it creates and displays the error. Range Validator: Use: To check for range of values, very usefull for numeric and date data types. Properties : Minimum value, Maximum value , Type Compare Validator: They are 3 uses. (i) Compare one control with another control. (ii) Compare a control- value (iii) Compare a control- data type Properties : Control value Control to validate Value to compare Error message Operator Type <asp: Compare Validator ID=Compare Validator1 Runat=Server Control / To Validate= Text Box3 Error Message=.. Value to compare= 15 Operator = Greater than (>) Type = Integer/> Control Control Control to validate Error message Control to compare Operator Type: DEPT OF CSE & IT Page 12

.NET <asp: Compare Validator ID=Compare Validator2 Runat=Server Control / To Validate= Text Box5 Error Message=.. Control to compare= Text Box4 Operator =Equal Type = String/> Control data type Control to validate Text Box 6 Error Message Invalid price Type Integer Operator = Data Type Check Validation Summary Control: Use: To report all validation control errors at one place.(dosent perform any validation ) We can display error message using text and error message property also. When both are given text will appear in place of control and error message will appear in summary control (if available) Property: Show message box (true) Show summary (true) Regular Expression Validator: One of the features that a language can provide is regular expressions. It is a concept where we perform validations using Runtime and Expressions and avoiding code. For Example: Email validations @ is compulsory After @ some text is compulsory @. Is wrong Scott @ scott. Is wrong After @ should not be in the beginning Using system.text . regularExpressions; Resex. Important resourses for writing expressions are: (i) Visual studio.Net.RegEx Editor(with samples) (ii) SDK help where Res Ex samples are available. (iii) Reg Ex tester software. (iv)Regular Expressions.org. Custom Validator: If all the validation controls doesnt fulfill our business requirements then we can write our own validation code and continue validation control benefits using custom validator. Custom validator can be implemented @ server side or client side or in both locations like asp.net controls. Custom validator c/s java script Custom validator server side- C#.code** Custom validator server side: Place custom validator and set the following properties. Control To Validate: Error Message DEPT OF CSE & IT Page 13

.NET go to properties eventsserver validate* Write code using server validate event args* 2nd argument which provides 2 properties IS value and value. Using system.Data.sql client; //data base Protected void Custom Validator1- server validate (object source , server validate event Args args) { //Event Handling is very important. Sql connection cn=new Sql Connection(@data source = nit\server; user id=sa; Database=pubs); Cn.Open( ); String stat=select username from users Where Username= +args.value+ ; SqlCommand cmd= new SqlCommand(stat.cn); Sql DataReader dr=cmd.ExecuteReader( ); if(dr.HasRows) args.IsValid=false; // show error else args.IsValid=true; // ok-no error } Button click (object sender, event Args e) If(page.IsValid).//page.validate( ) Response .Write(Name Accepted); Note : Page.validate will perform validations without any submit or other action from user. Page.IsValid returns true when all the validation controls are performed correctly and return false even a single control fails in validation. We can use both these properties for individual control also. Custom Validator-Client Side: Place custom validator and set the following properties. 1. Control To Validate 2. Error Message 3. Client Validation Function: <javascript function name> Goto Source.View(HTML View) Add script tag and write function with again 2 arguments. Function name should be same as given in the property. Write code for validation using same value and IsValid properties. Client Validation Function= CheckQty Source <script type> text/javascript> Function check Qty(a,b)//why a and b are not written without data types. { if(b.Value%5= =0)//value,Isvalid. b.Isvalid = true; else b.Isvalid=false; } </script> Important issues with validation controls:

DEPT OF CSE & IT

Page 14

.NET Causes validation is one property for every postback control which makes the control free from validations that are present in the form. Signup , help kind out buttons has nothing to do with validations in the page. We can use causes validation for these type of controls. Validation group is new concept added in Asp.Net 2.0 and which allows user to perform validations group wise within a single form. Remember validation group is exclusively for validation controls only. They dont group any other behavior. Avoiding client side validation: For an up level browser if we dont want to perform validations using java script at client side and perform validation onlt at server side then we can use very important property called EnableClient Script(true/false) (for validation controls) By default true: (We select false that means validation using at server side) Error Message=<img src=loading.gif><bg sound src=a manda.wMa> Invalid ASP.NET DATA BINDING: In entire .Net maximum data binding is required for web applications only. Because of there clients, browser and rendering. Asp.Net is very rich in supporting this data binding concept. Both in the form of controls and also in preparation of data objects . As part of controls it has the following options: 1. Basic Asp.Net data binding controls. 2. Dynamic data(3.5 spl) 3. Silver Light Data binding control (Sl tools) 4. Windows Live Controls (live tools) and some more. Data Ojects: Lot of .Net objects to store data. Collection objects, DB objects. Non .Net objects which are interop objects SOA (Service Oriented Architecture) Cloud objects where we can create some services on clouds and produce data. Note : In Asp.Net 2.0 Data Source controls is one new concept added to prepare data objects in a simplified method.(normally we used to prepare programmatically data objects) Data Objects: 1. Programmatically 2. Data source controls. Demo : (RAD method) 1. Goto server Explorer (viewServer explorer. 2. Create neew database connection using connect option. 3. From the displayed list of tables drag and drop the required table onto the form and observer automatically 1 bound control and 1 data source control is created. Data Connections: i. Data Source.MS SQL Server. ii. Server name iii. Use windows Authentication use Sql server quthentication. iv. Connect to database v. Text connection Demo 2: Create Data Source control manually and create bound control and bind it to created data source control. DEPT OF CSE & IT Page 15

.NET Sql Data Source . control is used to prepared Data object from any database that supports sql. Like sql server, oracle, MySql base. Sql data source Drag and drop Configure Data Source Window appear new connection Connection Here we are using Oracle Grid control view for format. Asp .Net 3.5 Linq Data Source Control Asp.Net 3.5 spl Ado.Net entity Data Source Control. Ling to Sql & Ado.Net entity frame work are two new concepts added in .Net 3.5/Spl/4. These concepts provide lot of benefits over other models of data access and it is highly recommended to use these objects instead of old Ado.Net objects. LINQ DATA SOURCE CONTROL Demo 3: Linq to Sql objects with Linq Data Source control. Select new item and select Linq to Sql Classes and give one name to it. Ex: Pubs and OK we see another design page is opened i.e object Relation Designer. After that goto Server Explorer. Drag and drop the authors , jobs. Now authors and jobs classes are created for front end. After that open one .aspx page, In Data select Linq Data Source. We give pubs that creates Data Context. Configure Data Source. Choose your context object. Pubs data Context and Next the Window opened Table. authors(<Table><job>) jobs<Table<job> Select one. And Finish Then object created using it. Linq Data Source. Steps : i) Add New ItemLinq to Sql Classes. ii) Goto Server Explorer and drag drop the required tables. Save them. iii) Goto Form, Create linq Data Source control and configure it with linq objects. iv) Grid view and bind it. Demo 4: Getting Data from linq objects without using Linq Data Source and using Linq Query. /* In form Select Button In Button double click DEPT OF CSE & IT Page 16

.NET Grid List We write code; Button { Pubs Data Context obj=new pubs Data Context( ); Var result=from n in obj.authors //where n.city==Oakland Grid View1.Data Source=result; Grid View1.Data Bind( ); } ADO.NET ENTITY DATA SOURCE CONTROL Demo 5: Steps for Ado.Net entity Data Source Control: 1. Add New Item ADO.Net entity Data model 2. This item will respond by asking from which database the model should be created. Respond with pubs or other data base followed by tables selection which is given to you. 3. Go to web form and now place. 4. Ado.Net entity DataSource control and configure them with created Ado.Net entity objects.(Entity frame work give.Entities as Suffix i.e if we give pubs it will create pubs Entities class) Programmatically preparing data objects: In order to prepare data objects that can store data from database we can use general .net collections but it will be heavy work to prepare our objects for data base data. To improve or prepare data objects for data base we need Ado.Net objects of .Net which are specialized in storing data base data. Ado.Net 2.0 Data set Data Reader Linq to Sql Linq to Sql objects. ADO.Net EDM ADO.Net entity objects. To prepare them are there any standards to follow. Yes there are and it is very important to follow the layered concept always in order to prepare / access data base. PRESENTATION CONTROLS FOR DATABASE VIEWS In Asp.Net we have a concept called Asp.Net folders. These folders are secured accessible to entire project and are meant for particular purpose. App-Code is one Asp.Net folder which is meant for creating all code related files, classes, linq objects, entity objects etc.. App-Data is another one which is meant for storage related files. Asp.Net folders. Security . default names. Select one class in website. DEPT OF CSE & IT Page 17

.NET Add one item (class) Data Helper.cs Using System.Data.Sql Client; //inorder to connect with Sql server. Public static class Data Helper.// to ensure all its members are static. Public static void Add( ) { } Public Static Data Set { //Class memberswhich are involved with class nameloaded only one. Sql Connection cn=new Sql Connection Data Source = Server; User id=sa; Database=pubs); Sql authentication Integrated Security=true; Windows authentication Initial catalog=pubs Cn.open( ); //will establish the connection Sql Data Adapter da=new Sql Data Adapter(stat, cn); Da.Fill(ds); Return ds; } } Form Code Button Click { Data Set jobs ds=Data Helper.Get Data(Select * from jobs); Grid View1.Data source=jobs ds; Grid View1.Data Bind( ); } Steps : Create a class in App-Code folder Write static methods (preferably) returning data set. In Webform create button and write code to retrieve data from data layer and bind same to grid view. Another Button Button 2. Code { Data set authorsds=DataHelper.GetData( Select * from authors); Grid View.DataSource=authorsds; Grid View1.DatBind( ); } Sql Data Source Sql supported Data base Linq Data Source Linq To SQL objects. DEPT OF CSE & IT Page 18

.NET ADO.NET EDS ADO.NET EDM Objects. Objects Data Source** User Def Objects. Note: Object Data Source control is for user defined classes but not for predefined linq, ADO.NET classes. Using object data source we can really fulfill our layered approach also. Demo : Object Data Source Object Data Source Choose Business Object

Define methods Define parameters. Business Layer. Public DataSet Get All obs( ) { Data set ds= Data Helper.Get Data(Select * from jobs); Return ds; } Public DataSet Get job info(string stat) { Dataset ds=Data Helper.Get Data (stat); Return ds; } Public DataSet Get Job Info(string stat) { Dataset ds=Data Helper.Get Data(stat); Return ds; } Public void Delete Job (int jobid) { Dataset ds=Data Helper.Get Data (jobid); Return ds; } Bound / Presentation Controls: Repeater older to new version Data list Grid view Form view Details view List view(3.5) Dynamic Data (3.5 spl) Supports implicity sorting of data and also allows for complete customization. Supports paging of data implicitly and allows customization using grid view we can present data very effectively and also perform update delete operations. DEPT OF CSE & IT Page 19

.NET Added in ASP.NET 2.0 and prior to that a control called data grid was used. Grid view is faster in performance and also provides better RAD development over data grid. ( Data grid is not displayed in tool box of visual studio but it can be used in source view directly without adding any references). Apart from above features Grid View has one important property called Auto-generate Columns:true/false by default it is true and it implies generate columns based on data object structure implicitly. When set to false we must provide columns information manually which is very important. False.we must provide columns information Grid view is structured and to fill its structure it provides a collection called <columns> Inside columns we cannot create any control that we want instead grid views only provides fields called grid view fields which can be used to prepare grid view columns. Every field represents a single column. Every field has its own purpose and maximum provides simplified structure filling. Grid View Fields: 1. Bound Field Simple and limited in presentation. It is attribute based and provides different attributes for presentation. Some important attributes arg Data field = data object field name. Header Text= <heading for column> Sort Expression = <column for sorting> Read Only = true/false. <asp: Grid View 10= Grid view1 runat=server Auto Generate column= False/> <columns> <asp:Bound Field Data Field = job_id Header Text=Code/> <asp:Bound Field Data Field = job_desc Header Text=Description/> <asp:Bound Field Data Field = min_v Header Text=Min Level/> <asp:Bound Field Data Field = max_v Header Text=Max Level/> </columns> </asp:Grid View> Important Points: We must write data fields which are present in data object. These fields may not be part of data base tables or in data sources. Exercises : Produce employee id, emp name (first name, last name), job- description. (employee, jobs) Display all jobs information including difference between max_ v and min_ v . Template Field and Data binding expressions: This is one more field of grid view and it is complex which can produce any type of presentation. Template field is again collection of templates and templates are used to define the content of creating field different templates are available to provide different parts of columns. Every template can have different type of content like controls, expressions and data binding expressions. In Asp.Net we can evaluate an expression against data object and some times class objects which are called as data binding expressions. To write them we have different asp.net blocks i.e < % # databinding expression %> DEPT OF CSE & IT Page 20

.NET Databinding expressions can be used in different places and especially for template field there are no properties to retrieve data object data. In Asp.Net 3.5 we can write data binding expressions in the following ways. i. < %# Data Binder.Eval (Container .DataItem, dataobject field name) %> ii. <%# Eval(<field name>)%> Asp.Net2.0 iii. <%# Bind (<field name>)% > Bind is set the data and send the data. iv. <%# any class accessible content%> v. <%# Computions %> Use bind when data object is updatable and presentation includes editable value. Eval (fld) represents data in object format. So before performing any calculations we must convert object to desired type and do calculations. Demo: (template field and databinding expressions). Auto generated columns:False <asp: Template Field> <templates <Header Template> <asp: Template Field> <asp:Grid view 1D=Grid View1 <columns> <asp:Template Field> <Header Template > <img src=hands.jpg /> </Header Template> <Item Template> <%# Eval (job-desc)%> <(item Template> <asp: Template Field> <Header Template> Max Level </Header Template> <item Template> <asp: Link Button ID= Imax Text = <%# Eval (Max v )%> runat = server. </item Template> </asp: TemplateField> <asp: Template Field> <Header Template> Difference</Header Template> <Item Template> <% # Convert.Tolnt 32(Eval (max_v) )- convert.Tolnt 32(Eval(min_v) )%> </Item Template> <asp:Template Field> </Columns> </asp:Grid View> Button click Button _Click Data set Template Field is collection of Templates. Header Template. to display heading for the current template field. Item Template** to repeat the given content for every row of data object. Footer Template DEPT OF CSE & IT Page 21

.NET to display the footer information for current template field. By default footer will not be displayed for Grid View. We have to explicitly set Show Footer: True(by default it is false) Show Header:true(default)/false Edit Item Template.*. used to provide editing content for the current template field column. Selected Item Template. Used to display content based on selection made within the grid view row.(dependent on selected Index property) <asp: Template Ffffield Header Text=Position> <item Template> <% # Get position (Eval (job _ desc) )%> </item Template> <Footer Template> <% # show Footer nfo( )%> </Footer Template> </Template Field> Declare int total Recs In this field we have use again gridview for presenting data and in this grid view auto generate columns:true is used Data Object for this grid view is design time prepared Sqld ata Source Control which is Conditionless. Good promotion for this will be with condition and also to bind data programmatically. In our example. Prepare Sql data Source for a table. Go to template field and add grid view in item template for this grid view use Data source ID instead of Data Source. <asp: Grid View ID = Grid View2 runat=server Datasource ID= Sql Data Source 1> </asp: GridView> Grid View Editing: All our above examples where presenting data to the user. If we want to make changes to data object using grid view we can implement grid view predefined editing concept. Grid view supports editing using properties events and its fields. All grid view fields support editing and they are based on gridview property called edit index. By default edit index value is -1 which means grid view running in non editing mode. When edit index is n then grid view is said to be in editing mode and n th row will be displayed for editing purposes. Bound Field, template field and other grid. View field react to this edit index property of grid view. One important field of grid view is used to provide edit and its related actions that field is command field of grid view. i) Used to display Edit, Update, Delete. ii) Provides events for its controls Edit Index Bound Field Template Command Field. Steps for designing a grid view with presentation followed by editing: 1. Place button and grid view in the form and set the following properties for grid view. Auto Generate Columns:false. 2. Display columns information using columns collection and its fields. 3. Once columns are prepared we must handle command field displayed button events. DEPT OF CSE & IT Page 22

.NET Edit Row Editing Delete Row Deleting Update Row Updating Cancel Row Cancelling Edit. Select Grid view goto events and choose Row Editing. Write the following code to change grid view to edit mode. <asp: GridView 10= Grid View1 runat= Server Auto Generate Column=False> <columns> <asp: Bound Field DataField= Job_id Header Text= Job _id Read Only= true/> <asp: Bound Field Data Field=Job _desc HeaderText=Job_desc/> <asp: Tempalte Field Header Text=Max Level> <Item Template> <% # Eval (Max- lvl)%> </Item Template <Edit Item Template> <asp: Drop Down List ID=Drop Down List1 runat=server> <asp: List Item>10 </asp:List Item> < >20 < > < >30< > < >40< > </asp: Drop Down List> <asp : Command Field Show Edit Button= true Show cancle Button = true show Delete Button= true/> .cs Button code: { Data set S= DataHelper.Get Data(Select * from jobs); Grid view1.Data Source=S; Grid View1.DataBind ( ); } .CS Grid View _Row Editing. { //New Edit Index gives the selected edit link row index Edit Index gives the selected edit link row index. Grid view1.Edit Index= e.Now Edit Index; Button 1-Click (sender , e); //rebind the data. } Grid view1_ Row Canceling Edit { Grid view1.Edit Index= -1; //default. Button Click (sender , e); } Up date button of Command field: Once user modifies the data and clicks on update we must retrieve the data from the current row and update the same with data base . To retrieve data from current row or any of the grid view content we have different retrieval methods for different contents. We have to use grid view structure to read data from its rows and cells. DEPT OF CSE & IT Page 23

.NET Grid View1.Rows - - Collections Grid View1.Rows [ 0 ] 1st row Grid View1.Rows[ 0 ].cells First Row Cells Grid View1.Rows[ 3 ].Controls-collection In the first row 3rd cell controls. Grid View1.Rows[n] . cells[n].Controls[n] //navigate all gridview1 rows. For(int i=0; i<GV1.Rows.Count; i++) { } Navigate particular row cells. For(int i=0; i<GV1.Rows[n].cells.Count; i++) { } Use for each instead of forloop Foreach (Grid View Row r in Grid View1.Rows) { r- refers current Row } For each(Grid View cell C in Grid view1.Row[n] cells) { C- refers to current cells in the row } Retrieval methods: If cell contains simple text then retrieve using text property of the cell. Navigate to the cell use text property. If cell contains data in a control which is implicity created then we have to use controls collection and retrieved the data. Ex : ( (Text Box) (Grid View1.Rows[0].Cells[1].Controls[0] ) ).Text (or) Text Box t1=(Text Box) (Grid View1.Rows [0].Cells[1].Controls[0]); T1.Text=.; To access structured grid view we can use its collections and perform these actions. Another important thing is if we can perform the action using java Script then it is highly recommanded. <Grid View> <Columns> <asp: Tempalte Field> <Item Template> <asp: CheckBox ID=Check Box1 runat=server </Item Template> <Bound Field DataField = job-desc Header Text=Description %> <asp: Bound Field Data Field= min-lvl Header Text=min Level/> </Columns> Button Click code { Data set ds=DataHelper.Get Data(string stat)Text=Selected } DEPT OF CSE & IT Page 24

.NET Check Box2-Checked Changed(Object sender, Event) { For each (Grid View Row rec in GridView1.Rows) { Check Box chk1=(Check Box) Grid View1.Rows [i] (or) Rec.Find Control(CheckBox1); Chk1.Checked=CheckBox2.Checked; ChekBox2.auto post back true. } /* if(CheckBox2.Checked) Chk1.checked=true; Else Chk1.Checked=false; */ Link Button1-Click (object sender, Event arg e) { List Box1.Items.Clear( ); For each (Grid View Row rec in Grid View1.Rows) { Check Box C1=(Check Box) rec.Find Control (Check Box1) If(C1.Checked) List Box1.Items.Add(rec.cells[1].Text) } } 1. Grid View Tasks: 2. In our example as a user selects the check box1 add items to list box. 3. Restaurant Repeater and DataList: These are also data bound controls that provide data binding concept. Less feature than gridview but unique in some of the outputs. Repeater and datalist has no structure like grid view. Repeater Control: Repeats the given layout for every row of data object. Template based and its structure should be defined using templates. Repeater Templates One of main advantage of repeater is its performance. It has no designing options, built in Layouts , runtime control for performing the tasks.(single property is also not available). No editing of data No paging of data No sorting of data All not supported features of repeater can be done programmatically. Button

DEPT OF CSE & IT

Page 25

.NET Repeator Source : <asp:Repeater ID=Repeater1 runat=Server> <Header Template> Job ID Description Min level </Header Template> <Item Template> <% # Eval (Job ID) %> <% # Eval (Job-desc) %> <% # Eval (Min-lvl) %> </Item Template> </Seperator Template> </Separator Template> <Footer Template> End of records </Footer Template> .CS Button Code: { Dataset dsa=Data Helper.Get Date(Select * from sal); Repeater.Data Source = dsa Repeater1.Data Bind ( ); } Demo : Button Repeater Source : <asp: Reader ID=Repeater1 runat=Server> <Header Template> <table border=1 <th> Select </th> <th> Job ID </th> <th> Description </th> <th> Min level </th> <th> Max level </th> </Header Template> <Item Template> <tr> <td> <asp: CheckBox ID=Check Box1 runat=server/> <im src= hands.jpg height=40 width=40/> </td> <td> <%# Eval(Job-id) %> </td> <td> <asp: Link Button ID=Link Button1 Text = <% # Eval (job-desc)%> Runat= server /> </td> <td> <%# Eval(Min-lvl) %> </td> DEPT OF CSE & IT Page 26

.NET <td> <%# Eval(Max-lvl) %> </td> </tr> </Item Template> <Footer Template> </table> </Footer Template> < Demo 3: Repeater <asp: Reader ID=repeater1 runat=Server> <Header Template> <h2> List of Available Titles </h2> </Header Template> <Item Template> <div id= sdir> <img src= hands.jps height =30 width=30 /><br> <a href= Default.aspx > <%# Eval(title) %> </a> <br/> <%# Eval (notes)% > <br> <a href= Default.aspx > similar pages </a> &n bsp &n bsp &n bsp <a href= Default.aspx > Cached pages </a> </div> </Item Template> Data List Control: Bound control that supports data binding. Provides Layouts for effective design and required Outputs. Provides properties/methods which allows user to control the Layout of DataList @ design time and run time. Its unique feature is presenting rows in the form of columns. Supports editing of data also but with little complexity not like grid view. No support for paging, sorting implicitly. Supports RAD also. Code: DataList1. Repeat Columns= Drop Down List1.Selected value; Data List1.Data Bind( ); Important Properties Of Data List: Repeat Columns:n Repeat Direction : Vertical / Horizontal Repeat Layout : Table / Flow Cell Spacing : n Cell Padding : n Grid Lines : Vertical / Horizontal / Both / None Some good design time options is using Edit Templates Option. Select DataList smart Tag and choose Edit Templates select the required template and start designing. (WYSIWYA aaroach of designing templates. Remember GridView also supports this kind of design.) Demo : DEPT OF CSE & IT Page 27

.NET Button Data List Button code { Dataset dsap= Data Helper.Get Data(Select * from jobs); Data List1.Data Source=dsap; Data List1.Data Bind ( ); } Source : <asp: DataList> <Item template> <%# Eval (job-desc)%> <br/> <asp: Link Button ID=Link Button1 Text = <%# Eval(max lvl)%> runat=server> </asp: Link Button> </Item Template> Note : In this example we have not used any sample code pre written but specified our own presentation code. After this we can continue using all properties methods of data list as usual. How Bound controls manage the post backs caused by their child controls? .Net provides a concept called Bubbled Event where a container control handles the child control event and in-turn raises a comman event. With Bubbled events we can write code within the context of bound control/ selection made.(not with independent code). For EX: Item Command event of DataList and Repeater fires when any post back is caused from their child controls similarly Row Command for Grid View Command name and Command Argument are two attributes that are used when child control event is handled by container. Command Name specifies the name of the control that caused post back and arguments for passing a value along with it. Demo : Add one XML File to our website. <items root> <item> <id> id54</id> <desc> It is a good </desc> <image 1> ~\img\5-jpg</image1> </item> </items root> 1. Create one Xml file with data along with it picture locations. In our Example : Items.Xml file. 2. Place images in the given location. DEPT OF CSE & IT Page 28

.NET 3. Place button and datalist in the form and write code to retrieve data from Xml file and also mark up to present the same. <Data List> <Item Template> <image Button ID= Image Button1 runat= server Image Url= ~/Children.jpg Command Name= m1 Command Argument= <% # Eval (image) %> <br> <asp: Link Button Text= <%# Eval (desc) %>/> <br> <%# Eval (price) %> <br> <br> <Item Template> Button click code { DataSet ds=new DataSet( ); Ds.Read Xml (Map Path(items.Xml) ); Data List1.Data Source=ds; Data List1.Data bind( ); Container means DataList properties. Data List1 _ Item Command and click it {//Response.Write(Item Selected); If(e.Command Name= = m1) Response .Write(e.Command Argument.To String ( )+Item Selected); Else if(e.Command Name= = L1) Response .Write (e.Command Argument.To String( )+Link Selected); Form View and Details View Controls: Specialized for inserting of data. Also provide editing, sorting and paging of data. Presents only single record @ a time. Derived from same grid view classes which means templates, fields etc will be like grid view. Details view uses Bound Fields under fields collection to display its data and Form View uses Templates to present its data. Mostly used along with data source controls but not with layers. (if layers are really required then object data source is used). Demo : Details view drag and drop Add Sql data source using choose Data source when that time we click advanced and checked Insert, Update & Delete and Click next enable insert, delete, update enable paging. Form View drag and drop Enable paging CRUD Operations Create , Read, Update and Delete. Default mode Change it insert. Demo 2: Grid View Details View

DEPT OF CSE & IT

Page 29

.NET For delete, Default update, select. change insert. mode, inserting

Sql Source Connection. Button Code // Details View1.Default Mode= Details View Mode.Edit; It cannot work. But no error. It works when run time create details view. Details View1.Change Mode(Details View Mode.edit) Demo 3: Grid view drag and drop. In Source <columns> out of columns <Empty Data Template> <asp: Text Box ID= Text Box1 runat=Server > </asp><br/> <asp: Text Box ID =Text Box2 runat= Server> </asp><br/> <asp: Button ID =Button 1 runat= Server> </asp></Empty Data Template> Grid View1: Edit Template and select Empty Data Template Details view drag and drop and change insert. Default mode set as insert. Empty Data Templates: It is one of the grid view template which is used to present data/ content when grid view data object has no rows. Remember , this template should be written outside colums or directly in grid view. We can refer the controls in this template using Find Control again otherwise we can use any details view. Form View etc directly. ASP.NET CONFIGURATION: It is very important to develop application based on configuration. Configuration based development will be scalable and also simple to handled project tasks. .NET is completely developed based on configuration. Base class Libraries, CLR and many new concepts like AJAX, WCF are also built based on provided for .Net application developers. In Asp.Net we can use two files: 1. Machine .Config 2. Web.Config for developing applications based on configuration. Some important common points for these configuration files are. 1. Simple text files can be edited using any text editor. 2. XML formatted which means hierarchial and case sensitive. 3. Cached in memory automatically which results in good performance for configuration based programs. 4. Processed in Hierarchical manner leading to configuration Inheritance in .NET which also means every configuration file inherits its parent configuration file settings. Machine .Config: Per server basis file and a system can have only single machine .config file. All settings of this file are applicable to projects running in the current system. Mostly handled by system/web administrators. Contains settings like browser capabilities limits for upload / download, default security principles etc. DEPT OF CSE & IT Page 30

.NET Located in .net frame work folder. Microsoft .Net\frame\ver\config Web . Config: It is called as application configuration file. Generally located in root folder of the project and optionally can be created in sub folders of the project. (use add new item to create sub folder web.config files) In asp.net 3.5, one of the improvement is Ajax enabled websites. All asp.net 3.5 / 3.5 spl sites are Ajax enabled. (Earlier to Ajax enable a site there was a big procedure) Where is that Ajax enabled in 3.5? In web.config it is enabled all settings split into 5 sections are written in web.config for Ajax enabling a site. Configuration file Structure: <configuration> .sections subsections </Configuration> As a developer we must be aware of setting and its section hierarchy. System.Configuration.dll is the assembly/ Namespace where all configuration settings related classes are present. We can use this in our code to read the settings of config files. All settings are divided into 3 categories. 1. Application Settings. 2. Security Settings. 3. System and other Settings. Application Settings: It contains static variable kind of declarations, mail settings, connection settings, compilation settings etc. 1. <app settings> In asp.net by default one page values are not available to other pages and if we want to define application wide static variables this is the most excellent method. appSettings <app Settings> <add key=user value= SCOTT/> <add key= db value= PUBS/> </appSettings> Ex : Label Button Button code Label1.Text=Configuration Manager.AppSettings[0]; (or) [user]; Q) Can we over ride the settings of parent configuration file? Yes by default. Todays Asp.Net means DEPT OF CSE & IT Page 31

.NET Asp.Net web forms Asp.Net Ajax Asp.Net MVC Asp.Net Dynamic Data. Ajax : Asynchronous Java Script and Xml Ajax is really a set of technologies working together: X HTML and Css for markup DOM for display & interaction. XML and XSLT for data interchange and manipulation JSON for marshalling objects XML Http Request for asynchronous communication 3-Tier Client Server Applications. Asp.Net AJAX: Set of Libraries (java script, server side and all others) Compatible with all browsers. Can we used by non asp.net people also used like PHP, Perl etc. Development will be lot simplified. History : ATLAS is beta name of AJAX Asp.Net AJAX 1.0 (in ASP.NET 2.0) as a separate installation. Now ASP.NET 3.5 (AJAX 3.5) part of it. ASP.NET AJAX 4.0 (beta) Q) How AJAX is provided for Asp.Net developers? Asp.Net AJAX is provided as server side ajax and client side Ajax. Also called AJAX extensions for asp.net. AJAX control toolkit for Asp.Net (separate install) AJAX extensions Script Manager Ajax show all these done in it. All JavaScript code. Update panel Take gridview put in update panel. (ii) Connection Strings: If we are using data sources like Oracle, Sql servers and other it is preferred to write connection strings in <Connection Strings> so that we can change it during deployment and also during project development when we relocate the application. Ex: <connection strings> <add name= Cnpubs Connection String= data source=nit \server; User id=Sa; Database=pubs; Provider Name=System.Data.Sql Client/> </connection strings> System.Configuration; Button1-Click { String S=Configuration Manager.Connection Strings[Cnpubs].ConnectionStrings; Sql Connection Cn=new Sql Connection(s) Cn.Open( ); Label.Text=Connected; } DEPT OF CSE & IT Page 32

.NET Q) Can we use configuration settings in mark up code? Yes. We can use but again a different blocks . < % $ section; setting % > Ex: Sample Connection String=<%$ Connection String:CnNwind% > <asp: Label .id= // runat= server Text = < % $ AppSettings: user %> /> <Compilation> tag (system.web) Debugging is one important aspect while developing an application. A language or IDE should be very much supportive for debugging an application. CLR, VS.NET, C# all have very strong support to debug. Every complier has some debug options and also runtime like CLR provide some utilities for debugging. Any how for Vs.Net users debugging is very rich and availanle in the following forms: Debug windows Break Points Visualizers Hovering messages/values Exceptions Events for error handling. Debug=true preferred during development. Debug=false preferred during production.(default value is false) Default language for asp.net is vb.net and if we want to change it for our project entirely for C# then use default language attribute of compilation tag. In <app Settings> <mail Settings> SENDING MAIL EXAMPLE Q) How to send mails from .Net application? For every web applications sending emails and sending sms is an essential part. .Net provides System.Net (Networking) assembly for entire network related classes. System .Net .Mail is the namespace where we contain SMTP related classes. (system.web.Mail old namespace) Q) What is SMTP? Simple Mail Transfer Protocol. Set of rules for sending mail to the required recipient. SMTP servers are softwares that implement these rules and provide all SMTP functionality. As a .Net developer we must either design our own SMTP server, use is as smtp server or use any third party smtp servers. (Many 3rd party and paid smtp servers are available and also when we host our site free smtp servers are provided from our site providers) Once SMTP server is setup then we can play smtp client role from our project. (open standards) (same rule for all SMTP servers) System.Net.Mail contains 2 important classes called MailMessage and SMTP Client. Mail Message is used to prepare mail content like To, CC, Subject, BCC, Body, attachments Smtp client is used to fulfill all requirements of smtpserver and pass the prepared. Mail Message object to Smtp server. DEPT OF CSE & IT Page 33

.NET Smtp.gmail.com Ex: Name From Passwords To Subject Body Using System.Net: // communication based library Using System.Net.Mail; Mail (Message msgobj ; //server obj.Use Default Credentials=true; Image Button Click { Smtp Client server obj=new SmtpClient( ); Server obj.Host=smtp.gmail.com; Server obj.Enable Ssl=true; //use encryption ssL smtp port 25 security socket location Server obj.Port=587; Msgobj=new Mail Message( ); Msgobj.From=new MailAddress(TextBox1.Text,Hidden, System.Text.Encoding.UTF8); Msgobj.To.Add(Text Box3.Text); Msgobj. Subject=Text Box4.Text; Msgobj. Body= TextBox5. Text; Msgobj.Attachments.Add (new Attachment (Map Path( Pocket pc.gif) ) ) ; Msgobj.Delivery Notificatio Options=Delivery Notification Options.On Failure; msgobj.Body= <h1> Hello </h1> <img src=grab.gif> msgobj. Is Body Html=true; Server obj.Send (msg obj); Label6.Text= Mail sent successfully.!; } Application <app set> <mail settings> <smtp from=info @gmail.com> <network host= smtp.gmail.com Password =secret port= 587 user Name=demo/> </smtp> </mail setting> ASP.NET AUTHENTICATION Security Configuration: Q) What do you mean by security for a web application? Basically every web application is poor in security and we need lot of security at different levels starting from top operating system level and lowest code level. Asp.Net along with iis provides all required security methods like: 1. Operating system level security 2. Ip level security and Domain level security. 3. User level security which can be individual or role based. 4. Finally code level security with assemblies. DEPT OF CSE & IT Page 34

.NET Administrative Tools IIS Select Website and goto properties Select Directory Security (web app) Authentication . Ip address and Domain Name restrictions. Secure Data Communications using SSL (secure socket layer) Asp.Net security refers to user and role based securities which are defined by application developers only for the web application. Role based security means we create a role like Manager, Clerk, Call Centre, Admin and assign permissions to it. After creating roles we create users and map them to relavant roles. This is universally followed and it makes work simple to add (remove permissions). User based Security: It means we assign permissions directly to users instead of any role. This is used when we dont have lot of permission sets and users. Asp.Net , Data Bases and Operating system all provide this security concept with 2 processes. i) Authentication Process. ii) Authorization Process. /* Authorization is a problem i.e Authentication identity access resources*/ The process of verifying user credentials against a source or in the defined method is called Authentication. Authentication includes creating identity also which is the proof for user is authenticated or not. The process of checking whether the requested resource like .aspx page, Xml file, image file, db file etc is allowed or denied is called authorization. For a good Security implementation. Authentication + Authorization = Security. Asp.Net supports authentication in 3 different methods. i) Windows authentication (default) ii) Passport or Live authentication. iii) Forms authentication **** A project can have only 1 authentication method implemented Microsoft. Windows Authentication: User makes a request IIS checks and in absence of identity displays a login window for entering credentials. User enters credentials and resubmits to IIs. Check with o/s accounts and on successful verification creates identity and redirects user for secured page. If anonymous automatically identity is created. Passport Authentication (or) Live Authentication: User makes a request for secured resource . IIs allows as anonymous but asp.net redirects to passport.com website in absence of passport ticket. Passport display login page and asks user to enter passport credentials (user should be registered with pp). Passport verifies the credentials with passport database and on successful verification creates passport authentication ticket. DEPT OF CSE & IT Page 35

.NET Again @ iis user is allowed as anonymous and this time asp.net serves user with secured page because of passport ticket present. Forms Authentication (Asp.Net authentication): In this case asp.net only does authentication. Forms Authentication Module (FAM) is the one which is responsible to perform all this authentication. System.Web.Security is the name space wher Forms Authentication module and its relavant classes are present. Forms Authentication is one very important class in it. Q) How Forms Authentication works? User makes a request for secured web page. Its allows user as anonymous redirects user to asp.net. Asp.Net checks for Forms authentication ticket and redirects user to a page called ticket. (Login .aspx should be explicitly created by user). After user entering credentials in login page it should be verified against a data source (which is completely created by user only.) Once credentials are matched / found then ask asp.net FAM to create Authentication ticket followed by redirecting user to secured page i.e requested. Now Asp.Net returns secured page because the ticket is available and most importantly along with results the created ticket is also sent to user. Asp.Net provides 2 tags <authentication> and <authorization> to setup the whole security process. <authentication mode=<windows/Forms/Passport>/> <authorization> <allow users= <usermanes>/> <deny users= <usernames>/> . Default allow users= * </authorization> In place of user names we can write two wild cards. * -all users. ? anonymons or unauthenticated. <deny users= ? /> <allow users = * /> Demo : A plan is always required for implementing security. In our application we have to divide pages into different folders and assign different authorizations for it. Try to implement all public content in the root and do not write any authorization for root. In every folder try to write authorization and specify the restrictions/security. 1. Start new website and create one folder called Admin in it. 2. Create some pages in Admin say add, aspx, remove .aspx etc. 3. Goto home page (default .aspx in root) and create two hyperlinks which redirects to admin pages. 4. Goto root web.config and change authentication mode to forms. 5. Goto Admin folder and create web.config file and set Authorization to allow only authenticated users. In web.config. <system.web> <authorization> <deny users= ? /> </authorization> </system.web> DEPT OF CSE & IT Page 36

.NET Login Page Code: As part of authentication when user is redirected to login page we have to provide input source so that user enters required data and we can check them against our data source. This data source must be planned and the following data sources are most standard in any type of application. 1. Database : This is the most preferred storage for user information and provides security performance etc. we have to create tables, procedures to perform all authentication related tasks like registration procedure , login checking procedure and others. 2. Xml.files: If for any reason data base is not used in the project then we can use Xml for user information Xml provides all functionality like data base but for limited amount of data and with additional security plan. 3. Configuration file only: We can use web.config inself for storage of data so that separate Xml or data base is not required but again performance, security and dynamic behavior is a constraint. In Database New table. User name Varchar(50).Primary key Password Varchar(50) Role Varchar(50) Remarks Varchar(50) a) Create table[s] and enter some sample data (real data will be entered from the application only) b) Write procedures to provide access to these tables.(highly recommended even though we can access table directly) c) Now in the application write code in data layer (business layer) for all tasks like adding users, modifying users, verifying users etc..(both procedure based and some table based). d) Now design ui like register .aspx for registration, login .aspx for authentication etc. and use Data layer to perform the tasks.

User name Scott Smith tiger

Password Admin 123

Role Good Manager

Remarks

Good

Right click stored procedure and add new stored procedure. Create procedure dbo .New User ( @Username Varchar(50), @Password Varchar(50), @role Varchar(50), @remarks Varchar(50), ) As DEPT OF CSE & IT Page 37

.NET Insert into users values (@username, @password, @role, @remarks) .return. In Datalayer. Public Static void Execute Procedure( String Procedure name, Sql Parameter[ ] pars) { Sql Connection cn=new Sql connection (@ data source =nit\ server ; user id=sa; Database=pubs); Cn.Open( ); Sql Command cmd=new Sql Command (procedure name, cn); Cmd.Command Type=Command Type.Stored Procedure; Foreach (Sql Parameter P in pars) { Cmd .Parameters.Add (p); } cmd.Execute Non Query( ); cn.Close( ); } Public static bool Check User (string uname, string pwd) { Sql Connection cn=new Sql Connection( @data source =nit\server; user id=sa; database = pubs); Cn.Open( ); String str=Select username from users Where username= +Uname+ and password = +pwd + ; Sql Command cmd =new SqlCommand(str,cn); Sql Data Reader dr=cmd.Execute Reader( ); If(dr.Has Rows) Return true; Else Return false; } Now Login.aspx Login page Using System.Web.Security In Button-Click.Code { If(Data Helper.Check User(TextBox1.Text, Text Box2.Text) ) Forms Authentication.Redirect from Login Page( TextBox1.Text, checkbox1.Checked); //Creates identity and redirects user to secured page Else Response.Write(Invalid User\Name\Password Retry); } How to create a ticket in Forms authentication? Different methods are available to create authentication ticket and most commonly used is forms authentication class method redirect from Login page. This method takes two arguments. DEPT OF CSE & IT Page 38

.NET 1. User Name which is the identity for asp.Net authorization. 2. A Boolean which specifies whether the created ticket should be persistent or not. False means in memory ticket which will be available as long as user is working with application. Once redirected to other site or if browser is closed the ticket is lost. 3. True means ticket will be persistent in clients locations and will be used for every visit to the site (default persistent time is 50 years)with this option we can provide choices like remember me on this computer, remember me for 15 days etc. 4. Once ticket is created we can destroy that using signout method of Form authentication class. <authorization> <deny users= SCOTT/> <deny users= ?/> <allow users= */> </authorization> Label : Admin /add.aspx.cs In Page Load Label1.Text=User.Identity.Name; User.Identity.Name: It is the property which provides authenticated username, returns null if user is not authenticated. Authentication type and Is Authenticated are two more available in this context. What about Sing up and other forms? A part from login we must design these forms also in the same tiered model. (Login, Register, Changed password etc..) In Root Add new Item as register.aspx Registration Page Data.Sql Client; In Register . Button code { Sql Parameter [ ] pars=new sql Parameter [4]; Pars [0]=new Sql Parameter (@ Username, Sql DbType.VarChar, 50); Pars [0] .value=Text Box1.Text; Pars [1] =new Sql Parameter(@password, Sql DbType.VarChar, 50); Pars [1].= TextBox2.Text; Pars [2]=new Sql Parameter (@role, Sql Db Type.VarChar, 50); Pars.[2].value=Drop Down List1.Selected Value; Pars [3] =new Sql Parameter (@remarks, Sql DbType.VarChar, 50); Pars [3].value=TextBox4.Text; Data Helper.Execute Procedure(New User, Pars); Label1.Text=Registration Successfully; //Instead of Sql Parameter & others preferred is factory In login page New User Navigate Url as Register.asps Other Sources for Storing User Information in Authentication: Xml: Steps : DEPT OF CSE & IT Page 39

.NET a) Add New Item create Xml file and store user information in it with a planned structured. b) When we have multiple sources for storing data it is always good practice to have configuration setting which specifies which data source to consume so that later we can simple modify setting an change behavior of project. c) Create a method in DataHelper which checks for valid credentials in Xml file. d) Goto form and use this method for crating a ticket User info.Xml <Users> <user> <user name> SCOTT </username> <password> TIGER </Password> </User> <User> <Username> Smith </username> <Password> 123 </Password> </User> <user> <Username> XYZ </username> <Password> 456 </Password> </User> </Users> In web.confign <app Settings> <add key=source value = XML /> </app Settings> In DataHelpers Class. Public static bool Check User (string uname, string pwd, string loc) { Dataset ds=new Dataset( ); Ds.ReadXml (loc); //read Xml file into data set hierarchical-relational Data Row[ ] recs=ds.Tables[0].Select (User name= + uname+ and password = +pwd+ ); If(recs.Length>0) Return true; Else Return false; } Goto Login page And In Login button code { Bool found; String str=Configuration Manager.App Settings[Source]; If(str = = XML) Found =DataHelper.Check User(TextBox1.Text, TextBox2.Text, Map Path (users info.xml) ); Else if (str = = DB ) Found =Data Helper.CheckUser(TextBox1.Text, TextBox2.Text); If(found) DEPT OF CSE & IT Page 40

.NET Forms Authentication.Redirect From Login Page (TextBox1.Text, Check Box1.Checked); Else Response .write(Invalid user Name/Password/-Retry); } Note : Xml provides functionality like database like dynamically adding data, modifying users etc Exercise : A project contains all public content in root folder and private content in 2 sub folders called Admin and Call centre. Admin folder should be accesses only by Admin users who are authenticated public content is accessible to every user. Call Centre content should be accessible who is aware of both call centre credentials and admin credentials. In every page the authentication name should be displayed. Questions : 1. Does asp.net support Digest Authentication of windows? 2. In a project can we have multiple authentication set and if we want then logically how to implement? 3. How to find out user in Login because of not authorized with his identity and of not authorized with his identity and also how to find the requested secured page from user? 4. What will happen if we set authorization as deny users=? In root.. 5. What will happen user directly requests? Secured page Authenticated page Public page Configuration file method: Instead of creating Xml file or database file and writing helper methods we can use web.config to store user information. Forms authentication class itself provides methods to check these credentials. This method doesnt provide any dynamic behavior for maintaining user information like adding users, modifying user information etc. In root web.config <authentication mode= Forms> <forms> <credentials password Format= Clear> <user name= Scott password= Config/> <user name= Smith password= 123/> </credentials> </forms> </authentication> Else if(str = = CFG) Found=FormsAuthentication.Authenticate(TextBox1.Text, TextBox2.Text); In <app Settings> <add key =source value = CFG/> </appSettings> Note : Authenticate method takes user name and password as input and returns Boolean as the result. DEPT OF CSE & IT Page 41

.NET One important feature that credentials stack provides is encrypted paaword option . Instead of clear in password Format we can use MD5 and SHA1 secure hash algorithm system.Cryptography. How to get the key for our value (if we want to implement SHA or MD5) Many tools provide the key and .net also provides one method in Forms Authentication called Hash PassWord for String In Config File (value, format) (config , shal) In Another link Bu in login page Response.Write(Form Authentication. Hash Password For Storeing In Config File(TextBox2.Text, SHAI) ); ASP.NET membership for security? For every website that we develop which needs security, we must follow same authentication authorization. Ticket creation etc and in our examples or projects. We have implemented commonly the following list: 1. Database Tables, Procedures 2. Security tags Authentication, Authorization 3. Layers Data Helpers 4. U I Login, Register, etc. 5. Validation Asp.Net membership automates all these tasks and expects very few inputs from user in order to set up the security problem. This total security set up is performed using configuration tool of Asp.Net. we must invoke this only after preparing public and private content of the project.(plan) First create one project In website After that Asp.Net Configuration Click on Security Use the security setup step by step Select from the internet After running the wizard we can find the following new changes to the project. 1. Root.web.config with Forms authentication. 2. New web.config in admin folder. 3. A database with name ASPNETDB.mdf in app-data is created with all tables and procedures. 4. In admin web.config authorization is also added. LOGIN CONTROLS: Asp.Net provides login controls set for providing membership user interface. All these controls can be consume with membership as well as independently with their properties, methods and events. 1. Login Control: Used to accept user credentials and verify the same with membership database using its own layers and procedures. Login and other controls of membership are completely customizable. Different properties, methods and events are provided for every control. 2. Login Name Control: Used to display authenticated user login name null when not authenticated can be placed wherever required.

DEPT OF CSE & IT

Page 42

.NET 3. Login Status Control: Displays Login/Logout based on user authentication both are coded i.e when we click on Login redirects to Login page and Logout destroys the ticket. 4. Login View Control: Allows user to prepare authenticated and unauthenticated content differently. 5. Change Password Control: To change authenticated user password we can use this control. Place it in authenticated page. Property: Continue Destination Page Url 6. Create User Wizard Control: To provide Registration option for our site users we can use this control. Fully customizable control many new/old content can be customized. 7. Password Recovery: This control provides new password to the user after verifying user name and hint answer. The result will be sent to registered email id account only and for this we have to set properties like from email addres, web.config smtp settings for smtp server otherwise it throws an exception. Without membership we can create one login page with Login Controls. After that we write the following code under Login_authenticate Controls { If(Login1.UserName= = Scott &&Login.Password= = tiger) e.Authenticated=true; else e.Authenticated=false; Label1.Text. Smith; In Check If(MemberShip.Validate User(Label1.Text, TextBox1.Text) ) Response .Write(authenticated); Else Response.Write(Failed); Login controls are complete customized. We can create user interface and connect with Membership also. Note : Both examples how to customize membership by consuming only their controls and also by using their data layers and backend procedures/tables. 1st Case: Without 2nd Case: Used membership with our own ui. When membership is not preferred? 1. If the data base server should be some non Sql server. Like Oracle, Xml etc. non possible. 2. Microsoft provided some additional sources sdk for using membership with Xml, access etc. but they must be separately downloaded from Microsoft site. 3. Some limitations of rules/ui cannot be modified. Some Advanced Settings for authentication: Can we change the default location of login .aspx and also its name if we want? Yes . we have to use <forms> tag of authentication to change it. Login Url is the attribute, using which we can change. Ex: In web.config <authentication mode= Forms> <forms LoginUrl= valid .aspx> </forms> DEPT OF CSE & IT Page 43

.NET </authentication> Can we change returnUrl from default aspx to other .page? Yes. Using default Url=<pagename> we can do that. What is the name of authentication ticket which asp.net by default creates? .aspx auth is default and it is highly recommended to change this for avoiding conflicts between asp.net developed websites. Name = <ticket name> In <forms name= Prjdemonit login Url=> Silver Light: Cross Browser Cross Platform Plug-In .Net Media Experiences RIA (Rich Internet Application ) Installation List. Visual Studio Silver Light Tools for Visual studio 2008. .Net frame work 3.5 service pack1. Silver Light SDK Expression Blend Deep Zoom Composer Java Script Helper Files. Expression Studio. Expression web Expression Blend Expression Media Expression Design Road Map Silver Light V1 Java Script base Silver Light V2 Java Script and .Net Tools (.Net managed support) Expression suite and visual studio updates for all Public Silverlight releases. Visual Studio Designer Support(Cider) Later this year Silver Light 3 (Beta) Run time Features: 2D, Graphics, Audio, Video Animations Text, Text Input*, Controls*, Layout*, Styles/Templates* DataBinding*, NetWorking. HTTP/s and sockets. .Net Support * C# & VB.Net*. LINQ*, Xml Apls*, Generics*, HTML Integration*. JSON serializer local storage*. Crypto Apls(AES)* Threading * *Silver Light2. XAML. Extensible Application Markup Language. XAML for designers. Code for developers. When to go for AJAX When to go for Silver Light DEPT OF CSE & IT Page 44

.NET Asp.Net AJAX XML HTTP calls Client Processing DOM manipulation JSON Tight Asp.Net Integration Silver Light Visualization Rich Graphics-Drawing and Animations Multimedia Designer + Developer .Net Integration

How to Develop a SilverLight Application? Desktop/Web/Ajax/Silverlight. We must know all the above. After installing Silverlight tools for Visual Studio. Start Visual Studio and select new project Silverlight SilverLight application. New Project . select it Then Window comes In C#Silverlight Then click OK. Another window open Add Silver light Application Add a new Asp.Net web project to the solution to host Silverlight. Automatically generate a test page to host Silverlight at build time. Ok

Click on that Then In solution Explorer In that Silverlight App Page.Xaml Siverlight App.Web Silverlight Application In default Script control Silverlight controlproperties Source. Silver light Client Bin Select Xap file In page.Xaml And right click select Expression Blend Then Expression Blend window opened.

ASP.NET STATE DEPT OF CSE & IT Page 45

.NET Asp.net ViewState: When http is stateless how asp.net provides state implicitly for its controls? In order to provide state for controls asp.net creates one hidden field implicitly and stores all processed values of the form as a single value. This hidden field will travel along with results of the form to the client. But client will not be aware of this hidden field values. Because hidden field will not be displayed in the form clients enters values asusual and submits the form to server. Server first reads all hidden field values and restores the form dispatched state. Continuous form processing with new values directly from form elements and old values from the hidden field like this always server contains old and new values at the time of processing the form. Originally server doesnt maintain any value for the client. But still output will be completely statefull for both form and its controls only processing will be there to server. Ex: In Button If(View state[a]==null) View State[a]=0; ViewState[a]= Covert.Tolnt(view state[a]) .ToString( )+1 Dataset myds; If(ViewState[ ds data] = =null) { Data Set myds=DataHelper.Get Data(Select from Jobs); View State[ ds data]= myds; } Else { Myds= (DataSet) View State[ ds data]; } Grid View1.Data source=myds; Grid View1.Data Bind( ); Link-Button Click { Myds=Data helper.Get Data(Select * from jobs); View State[ds data]=myds; GridView1. Data Source=myds; Grid View1.Databind ( ); } If we want to share view state to other pages and other users what should be done? Primitive/Complex type. Question: Is view state data is secured? Answer : No. It is not secured but it is not readable. It is encoded with base64 format. By default it is not secured but we can encrypt view state data and also perform some validation check based on machine using Enable View State Machine=T/F attribute for page and <machine key> tag in web.config can we used to encrypt data in SHA,MD5 and other algorithms. Making view state secure will effect performance of page state secure will effect performance of page. Question: Will there we any load on the server especially when we use view state ? Answer: Yes. It might effect server especially when we use complex types instead of primitive types. Because complex types like Dataset,Employee cannot be pack in a single DEPT OF CSE & IT Page 46

.NET string we have to serialized the data and store it in hidden field. Again when client gets the hiddenfield it should be deserialized into dataset at server. Even though server implicitly performs it. It is time consuming task and effects performance. Also to be nated is the objects which cannot be serialized will fail to get storage in viewstate. Int a=100; ds a=100; Serialization means Memory to string type. Question: What will happened when lot of view state data is programmatically created. Which is unknown at the time of development ? Answer: Normally view state limits same as page limits but from Asp.Net2 we are provided. A configuration setting where we can limit the view state data and using this programmatic and unknown data can be controlled. Http: Http is pure stateless protocol which means every request is treated as new request. Applications demand everything in statefull behavior today. So for a developer it is relly a tough job to implement state for web apps.(Desktops are completely statefull) This tough jobs is made simple with asp.net aupport to maximum extent. What state management is required? 1. Web forms and its controls should retain their values in round trips because they are normally lost in Web apps. 2. All form objects which are created @ runtime should also retain their values in round trips. Normally they do not retain. 3. Values between multiple pages. All values like control values, object values etc. by default when we redirect using hyperlink or redirect method all values are lost. This state is one of the most creative state that we can provide for example authentication ticket is implicitly statefull. 4. The above state i.e 3rd one should be within user context only. It should not be available to other users once that state is provided. The value should be available for multiple users. 5. Same state but accessible to entire application i.e to all users of app(not global variable) 6. Cross App Redirects with state(very harmfull) Meaning: Values should be accessible but unlike not within the application. They must be available to other application also.like passport authentication. This is not implemented in websites where security is the key area like banking. Online transactions etc. but this is also one of the important requirement for most of the one of the important requirement for most of the sites like online ticket booking needs to use payment gateways and visa services to process credit card transactions. Earlier we had very poor support for this state. But today SOA service oriented architecture is excellent solution. Asp.Net support or how to achieve this state Requirements? i) Asp.Net provides view state conept to achieve both controls and object state within the page. ii) Same view state concept. iii) Server.Transfer, CrossPage Post Back Url, Query String **, Cookies, Sessions and profiles. iv) Same as third one-all provide within user context. DEPT OF CSE & IT Page 47

.NET v) Application object, Cache Object, Velocity Service, Virtualization concept for all users. vi) Cross Domain Cookies, Cross App Request, some QueryString not preferred. Preferred: WebServices, WCF State between multiple pages: View state maintains state as long as user is working with current page, once redirected to other page or browser is closed then view state will be lost. Question: What for Multiple Pages ? Answer: Cross page post back option of asp.net 2.0. Normally every post back control causes a postback to same form (Post Back forms) . If we use a property called PostBackUrl and specify different page name then it submits the form to PostBackurl specified form. In this transfer current page view state will be submitted to new page and new page maintains both pages state. Question: How to refer current view state and previous page view state? Answer: Current form content should be reffered normally i.e textBox1.Text=-. Where as perform controls should be reffered using another reference provided by asp.net called previous page. Ex : From new page Page .TextBox1.Text refers to current page. Text Box1.Text refers to current page. Text Box t1= (Text Box)-Previous Page.Find Control(Text Box1); Refers to previous page text box1. (only in case of cross page PostBackUrl) Otherwise error occure available only between two pages not more than 2. Response.Redirect(<query string>) Using this kind of redirect we can carry values to the total website pages and also to other websites if they can receive this value. [REST(Representational State Transfer)] Response.Redirect(Add.aspx) Response.Redirect(Add.aspx? a=10); Response.Redirect(Add.aspx? a=+TextBox1.Text); Query string concept can carry values but @ a cost of user maintenance i.e Concatenation.code etc. Question: But what about again complex types in query string? Answer: We have to manually serialize the data and store it in string. ds.GetXml( )= It returns string with all data in xml format. Example: String data=ds.Get Xml( ); Response.Redirect(add.aspx? a=+data); Note: Remember this will be displayed in Url and Url size is limited. Try to implement upto 255 characters. For our own classes many serializers classes like stream classes, xml serialize class are available. Old Server.Transfer method: Redirects to a page which is within our application along with current page values which can be read simply using. Request[<control name>]. This will carry all values and it doesnt update browser url which leads to many other issues/problems. Page 1 Page 2 DEPT OF CSE & IT Page 48

.NET Server.Transfer(page2.aspx,true) In Page2 Request [TextBox1] this is from page 1. This state also is available between two pages only and not preferred in most cases.(in projects) Asp.Net /Http Cookies Concept of Http(not Asp.Net) It is a name=value pair like a variable which travels between every request/response. o Maintained by Browser. Based on domains where they are created and travel based on the domain name only (optionally with path). o Cookies are of two types. 1. In-memory cookie. 2. Persistent cookie. In-memory cookie is the one which will be available as long as user is working with web application i.e online. Persistant cookie means which is stored in client or browser system and which is retained when request is made to the related domain i.e online and offline. Question: Does browser restrict anything on cookies? Answer: (No .of cookies, size of cookies, type of data should be limit). 10 cookies , lmb per domain(up to 16mb accepted) type simple/primitive (no complex). Question: Why cookies are not safe? Answer: Cookies travel using http headers. Which is by default simple textual formatted. Optionally we secure them using ssl but @ a cost of performance. Some external sites/requests will be accessing our client resources. Fiddler browser traffic capturing. Nikhil web development tools helper IE Dev Tool Bar Fire Bug for Firefox. In browser tools web development. Click enable logging When click on it. Window appear Request Headers Question: Who can create cookies? Answer: Any http compatible like javascript/asp.net can create cookies. Question: How to create cookie in java script ? Answer: window.setcookie. (<cookie name>, <value>); Window.getcookie (<cookie name>) Question: How to create cookies in asp.net ? Answer: In 2 ways i. Old Response.Cookies[<cookie name>]=value; ii. Using Http cookie class Demo How to create In=memory cookie. User Name When we click on enter connect with another page submit Link button Enter In Button-Click { Httpcookie objcookie=new HttpCookie(user name); objCookie.Value=TextBox1.Text; DEPT OF CSE & IT Page 49

.NET Response.Cookies.Add(obj cookie); Response.write(cookie created); } In LinkButton-click Enter { Response.Redirect(default.aspx); } In pageload of Default.aspx Text Box1.Text=Request.Cookies[0] (or) value; Cookies [user name].value; In persistent Objcookie.Expires=Date Time.Now .Add Days(2); Note: Every browser storing cookies are different location. Question: Can we assure the existence of cookie? Answer: We cannot assure. HttpCookie obj=new HttpCookie (user ); Obj.values(name,10); Obj.values(e mail,20); Request.Cookies[user] [name] Request.Cookies[user] [email] Multi valued cookie Question: What are the draw backs of cookies? Answer: not safe Dont use for crotical data complex data cannot be stored. Limited data. Next state related to multiple pages is accomplished using session object of asp.net. 1. Application object of Asp.Net refers to application main process which is created to serve project request. 2. Application will be started when first user makes a request for a resource (It is an App domain internally for runtime) 3. Application contains different type of resources and by default the important content of every application is one or more sessions. Session: Session is another process which is reffered as sub process and which is created for identifying users. By default empty sessions with id are created by run time and when any content is requested for storage is requested then Asp.Net creates session with storage server. A session is created when new user makes a request for any resource. Every session is identified with a unique id called session id. This session id by default travels between request and response using cookie. Application and session objects can be used to store data so that our state management requirements can be fulfilled. Any data stored in application it is accessible to the entire application users. Session data is accessible only to the current user remember session data will not travel only session id travels. Question: When application ends? Answer: When all sessions are closed and created resources are collected (Garbage Collector & CLR) then application ends. Dont assume when no sessions are active application is down. It might be still running. Session ends always based on its time out period. In Asp.Net by default session time out is 20 minutes. Which means when user fails to request server back within 20 minutes then the session will be lost. Session can be programmatically stop using session. Abandon( ) method. After Abandon method further statements related to project resources will be executed with a new session id.

DEPT OF CSE & IT

Page 50

.NET It is always recommended when we abandon session redirect user to a new page of other site (or) current side based on requirement. One good feature of session handling in Asp.Net is its ability to control sessions programmatically and also using configuration <session state> is the tag in web.config which allows user to maintain session related settings. Ex : <session state timeout=5/> Will change default 20 minutes to 5 minutes. Same thing can be done programmatically using session object and time out property. Session.TimeOut=5; Demo In Application and session related to storage/stage. Label1 Label2 Link button Link button Total users Online users Link button 1 { Label 1.Text=Application [a].To String( ); } Link button 2 { Label 2.Text=Application [b].To String( ); } Application and session objects can be consume in the form of events also. These events cannot be written in any part of program like application and session variables. They must be placed in a separate file called Global.ASAX. Events like application starts, session starts application end, session end etc are in global.asax file. Global.asax and its importance: i. This file is called active server application file. ii. It should be placed only in the root directory of project and only one file should be present. iii. It is configured by itself to reject any direct requests, means no user can directly request global.asax file iv. When user requests a resource very first global.asax file will be executed followed by the requested resource. Global.asax file code is event based which means if the event matches with request then it will run the code, otherwise it ignores global.asax and continuous for the resource execution. v. This file can also be used to consume some classical COM components using different tags and methods. vi. Global.asax file is again internally a class which extends http application class.(which represent our app) <% Import Namespace=system.data %> (or) Using System.Data even Acquire Request State In Application start { Application [a]=0; Application[b]=0; DEPT OF CSE & IT Page 51

.NET } In session-start { Application [a]=Convert.Tolnt32(Application[a])+1; Application [b]=Convert.Tolnt32(Application[b])+1; } In session-end { Application [b]=Convert.Tolnt32(Application[b])-1; } Session-current user. Application data is accessible to all users. Steps for chatting using Application/Session variables: 1. Create a page with name chat room.aspx. 2. Place Text box and set to multiline Text Box. 3. In page-load write code to check whether any messages are present to display in application variable. If found write code to display them. Code : String mesgs; Page-Load { if(Application[Messages]!=null) means messages are present Text Box1.Text=GetMessages( ); } String Get Messages( ) { for each(String s in(List<string>)Application[Messages]) { mesgs+ =s+\n; // \n-It is not work system.Environment .New Line } Return mesgs; } 4. This page has o get messages from the added list @ regular intervals. We can do this in 3 way. i. Java script set TimeOut(<fn> ,<interval>) ii. Using < meta tag of html iii. Using Ajax Timer control. Goto sourc and add meta tag to this chat room page. <meta http-equir=refresh content=2/> //refresh every 2 seconds. 5. Create another page and place chat room.aspx inside it using <iframe src=<file name>.>tag. This tag loads a page like a control in another page. <I frame src=Chat Room.aspx runat=server Id=l1 name= l1> </iframe> <br/> 6. Place text box and button so that user can add messages to the messages collection. Button1-click //add message { DEPT OF CSE & IT Page 52

.NET If(Application[Messages]==null) { List <string> obj=new List <string> ( ); Obj.Add (TextBox2.Text); Application [Messages]=obj; } Else { List <string> obj=(List <string>)Application [Messages]; Obj.Add(TextBox2.Text); Response.Write (Message Added); Application [Messages]= obj; } Text Box2.Text= ; } Modify the same chat program with a login page where user enters chat login name and sends messages to the people who are already log on means show logged in users list also. The above page needs to be ajaxified so use update panels and try to put users li8st and messages in single page to avoid post back presentation. Forums , message boards, chatting all logics start here. Cookieless Sessions: By default session uses cookies to transfer session id between request and response. As cookies are based on browsers we want session handling independent of cookies. To do this we can use session state tag and set cookieless to sessions (or) work based on auto detect functionality. Ex : <session state cookieless=true/> <auto detect> means use Cookies if supported otherwise use browser url. Sessions in process and out process: By default asp.net sessions are created inside application process. Which are also reffered as in process sessions. If we want to perform any load balancing using other services then asp.net provides two options for out process management. Which means we can create sessions independent and also outside application process. The two supported options for this are: 1. Asp.Net state service 2. Data base (only server) Question : Sessions with Asp.Net state service? Answer: When we install .Net frame work which is required to run asp.net apps automatically one windows service called Aspnet-state will be added with some default port number.(refer help) To implement sessions with state service we have to start this service from services of o.s and then use session state tag to specify out process service based sessions. <session state mode=state server [state Connection string=/92.168.100.1:32324]> </session state> Advantages: 1. Performance can be improved.(based on load). 2. Application independent a restart or crash still saves sessions and their data. Dis advantages: 1. Additional cost in implementing/maintaining server.

DEPT OF CSE & IT

Page 53

.NET 2. Complex objects again should undergo serialization/deserialization because they have to travel on wire.(always recommended use simple types or minimize complex types). 3. Not suitable for low traffic site. Out Process with Data Base: 1. Goto sql server and run Install sql state, sql file. This file creates automatically all tables, procedures required for maintaining sessions inside data base. 2. Go to project and set session state tag reffering to sql server this time <session state mode= SQL Server Sql Connection String=data source=.> </session state> Advantages: Load balancing- good performance out process. Security is additional because of data base. Application independent. Tracing of data from tables can be done. Dis advantages: Only sql server Additional cost-for servers Complex data needs serialized/deserialized. ASP.NET CACHING: Question: What is Cache? Answer: Cache is a memory which is called as programmed memory area. Applications cache lot of content to avoid repeated processing always caching will provide processed result which is stired, because we are avoiding process we get good performance. This performance can effect the integrity of application. As a developer whenever we implement caching we must ensure the integrity is not violated. Which is the main task of cache implementation. Asp.Net provides lot of caching options especially caching services (Asp.Net 4.0 also called velocity). To improve the performance of application. Asp.Net caching provides applications scope means anything we cache is for all users of application. Any how in some places we can externally configure to use client side and page specific, user specific caching. Following is the support provided by Asp.Net for caching. i. Page output caching. ii. Data caching. iii. Fragment caching iv. Service method caching and others like data source caching, caching with external applications. Page output caching: In this type of caching we are going to cache the processed results of page. This caching will be based on time, means the processed result will be cached for the given time and caching continous once we assign in to page. For understanding page output caching and some other concepts like master pages, themes etc we must be aware of Asp.Net page life cycles. Page life cucle refers to 2 important activities. 1. Total page handling flow at server, and 2. The events associated with this flow. DEPT OF CSE & IT Page 54

.NET Further Request The request direct went to add.aspx complied copy and done. Complied Forms Performance in Asp.net Cached Request: (Explicitly done by developer) The Result in Result Question: How to implement page output caching? Answer: Using <% @ Output cache..> directive** Many attributes are supported some important and mandatory are Duration =<n> Vary By Param= <parameters> n no of seconds Demo Label (current system time) Button In Button code. Label1.Text=Date Time.Now.To Long Time String duration in seconds. In Source <% @ output cache Duration= 60 Vary By Param =none %> These are compulsory attributes. Eamcet results we can cache? No caching. Vary By Param=<Parameters[s]> Using this attribute we can cache multiple copies of same page based on one or more parameters. The other Vary By options can also be used in order to Vary By Browser external controls and http headers. Just specify Vary By Param equal to parameter name which can be a control name or a query string value. Vary By Control = <user defined control> If any user defined control is used and its properties or behavior is modified then a separate copy based on user defined control will be prepared. Vary By Custom = <custom values> Page output caching even supports some customized values like browser which means when a different browser is requesting cached page then it will process and store a separate copy for that browser . Vary By Header = <header name> Using this attribute we can create separate outputs based on http headers which browsers prepare while requesting a resource like version type of browser supported types etc. for headers we can help or traffic tools like fiddler which will show the transporting headers. Data Caching: In Data Caching we provide application level variables for users, which is not related to any page and controls. In Data Caching we processed set of statements and store the result in data cached variable (same like application variables). Application variables have lot of issues/draw backs to consume them ?* Resolved by caching **. External features which are required for app are not provided by Application or other objects? Cache provides them Draw backs of application variables: DEPT OF CSE & IT Page 55

.NET They are sharable and could lead to inconsistency with a simultaneous access. Solution: Application.Lock( ) and Application.Unlock( ) are 2 methods which resolved this issue. Lock( ) locks application state which includes all app variables and takes other requests in a queue. Application.Lock( ); Application [a]=(int) Application[a]+10; Application.UnLock( ); Lock should be specified by the user and unlock also by user.(time gap can be more.when not locked what happens?....) Lock( ) Locks all variables if a is consumed then b also cannot be accessed same queue for b. Performance will effect heavily Variables are lost only when application is closed never they are closed implicitly. (otherwise we can manually remove them using Application.Remove(.) ) Question: How Cache variables resolve this issue? Answer: Self or implicitly locked variables means user cannot lock variables. Locks specific instead of all-leads to good performance. When memory is required it removes the cache content for new data.(only on requirement basis) Additional feature o Time based Expiry o Dependency based expiry

DEPT OF CSE & IT

Page 56

Potrebbero piacerti anche