Category: Articles

  • Real World: Unit Testing Queries Against Entity Framework (EF) Model / Repositories

    Real World: Unit Testing Queries Against Entity Framework (EF) Model / Repositories

    Unit testing is a tricky beast. As with all unit tests it is important to abstract any dependencies – so in the case of EF it’s the data persistence source. This must be handled carefully because EF creates a container that performs the interaction with the data source. Abstracting that container (via mocking or stubbing) is painfully hard.

    There are a few approaches for doing this, this is mine. I’m using the following tooling:

    The pattern uses the following DAL class structure (like a pseudo-repository pattern against an example Product database table):

    • ProductDataRepository: IProductDataRepository – A thin layer to EF, returns only IQueryable<T> types from raw EF lookups. No filters, sorting or other queries are applied here as this class is not unit testable. This class internal to the DAL assembly.
    • ProductRepository(IProductDataRepository repos) – Constructor takes an instance of the IProductDataRepository interface, and uses this for executing specific queries against the base IQueryable<T> values. This class is exposed for external calls. This is unit-tested.

    The unit tests can use Moles to stub an instance of IProductDataRepository (delegating the internal Get… methods to returning a hard coded collection of test data) that is then passed to the instance of ProductRepository under test.

    Looking at these classes from the bottom up, as an example:

    ProductDataRepository

    To Provide a thin layer that only returns IQueryable<T> (our example also filters out deleted rows):

    public class ProductDataRepository : IProductDataRepository {
    
    private MyDatabase_ModelContainer _model;
    protected internal MyDatabase_ModelContainer Model {
    get {
    if (_model == null) {
    _model = new MyDatabase_ModelContainer();
    }
    return _model;
    }
    }
    
    public IQueryable<product> GetProducts() {
    return Model.Products.Where(p => p.IsTombstoned == false);
    }
    }
    

    ProductRepository

    Core Requirement: Provide the implementation and execution of the data lookup. Consumes an instance of IProductDataRepository via constructor injection.

    public class ProductRepository{
    public ProductRepository() : this(new ProductDataRepository()) {
    }
    
    private IProductDataRepository _mRepository;
    public ProductRepository (IProductDataRepository iRepository) {
    _mRepository = iRepository;
    }
    
    public Product GetProduct(String productKey) {
    return mRepository.GetProducts().FirstOrDefault(p => p.ProductKey.Contains(productKey));
    }
    
    public List<Product> GetProducts (String productKey) {
    return mRepository.GetProducts().Where(p => p.ProductKey.Contains(productKey).ToList();
    }
    }
    

    So, we can see that this is making calls to:

    mRepository.GetProducts()

    Which returns an IQueryable<T> type, then implements required functionality:

    .Where(p => p.ProductKey.Contains(productKey))

    and then executes the Query:

    .ToList();

    GetProductsTest

    To test the ProductRepository we can create an instance and stub the IProductDataRepository. The mocking and standard setup is done in an abstract class, to provide reusability for other tests that may require this functionality:

        [TestClass]
    public abstract class ProductTestContext
    {
    private IProductDataRepository _dataRepository;
    private IProductDataRepository DataRepository
    {
    get {
    if (_dataRepository == null) {
    _dataRepository = new SIProductDataRepository() {
    GetProducts = () => Products.AsQueryable()
    };
    }
    return _dataRepository;
    }
    }
    
    private ProductRepository _ProductRepository;
    public ProductRepository ProductRepository
    {
    get {
    if (_ProductRepository == null) {
    _ProductRepository = new ProductRepository(DataRepository);
    }
    return _ProductRepository;
    }
    }
    
    private List<Product> _products;
    public List<Product> Products
    {
    get {
    if (_products == null) {
    _products = new List<Product>();
    
    for (int i = 1; i <= 9; i++) {
    _products.Add(new Product(){ ProductKey = "MyKey" + i });
    }
    }
    return _products;
    }
    }
    
    }
    

    So, here we can see the IProductDataRepository readonly property returns a stubbed instance new new SIProductDataRepository. This stub is generated by the Moles framework (see Moles documentation on how to do this). During the creation of this object we delegate the GetVouchers method to return the concrete (and hardcoded because this is a unit test) instance of Products.AsQueryable():

    GetProducts = () => Products.AsQueryable()

    The .AsQueryable() is essential to insure the instance of IProductDataRepository, that is used during the test, returns the same type as the instance used in the real world.

    Now our unit test class can inherit ProductTestContext and Arrange, Act and Assert the required tests easily:

        [TestClass]
    public class GetProductsTest : ProductTestContext
    {
    
    [TestMethod]
    public void GetSingleProduct()
    {
    // repeat the test for each instance in the test collection
    for (int i = 1; i <= 9; i++) {
    // Arrange – most of the Arrangement is done in the abstract
    var goodProductKey = "MyKey" + i;
    
    // Act – on the abstract instance of ProductRepository,
    //            which is using the stubbed instance of ProductDataRepository
    var product = ProductRepository.GetProduct(goodProductKey);
    
    // Assert – make sure the correct product is returned from the stubbed data
    Assert.IsNotNull(product);
    Assert.IsTrue(product.ProductKey.Equals(goodProductKey));
    }
    }
    
    [TestMethod]
    public void GetIndivudalFilteredProducts()
    {
    // repeat the test for each instance in the test collection
    for (int i = 1; i <= 9; i++) {
    // Arrange – most of the Arrangement is done in the abstract
    var goodProductKey = "MyKey" + i;
    
    // Act – on the abstract instance of ProductRepository,
    //            which is using the stubbed instance of ProductDataRepository
    var products = ProductRepository.GetProducts(goodProductKey);
    
    // Assert – make sure the correct products are returned from the stubbed data
    Assert.IsNotNull(products);
    Assert.IsTrue(products.Count == 1);
    }
    }
    
    [TestMethod]
    public void GetMultipleFilteredProducts()
    {
    // Expectation – all the results in the abstract Products collection should be returned
    var expectation = Products.Count;
    
    // Arrange – most of the Arrangement is done in the abstract
    var goodProductKey = "MyKey";
    
    // Act – on the abstract instance of ProductRepository,
    //            which is using the stubbed instance of ProductDataRepository
    var products = ProductRepository.GetProducts(goodProductKey);
    
    // Assert – make sure the correct products are returned from the stubbed data
    Assert.IsNotNull(products);
    Assert.AreEqual(expectation, products.Count);
    }
    }
    
  • Microsoft Mocking

    Microsoft Mocking

    As a .NET developer I don’t like using third party controls when there is tooling available from MS that will do the job I need. For example I prefer using the “baked in” MSTest suit as opposed to NUnit or MBUnit.

    The same is true for a mocking framework. I have tried with varying levels of success to implement licenced and open-source variants, for example;

    • JustMock
    • TypeMocks
    • Moq
    • Rhino

    Then I found Microsoft Moles (part of the Pex toolkit) from MS Research labs. These tools are not officially released not supported, but they have matured for a couple of years, and whilst not as fully featured as something like JustMock, it has enough functionality to do what I need – simple mocking and stubbing and delegation of methods and properties.

    With Moles I managed stub my data access repository (with a little refactoring) with very satisfactory results:Real World: Unit Testing Queries Against Entity Framework (EF) Model / Repositories

  • SoapUI Pro – Browser Component is Disabled (Win7 64)

    SoapUI Pro – Browser Component is Disabled (Win7 64)

    Recording web tests on Soap UI Pro won’t work in full-blown 64 Bit environments (64bit windows, SoapUI and JRE). This is due to incompatibility with the Mozilla browser engine. Updates are expected soon. This will except with the following message: “Browser Component is Disabled”

    In the mean time install the 32bit version from http://dl.eviware.com/4_0/soapUI-Pro-x32-4_0_0.exe

    For more information see: http://www.eviware.com/forum/viewtopic.php?f=2&t=7797&p=22648&hilit=disabled+browser#p22648

  • WCF Configuration

    WCF Configuration

    During the deployment of a WCF service to an HTTPS QA server recently had us stumped… The service didn’t respond, didn’t display any error messages and didn’t log any issues in the Windows Event Log.

    The issues turned out to be (as expected) a type in the configuration file, we had used;

    system.serviceModel/services/service/endpoint/behaviorName

    and this should have been;

    system.serviceModel/services/service/endpoint/behaviorConfiguration

    Grrr!!!

  • SSMS Trusted

    SSMS Trusted

    It is possible to run SQL Server Management Studio under the guise of another user account from the command line:

    runas /netonly /user:domain\user c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\ssms.exe

    The command line will request a password which (quite rightly!) cannot be entered into the command. Successful authentication will launch an instance of SSMS 2008. Lovely.

  • Paperless Home

    Paperless Home

    Many, many years ago I had a flatbed scanner and that scanner had a gnatty ‘scan-to-email’ function that would email any scans as a PDF attachment.

    Many years later (but still many years ago) I signed up for the Google Documents online service and registered for their Email to Documents service. This was a hashed email address that would save attachments into the Google Docs cloud (and convert them if you wish).

    This combination of scan to email to cloud has had me literally salivating for years – it puts the paperless office within everyone grasp. So, finally after much procrastination I have finally got my act together, brought a duplex scanner (HP Officejet Pro 8500A Plus e-All-in-One Web Enabled Printer ), with a wireless internet connection ready to put my master plan in to action…

    After unboxing, what should I find?? A flipping Google Docs Storage Application! Yep, the scanner comes with a prebuilt in application that does exactly what I wanted… So, have I now got a paperless office? Well no, because the scanner also has a lovely printer function too, and to not use that would be a waste

  • .NET Assembly Versioning

    .NET Assembly Versioning

    A colleague recently asked me the difference between the different version properties available in a .NET assembly. I had read about this recently in Jeff Richters outstanding CLR via C# but couldn’t remember the semantics off the top of my head.

    • AssemblyFileVersion: The version number you want the public to see. Ideally you’d want the build tool (e.g. CSC.exe or AL.exe) to automatically update the build and revision number number, but this doesn’t happen. This version number can be seen when using Windows Explorer and is typically used to identify a specific assembly version when trouble shooting.
    • AssemblyInformationalVersion: This version number is stored in the Win32 version resource and is for informational purposes. This number exists to indicate which version of the product includes this assembly.
    • AssemblyVersion: This value is stored in the AssemblyDef manifest metadata table. THe CLR uses this version number when binding to strongly named assemblies. This number is used to uniquely identify an assembly, and is used to tightly bind the assembly as a reference within a product.
  • Silverlight Deferred / Delayed Selected Date Picker

    Silverlight Deferred / Delayed Selected Date Picker

    When implementing a date picker that is used to fetch some ‘details’ based on the selected date, the chances are that you don’t want to begin fetching the ‘details’ immediately.

    If you did, and made a rapid change to the SelectedDate (maybe holding down an arrow key), the asynchronous fetch will be repeated a large number of times.

    To prevent this, implement a deferral on the selected date change, for example:

    public class DeferredDP : DatePicker {
    
    public DeferredDP() {
    this.DefaultStyleKey = typeof(DatePicker);
    base.SelectedDateChanged += new EventHandler(DeferredDP_SelectedDateChanged);
    }
    
    DispatcherTimer _timer;
    
    void DeferredDP_SelectedDateChanged(object sender, SelectionChangedEventArgs e) {
    /// if there is an instance of the timer already running stop it.
    if (_timer != null) {
    _timer.Stop();
    _timer = null;
    }
    
    /// only trigger the selection changed event when the date has been changed
    if (e.AddedItems.Count == 1 &&
    e.AddedItems[0] is DateTime) {
    
    if (SelectionDelay.HasValue) {
    /// if the timer delay has been set, delay the setting of the value
    _timer = new DispatcherTimer();
    _timer.Interval = new TimeSpan(0,0,0,0,SelectionDelay.Value);
    _timer.Tick += (s1, e1) => {
    SetValue(SelectedDateDeferredProperty, (DateTime)e.AddedItems[0]);
    if (_timer != null) {
    _timer.Stop();
    _timer = null;
    }
    };
    _timer.Start();
    } else { // if the timer delay is not set, set the property immediately.
    SetValue(SelectedDateDeferredProperty, (DateTime)e.AddedItems[0]);
    }
    }
    }
    
    ///
    /// Milliseconds delay before the selected date value is updated.
    ///
    public int? SelectionDelay {
    get { return (int?)GetValue(SelectionDelayProperty); }
    set { SetValue(SelectionDelayProperty, value); }
    }
    
    public static readonly DependencyProperty SelectionDelayProperty =
    DependencyProperty.Register("SelectionDelay", typeof(int?), typeof(DeferredDP), new PropertyMetadata(null));
    
    public DateTime? SelectedDateDeferred {
    get { return (DateTime?)GetValue(SelectedDateDeferredProperty); }
    set { SetValue(SelectedDateDeferredProperty, value); }
    }
    
    public static readonly DependencyProperty SelectedDateDeferredProperty =
    DependencyProperty.Register("SelectedDateDeferred", typeof(DateTime?), typeof(DeferredDP), new PropertyMetadata(null, SelectedDateDeferredChanged));
    public static void SelectedDateDeferredChanged(DependencyObject d, DependencyPropertyChangedEventArgs args) {
    DeferredDP instance = d as DeferredDP;
    
    if (instance.SelectedDateDeferred != instance.SelectedDateDeferred) {
    instance.SelectedDateDeferred = instance.SelectedDateDeferred;
    }
    
    }
    }
    
  • MSDTC

    MSDTC

    We had some really strange problems getting MSDTC to work recently, specifically upgrading to VS2010 and SL4. Our developer environments are pointing to networked database servers and during this particular use-case the development workstation is running a both the hosted Silverlight Client and the Business Logic (API) served through a WCF service (both in Cassini). The API is performing the transactional logic.

    So, working through the bugs and error messages that we got;

    The first error requires MSDTC to be started (which is wasn’t by default):

    The transaction manager has disabled its support for remote/network transactions. Both the WCF Server (in our case the developer workstation) and the Database Server have to have MSDTC running. Start MSDTC using the command line: NET START MSDTC

    YMMV, but on Win7 the default properties for DTC also had to be updated. From Component Services MMC, navigate to Computers | My Computer | Distributed Transaction Coordinator | Local DTC. Right click + Properties and set as follows:

    clip_image002

    Next error then relates to the default firewall setting:

    The MSDTC transaction manager was unable to pull the transaction from the source transaction manager due to communication problems. Possible causes are: a firewall is present and it doesn’t have an exception for the MSDTC process, the two machines cannot find each other by their NetBIOS names, or the support for network transactions is not enabled for one of the two transaction managers. Sometimes we didn’t get this exception, and got a timeout instead and the failed transaction could be seen in the outstanding transactions list.

    To resolve this we updated the Windows Firewall to add an inbound and outbound tunnel for %SystemRoot%\System32\msdtc.exe

    All seems to OK … for now… :S

  • Silverlight Tab Stops – IsTabStop

    Just found a tricky little quirk with TabStop that caused a fair bit of confusion. It turns out that the default implementation of ContentControl overrides Control, so implements the IsTabStop property, and defaults that value to true.

    ContentControl is implemented by the delightful BusyIndicator, so if you have used a BusyIndicator within the scope of a series of input controls you’ll see the Invisible Tab Stop behaviour.

    HINT: Using Silverlight Spy shows us where the offending property lies. You’ll need to re-template that to set the IsTabStop property to false.