Software Programming

Kunuk Nykjaer

Archive for the ‘Csharp’ Category

Custom Configuration Section Samples – CSharp

leave a comment »

I think creating custom configuration section for a web.config or app.config file can be cumbersome.

I have created code samples for various custom configuration.
You can use it for inspiration if you need to create a custom configuration section.

Sometimes I think it’s easier to read and run code samples rather than lengthy API documentation.

https://github.com/kunukn/CustomSection-CSharp

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

    <configSections>                    
        <section name="companySection" 
           type="CompanyApplication.Code.CompanySection, CompanyApplication" />
      <!-- type = "full namespace path, assembly name" -->  
    </configSections>
    
    <companySection>
        <companies>
            <company name="Google" code="googl"/>
            <company name="Apple" code="aapl"/>
            <company name="Microsoft" code="msft"/>
        </companies>
    </companySection>
    
</configuration>


I recommend these articles if you want to read some guides about custom sections.

Written by kunuk Nykjaer

October 12, 2014 at 11:23 am

Posted in Csharp

Tagged with

How to write unit tests – mvc, test framework and mock example

leave a comment »

The code examples are also avaiable at

https://github.com/kunukn/UnitTestExample-CSharp


Synopsis
You have been given a task to write tests for a methods in a class.

You are working with a MVC web app framework, a test framework and a mocking framework.
For this example, I will use Asp.net MVC, Visual Studio Unit Testing Framework and Rhino Mocks.

Your task is to write unit tests for the actions in controller class.
Your have to unit test that the action returns the correct outcome for the possible inputs.

This is the controller class you must test.


DataController

using System.Collections.Generic;
using System.Net;
using System.Web.Mvc;
using MyApp.Services;

namespace MyApp.Controllers
{
    public class DataController : Controller
    {
        public ActionResult GetData(string subject)
        {
            if (subject == "foo")
            {
                new ReportService().ReportAbuseUsage(subject);
                return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
            }

            IList<string> data = new DataService().GetData(subject);
                        
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }
}


Analysis

The GetData action can have two possible outcome.

  • When the subject is foo it will invoke a ReportAbuseUsage method and return a http forbidden result
  • When the subject is anything else it fetch data from a service and then return a json result

The unit testing should test those two cases, input with foo and with something else than foo.
Then inspect the result and see if the outcome was as expected.

The action is dependent on two services. DataService and ReportService.
To unit-test the action you are not supposed to test those two services.
If you do then it is no longer a unit test of the action method but an integration test.

What you have is a method, which is not unit testable. You must refactor the action and mock the depended services.
The class has high coupling with the services.
Loose coupling is often preferred for various reasons. One is for better test-ability of your code.

There are various methods for refactoring to make it more testable.
I will show following techniques: constructor injection and property injection.



Refactoring

You start with adding interfaces to your services.


IDataService

using System.Collections.Generic;
namespace MyApp.Interfaces
{
    public interface IDataService
    {
        IList<string> GetData(string subject);
    }
}

IReportService

namespace MyApp.Interfaces
{
    public interface IReportService
    {
        void ReportAbuseUsage(string subject);
    }
}

DataService

using System.Collections.Generic;
using MyApp.Interfaces;

namespace MyApp.Services
{
    public class DataService : IDataService
    {
        public IList<string> GetData(string subject)
        {
            // returns data by subject, simulate get data 
            return new List<string> { "apple", "orange", "banana" };
        }
    }
}

ReportService

using MyApp.Interfaces;

namespace MyApp.Services
{
    public class ReportService : IReportService
    {
        public void ReportAbuseUsage(string subject)
        {
            // simulate report something to a repository
        }
    }
}


Property injection example

The controller class has been refactored to use property injection

using System.Collections.Generic;
using System.Net;
using System.Web.Mvc;
using MyApp.Interfaces;
using MyApp.Services;

namespace MyApp.Controllers
{
    public class DataController : Controller
    {
        private IDataService _dataService;
        public IDataService DataService
        {
            get { return _dataService ?? new DataService(); }
            set { _dataService = _dataService ?? value; }
        }

        private IReportService _reportService;
        public IReportService ReportService
        {
            get { return _reportService ?? new ReportService(); }
            set { _reportService = _reportService ?? value; }
        }
        
        public ActionResult GetData(string subject)
        {            
            if (subject == "foo")
            {
                ReportService.ReportAbuseUsage(subject);
                return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
            }

            IList<string> data = DataService.GetData(subject);

            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }
}

The getters only create a new instance of the service if it has not been set first.
The setters only allow to be set once if the value is not null.
The injection is done by setting the value before using the getters of the properties.


Unit testable state

Now the controller has dependencies on interfaces and not the implementation.
From here you are able to write unit test where you mock the services.

A Unit Test project has been created with reference to the project and system.web.mvc
and the nuget package has been installed: Install-Package RhinoMocks


Unit test implementation

I will use the Arrange Act Assert (AAA) Pattern.

The service methods has been mocked
(the reason I call them mocks and not stub is because I assert against them. Whether they have been called and with what arguments).

For the first unit test, I test that the action returns a json result for every input but foo.
I also verify that the DataService method was invoked and verify the ReportService method was not invoked.

For the second unit test, I test that the action returns http denied for foo input.
I also verify that the DataService method was not invoked and verify the ReportService method was invoked.

This is the unit test implementation using Visual Studio Unit Testing Framework and Rhino Mocks.

Test naming standard used is MethodName_StateUnderTest_ExpectedBehavior

using System.Collections.Generic;
using System.Net;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyApp.Controllers;
using MyApp.Interfaces;
using Rhino.Mocks;

namespace UnitTestMyApp
{
    [TestClass]
    public class DataControllerTest
    {
        // Injected services
        private IDataService dataService;
        private IReportService reportService;

        [TestInitialize]
        public void Setup()
        {
            dataService = MockRepository.GenerateStub<IDataService>();
            reportService = MockRepository.GenerateStub<IReportService>();

            dataService
                .Stub(s => s.GetData(Arg<string>.Is.Anything))
                .Return(new List<string>());
        }

        [TestMethod]
        public void 
        GetData_WhenCalledWithAnythingButFoo_InvokeGetDataAndReturnsJsonResult()
        {
            // Arrange            
            var controller = new DataController
            {
                DataService = dataService,
                ReportService = reportService
            };

            // act
            ActionResult news = controller.GetData(subject: "news");
            ActionResult fooish = controller.GetData(subject: "fooish");

            // Assert            
            Assert.IsNotNull(news as JsonResult);
            Assert.IsNotNull(fooish as JsonResult);
            
            dataService
                .AssertWasCalled(s => s.GetData(Arg<string>.Is.Anything));
            
            reportService
                .AssertWasNotCalled(s => s.ReportAbuseUsage(Arg<string>.Is.Anything));
        }


        [TestMethod]
        public void 
        GetData_WhenCalledWithFoo_InvokeReportAbuseUsageAndReturnsHttpDenied()
        {
            // Arrange            
            var controller = new DataController
            {
                DataService = dataService,
                ReportService = reportService
            };

            var forbidden = new HttpStatusCodeResult(HttpStatusCode.Forbidden);

            // act
            ActionResult foo = controller.GetData(subject: "foo");
            var fooHttpStatusCodeResult = foo as HttpStatusCodeResult;

            // Assert            
            Assert.IsNotNull(fooHttpStatusCodeResult);
            Assert.AreEqual(fooHttpStatusCodeResult.StatusCode, forbidden.StatusCode);
            
            dataService
                .AssertWasNotCalled(s => s.GetData(Arg<string>.Is.Anything));
            
            reportService
                .AssertWasCalled(s => s.ReportAbuseUsage(Arg<string>.Is.Anything));
        }
    }
}


Constructor injection example

The unit test for the constructor injection example is very similar to the property injection.
The DataController class looks similar to the injection example.

The refactoring for the DataController class looks like this.

DataController

using System.Collections.Generic;
using System.Net;
using System.Web.Mvc;
using MyApp.Interfaces;

namespace MyApp.Controllers
{
    public class DataController : Controller
    {
        private readonly IDataService dataService;
        private readonly IReportService reportService;

        public DataConstructorController()
            : this(new DataService(), new ReportService())
        {
        }

        public DataController(IDataService dataService, IReportService reportService)
        {
            this.dataService = dataService;
            this.reportService = reportService;
        }
        
        public ActionResult GetData(string subject)
        {            
            if (subject == "foo")
            {
                reportService.ReportAbuseUsage(subject);
                return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
            }

            IList<string> data = dataService.GetData(subject);
            
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }
}


The refactoring for the DataControllerTest class looks like this.

DataControllerTest

using System.Collections.Generic;
using System.Net;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyApp.Controllers;
using MyApp.Interfaces;
using Rhino.Mocks;

namespace UnitTestMyApp
{
    [TestClass]
    public class DataControllerTest
    {
        // Injected services
        private IDataService dataService;
        private IReportService reportService;

        [TestInitialize]
        public void Setup()
        {
            dataService = MockRepository.GenerateStub<IDataService>();
            reportService = MockRepository.GenerateStub<IReportService>();

            dataService
                .Stub(s => s.GetData(Arg<string>.Is.Anything))
                .Return(new List<string>());
        }

        [TestMethod]
        public void 
        GetData_WhenCalledWithAnythingButFoo_InvokeGetDataAndReturnsJsonResult()
        {
            // Arrange            
            var controller = new DataController(dataService, reportService);
            
            // act
            ActionResult news = controller.GetData(subject: "news");
            ActionResult fooish = controller.GetData(subject: "fooish");

            // Assert            
            Assert.IsNotNull(news as JsonResult);
            Assert.IsNotNull(fooish as JsonResult);

            dataService
                .AssertWasCalled(s => s.GetData(Arg<string>.Is.Anything));

            reportService
                .AssertWasNotCalled(s => s.ReportAbuseUsage(Arg<string>.Is.Anything));
        }


        [TestMethod]
        public void 
        GetData_WhenCalledWithFoo_InvokeReportAbuseUsageAndReturnsHttpDenied()
        {
            // Arrange            
            var controller = new DataController(dataService, reportService);            
            var forbidden = new HttpStatusCodeResult(HttpStatusCode.Forbidden);

            // act
            ActionResult foo = controller.GetData(subject: "foo");
            var fooHttpStatusCodeResult = foo as HttpStatusCodeResult;

            // Assert            
            Assert.IsNotNull(fooHttpStatusCodeResult);
            Assert.AreEqual(fooHttpStatusCodeResult.StatusCode, forbidden.StatusCode);

            dataService
                .AssertWasNotCalled(s => s.GetData(Arg<string>.Is.Anything));

            reportService
                .AssertWasCalled(s => s.ReportAbuseUsage(Arg<string>.Is.Anything));
        }
    }
}


Written by kunuk Nykjaer

September 7, 2014 at 7:31 pm

Monads for C# – tool for cleaner code

with one comment

Tedious codes

You want to extract a phone number from a data source.

 

Do you ever write code like this?


Building building = GetBuildingFromSomeSource();            
string phone = null;
if (building != null && building.Manager != null && building.Manager.ContactInfo != null)
{
    phone = building.Manager.ContactInfo.PhoneNumber;
}

All those null checks can be tedious. And the code doesn’t look ‘clean’

 

Here’s is an alternative method of the same idea.

var phone = building == null
    ? null
    : (building.Manager == null
        ? null
        : (building.Manager.ContactInfo == null
            ? null
            : building.Manager.ContactInfo.PhoneNumber));

The code still looks tedious.

 

Here’s another alternative method of same idea.

var phone = building != null 
    && building.Manager != null 
    && building.Manager.ContactInfo != null 
        ? building.Manager.ContactInfo.PhoneNumber 
        : null;

Still looks pretty tedious.

 

Naïve

What if you just write like this.

var phone = building.Manager.ContactInfo.PhoneNumber;

Problem is you could get null reference exception because any property in the chain could be null
(which you knew because you used all those null checks in your code).

 

Then what about this?

Try catch

string phone = null;
try { phone = building.Manager.ContactInfo.PhoneNumber; }
catch { }

No that’s is wrong. You should not use exception handling for controlling the flow.

More about this here

 

Null propagating operator

What if you could write like this?

var phone = building?.Manager?.ContactInfo?.PhoneNumber;

Unfortunately it is not available yet.
You can read more about the operator here.

 

Monad extension

What we want is something like the safe navigation operator where the code is clean.

var phone = building.=> Manager.=> ContactInfo.=> PhoneNumber;

That is not a valid syntax.


If we add some parentheses and some _ to make the syntax valid we could do this.

var phone = building._(_=>_.Manager)._(_=>_.ContactInfo)._(_=>_.PhoneNumber);


This looks a little cryptic I admit but the intend should be clear.
You want to safely extract the PhoneNumber without getting null reference exception.

This syntax is possible if you use this extension method.

MonadExtension.cs

public static class MonadExtension
    {
        public static TTo _<TFrom, TTo>(this TFrom input, Func<TFrom, TTo> evaluator) 
             where TFrom : class
        {
            return input == null ? default(TTo) : evaluator(input);
        }    
    }

This is an example of a Maybe Monad.

You can read more about Monads here.

 

Cleaner syntax

The syntax is not very clean and is usually to cryptic for must people in the example above.
The Monad extension in C# are usually preferred in this style.

var phone = building
            .With( b => b.Manager)
            .With( m => m.ContactInfo)
            .With( c => c.PhoneNumber);

If you want to return a default value in case there is a null somewhere in the property chain.
Then the return extension method is used.

var phone = building
            .With( b => b.Manager)
            .With( m => m.ContactInfo)
            .Return( c => c.PhoneNumber, "unknown");

MonadExtension.cs

public static class MonadExtension
    {
        public static TTo With<TFrom, TTo>(this TFrom input, Func<TFrom, TTo> evaluator) 
             where TFrom : class
        {
            return input == null ? default(TTo) : evaluator(input);
        }    

        public static TTo Return<TFrom, TTo>(
             this TFrom input, Func<TFrom, TTo> evaluator, TTo failureValue) 
             where TFrom : class
        {
            return input == null ? failureValue : evaluator(input);
        }
    }

This is an example of a Monads implementation for C#. I encourage you to read this channel9 post. This might inspire you to write ‘more clean code’.


EDIT:
There is also this alternative found at http://stackoverflow.com/a/4281533/815507

var phone = building.GetValueOrDefault(b => b.Manager.ContactInfo.PhoneNumber);

Written by kunuk Nykjaer

June 4, 2014 at 10:38 am

Posted in Csharp

Tagged with ,

Use the DI container as a way to monitor and maintain the health of the architecture

leave a comment »

Imagine your have been given the task as a technical architect for a large project.

Are you going to use a DI container?
If not you should consider using a DI container.

DI containers makes your architecture more manageable.
Not only manageable for the implementation details but it also enables you to control how your developers will implement and use the services in the project.

Imagine you you have N developers and they are giving various tasks to implement.
How do you manage, monitor, handle changes and orchestrate their usages and implementation of the various architectural services such as:
caching, repositories, CMS-services, feed-services, logging?

How do you make sure the developers don’t make duplicated implementations and how do the developers know where to find the existing implementations used across the architectural layer?

What you can do is to let the developers express their need and let a framework (e.g. DI container) provide the services they need.

Taken from How to explain dependency injection to a 5-year old?

“When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn’t want you to have. You might even be looking for something we don’t even have or which has expired.

What you should be doing is stating a need, “I need something to drink with lunch,” and then we will make sure you have something when you sit down to eat.”

Here the developers are the 5-year olds – metaphorically 🙂
They might break things and do stuff not approved by the architect.
What the architect should do is to provide the services which the developers need.

I am using MVC Asp.Net as an example (MVC based web-site)
You are building a news website.

Imagine you have a NewsController with the action Politics and a SportController with the action Tennis.

The developer needs to read data from a CMS system and return a view with populated model.
The developer has a need (read data from CMS system).

Example 1 – using DI

    public class NewsController : Controller
    {
        private readonly ICmsService _cmsService;
        public NewsController(ICmsService cmsService)
        {
            _cmsService = cmsService;
        }
		
		public ActionResult Politics()
        {
            var viewModel = new ViewModel { Data = _cmsService.GetData("politics") 
            return View(viewModel);
        }
	}
	
    public class SportController : Controller
    {
        private readonly ICmsService _cmsService;
        public SportController(ICmsService cmsService)
        {
            _cmsService = cmsService;
        }
        public ActionResult Tennis()
        {
            var viewModel = new ViewModel { Data = _cmsService.GetData("tennis") };
            return View(viewModel);
        }
    }

The developers simply add the needed service in the constructor and the service will be provided.
The developers don’t have to update the code if the service implementation is changed.
The developers must use the correct interface and the object instance is provided from elsewhere, i.e. injected.

Imagine the alternative version

Example 2 – not using DI

    public class NewsController : ServiceController
    {
        private readonly ICmsServiceImplementedByDeveloper1 _cmsService;
        public NewsController()
        {
            _cmsService = new CmsServiceImplementedByDeveloper1();
        }

        public ActionResult Politics()
        {
            var viewModel = new ViewModel { Data = _cmsService.GetData("politics") };
            return View(viewModel);
        }


    public class SportController : Controller
    {
        private readonly ICmsServiceImplementedByDeveloper2 _cmsService;
        public SportController()
        {
            _cmsService = new CmsServiceImplementedByDeveloper2();   
        }
        public ActionResult Tennis()
        {
            var viewModel = new ViewModel { Data = _cmsService.GetData("tennis") };
            return View(viewModel);
        }
    }

Here the developers have implemented their own interfaces because it was not provided and they made their own implementation to read from the CMS due to lack of communication or because they needed an implementation which was not provided at the time. Here we see code duplication. And worse when there are changes for the CMS service then all the developers must update their implementation of the CMS service. This makes it harder to maintain and adjust the system.

Written by kunuk Nykjaer

March 11, 2014 at 12:01 am

Posted in Csharp

Tagged with , ,

Dependency Injection in .NET

leave a comment »

I have worked with miscellaneous IoC containers for C# and wanted to get a more in dept knowledge about the IoC topic.

If you are a software developer then the concept IoC is a must for you.
It’s a pattern used for loose coupling and IoC containers will make your software architecture more easy to manage.

Here are some benchmarks of the various containers which is frequently updated.

I recently read a book called Dependency Injection in .NET which I highly recommend if you are into C#. I will get geeky about the DI topic and geeky is good if you want to learn 🙂

The books covers the concept and introduce you with a poor mans DI container. Then it demonstrate IoC patterns and anti-patterns and ends with review of 5 different DI containers.

Written by kunuk Nykjaer

June 28, 2013 at 10:44 am

Posted in Csharp, Framework

Tagged with