Maarten Balliauw {blog}

ASP.NET MVC, Microsoft Azure, PHP, web development ...

NAVIGATION - SEARCH

SQL Azure Manager

image

A few days ago, the SQL Server Team announced the availability of three major CTP’s and several new upcoming projects in the SQL related family tree: SQL Server 2008 R2, SQL Server StreamInsight and SQL Azure. Now that last one is interesting: Microsoft will offer a 1GB or 10GB database server “in the cloud” for a good price.

Currently, SQL Azure is in CTP and will undergo some more development. Of course, I wanted to play with this, but… connecting to the thing using SQL Server management Studio is not the most intuitive and straightforward task. It’s more of a workaround. Juliën Hanssens, a colleague of mine, was going crazy for this. Being a good colleague, I poored some coffee tea in the guy and he came up with the SQL Azure manager: a community effort to quickly enable connecting to your SQL Azure database(s) and perform basic tasks.

SQL Azure Manager

And it does just that. Note that it is a first conceptual release. And that it is still a bit unstable. But it does the trick. At least at a bare minimum. And for the time being that is enough. Want to play with it? Check Juliën’s ClickOnce page!

Note that this thing will become open-soucre in the future, after he finds a good WF designer to do the main UI. Want to help him? Use the submit button!

kick it on DotNetKicks.com

Book review: Beginning ASP.NET MVC 1.0

image It sure looks like August 2009 is the month in which I found multiple books on my doormat for review. Last week I did ASP.NET 3.5 CMS Development, this time I’ll be reviewing a competitor to my own book on ASP.NET MVC, ASP.NET MVC 1.0 Quickly: Simone Chiaretta and Keyvan Nayyeri’s “Beginning ASP.NET MVC 1.0”.

Let’s start with the “official book overview”, which I usually copy-paste from Amazon. This book will learn you:

  • The intricacies of the Model View Controller (MVC) pattern and its many benefits
  • The fundamentals of ASP.NET MVC and its advantages over ASP.NET Web Forms
  • Various elements in ASP.NET MVC including model, view, controller, action filters, and routing
  • Unit testing concepts, Test-Driven Development (TDD), and the relationship between unit testing and the MVC pattern
  • How to unit test an ASP.NET MVC application
  • Details about authentication, authorization, caching, and form validation in ASP.NET MVC
  • The ins and outs of AJAX and client-side development in ASP.NET MVC
  • Ways to extend ASP.NET MVC

After doing some reading over the weekend, I can say this book is great! It follows a different path than most of the ASP.NET MVC books out there today: of course it offers the basic introduction to ASP.NET MVC, it talks about models, controllers, views, …, however: it also covers more advanced topics like dependency injection (using NInject).

Near the end of the book, some case studies are discussed: first a blog engine is built from ground up. The second case study is about building a photo gallery application.

If you need a book which gives you the basics and some more advanced topics, Beginning ASP.NET MVC 1.0 is really for you. I liked reading it, and Simone and Keyvan have done a great job in explaining all there is to the great ASP.NET MVC framework. Looking forward to read more books by these guys! And to make sure my own sales figures do not drop: if you are a fan of a quick-start book on ASP.NET MVC, go buy ASP.NET MVC 1.0 Quickly :-)

Oh and by the way, a sample chapter is also available at the publisher’s site.

ASP.NET MVC Chained Controller Factory

My last post on the REST for ASP.NET MVC SDK received an interesting comment… Basically, the spirit of the comment was: “There are tons of controller factories out there, but you can only use one at a time!”. This is true. One can have an IControllerFactory for MEF, for Castle Windsor, a custom one that creates a controller based on the current weather, … Most of the time, these IControllerFactory  implementations do not glue together… Unless you chain them!

kick it on DotNetKicks.com

Chaining IControllerFactory

The ChainedControllerFactory that I will be creating is quite easy: it builds a list of IControllerFactory instances that may be able to create an IController and asks them one by one to create it. The one that can create it, will be the one that delivers the controller. In code:

[code:c#]

public class ChainedControllerFactory : IControllerFactory
{
    const string CHAINEDCONTROLLERFACTORY = "__chainedControllerFactory";

    protected List<IControllerFactory> factories = new List<IControllerFactory>();

    public ChainedControllerFactory Register(IControllerFactory factory)
    {
        factories.Add(factory);
        return this;
    }

    public IController CreateController(RequestContext requestContext, string controllerName)
    {
        IController controller = null;
        foreach (IControllerFactory factory in factories)
        {
            controller = factory.CreateController(requestContext, controllerName);
            if (controller != null)
            {
                requestContext.HttpContext.Items[CHAINEDCONTROLLERFACTORY] = factory;
                return controller;
            }
        }

        return null;
    }

    public void ReleaseController(IController controller)
    {
        IControllerFactory factory =
            HttpContext.Current.Items[CHAINEDCONTROLLERFACTORY] as IControllerFactory;
        if (factory != null)
            factory.ReleaseController(controller);
    }
}

[/code]

We have to register this one as the default IControllerFactory in Global.asax.cs:

[code:c#]

protected void Application_Start()
{
    ChainedControllerFactory controllerFactory = new ChainedControllerFactory();
    controllerFactory
        .Register(new DummyControllerFactory())
        .Register(new OnlyHomeControllerFactory())
        .Register(new DefaultControllerFactory());

    ControllerBuilder.Current.SetControllerFactory(controllerFactory);

    RegisterRoutes(RouteTable.Routes);
}

[/code]

Note: the DummyControllerFactory and the OnlyHomeControllerFactory are some sample, stupid IControllerFactory implementations.

Caveats

There is actually one caveat to know when using this ChainedControllerFactory: not all controller factories out there follow the convention of returning null when they can not create a controller. The ChainedControllerFactory expects null to determine if it should try the next IControllerFactory in the chain.

Download source code

You can download example source code here: MvcChainedControllerFactory.zip (244.37 kb) (sample uses MVC 2, code should work on MVC 1 as well)

kick it on DotNetKicks.com

REST for ASP.NET MVC SDK

REST - Representational State Transfer Earlier this week, Phil Haack did a post on the newly released REST for ASP.NET MVC SDK. I had the feeling though that this post did not really get the attention it deserved. I do not have the idea my blog gets more visitors than Phil’s, but I’ll try to give the SDK some more attention by blogging an example. But first things first…

kick it on DotNetKicks.com

What is it?

“REST for ASP .NET MVC is a set of capabilities that enable developers building a website using ASP .NET MVC to easily expose a Web API for the functionality of the site. “

Ok then. Now you know. It will get more clear after reading the next topic.

When should I use this?

There are of course features in WCF that enable you to build REST-ful services, but…

In many cases, the application itself is the only reason for development of the service. In other words, when the only reason for the service’s existence is to service the one application you’re currently building, it may make more sense  would stick with the simple case of using ASP.NET MVC. (Phil Haack)

Quickly put: why bother setting up a true WCF service layer when the only reason for that is the web application you are building?

Let me add another statement. Add a comment if you disagree:

In many cases, you are building an ASP.NET MVC application serving HTML, and building a WCF layer exposing XML and/or JSON using REST, so you can use this in your Ajax calls and such. Why build two or three things displaying the same data, but in another format?

This is where the REST for ASP.NET MVC SDK comes in handy: it 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.

An example…

… a simple ASP.NET MVC application!

Let’s say you have an application where you can create, read, update and delete your own name and firstname. We have a simple model for that:

[code:c#]

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

[/code]

We can do CRUD operations on this in our ASP.NET MVC application, using the action methods in our PersonController:

[code:c#]

public class PersonController : Controller
{
    protected List<Person> Data
    {
        get
        {
            if (Session["Persons"] == null)
            {
                Session["Persons"] = new List<Person>();
            }
            return (List<Person>)Session["Persons"];
        }
    }

    //
    // GET: /Person/

    public ActionResult Index()
    {
        return View(Data);
    }

    //
    // GET: /Person/Details/5

    public ActionResult Details(int id)
    {
        return View(Data.FirstOrDefault(p => p.Id == id));
    }

    //
    // GET: /Person/Create

    public ActionResult Create()
    {
        return View(new Person());
    }

    //
    // POST: /Person/Create

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Person person)
    {
        try
        {
            person.Id = Data.Count + 1;
            Data.Add(person);

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

    //
    // GET: /Person/Edit/5

    public ActionResult Edit(int id)
    {
        return View(Data.FirstOrDefault(p => p.Id == id));
    }

    //
    // POST: /Person/Edit/5

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, FormCollection collection)
    {
        try
        {
            Person person = Data.FirstOrDefault(p => p.Id == id);
            UpdateModel(person, new string[] { "FirstName", "LastName" }, collection.ToValueProvider());
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
}

[/code]

Any questions on this? Read the book :-)

… get some REST for FREE!

Like all “free” things in life, there’s always at least a little catch. “Free” in this case means:

  1. Adding a reference to System.Web.Mvc.Resources.dll provided by the REST for ASP.NET MVC SDK
  2. Registering another controller factory in Global.asax.cs (more on that later)
  3. Adding the [WebApiEnabled] to every controller and/or action method you want to expose via REST.

The first step is quite straightforward: get the bits from CodePlex, compile, and add it as a reference in your MVC project. Next, open Global.asax.cs and add the following in Application_Start:

[code:c#]

protected void Application_Start()
{
    // We use this hook to inject our ResourceControllerActionInvoker
    // which can smartly map HTTP verbs to Actions
    ResourceControllerFactory factory = new ResourceControllerFactory();
    ControllerBuilder.Current.SetControllerFactory(factory);

    // We use this hook to inject the ResourceModelBinder behavior
    // which can de-serialize from xml/json formats
    ModelBinders.Binders.DefaultBinder = new ResourceModelBinder();

    // Regular register routes
    RegisterRoutes(RouteTable.Routes);
}

[/code]

What we do here is tell ASP.NET MVC to create controllers using the ResourceControllerFactory provided by the REST for ASP.NET MVC SDK.

Next: add the [WebApiEnabled] to every controller and/or action method you want to expose via REST. And that’s about it. Here’s what I get in my application if I browse to http://localhost:2681/Person:

image

Nothing fancy here, just a regular ASP.NET MVC application. But wait, let’s now browse to http://localhost:2681/Person?format=Xml:

image

Cool, no? And we only added 4 lines of code. But there’s more! I can also browse to http://localhost:2681/Person?format=Json and get JSON data returned. But that’s not all. There’s more!

  • You can add custom FormatHandler classes and, for example, provide one that handles RSS data.
  • There’s no need to always add the query string variable “format”: you can also specify the type of content you want in your HTTP request, by setting the HTTP “Accept” header. For example, if I set the Accept header to “application/json,text/xml”, REST for ASP.NET MVC will provide me with JSON if possible, and if not, it will send me XML. This approach is particularly useful when working with AJAX calls on your view.

Downloads

Here’s a list of downloads:

kick it on DotNetKicks.com

Book review: ASP.NET 3.5 CMS Development

ASP.NET 3.5 CMS Development From time to time, the people at Packt Publishing send me a free book, fresh of the presses, and ask nicely if I want to read it and write a review on my blog. Last week, I received their fresh ASP.NET 3.5 CMS Development book, written by Curt Christianson and Jeff Cochran, both Microsoft MVP (ASP.NET and IIS).

According to the website, the book aims at learning people how to build a CMS. Now, I know from writing my ASP.NET MVC 1.0 Quickly book that these texts are written mostly by marketing people.

This step-by-step tutorial shows the reader how to build an ASP.NET Content Management System from scratch. You will first learn the basics of a content management system and how to set up the tools you need to build your site. Then, you start building your site, setting up users, and adding content to your site. You will be able to edit the content of your site and also manage its layout all by yourself. Towards the end, you will learn to manage your site from a single point and will have all the information you need to extend your site to make it more powerful.

Filled with plenty of code snippets and screen images to keep you on track as well as numerous additional samples to show you all the exciting alternatives to explore, this book prepares you for all the challenges you can face in development. 

Ok, it is true: this book will show you how to build a content management system in ASP.NET 3.5. However, if you are a developer working with ASP.NET for several years and the CMS part is the reason you are buying this book, you will be a bit disappointed. Don’t get me wrong, the book is good for another audience: if you are making your first steps in ASP.NET development and want to learn how things like datasources, n-tier development, membership provider, extensibility, … work, by example, this book is actually pretty good at that. Curt and Jeff managed to squeeze in about all commonly used ASP.NET features using only one example application that is built from ground up.

Conclusion: probably not the book for experienced developers, but an ideal “large, example-driven tutorial” for beginning development with ASP.NET 3.5.

Signed Access Signatures and PHP SDK for Windows Azure

PHP SDK for Windows Azure The latest Windows Azure storage release featured a new concept: “Shared Access Signatures”. The idea of those is that you can create signatures for specific resources in blob storage and that you can provide more granular access than the default “all-or-nothing” approach that is taken by Azure blob storage. Steve Marx posted a sample on this, demonstrating how you can provide read access to a blob for a specified amount of minutes, after which the access is revoked.

The PHP SDK for Windows Azure is now equipped with a credentials mechanism, based on Signed Access Signatures. Let’s see if we can demonstrate how this would work…

kick it on DotNetKicks.com

A quick start…

Let’s take Steve’s Wazdrop sample and upload a few files, we get a set of permissions:

https://wazdrop.blob.core.windows.net/files/7bf9417f-c405-4042-8f99-801acb1ea494?st=2009-08-17T08%3A52%3A48Z&se=2009-08-17T09%3A52%3A48Z&sr=b&sp=r&sig=Zcngfaq60OXtLxcsTjmPXUL9Q4Rj3zTPmW40eARVYxU%3D

https://wazdrop.blob.core.windows.net/files/d30769f6-35b9-4337-8c34-014ff590b18f?st=2009-08-17T08%3A54%3A19Z&se=2009-08-17T09%3A54%3A19Z&sr=b&sp=r&sig=Mm8CnmI3XXVbJ6y0FN9WfAOknVySfsF5jIA55drZ6MQ%3D

If we take a detailed look, the Azure account name used is “wazdrop”, and we have access to 2 files in Steve’s storage account, namely “7bf9417f-c405-4042-8f99-801acb1ea494” and “d30769f6-35b9-4337-8c34-014ff590b18f” in the “files” container.

Great! But if I want to use the PHP SDK for Windows Azure to access the resources above, how would I do that? Well, that should not be difficult. Instantiate a new Microsoft_Azure_Storage_Blob client, and pass it a new Microsoft_Azure_SharedAccessSignatureCredentials instance:

[code:c#]

$storageClient = new Microsoft_Azure_Storage_Blob('blob.core.windows.net', 'wazdrop', '');
$storageClient->setCredentials(
    new Microsoft_Azure_SharedAccessSignatureCredentials('wazdrop', '')
);

[/code]

One thing to notice here: we do know the storage account (“wazdrop”), but not Steve’s shared key to his storage account. Which is good for him, otherwise I would be able to manage all containers and blobs in his account.

The above code sample will now fail every action I invoke on it. Every getBlob(), putBlob(), createContainer(), … will fail because I cannot authenticate! Fortunately, Steve’s application provided me with two URL’s that I can use to read 2 blobs. Now set these as permissions on our storage client:

[code:c#]

$storageClient->getCredentials()->setPermissionSet(array(
    'https://wazdrop.blob.core.windows.net/files/7bf9417f-c405-4042-8f99-801acb1ea494?st=2009-08-17T08%3A52%3A48Z&se=2009-08-17T09%3A52%3A48Z&sr=b&sp=r&sig=Zcngfaq60OXtLxcsTjmPXUL9Q4Rj3zTPmW40eARVYxU%3D',
    'https://wazdrop.blob.core.windows.net/files/d30769f6-35b9-4337-8c34-014ff590b18f?st=2009-08-17T08%3A54%3A19Z&se=2009-08-17T09%3A54%3A19Z&sr=b&sp=r&sig=Mm8CnmI3XXVbJ6y0FN9WfAOknVySfsF5jIA55drZ6MQ%3D'
));

[/code]

We now have instructed the PHP SDK for Windows Azure that we have read permissions on two blobs, and can now use regular API calls to retrieve these blobs:

[code:c#]

$storageClient->getBlob('files', '7bf9417f-c405-4042-8f99-801acb1ea494', 'C:\downloadedfile1.txt');
$storageClient->getBlob('files', 'd30769f6-35b9-4337-8c34-014ff590b18f', 'C:\downloadedfile2.txt');

[/code]

The PHP SDK for Windows Azure will now take care of checking if a permission URL matches the call that is being made, and inject the signatures automatically.

A bit more advanced…

The above sample did demonstrate how the new Signed Access Signature is implemented in PHP SDK for Windows Azure, but it did not yet demonstrate all “coolness”. Let’s say the owner of a storage account named “phpstorage” has a private container named “phpazuretestshared1”, and that this owner wants to allow you to put some blobs in this container. Since the owner does not want to give you full access, nor wants to make the container public, he issues a Shared Access Signature:

http://phpstorage.blob.core.windows.net/phpazuretestshared1?st=2009-08-17T09%3A06%3A17Z&se=2009-08-17T09%3A56%3A17Z&sr=c&sp=w&sig=hscQ7Su1nqd91OfMTwTkxabhJSaspx%2BD%2Fz8UqZAgn9s%3D

This one allows us to write in the container “phpazuretest1” on account “phpstorage”. Now let’s see if we can put some blobs in there!

[code:c#]

$storageClient = new Microsoft_Azure_Storage_Blob('blob.core.windows.net', 'phpstorage', '');
$storageClient->setCredentials(
    new Microsoft_Azure_SharedAccessSignatureCredentials('phpstorage', '')
);

$storageClient->getCredentials()->setPermissionSet(array(
    'http://phpstorage.blob.core.windows.net/phpazuretestshared1?st=2009-08-17T09%3A06%3A17Z&se=2009-08-17T09%3A56%3A17Z&sr=c&sp=w&sig=hscQ7Su1nqd91OfMTwTkxabhJSaspx%2BD%2Fz8UqZAgn9s%3D'
));

$storageClient->putBlob('phpazuretestshared1', 'NewBlob.txt', 'C:\Files\dataforazure.txt');

[/code]

Did you see what happened? We did not specify an explicit permission to write to a specific blob. Instead, the PHP SDK for Windows Azure determined that a permission was required to either write to that specific blob, or to write to its container. Since we only had a signature for the latter, it chose those credentials to perform the request on Windows Azure blob storage.

kick it on DotNetKicks.com

Accessing ServiceConfiguration in FastCGI (PHP) web role

While working on a sample PHP application hosted on Windows Azure, I found that it is nearly impossible to retrieve information from the Windows Azure ServiceConfiguration.cscfg file. Also, it is impossible to write log messages to the Windows Azure Web Role. Well, both are not 100% impossible: you can imagine dirty hacks where you let a ASP.NET page do something from PHP and stuff like that. But how about a clean solution? How about… A PHP extension module?

kick it on DotNetKicks.com

I’ll not be going into detail on how this module was built, but there is a native C++ RoleManager implementation in the Windows Azure samples. Using the resources listed below, I managed to create a PHP extension module, wrapping this RoleManager. The result? You can now retrieve configuration values from the ServiceConfiguration.

[code:c#]

$appName = azure_getconfig(“AppName”);
$storageAccount = azure_getconfig(“StorageAccount”);

// etc.

[/code]

Next to this, logging is now also exposed: simply call azure_log() and you’re done:

[code:c#]

azure_log(AZURE_LOG_INFORMATION, “This is cool!”);
azure_log(AZURE_LOG_CRITICAL, “Critical errors are not cool…”);

// etc.

[/code]

Oh, you want to have the path where a localStorage is available? (see here for info)

[code:c#]

$rootPath = azure_getlocalresourcepath('teststore');
$pathMaxSizeInMb = azure_getlocalresourcepathsize('teststore');

// etc.

[/code]

Want to use it in your own PHP applications hosted on Windows Azure?

  • Download the php_azure.dll (see below) and make sure you have it in your /path/to/php/ext folder
  • Register the extension in php.ini: extension=php_azure.dll

Downloads

Resources

The following links have been helpful in developing this:

kick it on DotNetKicks.com