C# Inherit from multiple interfaces with clashing method names

Recently, in one of those many projects on the go, I was working on an interface between two individual systems that are required to talk to each other. I can’t discuss much about the project itself, white label and all, but I can abstract to a level to explain the solution to a problem I stumbled across, which was the need to Inherit from multiple interfaces with clashing method names.

As you are probably aware, in the C# environment you can inherit from multiple interfaces without any great difficulties, we use the following template;


public interface IFoo

{

    void DoFoo();

}

public interface IBar

{

    void DoBar();

}

public class FooBar : IFoo, IBar

{

    public void DoFoo()

    { //Foo Happens }

    public void DoBar()

    { //Bar Happens }

}

But a less known concept is the ability to inherit from multiple interfaces with clashing method names, but first let me explain.

I’ll use the example of a solution to log stock values between two systems, let’s say they are stock provisioning systems. Each system allocates stock to varying clients by different means, one through a web interface, an e-commerce system, and the other through the manual scanning of a products barcode by a store worker (For completeness, well say this is an Argos style store, in which you order your goods and wait for the warehouse team to bring them down). Reporting is required to allow real-time transfer of the data into a single logging file.

To this end, a solution is being implemented in the middle of the two systems, we’ll call them A and B.

Continue Reading →

18. September 2014 by Adam Riddick
Categories: C#, Tips | Leave a comment

C# Dynamically Load Types From DLL

Reflection is a great way to allow us to Dynamically Load Types From External DLL’s.

I love reflection. I learned about Reflection when I started creating FakeModel, and haven’t looked back since. I use Reflection in many projects for lots of different purposes, and it solves problems in each and every one of them that would have required architectural changes without it. One such problem can be solved using reflections ability to dynamically load types from external DLL’s at runtime.

In order to dynamically load types from external dll’s, we can use the following snippet;


string dllPath = "c:\users\mypath\somewhere\else\myassembly.dll";

Assembly assembly = Assembly.LoadFrom(dllPath);

Type type = assembly.GetType("MyType");

dynamic instanceOfMyType = Activator.CreateInstance(type);

//We can now call the methods, but won't have intellisense

string result = instanceOfMyType.MyMethod("A Parameter", 7);

Which is rather straight forward.

As we use the dynamic keyword, we won’t get intellisense and the compiler won’t generate errors if calls against instanceOfMyType are wrong, keep this in mind when testing.

First, we define the full path to the dll file. This could be done searching directories and filtering files, or by direct access if you know the location.

Adding Some Peace Of Mind

The above snippet is great, but will fall flat on its face in the presence of a tampered DLL. For example, if somebody got hold of the dll and create a constructor on “MyType” which wiped the hard disk, we’d have some pretty unhappy clients.

To protect against this, we can use a checksum against the DLL. This will require pre-computation of the checksum so that a valid checksum can be used. For this, MD5 will suffice as it is faster than other Hashing algorithms.


static byte[] generateMD5(String filepath)
{
    using (FileStream stream = File.OpenRead(filepath))
    {
        return MD5.Create().ComputeHash(stream);
    }
}

Once we have a pre-computed hash value, we can check that against the DLL as we load it, giving the Hash and the method used to produce the hash as parameters;


string dllPath = "c:\users\mypath\somewhere\else\myassembly.dll";

//byte[] hash = ... Pre-Computed Hash Here, or the line below ...

byte[] hash = generateMD5 (dllPath);

Assembly assembly = Assembly.LoadFrom(dllPath, hash, AssemblyHashAlgorithm.MD5);

Type type = assembly.GetType("MyType");

dynamic instanceOfMyType = Activator.CreateInstance(type);

//We can now call the methods, but won't have intellisense

string result = instanceOfMyType.MyMethod("A Parameter", 7);

With the help of this snippet it’s possible to dynamically load types from dll’s at runtime in a secure manner.

Of course, you may want to go one further and add further security to the DLL itself.

 

You can read more about reflection on MSDN.

11. September 2014 by Adam Riddick
Categories: C# | Leave a comment

Introducing Foreign Key Constraint May Cause Cycles Or Multiple Cascade Paths

Introducing Foreign Key Constraint May Cause Cycles Or Multiple Cascade Paths

“Introducing Foreign Key Constraint May Cause Cycles Or Multiple Cascade Paths” may be a message you have seen before when using Entity Framework. The error message is thrown when a relationship being built by Entity Framework has multiple paths in which it can cascade a delete, without knowing which to choose.

Entity Framework doesn’t contain a mechanism to make a choice on a cascade path, so we must remove the cascade for the relationship to work.

Before exploring the fix, well take a look at a scenario that will cause the “Introducing Foreign Key Constraint May Cause Cycles Or Multiple Cascade Paths” error.

Introducing Foreign Key Constraint May Cause Cycles Or Multiple Cascade Paths

Introducing Foreign Key Constraint May Cause Cycles Or Multiple Cascade Paths

Continue Reading →

03. September 2014 by Adam Riddick
Categories: Databases, Entity Framework | Leave a comment

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

← Older posts