Adventures on the edge

Learning new development technologies
    "When living on the bleeding edge - you sometimes have to bleed" -BillKrat

ASP.NET MVC - how to get config.json settings (beta7)

This adventure involves creating an IAppSettings implementation that can survive versioning changes - we want a single entry point to get settings so that if something changes, we only have to update one class or create a new implementation.  Note in the image below (on line 100) that our implementation of IAppSettings is AppSettingsBeta7..

Finding how to retrieve the config.json settings was quite the challenge since the methods shown during research vary from version to version.
Adventures on the edge I had to pave the way on this one as I couldn’t find anything that worked under beta7

The short version is that you have to store an instance of the IConfiguration in the IOC container (line 99 in the image below).  You can then retrieve the settings from it as shown in the AppSettingsBeta7 class (source code further down in this article).

The long version is a proof of concept that has a setting in the configuration file (DefaultFoo) which will designate which implementation of IFoo that should be used.  First I started by creating two implementations of IFoo (lines 94 and 95 in the image below).  We’ll let our factory decide which implementation to use based on the value of “DefaultFoo” in our config.json file.  


Since I throw an exception on line 168 above if the wrong implementation of IFoo is used, I can operate on the premise that  “no news is good news” and everything is working if I get to my index page.

Our config.json file is configured to use the value of “Foo2” for DefaultFoo

"AppSettings": {
"DefaultFoo": "Foo2"
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Da...
In the Configure method in the above image we resolve our factory on line 159 which instantiates the class propagating the dependency chain via constructor injection (reference line 188 below) and then uses the factory to get the concrete implementation of IFoo.
This is where the IAppSettings implementation comes in - we need to use its GetSetting() method to retrieve the setting for “defaultFoo”.   Because I am coding against an interface, I can use IAppSettings throughout the application without concern about breaking changes in the future; the new implementation will handle it.



// AppSettings
public interface IAppSettings { string GetSetting(string key); }

/// <summary>
/// Our application will code to IAppSettings since it is possible
/// configuration code will change - only this implementation will
/// have to be updated if required.
/// </summary>
public class AppSettingsBeta7 : IAppSettings
public const string APP_SETTINGS = "AppSettings";
private ConfigurationSection _section;

public AppSettingsBeta7(IConfiguration config)
_section = config
.GetSection(APP_SETTINGS) as ConfigurationSection;
public string GetSetting(string key)
var result = _section.Sources.Select(s =>
string value;

// Build the expected search key
var searchKey = string.Format("{0}:{1}", APP_SETTINGS, key);

// Try to get search key from IConfigurationSource
s.TryGet(searchKey, out value);

return value; // Return result
.Where(s => s != null);
// Only return non-null results

// Only get first or default if there are results
var returnValue = result.Any() ? result.FirstOrDefault() : "";
return returnValue;

The GetSetting() method above demonstrates “a way” to retrieve the config.json settings for beta7.   Note that it has a dependency on IConfiguration which is not set in the container by default - we had to add it as a singleton in the Startup class method ConfigurationServices.

Also note that we get our configKey from the config.json file and then we send it as a named parameter to the provider’s Resolve() method. 

var configKey = _settings.GetSetting("defaultFoo");
var returnValue = _provider.Resolve<IFoo>(configKey);

This is not actually a beta7 syntax for the built-in dependency injection (DI) container, I am use to Unity IOC (which I am now abandoning since Microsoft did) but liked the syntax so I’ll hold on to it - at least for now.   I used the following extension methods to emulate Unity’s Resolve<> method:


// ServiceProvider

/// <summary>
/// Used to Unity - will emulate its syntax
/// </summary>
public static class IServiceProviderExtension
public static T Resolve<T>(this IServiceProvider provider)
var result = provider.GetService(typeof(T));
return (T)result;
public static T Resolve<T>(
this IServiceProvider provider, string key)
// Wee bit of a hack - we'll use the class name as the key
var result = provider
.Where(s => s.GetType().Name == key);

if (result.Any<T>())
return result.FirstOrDefault();
return default(T);

Below are all of the code bits for IFoo and its implementation as you can see I am expecting the message “I am a foo too!” because I use Foo2 to implement IFoo based on the config.json file setting of “DefaultFoo”:


// Foo stuff
public interface IFoo { string GetFooMessage(); }

public class Foo1 : IFoo { public string GetFooMessage() {
return "I am a foo!"; } }

public class Foo2 : IFoo { public string GetFooMessage() {
return "I am a foo too!"; } }

public class FooFactory
private IServiceProvider _provider;
private IAppSettings _settings;

public FooFactory(
IServiceProvider provider, IAppSettings settings)
_provider = provider;
_settings = settings;
public IFoo GetDefaultFoo()
// Get the "defaultFoo" setting from the config.json file
var configKey = _settings.GetSetting("defaultFoo");

// Use it to get a named value (where name is implementation)
var returnValue = _provider.Resolve<IFoo>(configKey);
return returnValue;

ASP.NET MVC - RenderViewToString in MVC 6

The plumbing has changed with ASP.NET MVC 6 requiring us to think differently, particularly with inversion of control (aka dependency injection) now being a first class citizen.

In my latest adventure, my goal was focused on building a reusable class that allows me to convert a View into a string. This can be used for generating emails, newsletters, or insertion into other views.

To achieve this objective, I dug into the ASP.NET MVC source code to see how it works under the hood (reference blog “how to setup for using / debugging open source code”). To make this work I had to find the parameters required by the view engine’s FindView method and the view’s RenderAsync method.

I then created a new MVC website to prove out the code and updated the HomeController so that the About view injected the Contact views content:


The about.cshtml view was updated to display the raw data provided by the HomeController (line 10 in image below).


With the view done, I complied with the following steps within the HomeController class:

  1. Paste the ViewHelper class code into the HomeController (source available at end of this blog)
  2. Update the HomeController constructor so that dependency injection will resolve the ViewHelper via constructor injection (and as a result, its dependencies)
  3. Update the About() method to set ViewData[“Contact”] with the rendered content of the Contact view (on line 65-66 below).


Perhaps the most important and final step is to ensure the dependency injection container knows about the ViewHelper - this is done on line 49 below in the Startup.ConfigureServices() method.



public class ViewHelper
private IRazorViewEngine _viewEngine;
private ITempDataDictionary _tempDataDict;

public ViewHelper(
IRazorViewEngine viewEngine,
ITempDataDictionary dataDict,
IHtmlHelper helper)
_viewEngine = viewEngine;
_tempDataDict = dataDict;

public string RenderToString(
string viewName,
ActionContext actionContext,
ViewDataDictionary viewData)
using (var stringWriter = new StringWriter())
var viewEngineResult =
_viewEngine.FindView(actionContext, viewName);

var viewContext = new ViewContext(
new HtmlHelperOptions());


var result = stringWriter.GetStringBuilder().ToString();
return result;

ASP.NET MVC - The design time host build failed with the following error...

There is a finite number of steps one can take to troubleshoot build errors when attaching to ASP.NET MVC “open source” code  - in this adventure we overcame 4000+ build errors to resolve the following with less than 15 steps:

C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\DNX\Microsoft.DNX.targets(160,5): error : The design time host build failed with  the following error: Could not find a part of the path 'user path\.dnx\packages\System.Reflection.Emit\4.0.0\lib\contract\System.Reflection.Emit.dll'.

The adventure began after I added my clone of ASPNET/MVC to the solution’s global.json file

  "projects": [ "src", "test", "e:/github/mvc/src"],
  "sdk": {
    "version": "1.0.0-beta7"

The Microsoft.AspNet.Mvc projects were automagically added as expected.  During the build I had over 4000 errors which didn’t provide any clues to the issue.  However, the output window for “Build” did - the clue came from the fact that there is no System.Reflection.Emit\4.0.0\lib\contract folder for beta7 thus revealing a versioning issue.

Generally when I encounter build issues associated with adding ASP.NET source code I do the following:

  1. Launch GitShell and change directory into source - in this case
    path>cd MVC
  2. path>GIT tag   will show me available versions
  3. path>GIT checkout 1.0.0-beta7    this usually does the trick but in this case it didn’t - still 4000+ errors.
  4. path>.\build  to rebuild source - I noticed a mismatch of versions as beta8 was displaying


Adventures on the edge

In hindsight I found the following steps would have saved me a lot of headaches as I had different results coming from DNVM settings as processes ran; things changed unexpectedly.   I found the key was to perform a restore after setting the version; I suspect that without this the code may have been stale/invalid causing erroneous commands to be executed.  Note: as a general rule I wouldn’t recommend the restore unless build issues reveal versioning issues, it can be a lengthy process to restore than build particularly when --no-cache is being used (forcing a download versus using what is in the cache).

  1. path>DNVM install 1.0.0-beta7 -Persistent         // Ensure right version is selected
  2. path>DNU --version                                               // Verify version is beta7
  3. path>DNX --version                                               // Verify version is beta7
  4. path>DNU restore --no-cache                              // Restore source code for selected version
  5. path>.\Build                                                            // Rebuild the source code
             Build failed because of invalid Hosting reference
  6. path>cd ..\Hosting                                                 // Change to hosting folder
  7. path>DNU restore --no-cache                              // Restore source code for selected version
  8. path>.\Build                                                            // Rebuild Hosting source
              Build successful
  9. path>cd ..\Mvc                                                       // Switch back to MVC
  10. path>DNU restore --no-cache                              // Restore source code for selected version
  11. path>.\Build                                                             // Rebuild MVC source
              Build successful

Note: a lot of patience was required for the restore and build processes - at times I thought it locked up.

After complying with the above I went from 4000+ errors to a successful build


ASP.NET MVC - how to setup for using / debugging "open source" code

The actual steps for setting up and using the ASP.NET MVC source code are quite simple and literally only take a few minutes (after you know what your doing). 

STEP 1 – Install Tools
STEP 2 – Ensure environment is setup
STEP 3 – Install Source code from GitHub
STEP 4 – Configure VS to use Source Code

What is more challenging is understanding the steps, particularly if you don’t share a common core of experience with the authors sharing the information, i.e., I was lost even though I have been a hardcore Microsoft crony for many years, sticking primarily with Microsoft technologies such as Team Foundation Server for source control.  I trust a new developer will easily fall into the same category.

I get it now, after many weeks and rabbit holes, it is the intent of this article to shorten your learning curve by consolidating all of the “bits” into one location… 

My focus will be from a Microsoft Visual Studio developers perspective.  I strongly recommend reviewing the following videos - they put everything into perspective - this blog post will make some assumptions that you are familiar with some of the information presented in these videos:

  • DotNetConf 2014 - although the names have changed (from “K”) the information still applies
  • DotNetConf 2015 - invaluable information for understanding the command line tools and ASP.NET VNext


STEP 1 – install the tools, in my case I installed the latest beta release (Beta 7) from HERE.  This installs all of the necessary tooling (such as DNXVM.EXE, DNX.EXE, etc.).

You’re going to find a lot of references to command line utilities.  With ASP.NET VNext the command prompt is a first class citizen.  Why?  Because it provides the same cross platform experience (transparent to the developer) whether they are on a Mac, Windows, or Linux box.   For Windows users, if you use
SysInternals Process Explorer utility while in Visual Studio you’ll find that Visual Studio invokes the command line utilities for its processing.


STEP 2 – Ensure your environment is setup to utilize the newly installed .NET version.  In my case I had been using Beta 6 so I had to update my system to utilize the latest release.  I used the following command (by hitting the <WindowKey>-R and typing in “CMD”):

DNVM upgrade

The .NET Version Manager will install the latest version of the released .NET version (beta7), set its alias to “default” (used by Visual Studio), and then update both the process path and user path with the beta7 .NET environment (more on this below).  

In the image below I typed “DNVM” alone (first arrow) so that I could see the help screen and version.  Note that since I had executed the “DNVM update-self” earlier that I have the latest version of DNVM (beta8). 

I then performed the “DNVM upgrade” (second arrow) so that my environment would be pointing to the latest released version beta7, followed by the command “DNVM list” so that I can verify that beta7 was active, and my default alias was pointing to beta7.


It is important to know the difference between the process path and user path.  The process path will only apply for commands issued while in this command window; once you close the window the subsequent commands will revert back to the original version which in this case is 1.0.0-beta7.   In contrast, if the user path is set then that setting will persist even when the command window is closed. 

DNVM install 1.0.0-beta6 -Persistant  would set the NET version to beta6 and persist the settings.  In this case both the process and user paths are set.  Without the –Persistant switch only the process path would be set.   You would want to use DNVM install and -Persistant switch to switch to a version that is not the latest.

Below I created an ASP.NET Web Application using the Visual Studio 2015 ASP.NET 5 Preview Templates (the “Empty” template).  I then right clicked on the Web project AspNetBeta7Poc and selected “Open folder in Project Explorer”.  

TIP: from the Windows Explorer command line I replaced the path with “cmd” (see red oval in image below) so that I could open a command prompt in the project folder, required because commands such as DNX will use the current project location.

From within the command prompt window I typed (bottom pane of image below):

DNX --version

which shows (in the image below) that I am using the beta7 version of DNX.EXE to load a Web host.  I then execute the following command to launch a Web host (ref “Application started” in image below).   

DNX web


After reviewing the project’s hosting.ini file I can see my port is 5000 so I open a browser to http://localhost:5000 to verify my page is loading (shows “Hello World” - see below image), I then hit Ctrl-C to abort the Web host.

To demonstrate how I can change the version for the current command window, I then change the .NET environment to beta6 by executing DNVM install 1.0.0-beta6 from the prompt.  To verify my environment setting I typed DNX –version again which now shows the DNX.EXE utility will now use beta6 for processing.


Since I didn’t persist the setting when I close the command window my .NET environment will remain at beta7.


STEP 3 – with our .NET environment setup to point to beta7 it is now time to get the source code!

GitHub is an open source code repository that houses the ASP.NET open source projects.  If you’re an old school Team Foundation Server (TFS) developer it will seem a wee bit foreign so I’ll provide an introduction to basic usage – enough to get you up and running quickly with your source code.   Where it supports command line tools and processing, I opted to use the Windows utility.

Download the Windows Desktop GitHub application from HERE and install it.  When it is done you will have the following two icons:


Double click the “GitHub” icon to launch the tool, patience is required for the application to startup.

  • Once the GitHub application opens, click the gear on the top right corner of the application
  • Select options. 
    • I already had a GitHub account ( so I plugged in my login/password
    • I then set the “Clone path” to “E:\GitHub” which is my development drive.  Note: the GitShell will default to the folder set here which makes life simpler.
  • Save your settings (you can close the app or keep it open – won’t matter for the following steps)

With the Windows application installed you can now navigate to the source code that you would like to use.  For demonstration purposes I’m going to use the Hosting source code at

  • The first thing you’ll need to do is “Fork a Repo” (button on top right of page - reference image below).  This provides you with your own personal version that you can make changes to without affecting the original project - read more.
    For etiquette information please review THIS LINK before getting started  
  • Next “Clone” your fork by clicking the applicable button (reference arrow #2), it will require a wee bit of patience (I thought it wasn’t doing anything my first time) as it will need to load the GitHub application if it is not open.  It will then prompt you for the folder to install it in, you can simply click [OK] and it will install it under your configured folder.


Note: after my very first installation using the Microsoft Edge browser, the clone button took me to the Windows application download page.  Even after I installed the application the button kept taking me to the download page.   I had to run IE, click the button, have it launch the application, and “clone” (install) my source before I could use Microsoft Edge.  Both browsers now work consistently (I am on Windows 10).


STEP 4 - Configure Visual Studio to use Source Control

For this process to work you have to “Clone in Desktop” and not “Download ZIP”.

Open your global.json file from the “Solution items” folder and on the “projects” line add the location of the GitHub source code.   Be sure to add the “src” folder to your location, e.g., “e:/GitHub/Hosting/Src”, once you hit save, you’ll find after a momentary delay that the hosting project, and its dependencies, will automatically be added to your solution - in this case it added the three AspNet.Hosting projects shown below:



So now your project builds successfully and you attempt to run your web application and see the following error:

HTTP Error 403.14 Forbidden
The Web server is configured to not list the contents of this directory.

If you were running “web” versus IISExpress then you would see the exception

Microsoft.Dnx.Host.Clr.pdb not loaded

This is a red flag that there was an exception while executing code; the easiest way to troubleshoot this is to ensure you are using IISExpress and then enable CLR exceptions.  From the Visual Studio 2015 menu you can select the following:

Debug | Windows | Exception Settings and then check “Common Language Runtime Exceptions”

Now when you run IISExpress the actual error reveals its ugly head:

System.TypeLoadException occurred
Message: Exception thrown: 'System.TypeLoadException' in Microsoft.AspNet.Loader.IIS.dll
Additional information: Method 'Initialize' in type 'Microsoft.AspNet.Loader.IIS.RuntimeHttpApplication' from assembly 'Microsoft.AspNet.Loader.IIS, Version=, Culture=neutral, PublicKeyToken=null' does not have an implementation.

This red flag suggests a versioning error so in closer investigation of the projects I find that my Hosting projects are using beta8 versus beta7 (reference image below):


To fix this I’ll go into my GitShell and change into my GitHub Hosting folder (reference image below).  As I do, it reveals that I am in [dev] on the command line (within brackets in a cyan color) - so I execute the following:

git tag

to list the available tags and then I execute:

git checkout

This effectively selects beta 7 source code, my prompt changes to [] and I notice that in Visual Studio the Hosting projects automatically process a “Restore Packages”, when done they accurately reveal references to beta7 (versus beta8) - all of the project versions are now in sync.


Although the Hosting projects correctly restored to beta7 you may find that your actual project is complaining with a yellow yield shaped icon (reference image below).   To fix this, right click on the References node and select “Restore Packages”.  You should then be able to compile and run the application.


So I launch the application and am happy to see that I hit my breakpoint in my Startup.ConfigureServices method on line 16 below. 

I step out of this line and into the Hosting code to learn how it is possible that I can convert

void ConfigureServices(…)


IServiceProvider ConfigureServices(…)

and magically it will happily return, and use, my implementation of the ServiceProvider, e.g., Unity.   My primary objective for wanting to step into the source code was so that I could learn how it was working under the hood - particularly when it wasn’t ;) 


So lines 41 true 43 show how a void method can return a value - my assumption is that under the hood MethodInfo.Invoke() will return null if void.  This is a pretty cool little trick - I can also see that if null is returned that exportServices.BuildServiceProvider() will return an IServiceProvider reference.

I should note that in some videos and blogs they indicate that you’ll have to add the source code path to the “sources” element in your global.json file.  Where I have seen this successfully add the projects automagically to the folder - I haven’t had much success hitting breakpoints (the source was being ignored).  I did see in a video that someone added the path to the existing “projects” section so I tried this and and it has worked 100% of time.



Final note off topic: I dive a wee bit deeper into returning an IServiceProvider implementation in the following blog:

BlogEngine.Net “Update Failed”

I upgraded to the latest version of BlogEngine.Net and ran into an “Update Failed” message, this after everything worked perfectly on my local machine – it only occurred after I deployed.   The odd part was I could create a new post, I just couldn’t update it and none of the administrative features worked.


Adventures on the edge

Turns out, after much lost time, that my IIS Server application pool was running in “classic” mode.  Once I changed it to “integrated” everything started working as expected. 

Be sure to check all of your sites if you have to switch your application pool from Classic to Integrated.  Unfortunately, my oldest blog (BlogEngine - from 2008-2011) stopped working – problematic particularly since most of my hits (average 1,500 a day) come from that blog.   It was a mutually exclusive scenario as I could only use one or the other, but not both. 

I had some hoop jumping to do, but was able to use code from a different Blog (from 2011-2015) and migrated the data from the non-functioning blog to it and all was well – everything is working now.