You are using a PopupControlExtender from the AjaxControlToolkit and you added a Button or an ImageButton in it and every time you click on it this ugly js error appears: this._postBackSettings.async is null or not an object. You Google and you see that the solution is to use a LinkButton instead of a Button or an ImageButton.

Well, I want my ImageButton! Therefore I added to the Page_Load method of my page or control this little piece of code to fix the bug:

private void FixPopupFormSubmit()
{
  var script =
    @"if( window.Sys && Sys.WebForms 
    && Sys.WebForms.PageRequestManager 
	&& Sys.WebForms.PageRequestManager.getInstance) {
  var prm = Sys.WebForms.PageRequestManager.getInstance();
  if (prm && !prm._postBackSettings) {
    prm._postBackSettings = prm._createPostBackSettings(false, null, null);
  }
}";
  ScriptManager.RegisterOnSubmitStatement(
    Page, 
    Page.GetType(), 
    "FixPopupFormSubmit", 
    script);
}



Hope it helps you all.

I wanted to use this Accordion control on a page and so I specified the ContentTemplate and HeaderTemplate and gave it a DataTable as a DataSource and DataBound it. Nothing! No errors, no warnings, no display of any kind. After a few frustrating minutes of trying to solve it I asked buddy Google about it and it turned out that the Accordion control MUST receive a DataView as a DataSource and nothing else. Using datatable.DefaultView solved it.

Update: it has come to my attention that these kind of errors appear only when debug="true" in the web config. In production sites it might work regardless.

You want to programatically load a js in a user control. The user control becomes visible in the page only during async postbacks and it is hidden at page load. So you want to use some method of loading the external javascript file during that asynchronous UpdatePanel magic.

Use ScriptManager.RegisterClientScriptInclude. There is a catch, though. For each script that you want to include asynchronously, you must end it with
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
else the Ajax.Net script loader will throw an error like: Microsoft JScript runtime error: Sys.ScriptLoadFailedException:
The script '...' failed to load. Check for:
Inaccessible path. Script errors. (IE) Enable 'Display a notification about every script error' under advanced settings.
Missing call to Sys.Application.notifyScriptLoaded().
.

For the aspx version, use the ScriptManagerProxy control:
    <asp:ScriptManagerProxy runat="server">
<Scripts>
<asp:ScriptReference Path="~/js/myScript.js" NotifyScriptLoaded="true" />
</Scripts>
</asp:ScriptManagerProxy>

So you did some work in an ASP.Net web site and then you decided to or to add the Ajax extensions to it or switch to ASP.Net 3.5 or whatever and suddenly you get Ajax errors like "Sys is undefined" or you don't see images and the css files are not loaded. And after googling like crazy and finding a zillion possible solutions you decide to enter in the browser address bar the url of the offending image, css file or even ScriptResource.axd files containing the ajax javascript and you see a beautiful ASP.Net error page displaying "Session state is not available in this context.". Huh?

There are some reasons why this might happen, but let's examine the one that actually prompted me to write the article. Someone made a change in global.asax, trying to work with Session there, more precisely in the Application_AcquireRequestState event. The error was returned by the Session property of the HttpApplication object, the one that the global.asax file represents! In fact, this error can only be thrown from there in the current ASP.Net implementations.

First mistake: there was a Session property available in the HttpApplication object and it was immediately assumed that it is the same as Page.Session or HttpContext.Current.Session. It is about the same, except it throws an error if the underlying Session object is null.

Ok, but why is Session null? You are a smart .Net developer and you know that the Session should be available in that event. Any documentation says so! Yes, but it applies to your page, not to all the IHttpHandler implementations, like ScriptResource.axd! Also, the css and image problems occured for me only when opening the site in Cassini, not in IIS, so maybe it opens separate threads to load those resources and ignores the session or something similar, at least at that level.

Well, how does one fix it? Adding in global.asax a condition on Session not being null throws the same error, so you have to add it on HttpContext.Current.Session. In other words:
if (HttpContext.Current.Session!=null) //do stuff with sessions

Maybe this problem occurs in other places as well, but only the Session property of the HttpApplication will throw the "Session state is not available in this context." error.

and has 0 comments
I took a test recently, one of those asking ridiculous C# syntax questions rather than trying to figure out if your brain works, but anyway, I got stuck at a question about structs and classes. What is the difference between them?

Credit must be given where it is due, I took the info from a dotnetspider article, by Dhyanchandh A.V. , who organised the answer to my question very well:
  • Classes are reference types and structs are value types. i.e. one cannot assign null to a struct
  • Classes need to be instantiated with the new keyword, structs need only be declared
  • When one instantiates a class, it will be allocated on the heap.When one instantiates a struct, it gets created on the stack
  • One works with the reference to a class, but directly with the struct
  • When passing a class to a method, it is passed by reference. When passing a struct to a method, it’s passed by value instead of as a reference
  • One cannot have instance Field initializers in structs
  • Classes can have explicit parameterless constructors. Structs cannot
  • Classes support inheritance. But there is no inheritance for structs, except structs can implement interfaces
  • Since struct does not support inheritance, the access modifier of a member of a struct cannot be protected or protected internal
  • It is not mandatory to initialize all fields inside the constructor of a class. All the fields of a struct must be fully initialized inside the constructor
  • A class can declare a destructor, while a struct cannot
.

What is the purpose of a struct, then? It seems to be only a primitive type of class. Well, it serves purposes of backward compatibility with C. Many C functions (and thus COM libraries) use structs as parameters. Also, think of the struct as a logical template over a memory location. One could use the same memory space of an Int32 under a struct { Int16 lo,hi }. Coming from an older and obsolete age, I sometimes feel the need to just read the memory space of a variable and be done with it. Serialization? Puh-lease! just grab that baby's memory and slap it over someone else's space! :)

and has 0 comments
One of our sites started exibiting some strange behaviour when adding a lot of strings to a StringBuilder. The error was intermittent (best kind there is) and the trace showed the error originating from the StringBuilder class and then from within the String class itself (from an external method).

On the web other people noticed this and one possible explanation was that strings need to be contiguous and thus they cannot grow bigger than the largest free contiguous memory block. Remember defragmentation? Heh.

In order to test this, I added a letter to a StringBuilder, then added itself to it for a few times to see where it breaks. It broke at a size of 2^27 (134,217,728 = 0x8000000)! At first I thought it was a StringBuilder bug, but getting sb.ToString() then adding to it a letter resulted in an error. Then I thought maybe it is a default size that, for whatever reason, is considered the maximum string size. That would suck. I don't usually need 134Mb of string, but what if I do? I have 2.5Gb of memory in this computer. But no, people reported the same problem but with other powers of 2, like 29 and on a Vista computer I got 2^28.

Is it from the fragmentation of memory? Right now I have only 1.8Gb in use. I rather doubt that in the 700Mb of space left there is only one 134Mb contiguous memory block. But I cannot prove it one way or another. My guess is that there is another mechanism that actually interferes with this and effectively limits the maximum string size.

But what does that mean, anyway? For practical purposes it means that you have to plan not to have strings that big in your applications. Creating a custom string builder might work, but it would have to use some other methods than strings.

I have tried the same thing with byte arrays. While declaring a byte array of 2^28 was possible (probably also because a string uses Unicode characters internally and thus takes twice the memory) writing it to a MemoryStream resulted in an error.

So watch these things out, try to always keep single variable blocks to manageable sizes.

I will write a really short post here, maybe I'll complete it later. I had to create some controls dynamically on a page. I used a ViewState saved property to determine the type of the control I would load (in Page_Load). It all worked fine until I've decided to add some ViewState saved properties in the dynamic controls. Surprise! The dynamically created controls did not persist their ViewState and my settings got lost on postback.

It's a simple google search away: dynamically controls created in Page_Load have empty ViewState bags. You should create them in Page_Init. But then again, in Page_Init the page doesn't have any ViewState, so you don't know what control type to load. It seemed like a chicken and egg thing until I tried the obvious, since the ViewState is loaded in the LoadViewState method, which is thankfully protected virtual, why not create my control there, after the page loads its view state? And it worked.

Bottom line:
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
CreateControl(ControlName);
}

and has 0 comments
This was something I have been meaning to write for quite some time, but actually, I've never had to work with a proper serialization scenario until recently. Here is goes:

First of all, whenever one wants to save an object to a string they google ".Net serializer" and quickly reach the XmlSerializer because that's what most people think serialization is. But actually, it is not. The whole point of serializing an object is that you can transfer and store it. Therefore you need to use a format that is as open, clear and standard as possible and to send only the relevant data, which in case of objects is the PUBLIC data. And for that, the XmlSerializer does its job, albeit, it does have some problems I am going to describe later.

But suppose you didn't really want to send mere data over to another computer, but an entire class, with its state intact, ready to do work as if the transfer never happened? Then you need to FORMAT the object. Enter the IFormatter interface with its most prominent implementation: BinaryFormatter. Funny enough, the methods used to spurt an object through a stream are also called Serialize and Deserialize. The advantages of the IFormatter way is that it is saving the entire object graph, private members included, and doesn't need all the requirements the XmlSerializer does. It also produces a smaller output. So, is this it? Why use Xml (which everybody secretly hates) when you can use the good ole obscure binary file with almost no trouble? Well, because of the almost. Yes, this way of doing things is not fullproof either.

Some people feel that the sending only the data is not serialization, and that the saving of the completele graph and internal state of the object is. Wikipedia says: "serialization is the process of converting an object into a sequence of bits so that it can be stored on a storage medium (such as a file, or a memory buffer) or transmitted across a network connection link. When the resulting series of bits is reread according to the serialization format, it can be used to create a semantically identical clone of the original object.". So, they bail by using the obscure phrasing of "semantically identical", which pretty much says "they mean the same thing even if their structures may differ". So, I think I am in the right, as the BinaryFormatter has real issues with structure change.

Now for the quick and dirty reference:
The XmlSerializer
  • Only serializes public READ/WRITE properties and fields - it doesn't throw any error when trying to serialize readonly properties, so be careful
  • Needs the class to have a parameterless constructor - this pretty much restricts the design of the classes you can serialize
  • Does not work on Dictionaries
  • Does use a Type definition to serialize and deserialize, which means you can still use it if the types are named differently or of different versions, even if they are radically different, as it will only fill the values that it stored and not care about the others
  • There are all sorts of attributes one can decorate their classes with to control serialization as well as some events that are fired during deserialization
  • Has issues with circular references
  • If your class implements IXmlSerializable it can control how the serialization is done

The BinaryFormatter
  • It serializes both public and private, readonly or read/write properties and fields as long as their type classes are marked as Serializable - that sucks for classes that are not yours
  • It's a rigid method of serializing objects - if you change the source or destination objects or even their namespace, the deserialization won't work

The SoapFormatter
  • Just when I thought that a class that combines the benefits of both BinaryFormatter and XmlSerializer exists, it appears it has been obsoleted in .Net 3.5. Besides, it did far less than the BinaryFormatter


It seems that Microsoft's idea of serialization blatantly differs from mine. I would have wanted a class that can serialize binary or Xml based on a simply property, send public OR both types of fields and properties, be flexible in how decorating attributes are used and what the output is. In my project I had to switch from BinaryFormatter, which seemed to solve all problems, to XmlSerializer (thus having to change a lot of the classes and design of the app) just because the type of the class sent by the client application could not have the same namespace as the one on the server.

That doesn't mean one cannot build their own class to do everything I mentioned above, of course. Here are some CodeProject examples:
A Deep XmlSerializer, Supporting Complex Classes, Enumerations, Structs, Collections, and Arrays
AltSerializer - An Alternate Binary Serializer.

Update: the .Net framework 3.5 has added an object called JavaScriptSerializer which turns an object into a single line of text, JSON style. It worked great for me in order to log hierarchical or collection based data. Use it just like the XmlSerializer.

Another link to check out is this one: Fast Serialization, but read the entire article before using any code.

Well, I was trying to use for the first time the Microsoft ReportViewer control. I used some guy's code to translate a DataSet XML to RDLC and ran the app. Everything went OK except for the export to Excel (which was the only real reason why I would attempt using this control). Whenever I tried exporting the report, the 'Asp.net Session expired' error would pop up.

Googling I found these possible solutions:
  • set the ReportViewer AsyncRendering property to false - doesn't work
  • use the IP address instead of the server name, because the ReportViewer has issues with the underline character - doesn't work, albeit, I didn't have any underline characters in my server name to begin with
  • set the maximum workers from 2 to 1 in the web.config (not tried, sounds dumb)
  • setting cookieless to true in the web.config sessionState element - it horribly changed my URL, and it worked, but I would never use that
  • setting ProcessingMode to local - that seemed to work, but then it stopped working, although I am not using the ReportViewer with a Reporting Services server
  • Because towards the end I've noticed that the problem was not an expiration, but more of a Session communication problem, I tried setting machineKey in web.config, although it doesn't work for the InProc setting. So it didn't work either.


For a few days, this blog post showed the last solution as working. Then it failed. I don't know why. I fiddled with the RDLC file a little (arranging columns and colors and stuff) and then it seemed to work again. I have no idea why.

I got mad and used Reflector to get the source code for the ReportViewer control and see where it all happends and why! I have found the following:
  • the error message looks like this:
    ASP.NET session has expired
    Stack Trace:
    [AspNetSessionExpiredException: ASP.NET session has expired]
    Microsoft.Reporting.WebForms.ReportDataOperation..ctor() +556
    Microsoft.Reporting.WebForms.HttpHandler.GetHandler(String operationType) +242
    Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context) +56
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
  • the error occurs in the constructor of ReportDataOperation:
    public ReportDataOperation():
    this.m_instanceID =
    HandlerOperation.GetAndEnsureParam(requestParameters, "ControlID");
    this.m_reportHierarchy =
    (ReportHierarchy) HttpContext.Current.Session[this.m_instanceID];
    if (this.m_reportHierarchy == null)
    throw new AspNetSessionExpiredException();
  • the Session object that makes the error be thrown is set in the SaveViewState() override method in ReportViewer
  • Apparently, the error occurs only sometimes (probably after the HttpApplication was restarted and during the debug mode of Visual Studio).


This reminded me of the time when I was working on a Flash file upload control and I used a HttpHandler to get the flash file from the assembly. Back then the control would not work with FireFox and some other browsers which would use different sessions for the web application and for getting the Flash from the axd http handler.

This time it works with FireFox and IE, but it fails in debug mode and only in IE. I am using IE8, btw.

My conclusion is that
  1. the ReportViewer control was poorly designed
  2. the ASP.Net Session expired error is misdirecting the developer, since it is not an expiration problem
  3. the actual problem lies in the inability of the ReportViewer control to communicate with the HttpHandler.
  4. The problem also could be related to the browser using separate threads to get the application and access the HttpHandler.

and has 0 comments
Well, it may have been obvious for many, but I had no idea. Whenever I was writing a piece of code that uses a StringBuilder I was terribly upset by the lack of a substring method.

It was there all along, only it is the ToString method. You give it the startIndex and length and you're set.

Looking at the source, I see that in .Net 1.1 this method is only a normal Substring on the internal string used by the string builder. In Net 2.0, the method uses a InternalSubStringWithChecks internal method of the string class, which is using a InternalSubString unsafe method that seems to be more basic and thus faster.

Actually, I think this applies to any dynamic modification of drop down list options. Read on!

I have used a CascadingDropDown extender from the AjaxControlToolkit to select regions and provinces based on a web service. It was supposed to be painless and quick. And it was. Until another dev showed me a page giving the horribly obtuse 'Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.'. As you can see, this little error message basically says there is a problem with a control, but doesn't care to disclose which. There are no events or overridable methods to enable some sort of debug.

Luckily, Visual Studio 2008 has source debug inside the .Net framework itself. Thus I could see that the error is caused by the drop down lists I mentioned above. Google told me that somewhere in the documentation of the CascadingDropDown extender there is a mention on setting enableEventValidation to false. I couldn't find the reference, but of course, I didn't look too hard, because that is simply stupid. Why disable event validation for the entire page because of a control? It seems reasonable that Microsoft left it enabled for a reason. (Not that I accuse them of being reasonable, mind you).

Analysing further, I realised that the error kind of made sense. You see, the dropdownlists were not binded with data that came from a postback. How can one POST a value from a select html element if the select did not have it as an option? It must be a hack. Well, of course it was a hack, since the cascade extender filled the dropdown list with values.

I have tried to find a way to override something, make only those two dropdownlists not have event validation enabled. Couldn't find any way to do that. Instead, I've decided to register all possible values with Page.ClientScript.RegisterForEventValidation. And it worked. What I don't understand is why did this error occur only now, and not in the first two pages I have built and tested. That is still to be determined.

Here is the code

foreach (var region in regions)
Page.ClientScript.RegisterForEventValidation(
new PostBackOptions(ddlRegions,region)
);


It should be used in a Render override, since the RegisterForEventValidation method only allows its use in the Render stage of the page cycle.

And that is it. Is it ugly to load all possible values in order to validate the input? Yes. But how else could you validate the input? A little more work and a hidden bug that appears when you least expect it, but now even the input from those drop downs is more secure.

Update:
My control was used in two pages with EnableEventValidation="false" and that's why it didn't throw any error. Anyway, I don't recommend setting it to false. Use the code above. BUT, if you don't know where the code goes or you don't understand what it does, better use this solution and save us both a lot of grief.

and has 0 comments
I have found this great link in Tomáš Petříček's blog which gives a very simple and elegant solution to casting to an anonymous type.

Short story shorter:

// Cast method - thanks to type inference when calling methods it
// is possible to cast object to type without knowing the type name
T Cast<T>(object obj, T objOfTypeT)
{
return (T)obj;
}


So simple! You see that the objOfTypeT parameter is never used, but the type infered from it is!

Update:
Correct usage:Cast(obj,anonObj)
Incorrect usage:Cast(obj,anonObj.GetType())

I had this really old site that I was asked to "upgrade". Net 1.1 to 3.5. So I had to change old ADO.Net SqlConnection to Linq-to-Sql. A lot of unforseen issues. Sometimes it is close to impossible to recreate a simple SQL query without changing the database, as in the case of updating tables or views without primary keys.

Anyway, I got stuck in a very simple issue: How to sort a Linq query based on the string returned by the GridView Sorting event. After a lot of tries and Googling I found it was easier to use third party software (although it's more of a 2.5rd party software, as it is made by Scott Guthrie from Microsoft). Here is the link to the blog entry: Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library) . You can find there a sample project to download, with the LINQ Dynamic Library inside.

With this library and the OrderBy extension methods the code becomes:
var somethings=from something in db.Somethings....;
var data = somethings.OrderBy(Sort + " asc");
gv.DataSource=data;
gv.DataBind();

I had this calendar extender thingie in my site and the client was Italian so I had to translate it into Italian. Nothing easier. Just enable EnableScriptGlobalization and EnableScriptLocalization and set either the Web.config or Page culture settings.

However, the footer of the calendar kept showing "Today" instead of "Oggi". I checked the source and I noticed that it used a AjaxControlToolkit.Resources.Calendar_Today javascript variable to create the footer. Step by step I narrowed it down to the AjaxControlToolkit resources! Funny thing is that they didn't work. I tried just about everything, including Googling, only to find people having the opposite problem: they would have all these resource dlls created in their Bin directory and couldn't get rid of them. I had none! I copied the directories from the ACTK and nothing happened.

After some research I realized that the Ajax Control Toolkit does NOT include the option for multi language UNLESS in Release mode. I was using everything in the solution, including the ACTK, in Debug mode. Changing the AjaxControlToolkit build to Release in the solution made this work.

A few days ago a coworker asked me about implementing an autocomplete textbox with not only text items, but also images. I thought, how hard can it be? I am sure the guys that made the AutoCompleteExtender in the AjaxControlToolkit thought about it. Yeah, right!

So, I needed to tap into the list showing mechanism of the AutoCompleteExtender, then (maybe) into the item selected mechanism. The AutoCompleteExtender exposes the OnClientShowing and the OnClientItemSelected properties. They expect a function name that accepts a behaviour and an args parameters.

Ok, the extender creates an html element to contain the list completion items or gets one from the property CompletionListElementID (which is obsoleted anyway). It creates a LI element for each item (or a DIV in case of setting CompletionListElementID). So all I had to do was iterate through the childNodes of the container element and change their content.

Then, on item selected, unfortunately the AutoCompleteExtender tries to take the text value with firstChild.nodeValue, which pretty much fails if the first child of the item element is not a text node. So we will tap in OnClientItemSelected, which args object contains item, the text extracted as mentioned above (useless to us), and the object that was passed from the web service that provided the completion list. The last one we need, but keep reading on.

So the display is easy (after you get the hang of the Microsoft patterns). But now you have to return a list of objects, not mere strings, in order to get all the information we need, like the text and the image URL. Here is the piece of code that interprets the values received from the web service:
// Get the text/value for the item
try {
var pair = Sys.Serialization.JavaScriptSerializer.deserialize('(' + completionItems[i] + ')');
if (pair && pair.First) {
// Use the text and value pair returned from the web service
text = pair.First;
value = pair.Second;
} else {
// If the web service only returned a regular string, use it for
// both the text and the value
text = pair;
value = pair;
}
} catch (ex) {
text = completionItems[i];
value = completionItems[i];
}


In other words, it first tries to deserialize the string received, then it checks if it is a Pair object (if it has a First property) else it passes the object as value and text! If deserialization fails, the entire original string is considered. Bingo! So on the server side we need to serialize the array of strings we want to send to the client. And we do that by using System.Web.Script.Serialization.JavaScriptSerializer. You will see how it goes into the code.

So far we displayed what we wanted, we sent what we wanted, all we need is to set how we want the completion items to appear. And for that I could have used a simple string property, but I wanted all the goodness of the intellisense in Visual Studio and all the objects I want, without having to Render them manually into strings.

So, the final version of the AutoCompleteExtender with images is this: A class that inherits AutoCompleteExtender, but also INamingContainer. It has a property ItemTemplate of the type ITemplate which will hold the template we want in the item. You also need a web service that will use the JavascriptSerializer to construct the strings returned.

Here is the complete code:
AdvancedAutoComplete.cs

using System;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;

namespace Siderite.Web.WebControls
{
/// <summary>
/// AutoCompleteExtender with templating
/// </summary>
public class AdvancedAutoComplete : AutoCompleteExtender, INamingContainer
{
private ITemplate _template;

[TemplateContainer(typeof(Content))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate ItemTemplate
{
get { return _template; }
set { _template = value; }
}

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
const string script = @"
function AdvancedItemDisplay(behaviour,args) {
var template=behaviour.get_element().getAttribute('_template');
//if (!template==null) template='${0}';
for (var i=0; i<behaviour._completionListElement.childNodes.length; i++) {
var item=behaviour._completionListElement.childNodes[i];
var vals = item._value;
var html=template;
for (var c=0; c<vals.length; c++)
html=html.replace(new RegExp('\\$\\{'+c+'\\}','g'),vals[c]);
item.innerHTML=html;
}
}

function AdvancedSetText(behaviour,args) {
var vals=args._value;
var element=behaviour.get_element();
var control = element.control;
if (control && control.set_text)
control.set_text(vals[0]);
else
element.value = vals[0];
}
"
;
ScriptManager.RegisterClientScriptBlock(this, GetType(), "AdvancedAutoComplete", script, true);

OnClientShowing = "AdvancedItemDisplay";
OnClientItemSelected = "AdvancedSetText";
}

protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string template = GetTemplate();
((TextBox)TargetControl).Attributes["_template"] = template;
}

private string GetTemplate()
{
Content ph=new Content();
ph.Page = Page;
_template.InstantiateIn(ph);
HtmlTextWriter htw = new HtmlTextWriter(new StringWriter());
ph.RenderControl(htw);
return htw.InnerWriter.ToString();
}
}
}


MainService.cs

using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;

/// <summary>
/// Web service to send auto complete items to the AdvancedAutoComplete extender
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class MainService : WebService
{
[WebMethod]
[ScriptMethod]
public string[] GetCompletionList(string prefixText, int count)
{
JavaScriptSerializer jss=new JavaScriptSerializer();
List<string> list=new List<string>();
for (int c = 0; (list.Count< count) && (c < 100000); c++)
{
string s = (c*c).ToString();
if (s.StartsWith(prefixText))
{
object[] item = new object[] {s, "images/demo.gif"};
list.Add(jss.Serialize(item));
}
}
return list.ToArray();
}
}



An example of the use

<asp:TextBox runat="server" ID="tbMain"></asp:TextBox>
<cc1:AdvancedAutoComplete ID="aceMain" runat="server" BehaviorID="mhMain" TargetControlID="tbMain"
ServiceMethod="GetCompletionList" ServicePath="~/MainService.asmx" MinimumPrefixLength="0"
CompletionInterval="0">
<ItemTemplate>
<asp:Image runat="server" ID="imgTest" ImageUrl="${1}" /><asp:Label runat="server"
ID="lbTest" Text="${0}"></asp:Label>
</ItemTemplate>
</cc1:AdvancedAutoComplete>


That's it! All you have to do is make sure the controls in the template render ${N} text that gets replaced with the first, second, Nth item in the list sent by the web service. The text that will be changed in the textbox is always the first item in the list (${0}).

Restrictions: if you want to use this a control in a library and THEN add some more functionality on the Showing and ItemSelected events, you need to take into account that those are not real events, but javascript functions, and the design of the autocompleteextender only accepts one function name. You could create your own function that also call on the one described here, but that's besides the point of this blog entry.