Skip to content

Aspnetmvc articles

Differences between Azure Functions v1 and v2 in C#  

I’ve been messing around in the .NET ecosystem again and have jumped back in with Azure Functions (similar to AWS Lambda) to get my blog onto 99% static hosting. I immediately ran into the API changes between v1 and v2 (currently in beta).

These changes are because v1 was based around .NET 4.6 using WebAPI 2 while the v2 is based on ASP.NET Core which uses MVC 6. There are some guides around to converting but none in the pure context of Azure Functions.

I’ll illustrate with a PageViewCount sample that uses Table Storage to retrieve and update a simple page count.

v1 (.NET 4.61 / WebAPI 2)

[FunctionName("PageView")]
public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get")]HttpRequestMessage req, TraceWriter log)
{
    var page = req.MessageUri.ParseQueryString()["page"];
    if (String.IsNullOrEmpty(page))
        return req.CreateErrorResponse(HttpStatusCode.BadRequest, "'page' parameter missing.");

    var table = Helpers.GetTableReference("PageViewCounts");
    var pageView = await table.RetrieveAsync<PageViewCount>("damieng.com", page) ?? new PageViewCount(page) { ViewCount = 0 };
    var operation = pageView.ViewCount == 0
        ? TableOperation.Insert(pageView)
        : TableOperation.Replace(pageView);

    pageView.ViewCount++;
    await table.ExecuteAsync(operation);

    return req.CreateResponse(HttpStatusCode.OK, new { viewCount = pageView.ViewCount });
}

v2 (ASP.NET Core / MVC 6)

[FunctionName("PageView")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get")]HttpRequest req, TraceWriter log)
{
    var page = req.Query["page"];
    if (String.IsNullOrEmpty(page))
       return new BadRequestObjectResult("'page' parameter missing.");

    var table = Helpers.GetTableReference("PageViewCounts");
    var pageView = await table.RetrieveAsync<PageViewCount>("damieng.com", page) ?? new PageViewCount(page) { ViewCount = 0 };
    var operation = pageView.ViewCount == 0
        ? TableOperation.Insert(pageView)
        : TableOperation.Replace(pageView);

    pageView.ViewCount++;
    await table.ExecuteAsync(operation);

    return new OkObjectResult(new { viewCount = pageView.ViewCount });
}

Differences

The main differences are that:

  1. The return types are now the simpler IActionResult/ObjectResult objects rather than extension methods off of HttpRequestMessage (so, easier to mock/create custom ones)
  2. The input is the HttpRequest object rather than HttpResponseMessage (easier to get query parameters)

If you get an error about ‘Can not create abstract class’ when executing your function then you are trying to use the wrong one in the wrong environment!

Helpers

Both classes above use a small helper class to take care of Table Storage which doesn’t have the nicest to use API. A wrapper much like a data context that ensures the right types go to the right table names might be an even better options.

static class Helpers
{
    public static CloudStorageAccount GetCloudStorageAccount()
    {
        var connection = ConfigurationManager.AppSettings["DamienGTableStorage"];
        return connection == null 
            ? CloudStorageAccount.DevelopmentStorageAccount
            : CloudStorageAccount.Parse(connection);
    }

    public static CloudTable GetTableReference(string name)
    {
        return GetCloudStorageAccount().CreateCloudTableClient().GetTableReference(name);
    }

    public static async Task<T> RetrieveAsync<T>(this CloudTable cloudTable, string partitionKey, string rowKey) 
       where T:TableEntity
    {
        var tableResult = await cloudTable.ExecuteAsync(TableOperation.Retrieve(partitionKey, rowKey));
        return (T)tableResult.Result;
    }
}

To compile

If you want to compile this or maybe you were just looking for code to do a simple page counter here’s the missing TableEntity class;

public class PageViewCount : TableEntity
{
    public PageViewCount(string pageName)
    {
        PartitionKey = "damieng.com";
        RowKey = pageName;
    }

    public PageViewCount() { }
    public int ViewCount { get; set; }
}

[)amien

ASP.NET MVC preview available  

The first public preview of Microsoft’s ASP.NET MVC (model view controller) framework is now available.

Download ASP.NET 3.5 Extensions (EXE) (3.7 MB)

Download MVC Toolkit (ZIP) (400 KB)

The project takes cues from Ruby on Rail’s success and looks to address dissatisfaction with the testability and maintainability of WebForms applications and provides an alternative approach that is centered around views, models, controllers with a clear separation of concern and the ability to mock test the individual elements.The official documentation is online and there is a great four-part series over at Scott Guthrie’s blog which covers:

Phil Hack and Rob Conery are both now at Microsoft and working on the framework, they have some interesting things to say on it too:

A few other people have already written about the subject too:

Most of the examples and many of the routines/helpers fail to encode output which opens them up to HTML and script injection vulnerabilities. Remember to HttpUtility.HtmlEncode output and use Reflector if you’re unsure whether a function is encoding correctly.

The CTP requires Visual Studio 2008 to get the most out if it so either head over to MSDN Subscriber Downloads or grab a 90-day trial edition if you don’t already have it installed.

[)amien

Observations on Microsoft MVC for ASP.NET  

Anyone who’s tried to develop large complex web sites with ASP.NET has likely run into many problems covering the page and control life cycle, view state and post backs and subsequent maintainability including the difficulty in creating automated unit tests.

Microsoft, taking a cue from the popularity of Ruby on Rails and subsequent .NET related efforts such as MonoRail, are embracing the model-view-controller (MVC) pattern and developing something more suited to web development than WebForms which aimed to make web development as similar to Windows development as possible (despite the major underlying differences in architecture).

The prototype, currently named System.Web.Mvc or Microsoft.Web.Scalene depending on where you look, is headed by Scott Guthrie with both Phil Haack and Scott Hanselman involved (sounds like a dream project and team to be involved with) and a preview release (“drop”) is due within the coming weeks.

Gurthrie and Hanselman presented Microsoft MVC at the Alt.Net conference which revealed some interesting details buried in the video, my rough observations and notes based on the prototype they showed follows:

Philosophy

  • Don’t repeat yourself
  • Highly extensible & pluggable
  • Use generics to achieve strong-typing without code generation
  • Good performance, fast enough for large-scale sites
  • Separation of concern for maintainability
  • Clean URLs in and out
  • Clean HTML

Extensible

  • Interfaces used extensively
  • No sealed classes
  • Plug-in points for view engines (e.g. MonoRail’s NVelocity, Brail)
  • Support for Inversion of Control (IoC) engines (e.g. Windsor, StructureMap, Spring.NET)

Compatibility

  • Runs on the .NET 2.0 CLR
  • Some helper classes require .NET 3.5 (extension methods)
  • Normal Request, Response objects (via interfaces for mocking)
  • Does not support postback (form runat=”server”)
  • Supports MasterPages, DataBinding, CodeBehind
  • Existing .aspx’s are blocked using web.config

Visual Studio

  • Solution templates for web project and unit testing
  • Full designer & IntelliSense integration

Flow

  • Route -> ControllerFactory -> Controller -> Action -> ViewEngine -> View

Routing

  • Routes can be defined dynamically and support RegEx URL matching
  • IControllerFactory pops out the required IController
  • Routing is case insensitive by default
  • Support REST, blog engine, Jango style mappings etc. default is /controller/action/parameters

Controllers

  • FrontController style
  • IController exposes:
    • Execute(IHttpContext context, RouteData routeData)
    • IViewEngine ViewEngine property
  • Some implementations available, all with virtual methods:
    • ControllerBase (adds dispatching)
    • Controller (Populate parameters into ViewData[“key”])
    • Controller<T> (Populates parameters by making ViewData type T)
  • Attributes
    • [ControllerAction] attribute to expose methods as actions (secure default behaviour by not exposing helper methods)
    • Attribute for output caching
    • [ControllerAction(DefaultAction=true)] to override default method of Index

Parameters (to the controller)

  • Automatically parsed where a TypeConverter exists
  • Future versions will support more complex serialization of types
  • Can be nullable – use null coalesce operator for defaults

View Engine

  • IViewEngine
    • IView LoadView(string viewName)
  • Implementations include:
    • WebFormViewEngine

Views

  • IView
    • virtual void RenderView(object data)
  • Implementations include:
    • ViewPage – pick up parameters from ViewData[“”] in conjunction with Controller
    • ViewPage<T> pick up parameters from ViewData as type T in conjunction with Controller<T>

HTML

  • Clean HTML generation (have they sorted out the id mangling by MasterPages/INamingContainer?)
  • Static Html class supports Link, PagingLinks and Url methods
  • Map to action names using Lambda expressions to ensure follows refactoring, e.g.
    string url – Html.Link<ProductController>(controller =>controller.Edit(4);
  • Is there a way to follow the default action?

Model/data

  • Pagination extension methods extend IQueryable for getting pages of data (skip, limit)
  • Pattern for view-update-view cycle
  • Object property to form field id mapping available and pluggable, allows
    • product.UpdateFrom(Request.Form)

Testing

  • Easy to write tests by using mock objects (request, response)
  • Unit testing framework project (NUnit, MBUnit, xUnit.NET)

Finally

  • What’s with ScottGu’s nametag, can the show’s organisers not afford anything more than a PostIt note?
  • What cool software is Scott Hanselman using to do the screencast video/zoom/overlay/highlighting?

[)amien