.NET tanker & tips

.Net, jQuery og andre nørdede emner

SDD day 2 & 3 - Impressions and takeaways

May 23
by steffen 23. May 2019 20:23

As a part of my attendance at the SDD Conference in London, I have decided to write small blog posts summing up some of the impressions from the talks I attend. The format will be rougher since the posts have been written during the day and finished in the evening at the hotel.

This post is a summary of my impressions and takeaways from the second and third day of the SDD conference.

Version ASP.NET Core APIs

Philip Japiske (@skimedic) gave a walkthrough of the new versioning capabilities in .NET Core. Every public-facing API's are facing the same issues with regards to versioning. An API - like any other code - will almost always be a living thing, where new requirements will show up and change the endpoints and functionality.

In order not to introduce breaking changes to the existing API, that is being consumed by customers, a proper versioning strategy must be put into place. This was previously a manual process that the team agreed on, but with the new Microsoft.AspNetCore.MVC.Versioning.ApiExplorer assembly, this can be streamlined significantly by expressing which endpoints are supported in which versions of the API. By decorating a controller with the [ApiVersion("2.0")] data annotation, you can express which versions of the API the controller is currently supporting. It is even possible to have multiple decorations if the controller is supported in multiple version of the API.

Build RabbitMQ Microservices in C#

Queuing technology is here to stay. Richard Blewett gave a short introduction to one of the biggest actors in this technology stack: RabbitMQ. To support big spikes in load it is a common approach to implement a queue that can handle the messages. This can be handy if the request does not need an instant response (e.g. sending some data for processing). Each request can be put into the queue and the consumers can handle one at a time without being a bottleneck. RabbitMQ is written in Erlang and is optimized for performance - rumour has it that Google has a queue implementation that handles 1.000.000 messages per second!

One of the neat tricks that RabbitMQ has is the ability to add a 'topic'. The consumers can filter on this topic so that they only pick up the messages that they actually want to. It is a very simple approach, but the simplicity is what makes it so powerful. RabbitMQ is definitely on my list of things I want to learn more about.

Vue.js

One of the things that I am focusing on learning at the moment, is the different frontend javascript frameworks. Vue.js is Google's take on this and it plugs in very nicely with the ASP.NET MVC background that I have. Vue is extremely lightweight coming in at only 33k and also has its own logic with regards to manipulating the DOM, which means that you can also cut away jQuery saving even more bandwidth. It can work side by side with jQuery, but only if you actually have a specific need for jQuery (maybe legacy code). 

Vue supports all the cool stuff like two-way data binding and can easily be plugged into an existing Razor based MVC view. This means that you can use you traditional view models from MVC, to hand down data to Vue, which will use the data on the client-side. 

The first impression was very good and I will be digging into the pros and cons of Vue vs React and Angular soon.

UI Design crash course for software developers

I am not a designer, but as Joe Natoli (@joenatoli) pointed out it is very often that the developers (backend and frontend both) end up doing design work. In this talk Joe went through a few guidelines that will help anybody - even a developer - design UI that isn't horrible (might not be beautiful UI, but at least not horrible). 

Each element in the page must be in harmony with the other elements. This essentially means that it is important to align the elements vertically and horizontally as much as possible. If you draw a line from each vertical and horizontal edge on an element, this line should align with as many other lines in the screen. Also, make sure that the spacing between each element is the same.

If certain elements belong together, make sure to enhance this relationship by grouping the elements close together. This provides structure to the page and will make it easy for the user to understand the relationship between elements. Grouping can also be done with contrasting colours, but distance is superior for this, so choose to place elements close together overusing colour if possible.

One should be very aware of the concept of contrast. Black and white is the best contrast you can get and provides the user with very easy reading experience. Be aware of using very vibrant colours. Red on yellow might have great contrast, but can be very straining for the eye to read.

One should always try to keep the 'noise' as low as possible. Often there is simply too much content on a page, making it seem very messy and noisy. 'Less is more' is the goto motto, when deciding what to have on the page.

Tags: , , , , ,

SDD day 1 - Impressions and takeaways

May 21
by steffen 21. May 2019 20:44

As a part of my attendance at the SDD conference in London, I have decided to write small blog posts summing up some of the impressions from the talks I attend. The format will be more rough since the posts has been written during the day and finished in the evening at the hotel.

This post is a summary of my impressions and takeaways from the first day of the SDD conference.

Keynote - Flow: the worst software development approach in history

The two speakers, Sander Hoogendoorn (@aahoogendoorn) and Kim van Wilgen (@kimvanwilgen), had a very entertaining keynote, discussing all the "horrible" things that Agile methodologies are bring to the software development world. I might have been a little slow out of the blocks this morning, but I was a little confused by the talk and it took me quite a while to figure out that the bashing of agile, was meant as a joke and what they were really trying to do was to set the stage for a summary of what really is important in agile software development.

The keynote was entertaining but a little lightweight for my taste. The points made at the end, could easily be boiled down to a few slides taking 10 minutes. Bottom line was: focus on building great software - use what fits you from the agile methodology and scrap the rest.

Getting started with .NET Core

Jeremy Clark (@jeremybytes) is a favorite speaker of mine. Great humour and lots of knowledge packed into a talk that is kept as simple as possible, to ensure that everyone can follow. This time he talked about .NET Core 2.2 and all the good stuff it brings to the table. The main point here is the fact that .NET Core is cross-platform that actually works. This means that it is a perfect fit for Docker containers that can be deployed to many different operation systems.

Apart from being cross-platform, I also really like the light weight nature of .NET Core. You have to manually add all the assemblies that you need, and even though that might seem a little tedious, the biproduct is that your applications does not end up with a s***load of assemblies that is never really used, making the application much more heavy than actually needed. 

The last great thing that I want to mention, is that fact that .NET Core comes with dependency injection baked in. All too often I see applications that is not using any form of DI and hopefully the fact that .NET Core has this from the get-go, will make more developers discover (and understand) the beauty of DI.

Modernizing legacy .NET apps with Docker - revisited

Elton Stoneman (@eltonstoneman) gave an extremely fast paced talk about how to modernize a legacy webforms application using Docker. The abstract of the talk sounded like it would be on an introduction to Docker, but this talk was definitely for developers who already had experience with the technology. I tried as best as I could to hang on to what was going on, but I did not gasp all of the content. It would have been nice to cut away 1/3 of the examples and slow down to make sure that all the points made actually got across, instead of speed talking 100 km/t for 90 minutes.

That being said there is no doubt that the Docker container technology is a very interesting topic, that opens up a wealth of possiblities with regards to deployment and elimintation of technical debt. The great thing about Docker is that you can create a reverse proxy, which transfers the requests to a web application to different containers. This means that you can have a "main" container running you legacy code and another to run a subcomponent of the system that you have rewritten in a new technology (like .NET Core), without this being visible to the user. By doing this you can slowly and surely eliminate technical debt, by rewriting small components of the application one at a time - and even deploying them without taking down the entire application.

AI for C# developers: introducing ML.NET

Jeff Prosise (@jprosise) gave a great introduction to Microsofts first take on a machine learning framework: ML.NET. So far if you wanted to mess around with AI and Machine Learning (ML), you had to learn Python and/or R. With the introduction of ML.NET this is not quite true anymore. Eventhough ML.NET is only in version 1.0 and is still missing support for deep learning and more advanced AI topics, you will be able to go a long way creating ML models in C# and being able to use those models natively.

A great feature of the framework is the ablility to take pretrained models created in TensorFlow and use these as a stepping stone to a more specialized model. This means that you do not need the gigantic amount of computer power to train the models, since the heavy lifting has already been done for you. By importing one of these models and adding the specific training that you need, you have very efficient and complex model at a very low cost. Very cool stuff!

Tags: , , , , ,

Machine Learning | SDD

Is Blazor the new Angular killer?

May 20
by steffen 20. May 2019 14:44

As a part of my attendance at the SDD conference in London, I have decided to write small blog posts summing up some of the impressions from the talks I attend. The format will be more rough since the posts has been written during the day and finished in the evening at the hotel.

This post has been written as a short summary of Dino Esposito's pre-conference workshop at https://sddconf.com/

Microsoft new toy

At the Build conference in May 2019, Microsoft announced that the experimental Blazor project, would be picked up as a fully supported product. Version 1.0 is expected to launch together with .NET Core 3.0 in September 2019. 

Blazor is a brand new way of developing web applications, where the new WebAssembly standard is used to run C# code directly in the browser. This means that there is no need for Javascript og Typescript, since the WebAssembly sandbox has the same rights as Javascript and therefore can interact with the DOM and all the other stuff that can be done from the browser. The neat trick is that you can do everything in C#.

The current version is 0.9 and has some features, but there is missing some vital implementations e.g. authentication. The current version does show a little bit about some of the thoughts the Microsoft team has about the upcoming product. 

In the broad perspective there are two different flavours of Blazor: client only Blazor and server side Blazor.

Server side Blazor

The server side Blazor approach is expected to be shipped together with .NET Core 3.0, while it is unknown when client side Blazor will be shipped.

The server side approach is built using SignalR. When the server is hit SignalR will create a WebSocket connection from the browser to the server and this channel will be used to transfer the rendered HTML from the server to the client throughout the session. 

This approach solves the issue with the huge initial download in the client side approach and also looks a lot more like a vanilla flavour ASP.NET MVC Core application, making this approach very comfortable for developers who already knows this. 

The downside is that the server will have to maintain many concurrent WebSockets and you have to handle disconnect scenarios gracefully. However this issue is the same across most applications using the WebSocket technology.

Client only Blazor

The client only approach is running on a version of Mono that can interpret C# in the WebAssembly sandbox. When the server is hit with the first request, all the pages from the website and all the assemblies that is needed to run those pages are sent back to the client. The downside here is that the initial load is quite long pending your download speed. The upside side - which is pretty cool - is that for all subsequent actions the user makes on the page, the content is loaded instantly without hitting the server (unless you explicitly ask to hit the server), because everything has been loaded upfront. 

Depending on your scenario this could be a very attractive tradeoff. It actually makes you web application work a lot like an app, since all the code needed for running the application has been downloaded to the computer/device. 

The obvious downside is that if you have many pages and/or use many different assemblies the initial download will bloat very fast and will degrade the user experience.

Angular killer?

The new Blazor framework has a lot going for it. It is directly developed by Microsoft, it cuts away the need for having a codebase with multiple languages (e.g. C#, javascript, Typscript), removing the need for thrid party frontend frameworks lige Angular and React.

In the current form I do not believe that it will kill neither Angular, React or Vue - it is simply not good enought. But it will definitely be a competitor, the question is how big a competitor it will be. A lot depends on how the 1.0 version will look like. The version that I have seen demoed today in May 2019 is not ready to take on the mature Angular, React and Vue frameworks. 

The server side Blazor seems like a good idea. I like the fact that all code is in C#, which makes it easy to maintain, it's possible to unit test everything and the conceptual model is easy to understand.

The client only Blazor confuses me a little bit more. I find it har to figure out what Microsoft are trying to achieve with this approach. It could make sense to use as a substitute for native app's - but since it is running in the browser it will lack all the cool bells and whistles that native apps have. The fact that you have to download all the pages and dependencies to run it in the client does not sound like a sound idea to me. 

What will the final verdict be? We'll know when Microsoft launces version 1.0.

 

Tags: , ,

Do you have trust issues? You really should have...

April 19
by steffen 19. April 2019 10:27

Do you trust the data you receive over the internet? If you do, you are very naive and really shouldn’t. Especially when it comes to data relating to authentication and authorization you must tread very carefully and only trust parties that you truly now who are and expect to provide extra care for your data. You have to make sure that the data that you’re trusting has not been tampered with and verify that the data is coming from who you expect it to come from. The interwebs is a dangerous place my friend...

 

The need to transfer data securely over the internet has never been bigger. JSON Web Tokens (JWT, prenounced like jaw with a t at the end, jawt) fits perfectly into this landscap. It provides a secure and easy way of transferring data between two parties.

JWT is an open standard which defines how the format can be used for transmitting information between two parties, in a secure, compact and self-contained way. A JWT can always be verified by the recipient, because it is digitally signed using either the HMAC algorithm using a secret or by using RSA or ECDSA, with a public/private key set. This does not mean that the data cannot be read by others during the network transport, but the recipient can verify that the JWT was actually sent by the expected party in the other end. If the data contained is sensitive, the content can be encrypted, providing data privacy for the parties involved.

 

Use cases for JWT’s

The most common scenario for using JWT’s, is to handle authorization. The JWT can contain information regarding the users identity, which resources can be accessed and which operations are permitted by the user. Many implementations of OAUTH2, which is the most popular protocol for providing authorization, rely heavily on JTW’s. Another use case is simple data transfer. In scenarios where it is essential that the data in question, has not been tampered with and the sender is who they say they are, JWT provides an easy way to secure the data.

 

JWT format

A JWT consists of three parts, separated by dots:

[theHeader].[thePayload].[theSignature]

 

The header

The header consists of two parts: the type of token, which in the case of JWT is “typ”:”JWT” and the algorithm used for signing the token. The normal algorithms are HMAC SHA256 or RSA. The header could look like this: { “alt”:”HS256”, “typ”:”JWT” } When the JWT is being built, the header JSON is Base64Url encoded and is put in the as the first part of the JWT payload.

[theHeader].[thePayload].[theSignature]

 

The payload

The payload part of the JWT are called “claims”. A claim is some information regarding the user (or entity if it is not a user authorization scenario, but a data transfer).

 

Registered claims

There is a set of claims that is a part of the standard. These claims are called the registered claims. They are almost always a part of the payload, in order for the recipient to know which user the other claims in the payload are related to.

The registered claims are:

  • iss - Issuer, identifying the sender of the JWT
  • exp - Expiry, when does the token expire
  • sub - Subject, user identifier
  • aud - Audience, identifying who the token is meant for
  • nbf - Not Before, when the token is valid from
  • iat - Issued at, the time when the JWT was issued
  • jti - JWT Id, unique identifier of the JWT

It is not mandatory that all registered claims are a part of a JWT, but it is recommended. Please note that all the claim names are only three characters long. This is to keep the total payload size as small as possible. It is recommended that you try to mimic this and keep all your claim names as short as possible, in order to keep the total size small.

Public claims

The next type of claims are public claims. Public claims are registered in the IANA JSON Web Token Registry. IANA makes sure that there are no name collisions. Before adding your own custom claim names, please check if IANA already have a name for the data you are trying to save in the JWT or that the name that you want to use is not occupied by some other data type already.

Private claims

The last claim type are private claims. A public claim is a custom claim name that is neither a registed claim or a public claim. It could be some data, that is specific to you application and is not already registered with IANA. An example of a JSON payload could be:

{
   “iss”:”someIssuer”,
   “exp”:”2019-10-10 22:00:00”,
   “sub”:”someSubjectId”,
   “aud”:”someAudience”,
   “nbf”:”1900-01-01 00:00:00”,
   “iat”:”2019-04-10 22:00:00”,
   “jti”:”someJwtId”,
   “name”:”Foo Barson”,
   “xyz”:”MyPrivateClaimValue”
}

Just like the header, the payload is Base64Url encoded and added as the middle part of the JWT.

[theHeader].[thePayload].[theSignature]

The last part of the JWT is the signature. The signature is an encoding of the two preceeding parts of the JWT (the base64Url encoded header and the base64Url encoded payload separated by a dot).

 

For instance:

[SomeBase64UrlEncodedHeader].[SomeBase64UrlEncodedPayload]

 

This string will be encoded with the encoding algorithm stated in the header and added as the last part of the JWT.

[theHeader].[thePayload].[theSignature]

The resulting string is a very compact and secure representation of the data. Especially when comparing it to the “old” SAML standard, which produces much larger payloads. Since bandwith is always an issue - especially for mobile devices - the smaller the data is the better.

 

If you want to play around with how a JWT looks like and how it all works, https://jwt.io is a great resource with a lot of background information. The site also has a JWT debugger, where you can paste in a JWT and see the content or add content to the clear text payload and see the encoded JWT change live. They also have a long list of libraries, which can be used when working with JWT’s in different programming languages and environments.

 

 

 

 

Tags: , ,

General

You are not Mozart - get help with composition

January 07
by steffen 7. January 2019 15:21

Mozart In one of my previous blog posts I wrote about dependency injection and why this should be a core principle when designing software architecture. The benefits from injecting dependencies into the classes who need them are many. One of the most important benefits is that your code will be loosely coupled, which makes the code flexible and make it much easier to reuse the code in multiple scenarios. A great benefit from loosely coupled code is also, that the code will be much easier to unit test. This allows us to assert that the code behaves as in the way that it was intended.

The most common way of implementing DI is by using constructor injection. This means that each class will take all their dependencies as an argument in the constructor. This pattern ensures that it is not possible to create an instance of a class, if you do not provide all the required dependencies. You can also inject dependencies by exposing the class dependencies through properties, allowing the client to initialize the dependencies. Personally I am not a fan of this approach, since this put the responsibility of initializing the correct dependencies on the client, which may or may not have the knowledge on the inner workings of the class. This can result in runtime exceptions, if a method is called, which depend on a uninitialized dependency.

When using DI the classes needed for a software system to work, must be build as close to the entry point of the system as possible. In a console application this would be in the Main method and in a MVC application it should be before the controller is executed. This is easily accomplished by using a DI framework (e.g. StructureMap). When using a DI framework, which I highly recommend, it will be responsible for creating the entire object graph, required for the system to function. The DI framework will analyze the dependencies of you code and based on convention and/or configuration it will spin up the required objects and inject them into the program.

A great example of a mature and well functioning DI framework is StructureMap (soon to be called Lamar). One of the cool features in StructureMap is that it has some default conventions, that allows you to get up and running with fewer lines of code. The main convention is that, unless specified in the composition root (the configuration method of StructureMap), for an interface called IFoo it will look for a concrete class called Foo. As such StructureMap rely on the normal naming convention where the name of an interface always start with an "I". This convention means that StructureMap will automatically map all interfaces to the respective concrete implementations, without you writing a single line of code.

Obviously most scenario will not consist exclusively of interfaces and classes with this naming relation. For all the other interface/class combinations, you must define which concrete classes must be used for which interfaces. An example could be that you have a ICar interface and you want StructureMap to inject an instance of the Jeep class (which implements the ICar interface). This is easily done with a short line of code in the configuration of StructureMap.

public class DefaultRegistry : Registry {

public DefaultRegistry() {

            Scan(

                scan => {

                    scan.TheCallingAssembly();

                    scan.WithDefaultConventions();

                });

            For<ICar>().Use<Jeep>();

        }

    }

The DefaultRegistry class and the code in the constructor, is responsible for creating the object graph. This is called the "composition root" and in a more complex application this class will be significantly bigger as the entire object graph of the application is defined here. One of the strong points by having all the configuration centralized in the composition root, is that you always know exactly where the object tree is constructed.

When using StructureMap to control the composition root, an added benefit is that it integrations seamlessly into most application types. When installing StructureMap from NuGet, you can almost certainly find a flavor of StructureMap that suit you application type. This means that as soon as StructureMap has been installed, it will be "plugged into" your application pipeline, ensuring that the composition root is called whenever the application needs an object graph.

Tags:

Dependency Injection | General

Don't let Tony Stark down - use enums!

November 04
by steffen 4. November 2018 16:56

Photo credit Marvel Studio

As a software developer you have many tools in our toolbox, that help create powerful and useful software applications. One of the most important concepts in software development is the principle of simplicity aka. the KISS principle. The more simple your code is, the easier it is to understand and to change, when a change request comes (and it will come sooner or later).

 

One of the most simple concepts that we have is the concept of flags. A flag is a marker that enable the program to recognize different program states and to decide how to proceed in the program flow. The most simple flag is the boolean, which has two states; true or false. But often the state of the program has more than two states and for this scenario the Enum solves the need perfectly.

 

An example of the use of enum, could be the software that defines which type of drivetrain a car has. A normal car is either front wheel drive, rear wheel drive or four wheel drive. This can be clearly represented with the following enum.

 

enum DriveTrain

{

    FrontWheelDrive,

    RearWheelDrive,

    FourWheelDrive

}

 

The drivetrain of a car can be clearly stated with the use of the DriveTrain enum.

 

This is all good and well, but as it turns out you work for Stark Industries and mr Stark has come up with a brand new design for a car, which can direct power to all four wheels independently. At any given time, depending on the situation, any combination of the four wheels can have power. It could be only the left frontwheel, the two right wheel or all four wheels. This requirement could be solved by adding a enum value for each of the wheel combinations, however this is not the most elegant solution.

 

Instead it is possible to use a neat little feature in C#, where it is possible to use the bitwise operators. First we will change our enum to reflect each wheel instead.

 

[Flags]

enum DriveTrain

{

    LeftFrontWheel = 1,

    RightFrontWheel = 2,

    LeftRearWheel = 4,

    RightRearWheel = 8

}

 

Let's start with looking at what we can do with this and we'll look into the nitty gritty stuff afterwards.

 

With this new enum we could do something like this:

DriveTrain wheelsWithPower = DriveTrain.LeftFrontWheel | DriveTrain.RightRearWheel;

 

A call to wheelsWithPower.ToString() returns "LeftFrontWheel, RightRearWheel" to indicate which of the enum values are set in the variable wheelsWithPower. If we have the need to query if a certain flag is set in the variabel we can do this with

 

bool powerToLeftRear = wheelsWithPower.HasFlag(DriveTrain.LeftRearWheel);

 

Very simple and concise!

 

Now let's dig in to some of the details. The most important thing to notice is the fact, that each enum value has a designated value (1, 2, 4 and 8). These number must be a power of 2. If this is not done the code will not work as expected. This has to do with the implementation of the HasFlags, which is a bitwise AND operation and hence each value must have it's own bit.

 

The second thing to notice is the [Flags] attribute. This is not needed for the HasFlags to work. This is only for getting nicer feedback while debugging. If the attribute was not added to the enum, a call to ToString() like above would return 9 instead of "LeftFrontWheel, RightRearWheel". Again this has to do with the underlying implementation, which rely on bit wize logic. The HasFlags works regardless of the Flags attribute.

 

Now mr. Stark can have his car, which alternates between powering each wheel independently and can go kick some bad guy ass.

Tags:

Let StructureMap be your Alfred

July 11
by steffen 11. July 2018 14:03

Alfred Pennyworth - http://www.mothershiptoys.com/hot-toys-mms236-batman-armory-with-bruce-wayne-and-alfred-pennyworth.html

In my previous post I addressed the concept of dependency injection (DI) and what the advantages are by using this technique. In this post we will look at little closer at some concrete examples on how to use StructureMap to help resolve dependencies (injecting the correct objects to each class that has an dependency on an interface). 

Like all good super heroes a coder need a tech saavy helper, that make sure the hero has all the tools needed for the job. James Bond has Q, Batman has Alfred and .NET has StructureMap. 

What is StructureMap?

StructureMap is a DI framework, that rely heavly on conventions to resolve the dependecies a class has. It is preferable to choose the convention based approach, in order to save as much time on the tedious configuration. The main convention in StructureMap is that it rely on the name of the interfaces and classes to "connect the dots". The common naming convention is to prefix all your interfaces with "I" and StructureMap leverages this convention.

If a class is depending on an interface IBar, StructureMap will look for a concrete class called Bar. This means everytime you have a one to one realationship between an interface and a class (IBar to Bar), this is handled automatically, without any extra configuration. There will of course always be some configuration - especially if the dependecies does not fall into the default convention - we'll take a look at this next.

Configuring StructureMap in ASP.NET MVC

I'll use an ASP.NET MVC project as an example. First we have to install StructureMap in the solution. This is easiest done from the package manager console:

Install-Package StructureMap.MVC5

At the time of writing I'm running MVC version 5 and hence is using the package targeted this version. After all the dependecies has been installed a new folder called "DependencyResolution" has been created in the root of the web application project. In this folder open the DefaultRegistry.cs file:

public class DefaultRegistry : Registry {
        public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                    scan.With(new ControllerConvention());
                });
        }
    }

The body of the call to Scan is where the container is configured. The most important part here is to configure which assemblies StructureMap should search when resolving a dependency. The call to scan.TheCallingAssembly() means that StructureMap will be able to resolve all classes in the current assembly (all classes in the web project in this case).

Usually the solution will consist of more than one project. This could be a class library with all the domain classes. In this case StructureMap must be configured to include these assemblies when resolving a dependency. Let's illustrate this with an example.

Including assemblies

In the solution on the right, there are two projects: a class library called Domain, which contains an interface and a concrete implementation of the interface, and a MVC project. Assuming that the MVC project has a reference to the Domain project and uses an instance of the IFoo interface, we must set up StructureMap to find the correct assembly and resolve the correct concrete implementation of IFoo. 

The controller could look something like this:

public class HomeController : Controller
    {
        private IFoo _foo;

        public HomeController(IFoo foo)
        {
            _foo = foo;
        }

        public ActionResult Index()
        {
            return View();
        }
    }

At this moment StructureMap does not know about the Domain assembly and will throw an exception (a very confusing "Class has not parameterless constructur" error, which does not indicate that it is a StructureMap issue). In order to get StructureMap to inject an instance of Foo, when the controller is created and is requires an instance of IFoo, StructureMap must be configured to look in the Domain assembly. This is done fairly simple by telling StructureMap to add the assembly containing the required classes and interfaces. There is a few ways to do this, but the two most simple ways are adding it by the assembly name or pointing to a type (ie. class, interface) in the assembly. Just remember that if you change the assembly name/move the type to another assembly, StructureMap will not be able to find the correct assembly needed for the dependency injection.

The code for configuring StructureMap to look in the Domain assembly in the small test project looks like this (code using the method pointing to a type is commented out):

public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
					scan.With(new ControllerConvention());
                    //scan.AssemblyContainingType<Foo>();
                    scan.Assembly("Domain");
                });
        }

When conventions doesn't cut it

Obviously the example above is very basic, but it really get you off the ground in a hurry and let's you focus on the code instead of the configuration. When you run into scenarios that does not fit into the common StructureMap conventions a little configuration is needed. But fortunately the good guys and girls at StructureMap made sure that this is very easy to set up using the fluent API.

Let's assume that we have a concrete implementation of IFoo that is called Bar. Obviously this does not match the StructureMap conventions (IFoo -> Foo) and in order for StructureMap to handle this, we must configure this. The configuration is quite simple and readable and must be added after the call to Scan. The syntax is For<TheInterfaceName>().Use<TheTypeYouWantInjected>();. It looks like this:

public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
					scan.With(new ControllerConvention());
                    //scan.AssemblyContainingType<Foo>();
                    scan.Assembly("Domain");
                });
                For<IFoo>().Use<Bar>();
        }

Now each time a class requires a concrete type of IFoo StructureMap will inject an instance of Bar. You can even add logic in the configuration, if the application have different dependencies in different situations. This could look something like this:

public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
					scan.With(new ControllerConvention());
                    //scan.AssemblyContainingType<Foo>();
                    scan.Assembly("Domain");
                });
            if (someBoolValue)
            {
                For<IFoo>().Use<Bar>();
            }
            else
            {
                For<IFoo>().Use<Foo>();
            }
        }

I have used this approach with a webshop where there were different business rules (ie. VAT, tax, delivery) depending on which country the customer was from. 

Tags: , ,

ASP.NET | ASP.NET MVC | Dependency Injection

Let StructureMap be your Alfred

July 11
by steffen 11. July 2018 14:01

Alfred Pennyworth - http://www.mothershiptoys.com/hot-toys-mms236-batman-armory-with-bruce-wayne-and-alfred-pennyworth.html

In my previous post I addressed the concept of dependency injection (DI) and what the advantages are by using this technique. In this post we will look at little closer at some concrete examples on how to use StructureMap to help resolve dependencies (injecting the correct objects to each class that has an dependency on an interface). 

Like all good super heroes a coder need a tech saavy helper, that make sure the hero has all the tools needed for the job. James Bond has Q, Batman has Alfred and .NET has StructureMap. 

What is StructureMap?

StructureMap is a DI framework, that rely heavly on conventions to resolve the dependecies a class has. It is preferable to choose the convention based approach, in order to save as much time on the tedious configuration. The main convention in StructureMap is that it rely on the name of the interfaces and classes to "connect the dots". The common naming convention is to prefix all your interfaces with "I" and StructureMap leverages this convention.

If a class is depending on an interface IBar, StructureMap will look for a concrete class called Bar. This means everytime you have a one to one realationship between an interface and a class (IBar to Bar), this is handled automatically, without any extra configuration. There will of course always be some configuration - especially if the dependecies does not fall into the default convention - we'll take a look at this next.

Configuring StructureMap in ASP.NET MVC

I'll use an ASP.NET MVC project as an example. First we have to install StructureMap in the solution. This is easiest done from the package manager console:

Install-Package StructureMap.MVC5

At the time of writing I'm running MVC version 5 and hence is using the package targeted this version. After all the dependecies has been installed a new folder called "DependencyResolution" has been created in the root of the web application project. In this folder open the DefaultRegistry.cs file:

public class DefaultRegistry : Registry {
        public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                    scan.With(new ControllerConvention());
                });
        }
    }

The body of the call to Scan is where the container is configured. The most important part here is to configure which assemblies StructureMap should search when resolving a dependency. The call to scan.TheCallingAssembly() means that StructureMap will be able to resolve all classes in the current assembly (all classes in the web project in this case).

Usually the solution will consist of more than one project. This could be a class library with all the domain classes. In this case StructureMap must be configured to include these assemblies when resolving a dependency. Let's illustrate this with an example.

Including assemblies

In the solution on the right, there are two projects: a class library called Domain, which contains an interface and a concrete implementation of the interface, and a MVC project. Assuming that the MVC project has a reference to the Domain project and uses an instance of the IFoo interface, we must set up StructureMap to find the correct assembly and resolve the correct concrete implementation of IFoo. 

The controller could look something like this:

public class HomeController : Controller
    {
        private IFoo _foo;

        public HomeController(IFoo foo)
        {
            _foo = foo;
        }

        public ActionResult Index()
        {
            return View();
        }
    }

At this moment StructureMap does not know about the Domain assembly and will throw an exception (a very confusing "Class has not parameterless constructur" error, which does not indicate that it is a StructureMap issue). In order to get StructureMap to inject an instance of Foo, when the controller is created and is requires an instance of IFoo, StructureMap must be configured to look in the Domain assembly. This is done fairly simple by telling StructureMap to add the assembly containing the required classes and interfaces. There is a few ways to do this, but the two most simple ways are adding it by the assembly name or pointing to a type (ie. class, interface) in the assembly. Just remember that if you change the assembly name/move the type to another assembly, StructureMap will not be able to find the correct assembly needed for the dependency injection.

The code for configuring StructureMap to look in the Domain assembly in the small test project looks like this (code using the method pointing to a type is commented out):

public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
					scan.With(new ControllerConvention());
                    //scan.AssemblyContainingType<Foo>();
                    scan.Assembly("Domain");
                });
        }

When conventions doesn't cut it

Obviously the example above is very basic, but it really get you off the ground in a hurry and let's you focus on the code instead of the configuration. When you run into scenarios that does not fit into the common StructureMap conventions a little configuration is needed. But fortunately the good guys and girls at StructureMap made sure that this is very easy to set up using the fluent API.

Let's assume that we have a concrete implementation of IFoo that is called Bar. Obviously this does not match the StructureMap conventions (IFoo -> Foo) and in order for StructureMap to handle this, we must configure this. The configuration is quite simple and readable and must be added after the call to Scan. The syntax is For<TheInterfaceName>().Use<TheTypeYouWantInjected>();. It looks like this:

public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
					scan.With(new ControllerConvention());
                    //scan.AssemblyContainingType<Foo>();
                    scan.Assembly("Domain");
                });
                For<IFoo>().Use<Bar>();
        }

Now each time a class requires a concrete type of IFoo StructureMap will inject an instance of Bar. You can even add logic in the configuration, if the application have different dependencies in different situations. This could look something like this:

public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
					scan.With(new ControllerConvention());
                    //scan.AssemblyContainingType<Foo>();
                    scan.Assembly("Domain");
                });
            if (someBoolValue)
            {
                For<IFoo>().Use<Bar>();
            }
            else
            {
                For<IFoo>().Use<Foo>();
            }
        }

I have used this approach with a webshop where there were different business rules (ie. VAT, tax, delivery) depending on which country the customer was from. 

Tags: , ,

ASP.NET | ASP.NET MVC | Dependency Injection

Dependency Injection Principle and the Geekmobile

March 17
by steffen 17. March 2017 06:28

Almost everyone in the development environment agrees that Dependency Injection (DI) is a corner stone of good software design. When implemented correctly it gives quite a few advantages to the code. The biggest advantages are that the code becomes easier to unit test and that the code will be more loosely coupled. However the concept of Dependency Injection can be a little hard to grasp at first. I will therefore try to first in explain in it general terms and afterwards provide some code examples.

There are two rules to the Dependency Injection Principle:

  • High-level modules should not depend on low-level modules. Both should depend on abstractions
  • Abstractions should not depend on details. Details should depend on abstractions

Let's take a look at what that means. The first rule means that each class should have as few references (none, if possible) to concrete classes as possible. Not to say that a class can't use a concrete class, but it is a clear code smell if there is. Instead you should use abstractions ie. interfaces or abstract classes where possible. The use of interfaces makes the code loose coupled, hence making it much more flexible and handling changing requirements much easier.

The basic idea that, in order to prepare your code for future changes, it should be structured in a way that will make changes easy, without causing a tsunami of changes other places in your code. This is commonly referred to as loose coupling.

The second rule, means that you have to design your code, so that if you change something in your concrete class, it must not change the outcome from what the abstraction expects.

This is best illustrated with an example (inspired by Vincent Ramdhanie's answer on SO). When I get into my car, all the controls (eg. pedals and steering wheel) are abstractions (or interfaces if you will) between me and the mechanics of the car. I understand the abstractions and by using the controls I can control the car: when I press the right pedal the car will accelerate and when I press the middle pedal (or left if you're not driving a stick), the car will decelerate.

Steering wheel from the geek-mobile

Steering wheel from the Geekmobile (image from xboxfreedom.com)

If we change some of the implementation details (eg. changing the engine in the car), you cannot change the abstractions. For instance you cannot swap the pedals, so that the brake pedal is now on the right. The same rules should apply to you code. If you have a calculator class, which implements an interface with a method called Add, you can change the code in the concrete implementation, but never in a way that it changes the abstraction (eg. dividing instead of adding). This is of course a very simple example and you might think your code is much more complex. That might be true, but this is one more reason for you to try to design your code to be as simple and loosely coupled as possible. If you design your classes with the Single Responsibility Principle in mind, your interfaces should become more simple and it should be easier to determine if a change in the details effects the abstraction.

To sum up the Dependency Injection Principle is a way to design you classes, so that the have loose coupling and being aware that do not change the abstractions (the implied understanding of what a interface promise to do) of the system. The next blog post will be much more code heavy and will describe how to use Dependency Injection to put the Dependency Injection Principle into use.

Tags:

Dependency Injection | General

IIS is dead - Long live IIS!

December 22
by steffen 22. December 2014 14:35

A major part developing is debugging. Stepping through your code, inspecting variable and verifying the the program flow behaves as predicted is an essential skill for any developer. The debugger in Visual Studio is pretty good. Place you desired breakpoint, hit F5 and Visual Studio will fire up the local IIS and open up a new browser window (if it is a web application) and you're good to go.

The process of perfecting the code is usually requires alot of "trial and error", where each time you start the debugger, find a bug, stop the debugger, fix the bug and start over. By default Visual Studio will shut down the local IIS when you stop the debugger. That means that if you make a small fix in the code and compile it, you can't just refresh the browser and see the result of the new code instantly. 

Luckily there is an easy fix for this. In Visual Studio go to "Tools -> Options" and in this small popup window, find "Debugging -> Edit and Continue". Remove the checkmark in the "Enable Edit and Continue" from the checkbox and you're all good to go.

IIS will always shut down, when you close Visual Studio. If you want to shut down IIS without closing Visual Studion, go to the system tray, right click the IIS icon and choose close.

 

Tags: ,

ASP.NET | ASP.NET MVC | CodeProject | General