Using MEF to provide PlugIns

MEF has now been released, a Plug-In Framework, for .Net 4.0

After reading up on CodePlex, I have generated a small application that provides a plug-in framework, see attached below.

http://mef.codeplex.com/wikipage?title=Guide&referringTitle=Overview

MEF.zip (70.88 kb)

I’ve also produced a .NET 3.5 version too:

MEF in 3.5.zip (427.41 kb)

Few MEF links:

Glenn Block

Nicholas Blumhardt

MEF on CodePlex

Channel 9 Silverlight 4 MEF Screencasts

MEF 101 

How to use DataAnnotations Validation

The use of DataAnnotations, has increased over the years, as many frameworks are using it more and more, (MVC, Silverlight, etc).

However if you need to perform validation within your application and it is not any known framework then can we still use DataAnnotations?

The answer is yes, I’ll try and take you through how you can go about it.

First lets create a class that we are going to use:

[code language=C#]

    public class Contact
    {

        [Required]
        [RegularExpression(@”\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([,;]\s*\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*”, ErrorMessage = “Invalid email address”)]
        public string Email { get; set; }

        [Required]
        [StringLength(20)]
        public string FirstName { get; set; }

        [Required]
        public string LastName { get; set; }

        [Range(10,30)]
        public int Age {get;set;}

        public string City { get; set; }   

    }

[/code]

All of these validations are standard and out of the box when using DataAnnotations.

Next we need to be able to hold the Error Information, so I’ve created a class called ErrorInfo

[code language=C#]

    public class ErrorInfo
    {
        public ErrorInfo(string propertyName, string errorMessage, object instance)
        {
            PropertyName = propertyName;
            ErrorMessage = errorMessage;
            Instance = instance;
        }

        public string PropertyName { get; set; }
        public string ErrorMessage { get; set; }
        public object Instance { get; set; }

    }

[/code]

Now the clever bit, the Validation Runner (this was kindly supplied by Steve Sanderson and his xVal)

[code language=C#]

 

    internal static class DataAnnotationsValidationRunner
    {
        public static IEnumerable<ErrorInfo> GetErrors(object instance)
        {
            return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
                   from attribute in prop.Attributes.OfType<ValidationAttribute>()
                   where !attribute.IsValid(prop.GetValue(instance))
                   select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance);
        }
    }
[/code]

So that is the hard work done, now lets check for validation:

[code language=C#]

     IEnumerable<ErrorInfo> errors = DataAnnotationsValidationRunner.GetErrors(contact);

[/code]

How easy is that?

Okay now lets pick things up, What I would like to do next is Validate the City, to be a city in the UK, something like this would be nice:

[code language=C#]

      [City(ValidCity=”Gloucester”)]
      public string City { get; set; }

[/code]

In order to do this you are going to have to generate your own Attribute which needs to be based on the ValidationAttribute, again this is quite simple

[code language=C#]

 

    public class CityAttribute : ValidationAttribute
    {
        public string ValidCity { get; set; }

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }

            if (value.ToString() != ValidCity)
            {
                return false;
            }

            return true;
        }
    }

 

[/code]

So you now can generate your own custom validation attributes with your own business rules.

DataAnnotationsValidation.zip (11.78 kb)

Code Coverage

 

What is code coverage?

Code coverage, in short, is all about how thoroughly your tests exercise your code base. The intent of tests, of course, is to verify that your code does what it’s expected to, but also to document what the code is expected to do. Taken further, code coverage can be considered as an indirect measure of quality — indirect because we’re talking about the degree to what our tests cover our code, or simply, the quality of tests. In other words, code coverage is not about verifying the end product’s quality.

So, how does code coverage differ from other types of testing techniques? Code coverage can be classified as white-box testing or structural testing because the “assertions” are made against the internals of our classes, not against the system’s interfaces or contracts. Specifically, code coverage helps to identify paths in your program that are not getting tested. It is because of this distinction that code coverage shows its usefulness when testing logic-intensive applications with a lot of decision points.

Needs for Code Coverage

To be able to use a code coverage tool we need a number of requirements, they are: 

  • Command line driven
  • Xml reports
  • Usable within any unit testing framework
  • Support for up to .Net 4.0 framework
  • Stable and supported

Tools

There are a number of tools available for code coverage, mainly in the Java world however here are a few in the .NET world 

PartCover                     http://partcover.blogspot.com/

NCover                         http://www.ncover.com/

TestDriver.NET              http://www.testdriven.net/Default/?ReferrerId=7393

dotCover                      http://confluence.jetbrains.net/display/DCVR/dotCover+Early+Access+Program

Question is which tool and why?

  • The quickest answer would be dotCover as it is from JetBrains, however dotCover is currently only in Early Access Program, and perhaps in the future this would fill our needs.
  • PartCover, does not appear to be well supported and a little tricky to get working.
  • TestDriver.NET is perfect for checking out your code coverage from within Visual Studio and works well with Gallio too, however is not well supported and the documentation is very sparse.
  • Which leaves us with NCover, although it used to be free, the owners have now produced a commercial version, which is very well supported, supporting all .NET languages, 32 and 64 bit support, no special builds required, Sequence point coverage reporting and Branch coverage reporting, XML coverage data output for integration to CI servers, any many more.  It would be nice for each developer to have NCover, however the cost is quite high ($199.00 per user), and if budgets are restricted then a single version would be sufficient for the CI server.

Summary

I have not gone in to great detail about how to perform code coverage, as there is ample information on the internet, what I have tried to do is provide a simple justification to why code coverage is an integral part of the development process.

My recommendation would be NCover, mainly because it appear to be the only fully supported Code Coverage tool for .NET

Another Code Coverage tool, which is built in to Visual Studio Team edition, I have not covered here, as it was not available for me at the time of writing.  Thanks Nathan Gloyn for point this out.

 

Generating Sequence Diagrams

From time to time I need to generate Sequence Diagrams, as this are required to graphically represent processes, as a consultant each customer has a different sent of tools you can and can not use.  So it becomes hard to generate what should be something you don’t have to think about.

I found a great on-line tool Web Sequence Diagrams, it so simple and it also has a very easy to use API.

Just to show you how easy here is what I generated in what must have been 5 minutes

It can also be support in plain HTML, as you can see in the attached file

Commit Sequence.htm (457.00 bytes)

 

Validating XML against an XSD Schema

When handling XML files you are going to need to validate the XML, and the best way, currently, is to use an XSD Schema.  It took me a little while to work out how to do this, and with help from Assaf Lavie I finally came up with a method to validate two streams, one holding the XML the other the XSD.

[code language=C#]

public void Validate(Stream xml, Stream xsd)
        {
            if (xml == null)
            {
                throw new ArgumentNullException(“xml”);
            }

            if (xsd == null)
            {
                throw new ArgumentNullException(“xsd”);
            }

            xml.Seek(0, SeekOrigin.Begin);
            var readerXML = new StreamReader(xml);
            string textXML = readerXML.ReadToEnd();

            if (string.IsNullOrEmpty(textXML))
            {
                throw new ArgumentNullException(“xml need to hold some information”);
            }

            xsd.Seek(0, SeekOrigin.Begin);
            var readerXSD = new StreamReader(xsd);
            string textXSD = readerXSD.ReadToEnd();

            if (string.IsNullOrEmpty(textXSD))
            {
                throw new ArgumentNullException(“xsd need to hold some information”);
            }

            try
            {
                // 1- Set the streams to the beginning
                xml.Seek(0, SeekOrigin.Begin);
                xsd.Seek(0, SeekOrigin.Begin);

                var errorMessages = new List<string>();

                // 2- Read XML file content 
                var xmlReader = new XmlTextReader(xml);

                // 3- Read Schema file content 
                StreamReader schemaReader = new StreamReader(xsd);

                // 4- Set Schema object by calling XmlSchema.Read() method 
                XmlSchema Schema = XmlSchema.Read(schemaReader, (o, e) =>
                    {
                        errorMessages.Add(e.Message);
                    });

                // 5- Create a new instance of XmlReaderSettings object 
                XmlReaderSettings readerSettings = new XmlReaderSettings();

                // 6- Set ValidationType for XmlReaderSettings object 
                readerSettings.ValidationType = ValidationType.Schema;

                // 7- Add Schema to XmlReaderSettings Schemas collection 
                readerSettings.Schemas.Add(Schema);

                // 8- Add your ValidationEventHandler address to 
                // XmlReaderSettings ValidationEventHandler 
                readerSettings.ValidationEventHandler += (o, e) =>
                    {
                        errorMessages.Add(e.Message);
                    };

                // 9- Create a new instance of XmlReader object 
                XmlReader objXmlReader = XmlReader.Create(xmlReader, readerSettings);

                // 10- Read XML content in a loop 
                while (objXmlReader.Read())
                { /*Empty loop*/}

                // 11- Raise exception, if XML validation fails
                if (errorMessages.Count() > 0)
                {
                    throw new Exception(string.Join(“\r\n”, errorMessages.ToArray()));
                }
            }
            catch (XmlException XmlExp)
            {
                throw new XMLValidationException(XmlExp.Message, XmlExp);
            }
            catch (XmlSchemaException XmlSchExp)
            {
                throw new XMLValidationException(XmlSchExp.Message, XmlSchExp);
            }
            catch (Exception GenExp)
            {
                throw;
            }

            finally
            {
                xml.Seek(0, SeekOrigin.Begin);
                xsd.Seek(0, SeekOrigin.Begin);
            }
        }

[/code]

String to a Stream

The time has come where I needed to handle streams, so the first I needed to generate some tests and within these tests I need to generate a stream based on some text.  So the first task was to convert a String in to a Stream, and while I am at it how about the other direction to (Stream to a String)

String in to a Stream

[code language=C#]

string text = “To Jani, Reminder Don’t forget me this weekend!'”;
byte[] byteArray = Encoding.ASCII.GetBytes(text);
MemoryStream streamXML = new MemoryStream(byteArray);

[/code]

Stream to a String

[code language=C#]

xml.Seek(0, SeekOrigin.Begin);
var readerXML = new StreamReader(xml);
string textXML = readerXML.ReadToEnd();

[/code]

 

Rapid Generation of test objects

I came across a very easy to use and useful generation tool for objects today, NBuilder.

Through a fluent, extensible interface, NBuilder allows you to rapidly create test data, automatically assigning values to properties and public fields that are of type of the built in .NET data types (e.g. ints and strings). NBuilder allows you to override for properties you are interested in using lambda expressions.

If you understand Lambda then you’re going to be able to build test data for your objects.

All you need to do is reference FizzWare.NBuilder.dll in to your test project and you are off.

FizzWare.NBuilder-2.1.9-beta.zip (32.47 kb)