jquery ui autocomplete: Uncaught TypeError: Cannot read property ‘element’ of undefined

I got that exception when I loaded some options through JSON (with ASP.NET MVC). It took a lot of digging before I finally found what the cause was. And it’s not what I expected:

I’ve made a custom menu plugin in the jQuery namespace. And it seems like autocomplete tries to use ‘menu’ function ($jQuery.menu) too, which failed utterly. I removed my plugin and everything worked smoothly.

Here’s how you can use the autocomplete plugin yourself with ajax (I preload all available options):

In your Razor view:

<script type="text/javascript">
    var baseUri = '@Url.Content("~")'; // to get it working in root or a virtual dir
    $(function() {
      $.getJSON(baseUri + 'myController/myAction', function(data) {
          $('myTextbox').autocomplete({ source: data });
     });
    });
</script>

And in your controller:

public ActionResult Items()
{
    var items = _repository.GetYourItems().Select(p => p.Title).ToList(); // only get titles
    return Json(items, JsonRequestBehavior.AllowGet); //it's safe to get these items using GET
}
Posted in Uncategorized | Tagged , | Leave a comment

Liskovs Substitution Principle

I’m a big fan of patterns and principles. And I’m going explain all SOLID principles in different blog posts. This post is all about LSP.

LSP says that you should always be able to use a base class or interface instead of the actual implementation and still get the expected result. If you can’t, your breaking LSP.

An example:

public interface IDuck
{
   void Swim();
}
public class Duck : IDuck
{
   public void Swim()
   {
      //do something to swim
   }
}
public class ElectricDuck : IDuck
{
   public void Swim()
   {
      if (!IsTurnedOn)
        return;

      //swim logic  
   }
}

And the calling code

void MakeDuckSwim(IDuck duck)
{
    duck.Swim();
}

As you can see, there are two examples of ducks. One regular duck and one electric duck. The electric duck can only swim if it’s turned on. This breaks LSP since it must be turned on to be able to swim (the MakeDuckSwim method will not work as expected if a duck is electric and not turned on).

You can of course solve it by doing something like this:

void MakeDuckSwim(IDuck duck)
{
    if (duck is ElectricDuck)
        ((ElectricDuck)duck).TurnOn();
    duck.Swim();
}

But that would break Open/Closed principle (SOLID) and has to be implemented everywhere (and therefore still generate instable code).

The proper solution would be to automatically turn on the duck in the Swim method and by doing so make the electric duck behave exactly as defined by the IDuck interface.

The solution with turning on the duck inside the Swim method can have side effects when working with the actual implementation (ElectricDuck). But that can be solved by using a explicit interface implementation. imho it’s more likely that you get problems by NOT turning it on in Swim since it’s expected that it will swim when using the IDuck interface.

What LSP is really saying is that all classes must follow the contracts that they have been given. Just as you may not update items in your website with GET if you are following the HTTP protocol.

Posted in Architecture, CodeProject | Tagged , | Leave a comment

How to become a computer expert

Computer expert flowchart

Posted in Uncategorized | Leave a comment

More natural string formatting using an extension method

If you are like me, you don’t determine if you should include parameters in string before you start writing, thus you haven’t decided that string.Format should be used until it’s too late. You then need to go back and refactor that string, which can destroy the smooth coding flow that you got going.

Lets be saved by an extension method:

public static class StringExtensions
{
	public static string FormatWith(this string instance, params object[] arguments)
	{
	    return string.Format(instance, arguments);
	}
}

Which allows you to reformat the code as:

// Simple example
Console.WriteLine("Hello '{0}'!".FormatWith("world"));

// Multiple parameters:
var str = @"Happy birthday {0}!
    {1} is a beatiful age, isn't ?".FormatWith(user.Name, user.Age);
Posted in extensionmethods | Tagged | Leave a comment

HtmlHelper for enums in ASP.Net MVC3

Have you tried to get enums working with HtmlHelpers? It can be a hassle and here is my solution for it. It requires that you tag each entry in the enum with a [Description] attribute.

public static class SelectExtensions
{

    public static string GetInputName<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)
    {
        if (expression.Body.NodeType == ExpressionType.Call)
        {
            MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body;
            string name = GetInputName(methodCallExpression);
            return name.Substring(expression.Parameters[0].Name.Length + 1);

        }
        return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1);
    }

    private static string GetInputName(MethodCallExpression expression)
    {
        // p => p.Foo.Bar().Baz.ToString() => p.Foo OR throw...
        MethodCallExpression methodCallExpression = expression.Object as MethodCallExpression;
        if (methodCallExpression != null)
        {
            return GetInputName(methodCallExpression);
        }
        return expression.Object.ToString();
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) where TModel : class
    {
        string inputName = GetInputName(expression);
        var value = htmlHelper.ViewData.Model == null
            ? default(TProperty)
            : expression.Compile()(htmlHelper.ViewData.Model);

        return htmlHelper.DropDownList(inputName, ToSelectList(typeof(TProperty), value.ToString()));
    }

    public static SelectList ToSelectList(Type enumType, string selectedItem)
    {
        List<SelectListItem> items = new List<SelectListItem>();
        foreach (var item in Enum.GetValues(enumType))
        {
            FieldInfo fi = enumType.GetField(item.ToString());
            var attribute = fi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault();
            var title = attribute == null ? item.ToString() : ((DescriptionAttribute)attribute).Description;
            var listItem = new SelectListItem
                {
                    Value = ((int)item).ToString(),
                    Text = title,
                    Selected = selectedItem == ((int)item).ToString()
                };
            items.Add(listItem);
        }

        return new SelectList(items, "Value", "Text");
    }
}

Usage:

@Html.EnumDropDownListFor(m => m.SubscriptionMode);

If you want to be able to use it for validation, you need to be able to have a “undefined” entry in your enum and do the following change:

// replace "Value = ((int)item).ToString()," in to select list.
Value = (int)item == 0 ? string.Empty : ((int)item).ToString(),
Posted in CodeProject | Tagged | Leave a comment

Refactoring code to conform to open/closed principle

I answered a SO question and refactored the code to make it more flexible and conform to open/closed principle.

SO Question

Posted in Uncategorized | Leave a comment

REST:ify your delete links

Wrote an answer about it @ stackoverflow.com

Posted in Uncategorized | Tagged , | Leave a comment

The art of creating exceptions

Please take a moment and think about WHY you throw exceptions.

You done? Have you come up with a reason? You are probably thinking: “That b!@tch is a total moron. I throw exceptions to know that something exceptional have happened!”. If that is the case, please stop reading here. (The first part of the thought is totally fine by me, I can be a total moron.)

.
.
.
.
.
.

I SAID STOP READING!!!!

.
.
.
.
.
.
.

Really!

.
.
.
.
.
.
.
.
.

No? Well. Ok then. Want to be an exception master? Got some ninja skills? Have you bought a jump suit? I have actually created a diploma (yes, It’s true) that I will email to anyone who leave a comment that says: “I throw exceptions to be able to try to prevent them in the future”. Because that’s what you should really try to do. Sure, some exceptions that are thrown CAN’T be prevented. But a lot of them can.

Let’s take FileNotFoundException as an example. It can in MOST cases be prevented, if you are not a lazy SOB, by checking if the file exists before trying to open it. The exception can STILL be thrown if the file is deleted between the check and and you opening it. Life is harsh, isn’t it.

The problem is that if you do not provide any contextual information you will have a hard trying to prevent it in the future.

Instead of just writing

  throw new FileNotFoundException("Ohhh, the file was missing! *buhu*");

do write

  throw new FileNotFoundException(string.Format("Failed to find '{0}'.", amazingFileName));

Even better would have been if you could add some more context and add the filename as a parameter:

  throw new FileNotFoundException(string.Format("User photo for user #{0} was not found", userId)) { Filename = amazingFilename };

That gives a lot more information to work with, don’t you think? When designing exceptions you should ask yourself “What kind of context information can I provide in this exception to make it easier to prevent it?”. Regarding a file it’s quite obvious. Hence I would design the exception like this:

  public class FileNotFoundException : IOException
  {
      public FileNotFoundException(string message, string fileName)
	     : base(message)
	   {
			Filename = fileName;
	   }

       // *ALWAYS* include a constructor which takes a inner exception.
	   //
	   // I WILL HUNT YOU DOWN AND GIVE YOU SOME SPANKING IF YOU DON'T!
       public FileNotFoundException(string message, string fileName, Exception inner)
		: base(message, inner)
	   {
	   }

      public string Filename { get; private set; }
  }

Let’s look at another example.

I’ve talked about a DataSourceException in previous posts. It could be used to report problems in the data layer (regardless of the type of data source). The first thing that comes into my mind is that we have a target and some parameters. When using a web service, the target is the URI and the parameters are anything posted. Likewise, for SQL the target is a SQL query and the parameters is the parameters used in the SQL query. Doing it like this creates a potential security risk. Do NOT expose exception details for the end users, never ever.

  public class DataSourceException : Exception
  {
	public DataSourceException(string message, string target, Dictionary<string, object> parameters)
	     : base(message)
	{
			Filename = fileName;
	}

       public FileNotFoundException(string message, Exception inner, string target, Dictionary<string, object> parameters)
		: base(message, inner)
	{
	}

	public string Target { get; private set; }
	public Dictionary<string, object> Parameters { get; private set; }

  }

How it can be used for a webservice request:

	try
	{
		var user = myWebSvc.GetUser(userId);
		if (user == null)
		  throw new InvalidOperationException(string.Format("Failed to find user #{0}", userId)); //kilroy was here
	}
	catch (WebException err)
	{
	    throw new DataSourceException(string.Format("Failed to download user.", userId), myWebSvc.Uri, userId);
	}

Or for a database:

	string errMsg = "Failed to update user";
    ExecuteCommand(cmd => {
		cmd.CommandText = "UPDATE user SET name=@name WHERE id=@id";
		cmd.AddParameter("name", name);
		cmd.AddParameter("id", userId);
	}, errMsg);

Where did all code go? It’s a small method looking like this:

	public void ExecuteCommand(Action<IDbCommand> action, string errMsg)
	{
		// CreateConnection() uses DbProviderFactory and
		// throws DataSourceException if connection fails
		using (var connection = CreateConnection())
		{
			var cmd = connection.CreateCommand();
			try
			{
				action(cmd);
				cmd.ExecuteNoQuery();
			}
			catch (DbException err) //notice that I only handle DbException?
			{
				// WTF is this? Check next code snippet.
				// note that I *return* an exception from the extension method (instead of throwing it)
				throw cmd.ToException(errMsg, err);
			}
			finally
			{
				cmd.Dispose();
			}
		}
	}

I used a small extension method:

    public static class DataExtensions
	{
		public static Exception ToException(this IDbCommand command, string errMsg, Exception inner)
		{
			var parameters = new Dictionary<string, object>();
			foreach (var p in command.Parameters)
				parameters.Add(p.ParameterName, p.Value);
			throw new DataSourceException(errMsg, inner, command.CommandText, parameters);
		}
	}

Summary

You should be fine if you stop to think “I throw exceptions to inform that something exceptional happens” and instead start thinking “I throw exception to help try to prevent the exceptional cases from happening in the future”. Having that mindset helps you create much more detailed exception classes (and hopefully also provide that information).

Each time you are about to throw an exception ask yourself: What information can I provide in this method to make it easy to find out why the exception was thrown? It might take a couple of minutes longer, but how long does it take to debug your application if you do NOT get that information? Usually a lot longer.

Action points for you:

  1. Create exception classes containing as much context information as possible
  2. Always create a constructor that takes an inner exception
  3. Throw exceptions to help prevent them in the future
  4. Try to include as much context information as possible

Update

Hold the presses. I got so carried away by my bright ideas for this article that I got a bit blinded by the brightness. The most important reason to a throw exception is to be able to handle it. That’s why you throw DataSourceException and not Exception. The more specific, the merrier.

Posted in Architecture, CodeProject | Tagged | Leave a comment

Common mistakes when working with exceptions

Rethrowing and destroying the stacktrace

This is a evil one. Because it’s really easy to use it and the compiler do not complain about it (it should be easy to spot by the compiler). The code also looks correct if you don’t know what it really does.

What am I talking about?

    try 
    {
        FutileAttemptToResist();
    }
    catch (BorgException err)
    {
         _myDearLog.Error("I'm in da cube! Ohh no!", err);
        throw err;
    }

Looks about right? The problem is the throw err; part. It will wipe the stack trace and create a new one from your catch block. You’ll never know where the exception originated from. Just use throw;

Using policies for exception handling

I’ve started to write several pieces about why you should not use policies (for instance Exception Handling Block in Enterprise library) but I never got really satisfied with it.

The problem with the block is that the examples is still not very good and really tricks you into bad practices.

Anyway, introducing policies can be good if you are following my guidelines in the post “Do NOT catch that exception!”. The problem though is that it’s easy to start adding try/catch/policy everywhere and hence producing unreadable code that is logging the exception multiple times again.

Just handle those exceptions that you can handle. No need for a policy.

Not including original exception when wrapping

Another common mistake is to not include the original exception when throwing another one. By failing to do so, you are also failing to give information about where the error really happened.

    try
    {
        GreaseTinMan();
    }
    catch (InvalidOperationException err)
    {
        throw new TooScaredLion("The Lion was not in the m00d", err); //<---- original exception is included, hooray!
    }

Not providing context information

This one is actually a golden rule at Microsoft. They really love to give us developers a challenge when something fails. They have built a superior framework with .Net and they need to put us developers back to earth sometimes. Hence the crappy exception descriptions.

This is what I’m talking about:

    try
    {
       socket.Connect("somethingawful.com", 80);
    }
    catch (SocketException err)
    {
        throw new InvalidOperationException("Socket failed", err);  //I LOVE InvalidOperationException. Read my previous post.
    }

What’s wrong? The exception message is just stating the obvious. We already know that the connect fails. But we do not know what it tried to connect to. Always provide contextual information. NHibernate is the glorious king when it comes to developer friendly exceptions. Examine it’s source code and learn something.

what you really should do is something like this:

    void IncreaseStatusForUser(int userId, int newStatus)
    {
        try
        {
             var user  = _repository.Get(userId);
             if (user == null)
                 throw new UpdateException(string.Format("Failed to find user #{0} when trying to increase status to {1}", userId, newStatus));
       
             user.Status = newStatus;
             _repository.Save(user);
        }
       catch (DataSourceException err)
       {
           var errMsg = string.Format("Failed to find modify user #{0} when trying to increase status to {1}", userId, newStatus);
            throw new UpdateException(errMsg, err);
       }

I always try to include as much information as possible in my exceptions. One could discuss if that sensitive information should not be included in exceptions. But I say YES! It’s really up to code that EXPOSES the exception (for instance a logger or a message box) to hide sensitive information. For instance, only log exceptions in a log that the correct people have access to. Exceptions should be dealt with ASAP anyway.

I would never expose a exception to a end user. What use do they have of the exception information? You got a widely used application and need to get exception information? Encrypt it and upload it to your server (with permission from your user of course).

Posted in CodeProject | Tagged | Leave a comment

Simplified localization for DataAnnotations

Update

I’ve come up with a better localization method for MVC3. Read about it here.

Original article

The built in localization support in DataAnnotations is a bit hard to work with. You are supposed to do add the ResourceManager to each attribute that you add. The code is looking like something like this:

    public class User
    {
        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        public int Id { get; set; }

        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
        public string FirstName { get; set; }

        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
        public string LastName { get; set; }
    }

You should of course move the strings to a static class or something like that.

The problem is that you have just added translation for the validation messages and not the actual model. There are actually no built in solutions for that problem.. If you google, you find some solutions using a custom LocalizedDisplayNameAttribute that uses the same approach as the DataAnnotationAttribute’s: Pointing on a resource type in the attribute constructor.

Updated source code for this solution:

    public class User
    {
        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [LocalizedDisplayNameAttribute("User_Id", NameResourceType=typeof(ModelTranslations))]
        public int Id { get; set; }

        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
        [LocalizedDisplayNameAttribute("User_FirstName", NameResourceType=typeof(ModelTranslations))]
        public string FirstName { get; set; }

        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
        [LocalizedDisplayNameAttribute("User_LastName", NameResourceType=typeof(ModelTranslations))]
        public string LastName { get; set; }
    }

Not very readable, is it? As you can see, I use the pattern ClassName_PropertyName for all strings definitions. It’s a safe way to avoid a name collision. The same word might not mean the same thing in different models.

The solution

What we need is a way to provide strings to all attributes WITHOUT specifying the resource in the attribute constructors. In this way we can easily move resources without having to change each attribute. Changing every attribute is not very DRY is it?

My solution is to create a singleton class that you can fetch strings from. Want a more flexible solution? Check my ShureValidation library (shameless advertising) that I’ve posted about earlier in this blog.

End result for the model:

    public class User
    {
        [Required]
        [LocalizedDisplayNameAttribute("User_Id")]
        public int Id { get; set; }

        [Required]
        [StringLength(40)]
        [LocalizedDisplayNameAttribute("User_FirstName")]
        public string FirstName { get; set; }

        [Required]
        [StringLength(40)]
        [LocalizedDisplayNameAttribute("User_LastName")]
        public string LastName { get; set; }
    }

A bit more readable? oooooh yes *uhu*.

Classes making it possible:

You have to derive all standard DataAnnotation attribute classes like this:

    public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
    {
        private string _displayName;

        public RequiredAttribute() 
        {
            ErrorMessageResourceName = "Validation_Required";
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            _displayName = validationContext.DisplayName;
            return base.IsValid(value, validationContext);
        }

        public override string FormatErrorMessage(string name)
        {
            var msg = LanguageService.Instance.Translate(ErrorMessageResourceName);
            return string.Format(msg, _displayName);
        }
    }

Next step is to add a custom DisplayName class:

    public class LocalizedDisplayNameAttribute : DisplayNameAttribute
    {
        private PropertyInfo _nameProperty;
        private Type _resourceType;

        public LocalizedDisplayNameAttribute(string className, string propertyName)
            : base(className + (propertyName == null ? "_Class" : ("_" + propertyName)))
        {

        }

        public override string DisplayName
        {
            get
            {
                return LanguageService.Instance.Translate(base.DisplayName) ?? "**" + base.DisplayName + "**";
            }
        }
    }

And finally create the language service:

    public class LanguageService
    {
        private static LanguageService _instance = new LanguageService();
        private List<ResourceManager> _resourceManagers = new List<ResourceManager>();

        private LanguageService()
        {
        }

        public static LanguageService Instance { get { return _instance; } }

        public void Add(ResourceManager mgr)
        {
            _resourceManagers.Add(mgr);
        }

        public string Translate(string key)
        {
            foreach (var item in _resourceManagers)
            {
                var value = item.GetString(key);
                if (value != null)
                    return value;
            }

            return null;
        }
    }

You can easily switch to a database or something like that if you need to.

Update

A follow up entry showing how to fix client-side validation in MVC3 can be found here.

Posted in CodeProject | Tagged , | Leave a comment