Friday, May 29, 2009

JQuery, IE6, and 'Could not set the selected property. Unspecified error.'

I was trying to do this with JQuery - imagine htmlOptions is a client-side cache of option values to put in a select box, ctrl is the id of the box, and id is the current selected value:


function loadDropDown(htmlOptions, ctrl, id) {
   $(ctrl).html(htmlOptions); 
   $(ctrl).val(id); 
}

It worked great on everything but IE 6.0. Then I got the big, fat "Could not set the selected property. Unspecified error." Turns out there is a little bit of a timing issue with the DOM. After scouring the 'net for solutions, I finally settled on this as my favorite - no crazy browser hacks to determine the type and version, IE 6.0 gets the short end of the stick as it deserves:


function loadDropDown(htmlOptions, ctrl, id) {
   $(ctrl).html(htmlOptions); 
   try {
      $(ctrl).val(id); 
   }
   catch(ex) {
      setTimeout("$('" + ctrl + "').val('" + id + "')",1); 
   }
}

It's just enough delay to let the DOM settle and not complain.

Jeremy Likness

JavaScript and User Controls 101

I've been doing quite a bit with user controls and JavaScript. There is an art to using the JavaScript correctly, wiring it in and having it work consistently. I thought I'd post a brief article on the "101" around this based on the things I've found. Hopefully this can be a quick-and-dirty reference guide for those of you working to extend your user controls with JavaScript functionality.

Understand Multiplicity

First, understand if your user control can potentially be rendered multiple times on a page. For the most part, I assume this will be the case. However, there are some circumstances, such as a large grid control, where you may absolutely know there is only going to be a single instance. The reason you want to understand this is because you want to try to have exactly one copy of the JavaScript code emitted to the browser, so it will need to be "aware" of the instance it is working with.

JQuery

I am a major fan of JQuery because of the fact it feels "natural" with the combination of XPath selector and CSS-style selections, chaining, and the browser compatibility is handled for me. There are correlating functions in other libraries, but this is what I'll be using for my examples.

Part 1: The ASCX file

I try to keep as clean a separation of code from the ASCX file as possible. The exception are elements that I must derive on the server side. These typically include references for callbacks, URLs (I like to strongly type my URL references), and wiring "init" events.

We'll use a hypothetical "contact" control. Here is what I have at the bottom of my ASCX file, and this assumes I am using the AJAX framework and therefore have somehow registered a ScriptManager (this is outside the scope of this document — see the Script Manager control overview:


<script type="text/javascript">
   window.Sys.Application.add_init(contactInit);
   contactCtrlClientID = '<%=ClientID%>';
</script>

Basically, I've registered with the AJAX framework and told it to call contactInit once everything is loaded. I've also created a reference to the client id. If I'm going to have multiples, I'd push them to an array or use some other method to keep track (windows provides handles and references in AJAX as well) of them ... this is just a quick and easy way to know how it is registered to the page if it is inside of a master page, etc.

The JavaScript file

There are many ways you can include the related JavaScript. Some people like to make it a straight include reference so they can easily update the JavaScript on disk and test changes, etc. We produce commericial software so the code is embedded (I like to do initial testing with an external resource, then embed the JavaScript). My favorite convention is to name the JavaScript the same as the control and have it side-by-side with the control in the designer (i.e. if my control is ContactCtrl.ascx, then my JavaScript is ContactCtrl.js and at the same level as the control).

Embedding your JavaScript

This is an easy three-step process.

  1. Right click on the properties of your JavaScript file and indicate you wish to make it an Embedded Resource. If you don't want to ship the source, make sure you have "do not copy" selected for the destination.
  2. Your web project should have a Properties folder with AssemblyInfo.cs. At the bottom of this file, you need to add a tag to identify the embedded resource. You will use the namespace, including the folders, and then the filename itself. For example, let's say the namespace for the project is Company.Project and the control is in a UserControls/Contact folder. Your resource will look like this:
    [assembly: WebResource("Company.Project.UserControls.Contact.ContactCtrl.js", "text/javascript")]
  3. Finally, register a reference to it. When you register an embedded resource, you must specify a type. This ties the code to the control and prevents it from being emitted multiple times if the control appears multiple times. It is important to use typeof instead of GetType() or it may not behave as expected. Our example, which can go in onPreRender or onLoad:
    ...
    Page.ClientScript.RegisterClientScriptResource(typeof(ContactCtrl),
       ("Company.Project.UserControls.Contact.ContactCtrl.js");
    ...

Initialization

When you register an initialize event, you can then hook in to "prep" the control. For example, maybe my contact control has some dynamic sections that are conditional based on a contact type. I can do something like this:


function contactInit() {

   $(document).ready({
      $("#divAdmin").hide();
      $("#selType").change(contactTypeChange); 
   });

}

function contactTypeChange() {

...
   $("#divAdmin").show();

}

Essentially, this will hide the admin section, then wire in a change event to the dropdown and call the type change method which can conditionally show it, etc.

Events

Good development practice dictates I design my control as self-contained as possible. For example, if I am making a search criteria control, I can't just assume I'll have a "search results grid" and when the user clicks "submit" send some client information over to the control. The proper way to have user controls talk on the client side is the same way on the server: through events. There are two ways I like to wire in my events. If I'm doing a light weight control, I'll tab into the global event pool and have a unique event name. If I'm developing a more extensive control, I'll wire in an AJAX behavior and expose events that way. To learn how to create a full-blown AJAX client control (something that can expose all of your server side events in a similar clientside model) read Creating Custom ASP.NET AJAX Client Controls.

Let's assume I want to expose an event that is raised whenever the user changes the contact type. This way I can have other controls that might dynamically respond to the change on the client side, avoiding a server round trip. I don't have a true AJAX client control that corresponds to my contact control, so what can I do? An easy method is to plug into the Application events - think of these as "global" events. In my contact, I just need to know if someone is listening to my event. I'll give it the name "contactTypeChange" and send along the new type as well as my client id in case I have multiple instances.


function contactTypeChange(clientID,contactType) {

   var contactHandler = window.Sys.Application.get_events().getHandler("contactTypeChanged");
   if (contactHandler) {
      contactHandler(clientID,contactType);
   }

}

Now, in my control that is listening to the event, I simply register to do something with it. Let's call this my "Contact Security" panel and it will show special admin security rights if the contact is an admin. First, in my init function, I'll register for the event. Second, I'll provide a function to handle the event.


function contactSecurityInit() {

   window.Sys.Application.get_events().addHandler("contactTypeChanged", contactTypeChangeHandler); 

}

function contactTypeChangeHandler(clientID, contactType) {

   if (contactType == "admin") {
      $("#divSecurityAdminInfo").show(); 
   }

}

Callbacks

Finally, a caveat on callbacks. I use these a lot, because of the fact that update panels tend to add a lot of overhead. If your application requires javascript, you can manage a lot of the state in the browser page and use more tightly defined callbacks to perform dynamic updates. One "gotcha" with callbacks is that you must ask for the callback function in order for the control to listen for it. The three steps I find are easiest to manage callbacks:

  1. Implement ICallbackHandler on your UserControl. This will generate two methods: one that takes an event argument, and one that asks for a return result. That's it! The event argument is what you control on the client side and pass down. In your control, you'll process some result and then can send back something to the client. It can be as simple as a little message to display, or as complex as a dynamic snippet of JavaScript to eval() on the client.
  2. Ask for the callback reference. This is important! Even if you will explicitly callback from your code, you need to "ask" for the reference in order for the control to listen. It's as simple as:
    ...
    Page.ClientScript.GetCallbackEventReference(this, string.Empty, string.Empty, null);
    ...
  3. Wire in the call!

For example, let's say we want to display some text in a div based on the contact type. We want the server to retrieve the text and perform globalization functions against it before sending it back from the browser. This snippet of code will do the trick:


WebForm_DoCallback(callbackRef, contactType, function(args, ctx) { 
   $("#divHelp").html(args);    }, null, null, false);

Callbackref is the reference to the control. You can embed the GetCallbackEventReference above in your ASCX page and render the page to see how the control is referenced. It's essentially the path to the control separated by dollar signs (if you have a masterCtrl then a pageCtrl then the contactCtrl, it will look like masterCtrl$pageCtrl$contactCtrl). The next is the argument that gets passed to the server, following by the function to process when the result is returned. Here, we do an inline function and find the div and fill it with what we got back from the server. (You can read more about script callbacks).

Conclusion

Obviously, there is a lot you can do with scripts and user controls and this post only scratched the surface. Hopefully this gave you a good idea of some good practices for associating JavaScript to a user control and ways you can use JavaScript to extend the functionality, allow for greater interoperability between controls, and streamline performance through the use of callbacks.

Jeremy Likness

Wednesday, May 27, 2009

Copyleft, GNU, permissive, and, oh, my!

Just a quick little post for you today.

Ever get confused about what the "GNU" license really means? Or how about the newer MS-PL (Microsoft Permissive License?) It seems that every day someone is creating a new license and it can quickly become a confusing mess.

Fortunately, there is a site that provides some relief and covers more licenses than you can shake a stick at: Free Software Foundation: Licenses.

Enjoy!

Jeremy Likness

Monday, May 25, 2009

SOLID and DRY Part 2

Interface Segregation Principle

If I don't care about it, don't make me implement it!

The interface segregation principle simply dictates that you design your interfaces with the other principles in mind. Instead of creating a bloated interface, interfaces should be segregated into cohesive units of functionality. This way the implementation of the interface can focus on what is important for that class.

To better illustrate this, consider a data access class. One common approach might be to interface that class, and declare methods for loading, saving, updating, deleting, searching, performing a list, a security check, and who-knows-what-else. You could then create a concrete class that implemented this interface. The result is a fat interface that does everything the class needs, but doesn't necessarily allow for appropriate scaling.

Another example is the use of an ORM like NHibernate. Perhaps your company decides this is useful for the basic CRUD operations (create, read, update, delete) but that LINQ to SQL or some other framework will be used for the complex searches and sorts. With one large, "IWidgetDataAccess" interface, you would have to implement all of the method signatures, even if you really only did something concrete to the CRUD pieces. A common practice is to do this:


void MethodNotUsed() 
{
   throw new NotImplementedException();
}

If you find yourself throwing this exception, it's a pretty good sign you are not following the interface segregation principle. A better approach would be to break out two different interfaces. One interface is your standard CRUD interface, call it "ICrud" and the other is the specific set of methods for the class ("IWidget"). Then you could implement your ICrud pieces with the concrete NHibernate instance, and save the IWidget for a different concrete class.

This really comes back to the Liskov substitution principle. I don't want to pollute my IUser interface with methods for an administrator, otherwise everyone has to implement the method signature (even if simply to throw a NotImplementedException). With interface segregation, I can have IUser and IAdminUser and then my AdminUser would implement both:


public class AdminUser : BaseUser, IUser, IAdminUser

In summary, the interface should be fine-grained and focused on the client class that will implement the interface, rather than fat and bloated covering every possibility.

Dependency Injection or Inversion of Control

Depend on abstraction, not concreteness.

This final principle is very popular but not well understood. I see lots of discussion about dependency injection and inversion of control, but it all seems centered on the frameworks that implement it (such as StructureMap, Unity, Spring.NET, and so forth) rather than the principle itself. Like many of the other SOLID and DRY principles, this one does not stand alone but ties into the other principles as well.

The idea is rooted back in our "Single Responsibility." Once again, let's take an example. I am writing my data access class and for troubleshooting, I want to log issues. I decide that I'm going to use log4net and so I configure everything that I need and then start writing out logging information in my class.

At this point I've violated "single responsibility" because my class isn't doing one thing (data access), it's responsible for two things (data access and logging). If I continue down this path I'll end up with dozens or even hundreds of classes with log4net logging embedded in them. Then I get the notice from the powers that be that we cannot use any type of open source in our project. We decide to shift to Enterprise Library. Now I've got my work cut out for me because I depended so much on my concrete logging implementation that I have to touch every class.

By focusing on abstractions, I could instead have allowed for an ILogger interface and coded to that. I no longer make my class responsible for logging, instead it simply takes in the abstraction of a logger interface (ILogger) and depends on something else to make it concrete. This is where "dependency injection" comes from: the dependency on the concrete implementation is injected by something else. This also explains what "inversion of control" is - instead of my class being in control of logging, I invert that control and let something higher up the chain decide.

For a more detailed explanation of dependency injection, read Simplified Mocking with Dependency Injection.

As I mention in that article, DI does not require a framework. Taking the logging example, I could easily do this at the beginning, when I think, "We're going to use log4net, but let me go ahead and follow some solid object-oriented design principles and abstract it just in case."


public class Widget
{
    private ILogger _logger;

    public Widget() 
    {
       _logger = LoggerFactory.GetLogger();
    }
 
    public Widget(ILogger logger) 
    {
       _logger = logger;
    }
    ...
}

public static class LoggerFactory 
{
    public static ILogger GetLogger()
    {
       return new Log4NetLogger();
    }
}

As you can see, no framework is required. My classes work fine without anything knowing what to inject, but they make a constructor available anyway so if I do decide to move to configuration or a framework, I can do so. I use the factory pattern to get the logger. Again, we're hardcoded right now. But now I have possibilities. If I switch to Enterprise Library, for example, I only have to go to one place to change the concrete instance of my logger. Furthermore, I might want to have my logs Debug.Print during testing, in which case I create my custom DebugLogger that uses Debug.Print and inject that for testing.

Summary

These concepts are by no means "programming law" and there are many variations. I also didn't intend this to be a comprehensive discussion of the principles, but hopefully have touched on the surface and generated enough interest and curiosity for those not familiar to begin more research and apply these methods to their own software. In my opinion, you can give complex names to certain concepts or come up with new "architectures" or "design patterns" but in the end, it's about getting back to the basics and continuing to write simple, modular, easy to read and understand, maintainable code that works as building blocks for more powerful applications.

Jeremy Likness

Saturday, May 23, 2009

SOLID and DRY

No, this isn't a commercial for deodorant.

It's funny how many developers become so entrenched in their company and projects that they seldom venture outside to see what is going in the bigger world of Information Technology. I see this often in my interviews: a senior developer has worked a company for several years, quickly rose to the top and is the "go to" guy and now is ready to be an "architect." The only problem is that they only know how to work on their VisualBasic 6.0 system and think the best architecture is pulling everything as ADO XML and using stylesheet transformations to drive the application (I say this tongue-in-cheek because this is a framework I worked with and implemented in my past).

I can think of two good examples for this. The first is test-driven development (TDD). You can ask a question about TDD in an interview, and while there are many people who have never heard of it, you'll get a few that say, "Yes, absolutely, I follow TDD." "How, exactly?" "Oh, we write unit tests." If you think that writing unit tests means you are practicing TDD, you might want to do a little more research. The second example is generics - most people are familiar with generics in C#. What are they for? They are for lists, of course! (Again, if you feel that generics are only good for typing lists to prevent boxing, you'll want to research a bit deeper). Oh, and I just thought of a third: delegates are just for events, right?

My point is that sometimes we get stuck in what works for our system and it works well, but it's not always the right or best solution and we need to constantly challenge ourselves as software engineers (or whatever we call ourselves today) to stay on top of what's out there.

I decided to post this article in my C#er : IMage blog because I feel SOLID and DRY are very sound principles for software development and yet I constantly see people tripping over these concepts.

Let's tackle DRY first:

Don't Repeat Yourself

It's a simple principle, really.

I am writing an application I need to validate that a field follows the specific pattern for an IP address. So I plug in a textbox, attach a custom regex validator control and I'm off to the races. One year later we have a huge application with IP addresses all over the place, and we discover that the regular expression we Googled to validate IP addresses has a bug! Now it's search and replace and a LOT of unit testing.

I should have caught myself the second time I was adding a regex validator. It's easy to think, "I'm writing nice code because I'm not hand-rolling a regular expression validation, I'm using the validator." But even something like that lent itself to create an "IP textbox control" with the validator embedded. Then, instead of repeating myself, I can drop in that control. If it changes, I change it once.

You can repeat yourself by decorated code with string literals instead of collapsing them into constants, by having little utility methods and not saying to yourself, "Wow, I just wrote that method twice ... time to move it into a class." It's a powerful principle that will help you write scalable, maintainable code. You don't need to give it a fancy name like "Single Point of Truth" to appreciate that if you find yourself repeating something, anything, it's a good candidate to break out into a separate, reusable class.

This takes us to SOLID, which is a study in and of itself, so I'm going to be brief here. The intent is just to introduce you to the principle so you can study it yourself and learn from it, because I see a lot of developers who would benefit from understanding it.

SOLID is an acronym for:

  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion

Single Responsibility Principle

A class should have one, and only one reason to change.

This is fairly close to DRY, no? We say: keep it simple. A common pattern for this is Model-View-Controller (MVC). Instead of combining presentation concerns, data persistance concerns, and business logic all in the same class, you break it out so each class focuses on its own. Why is this so important? Because each thing the application does is not only a potential point of failure, but also a point of change. In other words, "doing something" might be "doing something different" down the road.

A common example of this is writing a drop down class. It calls the database, does an "order by" and then renders the control. Then you find out another page needs this same control, but as a textbox that has a "dynamic search" feature. So you copy the control, use some cool AJAX, and are looking good until you are informed that states will no longer be stored in the database, but must be managed via XML. Now you have TWO controls to change because of the ONE change of storing data.

If you followed the Single Responsibility Principle, you would have probably had four classes: one to fetch the data (persistance management), one to sort it (business logic), one to bind the data to a drop down and another for the fancy "look ahead" control (presentation). When the switch came, you'd only have to change it in one place.

This principle also makes it easier to scale development teams. Have you heard the saying, "9 women can't make a baby in 1 month?" With this principle, you can scale the speed of delivery for your application by breaking it into smaller, more maintainable units of work.

Open/Closed Principle

Open for extension, closed for modification.

This simply states that you should be able to extend what a class does without modifying its core behavior. It's open for extension, but closed for modification. Again, let's take an example. You might have a class that represents a user in the system, and you've determined that fundamentally a user consists of a login, a password, and an email address. Later, you find out some users can have contact information. Eventually you learn that some users are administrators and have additional information such as which parts of the application they can manage.

A class that violates these principles would require you to have a bloated class with lots of flags indicating what/who the user is. Every time you had to change or add something, you'd need to change that original class.

A more stable approach would be to put your fundamentals into a base class. Now you can have a ContactUser : BaseUser and extend the user to have contact information. Then you can have a AdminUser : BaseUser or perhaps an AdminUser : ContactUser. You are extending, not modifying the base class. I mentioned generics earlier: this is a perfect example where generics can be used to define some base functionality (for example, in your data access layer, opening and closing the connections) while your extensions strongly type the behavior for a specific class.

The Liskov Substitution Principle

Derived classes must be able to substitute for their base classes.

Why is this so important? Think about the example above with different contacts. If I have a function that validates a login, then I should be able to simply check the username and the password of the class. To do this, I don't need to know if the class is a base user, a contact user, or an admin user. All of these classes extend base user, so I will code my login against base user. The contact user behaves exactly as the base user.

What if I decide to write another class that displays user information? I make it UserInfo<T> but then break the principle by doing this:

if (typeof(T) == typeof(BaseUser) { return ((BaseUser)T).Email; }
else if (typeof(T) == typeof(ContactUser) { return ((ContactUser)T).Phone; }
...
else { throw new Exception("Could not determine the type."); }

What just happened? It might work on the surface, but suddenly I have a very difficult class. This class now needs to understand every possible derived type of T in order to do its job. How can the application possibly scale if I have to keep coming back to the same place to make changes and keep up to date? I might hire a new developer who goes off and builds a AccountingUser ... and then blows up the system because they did not update UserInfo.

A better way would be to override the ToString method. Each class can implement its own version of what "display information" is. Any other object can handle BaseUser (not caring what the derived type is) and display useful information simply by invoking ToString().

Now things are starting to get interesting because we're going to tackle one of the most popular "buzz words" going around today: dependency injection / inversion of control ... stay tuned, because we have two more principles to cover!

Jeremy Likness

Tuesday, May 12, 2009

JavaScript "isInteger"

When searching for this I found dozens of implementations doing crazy things like parsing each character, string manipulation, etc. But if you really want to know if it's an integer, what about this?


function isInteger(val) {

   return (val == null || isNaN(val)) ? false : 
      ( ((1.0 * val) == Math.floor(val)) && (val.indexOf(".") == -1));

}