Maarten Balliauw {blog}

ASP.NET, ASP.NET MVC, Windows Azure, PHP, ...

NAVIGATION - SEARCH

Windows Azure Tools for Eclipse for PHP developers

Pfew! Finally I can spread the word on this! While working on the Windows Azure SDK for PHP, I had the opportunity to test-drive the development builds of the WIndows Azure Tools for Eclipse. Today, the project has been released officially at www.windowsazure4e.org. Windows Azure Tools for Eclipse provides a series of wizards and utilities that allow developers to write, debug, and configure for and deploy PHP applications to Windows Azure.

image

The plug-in also bundles the existing Windows Azure SDK for PHP, which was introduced a few months ago. This SDK provides a simple API for PHP developers who use the Windows Azure storage component, making it very easy to use the blob, queue and table data storage features. Just visit the project site at http://phpazure.codeplex.com/.

Some labs are available to help you get started with PHP on the WIndows Azure platform: http://www.windowsazure4e.org/learn/

Upcoming sessions on Azure, PHP and ASP.NET

It’s going to be a filled end of 2009… There’s Microsoft PDC which I will be attending and will probably cause me some sleepless nights (both due to jetlag and due to all the new stuff that will be released). Next to that, I’ll also be doing some sessions in the next few weeks. Here’s a list…

Date

Event

28 october 2009

PHPBenelux Meeting: PHP and Microsoft technologies

I’ll be doing two sessions here:

· PHP and Silverlight, together with Kevin Dockx
“This session covers the basics of Microsoft Silverlight and demonstrates how PHP developers can benefit from developing rich client-side components that run in the web browser using Silverlight and PHP.”

· Make Web not War, together with Katrien De Graeve
“Microsoft will present the array of initiatives in the company to better support and integrate with PHP and give you an introduction on Windows Azure and its support for PHP in the cloud.”

More info? www.phpbenelux.eu

4 november 2009

First Azure User Group Belgium (AZUG.be) meeting

I’ll be doing an introductory session to Microsoft’s Azure platform. Yves Goeleven and Kurt Claeys will be showing off .NET services and provide more info on the AZUG.be. All of this followed by an open discussion.

Register now on www.azug.be!

24 november 2009

MSDN Live Meeting (Dutch)

Een ASP.NET-applicatie overbrengen naar Windows Azure
“Zet alles over naar the cloud! Met Windows Azure kunt u voordeel halen uit de cloud computing-infrastructuur voor hosting, computing en storage van uw applicaties. De sessie bevat talrijke demo’s, we brengen een bestaande ASP.Net-applicatie over naar hosting in Windows Azure en maken gebruik van Windows Azure storage”

More info on the MSDN pages!

Looking forward to see you at one of these events!

Recording of my session at Remix 2009 - ASP.NET MVC

On September 29, I did a session on ASP.NET MVC at Remix 2009 Belgium. All session recordings are now online, check the Remix09 site. Slides and code for my talk can be found in a previous blog post. The video material can be found below. Enjoy! And feel free to leave some comments!

kick it on DotNetKicks.com

ASP.NET MVC Wisdom

Abstract: "Building a Twitter clone in 60 minutes, featuring what's new in ASP.NET MVC 2 preview 1 and focusing on some of the core ASP.NET MVC features like security and routing."

Let me Bing that for you

Have you ever been bugged with stupid questions? Do you get tired of people asking stuff that is only one search engine query away? Chances are you answered both of these questions with “yes!”. Together with Phil Haack and Juliën Hanssens, I created LetMeBingThatForYou.com, a website that generates a search engine query for people who ask you questions they could easily answer by themselves.

Yes, the idea is a copy of LetMeGoogleThatForYou.com. However, we thought Bing deserved something similar. We even got Bing’s picture of the day working. How cool is that?

Find Chuck Norris

One last note: this project is not associated with Microsoft nor Bing. We’re doing this project for fun.

kick it on DotNetKicks.com

Leveraging ASP.NET MVC 2 futures “ViewState”

Let’s start this blog post with a confession: yes, I abused a feature in the ASP.NET MVC 2 futures assembly to fire up discussion. In my previous blog post, I called something “ViewState in MVC” while it is not really ViewState. To be honest, I did this on purpose, wanting to see people discuss this possibly new feature in MVC 2. Discussion started quite fast: most people do not like the word ViewState, especially when it is linked to ASP.NET MVC. As Phil Haack pointed out in a comment on my previous blog post, I used this foul word where it was not appropriate.

(…) I think calling it ViewState is very misleading. (…) what your serializing is the state of the Model, not the View. (…)

That’s the truth! But… how should we call this then? There is already something called ModelState, and this is something different. Troughout this blog post, I will refer to this as “Serialized Model State”, or “SMS” in short. Not an official abbreviation, just something to have a shared meaning with you as a reader.

So, SMS… Let’s use this in a practical example.

kick it on DotNetKicks.com

Example: Optimistic Concurrency

Concurrency between old train and updated train. Every developer who has worked on a business application will definitely have come to deal with optimistic concurrency. Data retrieved from the database has a unique identifier and a timestamp, used for optimistic concurrency control. When editing this data, the identifier and timestamp have to be associated with the client operation, requiring a persistence mechanism. This mechanism should make sure the identifier and timestamp are preserved to verify if another user has updated it since it was originally retrieved.

There are some options to do this: you can store this in TempData, in a Cookie or in Session state. A more obvious choice, however, would be a mechanism like “SMS”: it allows you to persist the model state on your view, allowing to retrieve the state of your model whenever data is posted to an action method. The fact that it is on your view, means that is linked to a specific request that will happen in the future.

Let’s work with a simple Person class, consisting of Id, Name, Email and RowState properties. RowState will contain a DateTime value when the database record was last updated. An action method fetching data is created:

[code:c#]

[HttpGet]
public ActionResult Edit(int id)
{
    // Simulate fetching Person from database
    Person initialPersonFromDatabase = new Person
    {
        Id = id,
        FirstName = "Maarten",
        LastName = "Balliauw",
        Email = "",
        RowVersion = DateTime.Now
    };
    return View(initialPersonFromDatabase);
}

[/code]

The view renders an edit form for our person:

[code:c#]

<h2>Concurrency demo</h2>

<% Html.EnableClientValidation(); %>
<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>

<% using (Html.BeginForm()) {%>
    <%=Html.Serialize("person", Model)%>

    <fieldset>
        <legend>Edit person</legend>
        <%=Html.EditorForModel()%>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>

<% } %>

[/code]

Let’s have a look at this view markup. <%=Html.EditorForModel()%> renders an editor for our model class Person. based on templates. This is a new feature in ASP.NET MVC 2.

Another thing we do in our view is <%=Html.Serialize("person", Model)%>: this is a HtmlHelper extension persisting our model to a hidden form field:

[code:c#]

<input name="person" type="hidden" value="/wEymwIAAQAAAP
////8BAAAAAAAAAAwCAAAARE12YzJWaWV3U3RhdGUsIFZlcnNpb249MS4wL
jAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1udWxsBQEA
AAAbTXZjMlZpZXdTdGF0ZS5Nb2RlbHMuUGVyc29uBAAAABo8Rmlyc3ROYW1
lPmtfX0JhY2tpbmdGaWVsZBk8TGFzdE5hbWU+a19fQmFja2luZ0ZpZWxkFj
xFbWFpbD5rX19CYWNraW5nRmllbGQbPFJvd1ZlcnNpb24+a19fQmFja2luZ
0ZpZWxkAQEBAA0CAAAABgMAAAAHTWFhcnRlbgYEAAAACEJhbGxpYXV3BgUA
AAAAqCw1nBkWzIgL" />

[/code]

Yes, this looks ugly and smells like ViewState, but it’s not. Let’s submit our form to the next action method:

[code:c#]

[HttpPost]
public ActionResult Edit([Deserialize]Person person, FormCollection form)
{
    // Update model
    if (!TryUpdateModel(person, form.ToValueProvider()))
        return View(person);

    // Simulate fetching person from database
    Person currentPersonFromDatabase = new Person
    {
        Id = person.Id,
        FirstName = "Maarten",
        LastName = "Balliauw",
        Email = "maarten@maartenballiauw.be",
        RowVersion = DateTime.Now
    };

    // Compare version with version from model state
    if (currentPersonFromDatabase.RowVersion > person.RowVersion)
    {
        // Concurrency issues!
        ModelState.AddModelError("Person", "Concurrency error: person was changed in database.");

        return View(person);
    }
    else
    {
        // Validation also succeeded
        return RedirectToAction("Success");
    }
}

[/code]

Let’s see what happens here…The previous model state is deserialized from the hidden field we created in our view, and passed into the parameter person of this action method. Edited form values are in the FormCollection parameter. In the action method body, the deserialized model is updated first with the values from the FormCollection parameter. Next, the current database row is retrieved, having a newer RowVersion timestamp. This indicates that the record has been modified in the database and that we have a concurrency issue, rendering a validation message.

Conclusion

“ViewState” (or “SMS” or whatever it will be called) is really a useful addition to ASP.NET MVC 2, and I hope this blog post showed you one example usage scenario where it is handy. Next to that, you are not required to use this concept: it’s completely optional. So if you still do not like it, then do not use it. Go with Session state, Cookies, hidden fields, …

kick it on DotNetKicks.com

Exploring the ASP.NET MVC 2 futures assemby

The future is cloudy! The latest preview of ASP.NET MVC 2, preview 2, has been released on CodePlex last week. All features of the preview 1 version are still in, as well as some nice novelties like client-side validation, single project areas, the model metadata model, … You can read more about these here, here and here.

Sure, the official preview contains some great features of which I’m already a fan: the model and validation metadata model is quite extensible, allowing the use of DataAnnotations, EntLib, NHibernate or your own custom validation logic in your application, while still being able to use standard model binders and client-side validation. Next to all this, a new version of the MVC 2 futures assembly was released on CodePlex. And oh boy, there’s some interesting stuff in there as well! Let’s dive in…

Quick note: the “piece de resistance” is near the end of this post. Also make sure to post your thoughts on this “piece”.

kick it on DotNetKicks.com

Controls

There’s not much that has changed here since my previous blog post on the MVC futures. Want to use a lightweight TextBox or Repeater control? Feel free to do so:

[code:c#]

<p>
    TextBox: <mvc:TextBox Name="someTextBox" runat="server" /><br />
    Password: <mvc:Password Name="somePassword" runat="server" />
</p>
<p>
    Repeater:
    <ul>
    <mvc:Repeater Name="someData" runat="server">
        <EmptyDataTemplate>
            <li>No data is available.</li>
        </EmptyDataTemplate>
        <ItemTemplate>
            <li><%# Eval("Name") %></li>
        </ItemTemplate>
    </mvc:Repeater>
    </ul>
</p>

[/code]

Asynchronous controllers

Yes, I also blogged about these before. Basically, asynchronous controllers allow you to overcome the fact that processing-intensive action methods may consume all of your web server’s worker threads, making your webserver a slow piece of software while it is on top-notch hardware.

When using asynchronous controllers, the web server schedules a worker thread to handle an incoming request. This worker thread will start a new thread and call the action method on there. The worker thread is now immediately available to handle a new incoming request again.

Get some REST!

Again: I already blogged on this one: REST for ASP.NET MVC SDK. This SDK now seems to become a part of the ASP.NET MVC core, which I really think is great! The REST for ASP.NET MVC SDK adds “discovery” functionality to your ASP.NET MVC application, returning the client the correct data format he requested. From the official documentation:

  1. It includes support for machine-readable formats (XML, JSON) and support for content negotiation, making it easy to add POX APIs to existing MVC controllers with minimal changes.
  2. It includes support for dispatching requests based on the HTTP verb, enabling “resource” controllers that implement the uniform HTTP interface to perform CRUD (Create, Read, Update and Delete) operations on the model.
  3. Provides T4 controller and view templates that make implementing the above scenarios easier.

Let’s come down to business: the REST SDK is handy because you do not have to care about returning a specific ActionResult: the SDK will automatically check whether a ViewResult, JsonResult, XML output or even an Atom feed is requested by the client. ViewData will automatically be returned in the requested format. Result: cleaner code, less mistakes. As long as you follow conventions of course.

Other stuff…

Yeah, I’m lazy. I also blogged on this one before. Check my previous blog post on the MVC futures for nice stuff like more action method selectors (like [AcceptAjax] and others), more HtmlHelper extensions for images, mailto links, buttons, CSS, … There’s more action filters as well, like [ContentType] which specifies the content-type headers being sent out with an action method.

There’s also donut caching, allowing you to cache all output for an action method except a specific part of the output. This allows you to combine cached views with dynamic content in quite an easy manner.

More new stuff: the CookieTempDataProvider, allowing you to turn of session state when using TempData. There’s also the [SkipBinding] attribute, which tells the ModelBinder infrasructure to bind all action method parameters except the ones decorated with this attribute.

ViewState!

ViewState gone evil! Got you there, right? The ASP.NET MVC team has been screaming in every presentation they gave in the past year that there was no such thing as ViewState in ASP.NE MVC. Well, there is now… And maybe, i will be part of the future MVC 2 release as well. Let’s first have a look at it and afterwards discuss this all…

On every view, a new HtmlHelper extension method named “Serialize” is present. This one can be used to create a hidden field inside a HTML form, containing a serialized version of an object. The extension method also allows you to pass a parameter specifying how the object should be serialized. The default option, SerializationMode.PlainText, simply serializes the object to a string and puts it inside of a hidden field. When using SerializationMode.Encrypted and/or SerializationMode.Signed, you are really using ASP.NET Webforms ViewState under the covers.

The call in your view source code is easy:

[code:c#]

<% using (Html.BeginForm()) {%>
    <%Html.Serialize("person", Model); %>
    <fieldset>
        <legend>Edit person</legend>
        <p>
            <%=Html.DisplayFor(p => Model.FirstName)%>
        </p>
        <p>
            <%=Html.DisplayFor(p => Model.LastName)%>
        </p>
        <p>
            <label for="Email">Email:</label>
            <%= Html.TextBox("Email", Model.Email) %>
            <%= Html.ValidationMessage("Email", "*") %>
        </p>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
<% } %>

[/code]

When posting this form back to a controller action, a new ModelBinder can be used: The DeserializeAttribute can be placed next to an action method parameter:

[code:c#]

[HttpPost]
public ActionResult Edit([Deserialize]Person person, string Email)
{
    // ...
}

[/code]

There you go: Person is the same object as the one you serialized in your view. Combine this with the RenderAction feature (yes, check my previous blog post on the MVC futures), and you have a powerful model for creating something like controls, which still follows the model-view-controller pattern mostly.

Now release the hounds: I think this new “ViewState” feature is cool. There are definitely situations where you may want to use this, but… Will it be a best practice to use this? What is your opinion on this?

kick it on DotNetKicks.com