Alexander Beletsky's Development Blog: 2012-03

MS SWIT 2012

The 22-23 of March this year I had a chance to participate biggest event organized by Microsoft Ukraine - MS SWIT 2012.


ms swit 2012

It's been almost two years ago I visited MS SWIT 2010. If the primary topic of last conference was cloud technologies - Azure, SQL etc. This time I would say the buzz was around Windows 8, Market Place and Metro-style applications. Of cause, there was still a lot of attention to Azure as well.

I really much enjoyed the Keynote of first day by Wolfgang Ebermann. Indeed, Microsoft opens pretty much interesting opportunities for developers on Windows 8 and Windows Phone markets. Not long time ago Ukraine officially is a part of MarketPlace, so no time to wait - go and create you first Metro style app. And with new Microsoft policies regarding adoption of open standards like HTLM5, EcmaScript - it looks really attractive to me.

Big attention was also about new recent releases like: Share Point, SQL Server Denali, Windows Server 8 etc. I would not say this is exactly interesting to me, since I more focus on web technologies, but it's always good to be aware what's going on around. First day of conference got a lot people moving around, so if you wanted to listen for some interesting speech you have to be in time to get free sit. Second day was not so overcrowded as for me, so the people who didn't come have to be sorry, cause Second day was much more interesting.

My talk was about new stuff in ASP.NET MVC4, with more focus to mobile web applications. That was the biggest audience I ever speak to. There was almost no free sits.. I don't know for sure it contained 150-200 people.. Huge!

Being much inspired by Steve Sanderson talk on TechDays 2012, I decided to make something similar. I came up with idea of simple mobile web application, namely it is a web client to http://asp.net portal and develop it just during the speech. I had several issue's there, first one I did a little more longer introduction and then some issues with internet that made me a little nervous and I lose tempo a bit. That forced me to skip the last part of talk regarding Offline mode for apps. Anyway, I hope I was able to show new sweet available stuff like CSS3 Media Queries, Display Modes and jQuery Mobile framework.


Thanks a lot for everyone who listened to me and came up with questions. I appreciate your attention and hope my talk was useful for you.


asp.net portal mobile

Regarding the app, I polished it a bit and going to release closer to the end of next week. The sources are hosted on https://github.com/alexanderbeletsky/aspnet.mobile, feel free to clone and send a pull request.

New in ASP.NET MVC4 Beta: Web API

This is a high level overview of new stuff that appeared within VS2011 release. So, let's briefly look inside. Today will take a look on changes appeared to Web API.

Web API

The biggest and most important change as for me is integration of Web API into ASP.NET. Web API is most known as WCF Web API - an attempt of .NET team build framework for creation of RESTfull services based on WCF infrastructure. There was several releases of WCF Web API made and general feedback from community was - "it's good enough". Since when, Microsoft did a strategic change, merged WCF Web API and ASP.NET teams together, so both products to be developed in sync. From now Web API is integral part of ASP.NET (and does not have any WCF prefix any more) and called ASP.NET Web API. It is not just re-branding, but it reflects changes both the programming model and processing architecture.

Simple Start

If we create a new ASP.NET MVC4 application, we see the following change into global.asax file.

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

MapHttpRoute is new extension method for RouteCollection. Similarly to ASP.NET MVC routing definition, it maps HTTP request with matching URL into corresponding API controller action. By default, the are all prefixed with "api" to do not "interfere" to ASP.NET MVC routing. It's not a problem to change that prefix to anything you want, like "services", "methods" etc.

    /api/contacts/      <- Web API
    /api/contacts/1     <- Web API
    /contacts/1         <- ASP.NET MVC

The API controllers are really similar to ASP.NET MVC controllers. Instead of inherit from Controller class, they inherited from ApiController class. Instead of returning ActionResult from action, in API controllers you return either IEnumerable or concrete instance, like Product (there are some more dedicated scenarios with returning types, we will see later).

By just looking into example from project template it is very easy to understand, what's going on. There are some small details you should know before API controller usage.

Action methods naming

API controllers are "Convention over configuration" based. The actual HTTP verb that action handles could be specified in method name.

public class ProductsController : ApiController
{
    // Handles GET
    public IEnumerable<Product> Get() { }
    // Handles POST
 public Product Post(Product product) { }
    // Handles PUT
 public Product Put(Product product) { }
    // Handles DELETE
 public void Delete(int id) { }
}

This convention applies only to GET, POST, PUT, and DELETE methods. You might be more specific in methods names, like GetProducts or DeleteProduct, the important is the prefix (Get, Post, Put etc.) of method.

If you don't want to rely of named based conventions, you can explicitly specify target HTTP verb by decorating methods with HttpGet, HttpPut, HttpPost, or HttpDelete attribute.

public class ProductsController : ApiController
{
    [HttpGet]
    public IEnumerable<Product> AllProducts() { }
    [HttpPost]
 public Product CreateProduc(Product product) { }
    [HttpPut]
 public Product UpdateProduct(Product product) { }
    [HttpDelete]
 public void DeleteProduct(int id) { }
}

One handler per one controller

API Controller are different from ASP.NET MVC controller. The main difference is that API controller handles exactly one HTTP request belongs to particular entity.

If you try to create the code like:

public class ProductsController : ApiController
{
    public IEnumerable<Product> Get() { }
    public IEnumerable<Product> GetAnother() { }
}

It would be build OK, but on a runtime if you try to access '/api/products', you will get an exception:

"Multiple actions were found that match the request: 
\u000d\u000aSystem.Collections.Generic.IEnumerable`1[MvcApplication7.Api.Controllers.Product] 
Get() on type MvcApplication7.Api.Controllers.ProductsController\u000d\u000aSystem.Collections.Generic.IEnumerable`1[MvcApplication7.Api.Controllers.Product] 
GetAnother() on type MvcApplication7.Api.Controllers.ProductsController"

The less stuff is very similar to something we get used in ASP.NET MVC. And you might think - why do we need this Web API at all, I can do exactly the same stuff with good-n-old ASP.NET MVC controllers? Not exactly. Web API has several killer features that makes it favorite for data oriented API's. Let's go on.

Content Negotiation

Content Negotiation is the process for mutual agreement between client and server about the received/sent data formats. Good news here, Web API does a lot of job for you, leaving content negotiation internals behind the scene. Let's take a brief look of how things happen.

When client sends HTTP request to server, besides the query string and payload it also provides different kind information. This information is being placed into HTTP header and provides server with specific details for better understanding each other. In particular, it contains Accept header field which specifies client preferences on response format. I'm going use Fiddler to check how Web API behaves on different conditions.

First, let's do not specify the Accept field at all. So, the payload we going to send to server from our client (Fiddler) will be like:

    GET /api/products HTTP/1.1
    User-Agent: Fiddler
    Host: localhost:5589

For that request, we will receive the response like:

    HTTP/1.1 200 OK
    Cache-Control: no-cache
    Pragma: no-cache
    Content-Type: application/json; charset=utf-8
    Expires: -1
    Server: Microsoft-IIS/7.5
    X-AspNet-Version: 4.0.30319
    X-SourceFiles: =?UTF-8?B?RDpcRGV2ZWxvcG1lbnRcUHJvamVjdHNcZXhwZXJpbWVudHNcTXZjQXBwbGljYXRpb243XE12Y0FwcGxpY2F0aW9uN1xhcGlccHJvZHVjdHM=?=
    X-Powered-By: ASP.NET
    Date: Mon, 19 Mar 2012 17:31:23 GMT
    Content-Length: 88

    [{"Description":"iPad","Id":1,"Price":1000},{"Description":"iPhone","Id":2,"Price":500}]

As you can see, the default Content-Type is "application/json; charset=utf-8", there is a json string in HTTP response payload.

Let's make our request a little more specific.

    GET /api/products HTTP/1.1
    User-Agent: Fiddler
    Host: localhost:5589
    Accept: text/xml

The corresponsing response:

    HTTP/1.1 200 OK
    Cache-Control: no-cache
    Pragma: no-cache
    Content-Type: text/xml; charset=utf-8
    Expires: -1
    Server: Microsoft-IIS/7.5
    X-AspNet-Version: 4.0.30319
    X-SourceFiles: =?UTF-8?B?RDpcRGV2ZWxvcG1lbnRcUHJvamVjdHNcZXhwZXJpbWVudHNcTXZjQXBwbGljYXRpb243XE12Y0FwcGxpY2F0aW9uN1xhcGlccHJvZHVjdHM=?=
    X-Powered-By: ASP.NET
    Date: Mon, 19 Mar 2012 17:33:34 GMT
    Content-Length: 329

    <?xml version="1.0" encoding="utf-8"?><ArrayOfProduct xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Product><Id>1</Id><Description>iPad</Description><Price>1000</Price></Product><Product><Id>2</Id><Description>iPhone</Description><Price>500</Price></Product></ArrayOfProduct>

As you can see, without any code changes we made it "adapt" for particular client needs. This is a very decent feature of Web API and available for use, just from the box. You even don't need to care about it at all. Leave the content negotiation for the infrastructure.

IQueryable<T> Support

Next cool feature is IQueryable<T> support. If you need to, instead of returning "plain" IEnumerable objects from the API action, you might return IQueryable<T>. Why?

Remember the times we implemented paging & sorting with ASP.NET MVC application. It was possible of cause, but it required a lot of manual job. Actions had to be extended with additional parameters, code have to respect those parameters and return exact portion of data we require to. The same story with sorting. In Web API it much simpler.

Change the signature and return type to IQueryable.

public IQueryable<Product> Get()
{
    return _storage.AsQueryable();
}

Now, if Web API sees the method like that, it will allow to access with with Open Data Protocol (OData) query string parameters. OData provides support for following queries: $filter, $orderby, $skip, $top.

Now, if I do the request:

    http://localhost:5589/api/products?$top=3

I will receive, 3 top products. Or something like,

    http://localhost:5589/api/products?$skip=2&$top=3

I will skip 2 and take rest 3. In short, having IQueryable and 4 OData query parameters it's much more easy to do the stuff required more time before.

Hosting

Hosting is a feature of Web API allow to run service inside the different hosts. What does it mean?

We are much get used to ASP.NET hosting as default. I saw no problem with that at all till working on one of my recent projects. The problem is for ASP.NET pipeline you need to have a web server (IIS), but web server always have some limitations (permissions and stuff). For simple things, that does not require any IIS benefits it is easier to host application just in .exe assembly. It's now possible with Web API.

We have several hosting providers out of the box: self-hosting and web-hosting. Besides of that there are already some provided by community Louis DeJardin created a host on top of OWIN and Pedro Félix host for Azure.

Also, there is a great article by Pedro Felix about in-memory hosting. This is very useful type of hosting for unit testing of services.

IoC improvements

Since Web API now is inside ASP.NET MVC, it uses the same strategy of resolving types by IDependencyResolver. That means that Web API classes are now supporting same IoC style as ASP.NET MVC controller classes. Being setup once you can put different dependencies inside API class constructor.

public class ProductsController : ApiController
{
 public ProductsController(IServiceProvider service, IRepository<Product> productRepository)
 {
  // .. 
 }

Conclusions

This is not everything, but very light overview of new stuff coming within ASP.NET MVC4. ASP.NET Web API is very nice addition to framework. There are already some good feedback, so let's hope it will be even more improved toward release.

VS2011 Beta is Ready for Review

29 February (leap day and huge failure of Azure Cloud) is the day then VS2011 Beta community preview has been released. As a lot of geeks around the globe I've downloaded installation image and tried it on my computer. With VS2011 Beta we also received .NET 4.5 framework and (drums here) - ASP.NET MVC4 Beta, that I really wanted to try since first CTP is out. I would not say I spent too much time with both products, but I already have some initial opinion on that.

VS2011 installation..

Well, I had some not really good experience with beta versions of VS2010 and compatibility between two visual studios on the same machine. Situation is different with VS2011. Installation very pretty smooth, I just run it on background while was working through RDP on another machine and it installed without any interaction. Whole process took about 40 minutes.

VS2010 and VS2011 beta could happily leave together without any interference. Moreover, you can freely work with your existing VS2010 solutions. Solutions for .NET 4, 3.5 and 2.0 are still supported in the same good way.

.. and first launch

VS2011 "cold" start up is a faster (about 40 seconds against 90 seconds, on my machine). The only one reason I see is VS2011 is not yet overloaded with different plugins I use in VS2010.

First very noticeable change is of cause the design. There were many blog posts with preview of VS2011 design before the beta release. And you know, I really liked what I saw on images. I changed my opinion on first launch. Probably it's just the matter of taste or habits, but new VS design looks awful to me (especially in Dark Theme - 80's monochrome display back!). It's totally grey, with no colors in icons at all. Fonts are in METRO style (all uppercase) looks very unusual. Solution explorer contains grey icons, it's a little difficult to distinguish between project types and file types inside. So, fellow developer - get ready to order new glasses since you decide to switch to VS2011.


vs2011 solution

Nevertheless, I was happy to open my exiting solution, press Ctrl + Shift + B and it successfully built. The good thing is .sln file has not been transformed (except the Format Version 11.00 has been changed to Format Version 12.00) so it's still can be opened both VS2010 and VS2011.

It also has been imported all my VS2010 settings. It is really nice, since you don't need to spent much time setting up favorite color scheme and key bindings.

I haven't seen any noticeable performance changes. Sometimes VS2011 works a little slower as for me (please note, this is only subjective feelings, does not pretend to be absolute truth). Looks like VS2011 has much larger memory footprint.


vs2011 memory usage

And for some mystical reason it spawns second devenv.exe process in a while, even if I have only one VS instance running.


vs2011 spawns process

Code editing

Code editor is almost the same. No new refactoring tools, no support of 3rd parties Unit Test systems (NUnit, XUnit etc.) from the box. Still Visual Studio requires to have ReSharper for more productive coding. My dream of using clean VS with minimum plugins installed seems not gonna come true with VS2011.

Some few nice moments I noticed for HTML/Razor/CSS editors. First of all, it updates closing HTML tag if you changed opening one (and vice versa). For CSS, it has much more better InteliSence + nice feature of picking colors.

I haven't noticed any significant changes to JS editor. Except the fact, that there are no 'Update JScript Intellisense' menu command, so I suppose that now it's done automatically. Still, it's very primitive and does not work all the time. For instance, I haven't managed to get any InteliSense during working with Knockout.js library, maybe I'm just doing something wrong.

I want my plugings

So, VS2011 is generally OK, so I would prefer to use it. Hope a lot of new fixes and some feature still will be included in RC.

What I personally lack is 2 plugins. ReSharper and NCrunch. Fortunately both appeared very fast. Remco Mulder released NCrunch 1.38b and JetBrains are came with ReSharper 7 EAP which is free for download and evaluation. Both plugins works really fine. Having good refactoring tools as ReSharper gives and having the power of Continuous Tests with NCrunch, makes the VS2011 ready to use IDE.

Conclusions

The beta looks very promising.. and in general it works fine! Except the design, nothing really new to IDE as for me. Probably I spent to few time to feel the power, so I'll be updating if I see some cool or bad features. The most sweet things with new VS is surely updated .NET framework and MVC. I'm now trying to play with new stuff and much as I can, already checked some new nice stuff of MVC4 framework.

Second Year of E-conomic

Yeah, it's been 2 years since I joined the e-conomic company. As it was last year, this year e-conomic still plays very important role in my life, so I'll spent some time to write this blog post.

Well, a lot of things changed I would say. Some people came, some people left. Teams rotating all the time, I'm no longer work with guys I used to work last year. We are doing revolutionary things there, no doubts. It doesn't mean, we are creating new search engines or inventing new type of computer. No, we are revolutionizing ourselves much.. doing the same type of products, but doing it differently.

Remember I wrote about how technologies helps to move product faster - that was an example of radical changes in framework and tools we did to successfully deliver the product. I believe something happened last year, something that gave much pulse for changes. And that pulse still affects us. We went much further of changing for Web Forms to MVC or jQuery to Backbone.js. Recently our back-end team finished up POC of using node.js + MongoDB as our perspective server side technology stack. And they actually proved that it will work for us.

From my perspective, e-conomic much improved in this year. And this is of cause happened, because people how work in e-conomic improved. Without any hesitate, I would say that currently we have the strongest team ever. Both Danish and Ukrainian parts. It's amazing how smooth the technologies change was, how fast new concepts been adopted, how motivated and hardworking guys joined together.

We've been empowered not only by engineers, but also with our newly assembled UI/UX team. No secret, everybody want to work with beautiful things. I equally appreciate both the quality of code and quality of design. And this is want UI/UX team care about. And this is fantastic job as for me. We are changing the design quite regularly and each iteration it turns better and better. Colors, fonts, usability tricks - that's something that gives a life to modern web applications.

As usually the developers see only the tip of iceberg of whole company business, but I really hope that all good stuff that's happening inside engineering department will find it's reflection in quality of service, usability and user happiness.. that at the end of the day bring the company more users and more money. Sure, the things are moved not only by developers. I would say, we are doing the easiest job. Our PO's and Stakeholders - that's where ideas are coming from. The quality of those "ideas" are directly proportional to output quality. And this quality is getting better and better each day.

We are doing finishing strokes on new product, called Debitoor.com. It's amazing application and I hope it will find it's audience very fast.

So, I'll say goodbye to the past year and look forward for new journeys in next one.

Foundstyles.com - Ready to use styles based on Foundation

Foundstyles.com is a little project I've been working for last week. The idea is very simple. Remember, I blogged about Foundation Framework that works pretty nice for me. So, I've decided to do something similar that exist for twitter bootstrap framework - bootswatch ready to pickup .css that could be easily integrated to your site. Today the site is available!


foundstyles.com

Unfortunately Foundation does not support LESS from the package, so I need to move colors and layout into corresponding .LESS files, so after it's just possible to have a basic template which is possible to customize with own colors.

As for now, I've created only 3 templates: Blades Of Steel, Evergreen Tree and Coffee and Milk.


foundstyles.com

I had a lot of joy making those styles. Making web designs and playing with colors is my next hobby, I think. Through, those styles are really simple ones, I'm going to add more eventually. Since the project is just hosted on github you are able to push you own styles. If you feel inspired, I would be really happy for submissions.

Nearest plans are apply some fixes for IE (both site and styles) and just go ahead and produce some more. Hope it could be useful for you guys.