The Imaginative Universal

Studies in Virtual Phenomenology -- @jamesashley

Ajax AutoComplete Extender with WCF

July 07
by James Ashley 7. July 2008 07:23

blackstone

The problem with conjuring tricks is that they lose practically all their glamour once you find out how they are done.  It's very cool to see David Blaine walk down the street, do a few passes over his hand, and resurrect a fly which proceeds to flee.  It's rather disappointing to do a google search and discover that in order to prepare for this trick, the first requirement is that you freeze a fly.

My trick is to make an autocomplete extender from the Ajax Control Toolkit call a WCF service instead of an asmx service.  For this recipe, I assume that you are already familiar with the autocomplete extender, and that you are using Visual Studio 2008.  I warn you in advance -- my trick disappoints.  It is so trivially easy that, once the technique spreads, it is very unlikely to impress your colleagues at work, much less get you a date with a supermodel.

Start by creating a new web project called AutocompleteWCF.  Add a reference to the AjaxControlToolkit.dll.  Open up the default aspx page that is generated with your project, and add the following code to:

    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
            <asp:TextBox runat="server" ID="myTextBox" Width="300" autocomplete="off" />
            <ajaxToolkit:AutoCompleteExtender
                runat="server" 
                BehaviorID="AutoCompleteEx"
                ID="autoComplete1" 
                TargetControlID="myTextBox"
                ServicePath="Autocomplete.svc" 
                ServiceMethod="GetCompletionList"
                MinimumPrefixLength="0" 
                CompletionInterval="1000"
                EnableCaching="true">
            </ajaxToolkit:AutoCompleteExtender>
    </div>
    </form>

 

This is the standard demo code that is shipped with the Ajax Control Toolkit Sample Website.  I've simplified it a bit by removing the animations.  The only significant change I've made is to change the ServicePath from Autocomplete.asmx to Autocomplete.svc, the latter being the extension for a WCF service.

The next step is to create our service and add a GetCompletionList operation to it.  The easiest way to do this is to go to Add | New Item and just select the Ajax-enabled WCF Service item template, but this would be so easy that it is hardly worth doing.

Instead, create a new WCF Service using the WCF Service Item Template and call it Autocomplete.svc.  Visual Studio will automatically generate a service interface for you.  Delete the interface.  We don't need it.  (To be more specific, I don't know how to get this to work with an interface, so I'm just going to ignore that it is possible.)

Again, I am going to rip off the ACT sample app and just borrow the code from their webservice and place it in our WCF service.  The WCF service class (Autocomplete.svc.cs) will look like this:

    [ServiceContract(Namespace = "")]

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

    public class Autocomplete

    {

 

        [OperationContract]

        public string[] GetCompletionList(string prefixText, int count)

        {

            if (count == 0)

            {

                count = 10;

            }

 

            if (prefixText.Equals("xyz"))

            {

                return new string[0];

            }

 

            Random random = new Random();

            List<string> items = new List<string>(count);

            for (int i = 0; i < count; i++)

            {

                char c1 = (char)random.Next(65, 90);

                char c2 = (char)random.Next(97, 122);

                char c3 = (char)random.Next(97, 122);

 

                items.Add(prefixText + c1 + c2 + c3);

            }

 

            return items.ToArray();

        }

 

A few things worth noting:

1. Autocomplete does not implement the IAutocomplete Interface.  Even though this is generated automatically, with the WCF Service item template, you should remove it.

2. The service contract has a blank Namespace explicitly declared. 

3. The ASPNetCompatibilityRequirements attribute must be added to our class.

 

This takes care of the code that calls the WCF service, as well as the service itself.  We now have rig up the web.config file.  If you've been working with WCF for any length of time, then you know that this is where the problems usually occur.  Fortunately, the configuration is fairly simple.  You need to set up an endpoint behavior for your service that enables web scripting (much the way asmx web services must be decorated with the ScriptService attribute in order to be called from client-script).  You also will need to turn AspNetCompatibilityEanbled on for the hosting environment.

 

    <system.serviceModel>

        <behaviors>

            <endpointBehaviors>

                <behavior name="AjaxBehavior">

                    <enableWebScript/>

                </behavior>

            </endpointBehaviors>

        </behaviors>

        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

        <services>

            <service name="AutocompleteWCF.Autocomplete">

                <endpoint address="" behaviorConfiguration="AjaxBehavior" binding="webHttpBinding" contract="AutocompleteWCF.Autocomplete"/>

            </service>

        </services>

    </system.serviceModel>

 

And that is all you need to do make the AutoComplete Extender work with a WCF service instead of an asmx web service.  I told you it would be unimpressive.

Of course, using a WCF service for Ajax has all the limitations that using an asmx file for Ajax did.  First of all, you can't call a service that is in a different domain than the page which hosts your client-code.  This is a security feature, to prevent malicious code from redirecting your harmless javascript to something nasty on the world wide web.

Second, you can't call just any service from your client-side code.  The service must be explicitly marked as something that can be called from client code.  In asmx web services, we used ScriptService for this.  In WCF services, we similarly use EnableWebScript binding property.

Now I feel like I've wasted your time, so here's a YouTube video of David Blaine to make up for it.  And remember, David Blaine is to Chris Angel what Daisy Duke was to Alexis Carrington.  It's an existential thing, and at some point, you've just got to pick sides and stay put in a way that will determine who you are for the rest of your life.

Are you a David Blaine/Daisy Duke kind of person or are you a Chris Angel/Alexis Carrington sort?  Do some soul searching and please let me know what you learn about yourself.

Tags: , ,

Ajax | Recipe | WCF

Comments

4/30/2009 12:36:19 PM #

Kumar

kool, worked for me like a charm

Kumar

11/18/2010 10:22:40 AM #

Free Samples and Stuff

we use symfony, which has some of these tools built in for easy ajax in php

Free Samples and Stuff United States

12/6/2010 5:21:57 AM #

muzaffer

Elma sirkesi kilo kaybı beslenme hakkındaki gerçeği keşfedeceksiniz. Elma sirkesi kendisi elma fermente edilmesiyle üretilen asidik bir çözümdür.

muzaffer Turkey

12/8/2010 6:11:02 AM #

web designing

we use symfony, which has some of these tools built in for easy ajax in php

web designing United States

12/21/2010 8:23:08 AM #

Asigurare locuinta

It works very fine for me. I've just tested the code and it makes a good job.

Asigurare locuinta United States

12/22/2010 10:53:36 AM #

Web Design

The code is well written and it's work very fine. I don't see any issue with the coding process or something else.

Web Design United States

12/23/2010 1:45:45 PM #

Marry

I just use this one and it is working fine, please keep us update with this type of post.

Marry United States

1/26/2011 3:43:18 AM #

Amanda

Thank! for good post. Useful for me and another one.

Amanda United States

2/23/2011 12:06:04 AM #

umbilical cord blood banking

Hi, The topic that you have discussed in the post is really amazing, I think now I have a strong hold over the topic after going through the post. I will surely come back for more information.

umbilical cord blood banking India

5/11/2011 8:35:32 AM #

syeed

yes, it is working .
But the scenario is create website add text,auto...,
add .svc file and  remove count variable and MinimumPrefixLength="0"  u will get response

syeed India

6/9/2011 3:35:22 AM #

meizitang

meizitang botanical slimming soft gel for sale
1.Meizitang zisu slimming pill meizitang for sale
Lose 20-30 lbs per month 100% herbal and safe
350mg x 30 capsules /box,

2. Meizitang strong version bottle
"MSV" on pills with laser , 650mg*36 pills

3. Meizitang New Version Meizitang slimming tablets
36 mzt soft gel for sale cheap meizitang

4. Meizitang old version weight loss
36 soft gel, meizitang slimming gel

5. Meizitang botanical slimming (Blue Capsule)
Weight loss 30 Ibs monthly.Meizitang OEM
http://yemade.com

meizitang People's Republic of China

6/9/2011 3:38:34 AM #

poerkan

When arousal time comes you’ll be ready to rock her world for as long as you want. You don’t have to worry about having an erection when you don’t want one. Libigrow male enhancement supplements only works with sexual stimulation so it only works when you want it to.
Libigrow male enhancement pills are one of the most popular male enhancement products sold online and sales of these herbal male enhancers continue to climb each year. Natural male enhancers use a combination of herbal ingredients used for centuries to promote sexual virility.
Libigrow Pills Reviews:
•Scientifically Formulated To Increase SEXUAL DESIRE
•Clinically Proven To Achieve POWERFUL ERECTIONS
•Assists With PRE-MATURE ELACULATION
•Works Only With SEXUAL STIMULATION
•Increases Orgasm Threshold & Intensity
•One Capsule Lasts Up To 4 Days
•Recommended For Men 18-80 Years Old
•Give Your Partner What They Really Want!
•100% Natural, Guaranteed!
•SARE EVEN FOR MEN WITH DIABETES
Libigrow Herbs Male Enhancement Suggested Use:
As A Dietary Supplement, take One (1) Capsule 30 To 60 Minutes
Prior To Sexual Activity Or Take One (1) Capsule On A Light Stomach During Mid-day.
Libigrow enhancement supplements ingredients: Cordyceps Sinensos, Flat-Stem Milkvetch, Chinese Dodder Seed, Ligustrum, Cnidium, Cherokee Rose, Walnut (nut), Dong Quai, Astragalus Root, Korean Ginseng, Schizandra Fruit, Vitamin B-6L-Arginine, L-Lysine, L-Glutamine
Libigrow Capsule: 25 capsules/box
*Dally Value not yet established.
Vegetable Magnesium Stearate and Water.          
These statements have not been evaluated by the Food and Drug Administration. This Libigrow enhancement supplements is not intended to diagnose, treat, cure or prevent any disease.
When arousal time comes you will be ready to rock her world for as long as you want. You donot have to worry about having an erection when you donnot want one. Libigrow men enhancement pills only works with sexual stimulation so it only works when you want it to. Come here! You will find best Libigrow wholesale! Purchase male enhancement pills from here!
YOU CAN TAKE ONE OR TWO BUT NO MORE THAN 900mg IN 24 HOURS.
http://www.poerkan.com

poerkan People's Republic of China

6/9/2011 7:53:12 AM #

jasmine09

As a Newbie, I am forever searching online for articles that can aid me. Convey you

<a title="buenos aires apartment" href="http://www.buenosairesdeluxe.com" target="_blank">buenos aires apartment</a>

jasmine09 United States

6/9/2011 7:56:12 AM #

Seguro de Auto Las Vegas

Hey, guy, your journal is respectable. It can transport me more reusable assemblage.

Seguro de Auto Las Vegas United States

6/9/2011 10:50:13 PM #

Pandora Bracelets

The article has truly peaks my interest.

Pandora Bracelets United States

6/29/2011 6:15:54 AM #

meizitang

Meizitang botanical slimming soft gel for sale
1.Meizitang zisu slimming pill meizitang for sale
Lose 20-30 lbs per month 100% herbal and safe
350mg x 30 capsules /box,

2. Meizitang strong version bottle
"MSV" on pills with laser , 650mg*36 pills

3. Meizitang New Version Meizitang slimming tablets
36 mzt soft gel for sale cheap meizitang

4. Meizitang old version weight loss
36 soft gel, meizitang slimming gel

5. Meizitang botanical slimming (Blue Capsule)
Weight loss 30 Ibs monthly.Meizitang OEM
http://www.romanoy.com

meizitang United States

7/4/2011 11:10:34 PM #

buy runescape gold

good

buy runescape gold United States

7/13/2011 7:48:36 AM #

SJR Luxuria

An interesting discussion is worth comment. I think that you should write more on this topic, it might not be a taboo subject but generally people are not enough to speak on such topics. To the next. Cheers

SJR Luxuria United Kingdom

7/19/2011 10:33:18 PM #

P90x Workout

A knowledge, a growth, a good article can make a person to enhance the taste, thank you for sharing, I will carefully read the product to make themselves rich!
<a href="http://www.p90xworkoutus.com">P90x Workout</a>
<a href="http://www.p90xworkoutus.com">P90x Dvd</a>

P90x Workout United States

7/22/2011 5:59:02 AM #

Developers Bangalore

Great share

Developers Bangalore United States

7/23/2011 2:30:40 AM #

pingback

Pingback from see00800.bestmedicament.com

Intensity autocomplete | See00800

see00800.bestmedicament.com

9/11/2011 10:19:32 PM #

pingback

Pingback from bewaretheclett.shikshik.org

Intensity autocomplete | Bewaretheclett

bewaretheclett.shikshik.org

Comments are closed

BlogRoll

Download OPML file OPML