Updating Data in CouchDb from c#/Asp.Net Mvc

One of my repositories is working against the REST interface of a CouchDb set of data.  Reads have been awesome, and the “Paste JSON as classes” feature of Visual Studio 2012 makes getting POCOs up and running a treat.

However I ran into the following error doing a POST to update a document in the database:

couchdb {“error”:”bad_request”,”reason”:”Referer header required.”}

For anyone working in the REST space, this will likely be an error you would never run into as you have a great handle on your HTTP verbs.  For us crossover guys – especially relational database, Asp.Net guys – this is a little harder to figure out what is going on.

I was fortunate enough to have had a conversation the other day with our partner on the project who had mentioned that we need to remember to keep our PUTs and POSTs in order.  When I saw the “bad request” message above, I knew what I was doing wrong, especially after having a great conversation about REST with Darrel Miller earlier this year.

When a document exists in CouchDb you send updates to the document URL with a PUT. To create a new entry, you use a POST to the document container and CouchDb will determine the newly created item’s URL.

Here is a generic method to update a document from c#:

image

Via Gist:

Easily Build A Time Selector

I’m working on a project where I need the user to select a time in 24 hour format.  It would have taken me a couple of minutes to punch out the lines to build a select option for each of the items that were to appear in the drop down list, but I elected to use the Enumerable.Range method instead and build the list dynamically.

image

Why approach it this way?  Well, if the requirements change, for example, and I need to change that to every 10 minutes instead of every 30 minutes, I don’t need to go and write another 96 lines of code. All I have to do is change the call the select projection where I compute the minutes (right now at the top and bottom of the hour).

A Picture is Worth Zero Lines of Code. Apparently.

So…I’m getting flack either way…either I post a code-image or I post a Gist. With a Gist, RSS readers can’t render the code. If I post an image, no one can copy and paste. So, there’s the image for you in your RSS readers, and here’s the Gist for those copy and paste aficionados.


Breaking Down the Code

This is actually more verbose than it needs to be but it makes it a little easier to walk through it.  The first two statements are simply capturing some integer values to represent the hours and minutes that I want to render.

IEnumerable<int> hours = Enumerable.Range(0, 24); IEnumerable<int> minutes = Enumerable.Range(0, 2)

.Select(x => x * 30);

The call to Enumerable.Range takes two parameters: the first is where to start counting and the second is how many steps to take.  In the second statement I am also projecting the minutes out by multiplying them by 30. If I wanted, instead to have the list include 6 intervals on the 10, I would change the code to the following:

    IEnumerable<int> minutes =
        Enumerable.Range(0, 6)
        .Select(x => x * 10);

All that’s left to do is build our strings.  We’re going to loop over our hours, and then format those intro a string along with each of the minutes that we’ve projected into our list:

    List<string> timeOptions = new List<string>();

    foreach (var hour in hours)
    {
        foreach (var minute in minutes)
        {
            timeOptions.Add(string.Format("{0}:{1:00}", hour, minute));
        }
    }

That’s it! The timeOptions variable now contains a list of any of the valid options we want our user to select from. You can now easily use this collection to build a drop down list for whatever client you’re building for.

 

Want the condensed version? Check here: Build a list of valid times

Bootstrap Icon Classes as Strings

I’m working on the Twitter.Bootstrap.Mvc package with Eric Hexter and one of the things that we’re going to be doing is templating around forms and controls as an extension to the NavigationRoutes project that we’ve broken out.  We’re going to be adding support to include automatic prepending/appending of icons to known form elements.

This has led me to break out an old class I had created a while ago which exposed all the Glyphicons used in Twitter.Bootstrap as strings.  I just created the gist (located here) which looks something like this:

It’s nothing terribly complicated, but it might help if you don’t want to sling the code yourself.

System.Web.WebPages Aren’t the HtmlHelpers You’re Looking For…

Had a bit of a frustrating morning, one of those times when your tools work against you by helping you out but cost you 35 minutes and an extra cup of coffee.  And maybe a sanity check or two.  The goal was to create a very simple HtmlHelper extension method.  I kept getting the error:

‘System.Web.Mvc.HtmlHelper<dynamic>’ does not contain a definition for ‘MethodName’ and the best extension method overload ‘Namespace.MethodName(System.Web.WebPages.Html.HtmlHelper)’ has some invalid arguments

TL;DR – Check your using statements.  If you’re sharp, the error’s quite indicative of what’s going on.

Here’s another hint as to why this went south on me:

image

I was a little quick on the CTRL + . this morning, and since the first item in the list was System.Web.WebPages.Html, the tools didn’t help me out much at all.  But hey…shouldn’t ReSharper be able to figure this one out for me and give me the light bulb of awesome? 

image

I digress…

Regardless of trying to put using statements in my views for my namespace, or adding the namespace to my web.config in the views folder, the problem was I had this guy:

using System.Web.WebPages.Html;

…but I really wanted this guy:

using System.Web.Mvc;

Fixing that using in the top of my helper class resolved the issue, as now I was actually targeting the proper HtmlHelper class, in the correct namespace, that is being used by my views.  Hope this helps someone else out there as well.

Web Camp–Vancouver

I am geeked to announce that my videos for MVC4 and Web API from Web Camp in Vancouver have been made available.  All of the videos in the collection are located here, and the videos I contributed are below.

Building and Deploying Web Sites with ASP.NET MVC 4

Watch the video on Channel 9

Disclaimer here: While recording this video I neglected to mention that you will need to properly configure your connection strings.  I inadvertently used two data contexts pointed at the same database, you’ll want to NOT do that!

Building a Service Layer with ASP.NET Web API

Watch the video on Channel 9

Enjoy!

VS2012 Code Snippet for Test Methods

I don’t post about unit testing, but when I do, lather, rinse, repeat.

Here’s a snippet to generate a AAA-friendly test method that can be invoked by typing aaa and then pressing tab. Better if you do it in a test class #JustSaying.  Tested in VS2012, works here Smile. The great thing about VS2012 – and to be honest I’m not sure what version this awesome was introduced – you can edit code snippets on the fly in Visual Studio and test them as you save them, without closing the file or having to restart Visual Studio.  Brilliant. I have been doing the VS restart for years, and just tripped over this feature.

Oh, right, the code snippet!

(View Gist on GitHub)

This snippet is based on Roy Osherove’s recommended test naming convention/theories. There’s no general consensus on what constitutes the “correct” test name, but this is pretty sound as far as conventions go.

A Comparison of Asp.Net MVC Templates

Visual Studio 2012 and the Asp.Net refresh (2012.2) have introduced a number of new and refreshed templates to help bootstrap your project as you turn up a new MVC 4 site.  This post breaks down the key items that are in each of the templates to help you get a better understanding of your starting point.

Structure, Feature and Element Comparison

The template names are across the top, and the items included in the template in the leftmost column.

  Empty Basic Internet Intranet Mobile
Folder Structure          
    Controllers, Models, Views, App_Start, App_Data     X     X     X     X     X
    Content, Scripts       X     X     X     X
    Views\Shared       X     X     X     X
Project Elements          
    Global.asax, Web.Config, Packages.Config     X     X     X     X     X
    FilterConfig, RouteConfig, WebApiConfig     X     X     X     X     X
    BundleConfig       X     X     X     X
    AuthConfig         X    
    _ViewStart, _Layout and Error Pages       X     X     X     X
    Sample Home Controller & Views         X     X     X
Notable Third-Party Features          
    Packages Installed     11     23     34     25     28
    jQuery, jQuery UI       X     X     X     X
    jQuery Mobile             X
    KnockoutJS, Modernizer, Validation       X     X     X     X
    EntityFramework       X     X     X     X
Authentication and Authorization          
    Sample Controller         X       X
    Models, EF DbContext Samples         X       X
    Supporting “Simple” Provider & ActionFilter         X       X
    Support for External OAuth         X       X
    Auth via Active Directory (Azure or Windows)           X  

And Then Again, In English

Taking a look at the templates from a more pragmatic perspective, let’s consider how you’d actually use them and the situations where they’d be most appealing.

  • Empty – This is the barebones project with enough of the MVC bits wired so that you can work on the Asp.Net stack. If you are looking for a clean slate, this is it. You can leverage the conventions of the framework, choose your client-side libraries, build your own templates, and create your controllers and views from scratch.
  • Basic – If you’re good with the default selection of scripts and templates – jQuery and jQuery UI are installed for you – the rest of the pieces are in place for you to pick up and start developing. This project type adds a basic template (your layout page) and an error page with no styling.  There’s more of a canvas here, with a little less legwork than the empty template.
  • Internet – This is the bells and whistles edition. Sample controllers, local accounts and third-party authentication, a complete style makeover and more. You can use this to build a decent looking CRUD site, just be prepared for 1984-style conformity.  There’s also a wealth of JavaScript libraries to help build a great end-user experience as you learn the MVC Framework.
  • Intranet – The biggest differentiator for this template from the Internet version is the absence of accounts and authorization. Instead, the project ships with a read me with links on how to configure Active Directory and integrated sign on. This is especially great if you’re working with Azure and corporate accounts where users have IE installed – you get single sign-on to the app.
  • Mobile – While all the template types support alternate views which could be used for mobile support, this project comes ready to target mobile browsers. I won’t get into the debate of responsive design vs. dedicated sites here, but certainly if you are trying to create a context-centric, mobile-specific experience, this is the easiest place to start.

Not Mentioned In Today’s Broadcast

There are notably three project types missing from the mix: Single Page Application, Web API and the newly introduced Facebook Application. These each a have specific function in the web development world and are worth considering individually; I’ll break them down in another post.

What’s in A Name?

While I’ve spelled out the features of MVC projects that are included in each of the templates, I want to also say that if there is something that you would like included in a template that doesn’t have it by default, it’s still pretty easy to add most in.  Many of the items above can be added with a right-click –> “New Something…” or by installing a package via NuGet.

And, Next on the Docket

All that’s left now to do is to poke around with the templates. Download Visual Studio 2012 from the Asp.Net MVC homepage to get all the bits you need to start building sites. You can get the template refresh from the vNext site. Finally, push through some of the tutorials and get an idea of what you can do with the MVC Framework!

Diving deeper? Try these:

Bootstrapping Asp.Net MVC–Introduction to Twitter.Bootstrap.Mvc4

I’m continuing my series in exploring Bootstrap integration with the Mvc Framework – part of the Asp.Net stack – and in this entry we’re going to be looking at a helper package that you can install in seconds to kickstart a project.  Covered in this video are:

  • Installing from NuGet
  • Forking from GitHub, building locally and using the latest bits (or contributing!)
  • Navigation routes
  • Auto-scaffolded views for CRUD operations


Getting the Latest Stable Bits

One thing I didn’t mention in the video is that you don’t have to build the packages locally to get the latest versions. Eric Hexter has a MyGet feed setup to help you out in this regard. imageFrom the Package Manager Console in Visual Studio, simply pop open the options and add a new package feed:

http://www.myget.org/F/erichexter/

This lets you install the package from MyGet if you want to expose features not yet posted to the primary NuGet feed.

Alternatively, you can use the NuGet Package Explorer (as I am in the image shown here) to browse through the packages on the feed. Primarily you’re going to be looking for “Bootstrap” or “Navigation” in the feed to pick up the relevant packages.

Detail All the Things!

I cover a lot of ground in the video and try to give you a sense of what is possible to do in only a few short minutes. If you want to dive deeper here are some resources to help you out as you explore Twitter’s Bootstrap library working with Asp.Net Mvc:

Have fun!

jQuery Script Map Causing Critical Error in jQuery 1.9.0

Script maps are a great addition to the debugging arsenal of any script developer. Even for those of us who are “consumers” of some of the libraries out there, the script maps will help us get at the details of why something is going sideways when we’re working with minified versions of the code. 

Without the map, it has been difficult to find the correlating code in the original file. Elijah Manor does a great job at going over how to take advantage of script map support and it’s benefits in jQuery 1.9.0.

Minification in MVC4 and Critical Errors from the jQuery Script Map

There is a chance that you’ll run into this if you’re dropping code in Visual Studio 2012 on Win 8 with Asp.Net MVC, using bundling and minification:

JavaScript critical error at line 1, column 11 in http://localhost:0000Scripts/jquery-1.9.0.min.map

SCRIPT1004: Expected ‘;’

If this is the case, check to see that your wildcard isn’t to greedy. For example, if you have something like this set up in your BundleConfig.cs:

    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-1.*"));

…you’re telling the bundling engine to grab anything matching the script “jquery-1.anything”, and as a great optimization, the MVC Framework is smart enough to grab only one of library.js or library.min.js, and it prefers the min.js for you.  The downside here is that the bundle builder is using a prefix match here, and it seems to be picking up the .map file as well. This seems to be inadvertently causing the critical error mentioned above (map files aren’t to be shipped to the client as part of the request).

The Fix is In

The good thing is that you’re not stuck on wildcards, and it’s likely better to be using the semantic versioning replacement token (especially with the jQuery libraries).  Update your bundle to the following:

    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-{version}.js"));

The {version} token is a replacement that does a best match against the file according to SemVer.  Now, instead of all the files getting added, and the risk of files being added multiple times, we get a smarter match on the library we are requesting for bundling and minification.

Upgrading to jQuery 1.9.0 Starts Giving you Unhandled Exception Errors

I am running Windows 8, Visual Studio 2012 and working with Asp.Net MVC4. My upgrade was from jQuery 1.8.2 to jQuery 1.9.0 when this error surfaced.

If you upgrade an MVC project to the latest jQuery bits, you man run into an error similar to the following:

Unhandled exception at line 115, column 5 in http://localhost:0000/Scripts/jquery.unobtrusive-ajax.js

0x800a01b6 – JavaScript runtime error: Object doesn’t support property or method ‘live’

There have been a number of methods that were deprecated in the library some time ago, and now jQuery 1.9.0 is executing on those changes and has removed the methods for good. You can read more about the changes on the jQuery site.

This doesn’t leave you stranded…the team has graciously provided a migration path for those who want to take advantage of the new library enhancements, but still need to maintain legacy code.  The unobtrusive ajax script in our MVC projects are still calling some of these deprecated methods, so we need to take advantage of this offering.

To add backwards compatibility to our project, we simple have to drop into the Package Manager Console and type the command:

PM> Install-Package jQuery.Migrate

 

Tada!