Sie sind auf Seite 1von 64

ASP.

NET

ASP.NET is a server-side technology for developing web applications based on the Microsoft .NET Framework. .ASP.NET is a server-side technology. That is, it runs on the web server. with ASP.NET, you can build Web applications that are displayed in any browser. ASP.NET lets you write the server-side code using your favorite programming languageor at least one the one you prefer from the long list of supported languages. The .NET Framework currently supports over 100 languages, and many of these may be used to build ASP.NET web sites. The most popular choices are C# (pronounced C sharp) and Visual Basic (or VB),

ASP.NET pages are compiled, not interpreted. ASP, pages were interpreted: every time a user requested a page, the server would read the pages code into memory, figure out how to execute the code, and execute it. In ASP.NET, the server need only figure out how to execute the code once. The code is compiled into efficient binary files, which can be run very quickly, again and again, without the overhead involved in rereading the page each time. This allows a big jump in performance, compared to the old days of ASP.

ASP.NET has full access to the functionality of the .NET Framework. Support for XML, web services, database interaction, email, regular expressions, and many other technologies are built right into .NET, which saves you from having to reinvent the wheel. ASP.NET allows you to separate the server-side code in your pages from the HTML layout. When youre working with a team composed of programmers and design specialists, this separation is a great help, as it lets programmers modify the server-side code without stepping on the designers carefully crafted HTMLand vice versa.

Steps to create web page in Visual Web Developer. 1.Start Visual Web Developer, and choose File > New Web Site (or hit the default keyboard shortcut, Shift+Alt+N). 2.Choose ASP.NET Web Site for the template and File System for the location type. This location type tells Visual Web Developer to create the project in a physical folder on your disk, and execute that project using the integrated web server. 3.Choose the language in which you prefer to code your pages. Although ASP.NET allows you to code different pages inside a project in different languages, for the sake of simplicity well generally assume you work with a single language. 4.If you chose C# for the language, type path for the folder location where you want to store the files for this exercise. 5.After clicking OK, Visual Web Developer will create the project with a basic structure. Your project

contains an empty App_Data folder, a basic Default.aspx file, and a basic configuration file, Web.config

What is IIS ? IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is used to host your ASP.NET Web application. IIS has it's own ASP.NET Process Engine to handle the ASP.NET request. So, when a request comes from client to server, IIS takes that request and process it and send response back to clients.

Worker Process: Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system. All the ASP.Net functionality runs under the scope of worker process. When a request comes to the server from a client worker process is responsible to generate the request and response. In a single word we can say worker process is the heart of ASP.NET Web Application which runs on IIS. Application Pool: Application pool is the container of worker process. Application pools is used to separate sets of IIS worker processes that share the same configuration. Application pools enables a better security, reliability, and availability for any web application. The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn't not impact other web application as they they are configured into different application pools. Application Pool with multiple worker process is called Web Garden.

Life cycle of ASP. Net in IIS

Stage 1: User requests an application resource from the Web server. The life cycle of an ASP.NET application starts with a request sent by a browser to the Web server (for ASP.NET applications, typically IIS). ASP.NET is an ISAPI extension under the Web server. When a Web server receives a request, it examines the file-name extension of the requested file, determines which ISAPI extension should handle the request, and then passes the request to the appropriate ISAPI extension. ASP.NET handles file name extensions that have been mapped to it, such as .aspx, .ascx, .ashx, and .asmx. Note: ASP.NET will not perform authentication or authorization checks on requests for .htm files. If the file-name extension of the requested resource type is not explicitly mapped to ASP.NET, ASP.NET functionality is not invoked for the request because the request is not processed by the ASP.NET runtime Stage 2: ASP.NET receives the first request for the application. When ASP.NET receives the first request for any resource in an application, a class named ApplicationManager creates an application domain. Application domains provide isolation between applications for global variables and allow each application to be unloaded separately. Within an application domain, an instance of the class named HostingEnvironment is created, which provides access to information about the application such as the name of the folder where the application is stored.

Stage 3:ASP.NET core objects are created for each request. After the application domain has been created and the HostingEnvironment object instantiated, ASP.NET creates and initializes core objects such as HttpContext, HttpRequest, and HttpResponse. The HttpContext class contains objects that are specific to the current application request, such as the HttpRequest and HttpResponse objects. The HttpRequest object contains information about the current request, including cookies and browser information. The HttpResponse object contains the response that is sent to the client, including all rendered output and cookies. Stage 4 :An HttpApplication object is assigned to the request After all core application objects have been initialized, the application is started by creating an instance of the HttpApplication class. If the application has a Global.asax file, ASP.NET instead creates an instance of the Global.asax class that is derived from the HttpApplication class and uses the derived class to represent the application.

Stage 5 :The request is processed by the HttpApplication pipeline.

Events are executed by the HttpApplication class while the request is processed.

Integration of above points Step 1:- The user sends a request to IIS. IIS first checks which ISAPI extension can serve this request. Depending on file extension the request is processed. For instance if the page is an .ASPX page then it will be passed to aspnet_isapi.dll for processing. Step 2:- If this the first request to the website then a class called as ApplicationManager creates an application domain where the website can run. As we all know application domain creates isolation between two web applications hosted on the same IIS. So in case there is issue in one app domain it does not affect the other app domain. Step 3:- The newly created application domain creates hosting environment i.e. the HttpRuntime object. Once the hosting environment is created necessary core ASP.NET objects like HttpContext , HttpRequest and HttpResponse objects are created. Step 4:- Once all the core ASP.NET objects are created HttpApplication object is created to serve the request. In case you have a global.asax file in your system then object of the global.asax file will be created. Please note global.asax file inherits from HttpApplication class. Note: The first time an ASP.NET page is attached to an application, a new instance of HttpApplication is created. Said and done to maximize performance, HttpApplication instances might be reused for multiple requests. Step 5:- The HttpApplication object is then assigned to the core ASP.NET objects to process the page. Step 6:- HttpApplication then starts processing the request by http module events , handlers and page events. It fires the MHPM event for request processing. ASP.NET Page Life Cycle When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering

Stage

Description The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page. In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property. During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state. During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

Page request

Start

Initialization

Load

If the request is a postback, control event handlers are called. After that, the Validate Postback event method of all validator controls is called, which sets the IsValid property of individual handling validator controls and of the page. (There is an exception to this sequence: the handler for the event that caused validation is called after validation.) Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property. The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.

Rendering

Unload

ASP.NET Page Life-Cycle Events Within each stage of the life cycle of a page, the page raises events that you can handle to run your own code. 1.PreInit

Raised after the start stage is complete and before the initialization stage begins. Use this event for the following: Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time. Create or re-create dynamic controls. Set a master page dynamically. Set the Theme property dynamically. Read or set profile property values. Note If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event. 2.Init Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page. Use this event to read or initialize control properties. 3.InitComplete Raised at the end of the page's initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event. Use this event to make changes to view state that you want to make sure are persisted after the next postback. 4.PreLoad Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance. 5.Load The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page. Use the OnLoad event method to set properties in controls and to establish database connections.

6.Control events Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event. Note In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.

7.LoadComplete Raised at the end of the event-handling stage. Use this event for tasks that require that all other controls on the page be loaded. 8.PreRender Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls.The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page. Use the event to make final changes to the contents of the page or its controls before the rendering stage begins. 9.PreRenderComplete Raised after each data bound control whose DataSourceID property is set calls its DataBind method. 10.SaveStateComplete Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback. 11.Render This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup to send to the browser. If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. 11.Unload Raised for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing controlspecific database connections.For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks. Note During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception. ASP.NET Page Directives A directive controls how the page is compiled.A directive is special instructions on how ASP.NET should process the page. The most common directive is <%@ Page %> which can specify many things, such as which programming language is used for the server-side code.

Format to write the directive is: <%@ Directive attribute= value %> The directives in ASP.NET are :@Page Defines the page specific attributes used by ASP.NET page parser & compiler. <%@ Page Language =VB AutoeventWireup = false CodeFile=Default.aspx.vb Inherits=_Default%> @Master Defines the master page specific attributes used by ASP.NET page parser & compiler. <%@ Master Language=VB codeFile=MasterPage1.master.vb false Inherits =MasterPage %> @OutputCache Declaratively controls the output caching policies of an ASP.NET page or a user control contained in a page. <%@ OutputCache Duration="100" VaryByParam="none" %> @ Register Creates an association between a tag prefix and a custom control, which provides developers with a concise way to refer to custom controls in an ASP.NET application file <%@ Register tagprefix="tagprefix" tagname="tagname" src="pathname" %> AutoeventWireup =

Standard Controls

Label : This control renders text, or an HTML fragment, on the page. You can change the displayed text with server-side code. Using <asp:Label> control, the control uses the Text Attribute to assign the content of the control. <asp:Label ID=Label1 Runat=server Text=Hello World/> Instead of Text attribute, you can place the content to be displayed in <asp:Label> element.

<asp:Label ID=Label1 Runat=server>Hello Word</asp:Label> Programatically providing text to the Label Control Label1.Text=Hello World;

TextBox : The user can enter text and numeric values into the boxes that are displayed. This control supports input masks that make it suitable for entering passwords or other sensitive information. The TextMode property accepts the following values:SingleLine Displays a single-line input field <asp:TextBox ID=TextBox1 Runat=server TextMode=SingleLine/> MultiLine Displays a multi-line input field <asp:TextBox ID=TextBox1 Runat=server TextMode=MultiLine/> Password Displays a single line input field in which the text is hidden. <asp:TextBox ID=TextBox1 Runat=server TextMode=Password/> Method Focus() Event TextChanged are changed. Properties Autopostback -> Enables you to post the form containing the TextBox back to the server automatically when the contents of the textbox is changed. AutoCompleteType -> Enables you to associate an AutoComplete class with the TextBox control. > Raised on the server when the contents of the text box -> Enables you to set the initial form focus to the text box.

Button This control renders a button that the user can click to send a command or to initiate an action. When a Button control is pressed, the page is submitted back to the server, and various events, such as Page.Load and Button.Click, are fired. <asp:Button ID=Button1 Runat=server Text=Button1 OnCommand=Button_Command CommandName=DoSomething/> Method

Focus() Events

-> Enables you to set the initial form focus to the Button Control

Click -> Raised when the button control is clicked Command -> Raised when the button control is clicked. The CommandName & CommandArgument are passed to this event. Properties Command Argument -> Enables you to specify a command argument that is passed to the command event. CommandName -> Enables you to specify a command name that is passed to the command event. Enabled -> Enables you to disable the Button control OnClientClick -> Enables you to specify a client-side script that executes when the button is clicked. PostBackUrl -> Enables you to post a form to a particular page.

Link Button This control renders an object that appears as a hyperlink to the user, but behaves as a button in terms of its programming model. i.e., Methods,Properties&Events are same like the Button. <asp:LinkButton ID=LinkButton1 Runat=Server OnClick=LinkButton1_Click Text=Submit/> Image Button This control renders an object that appears as an image to the user, but behaves as a button in terms of its programming model. i.e., Methods,Properties&Events are same like the Button. <asp:ImageButton ID=ImageButton1 Runat=server OnClick=ImageButton1_Click ImageUrl=MyButton.jpg/> The event handler for an Image Control is differ from other button controls, it is passed to an instance of the ImageClickEventArgs class. It has the following properties : X The x coordinate relative to the image the user clicked Y The y coordinate relative to the image the user clicked Hyper Link This control renders an HTML <a> tag, which you can use to link to another Web page.

Unlike LinkButton Control, the HyperLink control does not submit a form to a server. The HyperLink Control can be used for images as well as text. <asp:HyperLink ID=HyperLink1 Runat=server Text=Go to Home Page NavigateUrl=~/Default.aspx /> <asp:HyperLink ID=HyperLink1 Runat=server ImageUrl=~/LinkImage.jpg NavigateUrl=~/Default.aspx /> Properties Enabled -> Enables you to disable the hyperlink Text -> Enables you to label the hyperlink ImageUrl -> Enables you to specify an image for hyperlink NavigateUrl -> Enables you to specify the URL representation of hyperlink Target -> Enables you to open a new window DropDownList This control renders a drop-down list box from which the user can select an item. set the items that appear in the list by adding ListItem controls. Property SelectedIndex OnSelectedIndexChanged Description The index of a selected item The name of the function to be executed when the index of the selected item has changed You can

validation control
There are 5 validation control in asp.net 1. RequiredFieldValidator 2. RangeValidator 3. RegularExpressionValidator 4. CompareValidator 5. CustomValidator The Required Field is use when you want to make sure that there should be a value before the page is submitted to the server.

RangeValidator is used when you want to validate from one range to another. It has properties, MaximumValue and Minimunvalue; those are the Properties you can use. RegularExpressionValiadator is used to restrict the range of valid characters, to strip unwanted characters, and to perform length and format checks. CompareValidator is used to compare two values if they are the same. This is used mostly in password and password repeat scenario. ValidationSummary is used to display all the Warning for all controls that are linked to the validation control. CompareValidator control The CompareValidator control compares a user's entry against a constant value, against the value of another control (using a comparison operator such as less than, equal, or greater than), CustomValidator control The CustomValidator control checks the user's entry using validation logic that you write yourself. This type of validation enables you to check for values derived at run time. RangeValidator control The RangeValidator control checks that a user's entry is between specified lower and upper boundaries. You can check ranges within pairs of numbers, alphabetic characters, and dates. RegularExpressionValidator control The RegularExpressionValidator control checks that the entry matches a pattern defined by a regular expression. This type of validation enables you to check for predictable sequences of characters, such as those in e-mail addresses, telephone numbers, postal codes, and so on.

RequiredFieldValidator control The RequiredFieldValidator control ensures that the user does not skip an entry. ValidationSummary control The ValidationSummary control does not perform validation, but is often used in conjunction with other validation controls to display the error messages from all the validation controls on the page together.

User controls. User controls are containers into which you can put markup and Web server controls. You can then treat the user control as a unit and define properties and methods for it.

Custom controls. A custom control is a class that you write that derives from Control or WebControl. User controls are substantially easier to create than custom controls, because you can reuse existing controls. They make it particularly easy to create controls with complex user interface elements.

To create an ASP.NET user control


1. Open the Web site project to which you want to add user controls. If you do not already have a Web site project, you can create one. For more information, see Local IIS Web Site Projects or How to: Create File System Web Site Projects. 2. On the Website menu, click Add New Item. The Add New Item dialog box appears. 3. In the Add New Item dialog box, under Visual Studio installed templates, click Web User Control. 4. In the Name box, type a name for the control. By default, the .ascx file name extension is appended to the control name that you type. 5. From the Language list, select the programming language that you want to use. 6. Optionally, if you want to keep any code for the user control in a separate file, select the Place code in separate file check box. 7. Click Add. The new ASP.NET user control is created and then opened in the designer. The markup for this new control is similar to the markup for an ASP.NET Web page, except that it contains an @ Control directive instead of an @ Page directive, and the user control does not have html, body, and form elements. Add any markup and controls to the new user control, and add code for any tasks that the user control will perform, such as handling control events or reading data from a data source.

To add an ASP.NET user control to a Web page


1. In Visual Web Developer, open the Web page to which you want to add the ASP.NET user control. 2. Switch to Design view. 3. Select your custom user control file in Solution Explorer, and drag it onto the page. The ASP.NET user control is added to the page. In addition, the designer creates the @ Register directive, which is required for the page to recognize the user control. You can now work with the control's public properties and methods. In the containing ASP.NET Web page, create an @ Register directive that includes: A TagPrefix attribute, which associates a prefix with the user control. This prefix will be

included in opening tag of the user control element. A TagName attribute, which associates a name with the user control. This name will be included in the opening tag of the user control element. A Src attribute, which defines the virtual path to the user control file that you are including In the body of the Web page, declare the user control element inside the form element. Optionally, if the user control exposes public properties, set the properties declaratively. Ex:
<%@ Page Language="C#" %> <%@ Register TagPrefix="uc" TagName="Spinner" %> <html> <body> <form runat="server"> <uc:Spinner id="Spinner1" runat="server" MinValue="1" MaxValue="10" /> </form> Src="~/Controls/Spinner.ascx"

</body>
</html>

Custom controls To create the custom server control


1. From the File menu select New Project. The New Project dialog box is displayed. 2. Under Installed Templates, expand Visual Basic or Visual C#, and then select Web. 3. Select the ASP.NET Server Control template. 4. In the Name box enter ServerControl1. The New Project dialog box resembles the following illustration. 5. Click OK. Visual Studio creates a server control project that has a class file that is named ServerControl1.cs or ServerControl1.vb. 6. Rename ServerControl1.cs or ServerControl1.vb to WelcomeLabel.cs or WelcomeLabel.vb. A dialog box asks if you want to rename all references to ServerControl1, as shown in the following illustration. 7. Click Yes.

8. Open WelcomeLabel.cs or WelcomeLabel.vb. 9. Change the WelcomeLabel class so that it inherits from System.Web.UI.WebControls.Label instead of from System.Web.UI.WebControls.WebControl. 10. In the ToolboxData attribute for the WelcomeLabel class, change the string "ServerControl1" to "WelcomeLabel" in both places where it occurs. 11. Delete the code that is in the WelcomeLabel class, and insert a DefaultUserName property and a RenderContents method as shown in the following example: C#
using using using using using using using using using System.Drawing; System; System.Collections.Generic; System.ComponentModel; System.Linq; System.Text; System.Web; System.Web.UI; System.Web.UI.WebControls;

namespace ServerControl1 { [DefaultProperty("Text")] [ToolboxData("<{0}:WelcomeLabel runat=server></{0}:WelcomeLabel>")] public class WelcomeLabel : Label { [ Bindable(true), Category("Appearance"), DefaultValue(""), Description("The text to display when the user is not logged in."), Localizable(true) ] public virtual string DefaultUserName { get { string s = (string)ViewState["DefaultUserName"]; return (s == null) ? String.Empty : s; } set { ViewState["DefaultUserName"] = value; } } protected override void RenderContents(HtmlTextWriter writer) { writer.WriteEncodedText(Text); string displayUserName = DefaultUserName; if (Context != null) { string userName = Context.User.Identity.Name; if (!String.IsNullOrEmpty(userName))

{ displayUserName = userName; } } if (!String.IsNullOrEmpty(displayUserName)) { writer.Write(", "); writer.WriteEncodedText(displayUserName); } writer.Write("!"); } } }

12. In Solution Explorer, expand Properties and open AssemblyInfo.cs or expand My Project and open AssemblyInfo.vb. (You might have to click Show All Files to be able to expand My Project.) 13. At the beginning of the file, add the following line:
Using System.Web.UI;

This namespace is required for the TagPrefixAttribute attribute that you will add in the following step. 14. At the end of the file, add the following line:

[assembly: TagPrefix("ServerControl1", "aspSample")]

This TagPrefixAttribute attribute creates a mapping between the namespace ServerControl1 and the prefix aspSample. 15. Save the WelcomeLabel.cs or WelcomeLabel.vb file. Testing a Custom Server Control In the following procedure you will complete the following tasks: Create a Web site that you will use to test the server control that you created in the preceding procedure. Add a reference in the Web site project to the Server Control project. Add the WelcomeLabel control to the Toolbox. Add an instance of the WelcomeLabel control to the Default.aspx page. Run the Default.aspx page to see that the WelcomeLabel control works. You begin by creating a Web site that you can use for testing. This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects.

To create a Web site project to test the custom server control


1. In the File menu, click Add, and then select New Web Site. The New Web Site dialog box is displayed. 2. Under Installed Templates, select Visual Basic or Visual C#, and then select the ASP.NET Web Site template. 3. Name the Web site TestWebSite and save it in a new folder that is under the ServerControl1 solution folder. The New Web Site dialog box resembles the following illustration:

4. Click OK. Visual Studio creates a Web site project, adds it to the ServerControl1 solution, and opens the Default.aspx page in Source view. 5. In Solution Explorer, right-click the Web site project and select Set as Startup Project. 6. In Solution Explorer, right-click the Web site project and select Add Reference. The Add Reference dialog box is displayed. 7. Select the Projects tab, select the ServerControl1 project, and then click OK. The Add Reference dialog box is shown in the following illustration:

The next step is to add the server control to the toolbox so that you can use it in a Web page in the test Web site.

To add the Welcome Label control to the toolbox


1. From the Build menu, select Build Solution. Visual Studio compiles the solution and copies the assembly that is created by the ServerControl1 project into the Bin folder of the TestWebSite project. 2. With the Default.aspx page still open, open the Toolbox window. 3. Right-click anywhere in the Toolbox window and then click Add Tab. 4. Name the new tab Server Control1. 5. Right-click the Server Control1 tab and then click Choose Items. 6. Select Browse and then browse to the Bin folder of the TestWebSite project. 7. Select ServerControl1.dll and then click Open. The ServerControl1 assembly is added to the .NET Framework Components tab of the Choose Toolbox Items dialog box, as shown in the following illustration:

8. Click OK. The WelcomeLabel control appears in the Server Control1 tab in the Toolbox. You can now add the server control to a Web page and test the Web page.

To test the Welcome Label control


1. In the Default.aspx page, delete the text "Welcome to ASP.NET!" and in its place drag the WelcomeLabel control from the Toolbox. 2. Add Text and DefaultUserName attribute to the markup for the WelcomeLabel control and set it to "Welcome," as shown in the following example:
<aspSample:WelcomeLabel ID="WelcomeLabel1" runat="server" Text="Welcome" DefaultUserName="Guest"> </aspSample:WelcomeLabel>

3. Press CTRL-F5 to display the Web page in the browser. The WelcomeLabel control displays "Welcome!", as shown in the following illustration: 4. Click the Log in hyperlink. The Log In page is displayed. 5. Click the Register hyperlink.

The Create a New Account page is displayed, as shown in the following illustration. 6. Enter newuser as the user name, enter newuser@asp.net as the email address, enter a password, and then click the Create User button. ASP.NET creates the new user account, logs you in as the new user, and returns to the home page. The WelcomeLabel control now displays "Welcome, newuser!", as shown in the following illustration:

State Management
State management is the process by which you maintain state and page information over multiple requests for the same or different pages. Types 1.Client Side Management 2.Server Side Management 1. Client Side State Management This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator(url), or a cookie. The techniques available to store the state information at the client end are listed down below: a. View State Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state. b. Control State If you create a custom control that requires view state to work properly, you should use control state to ensure other developers dont break your control by disabling view state. c. Hidden fields Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed. d. Cookies Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site. e. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL. 2. Server Side State Management

a. Application State - Application State information is available to all pages, regardless of which user requests a page. b. Session State Session State information is available to all pages opened by a user during a single visit. Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties. Session State Session Server Session state is associated with a browser session. The session is invalidated with a timeout (by default, 20 minutes). Session state can be stored within an HttpSessionState object. The session state object associated with the current HTTP context can be accessed with the Session property of the Page class. Syntax : Session["<Session Name>"] = Value; Ex: Session["mydata"] = 0;

The following example shows how session state is read with the Session property using the session int val = (int)Session["mydata"]; Label1.Text = val.ToString(); val += 4; Session["mydata"] = val;

by default ASP.NET uses a temporary cookie with a session identifier. ASP.NET also supports sessions without cookies, where URL identifiers are used to map the HTTP requests to the same session. ASP.NET session state supports several different storage options for session data: a. InProc Stores session state in memory on the Web server. This is the default, and it offers much better performance than using the ASP.NET state service or storing state information in a database server. InProc is fine for simple applications, but robust applications that use multiple Web servers or must persist session data between application restarts should use State Server or SQLServer. b. StateServer Stores session state in a service called the ASP.NET State Service. This ensures

that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. ASP.NET State Service is included with any computer set up to run ASP.NET Web applications; however, the service is set up to start manually by default. Therefore, when configuring the ASP.NET State Service, you must set the startup type to Automatic. c. SQLServer Stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. On the same hardware, the ASP.NET State Service outperforms SQLServer. However, a SQL Server database offers more robust data integrity and reporting capabilities. d. Custom Enables you to specify a custom storage provider. You also need to implement the custom storage provider. e. Off Disables session state. You should disable session state if you are not using it to improve performance.

Server - Side State Management: Application State: ASP.NET allows you to save values using application state, a global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the Application key/value dictionary. Once you add your application-specific information to application state, the server manages it, and it is never exposed to the client. Application state is a great place to store information that is not user-specific. By storing it in the application state, all pages can access data from a single location in memory, rather than keeping separate copies of the data. Data stored in the Application object is not permanent and is lost any time the application is restarted. ASP.NET provides three events that enable you to initialize Application variables (free resources when the application shuts down) and respond to Application errors: a. Application_Start: Raised when the application starts. This is the perfect place to initialize Application variables. b. Application_End: Raised when an application shuts down. Use this to free application resources and perform logging. c. Application_Error: Raised when an unhandled error occurs. Use this to perform error logging. The following code snippet shows the basic syntax for storing application state information: Void Application_Start(object sender, EventArgs e)
{ Application["startMessage"] = "The application has started."; } Void Application_End(object sender, EventArgs e) { Application["endtMessage"] = "The application has ended."; }

Client- Side State Management: Cookies Cookies: Web applications can store small pieces of data in the clients Web browser by using cookies. A cookie is a small amount of data that is stored either in a text file on the client file system (if the cookie is persistent) or in memory in the client browser session (if the cookie is temporary). The most common use of cookies is to identify a single user as he or she visits multiple Web pages. Reading and Writing Cookies: A Web application creates a cookie by sending it to the client as a header in an HTTP response. The Web browser then submits the same cookie to the server with every new request. Create a cookie -> add a value to the Response.Cookies HttpCookieCollection. Read a cookie -> read values in Request.Cookies. Example: // Check if cookie exists, and display it if it does if (Request.Cookies["lastVisit"] != null) // Encode the cookie in case the cookie contains clientside script Label1.Text = Server.HtmlEncode(Request.Cookies["lastVisit"].Value); else Label1.Text = "No value defined"; // Define the cookie for the next visit Response.Cookies["lastVisit"].Value = DateTime.Now.ToString();Response.Cookies["lastVisit"].Expires = DateTime.Now.AddDays(1);

If you do not define the Expires property, the browser stores it in memory and the cookie is lost if the user closes his or her browser. To delete a cookie, overwrite the cookie and set an expiration date in the past. You cant directly delete cookies because they are stored on the clients computer. Controlling the Cookie Scope: By default, browsers wont send a cookie to a Web site with a different hostname. You can control a cookies scope to either limit the scope to a specific folder on the Web server or expand the scope to any server in a domain. To limit the scope of a cookie to a folder, set the Path property, as the following example demonstrates: Example: Response.Cookies["lastVisit"].Path = "/Application1"; Through this the scope is limited to the /Application1 folder that is the browser submits the cookie to any page with in this folder and not to pages in other folders even if the folder is in the same server. We can expand the scope to a particular domain using the following statement: Example: Response.Cookies[lastVisit].Domain = Contoso;

Storing Multiple Values in a Cookie: Though it depends on the browser, you typically cant store more than 20 cookies per site, and each cookie can be a maximum of 4 KB in length. To work around the 20-cookie limit, you can store multiple values in a cookie, as the following code demonstrates: Example: Response.Cookies["info"]["visit"].Value = DateTime.Now.ToString(); Response.Cookies["info"]["firstName"].Value = "Tony"; Response.Cookies["info"]["border"].Value = "blue"; Response.Cookies["info"].Expires = DateTime.Now.AddDays(1); Query Strings: Query strings are commonly used to store variables that identify specific pages, such as search terms or page numbers. A query string is information that is appended to the end of a page URL. A typical query string might look like the following real-world example: http://support.microsoft.com/Default.aspx?kbid=315233 In this example, the URL identifies the Default.aspx page. The query string (which starts with a question mark [?]) contains a single parameter named kbid, and a value for that parameter, 315233. Query strings can also have multiple parameters, such as the following real-world URL, which specifies a language and query when searching the Microsoft.com Web site: http://search.microsoft.com/results.aspx?mkt=en-US&setlang=en-US&q=hello+world Value Name | ASP.NET Object | Value mkt | Request.QueryString[mkt] | en-US setlang | Request.QueryString[setlang] | en-US q | Request.QueryString[q] | hello world Limitations for Query Strings: 1. Some Browsers and client devices impose a 2083 character limit on the length of the URL. 2. You must submit the page using an HTTP GET command in order for query string values to be available during page processing. Therefore, you shouldnt add query strings to button targets in forms. 3. You must manually add query string values to every hyperlink that the user might click. Example: Label1.Text = "User: " + Server.HtmlEncode(Request.QueryString["user"]) + ", Prefs: " + Server.HtmlEncode(Request.QueryString["prefs"]) + ", Page: " + Server.HtmlEncode(Request.QueryString["page"]); Hidden Field: A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP form collection along with the values of other controls. ASP.NET provides the HtmlInputHidden control that offers hidden field functionality.

//To set a value


Hidden1.Value=Test Value assigned to hidden field; //to retrieve a value string strValue=Hidden1.Value;

View State: ASP.NET introduces the ability to store client-specific state through a mechanism called view state. View state is stored in a hidden field on each ASP.NET page called __VIEWSTATE. Each time a page is posted to itself, the contents of the __VIEWSTATE field are sent as part of the post. The primary use of view state is for controls to retain their state across post-backs. The View State is the state of the page and all its controls. It is automatically maintained across posts by the ASP.Net framework. View State is enabled by default, but if you can disable it by setting the EnableViewState property for each web control to false. This reduces the server processing time and decreases page size. 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. Control State: If you create a custom control that requires ViewState, you can use the ControlState property to store state information for your control. ControlState allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property. To use control state in a custom control, your control must override the OnInit method and call the RegisterRequiresControlState method during initialization and then override the SaveControl-State and LoadControlState methods.

Advantages
Advantages of Client Side State Management: 1. Better Scalability: With server-side state management, each client that connects to the Web server consumes memory on the Web server. If a Web site has hundreds or thousands of simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that potential bottleneck.

2. Supports multiple Web servers: With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the clients state information. You can use multiple servers with server-side state management, but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access). Advantages of Server Side State Management: 1. Better security: Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. Therefore, you should never use client-side state management to store confidential information, such as a password, authorization level, or authentication status. 2. Reduced bandwidth: If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections. Instead, you should store large amounts of state management data (say, more than 1 KB) on the server.

CSS
CSS stands for cascading style sheets and is independent of ASP.NET. CSS is used to apply layout and visual style to elements on a page Styles define how to display HTML elements Styles were added to HTML 4.0 to solve a problem External Style Sheets can save a lot of work External Style Sheets are stored in CSS files

CSS Syntax
A CSS rule has two main parts: a selector, and one or more declarations:

The selector is normally the HTML element you want to style. Each declaration consists of a property and a value.

The property is the style attribute you want to change. Each property has a value.

CSS Comments
Comments are used to explain your code, and may help you when you edit the source code at a later date. Comments are ignored by browsers. A CSS comment begins with "/*", and ends with "*/" /*This is a comment*/ p { text-align:center; /*This is another comment*/ color:black; font-family:arial; }

The id and class Selectors The id Selector


The id selector is used to specify a style for a single, unique element. The id selector uses the id attribute of the HTML element, and is defined with a "#". The style rule below will be applied to the element with id="para1": #para1 { text-align:center; color:red; }

The class Selector


The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is most often used on several elements. This allows you to set a particular style for many HTML elements with the same class. The class selector uses the HTML class attribute, and is defined with a "." In the example below, all HTML elements with class="center" will be center-aligned: ex: 1. .center {text-align:center;} 2. p.center {text-align:center;}

Themes and Skins Themes and Skins are a way in ASP.NET to decouple the visual appearance of your server controls from the markup, and allow you to swap out the visual appearance at run time by changing the theme A theme is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in a Web application, across an entire Web application, or across all Web applications on a server. Themes are made up of a set of elements: skins, cascading style sheets (CSS), images, and other resources. At a minimum, a theme will contain skins. Themes are defined in special directories in your Web site or on your Web server.

Page Themes

A page theme is a theme folder with control skins, style sheets, graphics files and other resources created as a subfolder of the \App_Themes folder in your Web site. Each theme is a different subfolder of the \App_Themes folder.

Global Themes A global theme is a theme that you can apply to all the Web sites on a server. Global themes allow you to define an overall look for your domain when you maintain multiple Web sites on the same server.

Skins A skin file has the file name extension .skin and contains property settings for individual controls such as Button, Label, TextBox, or Calendar controls. <asp:button runat="server" BackColor="lightblue" ForeColor="black" /> To create a page theme 1. In Solution Explorer, right-click the name of the Web site for which you want to create a page theme, and then click Add ASP.NET Folder. 2. Click Theme. If the App_Themes folder does not already exist, Visual Web Developer creates it. Visual Web Developer then creates a new folder for the theme as a child folder of the App_Themes folder. 3. Type a name for the new folder. The name of this folder is also the name of the page theme. For example, if you create a folder

named \App_Themes\FirstTheme, the name of your theme is FirstTheme. 4. Add files to your new folder for control skins, style sheets, and images that make up the theme.

To add a skin file and a skin to a page theme


1. In Solution Explorer, right-click the name of your theme and then click Add New Item. 2. In the Add New Item dialog box, click Skin File. 3. In the Name box, type a name for the .skin file, and then click Add. The typical convention is to create one .skin file per control, such as Button.skin or Calendar.skin. However, you can create as many or as few .skin files as you need. 4. In the .skin file, add a normal control definition by using declarative syntax, but include only the properties that you want to set for the theme. The control definition must include the runat="server" attribute, and it must not include the ID="" attribute. To add a cascading style sheet file to your page theme 1. In Solution Explorer, right-click the name of your theme and then click Add New Item. 2. In the Add New Item dialog box, click Style Sheet. 3. In the Name box, type a name for the .css file, and then click Add.

To apply a theme to a Web site

1. In the application's Web.config file, set the <pages> element to the name of the theme, either a global theme or a page theme <configuration>
<system.web> <pages theme="ThemeName" /> </system.web> </configuration>

2. To set a theme as a style sheet theme and be subordinated to local control settings), set the styleSheetTheme attribute instead: <configuration>
<system.web> <pages styleSheetTheme="Themename" /> </system.web> </configuration>

1.To apply a theme to an individual page


Set the Theme or StyleSheetTheme attribute of the @ Page directive to the name of the theme to

use, as shown in the following example:


<%@ Page Theme="ThemeName" %> <%@ Page StyleSheetTheme="ThemeName" %>

The theme and its corresponding styles and skins now applies only to the page declaring it.

To apply a page theme programmatically


In a handler for the page's PreInit method, set the page's Theme property.
protected void Page_PreInit(object sender, EventArgs e) { switch (Request.QueryString["theme"]) { case "Blue": Page.Theme = "BlueTheme"; break; case "Pink": Page.Theme = "PinkTheme"; break; } }

To apply a named skin to a control


Set the control's SkinID property, as shown in the following example:
<asp:Calendar runat="server" ID="DatePicker" SkinID="SmallCalendar" />

ASP.Net Configuration Files

ASP.NET configuration files are XML files. The .NET Framework defines a set of elements that implement configuration settings, and the ASP.NET configuration schema contains elements that control how ASP.NET Web applications behave. Types of configuration files

machine.config web.config

Machine.config File

The machine configuration file, Machine.config, contains settings that apply to an entire computer. This file is located in the %runtime install path%\Config directory. Machine.config contains configuration settings for machinewide assembly binding, built-in remoting channels, and ASP.NET.
The machine.config file contains default and the machine-specific value for all supported settings. The machine settings are controlled by the system administrator and applications are generally not given access to this file. An application however, can override the default values by creating web.config files in its roots folder. The web.config file is a subset of the machine.config file.

Any web.config file can locally extend, restrict or override any settings defined on the upper level.

Visual Studio generates a default web.config file for each project. An application can run without a web.config file, however, you cannot debug an application without a web.config file.

Note Deploying an application using XCOPY will not copy the settings in the machine configuration file.

web.config File

Web .Configuration files is a in XML-based text files that stores configuration settings that affect all Web applications on a server, that affect only a single application, that affect individual pages, or that affect individual folders in a Web application. You can make configuration settings for features such as compiler options, debugging, user authentication, error-message display, connection strings, and more.

You can use any standard text editor or XML parser to create and edit ASP.NET configuration files. Multiple configuration files, all named Web.config, can appear in multiple directories on an ASP.NET Web application server. Each Web.config file applies configuration settings to its own directory and all child directories below it. Configuration files in child directories can supply configuration information in addition to that inherited from parent directories, and the child directory configuration settings can override or modify settings defined in parent directories.

Configuration File Sections


In order for an application to service Web requests, ASP.NET must first compile the application into one or more assemblies. The following example shows how to specify configuration settings in the compilation section.

<compilation debug="true"

optimizeCompilations="true"

targetFramework="4.0" />

Authentication and Roles


ASP.NET can authenticate the credentials, such as name and password, of a Web site user. By using mode attribute in the authentication configuration section, you can specify the authentication scheme for your application. The default is Windows authentication, where the Windows user's account information is used for authentication.

Example

<authentication mode="Windows"/>

Connection Strings
The connectionStrings configuration section specifies a collection of database connection strings

<connectionStrings> <add name="Sales" connectionString= "server=myserver;database=Products; uid=<user name>;pwd=<secure password>" /> </connectionStrings>

AppSettings Element
Contains custom application settings, such as file paths, XML Web service URLs, or any information that is stored in the.ini file for an application.

<appSettings file="relative file name" > </appSettings>

Configuration files that are specified in a file attribute must have the appSettings element rather than the configuration element as the root node. The following code example demonstrates how to use the correct form for a configuration file that is specified in the file attribute.

<appSettings> <add key="Application1" value="MyApplication1" /> <add key="Setting1" value="MySetting" /> <add key ="cstr" value ="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ORBILENDING.mdf;Integrated Security=True;User Instance=True" /> </appSettings>

You can read a setting from web.config in one line as follows: string value = System.Web.Configuration.WebConfigurationManager.AppSettings["Key"];

Global.asax file
The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level and session-level events raised by ASP.NET or by HTTP modules. The Global.asax file resides in the root directory of an ASP.NET application. At run time, Global.asax is parsed and compiled into a dynamically generated .NET Framework class derived from the HttpApplication base class

protected void Application_Start(Object sender, EventArgs e) { Application["OnlineCount"] = 0; ArrayList myAL = new ArrayList(); Application["UserList"] = myAL; } protected void Session_Start(Object sender, EventArgs e) { Session.Timeout = 20; Application.Lock(); Application["OnlineCount"] = Convert.ToInt32(Application["OnlineCount"]) + 1; Application.UnLock();

}
void Session_End(object sender, EventArgs e) { // Decrement sessions. Application["SessCount"] = (int)Application["SessCount"] - 1; Response.Write("Number of sessions: " + Application["SessCount"] + "&lt;br>");

Note :
Application_Start fires when the application restarts or IIS restarts Session_start fires each time a Session is created Application_End fires when application or sesrver get crahed

ASP.Net Caching
Caching The ability to store data in the cache memory and then allow for retrieval of the same as and when they are requested. Through this we can cache [store in memory] the output generated by a page and will serve this cached content for future requests. Type 1.Page Output Caching Page Output Caching is the most basic form of caching. The output caching simply maintains a copy of the HTML which was sent in response to a memory request. Subsequent requests are then given the cached output until the cache expires

<%@ OutputCache Duration=no of seconds Location=Any | Client | Downstream | Server | None VaryByControl=control VaryByCustom=browser |customstring VaryByHeader=headers VaryByParam=parameter %>

This directive, as with other page directives should appear at the top of the ASPX page, before any output. It supports five attributes (or parameters), two of which are required. Duration Location Required. Time, in seconds, the page should be cached. Must be a positive integer. Specifies where the output should be cached. If specified, must be one of: Any, Client, Downstream, None, Server or ServerAndClient. VaryByParam Required. The names of the variables in the Request, which should result in, separate cache entries. "none" can be used to specify no variation. "*" can be used to create new cache entries for every different set of variables. Separate variables with ";". VaryByHeader Varies cache entries based on variations in a specified header.

VaryByCustom Allows custom variations to be specified in the global.asax (for example, "Browser").

2.Page Fragment Caching Also known as Partial Page Caching, this is a feature that allows specific portions of the web page to be cached rather than caching the entire web page and is useful in situations where a particular web page can contain both static and dynamic content.
This allows specific portions of the page to be cached rather than caching the whole page. This is useful in

situations where we can have a page that contains both static and dynamic content. The following code depicts how this can be accomplished. <%@ OutputCache Duration="15" VaryByControl="EmpID;DeptID" VaryByParam="*"%> This directive is placed at the top of any User Control (.axcx file).

3 .Programmatic or Data Caching


Using the Cache object, you can store any serializeable data object, and control how that cache entry expires based on a combination of one or more dependencies. These dependencies can include time elapsed since the item was cached, time elapsed since the item was last accessed, changes to files and/or folders, changes to other cached items, or (with a little work) changes to particular tables in a database.

Storing Data in the Cache


Cache["key"] = "value"; This will store the item in the cache without any dependencies, so it will not expire unless the cache engine removes it in order to make room for additional cached data. To include specific cache dependencies, the Add() or Insert() method is used. Examples

Cache.Insert("key", myXMLFileData, new System.Web.Caching.CacheDependency(Server.MapPath("users.xml")));


This would insert xml data from a file into the cache, eliminating the need to read from the file on subsequent requests. The CacheDependency will ensure that when the file changes, the cache will immediately expire, allowing the latest data to be pulled from the file and re-cached

Cache.Insert("key", myTimeSensitiveData, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero);


This example will cache the time sensitive data for one minute, at which point the cache will expire

WPF APPLICATION
INTRODUCTION TO WPF: Developed by Microsoft, the Windows Presentation Foundation (or WPF) is a computersoftware graphical subsystem for rendering user interfaces in Windows-based applications. WPF, previously known as "Avalon", was initially released as part of .NET Framework 3.0. Rather than relying on the older GDI subsystem, WPF utilizes DirectX. WPF attempts to provide a consistent programming model for building applications and provides a separation between the user interface and the business logic. It resembles similar XML-oriented object models. WPF employs XAML, a derivative of XML, to define and link various UI elements. WPF applications can also be deployed as standalone desktop programs, or hosted as an embedded object in a website. WPF aims to unify a number of common user interface elements, such as 2D/3D rendering, fixed and adaptive documents, typography, vector graphics, runtime animation, and pre-rendered media. These elements can then be linked and manipulated based on various events, user interactions, and data bindings. WPF runtime libraries are included with all versions of Microsoft Windows since Windows Vista and Windows Server 2008. Users of Windows XP SP2/SP3 and Windows Server 2003 can optionally install the necessary libraries. As of 2011 Microsoft has released four major WPF versions: WPF 3.0 (Nov 2006), WPF 3.5 (Nov 2007), WPF 3.5sp1 (Aug 2008), and WPF 4 (April 2010). Microsoft Silverlight utilizes WPF to provide embedded web controls comparable to Adobe Flash, but with more focus on a UI object model and less on animation. 3D runtime rendering is supported in Silverlight since Silverlight 5. XAML: WPF introduces a new language known as eXtensible Application Markup Language (XAML; /zml/), which is based on XML. XAML is designed as a more efficient method of developing application user interfaces. The specific advantage that XAML brings to WPF is that XAML is a completely declarative language, allowing the developer (or designer) to describe the behavior and integration of components without the use of procedural programming. Although it is rare that an entire application will be built completely in XAML, the introduction of XAML allows application designers to more effectively contribute to the application development cycle. Using XAML to develop user interfaces also allows for separation of model and view, which is considered a good architectural principle. In XAML, elements and attributes map to classes and properties in the underlying APIs.

WPF Architecture
PresentationFramework, PresentationCore, and milcore) are the major code portions of WPF. Of these, only one is an unmanaged component milcore. Milcore is written in unmanaged code in order to enable tight integration with DirectX. All display in WPF is done through the DirectX engine, allowing for efficient hardware and software rendering.

WPF Features
State

of the art graphics DirectX under the covers Controls, 2D, 3D graphics Rich Media Integration (images, audio, video) Animation Visual Styling Takes advantage of modern video cards and GPUs Enhance application graphics and performance

Retained mode compositing model

New rendering engine Vector graphics based Logical pixels Transforms, overlays, opacity Very different from User32 and GDI32 DirectX under the covers Takes advantage of GPU for graphics processing

RESOURCES AND STYLES: Resources: Resources store reference to an object within a collection. For instance, most objects in the WPF framework have a Resources collection. The Application object, Window, Button, and other WPF controls all have a Resources collection. A resource can be anything, such as a Brush to use for painting the background, a control template (which we'll look at later), or many other types of objects. Below is an example of a brush defined in the windows resource collection. EXAMPLE: <Window.Resources> <LinearGradientBrush x:Key="BlueButtonBackground"> <GradientStop Color="AliceBlue" Offset="0" /> <GradientStop Color="Blue" Offset=".7" /> </LinearGradientBrush> </Window.Resources> Static Resource is an extension that is used to reference items defined in a resource collection. If not found in the immediate element's resource collection (the button's), it navigates up the stack until it can find the resource with that key. If the button resides in a StackPanel control - which resides in a Grid the resource will be sought for in the button first, StackPanel second, Grid third, Window fourth, and so on. Resources can contain anything, and the last section on Control Templates will illustrate how the control template itself will be defined and referenced as a resource. Resources can also be stored in a central place, such as a resource dictionary. A resource dictionary is a collection of resources that can be easily incorporated into an application. They can be used to contain a single reference to all the assemblies in a single or multiple applications. The following is a simple resource dictionary. <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <LinearGradientBrush x:Key="BlueBackground"> <GradientStop Color="AliceBlue" Offset="0" /> <GradientStop Color="Blue" Offset=".7" /> </LinearGradientBrush> <LinearGradientBrush x:Key="MouseOverBlueBackground"> <GradientStop Color="Blue" Offset="0" /> <GradientStop Color="Navy" Offset=".9" /> </LinearGradientBrush> </ResourceDictionary>

To include a resource dictionary in a Window or user control, include the following definition:

<Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="BasicBlueButtons.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources>

Styles : With ASP.NET 2.0 came a feature called themes. Themes had the ability to set styles to the inner style properties of a control. Any property that defined a ThemeableAttribute with a constructor value of true could assign that property in the skin file, using the same markup as the control (for the most part). Styles do not have the same markup as themes do, but the approach is the same. A style can set the inner properties of a XAML element using setters, as will be illustrated soon. We can define event triggers, which are styles that are applied when an event occurs. An even more useful approach is to use a style trigger, which applies itself whenever a target condition is evaluated to true. For instance, it is possible to change the background color and foreground color whenever a button is pressed, and then revert back to the original setting when that event is false. This works because of the change notification that elements provide when the value exposed by a property changes. EXAMPLE: <Style x:Key="BlueBackgroundStyle" TargetType="{x:Type Button}"> <Setter Property="Control.Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="AliceBlue" Offset="0" /> <GradientStop Color="Blue" Offset="1" /> </LinearGradientBrush> </Setter.Value> </Setter> <Setter Property="Control.FontSize" Value="12" /> </Style> This style is defined in the Window's Resources collection. The style is given a key, so it can be uniquely referenced. A series of setters can be defined in order to specify which properties will be changed. In the example above, only two setters are defined, but you could have continued on with many more entries. In the following example, the style changes the background property to a gradient brush. To use this style, the following code defines a static resource extension and embeds it in a control's background: <Button Style="{StaticResource BlueBackgroundStyle}" Content="Click Styled Button" /> In this situation, the style is applied to all buttons, depending on where it is defined (if in the application, Window, resource dictionary, or local resource collection). TargetType looks for any instance of a button and applies the appropriate style. With this approach, the Control prefix on the

setter property is no longer needed. Triggers can be used for styles as well. For instance, a button has several properties it can use to determine what state it is in. It has an IsPressed property that is used to determine whether a mouse button is currently pressed, an IsEnabled property that determines if the button is enabled, an IsFocused property for determining whether the control has focus (such as when tabbing through the controls on a form), and many more. Each of these properties can be used in a style trigger to perform some action. Take the definition below: <Style x:Key="BlueBackgroundStyle" TargetType="{x:Type Button}"> <Style.Triggers> <Trigger Property="IsPressed" Value="True"> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush> <GradientStop Color="Blue" Offset="0" /> <GradientStop Color="Navy" Offset=".7" /> </LinearGradientBrush> </Setter.Value> </Setter> </Trigger> </Style.Triggers> </Style> Upon pressing the button, the background changes from a lighter gradient to a darker one. This happens because the control has its own change notification. When the button is pressed, the "swap is made". Triggers require that the comparison is an equality comparison. A trigger can't be used to determine if a property is within a specific range. Rather, it often checks if a value matches its condition exactly. Control Templates Each control has a base template that it uses to render its user interface. This interface is a template and is instantiated whenever the control is displayed. The control itself is made up of a lot of different parts; but often includes styles and style triggers, and utilizes resources in several ways. A control template is actually an element that one can define in a resources collection, or in a resource dictionary. The following declaration is perfectly valid:

<Window.Resources> <ControlTemplate x:Key="SomeTemplate" TargetType="{x:Type Button}"> ... </ControlTemplate> </Window.Resources>


To use this template, a button must be declared as follows: <Button Padding="3" Template="{StaticResource SomeTemplate}">Templated

Button</Button> Using this approach, the following template can add a rounded corner border to a button control. In addition, the button has an inner white square border, and includes a commonly-used text statement at the top.

<ControlTemplate x:Key="BlueButtonTemplate" TargetType="{x:Type Button}"> <Border BorderBrush="Navy" BorderThickness="1" CornerRadius="5" Background="CornflowerBlue"> <Border BorderBrush="White" BorderThickness="3" Padding="10" Margin="10"> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Label Content="Please welcome:" Grid.Row="0" /> <ContentPresenter Grid.Row="1" /> </Grid> </Border> </Border> </ControlTemplate>

Our button has a rounded corner border consisting of blue colors. Note the ContentPresenter declaration; this declaration allows the inner content of the button to be bound inside the control. So the text "Templated Button" is rendered inside the templated button. Styles can be used to apply a control template. For example, it is possible to apply a style template using the following style (note that the style is still set the same way, by applying it through the Style property). <Style x:Key="BlueButtonTemplateStyle" TargetType="{x:Type Button}"> <Setter Property="Control.Template" Value="{StaticResource BlueButtonTemplate}" /> </Style> In addition, a template can be applied automatically, simply by using the TargetType attribute on a style. The following applies the control template to all buttons: <Style TargetType="{x:Type Button}"> <Setter Property="Control.Template" Value="{StaticResource BlueButtonTemplate}" /> </Style> A button can ignore this style by manually applying a style with the {x:Null} property value. ANIMATION: Windows Presentation Foundation (WPF) provides a powerful set of graphics and layout features that enable you to create attractive user interfaces and appealing documents. Animation can make an

attractive user interface even more spectacular and usable. By just animating a background color or applying an animated Transform, you can create dramatic screen transitions or provide helpful visual cues. Animation is an illusion that is created by quickly cycling through a series of images, each slightly different from the last. The brain perceives the group of images as a single changing scene. In film, this illusion is created by using cameras that record many photographs, or frames, each second. When the frames are played back by a projector, the audience sees a moving picture. Animation on a computer is similar. For example, a program that makes a drawing of a rectangle fade out of view might work as follows. The program creates a timer. The program checks the timer at set intervals to see how much time has elapsed. Each time the program checks the timer, it computes the current opacity value for the rectangle based on how much time has elapsed. The program then updates the rectangle with the new value and redraws it. Built in animation types Double Color Point

EXAMPLE : XAML:

Make an Element Fade In and Out of View

<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <StackPanel Margin="10"> <Rectangle Name="MyRectangle" Width="100" Height="100" Fill="Blue"> <Rectangle.Triggers> <!-- Animates the rectangle's opacity. --> <EventTrigger RoutedEvent="Rectangle.Loaded"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetName="MyRectangle" Storyboard.TargetProperty="Opacity" From="1.0" To="0.0" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever" /> </Storyboard> </BeginStoryboard> </EventTrigger>

</Rectangle.Triggers> </Rectangle> </StackPanel> </Grid> </Window>


The following shows how to create a rectangle that fades in and out of view in code.

using using using using using using

System; System.Windows; System.Windows.Controls; System.Windows.Media; System.Windows.Shapes; System.Windows.Media.Animation;

namespace WpfApplication1 { public partial class MainWindow : Window { private Storyboard myStoryboard; public MainWindow() { InitializeComponent(); StackPanel myPanel = new StackPanel(); myPanel.Margin = new Thickness(10); Rectangle myRectangle = new Rectangle(); myRectangle.Name = "myRectangle"; this.RegisterName(myRectangle.Name, myRectangle); myRectangle.Width = 100; myRectangle.Height = 100; myRectangle.Fill = Brushes.Blue; DoubleAnimation myDoubleAnimation = new DoubleAnimation(); myDoubleAnimation.From = 1.0; myDoubleAnimation.To = 0.0; myDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(5)); myDoubleAnimation.AutoReverse = true; myDoubleAnimation.RepeatBehavior = RepeatBehavior.Forever; myStoryboard = new Storyboard(); myStoryboard.Children.Add(myDoubleAnimation); Storyboard.SetTargetName(myDoubleAnimation, myRectangle.Name); Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(Rectangle.OpacityProperty)); // Use the Loaded event to start the Storyboard. myRectangle.Loaded += new RoutedEventHandler(myRectangleLoaded); myPanel.Children.Add(myRectangle); this.Content = myPanel; } private void myRectangleLoaded(object sender, RoutedEventArgs e) { myStoryboard.Begin(this);

} } }

Sample

WPF animation Application : 2

Using Double animation class:

XAML Design
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="358" Width="572"> <Grid Height="307" Width="495"> <TextBox Height="23" Margin="112,0,46,25" Name="textBox1" Text="Kumar " VerticalAlignment="Bottom"> <TextBox.RenderTransform > <RotateTransform Angle=" 0" CenterX="100" CenterY="100"></RotateTransform> </TextBox.RenderTransform> </TextBox> <Button Height="23" HorizontalAlignment="Right" Margin="0,0,12,64" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click">Button</Button> </Grid> </Window>

Code Behind
// Name space need to be use for animation using System.Windows.Media.Animation;

// button click event code

private void button1_Click(object sender, RoutedEventArgs e) { DoubleAnimation oLblani = new DoubleAnimation(); oLblani.From = 0; oLblani.To = 360; oLblani.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 500)); oLblani.RepeatBehavior = new RepeatBehavior(5); RotateTransform oTransform = (RotateTransform)textBox1 .RenderTransform ; oTransform.BeginAnimation(RotateTransform.AngleProperty, oLblani); }

Controle composition:
<Button Height="50" Width="50"> <StackPanel> <TextBlock>Play</TextBlock> <Polygon Points="0,0,0,26 ,17,13" Fill="Black" /> </StackPanel> </Button>

DATA BINDING IN WPF: Windows Presentation Foundation (WPF) data binding provides a simple and consistent way for applications to present and interact with data. Elements can be bound to data from a variety of data sources in the form of common language runtime (CLR) objects and XML.

WPF BROWSER APPLICATION: XAML browser applications (XBAPs) combines features of both Web applications and rich-client applications. Like Web applications, XBAPs can be deployed to a Web server and started from Internet Explorer or Firefox. Like rich-client applications, XBAPs can take advantage of the capabilities of WPF. Developing XBAPs is also similar to rich-client development. What Web Browser Applications Offer:
Web Browser Applications offer many benefits:

XAML. WPF introduces a new declarative programming model called "Extensible Application Markup Language," or XAML. Because it is a direct reflection of the underlying platform APIs, developers can leverage all the benefits of a typed programming system. This includes friendly markup error messages during compilation as well as more transparency into what code is needed to provide UI "hookups."

<Application x:Class="MyApp" />


Data binding. Data binding provides a flexible, declarative and robust way of getting data into the UI; it allows an application author to keep business logic and UI separated. Because WPF controls support data binding to information on a server, Web developers can asynchronously consume their data and visualize it in effective and interesting ways using a rich data templating system. 3-D. The WPF 3-D system is fully integrated into the platform. It is no more difficult to paint a 3-D shape with a solid color than to paint that same 3-D shape with a video or a paragraph of text.

3-D in the browser

Flow Documents. Unlike fixed documents, flow documents dynamically layout content based on window size, device resolution, user preference, and so on. This provides users with a superior, and more personalized, reading experience.

Same flow document, different window and font sizes

Text. WPF unlocks the rich typography features available in OpenType fonts (both TrueType and CFF). This provides better text rendering using the latest advances in ClearType, including sub-pixel spacing and ydirection anti-aliasing.

Typography in WPF

Animations. The WPF animation system provides a flexible method of specifying complex, synchronized changes in your scene. Full integration with the property and eventing systems, databinding, styling, and templating allows for deep support of rich, interactive applications.

Blackjack Card Animating in 3-D

Vector graphics. WPF's native use of vector graphics allows it to operate at full visual fidelity (with brilliant anti-aliasing) at any scale or resolution.

Same vector graphic, different window sizes

Hardware acceleration. Today's graphics hardware is getting better and better all the time. WBAs can take advantage of WPF's hardware acceleration support to create new levels of visual complexity while leaving the CPU free for the application's computing requirements. Security sandbox. WBAs run in a security sandbox that limits the types of actions that they can perform. This means WBAs can do things like render UI, talk to site of origin servers, write and read to/from isolated storage, and so on. However, they cannot do more dangerous things like access the registry, read or write directly to the file system, and so on (for more details, see the sandbox section of this document). No-touch deployment. Because Web Browser Applications are sandboxed non-installed applications, they do not require user interaction to launch: there is no need to click through a security prompt or an information bar message. They just run. .NET Framework programming languages. WPF is built on top of the .NET Framework. WBAs therefore receive all the benefits of being strongly typed managed applications. This includes the use of .NET Framework programming languages ( C#, Visual Basic, and so on), native communication to ASMX Web services, and access to the many tools available for the .NET Framework platform. Same programming model for desktop/Web. Many product teams are forced to author two independent versions of their applications: a Web DHTML version and a desktop Win32 version. Because WPF offers support for both online and installed applications, desktop and Web applications can share code bases. In order to build your application as a Web Browser Application, simply use the template included in Visual Studio 2003 or set three properties in your project file:

<HostInBrowser>True</HostInBrowser> <Install>False</Install>
Note The Web version of the application should also disable any functionality disallowed in the sandbox.

Designer and Developer split. WPF minimizes the contract between UI and logic, allowing developers and designers to focus on the thing they do best. Moreover, by encapsulating powerful design concepts (such as rich 2-D, animation, and dynamic layout) and exposing them in a highly toolable markup format, WPF enables the designer to directly express his or her best and most creative ideas and become an independent UI creator.

Application Scenarios for Web Browser Applications


Web Browser Applications offer many benefits to Web developers. As a Windows technology, they can also greatly enhance customer experience on Windows XP, Server 2003, and Vista machines. However, depending on the application content and customer reach goals, WBAs may not be the most appropriate technology for you. In this section, we discuss the scenarios where Web Browser Applications offer a big win.

Scenarios Where Web Browser Applications Are Recommended


WPF can offer many development and user experience advantages. Web Browser Applications are recommended in these scenarios:

Reading and Rich Content Visualizations. WPF can enable a better experience for content-based sites that are driven by asynchronously data-bound 3-D, animations, or text. They can also be easier to build: visuals can be defined in XAML, which designers can author directly or create using tools like Expression Interactive Designer. For sites that store content as XML, creating a server-side transform to both XAML and HTML is low cost and high impact. Online Gaming and Modeling. Sites like online games and scientific modeling require sophisticated logical or computational engines. Because WBAs use managed code to drive the applications, building complicated client-side logic comes with greater ease. And, because the heavy lifting can happen on the client with cached information in isolated storage, the user doesn't need to feel the latency of Web postbacks. Data Flow Management and Productivity Applications. Like gaming applications, data flow and productivity Web applications are logic driven. In addition, these applications often require Web service interaction. Since WPF is built on .NET, you can use the provided ASMX Web services infrastructure. There is no need to build your own mechanism to communicate between applications and Web services. Two Versions of Application: Desktop and Web. Instead of using two different application technologies, product teams can leverage the same code base by creating a WPF Web Browser Application and WPF installed application. Corporate Applications. The deployment of any of the above applications is even simpler in corporations where administrators control the hosting environment. This might include having the .NET Framework 3.0 preinstalled on all client machines or customizing security policy for intranet applications.

WINDOWS COMMUNICATION FOUNDATION Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data. A few sample scenarios include: A secure service to process business transactions. A service that supplies current data to others, such as a traffic report or other monitoring service. A chat service that allows two people to communicate or exchange data in real time. A dashboard application that polls one or more services for data and presents it in a logical presentation. Exposing a workflow implemented using Windows Workflow Foundation as a WCF service. A Silverlight application to poll a service for the latest data feeds.

While creating such applications was possible prior to the existence of WCF, WCF makes the development of endpoints easier than ever. In summary, WCF is designed to offer a manageable approach to creating Web services and Web service clients. Features of WCF WCF includes the following set of features. Service Orientation One consequence of using WS standards is that WCF enables you to create service oriented applications. Service-oriented architecture (SOA) is the reliance on Web services to send and receive data. The services have the general advantage of being loosely-coupled instead of hard-coded from one application to another. A loosely-coupled relationship implies that any client created on any platform can connect to any service as long as the essential contracts are met. Interoperability WCF implements modern industry standards for Web service interoperability Multiple Message Patterns Messages are exchanged in one of several patterns. The most common pattern is the request/reply pattern, where one endpoint requests data from a second endpoint. The second endpoint replies. There are other patterns such as a one-way message in which a single endpoint sends a message without any expectation of a reply. A more complex pattern is the duplex exchange pattern where two endpoints establish a connection and send data back and forth, similar to an instant messaging program . Service Metadata WCF supports publishing service metadata using formats specified in industry standards such as WSDL, XML Schema and WS-Policy. This metadata can be used to automatically generate and

configure clients for accessing WCF services. Metadata can be published over HTTP and HTTPS or using the Web Service Metadata Exchange standard. Data Contracts Because WCF is built using the .NET Framework, it also includes code-friendly methods of supplying the contracts you want to enforce. One of the universal types of contracts is the data contract. In essence, as you code your service using Visual C# or Visual Basic, the easiest way to handle data is by creating classes that represent a data entity with properties that belong to the data entity. WCF includes a comprehensive system for working with data in this easy manner. Once you have created the classes that represent data, your service automatically generates the metadata that allows clients to comply with the data types you have designed. Security Messages can be encrypted to protect privacy and you can require users to authenticate themselves before being allowed to receive messages. Security can be implemented using well-known standards such as SSL or WS-SecureConversation. Multiple Transports and Encodings Messages can be sent on any of several built-in transport protocols and encodings. The most common protocol and encoding is to send text encoded SOAP messages using is the HyperText Transfer Protocol (HTTP) for use on the World Wide Web. Alternatively, WCF allows you to send messages over TCP, named pipes, or MSMQ. These messages can be encoded as text or using an optimized binary format. Binary data can be sent efficiently using the MTOM standard. If none of the provided transports or encodings suit your needs you can create your own custom transport or encoding. For more information about transports and encodings supported by WCF see Transports in Windows Communication Foundation. Reliable and Queued Messages WCF supports reliable message exchange using reliable sessions implemented over WS-Reliable Messaging and using MSMQ. For more information about reliable and queued messaging support in WCF see Queues and Reliable Sessions. Durable Messages A durable message is one that is never lost due to a disruption in the communication. The messages in a durable message pattern are always saved to a database. If a disruption occurs, the database allows you to resume the message exchange when the connection is restored. You can also create a durable message using the Windows Workflow Foundation (WF). For more information, see Workflow Services. Transactions WCF also supports transactions using one of three transaction models: WS-AtomicTtransactions, the APIs in the System.Transactions namespace, and Microsoft Distributed Transaction Coordinator. For more information about transaction support in WCF see Transactions.

AJAX and REST Support REST is an example of an evolving Web 2.0 technology. WCF can be configured to process "plain" XML data that is not wrapped in a SOAP envelope. WCF can also be extended to support specific XML formats, such as ATOM (a popular RSS standard), and even non-XML formats, such as JavaScript Object Notation (JSON). Extensibility The WCF architecture has a number of extensibility points. If extra capability is required, there are a number of entry points that allow you to customize the behavior of a service. For more information about available extensibility points see Extending WCF.

Creating sample WCF Service Libaray

1.Open visual studio web developer 2.Choose WCF and WCF Service application

Iservice Interface

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together. [ServiceContract] public interface IService1 { [OperationContract] string GetData(int value); [OperationContract] CompositeType GetDataUsingDataContract(CompositeType composite); // TODO: Add your service operations here }

// Use a data contract as illustrated in the sample below to add composite types to service operations. [DataContract] public class CompositeType { bool boolValue = true; string stringValue = "Hello "; [DataMember] public bool BoolValue { get { return boolValue; } set { boolValue = value; } } [DataMember] public string StringValue { get { return stringValue; } set { stringValue = value; } } }

Operation contract
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together. public class Service1 : IService1 { public string GetData(int value) { return string.Format("You entered: {0}", value); } public CompositeType GetDataUsingDataContract(CompositeType composite) { if (composite == null) {

throw new ArgumentNullException("composite"); } if (composite.BoolValue) { composite.StringValue += "Suffix"; } return composite; } }

Running WCF SERVICE

WCF End point support ABCs OF WCF 1. 2. 3.


address binding

contract <endpoint address ="" binding="wsHttpBinding" contract="WcfServiceLibrary2.IService1"> <!-Upon deployment, the following identity element should be removed or replaced to reflect the identity under which the deployed service runs. If removed, WCF will infer an appropriate identity automatically. --> <identity> <dns value="localhost"/> </identity> </endpoint>

"A" stands for Address: Where is the service? "B" stands for Binding: How do I talk to the service? "C" stands for Contract: What can the service do for me?

"A" stands for Addressas expressed in the wsdl:service section and links wsdl:binding to a concrete service endpoint address. "B" stands for Bindingas expressed in the wsdl:binding section and binds a wsdl:portType contract description to a concrete transport, an envelope format and associated policies. "C" stands for Contractas expressed in the wsdl:portType, wsdl:message and wsdl:type sections and describes types, messages, message exchange patterns and operations.

Defining Service Contracts Ex :


using System.ServiceModel; [ServiceContract] public interface ICalculate { [OperationContract] double Add( double a, double b); [OperationContract] double Subtract( double a, double b); }

Defining Data Contracts Ex:


[DataContract] public class Person { [DataMember] public int Id; [DataMember] public string FirstName; [DataMember] public string LastName; }

Implementing Services
public class maths : ICalculate { public double Add( double a, double b) { Return a+b; } double Subtract( double a, double b) { Return a-b; } }

Choosing and Configuring Bindings


<?xml version="1.0" encoding="utf-8" ?>

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <system.serviceModel> <services> <service serviceType="SelfHostedService.People"> <endpoint address="http://localhost:8080/people" bindingSectionName="basicProfileBinding" contractType="SelfHostedService.IPeople"/> </service> </services> </system.serviceModel> </configuration>

LINQ- Language-Integrated Query


.NET Language-Integrated Query defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language

Ex:
using System; using System.Linq; using System.Collections.Generic; class app { static void Main() { string[] names = { "Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David" }; IEnumerable<string> query = from s in names where s.Length == 5 orderby s select s.ToUpper(); foreach (string item in query) Console.WriteLine(item); } }

Sorting and Grouping


string[] names = { "Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David" }; // unity sort var s1 = names.OrderBy(s => s); var s2 = names.OrderByDescending(s => s);

// sort by length var s3 = names.OrderBy(s => s.Length); var s4 = names.OrderByDescending(s => s.Length);

string[] names = { "Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David" }; var s1 = names.OrderBy(s => s.Length).ThenBy(s => s);

GroupBy

string[] names = { "Albert", "Burke", "Connor", "David", "Everett", "Frank", "George", "Harris"}; // group by length var groups = names.GroupBy(s => s.Length); foreach (IGrouping<int, string> group in groups) { Console.WriteLine("Strings of length {0}", group.Key); foreach (string value in group) Console.WriteLine(" {0}", value); }

SelectMany
string[] text = { "Albert was here", "Burke slept late", "Connor is happy" }; var tokens = text.Select(s => s.Split(' ')); foreach (string[] line in tokens) foreach (string token in line) Console.Write("{0}.", token);

Query Syntax
IEnumerable<string> query = names .Where(s => s.Length == 5) .OrderBy(s => s) .Select(s => s.ToUpper());

IEnumerable<string> query = from s in names where s.Length == 5 orderby s select s.ToUpper();

Join
var query = from n in names join p in people on n equals p.Name into matching select new { Name = n, Count = matching.Count() };

LINQ to SQL: SQL Integration

Steps to to Linq to sql: 1.RC-Project Explorer Choose Linq to sql Class:

2.Choose DataExplorer

3.Configure the database throug DataExplorer

4.Drag and drop the table to query

5.Querying from form


private void cmd_Query_Click(object sender, EventArgs e) { DataClasses1DataContext dbcls = new DataClasses1DataContext(); dg_data.DataSource = dbcls.ClientInfos; }

Das könnte Ihnen auch gefallen