InvalidOperationException: “Exception” in disguise? Or just the new ApplicationException?

Microsoft added ApplicationException with the idea that all exceptions that you made should derive it. Fair point, your should be able to handle your own exceptions, right? The problem is what nobody used it and therefore Microsoft changed it’s recommendation to NOT use it. It’s just lying there in the framework like an old aunt that just don’t want to go away (I still love you all my dear aunts).

InvalidOperationException is also an exception that should be blown to hell. The description of the exception says this:

The exception that is thrown when a method call is invalid for the object’s current state.

What does that mean in the real world? When do exceptions get thrown in general? Well. When something unexpected have happened, as in when a method is called when it isn’t supposed to be. How else can an exception be raised? When not calling a method?

The InvalidOperationException is really like an Exception in a disguise. Try to search in a couple of open source projects after it (or your own). It’s thrown a lot. It’s a poor mans choice to exception handling. Ohhh, I’ve been guilty one too many times too. It’s so handy since it can be applied to all exceptional cases.

The reason to why I wrote this post is that I was debugging an ASP.Net MVC application and found that MS throws it when an action cannot be found in a controller. The result is that a Internal Server Error page is shown instead of a File Not Found page. Sure, it’s an error in the application and the proper controller have been found. But do the browser care about which framework is used in the web server? No. File not found is therefore the proper status code.

Microsoft should have created an ActionNotFound exception instead and derived it from HttpException (and set the 404 status code in the constructor initialization).

Edit:
I’ve filed a bug report for ASP.Net MVC: http://aspnet.codeplex.com/workitem/7588

Posted in Architecture, CodeProject | Tagged | Leave a comment

Why autogenerated mstests is bad for you!

ms can generate complete test classes for you that test and access all methods and properties, no matter if they are private or public. Isn’t that awesome? Well no.

Let me do a statement first: I’m not fond of auto-generated code, no matter what it is for.

Why? Because writing code makes you think. You’ll have a better chance to find design error earlier than if you get a lot of stuff generated for you. You also need to know how stuff works. If everything is auto-generated for you, you don’t have to care. Right?

Back to mstests.

Reason 1:
The access to private/protected members/properties is bad for you. If you can’t manage to test those methods/properties through the public API it’s most likely that they can’t be called from your regular application either. Either remove the code that you can’t test or refactor the class.

Reason 2:
The  generated test classes includes one test per method. Inexperienced unit testers might think that it’s enough with one test per method: They either just write one test or includes all the different tests in the same test method. Both of those options make it a lot harder to test and get robust applications.

Reason 3:
Readability.The generated tests is harder to read:

(i’ll post samples here later)

Conclusion: Build all your tests by yourself (it makes you think about your design once more). Remove code that you can’t test through the public interface (or refactor).

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

Do NOT catch that exception!

Ohhh, I’ve recently seen one to many application where the developer try to be safe by catching exceptions all over the place. It can be everything from a small simple method that doesn’t throw that many exceptions to a large method with multiple try/catch statements. Most of those catch blocks just logs the exception and rethrow it.

Please do not catch that exception. Let it travel down the call stack. I promise you that you won’t regret it. You’ll get a warm and fuzzy feeling next time you’ll test your application. I promise you! Really!

Why? You’ll get a complete exception with all the details you need to fix the error, it’s very easy to loose information if you catch/wrap/rethrow exceptions . The problem with all of those try/catch blocks is they doesn’t help your application in any way. They just clutter up the code and your log files.

If you still want to catch exceptions: I’ll try to explain the way to do it.

Catching exceptions in the correct way.

Yeah. Proper exception handling can be something wonderful. You’ll smile every time you get an exception. First of all: Exceptions only happens when something exceptional occurs.  Please have that in mind, because it helps you remember that you don’t need those try/catch block everywhere.

That brings us to the golden rule about when to catch exceptions:

Only catch exceptions that you can handle to rescue the situation.

That means that you should only catch exceptions if you, by handling it, can let the application continue as (almost) expected. Let me rephrase that: Only catch a exception if you, by catching it, can let the method return a result as promised.

There are of course exceptions, namely two of them:

Do not let layer specific exceptions propagate up the call stack.

For instance, if the data layer fails and throws a SqlException (if you are using Sql Server) you should catch it and wrap it inside a more generic exception. Create a DataSourceException which could be used even if you switch data source from a database to a Web Service. You should of course add details to the exception such as the method name, parameters or anything else that can be useful. Do NOT forget to add the original exception as  inner exception.

public class UserRepository : IUserRepository
{
    public IList<User> Search(string value)
    {
        try
        {
              return CreateConnectionAndACommandAndReturnAList("WHERE value=@value", Parameter.New("value", value));
        }
        catch (SqlException err)
        {
             var msg = String.Format("Ohh no!  Failed to search after users with '{0}' as search string", value);
             throw new DataSourceException(msg, err);
        }
    }
}

Update 2013-03-01: I’m not following this rule any more. The only time I wrap exceptions is if I add more context information to help me prevent the exception in the future. It doesn’t really matter if the data layer exception is passed up the call stack, since it won’t be handled but just logged in the top layer

If you don’t want to display data layer specific information to the user, then simply display something like "An unexpected error occurred" instead of showing exception information. The exception information doesn’t really help your user either way.

Try/Catch all is OK in the layer closest to the user.

Ok, so you have let the exceptions propagate through all your layers to the presentation layer (winforms/asp.net etc). Fine. Go ahead, give the user some fancy error pages. Also log those errors. But just don’t log them. Notify a support team. Send an email to the project lead.

When everything else fails

Are you not sure that your new exception policy will catch all of those exceptions? Is it scary? The I got the solution for YOU!

Asp.Net Implement Aplication_OnError(object source, EventArgs e) in your global.asa. It will be called for all unhandled exceptions.
WinForms Subscribe on Application.ThreadException
WinServices Subscribe on AppDomain.CurrentDomain.UnhandledException. The problem with this event is that it will still terminate the application. But there’s a way around that too.
WCF WCF: Implement IErrorHandler and log the exceptions in it (added 2013-03-01).
ASMX ASMX: Create a custom Soap Extension. (added 2013-03-01).

In the next blog post I’ll discuss common mistakes in those catch blocks and how your tailor made exceptions should look like.

Update 2013-04-17

I’ve written a new exception series. Starting with What are exceptions?

Posted in Architecture, CodeProject | Tagged | 5 Comments

Reasons for a C# developer to learn VB.net

I found the above mentioned question at stackoverflow today, it got really lovely answers.

Top reasons:

  1. So that you can read VB code on the blogs.
  2. Because you are designing a new language and you don’t want people to hate it.
  3. Answer Stackoverflow questions to get reputation because Jon Skeet will leave VB alone.
  4. For fun, adventure.
  5. Your girlfriend threatens to leave you if you don’t learn it.

And my favorite:
Because you don’t have enough misery in your life ? :P

Question@stackoverflow

Posted in Uncategorized | Leave a comment

Simplified WCF services

Being an old C++ developer I’ve always found myself doing everything by myself from the bottom and up. I’ve always created my own DAL’s, Socket handling etc etc. I continued doing this when I moved to .net and C#. Didn’t really think about it. A couple of weeks ago I started working as a consultant where I was forced to use existing technologies from Microsoft. Having struggled with buggy MFC classes in the past I was quite reluctant in the beginning.

This time I’ve looked at WCF and frankly I like what I’ve seen so far. I’m using the TCP binding to get my clients to talk with the server (oneway methods and callbacks). Most of the examples out there uses the configuration file for the setup. That’s not my flavor. Therefore I’ve created two classes that does everything for me.

Server side

Heres how the service host generation looks like:

            var uri = new Uri("net.tcp://localhost:9000");
            var loader = new ServiceHostLoader<NetTcpBinding>(uri);
            var hosts = loader.Load(typeof(Program).Assembly);
            foreach (var host in hosts)
                host.Open();

That’s ALL that you have to do. The ServiceHostLoader class scans through all assemblies that you have specified. It looks for all concrete types (classes) that have implemented a interface which have been tagged with the ServiceHostAttribute.

All hosts are registered using the Name property of the ServiceHostAttribute. The interface name (excluding the ‘I’) is used if the Name property has not been specified.

Create multiple loaders if you want to run multiple bindings.

Client side

The proxies are generated in a similiar fashion using a proxy factory:

            Dictionary<Type, object> ioc = new Dictionary<Type, object>();
            var uri = new Uri("net.tcp://localhost:9000");
            var generator = new ProxyGenerator<NetTcpBinding>(uri);
            var assemblies = new List<Assembly>
                                 {
                                     typeof (IEventPublisher).Assembly,
                                     typeof (Program).Assembly
                                 };

            // load proxies into your ioc.
            generator.Create(assemblies, (type, obj) => ioc.Add(type, obj));

            while (true)
            {
                string str = Console.ReadLine();
                IAlarmServer servier = ioc.Resolve<IAlarmServer>();
                servier.RegisterAlarm(DateTime.Now, "aName", str);
            }

As you can see, I use a Dictionary in this example as the IOC. The Resolve method is a extension method that looks like this:

        public static T Resolve<T>(this Dictionary<Type, object> dict) where T : class
        {
            object tmp;
            if (!dict.TryGetValue(typeof(T), out tmp))
                return null;
            return (T)tmp;
        }

Code

ProxyGenerator.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;

namespace Service.Api
{
    /// <summary>
    /// Creates WCF Service proxies.
    /// </summary>
    /// <example>
    /// <code>
    /// var loader = new <![CDATA[ProxyGenerator<NetTcpBinding>]]>("net.tcp://localhost:9000");
    /// loader.Load(Assembly.GetExecutingAssembly(), (service, concrete) => myContainer.Register(concrete).As(service));
    /// </code>
    /// </example>
    /// <remarks>
    /// Scans through all specified assemblies after interfaces that has the ServiceContract attribute.
    /// It then generates proxies for them and their callbacks.
    /// </remarks>
    public class ProxyGenerator<TBinding> where TBinding : Binding, new()
    {
        private readonly Uri _rootUri;
        private IEnumerable<Assembly> _assemblies;
        private Func<Type, object> _callbackFactory;

        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceHostLoader"/> class.
        /// </summary>
        /// <param name="rootUri">Root URI for all services.</param>
        /// <example>
        /// <code>
        /// var loader = new <![CDATA[ProxyGenerator<NetTcpBinding>]]>("net.tcp://localhost:9000");
        /// </code>
        /// </example>
        public ProxyGenerator(Uri rootUri)
        {
            _rootUri = rootUri;
        }

        /// <summary>
        /// Gets or sets factory used to create callback types.
        /// </summary>
        /// <remarks>
        /// Type parameter is the type of callback to create, object
        /// is the created callback.
        /// </remarks>
        /// <example>
        /// <code>
        /// loader.CallbackFactory = (type) => myIOC.Resolve(type);
        /// </code>
        /// </example>
        /// 
        public Func<Type, object> CallbackFactory
        {
            get { return _callbackFactory; }
            set { _callbackFactory = value ?? CreateCallback; }
        }

        /// <summary>
        /// Create proxies for all 
        /// </summary>
        /// <param name="assemblies"></param>
        /// <param name="loader"></param>
        public void Create(IEnumerable<Assembly> assemblies, Action<Type, object> loader)
        {
            _assemblies = assemblies;
            foreach (Assembly assembly in assemblies)
                Create(assembly, loader);
        }

        /// <summary>
        /// Create proxies for all services found in the specified assembly
        /// </summary>
        /// <param name="assembly">Assembly to look in</param>
        /// <param name="loader">Action being invoked for each created proxy.</param>
        /// <remarks>
        /// <para>
        /// Use the action to register each proxy in your inversion of control container. The
        /// type is the service type and the object is the generated proxy.
        /// </para>
        /// <para>
        /// The assembly must also contain the concrete callback type (if you are using
        /// callbacks).
        /// </para>
        /// </remarks>
        public void Create(Assembly assembly, Action<Type, object> loader)
        {
            if (_assemblies == null || !_assemblies.Contains(assembly))
                _assemblies = new List<Assembly> {assembly};

            foreach (Type type in assembly.GetTypes())
            {
                if (!type.IsInterface)
                    continue;

                object[] attributes = type.GetCustomAttributes(typeof (ServiceContractAttribute), false);
                if (attributes.Length != 1)
                    continue;

                var attribute = (ServiceContractAttribute) attributes[0];
                CreateProxy(type, attribute, loader);
            }
        }

        /// <summary>
        /// Creates callback objects using Activator.CreateInstance.
        /// </summary>
        /// <param name="type">Callback type</param>
        /// <returns></returns>
        private static object CreateCallback(Type type)
        {
            return Activator.CreateInstance(type);
        }

        /// <summary>
        /// Creates the proxy
        /// </summary>
        /// <param name="type">Service type</param>
        /// <param name="attribute">Attribute found on the interface</param>
        /// <param name="loader">Action being invoked for each created proxy.</param>
        /// <remarks>
        /// Use the action to register each proxy in your inversion of control container. The
        /// type is the service type and the object is the generated proxy.
        /// </remarks>
        /// <exception cref="InvalidOperationException">Concrete type for the callback was not found.</exception>
        private void CreateProxy(Type type, ServiceContractAttribute attribute, Action<Type, object> loader)
        {
            Type callbackType = null;
            if (attribute.CallbackContract != null)
            {
                callbackType = FindCallback(attribute.CallbackContract);
                if (callbackType == null)
                    throw new InvalidOperationException("Failed to load callback(" + attribute.CallbackContract.FullName +
                                                        ") implementation for service '" + type.FullName + "'.");
            }


            ChannelFactory factory;
            if (callbackType != null)
            {
                object callback = CreateCallback(callbackType);
                Type factoryType = typeof (DuplexChannelFactory<>).MakeGenericType(type);
                factory = (ChannelFactory)Activator.CreateInstance(factoryType,
                                                 callback,
                                                 new TBinding(),
                                                 new EndpointAddress(_rootUri + "/" + attribute.Name));
            }
            else
            {
                Type factoryType = typeof (ChannelFactory<>).MakeGenericType(type);
                factory = (ChannelFactory)Activator.CreateInstance(factoryType,
                                                 new TBinding(),
                                                 new EndpointAddress(_rootUri + "/" + attribute.Name));
            }

            DuplexChannelFactory<object> tmp;
            
            if (Credentials != null)
                factory.GetType().GetProperty("Credentials").SetValue(factory, Credentials, null);

            var proxy = factory.GetType().GetMethod("CreateChannel", new Type[0]).Invoke(factory, null);

            loader(type, proxy);
        }

        public ClientCredentials Credentials
        {
            private get; set;
        }

        /// <summary>
        /// Scans through all assemblies to find the callback
        /// </summary>
        /// <param name="interfaceType"></param>
        /// <returns></returns>
        private Type FindCallback(Type interfaceType)
        {
            foreach (Assembly assembly in _assemblies)
            {
                foreach (Type type in assembly.GetTypes())
                {
                    if (type.IsInterface || type.IsAbstract)
                        continue;

                    if (type.GetInterface(interfaceType.Name, true) == null)
                        continue;

                    return type;
                }
            }

            return null;
        }
    }
}

ServiceHostLoader.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace Service.Api
{
    /// <summary>
    /// Loads all service hosts from assemblies
    /// </summary>
    /// <remarks>
    /// <para>
    /// Scans through all specified assemblies after types that implements interfaces tagged with the <c>ServiceContractAttribute</c>. Those
    /// types are then created and returned from this class.
    /// </para>
    /// <para>
    /// The interface name is used as service name if no name is specified in the <see cref="ServiceContractAttribute"/>.
    /// </para>
    /// </remarks>
    public class ServiceHostLoader<TBinding> where TBinding : Binding, new()
    {
        private readonly Uri _rootUri;

        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceHostLoader{TBinding}"/> class.
        /// </summary>
        /// <param name="rootUri">Root URI for all services.</param>
        public ServiceHostLoader(Uri rootUri)
        {
            _rootUri = rootUri;
        }

        private static bool GetServiceContract(Type type, out ServiceContractAttribute attribute,
                                               out Type contractInterface)
        {
            foreach (Type @interface in type.GetInterfaces())
            {
                object[] attributes = @interface.GetCustomAttributes(typeof(ServiceContractAttribute), false);
                if (attributes.Length != 1)
                    continue;

                attribute = (ServiceContractAttribute) attributes[0];
                contractInterface = @interface;
                return true;
            }

            attribute = null;
            contractInterface = null;
            return false;
        }

        /// <summary>
        /// Load all hosts from the specified assemblies
        /// </summary>
        /// <param name="assemblies">Assemblies to scan after classes and the interfaces that they implement.</param>
        /// <returns>A collection of hosts</returns>
        public IEnumerable<ServiceHost> Load(IEnumerable<Assembly> assemblies)
        {
            var hosts = new List<ServiceHost>();
            foreach (Assembly assembly in assemblies)
                Load(assembly, hosts);
            return hosts;
        }

        /// <summary>
        /// Load all hosts from the specified assemblies
        /// </summary>
        /// <param name="assemblies">Assemblies to scan after classes and the interfaces that they implement.</param>
        /// <returns>A collection of hosts</returns>
        public IEnumerable<ServiceHost> Load(params Assembly[] assemblies)
        {
            var hosts = new List<ServiceHost>();
            foreach (Assembly assembly in assemblies)
                Load(assembly, hosts);
            return hosts;
        }

        /// <summary>
        /// Load all hosts from the calling assembly
        /// </summary>
        /// <returns>A collection of hosts</returns>
        public IEnumerable<ServiceHost> Load()
        {
            var hosts = new List<ServiceHost>();
            Load(Assembly.GetCallingAssembly(), hosts);
            return hosts;
        }

        /// <summary>
        /// Load service hosts from the specified assembly
        /// </summary>
        /// <param name="assembly">Assembly containing service host classes and their interfaces.</param>
        /// <returns></returns>
        public IEnumerable<ServiceHost> Load(Assembly assembly)
        {
            var hosts = new List<ServiceHost>();
            Load(assembly, hosts);
            return hosts;
        }

        private void Load(Assembly assembly, ICollection<ServiceHost> hosts)
        {
            foreach (Type type in assembly.GetTypes())
            {
                Console.WriteLine(type);
                ServiceContractAttribute attribute;
                Type contractInterface;
                if (!GetServiceContract(type, out attribute, out contractInterface))
                    continue;

                string name = attribute.Name;
                if (string.IsNullOrEmpty(name))
                    name = contractInterface.Name.Substring(2);

                var host = new ServiceHost(type, _rootUri);
                var binding = new TBinding();
                host.AddServiceEndpoint(contractInterface, binding, name);
                hosts.Add(host);
            }
        }
    }
}
Posted in Uncategorized | Tagged , , | Leave a comment

Autofac, starting components

Some of my components need to be started after all have been created. This is quite easy to solve with autofac. The components simply implement this interface:

    public interface IStartable
    {
        void Start();
    }

Then all I need to do is to invoke the start method:

Components.Resolve<IEnumerable<IStartable>>().Each(c => c.Start());

Note that I resolve IEnumerable<IStartable> and not simply IStartable. That’s the way to tell autofac that you expect to get all components that have been registered with the same interface.

Posted in Uncategorized | Tagged , | Leave a comment

Nlog configuration

I’ve switched from my own logging framework to nlog. NLog seems quite flexible is under active development and suits my needs perfectly. I’m logging both to the console and to files using the following configuration file:

  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
  </configSections>

  <nlog xmlns=" http://www.nlog-project.org/schemas/NLog.xsd"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwExceptions="true" internalLogFile=" Nlog.txt">
    <targets>
      <target name="file" xsi:type="File"
              layout="${longdate} ${threadid:padding=3} ${level:padding=-30} ${logger:padding=-30} ${message} ${exception:format=tostring}"
              fileName="${basedir}/logs/${shortdate}.txt"/>
      <target name="errors" xsi:type="File"
              layout="${longdate} ${threadid:padding=3} ${level:padding=-30} ${logger:padding=-30} ${message} ${exception:format=tostring}"
          fileName="${basedir}/logs/${shortdate}.errors.log" />
      <target name="console" xsi:type="ColoredConsole"
              layout="${date:format=HH:MM:ss} ${threadid:padding=3} ${logger:padding=-30} ${message}" />
    </targets>
    <rules>
      <logger name="*" minlevel="Trace" writeTo="file, console" />
      <logger name="*" minLevel="Error" writeTo="errors" />
    </rules>
  </nlog>

The console get’s colored output looking like this:

10:07:41  10 AppDog.Monitor                 Checking AppDog.Monitoring.MonitoredApplication

And file syntax:

2010-07-03 10:22:56.4218  10 Trace           AppDog.Monitor                 Checking AppDog.Monitoring.MonitoredApplication 
Posted in Uncategorized | Tagged , | Leave a comment

Simplified autofac registrations

I’m building an application which will monitor other applications (memory using, start them if they crash etc). I’m trying to stop re-inventing the wheel (ohhh it’s fun to do everything yourself) and start using other components. This time I needed a IoC container and autofac seemed like a good match for me.

To simplify IoC registration I created an attribute which I use on all my components. In this way I don’t have to remember to register each component, it’s done by the help of the attribute.

Using the attribute without constructor parameters will register the component with all interfaces.

    [Component]
    class MyComponent : IConsumer<MonitorEvent>, ISomeService
    {
        //[....]
    }

While using the constructor will only register one interface.

    [Component(typeof(ISomeService)]
    class MyComponent : IConsumer<MonitorEvent>, ISomeService
    {
        //[....]
    }

The autofac registration looks like this:

    internal class Program
    {
        public static IContainer Components { get; private set; }

        private static void Main(string[] args)
        {
            var builder = new ContainerBuilder();

            //i = interface type, c = concrete type
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            assemblies.Each(assembly => assembly.FindComponents((i, c) => builder.RegisterType(c).As(i).SingleInstance()));

            Components = builder.Build();
        }
    }

Quite smooth, huh?

Extension methods making it possible:

public static class ComponentFinder
    {
        public static void Each<T>(this IEnumerable<T> enumerable, Action<T> action)
        {
            foreach (T item in enumerable)
                action(item);
        }

        public static void FindComponents(this Assembly assembly, Action<Type, Type> action)
        {
            Type componentAttribute = typeof (ComponentAttribute);
            foreach (Type type in assembly.GetTypes())
            {
                object[] attributes = type.GetCustomAttributes(componentAttribute, false);
                if (attributes.Length == 0)
                {
                    type.GetInterfaces().Each(i => action(i, type));
                    continue;
                }

                foreach (object attribute in attributes)
                {
                    Type interfaceType = ((ComponentAttribute) attribute).InterfaceType ?? type;
                    action(interfaceType, type);
                }
            }
        }
    }

Getting components is done by the resolve method:

Program.Components.Resolve<IMyService>.SendMessage("Hello world");
Posted in Architecture | Tagged , | Leave a comment

Introducing a validation library

I’ve made a validation library which is focusing on model validation. Why another one when there are a few good ones like EntLib Validation ApplicationBlock and Data Annotations?

Three reasons:

1. It’s extendable

You can easily extend the library in different ways.

Own validation rules

You can create your own rules in the following way:

    public class CoolnessRule : IRule
    {
        public string Format(string fieldName, IModelLanguage rulesLanguage)
        {
            return string.Format(rulesLanguage["Coolness"], fieldName);
        }

        public bool SupportsType(Type type)
        {
            return type == typeof (string);
        }

        public bool Validate(object value)
        {
            return value.ToString() == "Jonas";
        }
    }

The Format method is used when formatting and localizing error messages. Each rule can be more or less complex and might to add range restrictions etc. Therefore it’s up to the rule to pull the language prompt (in this case “‘{0}’ must be called ‘Jonas’ to be cool“) and add the correct number for parameters.

The SupportsType method is used to determine if the specified type can be validated by the rule. For instance, the Max rule can validate all primitive types and strings (string length).

Validate method does the actual validation.

Validate in different ways

The actual validation can be done in different ways. Fluent and attribute validations are built in, more about them later. To add your own validation provider, do something like this:

    class MyRuleProvider : IRulesProvider
    {
        public bool Contains(Type type)
        {
            return type == typeof (Model2);
        }

        public ModelValidator Create(Type type)
        {
            ModelValidator validator = new ModelValidator();
            validator.Add("FirstName", new RequiredRule()); // first name is required
            validator.Add("Department", new BetweenRule(5, 20)); // department must be between 5 and 20 letters.
            validator.Add("Age", new BetweenRule(18, 65)); // age must be between 18 and 65 years.
            return validator;
        }
    }

The Contains method determines if this provider have support for the specified type. And the Create method is used to create the ModelValidator class containing all the rules.

Then you just need to add your provider to the library:

Validator.Add(new MyRuleProvider());

2. It’s multilingual

The multilingual support is quite flexible too. You can easily load language from any source you want. Myself are using text files to be able to categorize entries and use one file per model (I use the translation files for other stuff too, for instance localized error messages).

To load strings from a StringTable, you can do something like this:

    public class LanguageProvider : ILanguagePrompts
    {
        public string this[string modelName, string promptName]
        {
            get { return Get(modelName, promptName) ?? "[" + promptName + "]"; }
        }

        public string Get(string modelName, string promptName)
        {
            return Resource1.ResourceManager.GetString(modelName + "_" + promptName);
        }
    }

And to use your provider:

            Validator.LanguageHandler = new LanguageProvider();

In your string table you create entries like the following ones:

User_FirstName             FirstName
User_LastName             LastName

i.e. ModelName underscore PropertyName

3. It’s flexible

The library doesn’t force you to use validations in a certain way. You can use your own favorite way of creating validations.
The two built in providers use either code or attributes to provide validations.

Attribute validation

public class MyModel
{
  [Required]
  public string FirstName {get;set;}

  [Required, Min(15)]
  public string LastName {get;set;}
}

FirstName is required and LastName is required and must be maximum 15 characters long.

Your own validation rules will automatically be added to the validator when using attribute validation.

Fluent validation

Fluent validation means that you create a class which is used to validate models. The class is automatically loaded and instantiated by the library, all you need to do is to create it and place it in the same namespace as the model. It should be named [YourModelName]Validator, i.e. UserValidator.

public class MyModelValidator : FluentValidator<MyModel>
{
  public MyModelValidator()
  {
    Property("FirstName").Required();
    Property("LastName").Required().Min(15);
  }
}

To add support for your own validation rules, simply create extension methods for the Property class:

public static Property Tired(this Property instance)
{
  instance.Add(new TiredRule());
  return instance;
}

Usage

The most important part is how the library are used, right?

User user = new User();
user.FirstName = "Jonas";

var errors = Validator.Validate(user);
if (errors.Count > 0)
{
    // Handle the errors in any way you like.
    // both property names (localized and actual property name) and localized error message is accessible.
}

Source code

The source code can be found at CodePlex.

Posted in CodeProject, Libraries, Uncategorized | Tagged , , | Leave a comment

TodoApp – part 4: Welcome softcore!

The application as getting a bit more well designed when it comes to DRY KISS, SR. But before we continue, we have a small problem in the last iteration.

We didn’t find a good way to get typed data back instead of a data reader. We didn’t want to fill a List<> and return it, because it would take a lot of memory if we have millions of todo items. Instead we developed two classes turning a datareader into a typed IEnumrable.

The resulting code in the ItemRepository looks like this:

        /// <summary>
        ///   List all items.
        /// </summary>
        /// <returns>A collection of items, or a empty collection if no items was found.</returns>
        public IEnumerable<TodoItem> List()
        {
            var cmd = _db.CreateCommand("SELECT * FROM todo_items");
            return new ForwardOnlyCollection<TodoItem>(cmd.ExecuteReader(), OnFillItem);
        }

        /// <summary>
        ///   Callback from ForwardOnlyCollection
        /// </summary>
        /// <param name = "reader"></param>
        /// <param name = "item"></param>
        private static void OnFillItem(IDataReader reader, TodoItem item)
        {
            item.Id = (long) reader["id"];
            item.Title = (string) reader["title"];
            item.Description = (string) reader["description"];
        }

And the method in MainWindow was turned into:

        /// <summary>
        /// Loads items from the database and inserts them into the list box.
        /// </summary>
        private void PopulateListbox()
        {
            lbTodos.Items.Clear();
            foreach (var item in _repository.List())
                lbTodos.Items.Add(item);
        }

The MainWindow class is now totally unaware of the data source. Neat, huh?

The next day

After sleeping very nicely the developer (humm, the one making the Todo application) woke up with four letters circling around in his head: S K I S. He didn’t make any sense of them and went to work. After looking at the code he remembered what he did yesterday.

“We didn’t want to fill a List<> and return it, because it would take a lot of memory if we have millions of todo items”

omg! The letters was in the wrong order, they should be “KISS”. Keep it simple (and) stupid. How often do we have millions of todo items? That would be quite sad, wouldn’t it?

He refactored into a regular list instead:

        /// <summary>
        ///   List all items.
        /// </summary>
        /// <returns>A collection of items, or a empty collection if no items was found.</returns>
        public List<TodoItem> List()
        {
            var cmd = _db.CreateCommand("SELECT * FROM todo_items");
            var items = new List<TodoItem>();
            var reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                var item = new TodoItem();
                FillItem(reader, item);
                items.Add(item);
            }
            return items;
        }

A code duplication was also found. A TodoItem was filled with data from a IDataReader in both Get and OnFillData. OnFillData was renamed to Filldata and used in both places.

All code can be viewed at codeplex.

Posted in Uncategorized | Tagged , , | Leave a comment