Tuesday, April 30, 2013

Understanding SQL Server statistics

I'm trying to tune a database using the excellent SQL Server Tuning advisor - which I will blog about later. However, one of its recommendations was to create statistics. Honestly, I didn't know what they were, but this post helped me out.

Turned out that SQL Server is on 'create statistics automatically', so it wasn't relevant for the performance, but it's interesting stuff.





Monday, April 29, 2013

Use Web Deploy. Period.

We had a tech session the other day about DTAP. Our office TFS server was updated to TFS 2012 and we want to install Lab Management and all those fancy gadgets in the near future. We we're talking about how others within our company deploy their stuff. Turns out almost everyone has his or her own way with some script here or there.

Right now we're using TFS only as a build server and 'package server' if you will, whereas I'm used to using TeamCity to both monitor the build and for deployments. The big difference between my old work and current, is that in the old job, we owned the DTAP servers and were able to deploy to those.
At the new job, we have to provide some 3rd party with an installation package and an instruction manual how to install.

More on that some other time - but what I found astonisghing is that a lot of people within my company didn't know about web-deploy. It reminded me of Scott Hanselman's blog back in 2010 (!) titled: "Web Deployment Made Awesome: If You're Using XCopy, You're Doing It Wrong". Even in the scripts we provide, we use web deploy. So seriously: start using web deploy.




Thursday, April 25, 2013

Quickly test your assemblies using MS Fakes

On hackernews I saw this article coming by about a feature that I didn't know about in VS 2012: adding fake assemblies. I can't go into it too deep - but it's super simple and very powerful. However - I also heard it's quite 'expensive' in terms of processing power which makes your tests a bit slow and that's annoying. So don't start faking everything right away.

On this topic - be sure to listen to the .NET Rocks! Podcast on testing with special guest Hendrik Lösch. AND there is an eBook about this feature available for download. Here are the links:

http://mikefourie.wordpress.com/2013/03/05/creating-the-better-unit-testing-with-microsoft-fakes-ebook/ 



A nice 101 on this feature: http://www.codeproject.com/Articles/582812/Unit-testing-with-Fakes-with-Visual-studio-Premium



And a very interesting podcast on testing on the .NET Rocks! podcast : http://www.dotnetrocks.com/default.aspx?showNum=865


Wednesday, April 24, 2013

Unit testing the EF DataContext using Moq and FakeDbSet

I came across a very sweet way of testing EF DataContexts: http://www.nogginbox.co.uk/blog/mocking-entity-framework-data-context . This guy figured it out.

What he does is:
- Change all DbSet<...> in your EF DataContext to IDbSet<...>
- Extract an interface
- Get NuGet package Moq : https://www.nuget.org/packages/moq
- Get NuGet package FakeDbSet : http://nuget.org/packages/FakeDbSet/

Setup a test datacontext with some data like so:

// Create mock unit of work
var mockDataContext = new Mock<IDataContext>();
var mockItemList= new InMemoryDbSet<item>(clearDownExistingData: true)
{
new item(FakeDepartureDate1, "drp1", "drp3", 1), 
new item(FakeDepartureDate1, "drp1", "drp3", 2), 
new item(FakeDepartureDate1, "drp1", "drp3", 2), 
new item(FakeDepartureDate2, "drp2", "drp3", 4), 
new item(FakeDepartureDate2, "drp2", "drp4", 5), 
new item(FakeDepartureDate2, "drp2", "drp4", 5)
};
mockDataContext.Setup(m => m.itemList).Returns(mockItemList);

And presto - you can start testing against your fake data. I used it to prove my query worked correctly.

EntityFramework testing will be done like so from now on by me!

But - don't take my word for it - check out the guy who figured it out before me:


Difference between NO LOCK and READPAST in SQL Server

I learned the difference today between NO LOCK and READPAST thanks to Tim Chapman. I suspect we have an SSIS package that locks the table for a significant amount of time - and I think we're going to solve the problem using READPAST. Check out Tim's post to read up on the difference between NO LOCK and READPAST.

Tuesday, April 23, 2013

Cool tool: XPathVisualizer - get instant visual feedback on your XPath query

I'm setting up an auto-deployment script for one of our applications. One step is to update certain web.config values ( you guessed it: connection strings ) for the different environments of our DTAP.

The tool we're using uses XPath selectors to find the nodes and attributes which will be updated. My XPath is a little rusty, but this tool made it a breeze: XpathVisualizer.

Get it here: http://xpathvisualizer.codeplex.com/


Friday, April 19, 2013

Using Unity+Interceptors with WCF services to transform exceptions to soap faults

This week I've been working on a WCF webservice and I wanted to get dependency injection going and leverage interception in order to nicely handle logging, exceptions and some performance measurement.

Although I prefer Ninject, I had to go with Unity for the IoC container. Now - the sweet thing is this NuGet package Unity.Wcf.

It's super easy to set up. What will happen is that your services will be served from a factory, that you populate by setting up the container. Check out this website to get going with this awesome package: http://unitywcf.codeplex.com/ and get it from NuGet.



So once you got that going, you can add interceptors to it to get some pre- and post method call behavior.

What I wanted to do is convert exceptions to SaupFaults. Piece of cake some custom behavior. So here's the factory that is generated by installing the unity.wcf factory - with the registration of the service + the behaviors:

  protected override void ConfigureContainer(IUnityContainer container)
        {
            // Enable Interception
            container.AddNewExtension<Interception>();

            // Register the wagenlijstservice
            container.RegisterType<ISomeService, MyService>(
                new Interceptor(new InterfaceInterceptor()),
                new InterceptionBehavior<TransformExceptionToFaultExceptionBehavior>(),
                new InterceptionBehavior<ExceptionLoggingBehavior>(),
                new InterceptionBehavior<PerformanceMeasureBehavior>(),
                new InterceptionBehavior<LogBehavior>());
             ...
    }

And this is the behavior itself:

   public override IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var methodReturn = getNext()(input, getNext);
            if (methodReturn.Exception != null)
            {
                var fault = new SomeCustomFaultImplementation()
                                {
                                    Code = methodReturn.Exception.GetType().Name,
                                    Message = methodReturn.Exception.Message
                                };
                throw new FaultException<SomeCustomFaultImplementation>(fault, fault.Message);
            }
            return methodReturn;
        }

The WSDL I'm working with has a custom fault implementation so I had to respect that. The point is though, that if I find an exception in the methodReturn.Exception - I throw a FaultException immediately with input from the exception.

I'm quite happy with the solution. Another way of doing this is adding a new errorbehavior to the WCF service using attributes - as described here: http://www.codeproject.com/Articles/26320/WCF-Error-Handling-and-Fault-Conversion . However - since I had the whole thing set up with interceptors already, I'm going with this one.

Wednesday, April 17, 2013

Unity IoC with interception

I'm used to working with Ninject for dependency injection, but for work I have to dig into Unity and use it for a WCF service. I want NLog logging using interceptors, so I had to wire that stuff up a bit.

Here's a quick proof-of-concept of getting Unity to intercept method calls.


namespace UnityConsole
{
    using System;
    using System.Collections.Generic;

    using Microsoft.Practices.Unity;
    using Microsoft.Practices.Unity.InterceptionExtension;

    internal class Program
    {
        private static void Main(string[] args)
        {
            // Instantiate the Unity Container
            IUnityContainer container = new UnityContainer();

            // Enable Interception
            container.AddNewExtension<Interception>();
            
            // Register the service and the interceptor
            container.RegisterType<IService, MyService>(
                new Interceptor(new InterfaceInterceptor()), new InterceptionBehavior(typeof(MyBehavior)));
            
            // Get the service from the container
            var myService = container.Resolve<IService>();

            // Invoke the method
            myService.SayHi();

            // Prevent screen from closing
            Console.ReadLine();
        }
    }

    public class MyBehavior : IInterceptionBehavior
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            // PRE execution logging
            System.Diagnostics.Debug.WriteLine("Executing method named: " + input.MethodBase.Name);

            // Continue method call
            var result = getNext()(input, getNext);

            // POST execution logging
            System.Diagnostics.Debug.WriteLine("Method execution done - resulted in value: " + result.ReturnValue);

            return result;
        }

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            // Empty - so no restrictions here 
            return new Type[] { };
        }

        public bool WillExecute
        {
            get
            {
                return true;
            }
        }
    }

    public class MyService : IService
    {
        public string SayHi()
        {
            return "Hi there buddy";
        }
    }

    public interface IService
    {
        string SayHi();
    }
}

Friday, April 5, 2013

Record your own coding demos with CodeMirror movies

I noticed that Zen Coding has changed name and is now called 'Emmet' and offers some extra functionality.
I was curious to see how they make the coding demo video you see if you hit 'Watch Demo'.



Apparently, it's a plugin for CodeMirror that allows you write video scripts. Check the project on GitHub:

Thursday, April 4, 2013

CodeMirror: online code editor

I came across this sleek and well working online code editor called CodeMirror. I'm sometimes hacking pieces of JavaScript into our CMS system, using CKEditor. However, CodeMirror looks really nice and the way to go for me from now on. Check it out on http://codemirror.net/ . Check out the JavaScript sandbox here.



Visual Studio 2012.2 update is out there

I'm a couple of days late, but the VS2012 update 2 is available for download. Get is here.

   

 From what I get from the video, the mainly focussed on the Agile planning UI for TFS, quality enablement, windows store development, line-of-business development and the development experience. Check out S. Somasegar's blog on VS 2012.2 for more detailed info.