Basic DataAnnotations Validation Example

In this example, I am using System.ComponentModel.DataAnnotations to validate my object.

I wrap two attributes around the property, one that requires a string, and one that marks the property as invalid if the String is greater than 20 chars.

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

Validating System.ComponentModel objects

We can validate the object using TryValidate on the System.ComponentModel.Validator class.

For now, we can just pass the Validator a new empty ValidationContext which is this code:

Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);

Full test class below:

namespace ExampleLibrary.Tests
{

    public class SimpleCustomer
    {
        [Required]
        [StringLength(20)]
        public string Name { get; set; }
    }

    [TestClass]
    public class DirtyTests
    {
                
        [TestMethod]
        public void Customer_Name_InvalidWhenOverTwentyChars()
        {
            // assemble
            SimpleCustomer d1 = new SimpleCustomer() { Name = "01234567890123456789" };
            bool validWithTwentyChars, validOverTwentyChars;

            // act
            validWithTwentyChars = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);
            d1.Name = "012345678901234567890";
            validOverTwentyChars = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);

            // assert
            Assert.IsTrue(validWithTwentyChars);
            Assert.IsFalse(validOverTwentyChars);
        }

        [TestMethod]
        public void Customer_Name_InvalidWhenEmpty()
        {
            // assemblt
            SimpleCustomer d1 = new SimpleCustomer();
            bool validNull, validEmptyString, validFilledString;

            // act
            d1.Name = null;
            validNull = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);
            d1.Name = string.Empty;
            validEmptyString = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);
            d1.Name = "Some value";
            validFilledString = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);

            // assert
            Assert.IsFalse(validNull);
            Assert.IsFalse(validEmptyString);
            Assert.IsTrue(validFilledString);
        }
    }
}

Dependency Injection with NInject

Here’s a demo I wrote to show how basic NInject code works.

I setup an abstraction of the IExample interface as the class Example. I’ll use this later to get my HelloWorld text.

I then use it in a Print object (which implements IPrint) and then call the HelloWorld function on the IExample object, whatever that is. Because I’ve already bound any requests for IExample to Example, I will get an Example object.

I initialise the NInject kernel here:

IKernel ninjectKernel = new StandardKernel();

I then add the NInject binding (mapping) here:

ninjectKernel.Bind<IExample>().To<Example>();

If I didn’t setup any binding, I’d get the following NInject.ActivationException:

Error activating IExample
No matching bindings are available, and the type is not self-bindable.
Activation path:
  1) Request for IExample

I’ve posted a full Console Application example below:

using Ninject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace ConsoleApplication1
{
    // Example interface
    public interface IExample
    {
        string HelloWorld { get; }
    }

    // Example implementation
    public class Example : IExample
    {
        public string HelloWorld
        {
            get
            {
                return "Hello world";
            }
        }
    }

    // print interface for abstraction
    public interface IPrint
    {
        string PrintFunction();
    }

    // print implementation
    public class Print : IPrint {

        private IExample _example;

        public Print(IExample exampleParam) {
            _example = exampleParam;
        }

        public string PrintFunction() {
            return _example.HelloWorld;
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            // declare the kernel for ninject
            IKernel ninjectKernel = new StandardKernel();

            // setup the example binding
            ninjectKernel.Bind<IExample>().To<Example>();

            // get an implementation (loosely coupled)
            IExample exampleInstance = ninjectKernel.Get<IExample>();

            // return the value and print to the console
            IPrint example = new Print(exampleInstance);
            Console.WriteLine("result: " + example.PrintFunction());
            Console.ReadLine();

        }
    }
}

Using C# Yield

I just found something cool I haven’t been using in Linq so I thought I would share here.

When enumerating through a collection of IEnumerable<Object>, you can use the yeild statement to quickly filter items.

For example if I had a set of ShoppingCartItems held in an IEnumerable<ShoppingCartItem>, and ShoppingCartItem has a Category, I could filter with an extension method like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ShoppingCartExample
{
    public interface IShoppingCartItem
    {
        string Description { get; set; }
        double Cost { get; set; }
        string Category { get; set; }
    }

    public class ShoppingCartItem : IShoppingCartItem
    {
        public string Description { get; set; }
        public double Cost { get; set; }
        public string Category { get; set; }
    }

    public static class Extensions
    {

public static IEnumerable<IShoppingCartItem> Filter(this IEnumerable<IShoppingCartItem> instance, string Category)
        {
            foreach (IShoppingCartItem item in instance)
            {
                if (item.Category == Category)
                {
                    yield return item;
                }
            }
        }

    }

}

So to use this, we ensure we’ve got the Extensions class in scope / included then call Filter on it like this:

// declare a cart
List cart = new List();

// add items
cart.Add(new ShoppingCartItem() { Category = "Toys", Cost = 1.23D, Description = "Monopoly" });
cart.Add(new ShoppingCartItem() { Category = "Fruit", Cost = 0.50D, Description = "Apple" });

// filter the items
IEnumerable results = cart.Filter("Fruit");

int count = results.Count; // will return 1

Related Content

Unable to serialize the session state

Unable to serialize the session state. In ‘StateServer’ and ‘SQLServer’ mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in ‘Custom’ mode.

Answer:

Make everything serialisable!

Simply declare the objects / types <Serialisable()> or [Serialisable()] if you’re C#

.NET Transactional Test Base

TransactionalTestBase

A Visual Basic .NET (VB.NET) Unit Test base class which automatically rolls back any ADO.NET or LINQ transactions.

Uses ServicedComponent with System.Transactions and provides event hooks for ease of use.

You can find all of this on my GitHub page – Transactional Test Base on GitHub

Minimum-Code Example

This example is the least amount of code required to setup a working Unit Test. There are more examples further down this README.

Imports Microsoft.VisualStudio.TestTools.UnitTesting

<TestClass()> _
Public Class Example_Tests
Inherits TransactionalTestBase

' Example barebones UnitTest with automatic transactioning and roll-back
' Author: Alexander Williamson
' Website: http://www.alexw.co.uk

#Region "Unit Tests"

<TestMethod()> _
Public Sub ExampleUnitTest
Assert.IsTrue(True) ' This test will pass
End Sub

#End Region

End Class

Usage

Create a new Unit Test class. Include any (required) Microsoft Unit Testing references:

Imports Microsoft.VisualStudio.TestTools.UnitTesting
Add the TransactionalTestBase file wherever your test are. Subclass child tests off this class.

<TestClass()> _
Public Class ExampleUnitTest
Inherits TransactionalTestBase

End Class

Each Sub that is decorated with the TestMethod() Attribute will automatically be wrapped in a transaction and rolled back when finished (or when an exception is encountered).

<TestMethod()> _
Public Sub ExampleUnitTest()
Assert.Pass("Hello world!")
End Sub

Hooks

Set-up Sequence

  1. Init Unit Test
  2. PreTransactionBegin
  3. (Transactions are created)
  4. PostTransactionBegin (we are now in transactions)
  5. Unit Test Runs
  6. (Unit Test passes or fails)
  7. PreRollback
  8. (Transactions are rolled back)
  9. PostRollback (we’re out of the transaction, everything has been rolled back)

Tear-down Sequence
Unit Test Ends -> PreRollback -> (Transactions rolled back) -> PostRollback -> End

Overridable functions

You can optionally override the following functions in your Unit tests.

PreTransactionBegin
Called before the transaction is created.

Public Overridable Sub PreTransactionBegin()

PostTransactionBegin
Called after the transaction is created, just before the Unit test is executed.

Public Overridable Sub PostTransactionBegin()

PreRollback
Called after the unit test has run, failed or caused an exception; before the transaction is rolled back.

Public Overridable Sub PreRollback()

PostRollback
Called after the transaction has been rolled back:

Public Overridable Sub PostRollback()

Recommended Example

Normally only overriding PostTransactionBegin to add Set-Up code is required. All transactions will roll back when each Unit Test finishes.

Imports Microsoft.VisualStudio.TestTools.UnitTesting

<TestClass()> _
Public Class Example_Tests
Inherits TransactionalTestBase

' Example barebones UnitTest with automatic transactioning and roll-back
' Author: Alexander Williamson
' Website: http://www.alexw.co.uk

#Region "Set-Up and Tear-Down"

Public Overrides Sub PostTransactionBegin()
' Called after the TransactionalTestBase transactions are created.
' We are in a transaction at this point.
' This is an optional override
' Put your Set-Up Code in here. This is normally the only section you will need.
End Sub

#End Region

#Region "Unit Tests"

<TestMethod()> _
Public Sub ExampleUnitTest
Assert.IsTrue(True) ' This test will pass
End Sub

#End Region

End Class
Full Unit Test Example
Imports Microsoft.VisualStudio.TestTools.UnitTesting

<TestClass()> _
Public Class Example_Tests
Inherits TransactionalTestBase

' Example UnitTest with automatic transactioning and roll-back
' Author: Alexander Williamson
' Website: http://www.alexw.co.uk

#Region "Set-Up and Tear-Down"

Public Overrides Sub PreTransactionBegin()
' Called before the TransactionalTestBase transactions are created.
' We are not in a transaction at this point.
' This is an optional override.
End Sub

Public Overrides Sub PostTransactionBegin()
' Called after the TransactionalTestBase transactions are created.
' We are in a transaction at this point.
' This is an optional override
' Put your Set-Up Code in here. This is normally the only section you will need.
End Sub

Public Overrides Sub PreRollback()
' Called just before a transactional roll-back.
' Put your Tear-Down code here (although you probably don't need anything in here).
' We are still in a transaction at this point.
' This is an optional override.
End Sub

Public Overrides Sub PostRollback()
' Called after the TransactionalTestBase transactions are created.
' We are not in a transaction at this point.
' This is an optional override.
End Sub

#End Region

#Region "Unit Tests"

<TestMethod()> _
Public Sub ExampleUnitTest
Assert.IsTrue(True) ' This test will pass
End Sub

#End Region

End Class

Generate QR Codes using the Google Chart API

When I’m testing or deploying websites built for mobiles and desktops, it’s often a bit of a challenge to get a URL over to a mobile. This isn’t really a problem the first couple of times; you can copy and paste, use Chrome to Phone or Google Chrome, email it over, etc., however I always like to find ways to speed up repetitive tasks.

To address this, at the bottom of our apps, I generate a link to the page and append it to the following URL. This link will generate a 400 w x 400 h pixel QR code to the chl argument.

https://chart.googleapis.com/chart?cht=qr&chs=400x400&chl=[url here]

Example Generated QR Code

Blow on the pie!

Example script

<p><img src="" alt="Example QR Code" id="generateMe" /></p>
<script type="text/javascript">
var ele = document.getElementById("generateMe");
ele.src = "https://chart.googleapis.com/chart?cht=qr&chs=400x400&chl=" + document.location.href;
</script>

Useful links

Writing Windows Services

I’m currently writing a Synchronisation Service for RedZebra Software. It synchronises information between Call2Field and k3 SysPro.

I was having a bit of trouble getting the MSI installer to register the service, so I thought I’d throw this post together in case it would help me if I forget again!

Microsoft have produced a tutorial for creating an Windows Service app and installer, it’s pretty foolproof, right up to the part where it says you might not need Custom Components (but you do, otherwise the program files get copied but the service isn’t registered), so don’t skip that bit!

Install, Start, Stop and Uninstall Windows Services using SC

SC is a very useful command for total manipulation of Windows Services, especially when you get past it’s quirky arguments.

  • Install a Windows Service with SC
    sc create "Service Name" binPath= "C:\Program Files\Whatever\Service.exe"

    Note: There’s a space between binPath= and the actual path – this catches a lot of people out!

  • Uninstall a Windows Service with SC
    sc delete "Service Name"
  • Start and Stop a Windows Service with SC
    sc start "Service Name"
    sc stop "Service Name"