Read My Tweets
Ever feel like you're not getting the best experience on the web?
Get Silverlight to see the whole site!

TUTORIAL #8: Creating An AutoComplete TextBox With AJAX

Monday, October 27, 2008

There's this incredible resource in the AJAX Control Toolkit, and it's about time we started using it. Today I am going to talk about the AutoComplete Extender, and how simple it is to rig up to an existing ASMX web service. As usual, I will provide the code at the end of this post in both C# and VB.NET. Let's start at the beginning:

1) Create a new web site.



2) Create a new ASMX web service.

Right-click on the project, and choose "Add New Item..." From the dialog box, choose Web Service, and name the service NCAA.asmx (I'll explain the name later.) Also, for our demo, we're going to leave the code in one single file. Uncheck the "Place code in a seperate file" box.


3) Write a quick web method.

We'll be making this more complicated later, but for now, we're going to write a simple web service that is meant for the AutoComplete Extender. For this control, our method must have this signature:
public string[] GetTeamList(string text)
So for now, here's the full code to put inside your ASMX file:
using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;


namespace AutoComplete
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ncaa : System.Web.Services.WebService
{
[WebMethod]
public string[] getTeamList(string prefixText)
{
string[] teamName = new String[6];
teamName[0] = "Bowling Green State University";
teamName[1] = "Ohio State University";
teamName[2] = "Ohio University";
teamName[3] = "Cleveland State University";
teamName[4] = "University of Cincinnati";
teamName[5] = "University of Dayton";
return teamName;
}
}
}


4) We should verify our web service works.

Right click on your ASMX file, and choose "View in Browser." Clicking on the method name, GetTeamList, will ask you for a "prefixText" value. That value isn't used yet, so just click the Invoke button to see our list of colleges returned in XML.


5) Now we need add a textbox.

We're actually going to add a few things to our Default.aspx page, but the first thing to do is add a standard TextBox control to the page. You should be able to grab that from your toolbox. The other things to add require a potential download first. I'll show you the completed HTML after step #9.


6) Get the ASP.NET AJAX Library.

You only need to do this if you're not using the ASP.NET 3.5 framework. Here is the link to the AJAX library downloads.


7) Get the AJAX Control Toolkit.

The control toolkit is an open source project on CodePlex, and you can download it here. Unless you're really interested in contributing/taking it apart, all you really need is the link to the DLL Only. Save that to your computer, and then you need to add it to your Toolbox.


8) Add it to your VS Toolbox.

Here's the quick way to get those new controls and extenders into your Visual Studio toolbox:
  1. Pin out your toolbox by clicking on the pushpin icon at the top.
  2. Right-click on the toolbox and choose "Add Tab"
  3. Give it a name like "AJAX Control Toolkit."
  4. Drag the toolkit .DLL file from your computer to the new tab you created.
  5. You should now see your new controls in your toolbox.


9) Add our AJAX elements to the page.

Now we need to add an AJAX ScriptManager and a new AutoCompleteExtender to our page. You can either type them, or just drag them from your toolbox. Here's what your Default.aspx file should look now:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AutoComplete._Default" %>
<%
@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<
html xmlns="http://www.w3.org/1999/xhtml" >
<
head runat="server">
<
title>Jeff Blankenburg | AutoCompleteExtender</title>
<
link href="style.css" rel="stylesheet" type="text/css" />
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<
asp:TextBox ID="collegeteam" runat="server"></asp:TextBox>
<
cc1:AutoCompleteExtender ID="collegeteamextender" runat="server" ServicePath="ncaa.asmx" ServiceMethod="getTeamList" MinimumPrefixLength="3" CompletionSetCount="10" TargetControlID="collegeteam">
</
cc1:AutoCompleteExtender>
</
div>
</
form>
</
body>
</
html>


10) Some explanation for the HTML...

You'll notice that I added some properties to the controls that are on our page, so let me explain what they are.
  • Service Path - this is the web service that we are going to call
  • Service Method - this is the method in that web service that we are calling.
  • Minimum Prefix Length - this is the number of characters a user must enter before the extender will start calling the web service. If you've got thousands or millions of possible return values, I'd make this 3 or 4, at a minimum.
  • Completion Set Count - this forces the control to only show a specific number of results (you need to modify your web service for this to work).


11) Run the web site.

At this point, we should have a fully functional AutoComplete extender. You can run the site to check it out. Just start typing in the textbox to see what happens. But we're pulling back a static list of data. That's not very interesting at all. I want to do something realistic with this functionality.

12) Web Service += Usefulness

The reason that I called my web service NCAA is because I want to allow my users to choose from a list of colleges as they are typing. The first thing we'll need then, is a database of colleges. Here's my database of all of the Division I schools, with their names, mascots, and hex colors. Now we need to modify our web service so that we're pulling results out of the database based on our text typed in the TextBox. Here's my new web service code (you can just copy and paste over the old stuff.)

using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;


namespace AutoComplete
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ncaa : System.Web.Services.WebService
{
[WebMethod]
public string[] getTeamList(string prefixText)
{
DataSet teams = new DataSet();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string sql = "SELECT team_name FROM team WHERE team_name LIKE '" + prefixText + "%'";
SqlCommand sqlCmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlCmd;
sqlAdpt.Fill(teams);
string[] teamName = new String[teams.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow row in teams.Tables[0].Rows)
{
teamName.SetValue(row["team_name"].ToString(), i);
i++;
}
}
catch { }
finally
{
conn.Close();
}
return teamName;
}
}
}


You'll notice that without modifying our .aspx file, we can completely update the functionality behind our web service. This seperation can be invaluable when building applications from web services, because you don't want a change in one thing to potentially break another.

13) What about that CompletionSetCount?

So I mentioned earlier that you can set the number of results you want returned so that you don't end up with a huge, unmanageable list. This will require a small change to your web service, but nothing significant. Without these changes, your CompletionSetCount value will just be ignored. The first change is that we need to receive a second parameter (an integer) in our WebMethod. That's right, the extender just sends it as a second parameter to your method. The second change, then, is just to modify your method to utilize that value. Here's my final web service source code, using this added feature:

using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;


namespace AutoComplete
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ncaa : System.Web.Services.WebService
{
[WebMethod]
public string[] getTeamList(string prefixText, int count)
{
DataSet teams = new DataSet();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string sql = "SELECT TOP " + count + " team_name FROM team WHERE team_name LIKE '" + prefixText + "%'";
SqlCommand sqlCmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlCmd;
sqlAdpt.Fill(teams);
string[] teamName = new String[teams.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow row in teams.Tables[0].Rows)
{
teamName.SetValue(row["team_name"].ToString(), i);
i++;
}
}
catch { }
finally
{
conn.Close();
}
return teamName;
}
}
}


Demo

Here's a link to the active demo. Because my hosting provider does not support SQL Express (we can talk about CrystalTech later), I am actually running it from a full SQL 2005 database, but the MDB I provided is merely a copy of the table I am using.

Click to see the AutoComplete demo.

Source Code

Click to download the AutoComplete demo in C#. Click to download the AutoComplete demo in VB.NET.

kick it on DotNetKicks.com

Labels: , , , , , ,

posted by Jeff Blankenburg, 12:16 PM | link | 2 comments |

TUTORIAL #2: Using Javascript To Call A WCF Web Service

Wednesday, September 03, 2008

Sometimes you just need to use Javascript. It's one of those things that web developers claim to hate, but secretly, I just hated the lack of tools support for it. That seems to be solved, at least for me.

Today I'm going to show you how to call your asynchronous web service from Javascript, and how we can incorporate JS Intellisense to make our job infinitely easier (one line of code, anyone?) The source code is provided at the end, in both C# and VB.NET.

1) Let's start with a new web application project.

Solution Explorer

2) Next, we're gonna need a web service to talk to.

image

Now, you may already be saying to yourself, "Jeff, this is all well and good, but I already have WCF services created. We don't all have the luxury of creating stuff from scratch each time!" I've got you covered. There's actually only one line of code that changes a WCF service into an AJAX-enabled WCF service. And here it is:

[ServiceContract(Namespace = "")]
 //The following line is the one you need!
 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
 public class JeffsName
 {
  [OperationContract]
  public string GetJeffsName()
  {
   return "Jeff Blankenburg";
  }
 }


One you've got your WCF service up and rockin, we need to get it to DO something, right?



3) Getting our method to DO something

For this tutorial, I'm not going spend time talking to a database or anything extravagant. But I want to do more than return a name. I was talking with a friend of mine yesterday about why the nickel seems to be the rarest of coins in your pocket, and that inspired my method for this example.

<LONGSTORY TYPE="INTERESTING" VALUE="NOT IMPORTANT TO THE TUTORIAL">

Dan pinged me over IM to tell me about this guy who had started a game collecting money on the street. He called it the "Change Race." He wanted to see who could collect $100 faster by ONLY collecting money that was "found." It didn't count if you found $5 in an old coat from the previous winter, that was still your money.

Anyway, so Dan, who is known to like to try eccentric things like these, thought he would give it a go. In his coin finding history to this point, he discovered that he was finding significantly fewer nickels than any other coin. Here's the breakdown:

$0.25 - 7

$0.10 - 16

$0.05 - 6

$0.01 - 63

Yes, there are only 7 quarters, but who drops a quarter and leaves it? I certainly understand those pennies, however. But only 6 nickels? That seems surprising, as I'm calling it, "The Silverier, Fatter Penny."

So the conversation we had was about WHY there seems to be fewer nickels. We threw around many theories, but ultimately came up with the fact that there are fewer change scenarios where a nickel is necessary. In addition, there's rarely a time where you are going to get 2 nickels in change, because you're more likely to get a dime. Anyway, I'd love to see a debate about this in the comments. There's even a good article someone wrote about "The Mystery of the Vanishing Nickel."

</LONGSTORY>

So that story led me to think about the 99 change scenarios that are possible when receiving change from a cashier. 1 cent through 99 cents. Zero doesn't count because you would just get bills (or nothing at all.)

My web service is going to take an integer value and return the fewest number of coins necessary to make that change. If your integer is greater than 99, I just subtract out the dollars until we are left with the change.

Here's my web service method:

public class ChangeScenario
 {
  [OperationContract]
  public string GetMinimumCoins(int changevalue)
  {
   int quarter = 0;
   int dime = 0;
   int nickel = 0;
   int penny = 0;
   int tempvalue = changevalue;
   while (tempvalue > 0)
   {
    if (tempvalue >= 100)
    {
     tempvalue -= 100;
    }
    else if (tempvalue >= 25)
    {
     tempvalue -= 25;
     quarter += 1;
    }
    else if (tempvalue >= 10)
    {
     tempvalue -= 10;
     dime += 1;
    }
    else if (tempvalue >= 5)
    {
     tempvalue -= 5;
     nickel += 1;
    }
    else if (tempvalue >= 1)
    {
     tempvalue -= 1;
     penny += 1;
    }
   }
   return "You need " + changevalue + " cents in change.<BR/><BR/>You get " + quarter + " quarters, " + dime + " dimes, " + nickel + " nickels, and " + penny + " pennies";
  }

In all, I take an integer parameter, and return a string that represents the fewest coins that will satisfy that change scenario.

4) Making the page aware of the web service

I wish I could say that this was now as easy as writing a line of code in a script block and you're done. But it's maybe 5 lines of code more complicated than that. And most of those lines are dedicated to letting the .aspx page know that you want to talk to the web service.

So speaking of that, I will need to add my all-too-familiar-scriptmanager to the page, as well as a reference to the web service we want to use.

<form id="form1" runat="server">
    <asp:ScriptManager runat="server" ID="sm">
        <Services>
            <asp:ServiceReference Path="~/ChangeScenario.svc" />
        </Services>
    </asp:ScriptManager>
    <div id="valuebox">
        <a href="javascript:callWebService();">Click to call web service.</a>
    </div>
</form>
You'll notice that I also have a DIV tag in there, with an ANCHOR tag calling a Javascript function. Inside this function is where I will call my web service method.

5) Calling the web service from Javascript

Now I have created a Javascript function at the top of my page, and I need to make that call to my web service. The syntax is generally what you would expect to find:

<script language="javascript" type="text/javascript">
    function callWebService()
    {
        ChangeScenario.GetMinimumCoins(86, setText);
    }
 
    function setText(changetext)
    {
        var myElement = document.getElementById('valuebox');
        myElement.innerHTML = changetext;
    }
</script>

The one thing that stuck out to me in all of this was the second parameter in the method call. It's the name of another Javascript function. This new ability also gives us some new Intellisense.

Javascript Intellisense

The first value is the parameter that the web service method takes. In this case, it's even expecting an integer. The second is the name of the Javascript function you want to be called upon successful completion of the asynchronous call. The third is another JS function for when the call fails.

So, when we click our button, we call the callWebService() function, passing in an integer value to determine our change.

In turn, it returns our value successfully, and calls the setText() Javascript function with the parameter our method returns.

This function then renders that value as the HTML for the DIV we have on the page.

6) Summary of our adventure

As I demonstrated, in rather verbose fashion, it's pretty simple to talk to a web service from Javascript directly. Most of your effort will be spent writing a service far more valuable than mine. The nice part is that the asynchronicity of the calls is completely handled for you.

Please let me know if you have any questions...I'd be glad to help you out.

7) Let's see this code in action!

I have uploaded my sample application for demonstration of this code. It has been slightly modified, so that we call the web service 99 times, once for each "change scenario." One thing that I have noticed, at least in my environment, is that because we are making asynchronous calls, they don't always return in the order they were sent. So you'll see that, even though we are making the calls in the order from 1-99, they don't necessarily get written to the page in that order. We're just taking the data as it returns.

demo

8) Source Code Links

Even though I provided my examples above in C#, I have provided source code for both C# and VB implementations of this example. Enjoy!

C#.NET Source Code VB.NET Source Code



kick it on DotNetKicks.com

Labels: , , , ,

posted by Jeff Blankenburg, 4:11 PM | link | 2 comments |

My Upcoming Travels...and a new, cool Night of AJAX

Tuesday, September 18, 2007


In case you're terribly interested in where I'll be over the next month, here's the short list (I'm sure this will be added to).

September 24 - Halo 3 Pre-Launch Party in Detroit, MI
September 25 - Halo 3 Launch Party in Columbus, OH
September 26 - Halo 3 Launch Party in Cincinnati, OH
September 27 - Columbus .NET Developer's Group Meeting
October 8 - ReMix07 Boston
October 9 - ReMix07 Boston
October 11 - Nashville .NET User's Group
October 12 - DevLink
October 13 - DevLink
October 15 - The Night of AJAX in Cleveland, OH (at the Microsoft office)
October 20 - Day of .NET in Ann Arbor, MI

26 days, 7 cities. Not bad. Where should I go next? Anyone have some great events coming up that I'm not aware of?

Also, in case you're curious, the Night of AJAX is a public event in Cleveland. We are going to be welcoming Jay Kimble of Codebetter.com fame and AJAX guru from Florida. It is planned to be a two hour event in which Jay will present an Intro to AJAX followed up with AJAX best practices and a discussion of Javascript Alternatives (eg. Script#/Silverlight). Please plan to check it out. Be sure to check back for more information as it becomes available. Please leave a comment or email me if you'd like more information. Special thanks to Dave Balzer for getting this great idea put together.

Labels: , , , , ,

posted by Jeff Blankenburg, 9:02 PM | link | 0 comments |

Ah, the irony.

Tuesday, May 01, 2007

You're presenting at Mix. You've got an intriguing title and abstract:

High Speed Development with the AJAX Control Toolkit

You're ten minutes late. Very professional. Helps your credibility.

Labels: ,

posted by Jeff Blankenburg, 1:02 PM | link | 1 comments |

Day 1: Holy Cow.

Monday, April 30, 2007

So it's been hyped for the past few weeks that we were going to see many new things announced by Microsoft this morning. The hype didn't keep up with reality.

It was WAY better than sold.

THe biggest highlight of this conference is the combination of Silverlight with the .NET framework.

We can actually write C# code to function like you would normally expect Javascript to do.

We can create vector based animations to run in a cross-browser, cross platform environment, with all of the instructions stored in XAML.

Designers can completely control the look and actions of these elements in a graphical interface, but that design is then translated down to XAML, which can be edited, updated, etc as a file on the server. This allows the designer to control the looks, and the developer to control the functionality.

Two demos during the keynote were flooring, however.

First, the CEO from a company named Metaliq demoed a new AJAX/Silverlight/.NET application they call Top Banana. It is basically a content editing application, all within a browser. The URL is http://silverlight.metaliq.com/topbanana
It appears they have taken their demo down, but as soon as I can get access to it again. I will post it. It was truly unbelieveable.

The other struck close to home. I'm a huge baseball fan. Mondo big. And having grown up in Cleveland, I've been forced to suffer with the Indians my entire life. THe C-something-something from MLB.oom was here demoing their new MLB.TV application. It acted as I expected. Showed every possible statistic available in an interface that also shows the live games streamed over the internet. All great, all what I would expect. It include a feature that allowed you to add your favorite players (think fantasy baseball) and it would alert you every time your player did something in any of the games. It would also serve up the specific video clip of that notable performance. (On a sidenote, thsi guy said that they generate 10 DVDs worth of data with every pitch of every game. That seems like a little bit. :))

Anyways, even the fantasy player list wasn't the coolest part of this demo. Oh no. He then pulled out his cell phone, and showed us a Silverlight application running there. It showed stats, game scores, even live score updates, and runners on base. Think about the graphics that show up during a TV broadcast. Minus the actual game video. Well, with Silverlight, it appears they are going to be successful in streaming actually live video to your phone, and remember that fantasy player list, statistics, and video feeds? That was all demonstrated as well.

Man, this has been amazing thus far. Thanks again to Quick Solutions for sending me here.

Labels: , , , ,

posted by Jeff Blankenburg, 6:34 PM | link | 1 comments |