ASP.NET – Managing State

ASP.NET – Managing State ”; Previous Next Hyper Text Transfer Protocol (HTTP) is a stateless protocol. When the client disconnects from the server, the ASP.NET engine discards the page objects. This way, each web application can scale up to serve numerous requests simultaneously without running out of server memory. However, there needs to be some technique to store the information between requests and to retrieve it when required. This information i.e., the current value of all the controls and variables for the current user in the current session is called the State. ASP.NET manages four types of states: View State Control State Session State Application State View State The view state is the state of the page and all its controls. It is automatically maintained across posts by the ASP.NET framework. When a page is sent back to the client, the changes in the properties of the page and its controls are determined, and stored in the value of a hidden input field named _VIEWSTATE. When the page is again posted back, the _VIEWSTATE field is sent to the server with the HTTP request. The view state could be enabled or disabled for: The entire application by setting the EnableViewState property in the <pages> section of web.config file. A page by setting the EnableViewState attribute of the Page directive, as <%@ Page Language=”C#” EnableViewState=”false” %> A control by setting the Control.EnableViewState property. It is implemented using a view state object defined by the StateBag class which defines a collection of view state items. The state bag is a data structure containing attribute value pairs, stored as strings associated with objects. The StateBag class has the following properties: Properties Description Item(name) The value of the view state item with the specified name. This is the default property of the StateBag class. Count The number of items in the view state collection. Keys Collection of keys for all the items in the collection. Values Collection of values for all the items in the collection. The StateBag class has the following methods: Methods Description Add(name, value) Adds an item to the view state collection and existing item is updated. Clear Removes all the items from the collection. Equals(Object) Determines whether the specified object is equal to the current object. Finalize Allows it to free resources and perform other cleanup operations. GetEnumerator Returns an enumerator that iterates over all the key/value pairs of the StateItem objects stored in the StateBag object. GetType Gets the type of the current instance. IsItemDirty Checks a StateItem object stored in the StateBag object to evaluate whether it has been modified. Remove(name) Removes the specified item. SetDirty Sets the state of the StateBag object as well as the Dirty property of each of the StateItem objects contained by it. SetItemDirty Sets the Dirty property for the specified StateItem object in the StateBag object. ToString Returns a string representing the state bag object. Example The following example demonstrates the concept of storing view state. Let us keep a counter, which is incremented each time the page is posted back by clicking a button on the page. A label control shows the value in the counter. The markup file code is as follows: <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”statedemo._Default” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title> Untitled Page </title> </head> <body> <form id=”form1″ runat=”server”> <div> <h3>View State demo</h3> Page Counter: <asp:Label ID=”lblCounter” runat=”server” /> <asp:Button ID=”btnIncrement” runat=”server” Text=”Add Count” onclick=”btnIncrement_Click” /> </div> </form> </body> </html> The code behind file for the example is shown here: public partial class _Default : System.Web.UI.Page { public int counter { get { if (ViewState[“pcounter”] != null) { return ((int)ViewState[“pcounter”]); } else { return 0; } } set { ViewState[“pcounter”] = value; } } protected void Page_Load(object sender, EventArgs e) { lblCounter.Text = counter.ToString(); counter++; } } It would produce the following result: Control State Control state cannot be modified, accessed directly, or disabled. Session State When a user connects to an ASP.NET website, a new session object is created. When session state is turned on, a new session state object is created for each new request. This session state object becomes part of the context and it is available through the page. Session state is generally used for storing application data such as inventory, supplier list, customer record, or shopping cart. It can also keep information about the user and his preferences, and keep the track of pending operations. Sessions are identified and tracked with a 120-bit SessionID, which is passed from client to server and back as cookie or a modified URL. The SessionID is globally unique and random. The session state object is created from the HttpSessionState class, which defines a collection of session state items. The HttpSessionState class has the following properties: Properties Description SessionID The unique session identifier. Item(name) The value of the session state item with the specified name. This is the default property of the HttpSessionState class. Count The number of items in the session state collection. TimeOut Gets and sets the amount of time, in minutes, allowed between requests before the session-state provider terminates the session. The HttpSessionState class has the following methods: Methods Description Add(name, value) Adds an item to the session state collection. Clear Removes all the items from session state collection. Remove(name) Removes the specified item from the session state collection. RemoveAll Removes all keys and values from the session-state collection. RemoveAt Deletes an item at a specified index from the session-state collection. The session state object is a name-value pair to store and retrieve some information from the session state object. You could use the following code for the same: void StoreSessionInfo() { String fromuser = TextBox1.Text; Session[“fromuser”] = fromuser; } void RetrieveSessionInfo() { String fromuser = Session[“fromuser”]; Label1.Text = fromuser; } The above code stores only strings in the Session dictionary object, however, it can store all the primitive data types and arrays composed of primitive data types, as well as

ASP.NET – Discussion

Discuss ASP.NET ”; Previous Next ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic web sites. It allows you to use a full featured programming language such as C# or VB.NET to build web applications easily. This tutorial covers all the basic elements of ASP.NET that a beginner would require to get started. Print Page Previous Next Advertisements ”;

ASP.NET – Quick Guide

ASP.NET – Quick Guide ”; Previous Next ASP.NET – Introduction What is ASP.NET? ASP.NET is a web development platform, which provides a programming model, a comprehensive software infrastructure and various services required to build up robust web applications for PC, as well as mobile devices. ASP.NET works on top of the HTTP protocol, and uses the HTTP commands and policies to set a browser-to-server bilateral communication and cooperation. ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled codes, written using the extensible and reusable components or objects present in .Net framework. These codes can use the entire hierarchy of classes in .Net framework. The ASP.NET application codes can be written in any of the following languages: C# Visual Basic.Net Jscript J# ASP.NET is used to produce interactive, data-driven web applications over the internet. It consists of a large number of controls such as text boxes, buttons, and labels for assembling, configuring, and manipulating code to create HTML pages. ASP.NET Web Forms Model ASP.NET web forms extend the event-driven model of interaction to the web applications. The browser submits a web form to the web server and the server returns a full markup page or HTML page in response. All client side user activities are forwarded to the server for stateful processing. The server processes the output of the client actions and triggers the reactions. Now, HTTP is a stateless protocol. ASP.NET framework helps in storing the information regarding the state of the application, which consists of: Page state Session state The page state is the state of the client, i.e., the content of various input fields in the web form. The session state is the collective information obtained from various pages the user visited and worked with, i.e., the overall session state. To clear the concept, let us take an example of a shopping cart. User adds items to a shopping cart. Items are selected from a page, say the items page, and the total collected items and price are shown on a different page, say the cart page. Only HTTP cannot keep track of all the information coming from various pages. ASP.NET session state and server side infrastructure keeps track of the information collected globally over a session. The ASP.NET runtime carries the page state to and from the server across page requests while generating ASP.NET runtime codes, and incorporates the state of the server side components in hidden fields. This way, the server becomes aware of the overall application state and operates in a two-tiered connected way. The ASP.NET Component Model The ASP.NET component model provides various building blocks of ASP.NET pages. Basically it is an object model, which describes: Server side counterparts of almost all HTML elements or tags, such as <form> and <input>. Server controls, which help in developing complex user-interface. For example, the Calendar control or the Gridview control. ASP.NET is a technology, which works on the .Net framework that contains all web-related functionalities. The .Net framework is made of an object-oriented hierarchy. An ASP.NET web application is made of pages. When a user requests an ASP.NET page, the IIS delegates the processing of the page to the ASP.NET runtime system. The ASP.NET runtime transforms the .aspx page into an instance of a class, which inherits from the base class page of the .Net framework. Therefore, each ASP.NET page is an object and all its components i.e., the server-side controls are also objects. Components of .Net Framework 3.5 Before going to the next session on Visual Studio.Net, let us go through at the various components of the .Net framework 3.5. The following table describes the components of the .Net framework 3.5 and the job they perform: Components and their Description (1) Common Language Runtime or CLR It performs memory management, exception handling, debugging, security checking, thread execution, code execution, code safety, verification, and compilation. The code that is directly managed by the CLR is called the managed code. When the managed code is compiled, the compiler converts the source code into a CPU independent intermediate language (IL) code. A Just In Time(JIT) compiler compiles the IL code into native code, which is CPU specific. (2) .Net Framework Class Library It contains a huge library of reusable types. classes, interfaces, structures, and enumerated values, which are collectively called types. (3) Common Language Specification It contains the specifications for the .Net supported languages and implementation of language integration. (4) Common Type System It provides guidelines for declaring, using, and managing types at runtime, and cross-language communication. (5) Metadata and Assemblies Metadata is the binary information describing the program, which is either stored in a portable executable file (PE) or in the memory. Assembly is a logical unit consisting of the assembly manifest, type metadata, IL code, and a set of resources like image files. (6) Windows Forms Windows Forms contain the graphical representation of any window displayed in the application. (7) ASP.NET and ASP.NET AJAX ASP.NET is the web development model and AJAX is an extension of ASP.NET for developing and implementing AJAX functionality. ASP.NET AJAX contains the components that allow the developer to update data on a website without a complete reload of the page. (8) ADO.NET It is the technology used for working with data and databases. It provides access to data sources like SQL server, OLE DB, XML etc. The ADO.NET allows connection to data sources for retrieving, manipulating, and updating data. (9) Windows Workflow Foundation (WF) It helps in building workflow-based applications in Windows. It contains activities, workflow runtime, workflow designer, and a rules engine. (10)Windows Presentation Foundation It provides a separation between the user interface and the business logic. It helps in developing visually stunning interfaces using documents, media, two and three dimensional graphics, animations, and more. (11) Windows Communication Foundation (WCF) It is the technology used for building and executing connected systems. (12) Windows CardSpace It provides safety for accessing resources and sharing personal information on the internet. (13) LINQ It imparts data querying

ASP.NET – Useful Resources

ASP.NET – Useful Resources ”; Previous Next The following resources contain additional information on ASP.NET. Please use them to get more in-depth knowledge on this topic. Useful Video Courses ASP.NET Online Training 52 Lectures 5.5 hours Tutorialspoint More Detail Advanced ASP.NET Core 3.1 MVC 141 Lectures 9 hours Bhrugen Patel More Detail Learn ASP.Net MVC and Entity Framework (Database First) Most Popular 20 Lectures 5 hours Trevoir Williams More Detail Full-Stack Web Development using Angular 10, Web API & SQL Server 33 Lectures 1.5 hours Vinay Kumar More Detail ASP.Net Core MVC Training Course 53 Lectures 3 hours Skillbakery More Detail Create Chatbots using Dialogflow v1& deploy on GCloud 29 Lectures 3 hours Nilay Mehta More Detail Print Page Previous Next Advertisements ”;

ASP.NET – LINQ

ASP.NET – LINQ ”; Previous Next Most applications are data-centric, however most of the data repositories are relational databases. Over the years, designers and developers have designed applications based on object models. The objects are responsible for connecting to the data access components – called the Data Access Layer (DAL). Here we have three points to consider: All the data needed in an application are not stored in the same source. The source could be a relation database, some business object, XML file, or a web service. Accessing in-memory object is simpler and less expensive than accessing data from a database or XML file. The data accessed are not used directly, but needs to be sorted, ordered, grouped, altered etc. Hence if there is one tool that makes all kind of data access easy that allows joining data from such disparate data sources and perform standard data processing operations, in few lines of codes, it would be of great help. LINQ or Language-Integrated Query is such a tool. LINQ is set of extensions to the .Net Framework 3.5 and its managed languages that set the query as an object. It defines a common syntax and a programming model to query different types of data using a common language. The relational operators like Select, Project, Join, Group, Partition, Set operations etc., are implemented in LINQ and the C# and VB compilers in the .Net framework 3.5, which support the LINQ syntax makes it possible to work with a configured data store without resorting to ADO.NET. For example, querying the Customers table in the Northwind database, using LINQ query in C#, the code would be: var data = from c in dataContext.Customers where c.Country == “Spain” select c; Where: The ”from” keyword logically loops through the contents of the collection. The expression with the ”where” keyword is evaluated for each object in the collection. The ”select” statement selects the evaluated object to add to the list being returned. The ”var” keyword is for variable declaration. Since the exact type of the returned object is not known, it indicates that the information will be inferred dynamically. LINQ query can be applied to any data-bearing class that inherits from IEnumerable<T>, here T is any data type, for example, List<Book>. Let us look at an example to understand the concept. The example uses the following class: Books.cs public class Books { public string ID {get; set;} public string Title { get; set; } public decimal Price { get; set; } public DateTime DateOfRelease { get; set; } public static List<Books> GetBooks() { List<Books> list = new List<Books>(); list.Add(new Books { ID = “001”, Title = “Programming in C#”, Price = 634.76m, DateOfRelease = Convert.ToDateTime(“2010-02-05”) }); list.Add(new Books { ID = “002”, Title = “Learn Java in 30 days”, Price = 250.76m, DateOfRelease = Convert.ToDateTime(“2011-08-15”) }); list.Add(new Books { ID = “003”, Title = “Programming in ASP.Net 4.0”, Price = 700.00m, DateOfRelease = Convert.ToDateTime(“2011-02-05”) }); list.Add(new Books { ID = “004”, Title = “VB.Net Made Easy”, Price = 500.99m, DateOfRelease = Convert.ToDateTime(“2011-12-31”) }); list.Add(new Books { ID = “005”, Title = “Programming in C”, Price = 314.76m, DateOfRelease = Convert.ToDateTime(“2010-02-05”) }); list.Add(new Books { ID = “006”, Title = “Programming in C++”, Price = 456.76m, DateOfRelease = Convert.ToDateTime(“2010-02-05”) }); list.Add(new Books { ID = “007”, Title = “Datebase Developement”, Price = 1000.76m, DateOfRelease = Convert.ToDateTime(“2010-02-05”) }); return list; } } The web page using this class has a simple label control, which displays the titles of the books. The Page_Load event creates a list of books and returns the titles by using LINQ query: public partial class simplequery : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { List<Books> books = Books.GetBooks(); var booktitles = from b in books select b.Title; foreach (var title in booktitles) lblbooks.Text += String.Format(“{0} <br />”, title); } } When the page is executed, the label displays the results of the query: The above LINQ expression: var booktitles = from b in books select b.Title; Is equivalent to the following SQL query: SELECT Title from Books LINQ Operators Apart from the operators used so far, there are several other operators, which implement all query clauses. Let us look at some of the operators and clauses. The Join clause The ”join clause” in SQL is used for joining two data tables and displays a data set containing columns from both the tables. LINQ is also capable of that. To check this, add another class named Saledetails.cs in the previous project: public class Salesdetails { public int sales { get; set; } public int pages { get; set; } public string ID {get; set;} public static IEnumerable<Salesdetails> getsalesdetails() { Salesdetails[] sd = { new Salesdetails { ID = “001”, pages=678, sales = 110000}, new Salesdetails { ID = “002”, pages=789, sales = 60000}, new Salesdetails { ID = “003”, pages=456, sales = 40000}, new Salesdetails { ID = “004”, pages=900, sales = 80000}, new Salesdetails { ID = “005”, pages=456, sales = 90000}, new Salesdetails { ID = “006”, pages=870, sales = 50000}, new Salesdetails { ID = “007”, pages=675, sales = 40000}, }; return sd.OfType<Salesdetails>(); } } Add the codes in the Page_Load event handler to query on both the tables using the join clause: protected void Page_Load(object sender, EventArgs e) { IEnumerable<Books> books = Books.GetBooks(); IEnumerable<Salesdetails> sales = Salesdetails.getsalesdetails(); var booktitles = from b in books join s in sales on b.ID equals s.ID select new { Name = b.Title, Pages = s.pages }; foreach (var title in booktitles) lblbooks.Text += String.Format(“{0} <br />”, title); } The resulting page is as shown: The Where clause The ”where clause” allows adding some conditional filters to the query. For example, if you want to see the books, where the number of pages are more than 500, change the Page_Load event handler to: var booktitles = from b in books join s in sales on b.ID equals s.ID where s.pages > 500 select new { Name = b.Title, Pages =

ASP.NET – Multi Threading

ASP.NET – Multi Threading ”; Previous Next A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your application involves complicated and time consuming operations such as database access or some intense I/O operations, then it is often helpful to set different execution paths or threads, with each thread performing a particular job. Threads are lightweight processes. One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increases efficiency of an application. So far we compiled programs where a single thread runs as a single process which is the running instance of the application. However, this way the application can perform one job at a time. To make it execute multiple tasks at a time, it could be divided into smaller threads. In .Net, the threading is handled through the ”System.Threading” namespace. Creating a variable of the System.Threading.Thread type allows you to create a new thread to start working with. It allows you to create and access individual threads in a program. Creating Thread A thread is created by creating a Thread object, giving its constructor a ThreadStart reference. ThreadStart childthreat = new ThreadStart(childthreadcall); Thread Life Cycle The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution. Following are the various states in the life cycle of a thread: The Unstarted State : It is the situation when the instance of the thread is created but the Start method is not called. The Ready State : It is the situation when the thread is ready to execute and waiting CPU cycle. The Not Runnable State : a thread is not runnable, when: Sleep method has been called Wait method has been called Blocked by I/O operations The Dead State : It is the situation when the thread has completed execution or has been aborted. Thread Priority The Priority property of the Thread class specifies the priority of one thread with respect to other. The .Net runtime selects the ready thread with the highest priority. The priorities could be categorized as: Above normal Below normal Highest Lowest Normal Once a thread is created, its priority is set using the Priority property of the thread class. NewThread.Priority = ThreadPriority.Highest; Thread Properties & Methods The Thread class has the following important properties: Property Description CurrentContext Gets the current context in which the thread is executing. CurrentCulture Gets or sets the culture for the current thread. CurrentPrinciple Gets or sets the thread”s current principal for role-based security. CurrentThread Gets the currently running thread. CurrentUICulture Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time. ExecutionContext Gets an ExecutionContext object that contains information about the various contexts of the current thread. IsAlive Gets a value indicating the execution status of the current thread. IsBackground Gets or sets a value indicating whether or not a thread is a background thread. IsThreadPoolThread Gets a value indicating whether or not a thread belongs to the managed thread pool. ManagedThreadId Gets a unique identifier for the current managed thread. Name Gets or sets the name of the thread. Priority Gets or sets a value indicating the scheduling priority of a thread. ThreadState Gets a value containing the states of the current thread. The Thread class has the following important methods: Methods Description Abort Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread. AllocateDataSlot Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. AllocateNamedDataSlot Allocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. BeginCriticalRegion Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might endanger other tasks in the application domain. BeginThreadAffinity Notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread. EndCriticalRegion Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task. EndThreadAffinity Notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread. FreeNamedDataSlot Eliminates the association between a name and a slot, for all threads in the process. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. GetData Retrieves the value from the specified slot on the current thread, within the current thread”s current domain. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. GetDomain Returns the current domain in which the current thread is running. GetDomainID Returns a unique application domain identifier. GetNamedDataSlot Looks up a named data slot. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. Interrupt Interrupts a thread that is in the WaitSleepJoin thread state. Join Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping. This method has different overloaded forms. MemoryBarrier Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier. ResetAbort Cancels an Abort requested for the current thread. SetData Sets the data in the specified slot on the currently running thread, for that thread”s current domain. For better performance, use fields marked with the ThreadStaticAttribute attribute instead. Start Starts a thread. Sleep Makes the thread pause for a period of time. SpinWait Causes a thread to wait

ASP.NET – Data Caching

ASP.NET – Data Caching ”; Previous Next What is Caching? Caching is a technique of storing frequently used data/information in memory, so that, when the same data/information is needed next time, it could be directly retrieved from the memory instead of being generated by the application. Caching is extremely important for performance boosting in ASP.NET, as the pages and controls are dynamically generated here. It is especially important for data related transactions, as these are expensive in terms of response time. Caching places frequently used data in quickly accessed media such as the random access memory of the computer. The ASP.NET runtime includes a key-value map of CLR objects called cache. This resides with the application and is available via the HttpContext and System.Web.UI.Page. In some respect, caching is similar to storing the state objects. However, the storing information in state objects is deterministic, i.e., you can count on the data being stored there, and caching of data is nondeterministic. The data will not be available in the following cases: If its lifetime expires, If the application releases its memory, If caching does not take place for some reason. You can access items in the cache using an indexer and may control the lifetime of objects in the cache and set up links between the cached objects and their physical sources. Caching in ASP.Net ASP.NET provides the following different types of caching: Output Caching : Output cache stores a copy of the finally rendered HTML pages or part of pages sent to the client. When the next client requests for this page, instead of regenerating the page, a cached copy of the page is sent, thus saving time. Data Caching : Data caching means caching data from a data source. As long as the cache is not expired, a request for the data will be fulfilled from the cache. When the cache is expired, fresh data is obtained by the data source and the cache is refilled. Object Caching : Object caching is caching the objects on a page, such as data-bound controls. The cached data is stored in server memory. Class Caching : Web pages or web services are compiled into a page class in the assembly, when run for the first time. Then the assembly is cached in the server. Next time when a request is made for the page or service, the cached assembly is referred to. When the source code is changed, the CLR recompiles the assembly. Configuration Caching : Application wide configuration information is stored in a configuration file. Configuration caching stores the configuration information in the server memory. In this tutorial, we will consider output caching, data caching, and object caching. Output Caching Rendering a page may involve some complex processes such as, database access, rendering complex controls etc. Output caching allows bypassing the round trips to server by caching data in memory. Even the whole page could be cached. The OutputCache directive is responsible of output caching. It enables output caching and provides certain control over its behaviour. Syntax for OutputCache directive: <%@ OutputCache Duration=”15″ VaryByParam=”None” %> Put this directive under the page directive. This tells the environment to cache the page for 15 seconds. The following event handler for page load would help in testing that the page was really cached. protected void Page_Load(object sender, EventArgs e) { Thread.Sleep(10000); Response.Write(“This page was generated and cache at:” + DateTime.Now.ToString()); } The Thread.Sleep() method stops the process thread for the specified time. In this example, the thread is stopped for 10 seconds, so when the page is loaded for first time, it takes 10 seconds. However, next time you refresh the page it does not take any time, as the page is retrieved from the cache without being loaded. The OutputCache directive has the following attributes, which helps in controlling the behaviour of the output cache: Attribute Values Description DiskCacheable true/false Specifies that output could be written to a disk based cache. NoStore true/false Specifies that the “no store” cache control header is sent or not. CacheProfile String name Name of a cache profile as to be stored in web.config. VaryByParam None * Param- name Semicolon delimited list of string specifies query string values in a GET request or variable in a POST request. VaryByHeader * Header names Semicolon delimited list of strings specifies headers that might be submitted by a client. VaryByCustom Browser Custom string Tells ASP.NET to vary the output cache by browser name and version or by a custom string. Location Any Client Downstream Server None Any: page may be cached anywhere. Client: cached content remains at browser. Downstream: cached content stored in downstream and server both. Server: cached content saved only on server. None: disables caching. Duration Number Number of seconds the page or control is cached. Let us add a text box and a button to the previous example and add this event handler for the button. protected void btnmagic_Click(object sender, EventArgs e) { Response.Write(“<br><br>”); Response.Write(“<h2> Hello, ” + this.txtname.Text + “</h2>”); } Change the OutputCache directive: <%@ OutputCache Duration=”60″ VaryByParam=”txtname” %> When the program is executed, ASP.NET caches the page on the basis of the name in the text box. Data Caching The main aspect of data caching is caching the data source controls. We have already discussed that the data source controls represent data in a data source, like a database or an XML file. These controls derive from the abstract class DataSourceControl and have the following inherited properties for implementing caching: CacheDuration – It sets the number of seconds for which the data source will cache data. CacheExpirationPolicy – It defines the cache behavior when the data in cache has expired. CacheKeyDependency – It identifies a key for the controls that auto-expires the content of its cache when removed. EnableCaching – It specifies whether or not to cache the data. Example To demonstrate data caching, create a new website and add a new web form on it. Add a SqlDataSource control with

ASP.NET – Web Services

ASP.NET – Web Services ”; Previous Next A web service is a web-based functionality accessed using the protocols of the web to be used by the web applications. There are three aspects of web service development: Creating the web service Creating a proxy Consuming the web service Creating a Web Service A web service is a web application which is basically a class consisting of methods that could be used by other applications. It also follows a code-behind architecture such as the ASP.NET web pages, although it does not have a user interface. To understand the concept let us create a web service to provide stock price information. The clients can query about the name and price of a stock based on the stock symbol. To keep this example simple, the values are hardcoded in a two-dimensional array. This web service has three methods: A default HelloWorld method A GetName Method A GetPrice Method Take the following steps to create the web service: Step (1) : Select File -> New -> Web Site in Visual Studio, and then select ASP.NET Web Service. Step (2) : A web service file called Service.asmx and its code behind file, Service.cs is created in the App_Code directory of the project. Step (3) : Change the names of the files to StockService.asmx and StockService.cs. Step (4) : The .asmx file has simply a WebService directive on it: <%@ WebService Language=”C#” CodeBehind=”~/App_Code/StockService.cs” Class=”StockService” %> Step (5) : Open the StockService.cs file, the code generated in it is the basic Hello World service. The default web service code behind file looks like the following: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; namespace StockService { // <summary> // Summary description for Service1 // <summary> [WebService(Namespace = “http://tempuri.org/”)] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] // To allow this Web Service to be called from script, // using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class Service1 : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return “Hello World”; } } } Step (6) : Change the code behind file to add the two dimensional array of strings for stock symbol, name and price and two web methods for getting the stock information. using System; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; [WebService(Namespace = “http://tempuri.org/”)] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // To allow this Web Service to be called from script, // using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class StockService : System.Web.Services.WebService { public StockService () { //Uncomment the following if using designed components //InitializeComponent(); } string[,] stocks = { {“RELIND”, “Reliance Industries”, “1060.15”}, {“ICICI”, “ICICI Bank”, “911.55”}, {“JSW”, “JSW Steel”, “1201.25”}, {“WIPRO”, “Wipro Limited”, “1194.65”}, {“SATYAM”, “Satyam Computers”, “91.10”} }; [WebMethod] public string HelloWorld() { return “Hello World”; } [WebMethod] public double GetPrice(string symbol) { //it takes the symbol as parameter and returns price for (int i = 0; i < stocks.GetLength(0); i++) { if (String.Compare(symbol, stocks[i, 0], true) == 0) return Convert.ToDouble(stocks[i, 2]); } return 0; } [WebMethod] public string GetName(string symbol) { // It takes the symbol as parameter and // returns name of the stock for (int i = 0; i < stocks.GetLength(0); i++) { if (String.Compare(symbol, stocks[i, 0], true) == 0) return stocks[i, 1]; } return “Stock Not Found”; } } Step (7) : Running the web service application gives a web service test page, which allows testing the service methods. Step (8) : Click on a method name, and check whether it runs properly. Step (9) : For testing the GetName method, provide one of the stock symbols, which are hard coded, it returns the name of the stock Consuming the Web Service For using the web service, create a web site under the same solution. This could be done by right clicking on the Solution name in the Solution Explorer. The web page calling the web service should have a label control to display the returned results and two button controls one for post back and another for calling the service. The content file for the web application is as follows: <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”wsclient._Default” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title> Untitled Page </title> </head> <body> <form id=”form1″ runat=”server”> <div> <h3>Using the Stock Service</h3> <br /> <br /> <asp:Label ID=”lblmessage” runat=”server”></asp:Label> <br /> <br /> <asp:Button ID=”btnpostback” runat=”server” onclick=”Button1_Click” Text=”Post Back” style=”width:132px” />     <asp:Button ID=”btnservice” runat=”server” onclick=”btnservice_Click” Text=”Get Stock” style=”width:99px” /> </div> </form> </body> </html> The code behind file for the web application is as follows: using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; //this is the proxy using localhost; namespace wsclient { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { lblmessage.Text = “First Loading Time: ” + DateTime.Now.ToLongTimeString } else { lblmessage.Text = “PostBack at: ” + DateTime.Now.ToLongTimeString(); } } protected void btnservice_Click(object sender, EventArgs e) { StockService proxy = new StockService(); lblmessage.Text = String.Format(“Current SATYAM Price:{0}”, proxy.GetPrice(“SATYAM”).ToString()); } } } Creating the Proxy A proxy is a stand-in for the web service codes. Before using the web service, a proxy must be created. The proxy is registered with the client application. Then the client application makes the calls to the web service as it were using a local method. The proxy takes the calls, wraps it in proper format and sends it as a SOAP request to the server. SOAP stands for Simple Object Access Protocol. This protocol is used for exchanging web service data. When the server returns the SOAP package to the client, the proxy decodes everything and presents it to the client application. Before calling the web service using the btnservice_Click, a web reference should be added to the application. This creates a proxy class transparently, which is used by the btnservice_Click event. protected void btnservice_Click(object sender, EventArgs e) { StockService proxy

ASP.NET – Security

ASP.NET – Security ”; Previous Next Implementing security in a site has the following aspects: Authentication : It is the process of ensuring the user”s identity and authenticity. ASP.NET allows four types of authentications: Windows Authentication Forms Authentication Passport Authentication Custom Authentication Authorization : It is the process of defining and allotting specific roles to specific users. Confidentiality : It involves encrypting the channel between the client browser and the web server. Integrity : It involves maintaining the integrity of data. For example, implementing digital signature. Forms-Based Authentication Traditionally, forms-based authentication involves editing the web.config file and adding a login page with appropriate authentication code. The web.config file could be edited and the following codes written on it: <configuration> <system.web> <authentication mode=”Forms”> <forms loginUrl =”login.aspx”/> </authentication> <authorization> <deny users=”?”/> </authorization> </system.web> … … </configuration> The login.aspx page mentioned in the above code snippet could have the following code behind file with the usernames and passwords for authentication hard coded into it. protected bool authenticate(String uname, String pass) { if(uname == “Tom”) { if(pass == “tom123”) return true; } if(uname == “Dick”) { if(pass == “dick123”) return true; } if(uname == “Harry”) { if(pass == “har123”) return true; } return false; } public void OnLogin(Object src, EventArgs e) { if (authenticate(txtuser.Text, txtpwd.Text)) { FormsAuthentication.RedirectFromLoginPage(txtuser.Text, chkrem.Checked); } else { Response.Write(“Invalid user name or password”); } } Observe that the FormsAuthentication class is responsible for the process of authentication. However, Visual Studio allows you to implement user creation, authentication, and authorization with seamless ease without writing any code, through the Web Site Administration tool. This tool allows creating users and roles. Apart from this, ASP.NET comes with readymade login controls set, which has controls performing all the jobs for you. Implementing Forms-Based Security To set up forms-based authentication, you need the following: A database of users to support the authentication process A website that uses the database User accounts Roles Restriction of users and group activities A default page, to display the login status of the users and other information. A login page, to allow users to log in, retrieve password, or change password To create users, take the following steps: Step (1) : Choose Website -> ASP.NET Configuration to open the Web Application Administration Tool. Step (2) : Click on the Security tab. Step (3) : Select the authentication type to ”Forms based authentication” by selecting the ”From the Internet” radio button. Step (4) : Click on ”Create Users” link to create some users. If you already had created roles, you could assign roles to the user, right at this stage. Step (5) : Create a web site and add the following pages: Welcome.aspx Login.aspx CreateAccount.aspx PasswordRecovery.aspx ChangePassword.aspx Step (6) : Place a LoginStatus control on the Welcome.aspx from the login section of the toolbox. It has two templates: LoggedIn and LoggedOut. In LoggedOut template, there is a login link and in the LoggedIn template, there is a logout link on the control. You can change the login and logout text properties of the control from the Properties window. Step (7) : Place a LoginView control from the toolbox below the LoginStatus control. Here, you can put texts and other controls (hyperlinks, buttons etc.), which are displayed based on whether the user is logged in or not. This control has two view templates: Anonymous template and LoggedIn template. Select each view and write some text for the users to be displayed for each template. The text should be placed on the area marked red. Step (8) : The users for the application are created by the developer. You might want to allow a visitor to create a user account. For this, add a link beneath the LoginView control, which should link to the CreateAccount.aspx page. Step (9) : Place a CreateUserWizard control on the create account page. Set the ContinueDestinationPageUrl property of this control to Welcome.aspx. Step (10) : Create the Login page. Place a Login control on the page. The LoginStatus control automatically links to the Login.aspx. To change this default, make the following changes in the web.config file. For example, if you want to name your log in page as signup.aspx, add the following lines to the <authentication> section of the web.config: <configuration> <system.web> <authentication mode=”Forms”> <forms loginUrl =”signup.aspx” defaultUrl = “Welcome.aspx” /> </authentication> </system.web> </configuration> Step (11) : Users often forget passwords. The PasswordRecovery control helps the user gain access to the account. Select the Login control. Open its smart tag and click ”Convert to Template”. Customize the UI of the control to place a hyperlink control under the login button, which should link to the PassWordRecovery.aspx. Step (12) : Place a PasswordRecovery control on the password recovery page. This control needs an email server to send the passwords to the users. Step (13) : Create a link to the ChangePassword.aspx page in the LoggedIn template of the LoginView control in Welcome.aspx. Step (14) : Place a ChangePassword control on the change password page. This control also has two views. Now run the application and observe different security operations. To create roles, go back to the Web Application Administration Tools and click on the Security tab. Click on ”Create Roles” and create some roles for the application. Click on the ”Manage Users” link and assign roles to the users. IIS Authentication: SSL The Secure Socket Layer or SSL is the protocol used to ensure a secure connection. With SSL enabled, the browser encrypts all data sent to the server and decrypts all data coming from the server. At the same time, the server encrypts and decrypts all data to and from browser. The URL for a secure connection starts with HTTPS instead of HTTP. A small lock is displayed by a browser using a secure connection. When a browser makes an initial attempt to communicate with a server over a secure connection using SSL, the server authenticates itself by sending its digital certificate. To use the SSL, you need to buy a digital secure certificate

ASP.NET – Deployment

ASP.NET – Deployment ”; Previous Next There are two categories of ASP.NET deployment: Local deployment : In this case, the entire application is contained within a virtual directory and all the contents and assemblies are contained within it and available to the application. Global deployment : In this case, assemblies are available to every application running on the server. There are different techniques used for deployment, however, we will discuss the following most common and easiest ways of deployment: XCOPY deployment Copying a Website Creating a set up project XCOPY Deployment XCOPY deployment means making recursive copies of all the files to the target folder on the target machine. You can use any of the commonly used techniques: FTP transfer Using Server management tools that provide replication on a remote site MSI installer application XCOPY deployment simply copies the application file to the production server and sets a virtual directory there. You need to set a virtual directory using the Internet Information Manager Microsoft Management Console (MMC snap-in). Copying a Website The Copy Web Site option is available in Visual Studio. It is available from the Website -> Copy Web Site menu option. This menu item allows copying the current web site to another local or remote location. It is a sort of integrated FTP tool. Using this option, you connect to the target destination, select the desired copy mode: Overwrite Source to Target Files Sync UP Source And Target Projects Then proceed with copying the files physically. Unlike the XCOPY deployment, this process of deployment is done from Visual Studio environment. However, there are following problems with both the above deployment methods: You pass on your source code. There is no pre-compilation and related error checking for the files. The initial page load will be slow. Creating a Setup Project In this method, you use Windows Installer and package your web applications so it is ready to deploy on the production server. Visual Studio allows you to build deployment packages. Let us test this on one of our existing project, say the data binding project. Open the project and take the following steps: Step (1) : Select File -> Add -> New Project with the website root directory highlighted in the Solution Explorer. Step (2) : Select Setup and Deployment, under Other Project Types. Select Setup Wizard. Step (3) : Choosing the default location ensures that the set up project will be located in its own folder under the root directory of the site. Click on okay to get the first splash screen of the wizard. Step (4) : Choose a project type. Select ”Create a setup for a web application”. Step (5) : Next, the third screen asks to choose project outputs from all the projects in the solution. Check the check box next to ”Content Files from…” Step (6) : The fourth screen allows including other files like ReadMe. However, in our case there is no such file. Click on finish. Step (7) : The final screen displays a summary of settings for the set up project. Step (8) : The Set up project is added to the Solution Explorer and the main design window shows a file system editor. Step (9) : Next step is to build the setup project. Right click on the project name in the Solution Explorer and select Build. Step (10) : When build is completed, you get the following message in the Output window: Two files are created by the build process: Setup.exe Setup-databinding.msi You need to copy these files to the server. Double-click the setup file to install the content of the .msi file on the local machine. Print Page Previous Next Advertisements ”;