Click here to Skip to main content
15,881,852 members
Articles / Web Development / ASP.NET
Tip/Trick

ASP.net QuickSet of 12 Tips and Tricks

Rate me:
Please Sign up or sign in to vote.
4.66/5 (29 votes)
31 Jul 2011CPOL37 min read 69.7K   36   25
I do not claim that this piece of writing is going to be something new but a very short combined set that can get someone going with ASP.net in no time.

Events Life Cycle


Instructions: Go to the code behind view of an ASP.NET page. In the left menu of the page, select PageEvents and on the right side, we get all available events for the page.

Unload Event: Page is already rendered, so no new changes are not possible to make to the page. If we write something like Response.Write, we get an exception because the page is complete. This event is used to do all the wrap-up jobs like if a file is opened by the page, we can close it here etc.

PreInit Event: This is the first event that is raised by an ASP.NET page. We check if the request for the page is a postback or not, using the Page.IsPostBack property. If the request is a postback, the controls available on the page haven’t been reconstituted yet because Page PreInit event is a very early stage of page event lifecycle. We can do the following in this event: Setting things that are global to the page. Set the master page or theme property of the page dynamically based on the geography or time or date. Setting the profile property using the ASP.NET profile system. Dynamically add/reconstitute controls to the page.

Init Event: Gets fired after all the controls in the page gets initialized and any skin settings have been applied to the controls. We can read or write any specific control properties.

InitComplete Event: Gets fired when all initialization of the page and its controls are done. If we have to implement some logics that depend on the controls in the page to be initialized, this is the right place to do so.

PreLoad Event: Do any processing on a page or on its controls before the page gets loaded. First the page preload event gets fired and after that, preload events for all page controls get fired. After this, the viewstate gets initialized and all of the postback data get initialized from the request object.

Load Event: All the OnLoad events get fired for each and every control in the page. All other control specific events e.g. TextChanged event of a text box are ready to get fired from this point onward.

LoadCompleteEvent: By this stage, all the validation of the page is completed if any validation controls are implemented on the page. We can implement validation for all other child controls on the page, in this event.

PreRender Event: Each control has its own PreRender event. Before this page PreRender event gets fired, all other control specific PreRender events get fired. We can make any final changes necessary to the page or its controls before the page is completely turned into HTML for sending down to the browser.

SaveStateComplete Event: Before it gets fired, the VIEWSTATE for the entire page and for all the controls of the page is saved. Any changes that are made to the state of the page and for the controls in the page will simply be ignored from this point onward thus they will not be converted to HTML and sent to the browser. Implement any logic that requires VIEWSTATE to be completed i.e. any logic that does not require the page to be rendered differently. After this event is fired, the page is rendered. When the page objects are created, the Render methods are called automatically and that’s when the rendering takes place. There is no separate render event handler.

Server Controls


Label Control: In design view, drag and drop or double click on the label control in the toolbox. In source view, place the cursor in the appropriate position where I want the label control code to be inserted and then double click on the label control in the toolbox. We can also drag and drop. A asp:Label tag will be inserted with proper attributes and initialization.

Button control: Adding is same as the label control. Properties are as follows - Text: The text that is to be viewed on the button for the user. CssClass: If a Style Sheet is attached to our page document and it has got some CSS classes declared, we can link out control to one of those CSS classes using this property in the property window through a dropdown list of available CSS classes. OnClientClick: To handle client side click event (using JavaScript). So, we can implement both server side and client side click event handler for a button. (Expressions): Database expressions like data binding etc. ToolTip: The text we insert here will be shown when the mouse cursor is placed over the button control but the mouse button is not down.

Events: Access using the bolt sign in the properties window. To generate an event handler for the click event, double click on the Click event listed in the properties window. Double clicking the control in design view will open the default event handler in code behind. TextChanged event fires whenever there is any text change in text box.

Submit and Postback


Button and any other controls that are parts of ASP.NET have a prefix ‘asp:’. In the <form> tag, the attribute ‘runat’ is specified is as ‘server’. Investigating the source of a running ASP.NET application page: In the <form> tag: The method is post and the action is Default.aspx (given the page we are viewing is named as Default.aspx). There are couple of hidden input types which has names of VIEWSTATE and EVENTVALIDATION. VIEWSTATE and EVENTVALIDATION will be covered later. As we have included one text box and one button during development, there are two input fields having the same name we chose for out text box and button control during development. The textbox has an input type of Text and the button has an input type of ‘submit’. ‘submit’ is a special type of input type which causes a form submission to the server and server causes a postback.

Explaining postback: Create a button event hander and a Page Load event handler. Put no logic for the button event handler and place TextBox1.Text = System.DateTime.Now; in the page load event handler. When we click on the button now at runtime, we will see that the textbox time display is changed even though there is no button handler logic implemented. This happens because in order to execute that button click event handler, the postback has to happen and whenever the postback happens, the page load event gets fired before the page is reconstituted.

Executing server side logic before the form submission is completed by the user: Create a dropdown list and add some item using the handy task editor. In the property window for our dropdown list, set the AutoPostBack property to ‘true’. Now running the application, whenever user will choose any item from the dropdown list, the page will be refreshed and server will cause a postback automatically even though the submission of the form was not performed through the submit button.

Investigating the page source again: Additional hidden input types such as EVENTTARGET, EVENTARGUMENT and LASTFOCUS are there which will be automatically posted back to server so that we can have the additional information about our page. EVENTTARGET will tell us which control on the page is responsible for causing that postback. The dropdown list has been converted to basic <select> tag. The submit tag is wired to the javascript method dopostback.

The javascriptdopostback event handler: It explicitly calls the form to perform a submission because by default the form will be submitted only when the button will be clicked. This has to be done because we want the dropdown list to submit automatically. Also, the method sets the hiddeninput types’ values property so that we can know which control is causing the postback.

Handling postback manually without using ASP.NET auto generated codes (by writing code): Write javascript for postback event handling. Insert a ASP.NET text box. In page load event handler, set text box’s text property to the current server machine time. Add an HTML button and set its onclick event handler attribute to our written javascript event handler. Run the project and we are good to go!

Application Level Objects


Scope:

  1. Geographical: A given element of our software code is visible to certain areas of our code and not visible to other areas of out code. Example: If an integer variable is declared inside a class as private, it’s not available or visible outside that class i.e. other objects cannot access this integer variable.
    • Chronological: It decides how long does an object live and accessible within our code. Example: When we create an instance of a class, that object is stored in the memory and the address is referenced by the instance variable. When that reference is removed from that object, that object becomes collectible by the .NET framework garbage collector. This object will be cleared from the memory as soon as the garbage collection takes place. So, having an object referenced by the reference variable inside our code is its chronological scope.

Application Level Objects: Events, Event handlers and Variables.

Working with Application Level Objects: Add New Item -> Global Application Class (file name e.g. global.asax) -> Add. The given event handlers have exclusive names and are designed to be automatically wired to the proper events by ASP.NET; so they do not need to be specified separately which events they are going to handle.

Three event handlers for Application Level Events: Application_Start fires when your application that is not yet running and is initialized for the first time. When and application is ready to serve on the server machine but no user has yet made any request for that application, our application is not consuming any memory. When a user request is made for that application (for any page for example), the application actually starts and gets loaded into the memory. Exactly at the beginning of that point, this event gets fired.Application_End: Conversely, when an application gets removed from the memory (in other words, when the application ends), this event gets fired. There is a Time Out period and during that period, an application will stay active in memory without servicing any request. When the time out period gets expired, the ASP.NET runtime will decide to remove it from the memory. Application_Error: Generally, all the errors should be handled separately following the proper error or exception handling mechanism. But in production development environment, there might be a chance of slipping some errors which remains unhandled. If you implement a global error handler for the entire application, those types of mistakenly unhandled errors will be handled here.

Usage of Application_Start Event Handler: Anything we need to prepare the application for execution. Implementing Page Hit Count functionality: Create an application level variable called PageHitCount and initialize its value using zero inside the Application_Start event handler.
Application["PageHitCount"] = 0;

Application level variables are stored as dictionary values. Create a page load event handler and inside that handler, increment the previously created application level variable by one. So, each time the page gets loaded because of a user request for that page, the PageHitCount variable will be incremented by one thus serving our purpose.
Application["PageHitCount"] += 1;

Insert a label control and set its property to PageHitCount’s value inside the page load event handler.
Label1.Text = Application["PageHitCount"];

Request for the page from different browsers and the label will show that each time the page hit count is getting incremented. In short, Application level objects span across all of the sessions and all of the users in an application.

Session Level Objects


When we need objects specific to users and we need them to survive in between the consecutive page requests, we use Session level objects. Session level objects have Events, Event Handlers and Variables just like the Application level objects. Usually when an ASP.NET resource is requested by the user, a page for example, it’s represented by a .NET class. That class might have some variables and objects of its own. Anything which is included in that resource such as images, JavaScript codes, or some other variables gets settled down to the browser on client side in response to the request. After that, ASP.NET runtime removes those objects from the memory and frees the resources. So, those objects do not last until the next request. In case we need our objects to last until the next request, we need to use Session objects.

Using Session Objects:

Implementing a Session Hit Counter: Create a session level variable called SessionHitCount and initialize its value using zero inside the Session_Start event handler.
Session["SessionHitCount"] = 0;

Create a page load event handler and inside that handler, increment the previously created session level variable by one. So, each time the page gets loaded because of a user request for that page, the SessionHitCount variable will be incremented by one thus serving our purpose.
Session["SessionHitCount"] += 1;

Insert a label control and set its property to SessionHitCount’s value inside the page load event handler.
Label1.Text = Session["SessionHitCount"];

Request for the page from different browsers and the label will show that the counter is starting from 1 each time we are requesting from a different web browser.

Debugging


There are two ways of running an ASP.NET application in VS 2008. Without using the Debugger: Should be used when we need to see exactly how the application will run in the production environment for the end user. Menu Bar -> Debug -> Start Without Debugging or press Ctrl + F5. Using the Debugger: Should be used when we need to test our project and find out where the errors or bugs are. Also, to know what exactly the errors are. Menu Bar -> Debug -> Start Debugging or press F5 The warning message will tell us if we want to enable the debugging in web.config file or we want to run the application without enabling the debugger (equivalent to pressing Ctrl + F5). If we enable debugging by pressing OK or by modifying the web.config file manually, we should turn the debugger off in that file before we deploy the application to the production environment.

Enabling debugging manually: Open web.config file in Visual Studio. Look for the <Compilation /> tag. There is an attribute called debug which is currently set to false. Change the attribute value to true to enable debugging in our application.

Breakpoint: What is it: A breakpoint is an indicator to a particular line of code up to which the execution will run normally and when the breakpoint is reached, the application execution will be frozen until it’s told to step into the next line code or continue running the rest of the application. Setting a breakpoint: Place the cursor on the line for which I want to set the breakpoint and then Menu Bar -> Debug -> Toggle Breakpoint or simply press the F9 key. Click the left hand side of the source editor beside a line of code to set a breakpoint for that particular line.

Deleting or disabling a breakpoint: Pressing the F9 key or clicking on the Toggle Breakpoint again will delete the breakpoint. Clicking on the red ball (which indicates the breakpoint) again will delete the breakpoint. Right clicking on the red ball will disable the breakpoint (but will not delete it). This is just to remember that here we might need a breakpoint again in future.

Breakpoint in action: When a breakpoint is set and we run our program, after the breakpoint is reached, the program will pause execution and come back to the code window. There on the breakpoint red ball, we will see a yellow arrow to indicate that this is the current line of code that is about to be executed.

Stepping Mechanisms:

Step Into: Execute the next line of code but if that line is a method call, then go to the definition of that method and execute the codes written into that method one by one. Menu Bar -> Debug -> Step Into or press F11

Step Over: Execute the next line of code but if that line is a method call, execute the whole method at a time and start executing the code after the method call line by line. Menu Bar -> Debug -> Step Over or press F10

Step Out: If we accidentally stepped into a method but we actually intended to step over, we should use Step Out mechanism. Execute current method call at a time and then come right back exactly to the previous line of that method call. Debug Toolbar -> Step Out or press Shift + F11

Skipping executing a line of code: A yellow arrow always indicated the line is about to be executed. We simply need to drag the arrow to the next line to skip the current line from execution.

Call Stack Window: Represents/keeps track of the stack of calling methods during the execution. For example, sometimes we might call method from within a method from within a method. The call stack will tell us about the stack of method calls for the current line that is being executed.

Output Window: This output window is for Visual Studio to tell us about some actions that are being performed by it. For example, it is loading some assembly from the Global Assembly Cache (GAC) or some other customized DLL’s. This output window works as a live log for all the actions of Visual Studio during the execution of the assembly.

Locals Window: Contains all of the objects and information within those objects that are available to the current level of execution within our application. Expanding an object using the plus (+) sign beside it will show all the properties that are available for that object. Those properties can be changed during the debugging session and we can see the output accordingly.
The property that is changed during the debugging session will be indicated by Red color. The default visualizer is Text. There are two other visualizers – XML and HTML. We can use those visualizers to see our property change effect in XML or HTML format.

Watch Window: If we want to watch the value and behavior of a particular control’s particular property during the debugging, we can always do that using the locals window but the process of finding our desired control and property might often get very tiresome and irritating. We can overcome the problem using this Watch window. We simply need to drag and drop a property or a control from our code to the Watch window and the details debugging view for that control or property will be available for us immediately.

Immediate Window: We can write code in this window and make the necessary changes to experiment during the debugging session. This window also gives the intellisense support as well as the error detection by the compiler.

Intellisense in Debugging: Put the mouse pointer over the highlighted area of our currently to be executed code line. The properties will be shown by the Visual Studio with an plus (+) sign which indicates that we have full editing/experimenting support over here as well just like we got it in Locals and Watch windows.

ASP.NET Tracing: When the application is running in a production environment, we cannot use debugger and breakpoints because the user will be frozen when they will reach those breakpoints. But we still need to track if our product has any kind of bugs within. There comes the need for Tracing.

Using tracing: Click Menu Bar -> Website -> ASP.NET Configuration. In the new browser window, click on Application Tab and then click on Configure Debugging and Tracing. Check – Capture Tracing information and Display tracing information on individual pages. Select Display trace output for – Local Requests Only. Tracing information will be shown only when a request will be made by the server machine itself (on which the site resides). All Requests. Tracing information will be shown to everyone whenever a request for a page is made.

Leaving ‘Capture Trace Information’ checked and ‘Display tracing information on individual page’ unchecked will result in showing no trace information on our requested pages – no matter the request is made by local server or client machine. But we can always see the trace information that our website is currently experiencing simply by putting this into our browser Address Bar: http://BaseWebsiteAddress/trace.axd. After that, overall Trace information will be shown. We can click on the View Details hyperlink for each of the request and investigate the actions that were performed by our website.

In our code, we can write Trace.Write(“Some tracing.”); and we can find it in our trace information in trace.axd file. This is useful because we can put these Trace.Write statements in the problematic areas of our application so that we can find out exactly where the application has a bug. These Trace.Write statements work as the breakpoint in production environment because we are not allowed to put breakpoints to pinpoint out problem but these trace statements can certainly help us doing so.

Exceptions and Error Pages: When we run our application in Debugging environment and an exception occurs, the Visual Studio Debugger catches the error and shows - The main error message. The reason for this error message, if known. Some troubleshooting tips. Online help links etc. When our application does not run in production environment (or runs without debugging) and an error/exception occurs - The ASP.NET runtime generates an error message and Shows it on the page with ugly and unfriendly technical details.

Creating and viewing a custom and nice error page: Add a page to the project. Name it ErrorMessage.aspx or something similar. Put a nice and friendly error message on this page. Go to Menu Bar -> Website -> ASP.NET Configuration. Click on Set Default

Error Page: Change the radio button to choose the error page from the project files tree. Select the ErrorMessage.aspx page. Go to the web.config file and look for the <customErrors /> tag. Add an attribute called mode and set the value to “On”. Save and run the application without debugging. If an error occurs, the error page will be shown.

CSS


Download readymade CSS from www.oswd.org and www.freecsstemplates.org

An inefficient way of using styles: Add a label control to the form. Go to the properties windows of that label control. Change the property BakcgroundColor to red or blue for example. See the Source view and look for the change Visual Studio made automatically It’s inefficient because if we want to apply this back color to all of my label controls, we have to do this for all my controls separately.

The Style Toolbar in Visual Studio:

Style Application options: Auto, Manual

Target Rule: Auto CssClass, Inline. Apply New Style (we should use it most of the time)

Working with the Add New Style wizard: Select the control or place the cursor anywhere in the design view. From the combo box labeled as Target Rule in the CSS Toolbar, select Add New Style. From the combo box labeled Selector, we can choose any HTML element that might be available or added to our page

Three different style types:

Element: Named after any HTML element. Gets automatically applied to the related HTML element of that name.
ID: Naming can be anything meaningful. Starts with a #. Gets applied to the element or control of the page which has an ID name equals to our ID style
Class: Naming can be anything meaningful. Starts with a dot (.). The flexibility of defining a class is that it can be applied to any control having different ID names on the page just by assigning the class or CssClass property value to the name of the CSS Class.

Using an element style: Look up for the element ‘td’ in the Selector combo box. Change the background color to aqua. Click OK and the VS 2008 will tell me that the style was created successfully but will not be applied to any elements on the page. It says so because we have not added any td element to our page yet. From the toolbox under the HTML view, add a Table to the page. Each of the cells of the table will be filled with aqua color because we have an element style for the td element and the cell is defined by td element in the table. So, it’s getting automatically applied.

Using an ID style: Go to the design view and open up the Create New Style box. In the selector combo box, type in the name of the style: #SpecialTD. Change the background color to pink. Click OK. Add an ID attribute to one of the td’s in the table element and name the ID as SpecialID. That particular cell will now show a pink background. Those ID’s can be reused but it’s not a good idea because ID is used to identify a particular element. This creates a lot of confusion at the later stage of development.

Using a class style: Open the New Style window and in the selector combo box, write the class name as .MyCSSClass. Set the background color to yellow. Select the desired control or element to apply the new style on. In the Manage Styles window, right click on our newly created class style name and select Apply Style. The Class style will be applied to the selected element or control on the page.

Using CSS Properties window: In design view, when we click on a TD tag, the CSS properties window shows all the available properties for the TD element style. It also shows the scope of the styles and if it is inline or an element or an ID or a class. We can change each and every property in the property manager for styles. For example, choose the border style to be doubled in the property manager window. The result will be the table borders will show in doubled mode.

Using the Manage Styles window: From the options button, we can choose categorize the styles by types or two other options. If we choose that mentioned option, the available CSS styles will be shown in three categories – Elements, ID’s and Classes. The blue dots are for elements and the red dots are for ID’s. If there is a gray circle around the dots, it means that the style is being used by some element on the page.

We can always keep our styles classes, ID’s and elements to a separate file which has an extension of .css and will have to be referenced by the current document in which we want to use those styles on different controls and elements. Add New Item -> MyStyleSheet.css -> OK. Add desired class, element and ID styles to that file. In the Manage Styles window, click on Attach Style Sheet and select the style file from the next prompt window. An alternative to this procedure is to drag the file from the solution explorer and drop it to the <head> section of the web page. Right click on a particular style name and select View code to see the code for that style. Right click in the same way and click on Select all n related elements (n = any number which represents the number of elements that are using the style). And VS 2008 will select only those elements which are using that particular style. If we want to use the Style creator window instead of working with the code directly, we have to right click on the style and choose Modify Style.

Master Pages


If our website has some common portion on each and every page, we should create a master page to hold those contents and make other page derive from that master page. The concept of master page can be farther extended to nested master page. Sometimes we might need a common set of contents for the whole site and some other contents which are not common to the whole site but a portion of the site. In that case, we would create a parent master page to hold the global contents and create another master page which will derive from that parent master page and will define other common contents which are common to portion of the website.

A demonstration of nested master pages: Download a readymade CSS from Open Source Web Design .org (www.oswd.org). Copy that CSS file to our project solution explorer. Add New Item ->MasterPage.master -> Rename it to SiteMasterPage.master -> OK. In source view of the master page, link the CSS file to the page by dragging and dropping the file to the <head> section of the page.

Investigating the default master page source: It looks like a normal ASP.NET page. Only thing that is new here is 2 content place holders – one in the head and another one is in the body of the master page. These content place holders are provided so that the asp.net pages that will derive from this master page can place new contents modify it according to their need inside the content place holders. Any other sections are not modifiable to the deriving pages. We do not need the content place holder inside the <head> so we delete that one. Rename ContentPlaceHolder1 to MenuContentPlaceHolder. Open the index.html in Edit mode with Microsoft Expression Web and copy the links, headers, and menu items portion of the page. Paste the copied script to the master page at the top of the form right before the default <div> started. Copy the footer section of the index.html and paste it after the default <div> ended. Add new item ->WebForm -> Check the box called Select Master Page -> In the master page selection window, select SiteMasterPage.master -> OK. In the source view of our newly added page, we find the MasterPage attribute in the first line of the script which says that this page derives from that particular master page. Another element comes with this page is the Content element which has an ID of its own and another ContentPlaceHolderID with the value we gave to our master page’s content place holder. This means that we can add multiple content elements to our page and there might be multiple content place holders in our master page and we can tell each of our content elements which content place holder it should be placed in.

Rename the content element ID to DerivedContent and put some code inside it e.g. <center><br /><br /><br />Hello World!</center> Run the application and we will see that the page looks like our master page and in the place where the content place holder was put in our master page, we can see the content added by our asp.net webpage. Delete the sample page so that we can create a nested master page from ground up. Add new item ->MasterPage -> Rename it to MenuMasterPage.master -> Select master page check box checked -> Select the master page from the selector window -> OK In our nested master page, we have a content element which has a content place holder ID of our parent master page’s content place holder. Copy the left menu script from that index.html page and paste it to the content element. Place a content place holder to our nested master page so that the pages that will derive from this master page can place contents of their own. Place this content place holder inside the <div> which was created to place the main body portions of our website pages. Rename the content place holder to MainContentPlaceHolder. Now derive a new page from that nested master page and put some contents into that content element. Run the web project.

SOAP Web Services


Creating a web service: From the templates , choose ASP.NET Web Service. Choose the location as HTTP. Change the location to http://localhost /MyWS. Choose your preferred language and click on the OK button.

Examining the solution explorer: Instead of a ASPX page, we have a ASMX page. In the App_Code folder, we have a C# code file called Service.cs; There is a App_Data folder because web services might use database

Investigating the Service.cs file: Required namespace declarations are System.Web.Services and System.Web.Services.Protocols. Some attributes are declared which contains the web service namespace which is supposed to be the URL which located the server location where the web service can be accessed. The Service class inherits from the WebService class. There is a sample method which is decorated with the [WebMethod()] attribute. This attribute tells the .NET framework that the method is going to be called as a web service.

How ASP.NET Web Services are easier to develop: Just using the single WebMethod() attribute, we are handing over the duty of doing all the hard work to ASP.NET framework. In a web service, the data needs to be passed back and forth through the HTTP but in our code we are simply using the .NET framework data types. Behind the scene, ASP.NET serializes the data our of the objects whatever type it is into something that can be streamed into byte stream over HTTP. While receiving the data, it gets some byte streams and then converts into the appropriate ASP.NET data type.

Creating a method of our own: Change the HelloWorld method to something else e.g. ShowGreeting. Add a string type parameter called username. In the return statement, change the return value using the username variable. Run the application. Click on the ServiceDescription link which will show an XML definition of our web service. This definition describes what our web service takes as parameter, what is the return value etc. This is called WSDL (Web Service Definition Language). Mainly this WSDL file is given for the client so that they can figure out how to deal with our web service. Click on the ShowGreeting link to use the web service we just created. This will present us a textbox labeled as username since we used a parameter called username of string type. Type a name in that textbox and click on the Invoke button. We will be presented with another XML file with the return value of our web service method.

Creating a Web Service Client: The client application or the consuming application (which will consume the web service) can be any type of application - Web application, Windows Forms application, Console application, Windows service, WPF application, For a demonstration, let’s create an ASP.NET web application, Name it MyWSClient or something you like. Add a textbox (for taking the username from the user and pass it to the service), a button (for submitting the form and call the web service) and a label to show the value (greeting) which will be returned by our web service. Go to the button click event handler of the button we added. Here we need to create reference to our SOAP web service. Right click on the project name in the solution explorer and click on Add Web Reference. In the URL input text box, we can type in the HTTP URL directly in case the service is not on our own machine. There are other options to refer to a web service like a web service in the current solution and a web service on local machine etc. Click on the web service on local machine link and the next page will offer us all the services that are available on our machine. Choose MyWS one. On the right side of the window, change the reference name to something you like and click on the add reference button. In the solution explorer, VS 2008 creates a new folder called Web_References and under that folder we can see two files grabbed and added automatically - Service.wsdl tells what is the object definitions and the input and output expectations of the web service method. Service.disco tells the VS 2008 what services are available on that server that I pointed to so that I can program against those services. VS 2008 uses the WSDL file to offer intellisense. In the button event handler, create an instance of the web service; name it myService. Type in Label1.Text = myService.ShowGreeting(TextBox1.Text). Run the application. Whatever value we will now type into the textbox, there will be a postback and after that we will see that the label control will show us the value returned by our web service method.

AJAX


AJAX Service Method call: Create a web application and name it HelloAJAX. In this example, we will call the service from our web browser using the JavaScript code instead of using our server side event handling for button click event. Sometimes we need to call the service method from multiple applications and we need a separate and independent web service. But creating services for a specific application is also a common scenario. In that case, we create the service ASMX file within our web project solution which will use that service. Right click on the project name in the solution explorer and click on add new item -> choose web service -> rename it as wished. In the auto created C# code file Service.cs, do the same thing as we did in our previous lesson.

SOAP Web Services: On top of the class definition we need to add the following attribute so that we can call this web service method using the JavaScript:
[System.Web.Script.Services.ScriptService]

This attribute tells the runtime that the method those are inside this class are to be called using JavaScript Now in our application and in the Default.aspx page, add an HTML textbox, an HTML button and a <div id=”CallResponse”></div> tag. Double click on the HTML button to let the VS 2008 create the button click JavaScript event handler. All ASP.NET AJAX application development use the ScriptManager control for telling the JavaScript code where all the resources are and from where it should get the necessary information. Inside the <body> tag and on top of the event handler, insert a ScriptManager. We need to tell the script manager that we are going to use that service we just added to our application. To do so, add a Services element within that ScriptManager definition. Add a ServiceReference element and set the path. We could pick any URL for our path value and this URL can be directly an address to a web server where service is located. In our case, since we have added a service within our application, this is shown by the VS 2008 intellisense system automatically to set the path attribute value of our ServiceReference element. Inside our JavaScript button event handler, we put the following code:
Ret = WebService.ShowGreeting(document.getElementById(‘Text1’).value, onComplete, onError);


The web service method that we are calling is on the server and we are using the JavaScript proxy method to call that method. This proxy method expects the second and the third parameter that we specified – on complete method and an on error method. Implement the onComplete and the onError java script methods:
Function onError(arg) { alert("Sorry. Error occurred"); }
Function onComplete(arg) { document.getElementById(‘CallResponse’).innerHTML = arg; }

The error method is simple and straightforward. The complete method gets called when we have successfully called our web service and got the appropriate result as output. If that happens, the argument arg of onComplete method contains that web service method returned output. We simply need to assign that output to our CallResponsediv’s inner HTML property. Run the application and it will give us the web service output without refreshing the page.

Validation


Validation is checking for the correctness and validity of input data provided by the user through a web form. This is important to validate the data using JavaScript as well as Server side scripting logic because it’s not too difficult for hackers to bypass the JS validation and posting something invalid or harmful to the backend i.e. application server.

Visual Studio ASP.NET validation controls provide both JS and server side validation by default and without writing a single line of code, we can make sure that the user is providing with valid data through our web form.

Demonstration of the necessity these validation control in an ASP.NET web page: Create a sample comment form. Used ASP.NET form controls are- Name (textbox), Email Address (textbox), Subject (textbox), Comment (multiline textbox), Click Here to Submit (Button), Notification (after the user submits the form – a label), In the button click event handler, set the text property of the label control to “Your Comment has been Submitted”. Run the application and click the button without giving any input. The server says through the label control that the form has been submitted.

The problem is that the forms gets submitted with invalid data. The reason is that we did not do anything to check if the data is valid or not. Here the ASP.NET validation controls come into action.

Using the validation controls in ASP.NET for our previous scenario: In the toolbox, scroll down and find the Validation controls group. Drag the required field validator to the right side of each of the textboxes and drop. Change the following property of the required field validator for our TextBoxName- ID: Change it to RequiredFieldName. ControlToValidate: Select the TextBoxName from the combo box list. ErrorMessage: Name field is required!

Similarly configure other required field validators on the form for other textboxes. Run the application and try to submit it without entering any data again. This time the problem is solved and we don’t get the page submitted to the server and the JS validation tells the user the messages we set for the ErrorMessage property. A slightly more advanced validation technique (regular expression validator): There is still a problem. When we enter an invalid email address, it still submits correctly and shows us the success message on the label control. Drag and drop the regular expression validator beside the TextBoxEmail control. Change the following property of the regular expression validator- ID: RegExEmail, Error Message: The email address is invalid. ControlToValidate: TextBoxEmail. ValidationExpression: Click on the button beside this property value field -> In the regular expression editor, choose internet email address regular expression (which is predefined and given as a template by the VS 2008). Run the application and test it entering an invalid email address.

Login


Configuring the security using the ASP.NET Configuration: Menu -> Website -> ASP.NET Configuration. Click on the Security tab to set the security provider. Current authentication type is Windows. Below that statement, there is a link called Select Authentication Type. Click on it. Choose from the internet option. On the next page, in the first box from left side of the page, click on the Create User link. This opens up the new user creation form. Provide all necessary data and click on the Create User button. If everything goes well, the success message will show up

Using the Login controls in ASP.NET: From the toolbox, find the Login controls collection. Drag and drop a login view control onto the master page so that every page shows this login view. Inside the LoginView definition, add one AnonymousTemplate and a LoggedInTemplate definition. Inside the AnonymousTemplate definition, insert a Login control. So, the users who are not logged in will view the login control so that they can login to the site. Inside the LoggedInTemplate definition, we can put anything of our choice that we might want us logged in users to see. Inside the Default.aspx page which inherits from the master page, we insert another login view control in the content place holder. Just like the previous steps, add an Anonymous and a logged in control. Inside the anonymous definition, write something like – Please register on our website. Inside the logged in definition, write something like – We love our members. To give the user the option to log out from the site, insert a LoginStatus control right after the line – We love our members. Run the application and log in to the site using the username and password we provided to our ASP.NET configuration page. After logging in, we will see the Log Out option right after the ‘We love our members’ message.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Rapture Innovation
Bangladesh Bangladesh
Entrepreneur, Game Developer, Software Engineer, Academic, Writer, Photographer, Bassist, Lyric Poet & Music Composer.

Affiliation:

1. INETA • 2011
2. IET • 2011
3. ACM • 2006

Birthday: September 4

Awards:

1. Microsoft Imagine Cup • People's Choice Award • Worldwide Finals • 2011
2. Microsoft Imagine Cup • Champion - Bangladesh • 2011
3. Vice Chancellor Award • AIUB • 2009
4. 12th Year Celebration Award • Graphics Design (3D Animation) • AIUB • 2006
5. Scholarship of Merit • AIUB • 2004
6. Government Scholarship of Merit • People's Republic of Bangladesh • 2001

Email: me@niazmorshed.net
Phone: (880) 161 AhmedNM
Website: NiazMorshed.NET

Comments and Discussions

 
GeneralRe: I agree, too! Actually if I want to defend myself, I would s... Pin
Niaz Morshed31-Jul-11 21:11
Niaz Morshed31-Jul-11 21:11 
GeneralReason for my vote of 5 Great Article! Pin
Tech Code Freak7-Aug-11 6:31
Tech Code Freak7-Aug-11 6:31 
GeneralRe: Thanks! :) Pin
Niaz Morshed9-Aug-11 0:37
Niaz Morshed9-Aug-11 0:37 
GeneralReason for my vote of 1 Good one Pin
RajendranK4-Aug-11 18:59
RajendranK4-Aug-11 18:59 
GeneralRe: Your comment is "Good one" but you cast a vote of 1? Are you... Pin
Niaz Morshed7-Aug-11 3:25
Niaz Morshed7-Aug-11 3:25 
GeneralRe: Reason for my vote of 1Good one Pin
adriancs1-Nov-12 2:03
mvaadriancs1-Nov-12 2:03 
GeneralReason for my vote of 2 This doesnt seem to be quick or tips... Pin
NetSecurity1-Aug-11 8:21
NetSecurity1-Aug-11 8:21 
GeneralRe: As you can see that you are the only one to come up with thi... Pin
Niaz Morshed2-Aug-11 1:00
Niaz Morshed2-Aug-11 1:00 
GeneralReason for my vote of 4 Thanks! Good basic info here. No of... Pin
BrianBissell27-Jul-11 5:57
BrianBissell27-Jul-11 5:57 
GeneralRe: I think you got your answer in my previous reply. I will imp... Pin
Niaz Morshed31-Jul-11 21:12
Niaz Morshed31-Jul-11 21:12 
GeneralReason for my vote of 4 Examples would put this up to a 5...... Pin
BrianBissell22-Jul-11 9:17
BrianBissell22-Jul-11 9:17 
GeneralReason for my vote of 4 nice tips Pin
Member 42824319-Jul-11 8:41
Member 42824319-Jul-11 8:41 
GeneralRe: Thank you! Pin
Niaz Morshed20-Jul-11 12:08
Niaz Morshed20-Jul-11 12:08 
GeneralReason for my vote of 3 Not exactly a "quickset" Pin
MacSpudster18-Jul-11 10:25
professionalMacSpudster18-Jul-11 10:25 
Reason for my vote of 3
Not exactly a "quickset"
GeneralRe: Covering 12 features of ASP.net in a single tip. Maybe that ... Pin
Niaz Morshed20-Jul-11 12:07
Niaz Morshed20-Jul-11 12:07 
GeneralThis "QuickSet" isn't exactly a "quick" read. A better layou... Pin
MacSpudster18-Jul-11 10:24
professionalMacSpudster18-Jul-11 10:24 
GeneralRe: I agree, I tried to echo that in my comment. The formatting ... Pin
BrianBissell27-Jul-11 5:59
BrianBissell27-Jul-11 5:59 
GeneralReason for my vote of 4 A little brief in some explanations,... Pin
tsdragon12-Jul-11 11:08
tsdragon12-Jul-11 11:08 
GeneralRe: Very useful feedback. Thank you. I will keep that in mind. Pin
Niaz Morshed20-Jul-11 12:05
Niaz Morshed20-Jul-11 12:05 
GeneralReason for my vote of 5 Very Useful article on life cycle. Pin
kunal_shivalkar12-Jul-11 7:40
kunal_shivalkar12-Jul-11 7:40 
GeneralRe: Thank you! I am going to write a full article which will cov... Pin
Niaz Morshed20-Jul-11 12:05
Niaz Morshed20-Jul-11 12:05 
GeneralReason for my vote of 2 Simple Quickset. Pin
sankarlearns11-Jul-11 20:29
sankarlearns11-Jul-11 20:29 
GeneralRe: Maybe you forgot that this is not an article but a tip? :) Pin
Niaz Morshed20-Jul-11 12:04
Niaz Morshed20-Jul-11 12:04 
GeneralReason for my vote of 5 Nice Tips. Pin
Anurag Gandhi11-Jul-11 20:23
professionalAnurag Gandhi11-Jul-11 20:23 
GeneralRe: Thanks! You guys are my inspiration! :) Pin
Niaz Morshed20-Jul-11 12:04
Niaz Morshed20-Jul-11 12:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.