:::: MENU ::::

Tuesday, March 17, 2009

It seems like such a trivial thing to be talking about but not knowing the difference between the two operators can make a huge difference between working code and code that only seems to work.

Let me illustrate:

        bool b = false;

        bool c = true;

        if(b & c)

            // do something

 

        if(b && c)

            // do something

In the code above, both b & c and b && c evaluate to false, so  we are safe.  No problems.  But this leads us to believe that the following code is also safe:

        string s = null;

        if(s != null & s.Length > 0)

            // do something

 

        if(s != null && s.Length > 0)

            // do something

and this is what would get you in trouble.

The single ampersand and single pipe are knows as “bit wise operators.”  What this means in practical terms is that they will take whatever they find on BOTH sides of the operator and AND (&) or OR(|) them together.

So in the case of:

if(s != null & s.Length > 0)

s.Length > 0 will still get evaluated even if s is null.  Not exactly what we had in mind.

There is another side effect of bitwise operators that gets used very infrequently.  Because they are bitwise, I can use them on integers as well as boolean values.

int i= 5 & 6;

is a perfectly legal construct in CSharp.  It will AND all the bits that make up 5  (101) and all the bits that make up 4 (100) and store the result in i (4 or 100).

On the other hand, && and || are strictly used for boolean expressions and will evaluate as little of the expression as it can get away with.

This is why we can write:

        if(s != null && s.Length > 0)
            // do something

If s is null, we already know that the expression will fail, so there is no need to evaluate the string’s length.

And now for one of my favorite binary statements.

There are 10 types of people in the world.  Those who understand binary and those who don’t.

 

Friday, March 13, 2009

Rather than using Copy[Ctrl C] and paste [Ctrl V] in pairs, developers can  store multiple cut/copy segments in the memory and use Ctrl+Shift+V to cycle through them.

To try this, simply select texts in editor and continue to copy your selections using Ctrl C. You can copy up to 20 selections at a time.

Now point your cursor where you want to insert these selections and select Ctrl+Shift+V. Keep hitting ‘V’ key to cycle through the list of all the selections you have.Hit enter and your selected selection will be pasted where cursor is located.

 

Tuesday, March 10, 2009

From my recent engagements I collected few performance anti-patterns that make ASP.NET web application to perform the way that is less than optimal. Many related to architecture and design.
Below is the list of the anti-patterns and related materials on how to identify, analyze, and fix it.
Have fun - if you feel like sharing your own experiences - that would rock my world!

Why My ASP.NET Application Slow?

 

Thursday, March 5, 2009

Introduction

JQuery is a powerful JavaScript library that enables the developer to do more in less code, a point which I hope to show you in this article. Rather than give a brief overview, let's learn in this article by example.

To start, JQuery uses the $ notation to target the HTML elements for retrieval or manipulation purposes. As an example, take a look at some of the ways you can access HTML elements.

Listing 1: Accessing a single or array of elements

  1. $("p") //accesses all p elements  
  2. $("#pid") //accesses an element by its ID  
  3. $(".p") //accesses elements using a class name  

The notation you see above, using an identifier within the $() notation, is a common approach across most JavaScript libraries. Not all libraries provide all three of these features as simple as JQuery does. Whether it's a single element or an array, JQuery makes working with elements easy. Let's take a look at what can be done with JQuery.

Selectors

As we saw above, JQuery makes it easy to access elements by an id, css class, or tag name. JQuery goes beyond this by providing a wide array of selectors all in one statement. The first selector I will demo provides the capability to drill down through a hierarchical structure, such as a table in Listing 2.

Listing 2: Parsing tables

  1. $("table > tbody > tr") //processes all table rows in a table  
  2. $("#t1 > tbody > tr") //processes all table roes in one specific table  
  3. $(".table > tbody > tr") // processes tables with the table class  

The greater than notation specifies the hierarchy of elements that must exist to match all TR elements; these patterns will not match TR elements within the header or footer of a table, nor would it match a table without a body element. Note that the id or class matching can be used anywhere in the selector. For instance, replacing the tr tag with a css class called "tablerow" would also work, but limits the results (which may be a more desired result).

Selectors can target one or multiple elements using a variety of patterns. Targeting multiple elements can be done by matching all elements of a specific tag type [$("p")], ore match multiple elements simultaneously using a comma separated list like: p, span, div. Selectors can also use filters that restrict the results returned, as shown in Listing 3.

Listing 3: Some of the available filters

  1. $(p:first)  //first in range  
  2. $(p:last)  //last in range  
  3. $(table > tbody > tr:even)  //even rows  
  4. $(table > tbody > tr:odd) //odd rows  
  5. $(p:eq(1)) //at index 1  
  6. $(p:gt(2)) //greater than 2, elements 3 and beyond  
  7. $(p:lt(10)) //less than 10, 0-9  
  8. $(p:empty) //where p has no children  
  9. $(p:parent) //where p is a parent  

Some of these filters are handy; for instance, when styling tables, using the :even and :odd filters work very well to create an alternating pattern. Using the :lt filter is good when you want to get the top 10 of something within a specific list. Accessing elements using an index (:eq) or getting the :first or :last in a list is always handy. Attributes can also be used to filter the results returned. For instance, take a look at using attributes to filter data.

Listing 4: Accessing text control values

  1. $("input[type='text']").css("color", "red");  

This is by no means a complete list; you can find more selectors at: http://docs.jquery.com/Selectors.

Accessing Content

JQuery provides access to the content of elements that expose a value and those that do not. Depending on the type of elements being accessed, these methods can extract this information. For instance, take a look at some of the assignments below.

Listing 5: Accessing content

  1. $("#span").html();  
  2. $(:input).val();  
  3. $("#name").text();  

In the examples above, some methods are used to extract information out of the underlying result set. The html() method allows the developer to extract the inner HTML information from the target element. The result-set must be singular in nature; this means that the results returned via $() has to be a single element; otherwise, the first element's value is returned. The val() method works differently; it can return a single result of the first element in the result. Notice the :input notation; this targets all text input controls. There are a couple of these filters available, which you can find out more at jquery.com.

When using these values, know that val() method looks for elements that have a value property associated with them. The html() method looks for the inner HTML contents of an element. The text() method gets the text of an element; this is the only multi-range method, as it concatenates the values into a single string.

Each of these methods works in a get and set mode; the get mode is the empty method call; passing in no value to the method performs a get call. When passing in a value, this performs a set operation, overriding the inner content.

There are other methods that can be used to manipulate HTML markup I didn't mention. One of the more common options is the css() method. This method takes two parameters: the name of the css value to modify, and the new value to apply. It can also take a collection of name value pairs in a class (noted by the {}). This makes it easy to apply css rules to a single or multiple elements.

Another popular method is the attr() method; this method reads or writes attributes of an element. To write an attribute, provide the name and value of the attribute to the method. Or, to set more than one attribute at a time, use the {} notation to set properties in bulk.

Take a look at some of the following examples.

Listing 6: Using css() and attr()

  1. $("p").css("background-color", "blue");  
  2. $("p").css({ "background-color" : "navy", "color", "white" });  
  3. $("button").attr("disabled", "disabled");  

These are by no means the only methods; there are other methods for modifying content; there are plenty of other methods that can modify the markup, such as wrapping content with HTML markup or replacing content with a substitute. You can find more documentation at: http://docs.jquery.com/Manipulation

Traversing Content

JQuery includes helpful methods that traverse the result set, or affect the results in a variety of ways. For instance, JQuery can navigate up or down the stack using the parent() or children() methods. These methods assume a single result of course, but these options are available.

In addition, other methods like the filter() method can trim down a larger result set; for instance, suppose that a JQuery result returns a collection of paragraph elements. The filter method can apply an expression that reduces the total number of results that will have a chained response applied to it. There are plenty of other methods for accessing the previous, next, sibling, and other related elements too.

Let's take a look at some of these methods in use:

Listing 7: Using the parent(), children(), and filter() methods

  1. alert($("#pid").parent().tagName);  
  2. $("#pid").children().hide();  
  3. $("#pid").children("[type='hidden']:first").val();  
  4. $("p").filter(".highlighting").show();  

There are plenty of other methods used for traversing content available at: http://docs.jquery.com/Traversing.

Events

JQuery can listen to object events. The most notable and frequently used event is the ready event, an event that fires when the browser has loaded. To attach to the ready event, do the following.

Listing 8: Attaching to the ready event

  1. $(document).ready(function() { .. });  

The ready event is where most of the code processing is placed, but this isn't required. If using ASP.NET AJAX, the page's client-side init or load event handler is another opportune place to put initialization code in. JQuery isn't limited to the ready event; it can also listen to other events like:

Listing 9: Handling a button click

  1. $("#buttonid").click(function() { alert("BUTTON CLICK"); }  

Handling events is a pretty standard process, as shown above. In the event definition, the this pointer actually refers to the object that raised the event (the button that was clicked, in the case of listing 7).

There are some other options to attaching events, but that is out of scope for this article. You can find more about events at: http://docs.jquery.com/Events.

 

1. The Byzantine Generals Problem (1982) by Leslie Lamport, Robert Shostak and Marshall Pease - The problem with distributed consensus
2. Go To statements considered harmfull (1968) - by Edsger W. Dijkstra - Didn't you always want to know why ? :)
3. A Note on Distributed Computing (1994) - by Samuel C. Kendall, Jim Waldo, Ann Wollrath and Geoff Wyant - Also on Michael's list but it is one of the foundation papers on distributed computing
4. Big Ball of Mud (1999) - Brian Foote and Joseph Yoder - patterns or anti-patterns?
5. No Silver Bullet Essence and Accidents of Software Engineering (1987) - Frederick P. Brooks - On the limitations of Technology and Technological innovations.
6. The Open Closed Principle (1996) - Robert C. Martin (Uncle Bob) - The first in a series of articles on Object Oriented Principles (you remember the debate on SOLID...)
7. IEEE1471-2000 A recommended practice for architectural description of software intensive systems (2000) various- It is a standard and not a paper but it is the best foundation for describing a software architecture I know.
8. Harvest, Yield, and Scalable Tolerant Systems (1999) Armando Fox, Eric A. Brewer - That's where the CAP theorem was first defined
9. An Introduction to Software Architecture (1993) - David Garlan and Mary Shaw - one of the foundation articles of software architecture field (although based on earlier work by the two)
10. Who Needs an Architect? (2003) Martin Fowler - Do we or don't we?

 

More

  1. On the criteria to be used in decomposing systems into modules – David Parnas
  2. A Note On Distributed Computing – Jim Waldo, Geoff Wyant, Ann Wollrath, Sam Kendall
  3. The Next 700 Programming Languages – P. J. Landin
  4. Can Programming Be Liberated from the von Neumann Style? – John Backus
  5. Reflections on Trusting Trust – Ken Thompson
  6. Lisp: Good News, Bad News, How to Win Big – Richard Gabriel
  7. An experimental evaluation of the assumption of independence in multiversion programming – John Knight and Nancy Leveson
  8. Arguments and Results – James Noble
  9. A Laboratory For Teaching Object-Oriented Thinking – Kent Beck, Ward Cunningham
  10. Programming as an Experience: the inspiration for Self – David Ungar, Randall B. Smith

On the criteria to be used in decomposing systems into modules – Parnas

This is a very old paper, but it is more than a classic. In in it, Parnas introduces a forerunner to the Single Responsibility Principle. He introduces the idea that we should use modularity to hide design decisions – things which could change. People still don’t consider this as often as they should.

Another thing I really like in the paper is his comment on the KWIC system which he used as an example. He mentioned that it would take a good programmer a week or two to code. Today, it would take practically no time at all. Thumbs up for improved skills and better tools. We have made progress.

A Note On Distributed Computing – Waldo, Wyant, Wollrath, Kendall

Abstraction is great but it can only go so far. In this paper, the authors lay to rest what was once a pervasive myth – that we could design a distributed system and make distribution transparent. Ever wonder why you had to implement specific interfaces to do remoting in Java? This is why.

In the aftermath it might seem hard to believe that people thought this was possible. I think we can we partially thank this paper for that.

The Next 700 Programming Languages – Landin

Most of us have spent a lot of time working in traditional programming languages, but functional programming languages are slowly seeing an uptick and many OO languages are gaining functional features. This paper (which reads like a tutorial) makes an argument for an expression-oriented style of programming. It also lays the foundation for lazy evaluation.

One of the other neat things about this paper, from a historical point of view, is that there is a discussion section at the end in which there a number of questions and comments about whether making indentation significant in a language is a good idea. I was thrown to see people asking whether or not this would be a problem for functions which span over several pages(!).

Can Programming Be Liberated from the von Neumann Style? – Backus

John Backus is known for a number of achievements in computer science. He received the ACM Turing Award for his work on Fortran. This paper, which he presented at the award ceremony was rather shocking at the time because it said, in essence, “we got it wrong.” Backus took the opportunity to make a plea for pure functional programming. His arguments were convincing and they helped to set a research agenda which is just now starting to make some waves in the mainstream.

Reflections on Trusting Trust – Thompson

I once heard that when this paper was presented, people in attendance rushed back to de-compile their C compilers and look for, er, problems. This paper unveiled a hard problem at the heart of computer security. If you’ve spent any time at all thinking about security, you need to read it.

Lisp: Good News, Bad News, How to Win Big – Gabriel

This paper is a bit atypical in this list. It’s aimed at the Lisp community and it comes off as a bit of a lament. But, hidden deep within it is the Gabriel’s description of the ‘Worse is Better’ philosophy – an idea with profound implications for the acceptance and spread of technology.

An experimental evaluation of the assumption of independence in multiversion programming – John Knight and Nancy Leveson

Behind this dry title lies something very interesting. I first heard about this paper from Ralph Johnson in a newsgroup discussion about program correctness. It turns out that one of the avenues that engineers in other disciplines take to make their products stronger – redundancy – doesn’t really work in software. Multi-version programming was the idea that you could decrease faults in critical systems by handing the spec to several teams, having them develop the software independently, and then having the systems run in parallel. A monitoring process verifies their results and if there is any discrepancy it picks the most common result. Sounds like it should work, right? Well..

Arguments and Results – Noble

I think that all of the other papers in this list are rather well known in some circles. This one isn’t, or if it is, I just haven’t found that circle yet. What I like about this paper is that it takes something which we deal with every day – the set of arguments and results of functions – and it works them through a series of variations which just don’t occur to many people. The fact is, every function that you work with has a number of possible directions if could evolve in. Not all of them are appropriate, but if you know the possible directions, you’re richer for it.

A Laboratory For Teaching Object-Oriented Thinking – Beck, Cunningham

There are an incredible number of papers about there about object orientation. The thing which makes this one great is its directness. OO went through a number of stages. It was once fresh and novel, then it was ornate, and then it became matter-of-fact. This paper hits upon key ideas which many people don’t talk about much any more: anthropomorphism and dropping the top/down perspective. It also shows you how you can design with index cards. It may not sound cool but it is incredibly effective.

Programming as an Experience: the inspiration for Self – Ungar, Smith

How many people know about the Self Project? Not enough in my opinion. Self was an attempt to take two ideas in computing and push them as far as humanly possible. The first was minimalism: the Self programming language was thoroughly in the Lisp and Smalltalk vein – everything was defined in terms of the smallest number of primitives possible. The other idea was direct manipulation – the idea that the object metaphor could be pushed all the way in the user interface – the programmer and user sit with a mouse in a sea of directly clickable objects and use them for everything. If they could’ve gotten away with dropping the keyboard, I think they would’ve.

The amount of technology which the Self project threw off is terrifying also. Self broke ground in dynamic language optimization and VM design. Chances are, your VM uses technology it pioneered. It’s also one of the more perverse ironies that the most widely distributed programming language today (JavaScript) is a prototype-based programming language which borrowed ideas from the hyper-research-y Self.

More

Tuesday, March 3, 2009

In your applications there may be times when you want to give the user the ability to override a setting or configuration value.  Often times you want to provide sensible defaults so that every single configuration option does not have to be specified, only those you which to override.  I want to show a very simple way to make your applications a bit smarter when creating classes with overridable default values.

Example 1:

   1: public class DemoObejct

   2: {

   3:     private string DEFAULT_MESSAGE = "Thank you for your order";

   4:    

   5:     private string message = DEFAULT_MESSAGE;

   6:    

   7:     public string Message

   8:     {

   9:         get { return message; }

  10:         set { message = value; }

  11:     }

  12: }

Example 2:

   1: public class DemoObejct

   2: {

   3:     private string DEFAULT_MESSAGE = "Thank you for your order";

   4:    

   5:     private string message;

   6:    

   7:     public string Message

   8:     {

   9:         get { return message ?? DEFAULT_MESSAGE; }

  10:         set { message = value; }

  11:     }

  12: }

So what's the difference?  The difference IS subtle but I consider the following code snippet:

   1: var obj = new DemoObject();

   2: 

   3: Console.WriteLine(obj.Message);

   4: 

   5: obj.Message = null;

   6: 

   7: Console.WriteLine(obj.Message);

Setting the Message property to null in line 5 results in different behavior between the two examples.  I find the second example to be preferable, setting the property to null invokes the default message again.  It's a very simple thing you can do to provide a more robust object

Here are two more examples where I use this strategy often:

Integers and Default Values:

   1: public class DemoObject

   2: {

   3:     private int? attemptThreshold;

   4:     private const int DEFAULT_ATTEMPTTHRESHOLD = 3;        

   5:        

   6:     public int AttemptThreshold

   7:     {

   8:         get { return attemptThreshold.HasValue ? attemptThreshold.Value : DEFAULT_ATTEMPTTHRESHOLD; }

   9:         set { attemptThreshold = value; }

  10:     }

  11: }

Logging Component:

   1: public class DemoObject

   2: {

   3:     private ILogger logger;

   4: 

   5:     public ILogger Logger

   6:     {

   7:         get { return logger ?? NullLogger.Instance; }

   8:         set { logger = value; }

   9:     }

  10: }

The above logging example is where this type of strategy really shines.  It prevents NullReferenceExceptions in your code if by chance your logger gets a null value at some point, again providing for a more robust object and application.

 

Thursday, February 26, 2009

Just released LinqExtender 2.0. Over previous release , it contains generally bugs fixes. Overall, I have focused on striping out complexity as much as possible to keep you focused on your business logic. You can see the full list of features in the documentation that comes with it.

Now, while creating the LinqToTwitter example, I have shown that creating custom providers with LinqExtender requires two steps, first you have to define a query object by implementing IQueryObject and then you have made a Query<T> successor and override few methods. In LinqExtender, object/ entity equivalent is Bucket. Starting from 2.0, there is a Fluent interface implementation of it that works as an internal DSL and gives you a single entry point for all query and update , inserts and delete, thus making things more declarative and one way.

In this post, I will show you how to generate SQL statement from LINQ query with nested where clause, using the fluent interface implementation. To start, let's consider the following query

var query = from book in bookContext
where ((book.Author == "Mehfuz" && book.ISBN == "2") || book.Id == books[2].Id) || 
(book.Author == "Paolo Pialorsi" && (book.ISBN == "100-11-777" || book.ISBN == "1"))
select book;

It's taken from the Entrypoint.cs test class that comes with LinqExtender project along with OpenLinqToSql sample ORM. Now, to do things in a very basic way. Let's first create a string builder and append the initial select.

StringBuilder builder = new StringBuilder("SELECT * FROM [" + Bucket.Instance.Entity.Name + "]");

To be precise, Bucket.Instance is the entry point for all query and object details. Moving to where statement , LinqExtender uses simplified expression tree that is exposed by Bucket.Instance.ExpressionTree. All we need to setup how the output will look like and the rest will be covered by the toolkit.

builder.Append("WHERE");
builder.Append("\r\n");
 
Bucket.Instance.ExpressionTree.Setup
.Begin(delegate
{
    builder.Append("(");
})
.Root(delegate(OperatorType operatorType)
{
    builder.Append(" " + operatorType + " ");
})
.EachLeaf(delegate(BucketItem item)
{
    string value = GetValue(item.Value);
    builder.Append(item.Name + RelationalOperators[item.RelationType] + value);
})
.End(delegate
{
    builder.Append(")");
})
.Execute();

Here, let assume that GetValue(..) will return a formatted SQL string and ReleationalOperators is a dictionary that has mappings for item.RealtionType ( GreaterThan -> ">" , LessThan => "<", etc). Basically, as the implementation shows, we are defining how the tree output will take place.All these code should be placed in Query<T>.Process(IModify<T> items) method and on execute it will just return the following SQL

Select * from book 
 WHERE
(((Author='Mehfuz' AND ISBN='2') OR Bk_Id='1734') 
OR (Author='Paolo Pialorsi' AND (ISBN='100-11-777' OR ISBN='1'))) 

Extender basically knows how to get though this nested where clause. From basic computer science, it builds linked objects based on a Syntax Tree, with each parenthesis adding diversion to the tree like shown below

So far, this is a very rudimentary example. With 2.0 it is also possible to build your own reusable format provider for building literals that saves repetitive code blocks for same kind of task (updating a database). This is actually just a schema builder that defines how the output will look like using the same Bucket.Instance calls. Out of the box, TSqlFormatProvider is provided.Depending under which Query<T> method it is used; it will generate insert, update, delete or select statement where all you have to call Bucket.Instance.Translate(...).

string sql = Bucket.Instance.Translate(new TSqlFormatProvider());

This enables you to build not only your own LINQ to Anything format providers but also share it with the community to reuse what is already out there. More information on how to get started can be found at the project documentation.

In a word, Bucket.Instance is all you need to go through and build your own LINQ provider. Optionally, you can override the following methods (under Query<T>) to give your provider various OTS (Object tracking service) support .

1. AddItem () - called during SubmitChanges() call for new object.
2. RemoveItem () - called during SubmitChanges() call for Delete.
3. UpdateItem () – called during SubmitChanges() call for update.

I have updated Creating LinqToTwitter using LinqExtender post with the latest release. You can get a copy of the latest 2.0 release from www.codeplex.com/linqextender,  and of course as usual all your feedbacks are really helping to shape the toolkit.

More

Tuesday, February 24, 2009

OutOfMemory exceptions are often caused by address space fragmentation in Visual Studio process. For users experiencing excessive OutOfMemory exceptions we provide a tool which overrides Visual Studio's memory allocation policy to ensure more continuous address space for Common Language Runtime.

To use the tool download wrappers.zip file, unpack it and run devenv2005_wrap and devenv2008_wrap instead of devenv.exe for Visual Studio 2005 and 2008 correspondingly.

In some cases Visual Studio fails to start under wrappers. Check AppInit_DLLs. Rogue DLLs activated from there can interfere with wrappers. Example: wxvault.dll preinstalled with Dell laptops.

Sometimes wrappers won't help (because it's simply not enough memory), see http://stevenharman.net/blog/archive/2008/04/29/hacking-visual-studio-to-use-more-than-2gigabytes-of-memory.aspx for other solutions and explanations.

Thanks,

JetBrains

It's a common problem: you have a registration form, but you want to prevent user names or other values from being used more than once. You need a user-friendly way to prevent duplicate values being submitted. This is where the simplicity of jQuery excels.

User names and passwords are normally stored within a database. Commonly, developers wait until the form has been submitted before they perform any duplicate checking. This means that the user has to wait for a postback to complete before being informed that the user name they chose is already in use, and that they need to choose another one. Ajax tidies this up by allowing asynchronous querying of databases.

This example shows a very simple form:

 

<form id="form1" runat="server"> 

<div id="register"> 

  <fieldset>

    <legend>Register</legend>

    <div class="row">

      <span class="label">User Name:</span>

      <asp:TextBox ID="UserName" runat="server"></asp:TextBox><span id="duplicate"></span>

    </div>

    <div class="row">

      <span class="label">Password:</span>

      <asp:TextBox ID="Password" runat="server"></asp:TextBox>

    </div>

    <div class="row">

      <span class="label">&nbsp;</span>

      <asp:Button ID="btnRegister" runat="server" Text="Register" />

    </div>

  </fieldset>

</div> 

</form> 

 

A web service will be used to house the method that checks the database for possible duplicates:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Web.Script.Services;

using System.Data.SqlClient;

 

/// <summary>

/// Summary description for UserService

/// </summary>

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

 

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[ScriptService]

public class UserService : WebService {

 

    public UserService () {

    }

 

    [WebMethod]

    public int CheckUser(string username)

    {

      string connect = @"Server=SERVER;Database=Database;Trusted_Connection=True;";

      string query = "SELECT COUNT(*) FROM Users WHERE UserName = @UserName";

      using(SqlConnection conn = new SqlConnection(connect))

      {

        using(SqlCommand cmd = new SqlCommand(query, conn))

        {

          cmd.Parameters.AddWithValue("UserName", username);

          conn.Open();

          return (int)cmd.ExecuteScalar();

        }

      }

    }

}

 

There's nothing clever about this code. One (Web) method - CheckUser() - accepts a string as an argument and then returns the number of rows in the database where that name is found. The [ScriptService] attribute is uncommented, so that the service is availabe to AJAX calls (not just ASP.NET AJAX, incidentally).

Now we'll look at the Javascript that uses jQuery to effect the call:

 

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> 

<script type="text/javascript"> 

  $(function() {

    $("#UserName").change(checkUser);

  });

 

  function checkUser() {

    $.ajax({

      type: "POST",

      url: "UserService.asmx/CheckUser",

      data: "{username: '" + $('#UserName').val() + "'}",

      contentType: "application/json; charset=utf-8",

      dataType: "json",

      success: function(response) {

        var retval = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

        $("#duplicate").empty();

        if (response.d != "0") {

          $("#duplicate").html('That user name has alrady been taken');

        }

      }

    });

  }

 

</script> 

 

The first <script> tag brings in the jQuery library from Google's public code repository. Then an event handler is added to the element with the ID of UserName, which is the TextBox waiting for the user to put their chosen User Name in. The handler is wired up to the TextBox's onchange event, and calls the checkUser() function. Then the checkUser() function is defined in code.

When the user has added some text to the TextBox and then moves their cursor away, the chenage event is fired, and an AJAX call is made to the web service. If the response is not 0, then the web method has foound at least one row that matches the user name that the user is attempting to submit. The <span> with the ID is "duplicate" is emptied of any messages resulting from previous attempts, and the message displayed to the user.

More