Linq Expressions on an Interface

One thing I found myself doing quite a bit an often causing logic errors was comparing
dates in Linq queries. For example, if I want to get games that occur between a date range, I might be
doing something like this :

	public static IQueryable<Competition> GetBetweenDates(DateTime startDate, DateTime endDate)
	{
		return (from comp in DataContext.Competitions
				where comp.Date >= startDate && comp.Date <= endDate
				select comp);
	}

I then want to get a list of tournaments that occur between a date range, and I might
essentially rewrite this code using a couple different variables. Rather, I can implement
a common interface on these classes and have an expression applied to all classes that
implement this interface.

	public interface IDate
	{
		DateTime Date { get; set; }
	}

	public partial class Competition : DataBase, IDate
	{
		...
	}

	public static class Expressions
	{
        public static Expression<Func<T, bool>> GetBetweenDates<T>(DateTime start, DateTime end)
            where T : IDate
        {
            return (t => t.Date >= start && t.Date <= end);
        }
	}

Then, rather than rewriting this for each class with a date, I can just apply this expression
to my queries.

	public static IQueryable<Competition> GetBetweenDates(DateTime startDate, DateTime endDate)
	{
		return (from comp in DataContext.Competitions
			select comp).Where(
                             Expressions.GetBetweenDates<Competition>(startDate, endDate));
	}

jQuery Custom Selector for selecting elements by exact text :textEquals

I needed a way to find labels based on the text that they contained.  I thought about using :contains() for this, but in this particular case the text items I was searching on were names and I could have similar names that :contains() could incorrectly match on.  For instance, if I was searching for “Banks, Tim” and there was an item with the text “Banks, Timothy” I would get both items returned.  This is not the behavior I was looking for.

I decided to write a little custom selector to match on exact text.  Here is the code for the custom selector:

$.expr[':'].textEquals = function(a, i, m) {
return $(a).text().match("^" + m[3] + "$");
};

What is happening here is I am using a regular expression to test if the start and end of the element’s text matches the string passed in.  Now I could search for the name “Banks, Tim” on a label element like this:

$("label:textEquals('Banks, Tim')");

Make Table Rows Sortable Using jQuery UI Sortable

So you want to make table rows sortable using jQuery UI? Luckily, the Sortable interaction does most of the work for you.

But there’s a catch: one problem that I ran into when implementing this (with UI version 1.7) was the cell widths of the row would collapse once I started dragging it.

Suppose you have a table of data, like this one:

<table id="sort" class="grid" title="Kurt Vonnegut novels">
	<thead>
		<tr><th>Year</th><th>Title</th><th>Grade</th></tr>
	</thead>
	<tbody>
		<tr><td>1969</td><td>Slaughterhouse-Five</td><td>A+</td></tr>
		<tr><td>1952</td><td>Player Piano</td><td>B</td></tr>
		<tr><td>1963</td><td>Cat's Cradle</td><td>A+</td></tr>
		<tr><td>1973</td><td>Breakfast of Champions</td><td>C</td></tr>
		<tr><td>1965</td><td>God Bless You, Mr. Rosewater</td><td>A</td></tr>
	</tbody>
</table>

Your first attempt to make it sortable might look like this:

$("#sort tbody").sortable().disableSelection();

And it actually works, but there is a bit of a problem. The cell widths seem to be collapsing once you start dragging a row (notice how close the “C” cell is to the “Breakfast of Champions” cell). It looks like this:

Sortable row collapsed widths

The problem has to do with the helper object. The helper object is basically the DOM element that follows the cursor during the drag event. When it is created by default, the cells collapse to the size of the content inside of them.

You can specify a function that returns a jQuery object to create a custom helper object. By creating a function that will keep the cell widths consistent, this problem can be fixed.

// Return a helper with preserved width of cells
var fixHelper = function(e, ui) {
	ui.children().each(function() {
		$(this).width($(this).width());
	});
	return ui;
};

$("#sort tbody").sortable({
	helper: fixHelper
}).disableSelection();

Now it works as expected:
Sortable row fixed

Keep Original Variable State Between Event Binding and Execution – JavaScript

Also known as: Binding Events Inside of a Loop with jQuery

Sometimes I want to create a closure that accesses a variable in the state that it was in when the closure was created. I don’t want to know what the current value is, I want to know what the value was when I created the function. I may want to do this when binding an event to a DOM object, or when executing a function inside of setTimeout().

The Problem

Here is an example of the problem using the jQuery library (consider what will happen when you click on any of the li elements):

	$(function() {
		$("body").append("<ul id='container'></ul>");

		for (var i = 0; i < 5; i++)
		{
			var $item = $("<li />").text("Item " + i);
			$("#container").append($item);

			$item.click(function() {
				alert("You clicked number " + i);  // always "You clicked number 5"
			});
		}
	});

The event handler will always use the final value of the variable “i”, which will be 5 in this case. One way to fix this problem is to create a function and pass “i” as a formal parameter:

Solution 1 – Traditional Function

	function bindItem($item, ind) {
		$item.click(function() {
			alert("You clicked number " + ind);  // Works as expected
		});
	}

	$(function() {
		$("body").append("<ul id='container'></ul>");

		for (var i = 0; i < 5; i++)
		{
			var $item = $("<li />").text("Item " + i);
			$("#container").append($item);
			bindItem($item, i);
		}
	});

Since this passes the variable as a parameter to a function, the variable “ind” will always remain the same, even if “i” changes after the function finishes execution. The function bindItem() creates a new scope. Any variables (passed as parameters or declared inside the function) will reserve their own space in memory, and will not be affected by the state of the variable ‘i’. Thanks to reddit user Mych for correcting me.

This is what I wanted in the first place, but we may not want to have a named function here – if we used a closure we would still have access to variables in the same scope (like $item) without having to pass them as parameters to bindItem().

This does the trick:

Solution 2 – Self Executing Function

	$(function() {
		$("body").append("<ul id='container'></ul>");

		for (var i = 0; i < 5; i++)
		{
			var $item = $("<li />").text("Item " + i);
			$("#container").append($item);

			(function() { // Closure here here instead of "bindItem()"
				var ind = i;
				$item.click(function() {
					alert("You clicked number " + ind); // Works as expected
				});
			})(); // Execute immediately
		}
	});

This is a trick I first saw in the jQuery plugin development tutorial, in the custom alias section.

Declaring the closure creates a new scope in the loop. Any variables (such as ‘ind’) passed as parameters or declared inside of this scope will reserve a new space in memory that is not a reference to ‘i’.

The extra parentheses at the end of a block like this “(function() {…})()” cause the closure to execute immediately .

These are just a couple ways to solve the problem of variable state changing between event binding and execution. Closures are a powerful language feature that makes JavaScript very flexible, but when execution of them is being delayed via a timeout or event handler, it is important to keep track of the variables that they are closed over.

Adapting a Development Process

One of the key reasons to choose a rapid development philosophy over a waterfall development philosophy is the ability to adapt to changing requirements.  Once you decide to go with some form of rapid development – which should you choose?  It seems like there are as many options as there are companies utilizing them.

There is no one correct answer.  My advice is to pick and choose what works best for your development team, your product, your customers, and your company.  In addition to adopting a development philosophy that allows rapid change in requirements of your software – be prepared to rapidly change the process itself.  Our process has changed dramatically over my years at Lanit due to new people, new priorities, new technologies, and new tools.

At Lanit, we are currently using a form of Agile software development.  We have very few rigid processes that the design/development team must follow – instead we have a toolbox from which we grab the appropriate tool from in any situation.  Below I will give an overview of a lot of things we do here.  Hopefully some of the things we do will be useful for you/your team.

Planning

Some agile shops will say that you should avoid all planning.  I don’t think that scales well to complicated problems  (and, I don’t really believe they don’t plan – they just have shorter term plans or personal plans).  We plan at Lanit – we are just ready for our plans to change at any time.  And, we are careful to scope our plans appropriately – longer term plans are more vague, shorter term plans get more specific.

Vision statements

Vision statements are simple, vague, big picture plans which are useful to guide the smaller picture plans later.  Be careful not to get too detailed so that it’s easy to adapt.

  • Company/Strategic planning – Lanit has a vague mission statement that pertains to everything we do, and helps guide our smaller plans.  Basically, we want to write software that improves people’s lives in a meaningful way.
  • Product planning – Each product sets forth its own broad goals.    For Foliotek, we want to make the accreditation process easy for schools by providing sensible, clean, and easy to use portfolio software.  We focus on making the portfolio process as simple as possible for students and faculty to ease the burden that adding a portfolio culture to a school can create.
  • Release planning – Often times, we have a common goal (or a few goals) that helps us decide on feature sets for each release we do.  Recently, we’ve had releases that focused on making the system more maintainable by adopting some newly available frameworks throughout a project.  An upcoming release will focus on adding more interactivity to the system through the use of more client scripting and ajax.

Releases and Feature evaluation

For existing products at Lanit, we develop in 8 week cycles.   If anything takes longer than that to get from idea to release, then we run the same risks of the waterfall model – we either build something that is to late to market (the market changes between when we plan and when we release).  Or, we waste a bunch of effort because we got the plan wrong to begin with, and spent months developing the wrong thing.  As with all rapid development philosophies – the point is to find out as soon as possible when you make a mistake and change course immediately.  Even inside of the 8 week cycle, you’ll see we allow customers to see and comment on complicated designs sooner.

For existing products – we keep feature wishlists that eventually evolve into planned feature sets for a particular release.  We use FogBugz (http://fogbugz.com) to store the wishlists, and items move to different projects (new ideas -> for development) and releases (undecided release -> Summer 01 2009) as we evaluate the lists.

  1. Keep an ongoing wishlist
    • from customers (help them succeed with how they want to use the product)
    • from business team (help sell the product to new customers)
    • from support team (spot trouble spots, ease support burden)
    • from development team (more maintainable code, or newer and better technologies)
  2. Shortly before starting to develop a release (at most a week, so that you have the best possible information), pull the most valuable ideas into a release wishlist
    • usually, stakeholders from support/business/dev make a ‘top ten’ type list, then combine them to create an initial release list
    • this is also a good time to completely eliminate ideas from the wishlist that are no longer valid
  3. Dev team comes up with very rough estimates to develop ideas
  4. Dev, support, and marketing ranks the wishlist based on cost/benefit type analysis (usually, in a meeting.  also a good time to describe and document the needs of each feature better).  Often, the idea is refined or simplified based on discussions in this meeting.  We always try to build the simplest useful version of a feature possible, and only add complexity after people have tried the simple version and more is still needed.
  5. Narrow down the release to a reasonable list based on available time and estimates
  6. Dev team works on the list in order of priority – Everyone knows that the bottom items may drop into the next release based on changing circumstances and priorities.  This also allows for new items to be injected at the cost of items at the bottom, and allows more time to think about the expensive, less well defined items that should be further down the list.

Designing/Developing Features

The rest of the work is taking the requested feature and taking it to implementation.  This process has the most variability – some features are small and easily understood, a text description is enough to develop it.  Some features are more detailed or important and require more elaborate designs.  The most expensive features to implement should be discussed with customers at early stages to prevent wasted effort.  So, we never mandate that each feature must go through these steps – the dev team is allowed to determine which tasks are appropriate for the item they are working on.

  • Feature descriptions – pretty much every feature idea has at least a sentence in FogBugz describing it.  Typically, links to current screens are included (for “change” type requests) to get everyone on the same page.  Often, the descriptions are detailed during the release feature set prioritization meeting.
  • Paper sketches – if the feature has a small amount of sophistication, it often useful for the developer to do a rough paper sketch for their own benefit.  This could be a UI sketch, a db model, a flow diagram, etc.
  • Informal discussion – sometimes, a brief chat about the feature is all that is necessary.  Face-to-Face can be a double edged sword – they can be very powerful for the person that needs help, and very distracting for the other party.  We use yammer (http://yammer.com) for these kinds of communications so that each person can decide their level of interruptibility (each user can decide to have an IM-like client open, to get email notifcations, to get daily email digests, etc – and can customize those options based on subject).  Many times, we still talk face to face – but we initiate conversations using yammer instead of physically disrupting the other person.
  • Plain ‘ol Whiteboards (POWs) – Sometimes, features are too hard to describe.  Others, the business team only has a need (this is too slow/complicated) but doesn’t have a clue how it should be solved.  In these cases, it’s useful to collaboratively sketch ideas at a whiteboard.
    • POWs can become real, permanent documentation!  We use a few handy tools in combo to make this happen:
      • A digital camera
      • An Eye-Fi (http://www.eye.fi/) wireless SD card – gets pictures to us without the hassle of a card reader
      • EverNote (http://www.evernote.com) – archives whiteboard photos.  Allows easily retrieval through tags, and even can OCR/search some handwritten text in a pic.  Integrates with Eye-Fi – so you get a new note with each pic without any hassle.  Synchs across all popular computers and smartphones.
      • Whiteboard Photo (http://www.polyvision.com/ProductSolutions/WhiteboardPhotoSoftware/tabid/284/Default.aspx) – software package that takes a photo of a whiteboard and cleans it up a ton – picture ends up looking like it was sketched in paint.  Allows copy-paste – so you can click the photo in evernote, ctrl-c, click whiteboard photo, ctrl-v, clean, and repeat in opposite direction.
  • Comps – sometimes, the detail needed is aesthetic.  In those cases, someone is commissioned to a more refined Photoshop or Fireworks comp (often based on a sketch).
  • Paper or digital sketch “prototypes” -  Sometimes, the feature/ui itself is complicated.  In these cases its useful to get feedback from inside the team and from customers before you write a bunch of code.  Most of the time, you can get the info you need by walking the customer through sketches – either by explaining a flipping through a succession of paper sketches, or by building digital sketches in Fireworks – which can be linked together and allow clicking between screens.  This is a good low cost way to get something that feels a lot like a programmed prototype.
  • Coded prototype/betas – When a feature is very interactive, or is highly data driven, etc – sometimes you need something real to evaluate the design.  In those cases we build out the feature as small as possible and release it to a carefully chosen set of customers (or ourselves) for “real” use – and we tweak it before we release to everyone.

Testing and Maintanance

After the dev team believes it is done, the release is pushed to a testing area.  The main contact for each new feature request is responsible for testing it to make sure that it works properly and fills the intended need.  We usually spend about a week going back and forth with the support/sales teams until everyone is satisfied with the release.  Then, it goes out to our customers.

We’re not perfect.  Sometimes, bugs get out to the live environment.  For the highest priority issues, the support team can interrupt new development and get an immediate resolution.

Doing this for every trivial issue would severely hamper new development, so we limit these cases to a small number per year. For all other issues, we have a weekly patch schedule.  Support reports problems (to another area in FogBugz), and we fix throughout the week.  On Mondays, we send the set of fixes all out at once.  To keep the developers sane, we rotate the developer responsible for writing fixes each week.

This schedule allows the dev team to stay focused on making the product better – but also allows the support team to be responsive about issues in the system.  Customers are more accepting of problems when we can tell them when it will be fixed.

“Green Field” development

So far, I’ve focused on how we develop changes and additions for our existing products.  Many of these techniques are also useful for developing brand new products.  Planning new projects can often be more complicated, though, and features aren’t as well understood to begin with.  Many more decisions need to be made.

  • Brainstorming sessions – Early on, the idea is very vague.  The quickest way to narrow it down into a plan is to get people into a room and come up with ideas.  Be sure to involve potential customers.  We’ve been very successful by developing “advisory boards” of people who are in your market – and allowing them to help brainstorm and design the product.  When they are done, not only does your product fit the market better – but you end up with a group of devoted customers right off the bat since they feel some ownership of the product.
  • Multi disciplinary team design sessions – IDEO developed a method where you take a problem, and design separate solutions in several small groups of about three or four.  Then, you come back and evaluate as a group and combine the ideas into one solution.  This can be very useful for developing a feature set for a new product.  For best results, each team should have a tech person, a business person, a support person, etc.
  • User Studies – The best way to get all of the little details right is to sit down with a real user and watch them try to use your new product.  You don’t need expensive equipment – just sit down and watch, and take notes or record with a webcam.  You don’t need a completely functioning system – you can (and should) walk users through paper sketches (what would you click on here – ok, now you see this) and later have them use sketch prototypes (click through – ok that would be added here when its a real system).  If the system is really interactive, build a simple html/js prototype.  You also don’t need scientific population samples -  any 3-5 people you grab (your spouse, neighbors, friends…) will catch all of your really important usability problems.

Internationalization Data Storage in .NET (Part 1)

.NET has many built in structures for setting up your web application to support multiple languages. Most of which reside in the System.Globalization namespace. Within the System.Globalization namespace you get access to the CultureInfo class. This class defines how datatypes such as Dates, Currency and other culture related objects are displayed.

For example if the CultureInfo object is set to “mx-es” (spanish) the date would be displayed dd/mm/yyyy instead of mm/dd/yyyy. You can manage all the output settings by setting their respective properties in the CultureInfo class.

Now that we have a very basic idea of what the built in .NET tools provide us in terms of displaying internationalized data lets take a look at the solutions we have for storing globalized data.

So lets say we have a database table called Product with a field called “Description” we want to internationalize:

ProductID Name Description Date Added
1 Vista If you own or run a small business, you’ll want Windows Vista Business. 6/22/2009 3:57:07 PM

To store the multiple langages we could add a columns for each language to the table structure and subsequently update all related dependencies. Storing values in this manner is something we want to avoid here at LANIT.

Another option would be to build a look up table that stores translated values and replaces our description with a reference. This method would allow for efficiently searching and indexing but would increase the complexity of our database structure.

In our situation we decided to store every language into an XML document. The benefits of doing it this way is it allows us to add infinitely many translated versions of the product name without affecting are database structure. The draw back of using this method is the inability to efficiently search through the database on the internationalized column(s).

Let’s say we wanted to store English/French/Spanish/German translations of our product description we could do so by generating an XML file that looks similar to this.

<?xml version="1.0" encoding="utf-8" ?>
<localizedString>
<value language="en-US"> If you own or run a small business, you'll want Windows Vista Business.</value>
<value language="es-MX">Si usted es dueño o ejecutar un pequeño negocio, usted desea que Windows Vista Business.</value>
<value language="fr-FR">Si vous êtes propriétaire ou de lancer une petite entreprise, vous souhaitez que Windows Vista Business.  </value>
<value language="de-DE">Wenn Sie selbst oder ein kleines Unternehmen, Sie wollen Windows Vista Business.</value>
</localizedString>

Each value element represents a language and has an attribute called language which is set to a culture name. A list of culture names can be found here MSDN Culture Names

Updated Table Data:

ProductID Name Description Date Added
1 Vista <?xml version=”1.0″ encoding=”utf-8″ ?> 6/22/2009 3:57:07 PM

This provides us with a data storing model that will fit very easily into the current database structure and also provide us the ability to scale to as many languages as we see fit in the future.

That is it for part 1 . In part 2 I will discuss building a class/datatype that will get,set and build the above XML document for storing our translated values.

Accessible Custom AJAX and .NET

One general rule in making an accessible web application is that you shouldn’t change content of the page with javascript. This is because screen readers have a tough time monitoring the page and notifying the user of dynamic changes. Usually, the reason you would use Ajax is exactly that – do something on the server, and then update some small part of the page without causing the whole page to refresh. That means if you have an “ajaxy” page and you care about accessibility, you have to provide a non-ajax interface as a fallback for screen readers.

Ajax.NET, Microsoft’s library for Ajax, makes this fallback easy to implement. Microsoft has you define your AJAX properties in an abstraction layer – the page XAML – which means that the framework can decide to not render the AJAX code to certain browsers (and screen readers) that will not support it, and instead use the standard postback method.

The problem with Ajax.NET is that the communication can be bloated (mostly because of the abstraction layer, it sends more post values than you might need – like the encrypted viewstate value), which negates many of the benefits of an Ajax solution. I really wanted to roll my own ajax communications to make them as lightweight as possible.

My solution was to write the page in a standard .NET postback manner, and then use a user-defined property that would allow javascript to replace the postback in javascript/jQuery with an Ajax call.

Here’s my code:

$(function() {
            if (serverVars.uiVersion != "accessible") { // use js/ajax for checking/unchecking where possible
                var $todos = $("#chkToDo");
               $todos.removeAttr("onclick"); // remove postback
                $todos.click(
                    function() {
                        //some stuff altering the document, and an ajax call to report the change to the db
                    }
                );
            }

This works great, although you need to be careful about your server-side events. In my case, I had an OnCheckChanged event to handle the postback/accessible mode. Even though checking/unchecking the box no longer fired an autopostback – ASP.NET will still fire the checkchanged event if you postback later for some other reason (e.g. – a linkbutton elsewhere on the page) after the checked status had changed. So, if a user had changed the state of a checkbox, then clicked another link button on the page – instead of sending the user to the intended page,my app just refreshed the whole page(because my CheckChanged event redirected to reload the page – which caused it to skip the ‘click’ event of the linkbutton). Once I realized this was happening, it was easy enough to fix – I just needed to only run the event logic if the user was in accessibility mode. I spent a little time running in circles on that one though, at first I thought my client side document changes were causing a ViewState validation error on the server.

Avoid static variables in ASP.NET

Occasionally, I like to write static methods on classes. They are useful whenever the method loosely relates to to the class – but it doesn’t involve a specific instance of the class.

A good example of a static method in the .NET library is the int.Parse(string val) method. This method basically reads a string and tries to return an integer representation. The method logically fits with the int Class (I suppose a string could have a ToInt() instance method…but that would be overwhelming as you added ToFloat(), ToDecimal(), To…()) – but when you run it, there’s no reason to have an instance of int already. You run it to create a new instance of int.

Commonly, I follow similar logic in the business layer of my webapps. I write a static Add(param1,….,paramx) method that returns an instance of the class after it is persisted to the database. I could accomplish this other ways, but I think the resulting application code reads better like:

      User.Add(username,password);

Than:

      new User(username,password).Add();

or, worse:

      DataContext.Users.InsertOnSubmit(new User(username,password));
      DataContext.SubmitChanges();

The issue with static methods in your business logic is that you often need a common object to talk to the database through: a SqlConnection, a TableAdapter, A LINQ DataContext, etc. I could certainly create those objects locally inside each static method, but that’s time consuming and hard to maintain. I want instead to define a common property (in the business class or a parent class of it) that lazy-initializes and returns an instance of the object when I need it. The problem is that the property must also be static for a static method to have access to it.

The easiest way to accomplish this is something like:

      private static ModelDataContext dataContext=null;
      protected static ModelDataContext DataContext
      {
            get
            {
                 if(dataContext==null)
                     dataContext = new ModelDataContext();
                 return dataContext;
             }
       }

The tricky thing is that this will probably work in development and testing, until you get some load on your website. Then, you’ll start seeing all kinds of weird issues that may not even point to this code as the problem.

Why is this an issue? It’s all about how static variables are scoped inside a ASP.NET application. Most web programmers think of each page in their application as its own program. You have to manually share data between pages when you need to. So, they incorrectly assume that static variables are somehow tied to a web request or page in their application. This is totally wrong.

Really, your whole website is a single application, which spawns threads to deal with requests, and requests are dealt with by the code on the appropriate page. Think of a page in your webapp as a method inside of one big application, and not an application of its own – a method which is called by the url your visitor requests.

Why does this matter? Because static variables are not tied to any specific instance of any specific class, they must be created in the entire application’s scope. Effectively, ASP.NET static variables are the same as the global variables that all your programming teachers warned you about.

That means that, for the property above, every single request/page/user of your website will reuse the first created instance of DataContext created. That’s bad for several reasons. LINQ DataContexts cache some of the data and changes you make – you can quickly eat up memory if each instance isn’t disposed fairly quickly. TableAdapters hold open SQLConnections for reuse – so if you use enough classes of TableAdapters, you can have enough different static vars to tie up all of your db connections. Because requests can happen simultaneously, you can also end up with lots of locking/competing accesses to the variable. Etc.

What should you do about it? In my case, I take advantage of static properties that reference collections that are scoped to some appropriately short-lived object for my storage. For instance, System.Web.HttpContext.Current.Items:

      protected static ModelDataContext DataContext
      {
            get
            {
                 if(System.Web.HttpContext.Current.Items["ModelDataContext"]==null)
                     System.Web.HttpContext.Current.Items["ModelDataContext"] = new ModelDataContext();
                 return (ModelDataContext)System.Web.HttpContext.Current.Items["ModelDataContext"];
             }
       }

In this case, each instance of DataContext will automatically be disposed for each hit on the site – and DataContexts will never be shared between two users accessing the site simultaneously. You could also use collections like ViewState, Session, Cache, etc (and I’ve tried several of these). For my purposes, the HttpContext.Items collection scopes my objects for exactly where I want them to be accessible and exactly how long I want them to be alive.

Using Custom Properties Inside LINQ to SQL Queries

One thing that initially caused me some trouble with Linq to SQL was that properties
and functions defined on the object cannot be translated to SQL. For example, this code throws an
“The member ‘Table1.DisplayName’ has no supported translation to SQL.” exception when executed.

public string DisplayName
   {
      get
      {
         return this.NameFirst + " " + this.NameLast;
      }
}

public static IQueryable<Table1> GetAll()
{
   return (from t in DataContext.Table1s
             select t).OrderBy(t => t.DisplayName);
}

One simple solution is to just define your sort option each time it needs used.

public static IQueryable<Table1> GetAll()
{
   return (from t in DataContext.Table1s
             select t).OrderBy(t => t.NameFirst + " " + t.NameLast);
}

This option is pretty tedious to write and maintain, especially if you’re going to be using the function often.

Another option is to define a System.Linq.Expression, which is a lambda expression that can be converted to SQL.

static Expression<Func<Table1, string>> DisplayNameExpr = t => t.NameFirst + " " + t.NameLast;

public static IQueryable<Table1> GetAll()
{
   return (from t in DataContext.Table1s
             select t).OrderBy(Table1.DisplayNameExpr);
}

Note that if you do choose this way, the “DisplayName” is essentially defined in two different places. To solve this problem, use the expression to define the property.

{
   get
   {
      var nameFunc = DisplayNameExpr.Compile(); // compile the expression into a Function
      return nameFunc(this); // call the function using the current object
   }
}

Note this method can also be used to define functions that accept arguments,  so the following code also works as expected.

static Expression<Func<Table1, bool>> HasReq(int numReq)
{
   return (t => (t.IntItem + t.AnotherInt) > numReq);
}

public static IQueryable<Table1> GetWithReq(int req)
{
   return (from t in DataContext.Table1s
             select t).Where(Table1.HasReq(req));
}

Extending jQuery to Select ASP Controls

If you have worked with JavaScript in an ASP.NET Web Forms environment, you almost certainly have been frustrated that this markup:

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

renders out as something like:

	<input type="text" id="ctl00_ctl00_ctl00_main_Content_txtPhoneNumber"
		name="ctl00$ctl00$ctl00$main$Content$txtPhoneNumber" />

The fastest and easiest way to get a reference to a DOM element in JavaScript is using the ID attribute and document.getElementById(). Unfortunately, the ID attribute generated by the server is unpredictable and based on the server naming containers. There are a couple ways of that I have previously dealt with that problem, but both have problems.

Old Solutions

  1. Accessing the ClientID of the server control

    If you use inline code inside <% %> tags, you can access the ClientID directly from the .aspx page.

    	var goodID = '<% txtPhoneNumber.ClientID %>';  // = 'ctl00_ctl00_ctl00_main_HeaderTabs_txtPhoneNumber'
    	var badID = 'txtPhoneNumber'; // The text box does not have this ID, it will not work
    	var uglyID = 'ctl00_ctl00_ctl00_main_Content_txtPhoneNumber'; // DO NOT hardcode the generated ID into your code!
    

    This is not ideal because you cannot reference the ClientID from outside of the page, so you cannot keep your JavaScript in external files.

  2. Setting attributes on control and accessing with jQuery selectors

    jQuery has an excellent selector API that can easily grab an element if you know attributes on it. So, if there were a couple controls defined as:

    	<asp:TextBox runat="server" ID="txtPhoneNumber" CssClass="txtPhoneNumber" />
    	<asp:TextBox runat="server" ID="txtAddress" ClientID="txtAddress" />
    

    You could access them with jQuery:

    	$(".txtPhoneNumber").keyup(...);   // This works
    	$("[ClientID='txtAddress']").keyup(...);   // This works
    
    	$("#txtPhoneNumber").keyup(...);   // This still DOESN'T work
    	$("#txtAddress").keyup(...);   // This still DOESN'T work
    

    This is not ideal because it requires adding extra attributes onto any server control that you want to access with JavaScript.

Original jQuery Solution

I first happened upon a solution to the same problem over on John Sheehan’s blog. This looked promising, but did not work the current latest release of jQuery (1.3). Another contributer to this blog, Tim Banks, updated the code in to work with the newer version.

However, I found an error in Internet Explorer and a more reliable way to get the ClientID would be to use the jQuery attribute selector and match based on an “id” attribute that ends with the Server ID. So, I wrote a JavaScript function called $asp that returned a jQuery collection. This function worked well and was implemented in the latest Foliotek release.

	function $asp(serverID) {
		return $("[id$='" + serverID+ "']");
	}

	// Once this function is included, you can call it and get back a jQuery collection
	$asp("txtPhoneNumber").keyup(...);

Updated jQuery and Sizzle Solution

It seemed like it would be better if the solution actually extended the selector engine rather than using a function to select objects. This would fit better into a jQuery development paradigm, allow more complex selectors, and also allow the selector to be used in other library functions, like “filter” or “find”. Also, it would be nice to be able to use the tag name in the selector to give a performance improvement, since getElementsByTagName is a fast operation that will narrow the element collection.

So, I returned to the selector, fixed the IE bug and made sure it worked with the now latest version of jQuery (1.3.2). This short function extends the Sizzle selector engine to return an element that has an ID that ends with the ID that is passed in the parenthesis after the “:asp()” selector.

	// Include this function before you use any selectors that rely on it
	jQuery.expr[':'].asp = function(elem, i, match) {
		return (elem.id && elem.id.match(match[3] + "$"));
	};

	// Now all of these are valid selectors
	// They show why this method has more functionality than the previous $asp() function.
	$(":asp(txtPhoneNumber)")
	$("input:asp(txtPhoneNumber):visible")
	$(":asp(txtPhoneNumber), :asp(txtAddress)")
	$("ul:asp(listTodos) li")
	$("#content").find("ul:asp(listTodos)")

This function allows access to server controls without adding additional markup and without the JavaScript existing on the .aspx page.


Note, there is a potential limitation if you had one control with the ID=”txtPhoneNumber” and another with ID=”mytxtPhoneNumber”. Both elements end with “txtPhoneNumber” and the selector would not necessarily return the correct value. This solution is not perfect in that sense, but the benefits it provides over other methods (cleaner markup and ability to use external JavaScript files) make it a good alternative.