Isolating Unit Tests with Microsoft Fakes

Isolating unit tests is a large requirement of unit testing. Quite often, individual units of code will rely on, or access,  other sections to do their processing. For example, a method that saves an entity to the database will call a method in a repository that is responsible for the actual saving.

Such methods, as they stand, can only be unit tested by containing the requirement. For example, to unit test saving to the database you would require a database for testing, or do something ill-advised and test against a live database. Which is a bad idea, even inside a Transaction (Once upon a time I was very naïve and did this myself, tut tut!).

Thankfully, Isolating Unit Tests doesn’t have to be difficult.

There are many approaches to Isolating Unit Tests, which I suppose depends on the Unit Test Framework you are using. Personally, I use MsTest, Visual Studio’s built in testing suite, and to date I have found no reason to change, and within MsTest we can utilise Microsoft Fakes when Isolating Unit Tests.

Continue Reading →

23. August 2014 by Adam Riddick
Categories: C#, Testing, Tips | Leave a comment

MemoryCache V1.2.0

Announcing MemoryCache V1.2.0

Yesterday I was giving some thought to my small collection of NuGet packages, and I had told myself that MemoryCache V1.2.0 was just about due. Then I recieved an email shortly after 11pm last night from Erik Zettersten putting forward an idea that would improve the usage of MemoryCache.  So I decided to spend some time on some improvements to MemoryCache, and here we are with MemoryCache V1.2.0.

Erik pointed out that a setup, such as the following, could be improved with an Update method, which would improve the first block of code.


if (Cache.Exists(key))
 {
         int newItem = (int)Cache.Get(key)++;
         Cache.Remove(key);
         Cache.Store(key, newItem);
 }
 else
 {
         Cache.Store(key, 1);
         Cache.AddExpiration(key, 1000);
 }

Erik also pointed out a frustration. MemoryCache would not retain the original expiration, and to keep the original expiration, some form of tracking would be required. He suggested an Update method that would persist the original expiration time.

Continue Reading →

14. August 2014 by Adam Riddick
Categories: MemoryCache, News | Leave a comment

.Net Interview Q & A Resources

.Net Interview Q & A

Generally speaking, I’m an anxious person.

Not in the sense that I fear what is going to happen, on the contrary, I think that I’m a bit excitable when it comes to new things, and I drive myself mad with anxiety until the experience is done. Which in itself is a challenge. It’s tiring, and it does make it hard to enjoy things, in an epitomised sense.

But it does mean I enjoy a lot of experiences that many people find daunting, such as interviews, the topic for the day.

This week I found myself introducing a colleague to the Joel Test. For those of you who are unfamiliar and don’t want to click the link, the Joel Test is an unequivocal system to determine the quality and maturity of a software team.

I’ve experienced both ends of the scale of the Joel Test. A team who scored 4, which my influence turned into an 8 before moving on, to leading a team which, in the manner we operate, scores 9. This however, disappoints me. There is nothing preventing us from pushing this to a healthy 12, which we have the resources to maintain as a long-term position.

The reason I mention the Joel Test, if one of the points eludes many software companies but is a critical measure of maturity;

Do new candidates write code during their interview?
Would you hire a magician without asking them to show you some magic tricks? Of course not.

- Joel Spolksy

Continue Reading →

12. August 2014 by Adam Riddick
Categories: Bits & Bobs, Experiences, Tips | Leave a comment

ASP.Net Per-Request Pattern

When Developing, the objects we create can have different Lifecycles. For example, an object can maintain a Singleton lifecycle, in which only one version of the object can ever exist. Today, I will demonstrate how to implement a Per-Request Lifecycle.

Per-Request Lifecycle

An object with a Per-Request lifecycle will only remain in scope for the entirety of a single web request. This means, when a request is made to a server the object is instantiated, and acts as a Singleton lifecycle, but only for the duration of the request.

Take MVC, as an example. The user makes a request of a controller. As soon as the request begins a Repository, used for data persistence, is instantiated. This is then accessed by multiple other services within the application, to complete the users action. Then the controller returns a View to the user, with some data, and at the very end of the requests lifecycle, when the data is traversing hundreds of miles of network to the user’s machine, the Repository goes out of scope.

More goes on in the middle, but it’s the gist that counts here.

Typically, the Per-Request lifecycle is best used for objects which use connections to external sources, such as database connections, but there is no limitations on what objects can hold a Per-Request lifecycle.

Continue Reading →

07. August 2014 by Adam Riddick
Categories: ASP.Net, C#, Design & Practice | Leave a comment

FakeModel V0.0.7

Introducing FakeModel v0.0.7

It’s been a while since I’ve been able to commit some time to improving FakeModel, but I’m now proud to announce the release of FakeModel v0.0.7, bringing some essential fixes to the nature of FakeModel.

What’s New

FakeModel v0.0.7 brings the following updates;

  • Limited Characters in String Generation

Continue Reading →

26. July 2014 by Adam Riddick
Categories: FakeModel | Leave a comment

Insight: AuthorizeAttribute Lifecycle

I’ve learned a valuable lesson about the AuthorizeAttribute Lifecycle recently, one which I feel should be shared with the world. Hopefully, someone will gain something from this, hopefully I can fix the issue I faced for others.

The Story

The situation is a simple one, I required that access to certain controllers and actions was subjected to the approval of an authorisation process. In MVC, we are provided with the AuthorizeAttribute to help us along our way. Not wanting to re-invent the wheel in any way, I implemented the AuthorizeAttribute filter, as I have many times before without ever fully understanding the AuthorizeAttribute Lifecycle, and went on my way, assuming the filter was doing it’s job because the tests passed and I could authorise against the attribute.

Continue Reading →

22. July 2014 by Adam Riddick
Categories: ASP.Net, C# | Leave a comment

Software Overengineering

Software Overengineering

How do you know when you are over thinking the architecture of a solution? Should we forget about the future and build for now, or should we focus our efforts on building for the future? Are we all Software Overengineering?

First, I want to define Software Overengineering. It may be natural towards thinking this means putting too much effort into a solution that requires less. Whilst it follows the same mold, it is not entirely the same.

By Software Overengineering, I refer to putting too many constraints on the architecture or design of a solution, constraints that we feel are required though never actually will be, we can build for the future without building the future. It’s an easy trap to fall in to, it’s among many people’s traits to over think a situation, and many developers over complicate solutions, a lot simply because they feel it makes them appear smarter and better at what they do.

Continue Reading →

15. July 2014 by Adam Riddick
Categories: Achitecture | Leave a comment

Backup All Databases SQL

Data is precious and for many companies data means money, directly or indirectly. More and more countries are taking up laws on the ownership storage and historical persistence of data, meaning companies need to pay attention to backups for multiple reasons. But whatever the reason for a backup, you should be able to backup all databases without it giving you a headache.

Of course we could use Sql Server Management Studio (SSMS) to create a maintenance plan, and that’s fine and easy when we have a handful of databases, or less, but what if there are dozens or hundreds of databases that require attention? Do we really want to maintain that may maintenance plans?

We can backup all databases in an Sql server using a T-Sql script, which will cycle our databases and create a dated backup at the  location of our choice. This script can be scheduled through a SQL Job to automatically backup all databases to a set schedule.

Backup All Databases Script


DECLARE @name VARCHAR(50) -- database name
 DECLARE @path VARCHAR(256) -- path for backup files
 DECLARE @fileName VARCHAR(256) -- filename for backup
 DECLARE @fileDate VARCHAR(20) -- used in file name
 SET @path = 'C:\backups\' --path to the backup folder

 SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
 DECLARE db_cursor CURSOR FOR
 SELECT name
 FROM master.dbo.sysdatabases
 WHERE name NOT IN ('tempdb')
 OPEN db_cursor
 FETCH NEXT FROM db_cursor INTO @name
 WHILE @@FETCH_STATUS = 0
 BEGIN
 SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
 BACKUP DATABASE @name TO DISK = @fileName
 FETCH NEXT FROM db_cursor INTO @name
 END
 CLOSE db_cursor
 DEALLOCATE db_cursor

The power of T-SQL allows us to be flexible enough to include of exclude certain databases, in case they are archived already, their backups are handled by an existing maintenance plan or they are temporary databases. This can be achieved through a standard WHERE clause. The full power of T-SQL is at our disposal for handling backups, which allows us to be very dynamic in what we create backups of.

05. July 2014 by Adam Riddick
Categories: SQL | Leave a comment

MVC External Controllers

In my current role I am architecting and implementing an application platform that is flexible and dynamic enough to allow a full set of application features be loaded into the application without any outward dependencies from the central application block. This requires that each Service being loaded into the application is dependent only on the central applications functionality, using a separated data access layer to handle any data persistence. It also requires that a single MVC presentation layer handles the loading and routing of External Controllers. These External Controllers are to be located within the services, separate from the base presentation layer.

Effectively, this application is operating with an N-Tier architecture, in which N is only definable within a given deployment.

Each of the services that will be created for this application needs to be in a position to declare and handle it’s own Controllers, Views and Routes, three essential components of the MVC engine.

Handling External Controllers from a single presentation application has perhaps been the most complex part of the project to date.

The most obvious point approaching the problem of External Controllers was that the Routing table would need to be aware of the routes in order to pass a request to the controller in question. This was achieved by mapping all of the routes into the routing table on application startup. Using an interface implemented within each service, derivatives of the interface can be loaded on application start and there register method called to map the routes.

But it doesn’t stop there. Each of the routes mapped must set the Namespace parameter to declare the full namespace in which the controller can be found, otherwise the routing engine will stop after checking the default namespaces.

For example;

context.MapRoute<"MyRoute","My/External/Route",
new { controller = "ExternalExample", action = "Index"},
new string[] { "MvcApplication.Controllers" });

The next step is to make sure every resource that will be rendered is set a an Embedded Resource and each of the External Controllers must return a view by the entire namespace name, I.E “MvcApplication1.Views.Home.Index”.

Next, there is a need to implement a custom VirtualPathProvider to tell the MVC engine where to find our resources, which is registered on application start. There are a lot of examples of this on the internet (Try Ian Mariano’s), it’s normally just a case of tweaking the path locations depending on the setup of your external controllers assemblies.

In order to handle media files (.css, .js, .png, .jpg …. etc), they must also be set as Embedded Resource’s, and can be called through the following method, within the Presentation layers controller;


public FileStreamResult Content(string id)
{
string resourceName = Assembly.GetExecutingAssembly().GetManifestResourceNames().ToList().FirstOrDefault(f => f.EndsWith(id));
return new FileStreamResult(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName), GetMIMEType(id));
}

Finally, we must ensure that the separate services are locatable by the app domain. In order to do so, we have to use a PreApplicationStartupMethod (See This) in which we load a shadow copy of the assemblies into the app domain.

In order to do so, we must set the Probing PrivatePath property to the location we will shadow copy the assemblies to. This is done in the web.config <runtime><assemblyBinding> section;


<Probing PrivatePath="/ShadowCopies" />

Once we load the shadow copied folder into the private path, which is done using a standard file.copy from a dynamic directory search, the shadow copied assembly must be registered with the Build Manager, so MVC knows to reference this DLL as part of the application domain. This is done using;


BuildManager.AddReferencedAssembly(myShadowCopiedAssembly);

The build manager requires that this is done in a PreApplicationStartupMethod. So we use our PreApplicationStartupMethod to make shadow copies of the DLL’s we are working with and registered the appropriate ones with the Build Manager.

And from there, the External Controllers can be accessed through the base application, without the application needing a reference to the external controllers assembly. This allows us to swap and change Services in a plugin fashion and the only requirement is that we restart the applications domain, which is a very straightforward operation, just have a controller action call the following;


AppDomain.Unload()

The next steps will include allowing a Plugin architecture to be handled for the Modular services, so they themselves and have their functionality expanded without the need for updates. Unfortunately, this would require that the plugin dll’s are also loaded into the BuildManager pre-startup.

I plan on experimenting with holding an additional app-domain to hold plugins in a separate environment to the main application, one that would be started when the plugins are requested by the service itself, holding only the required lifecycle and not being present for the entire application lifecycle when they may not be used.

If I have much success, I may plan to implement this into the services, however it depends how nicely MVC plays with controllers in separate app domains, considering the setup required for External Controllers.

26. June 2014 by Adam Riddick
Categories: Achitecture, C# | Leave a comment

C# ?? Operator

Those of you who have used C# for a while will probably be familiar with the ?? operator, known as the null coalescing operator. The ?? Operator is used to check if a value is null, and will return the left hand operand if it isn’t, and the right hand if it is.

For example;


string myString = null;

string result = myString ?? "Empty String"; //Result is set to "Empty String"

myString = "A String";

result = myString ?? "Empty String"; //Result is set to "A String"

The reason for this post wasn’t to introduce anyone to the ?? Operator, which most of you will have seen at least in passing before. But it was because I discovered something new about the ?? Operator today, it can be chained.

The ?? Operator can be used multiple times in the same operation to determine if multiple operands are null.

An example usage;


string valueOne = null;

string valueTwo = null;

string valueThree = "Hello";

string result = valueOne ?? valueTwo ?? valueThree ?? "No Value"; //Result is set to "Hello"

valueOne = "Changed";

result = valueOne ?? valueTwo ?? valueThree ?? "No Value"; //Result is set to "Changed"

Sometimes it’s the simplest things that make our lives more concise!

Credit where credit is due, Rick Stahl.

16. June 2014 by Adam Riddick
Categories: Uncategorized | Leave a comment

← Older posts