.Net, Web

AutoCompleteExtender with data from ASPX code behind

The auto complete functionality is a useful aid where suggestions are displayed when you type into a textbox. You would have come across this in many sites. Looking at how to implement this in an ASP.Net application using the AJAX control toolkit, it was not a complex task, as the great video tutorial here demonstrates. But the video (and many other articles on the web) showed how to use the auto complete extender hooked up to a ASMX file. Almost all the articles described how AJAX retrieves the auto suggestion text via a web service and displays them when the user types into the text box. But my need was to get the suggested text from the code behind of the ASPX file where the textbox was displayed. I needed the AJAX control to communicate with a method in the ASPX code behind, instead of a service. Documented in the following sections is how I got it working.

In case you don’t have the AJAX control toolkit downloaded and integrated with Visual studio, the video here shows how to obtain the toolkit, and set it up in the development environment. I used Visual Web developer 2010 express for the example given here. Opening up the IDE, create an ASP.Net web project and reference the AJAX control toolkit DLL. You can also create a new tab in the toolbox and add the controls to it by selecting the DLL (the steps to do this are in the same video link). Drag a textbox to the default.aspx page, this will be the textbox where the user will type in and get the autocomplete suggestions.

Switching to source view in default.aspx,drag a ToolkitScriptManager from the AJAX control toolkit tab in the toolbox into the source window:

You need a script manager when using the AJAX control tools. The script manager takes care of generating the code to communicate with the back end using AJAX  without doing a post back of the page. ASP.Net AJAX extensions already provide a script manager, but the ToolkitScriptManager inherits from this previous componenet, and is better in performance due to script combining.

Next, drag the AutoCompleteExtender control onto the source window. This will be the AJAX component that specifies which control in the ASPX page gets the auto complete functionality and how:

Some properties in the AutoCompleteExtender have to specified in order for the auto complete functionality to work, and these are shown in the below screenshot:

TargetControlID is the ID of the textbox to which the AutoCompleteExtender is connected. ServicePath and ServiceMethod are the web service path and web method respectively. But as we are retrieving auto complete suggestions from our default.aspx.cs code behind, the ServicePath is left empty, and the ServiceMethod ‘GetNames’ is the name of the static method in the code behind that will return the array of strings triggered by the AJAX request.

The code behind file, default.aspx.cs will contain the method that will return the array of strings to the AJAX control in the ASPX page. The method has to be declared static, and should be decorated with the ‘WebMethod’ and ‘ScriptMethod’ attributes. WebMethod is used to specify that the method is part of a service, and ScriptMethod is used to identify a method that AJAX can invoke. The complete code in the default.aspx.cs is given below:

Some specifics to note:

  • The ServiceMethod can have any name, but it should be declared static, and it should be decorated with the WebMethod and ScriptMethod attributes.
  • The parameters of the method should be ‘prefixText’ and ‘count’, of type string and int, respectively. They are case sensitive and cannot be changed to any other variable name. prefixText is the text we enter into the textbox, sent over by AJAX, and count is the number of characters typed in. They can be used in many ways, specially when retrieving string values from a database.
  • The method should return an array of strings. There are workarounds to return collections and key-value pairs, but they are out of the scope of this post.

When you debug the web application, you should see the auto complete functionality that you have wired up to your textbox, when you type in some text:

I had to type a minimum of three characters before the auto complete kicked in, but this minimum number of characters can be set in the AutoCompleteExtender control, using the ‘MinimumPrefixLength’ property. This basically covers the essentials needed for passing data to the auto complete AJAX control using a method from the ASPX code behind file, instead of  a Web service or WCF service.


Code contracts in DotNet 4.0

Microsoft research has come out with some new additions in the .Net 4.0 release, and one feature that caught my eye was code contracts. An earlier Microsoft research project dealt with a language called spec#, which is an extension of C# but with some added enhancements (http://research.microsoft.com/en-us/projects/specsharp/), code contracts being one of them. Now that code contracts are a feature of .Net 4.0, the .Net family of languages can benefit much in terms of secure and verifiable code (an article that explains how you can use this feature in code can be found here. The code contract constructs are found in the System.Diagnostics.Contracts namespace).

But my train of thought was not in the inclusion of code contracts in the latest release of the .Net framework, but on the origins of code contracts and contractual programming. Code contracts are derived from the concept of design by contract, a term invented by Bertrand Meyer and now a trademark of Eiffel software. Meyer created the programming language Eiffel to demonstrate design by contract and other concepts that helped create more secure software (secure as in stability and the ability to handle erroneous conditions effectively). The design by concept principle reflects the real world scenario of a publishing entity and a subscribing entity (or a ‘client’ and ‘supplier’ as described in Eiffel texts), where the subscriber receives from the publisher, and the publisher offers to the subscriber. The publisher has to make sure that the subscriber has fulfilled his or her part in the bargain in order to supply or sell. The subscriber has the benefit of receiving from the publisher, as long as his end of the bargain is kept. Both entities have to follow a common contractual set of rules in their transactions. This concept applied to programming is an overview of what design by contract is all about. Methods and classes need to provide preconditions, postconditions and invariants which stand as contractual bindings that have to be followed in the message passing scenario of the object oriented world. The Eiffel language enables design by contract design, and has more advanced extensions where contracts are inherited by sub-members of abstract types (more information can be found at http://www.eiffel.com/developers/design_by_contract.html).

The Eiffel language appeared commercially by the end of 1986. Design by contract is an old concept, but one that is showing positive signs of adoption from the day of inception. The .Net 4.0 feature of code contracts is one such sign, and hopefully the .Net community will utilize and benefit from this feature in writing secure code, taking the opportunity to practice a time tested principle in the complex world of software development today.


Breakpoint in global.asax is never reached by debugger in VS

Yesterday at work, I came across the situation where I had inserted a breakpoint to debug some code inside my global.asax file in a web application, but the VS debugger never reaches it.

The first indication of trouble came when some data values loaded during application start never changed, even after I manually changed the database records. After a clean/build in VS, the values changed to what I expected, and debugging the global.asax file became possible. But the next debug run show the values never change, and the code in global.asax is never reached. The initial thought that came to mind was that global.asax, where the application start events are fired, was acting very funny.

Reading up on this issue on the net brought up the overlooked fact that Cassini, the lightweight web server distributed with ASP.Net, does not close down after it has initially started, in order to increase performance the next time the application is run. This means that the application start events do not fire until the next time the web server process is restarted.

In essence, the problem I was facing was that each time I try to debug my global.asax file, if the application start events have already been fired and loaded, the code in the global.asax is skipped. Why it works when I do a clean/build is that cassini has to restart after each build. The direct workaround this is to go to the system tray, right-click on the cassini icon and select stop. Now the debugger can reach breakpoints inside global.asax next time the application is run.

Rather than manually killing the process each time you stop debugging, you can use the edit and continue option in VS. Enabling edit and continue does not kill the cassini process, but restarts it each time you debug the application. The option can be enabled in VS 2010 by selecting ‘debug’ in menu bar, and then option and settings:

If you are using IIS (as I was) to debug the web application, killing the cassini process will not help. In this case, you have to start the IIS manager, and check which application pool your web application has been assigned to. Once you know the application pool, right clicking it and selecting advanced settings brings up the window shown below:

In this case, the idle time-out sets the time limit for the worker process to shut down. Changing the time to zero would disable the setting, and each time requests come in, the web application would load its application settings anew. If you do not want to change the setting, the alternative would be to restart the application pool by right clicking it, selecting stop, and again selecting start. But you would have to do this after each debug run, so disabling it by entering zero for the idle time-out would be the better option.

This in essence, is the activities you have to go through in order to debug global.asax files. I welcome any suggestions and ideas on the readers’ part.