Dependency Injection in ASP.NET vNext (adding Unity container)

by BillKrat 24. August 2015 06:26

As a prerequisite to reading this blog I would strongly suggest you review the “.NET Web Development and Tools” blog on this topic at Dependency Injection in ASP.NET vNext.

We live in an agile world which gives us the opportunity to work with the latest and greatest as it unfolds.   As such I found the above link helpful, but not complete as the latest videos on this topic (as of this writing) suggest that we have to return our IServiceProvider implementation from ConfigureServices – which is by default a void method.   In addition to videos I found the blog on using Autofac IOC container that provided more clues, but still fell short….

My research found that it will be the DI container authors responsibilities to make the necessary adapters for their respective containers (as Autofac did).  If you are like me and don’t want to be blocked, nor code in a lot of technical debt until the DI container vendor creates their service provider adapter for ASP.NET MVC, I offer a “poor man” adapter that will get the job done so that you can code against your favorite DI container.

The shortfall eluded to above was that the ASP.NET MVC 6 template had a lot of code in it and simply returning my Unity Service Provider was a more daunting task (reference method in image below).   A task that required me to dig into the source code to figure out how to create and implement my own provider.

SOURCE CODE: contains two classes and an interface in => Unity.Framework.DependencyInjection.zip 
                          (project has dependencies DependencyInjection beta 6)

BUG: There is a bug in MVC beta 6 that causes the default provider to be returned even if a new/different
         implementation is  returned by ConfigureServices.  Reported here with work-around

The following Startup code shows the updated source for my POC highlighted in a yellow box.   I should note that without line 98 my HomeController (which has dependency property requiring setter injection by Unity) will never be seen by the IServiceProvider implementation – the controller will be “new’d” up versus resolved.

The code comments will make the remaining code self explanatory – I’ll just add that the UnityContainerManager wires up the UnityServiceProvider (these two classes are all that are required).

Startup

I take a rather simplified approach that allows the developer to use both the default IOC container while providing their own (has less moving parts and places for failure).  When you review the UnityServiceProvider class code you’ll find that I first try to resolve types using the default MVC service provider and if successful return its value, IF NOT SUCCESSFUL I’ll use the Unity Container to resolve the type – this works because I have no plans or intentions of modifying Microsoft code (even though it is open source) to where I’ll need to inject my components into them.   If I require any default framework implementation, i.e., logging, then I’ll inject an instance into my container when I register other implementation (reference line 113 above).

The “cool” part of this process was that I would need to change the default return value of ConfigureServices from “void” to “IServiceProvider” and it would know how to use my provider.   I connected to the source code, put a break point at the end of CreateServices and when I stepped out the calling process gave me the information I needed; BuildServiceProvider (line 106 above).   On line 41 below, if CreateServices is void it will return null resulting in a default service provider being constructed using BuildServiceProvider, otherwise it returns the provided instance – so whether void or not it returns an instance of IServiceProvider.

CallsStart

Note the blue highlighted line in above image (bottom Locals pane): if I had not taken the simplified approach of using both default and Unity service providers I would be responsible for transferring the 241 interface, scope, and implementations into my container. 

To simplify code I decided to register my Unity container manager with the “default” service provider (line 103 below), build the Service Provider for default services (line 106), and then resolve my IUnityContainerManager implementation on line 110. 

StartupExcerpt

I did this to save some coding steps, this effectively allows me to grab an instance of the default MVC service provider via constructor injection in my UnityContainerManager (reference below line 30).   Note on line 43 that I effectively store the default service provider in “my” Unity container with a named parameter so that I can retrieve it in my UnityServiceProvider.

image

This keeps my Unity service provider compact and lightweight as shown below.  On lines 23-30 I attempt to resolve the type using the built-in (default) service provider (which in my POC has 241 registrations).  If the value is not null then I use the Unity container’s BuildUp method so that any dependency properties will be injected (setter injection); this is required for Controllers setter injection.  If null is returned I then use my Unity container (line 46) to resolve the type.  

IMPORTANT NOTE: Controller constructor injection will utilize the ASP.NET MVC default service provider – not the Unity service provider.  After the default service provider resolves the controller (line 30 below) the Unity Container will perform a BuildUp (line 39) effectively setting any dependency properties registered in the Unity container.  

ServiceProviderV1

Below is the final result of my POC

HelloWorld

How to use SQLite Designer Support in Visual Studio (5 steps)

by BillKrat 29. June 2015 21:02

The SQLite.NET.chm available HERE states the following:

Installing SQLite Visual Studio Design-Time Support

Supporting the Visual Studio query designer and allowing you to manipulate SQLite databases from within Visual Studio is a great time-saver.  Though the support is not yet fully-implemented, there's certainly enough there to keep you busy.  You can create databases, design and execute queries, create typed datasets and lots more all from Visual Studio.

Installation Instructions

Download and run one of the setup packages and then select the "Install the designer components for Visual Studio 20XX." option when prompted.

Which is all very promising but left me with a wee bit of a headache working out the details – I’ll share this adventure here to hopefully make it easier for the next person.

1. Go to THIS LINK and find the setup package that applies to your version of Visual Studio – note that the x64 does not install the design-time components, only the x86 version does.  Since I am using NuGet to install the libraries I’ll use this package primarily to install the design-time components.

Download

2. Once you download the application, right click on it and run as administrator – when you see the following screen ensure the “Install the designer components for Visual Studio 2013” is checked.

Checkboxes

3. There will be no apparent changes in Visual Studio however if click on View and open the Server Explorer you can select System.Data.SQLite Database File as the Data source.

Connection

4. Click on Continue which will open the “Add Connection” window.  Type in the full path of your database, which will be in the bin\debug folder of your project (assuming desktop application in DEBUG environment).  Click Test Connection to see if your connection is successful.

Connection1

5. Use the designer as applicable to update your database.

AddNewTable

SQLite Primer for .NET and Visual Studio installation (9 easy steps)

by BillKrat 29. June 2015 19:10

I guess when something is easy to use much is assumed – setting up Sqlite to work with my Visual Studio projects took longer than it should have – it is amazing how little documentation there is on the topic…

The first step I generally take is to install from NuGet

1. Right click on Project References
2. Click Manage NuGet Packages…
3. Search for SQLite
4. Select System.Data.SQLite (x86/x64)
5. Click the install button (it will install all dependencies)

In this case I was not disappointed to find SQLite available, what was more promising was the ADO.NET provider.  My initial efforts to install it in my Universal Apps did not yield expected results so I opted to go from the known to the unknown – I’ll start with Test Driven Development (TDD) on the desktop platform.

Nuget

Now that it was installed I wanted to see it work.  I accessed the System.Data.SQLite home page and was disappointed to find nothing available online, but the link to the SQLite.NET.chm was hopeful. 

6. I download the document and found some code under the “Introduction to System.Data.SQLite” in the “Using DbProviderFactories” section – I grabbed the code from Scenario 2 and plugged it into my unit test.

TDD-PastedSource

Well that would have been too easy…  What would have been nice is a reminder (it has been a long time since I dabbled in ADO.NET) that you have to:

7. Right click on project References
8. Add a reference to System.Data (knowledge assumed)

This made the IDE happy as all of the red went away, but it did raise a question in my mind as to how I was going to run this code in the Universal App world as it won’t have access to System.Data (an adventure for another day). 

So I run my unit test and walla!   Not an expected result….  (knowledge assumed)

ProviderNotFound

9. Copy the code from the documentation referenced in step 6 (Scenario 1) into the App.Config file. 

Note that the NuGet installation added an invariant for EF6 (Entity Framework 6 lines 10-13 in bottom pane of image below) but not for the code the documentation references.  This makes sense as I can now assume that GetFactory (line 16 in top pane of image below) will retrieve the configuration information for “System.Data.SQLite” which I just pasted into it (bottom pane).

AppConfig

Walla!  I now have successfully opened my database and can start TDD on the data access layer.

There is plenty of documentation out there for ADO.NET and the referenced documentation that I download has a section on ‘Query Language Understood By SQLite” so I trust my adventures should be less challenging…

image

I can guess your number in 6 steps (using linear algebra)

by BillKrat 27. February 2015 03:50

I’m taking a linear algebra course and was tasked with an assignment to demonstrate how it can be used to perform a “magic trick”.   The instructor gave a couple of examples which got me thinking – “how can I use it to guess a persons number and reveal it to them”.  The answer follows:

Grid1

Grid2

How it works => CLICK HERE

Tags:

Algebra

Online 3D model editor and artist website

by BillKrat 24. February 2015 19:12

Source: SculptFab-face.obj  (this is actually a text file)

The above source file can be loaded into SculptFab’s online editor at:https://labs.sketchfab.com/sculptfab/ 
Note: site worked with FireFox and IE 11.

Sculptfab is a very simple tool letting you sculpt 3D models in the browser and publish them in 1 click to sketchfab.com.   Tutorial is available at THIS LINK

Face

I created an account at SchetchFab and with a click posted my 3D face to https://sketchfab.com/billkrat
Note: site worked with FireFox and IE 11.

Scetchfab

Tags:

3D

The type name or alias … could not be resolved. Please check your configuration file and verify this type name

by BillKrat 18. February 2015 08:38

This one took me more time than I care to admit as well as a number of dead-end Bing searches…   There are any number of reasons why Unity won’t load a configuration file, i.e., typo in “type” or “mapto” attributes, but in my case these were correct – I even copy/pasted both namespace and class names to ensure there was not some unforeseen typo.

What I didn’t quickly find was resolution to my issue which was that you must have an <assembly name=”” entry in your configuration file.  Once I added it Unity happily loaded the configuration file.

Screenshot

GhostDocUtil – adding custom pages to your .chm file

by BillKrat 16. February 2015 20:38

            Source: GhostDocUtil.zip (Visual Studio 2012 and greater)
  Prerequisites: Html Help Workshop  
                           When prompted associate .HHP file with C:\Program Files (x86)\HTML Help Workshop\HHW.EXE
Documentation: GhostDocUtil: Help folder contains a GhostDocUtil.chm file.   See Quick Start for more details

The Ghost Doc application is an amazing tool for documenting source code, I particularly like the preview feature.  The only issue I encountered was that it only generates an API listing, e.g., you’ll only see the area shown in the red box in figure 1. 

I found a way to back door the system so that I could add custom pages which prompted me to write a utility to automate the process.   GhostDoc generates all of the files necessary for the Html Help Workshop to compile a new .chm – thus providing the means to add custom pages.  However, after successful building the .chm it deletes all of the files (more specifically the temporary folder).  So the key was to figure out a way to prevent this from happening at a point when processing was completed.   The solution was to open the .chm after a successful build and then build the help file again, this generates an error message (which I ignore) which opens the door for GhostDocUtil to automagically generate the custom pages.

The entire process takes six manual steps which are outlined in the Quick Start page (see prerequisites above).  The important part is that you can author your custom pages using a normal .htm page as shown in figure 2. 

The GhostDocUtil.chm pages combined with the GhostDocUtil source code (which was used on itself to generate the documentation) should give you the information necessary to create custom pages for your project’s documentation

ChmPage
Figure 1 screenshot of .chm after processing custom pages

SolutionFolders
Figure 2 solution folder screenshot

GhostDoc solves the age old problem of documentation

by BillKrat 15. February 2015 10:02

See GhostDocUtil for information on how to create custom pages in your .chm.

Historically the problem with technical software documentation has been keeping the UML diagrams and/or documents in sync with the code.  GhostDoc Professional and Enterprise now offers a solution to the problem.

GhostDoc not only provides an easy means to generate XML documentation, it also supports the ability to easily add images and preview documentation.  In figure 2 below I show the UML sequence diagram that represents the business logic flow of the BootstrapperBase class.  In the future, if I am working on this section of code all I would have to do is right click on the code and request a preview (reference figure 1).  It will show me the documentation preview shown in figure 2 (right pane) where a picture will truly say a thousand words – particularly when I reference this diagram from the bootstrapper class that will derive from it.

As for up-keep, all I have to do is keep the XML documentation current as I modify the code and after updating the UML diagram I’ll then then capture a screenshot of it saving it using its use case designator, in this case SD0300-020-075-010.PNG.  Walla!  We’re documented and can move on without looking back; all references to this use case within documentation will be updated when I produce the .chm file.  Likewise it will be current for the next preview.

This provides a great return on investment making it worth the time to clearly document each process in a class. 

I will be using this for my open source project http://PasswordMgr.CodePlex.com which will utilize my Prism Light framework

SolutionShot
Figure 1 right click on code, select GhostDoc Enterprise, and request a preview

SequenceDiagram
Figure 2 code with preview

MVPVM - Overview

by BillKrat 15. February 2015 05:04

MvpVm
 
Read article on MSDN

The MVC Presentation Model pattern was the development pattern that was used for early development, it is synonymous with MVVM. Some of the problems encountered with this pattern were ViewModel bloat, inability to reuse components, pollution of domain objects with view state, and no access to view components (as only data binding was used).

Because of these limitations our late architects evolved to the MVP (Model-View-Presenter) pattern - reference Martin Fowler article on GUI Architectures for more information.

John Gossman, father of MVVM, noted “On naming, my opinion at this point is the the Model-View-ViewModel pattern is a WPF-specific version of the PresentationModel pattern. PresentationModel is a lot easier to say and to write, and is more widely known...but for now I'm sticking to M-V-VM terminology in my own thinking in order to capture the WPF-ness and to avoid any interpretation conflicts”,

I refer to the WPF specific version of MVP as the Model-View-Presenter, ViewModel (MVPVM) pattern for the same reasons noted by John.

 UC0100-AnOverView

If In my experience I have found that developers are well aware of pattern rules, such as not having a View referenced from the ViewModel, but I found they lost track of the reason why; in case you are one of those developers, the reason is because it prevents reuse of the ViewModel; the ViewModel should be able to be accessed by multiple  views depending on your use case (more on this below). 

Reuse is the primary reasons we also have a rule that says we don't want to put code in the Views code-behind.  So we defeat the purpose of this rule if we put all of our code in the ViewModel because we essentially turn our ViewModel into a View’s code-behind without the benefit of being able to access the view components; worst yet, we cannot share it with other applications or platforms. 

The MVP pattern allows our developers (as a rule) to access the View and ViewModel equally, this permits the components to remain decoupled allowing them to be reused by other applications and platforms.  Some developers may feel that MVPVM is an enterprise development pattern not to be used with small programs, however I suspect most of us have experienced that small program that turned into a large application – they have a tendency to grow feet, suffer from scope creep (once client knows what they can have), and can become impossible for reuse  of components.

Many years ago I wrote a small application for the Amarillo Medical Group, it was for handheld device that was going to allow the doctors to track their billing.  After the first release some doctors wanted it on a laptop so I had to write a second program the worked on the desktop platform.  Later, some doctors wanted access from a website so the small program turned into three applications.  One day a doctor asked for a change to the application and couldn't understand why he was charged for three application updates - he felt it should have been a change in one place and this caused frustration since the apps looked exactly the same.  It was this experience that sent me down road looking for a way to develop one program that could be used for all platforms.  I started the journey on my open source project http://PasswordMgr.Codeplex.com.  Along the way I learned the importance of creating reusable, decoupled components and the value of MVPVM as MVP was a pattern created to achieve this goal; those who do not learn from the past are doomed to make the same mistakes.

In the PasswordMgrV3 folder of the Codeplex open source project http://PasswordMgr.Codeplex.com, we created an ASP.NET MVC application and pulled all of the login view models into a reusable portable class library.  This will permit us to create views that can reuse these view models from the desktop, tablet and phone platforms (as well as the Web platform).  So you can see that If we tie a view models business logic to one platform we won't be able to easily reuse it on the others.  So as MVPVM dictates we’ll move the business logic into the controller or presenter as applicable.   The goal is that the use cases in gray below can be reused cross-platform, on all devices, using one set of code written in C#.  For this purpose the Prism Light framework was born.

UC0100-Relationships

Prism (light) for Xamarin

by BillKrat 14. February 2015 10:26

Prism Light

Source code: CodePlex 
Change set: 107164

I am excited about the technology that will permit us to develop cross platform applications; Xamarin provides the ability to program to IOS, Android, and Windows devices.  This is a band wagon I am ready to jump on and fortunately there is a toolkit that is paving the way to make this easier for us – the MVVM light toolkit.   Although I will be using MVPVM for my application framework design, I will be able to use the components of the toolkit to make this job easier.  

It was great to see that Unity is supported by the portable class library, I’ll use this instead of SimpleIoc but I didn't see any support for Prism just yet.  This will require me to roll my own until something is available,  unlike my efforts in the past (my PasswordMgrV2 folder has a Prism portable class library that I ported) I am going to take a more agile approach and only create the Prism “like” components that I require at each phase of development.  I’ll use the MVVM Light toolkit components where applicable, in lieu of creating a Prism “like” component.

The goal for the POC was to modify the MVVM Light template as little as possible while providing MVPVM capabilities.  The end result is shown below for this phase of development:

AppScreenShot

The above screenshots shows four modules (top pane).  A module is the equivalent to what you would get if you created a single MVVM Light template – a single view that represents a use case.  The four modules in this POC are the menu, status bar, user (left pane), and generator (right pane).  At this phase of development they all have the same module code shown above with different views containing the XAML shown below:

    <Grid>
        <TextBlock FontSize="18"
                   FontWeight="Bold"
                   Foreground="Purple"
                   Text="{Binding WelcomeTitle}"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"
                   TextWrapping="Wrap" />
    </Grid>

The modules reside in a project called MvpVmDesktop while the MVPVM framework resides in project MvpVmPcl, it a portable class library that should port over to Xamarin, we’ll know more when the Visual Studio 2015 Starter license becomes available in a couple of months.

MVVM light developers will feel right at home when they open the POC project as all of the binding and wire-up is the same.  I made only the changes shown in red boxes (image below), the bootstrapper is the only new class. 

Prism developers should feel right at home with bootstrapper, EventAggregator, and module concepts.  I did implement my own ILogger (not Prism’s LoggerFacade) at this point so that I can subscribe to logger events – this allows me to easily send logging information to a textbox (coming soon).  This framework is barebones but functional as of this change set.

You’ll notice that in the solution there is a web project (MvpVmWeb).  This web project uses the MVC template, I removed the view models from it and moved them into the MvpVmPcl (portable class library project) so that I could use them in the log-in module of the MvpVmPoc (desktop app); reuse of views and view models is where MVPVM shines.

Since the ASP.NET MVC website uses these view models I would not want to add any business logic to them.  In MVPVM it is the each module’s presenter (coming soon) responsibility to populate the view models as required allowing the views and view models to remain completely decoupled.

Note: as this framework progresses there will be a Windows Phone, Tablet, Desktop, and Website password manager application that utilizes the same code and view models – only the UI code will be different.   When it comes time for IOS and Android, via Xamarin, I should only have to create those UIs as well.  NO CODE will reside in views and view models (outside of visual state and bootstrapping) making the transition to other C# supported platforms easy.

MvvmLightCodeAdded

Notice

Hall of fame

Blog videos and references to CodePlex projects are no longer valid