Thoughts from Dan Miser RSS 2.0
# Thursday, 08 November 2012
The new DisplayMode engine in ASP.NET MVC 4 is rather nice. By default, it will detect whether you come in from a mobile device or a desktop machine, and load up a specialized view for you based on that detection.

For example, if you were trying to navigate to from an iPhone, the default behavior will be to look for Players\Index.Mobile.cshtml, followed by Players\Index.cshtml. Whichever it finds first will be the view that gets used. Note that this also requires you to have a _Layout.Mobile.cshtml file.

This is great for new projects, but I have a non-trivial app with a lot of views that have been built over the years using the technique by Scott Hanselman. That approach would look for the file in Players\Mobile\Index.cshtml. I was not looking forward to renaming all of those files.

In order to use my already existing file structure, I added one class:

public class SubfolderDisplayMode : DefaultDisplayMode
    public SubfolderDisplayMode() : base("Mobile")
        // Be sure to use, or a good browser capabilities file
        ContextCondition = (context => context.GetOverriddenBrowser().IsMobileDevice);

    protected override string TransformPath(string virtualPath, string suffix)
        var dir = VirtualPathUtility.GetDirectory(virtualPath);
        var filename = VirtualPathUtility.GetFileName(virtualPath);
        return VirtualPathUtility.Combine(dir, "Mobile/" + filename);

Registered it in my Globabl.asax.cs:

DisplayModeProvider.Instance.Modes.Insert(0, new SubfolderDisplayMode());

It works very well, and I can come back and rename those files later.

Also be sure to put a call to @Html.Partial("_VewSwitcher") somewhere in your desktop _Layou.cshtml file so the user can get back to the mobile version of the site.

Updated on 11/9/12 to clean the sample code up a bit
Thursday, 08 November 2012 21:11:20 (GMT Standard Time, UTC+00:00)  #    Comments [0] -
# Wednesday, 29 August 2012
After installing the RTM version of VS2012 last week and upgrading my project, I noticed that my web site was broken. The real culprit seemed to be that Microsoft changed how bundling works (the process of combining and minifying resources like js script and css files) between the RC version and the RTM version. For an excellent background on what this feature can do for you, see this tutorial.

It turns out my real problem was with Kendo. They don't provide non-minified files in the trial version, so the new bundling mechanism wasn't including the minified assets, which meant the Kendo minified assets were getting stripped out when I was trying to run under debug. (Reference here). I was able to use the work-around offered on this thread, and things started working again.

However, there are a few wrinkles when using the bundling code, so I thought I'd capture my experiences here. For example:

  • For 3rd party components that don't ship with non-minified assets, you need a better way around the default bundling strategy provided in the kendo article above. The solution provided in that thread of removing the min files from the ignore list will end up duplicating other assets that do provide both a minified and regular version of their assets while running in debug mode, e.g. jquery. There is a workaround for this, though: If you specify your bundle file's pattern with the {version} macro, then the bundling framework is smart enough to include just the one copy of the asset. If you use a wildcard in the pattern (as shown in the thread), you will get duplicate min and non-min versions of the asset when you render. Here is what your code should look like:
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
  • When specifying a CDN location, right now, you can't use the {version} macro, so you end up with a hardcoded reference for your CDN link (1.7.1 in the sample) and a {version} macro for the non-CDN reference (which could be 1.7.1, 1.7.2, or anything else that exists in your solution). This means that when you update locally, you need to remember to keep those version numbers in sync. The CDN path could take the version you have locally and substitute it in the CDN path that you provide removing this requirement.
  • In the tutorial, there is a fallback script that they recommend you write after your Scripts.Render statement so you can gracefully fall back to the local version if the CDN version doesn't load. It would be much better if that fallback code would be emitted for you when you call Scripts.Render.
  • Speaking of CDN, it appears that there is a very tight coupling assumed between a bundle and a CDN path. In other words, you cannot include multiple assets in one bundle because the CDN path for the bundle assumes it is a reference to a specific file on the CDN. It would be better to have CDN paths be tied to each individual item in the bundle.
  • Also relating to CDN support: The CDN path will only be used if you set bundles.UseCDN to true AND you either have BundleTables.EnableOptimization set to true or compilation debug set to false in your web.config. Granted, you probably only want to use the CDN when you are pushing to production, but while trying to test things out, I was doing it locally and this caught me by surprise. The 2 items should be independent of each other. If not, why even bother having the UseCDN property?

It seems that there is quite a bit of friction in the current version of the bundling framework. Fortunately, it resides in the Optimization assembly which can be upgraded independently of the entire MVC framework. I hope Microsoft releases an update very soon to overcome these obstacles. I have every reason to believe that they will since I'm seeing the author of this assembly answering tons of questions on StackOverflow.

Wednesday, 29 August 2012 19:39:05 (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
# Monday, 30 July 2012
I'm trying to settle on a standard for a grid component for use in an ASP.NET MVC app. It looks like is the winner for now.

Here is my quick run-down on how to get it working:

  • Using NuGet, install Mvc.Jquery.Datatables
  • Using NuGet, install EmbeddedVirtualPathProvider.
  • In the generated App_Code\RegisterVirtualPathProvide.cs file, add the following line where the comment tells you to. These last 2 steps are needed to get the grid to show up on the page.
    {typeof(Mvc.JQuery.Datatables.DataTableVm).Assembly, @"..\Mvc.JQuery.Datatables"} 
  • The sample found here is a little outdated and the instructions on the page don't match what's happening inside the actual view. Use these instructions instead:
    • In the controller, you need to return a DataTablesResult (not an IDataTablesResult). The assembly relies on finding an action with this return type, so that also means that you can't redirect views, which isn't the worst thing since this should be an AJAX request anyways.
    • In the view, add this to the top (instead of the calls to the link and script tags cited in the page:
    • In the view, the code should look similar to this where you want the grid (remember, you need to have the controller action method return DataTablesResult in order for this to work):
        var vm = Html.DataTableVm("table-id", (DashboardController h) => h.GetWireHistoryData(null));
      @Html.Partial("DataTable", vm)

There is a good series expanding on datatables usag in ASP.NET MVC over at

Thanks to Harry for the NuGet package. It definitely will make keeping things up to date much easier.

Monday, 30 July 2012 20:46:19 (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
# Friday, 27 April 2012
I needed a way to get a list of specific scheduled tasks running on a server. The main problem is that the command-line tool, schtasks.exe, is horrid. There is no ability to filter data. You get all of the data, or you get none. This is the Powershell script that I eventually settled on after piecing together a bunch of StackOverflow and blog entries. The key is the convertfrom-csv cmdlet that turns the result into objects that can be queried on, instead of a list of strings.

It's my first time using Powershell, and I don't know quite what to think. While it helped me solve my objective, and is quite powerful and extensible, it just doesn't feel natural to me. I'm sure that would change over time if I decide to invest time and energy to grok it. If anyone knows of a less awkward LINQ syntax, please let me know because that would turn me around on Powershell in a heartbeat.

schtasks /query /v /fo:csv | convertfrom-csv | where {$_.'Task To Run' -like '*MyProcess.exe*' }
Friday, 27 April 2012 14:36:50 (GMT Daylight Time, UTC+01:00)  #    Comments [0] -

# Saturday, 10 March 2012
There is no way I can list everything I learned with MonoTouch over the last couple of months. I'll summarize my experience by saying I'm a very happy customer. There were bumps and bruises along the way, but between the mailing list and the support crew at Xamarin, I heartily recommend investigating MonoTouch if you're a .NET developer that wants to get to the iOS AppStore quickly. I had to take several detours along the way (converted my existing app from Lightspeed to EF4 CodeFirst, converted to use POCOs, had support obligations, and wrote a sync engine to communicate over ServiceStack, but in the end, things lined up pretty well.

Some of the highlights:

  • I had to write code to essentially mimic the context loading that EF would do for you. This included fixing up object references as well as reading and writing from the SQLite database. Not horribly difficult, but it was something I'd rather I didn't have to do.
  • I encountered a couple of problems executing various LINQ statements when running on the device. A quick test case, and the devs at Xamarin had me with either workarounds or fresh bits to solve my problems.
  • Be sure to embrace threading when making web calls - especially on startup. You have 15 seconds to have your app launched on the device, or the device will think it is hung and kill the app.
  • Deploying to the app store has been written about extensively as a complex and intricate process. It turns out, there's good reason for that. After I got through an error due to linking my release build to ServiceStack.Text.dll, the resulting upload to the app store was failing verification. For some reason, the application name of was not being accepted. I changed the name to and it sailed right through. I have no idea exactly why this was required, but there you have it.
  • MonoTouch.Dialog is a very nice framework for building a line of business app. Be sure to check it out.

When I look back on the road I travelled to get my app to the app store, I'm impressed with how much of the business logic I was able to carry over. The time savings in being able to bring my business logic across as POCOs that have been extensively tested in production over many years was the real reason I went with MonoTouch to begin with. I most definitely do not regret that decision.

Note: I was not compensated or asked to write this post. I am just a happy paying customer of a product that saved me time, and I wanted to share my experience.

Saturday, 10 March 2012 01:48:03 (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | iPhone
# Wednesday, 29 February 2012
The iPhone app that I'm writing uses ServiceStack to communicate with an existing ASP.NET MVC app that I've had in production for a long time. The way I have things set up is that I'm doing my iPhone development on MonoTouch on the Mac side, and I use VMWare Fusion to run Windows as a guest OS. This blog will highlight a few of the tips that I found to be handy.

  1. Getting IIS Express to work from an external server (even the Mac OS host) is theoretically possible. I found articles lying around the net saying it could work, but it never worked for me. I ended up going back to Cassini (WebDev.WebServer40.exe) and using tcpTrace to listen externally on port 8080 and forwarding to my local port (e.g. 1234).
  2. In order to get VMWare Fusion using NAT to talk to my Windows OS on a consistent IP address, I added this section at the bottom of /Library/Preferences/VMware Fusion/vmnet8/dhcpd.conf (replacing the MAC address of the Macintosh and the IP address from the Windows machine)

    host winguest {
    	hardware ethernet xx:xx:xx:xx:xx:xx;
  3. In order to get external devices (e.g. my iPhone connected to the same wireless network) to see in to the Windows OS, I set up port forwarding to route requests coming in to the Mac on port 80 to point to port 8080 on the Windows machine. I did this by modifying this section in /Library/Preferences/VMware Fusion/vmnet8/nat.conf:

    80 =

After all of that, I can communicate from my iPhone through my Mac into the VMWare-hosted Windows machine to get at the data.

Wednesday, 29 February 2012 00:37:46 (GMT Standard Time, UTC+00:00)  #    Comments [0] -
iPhone | Macintosh
# Sunday, 19 February 2012
I have an HTML form that allows users to fill out a bunch of different parameters, and then it will display the result on the same page via an AJAX call. Pretty standard, and it works great. I had a request to allow for exporting the data in Excel format. Unfortunately, just returning a File ActionResult won't work from within the context of an Ajax form. There were some workaround posted out there (e.g. hidden iframe, duplicate the form on the page, etc.). I found the following approach to be a nice compromise and DRYs things up considerably. The key is that by putting the onclick on the Export button to do this.form.submit(), it forces the request to be a standard POST and not an AJAX call.


@using(Ajax.BeginForm("ReportData", new AjaxOptions {UpdateTargetId="result"})) {
  ... other input elements here
  <input type="submit" value="Display" />
  <input type="submit" value="Export" onclick="this.form.submit();">


public ActionResult ReportData(... parameters go here ...) {
  if (Request.IsAjaxRequest()) {
    // Do the normal behavior here to build up a string
    return Content(s);

  // I actually stream the result with a custom ExcelResult action, 
  // but this shows how to just return a file.
  return File(@"c:\library\report.xls", "application/");
Sunday, 19 February 2012 17:33:35 (GMT Standard Time, UTC+00:00)  #    Comments [0] -
# Wednesday, 15 February 2012
I had a class that looked like this:

public class CollectionDetail {
  public int Id { get; set; }
  public MachineField MachineField { get; set; }

I would then later write LINQ code that would end up retrieving these objects. The problem was MachineField was always set to null. I banged my head on this for a long time looking at everything I could think of. Finally, after looking at the CollectionDetail class one more time, I noticed that other Foreign Key objects were marked with virtual, and I remembered that I removed virtual while I was trying to test whether or not the object's lazy load behavior. All of the documentation clearly states that you need to mark this virtual. Once I added the virtual keyword back, everything worked exactly as it should have.

Wednesday, 15 February 2012 00:55:59 (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | EntityFramework
# Sunday, 22 January 2012
I found the class ActionSheetDatePicker from the book Developing C# Apps for iPhone and iPad using MonoTouch iOS Apps Development for .NET Developers. It was a very nice and clean implementation that would allow for having an ActionSheet pop up with a UIDatePicker in an iOS application.

It did lack 2 things, though:

  1. The ability to specify a starting default date in the UIDatePicker
  2. The ability to get cleanly launched from a UITextField component (i.e. effectively replace the default keyboard of a text field with this date picker). The original code would leave the default keyboard up when getting called from a UITextField component.

I fixed those things, and you can find the results in this gist.

Sunday, 22 January 2012 18:13:42 (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | iPhone
# Sunday, 15 January 2012
What's the difference between these 2 methods?

Html.ActionLink(string linkText, string actionName, object routeValues, object htmlAttributes)
Html.ActionLink(string linkText, string actionName, RouteValueDictionary routeValues, IDictionary htmlAttributes)

Yes, they have the same number of parameters. Yes, they even have the same parameter names. So in essence the intent of calling either of these methods is to build up a link with the passed in route values and HTML attributes. Yet the difference between these 2 methods couldn't be more pronounced.

Take this line of code:

@Html.ActionLink("Back to List", "Index", TempData["SavedRouteValues"], null)
What I wanted was an easy way to retain the settings of a Telerik ASP.NET MVC Grid and build up a link to bring me back to the correct state. This line of code does that. However, it generates a link similar to this (word-wrapped here for clarity):

Brutal. Ugly.

To fix this, just use this code (a simple typecast) to force the correct overloaded method to be picked:

@Html.ActionLink("Back to List", "Index", (RouteValueDictionary)TempData["SavedRouteValues"], null)

The moral of the story? If you're an API desiger, don't make overloaded methods lightly. Make sure they add value and distinction. A strong type vs. an object reference doesn't pass that test. If you do violate that rule, however, then at least be sure that the overload fulfills the intent and implied contract of that method.

Sunday, 15 January 2012 15:52:59 (GMT Standard Time, UTC+00:00)  #    Comments [0] -
<2012 November>
About the author/Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2018
Dan Miser
Sign In
Total Posts: 388
This Year: 0
This Month: 0
This Week: 0
Comments: 630
Pick a theme:
All Content © 2018, Dan Miser
DasBlog theme 'Business' created by Christoph De Baene (delarou)