Monthly Archives: January 2011

MIX Open Call Sessions

I have a couple of talks up for voting for MIX 2011. If you’re interested in hearing my speak about any of these topics, would love the vote.

Thanks

MVC – Breaking the Mold

Hadi Hariri

ASP.NET MVC is in its third incarnation and despite numerous improvements, when creating large scale applications, problems arise. If you don’t take the right steps, your code can soon turn into a big ball of mud. However, with a few conventions, a twist to routing and some voodoo magic, we can create a much better architecture that allows for sustainable code and increased productivity. In this session we’ll see how to refactor ASP.NET MVC as it comes into a cleaner architecture, allowing for a better approach to writing applications.

Working with Dynamic keyword effectively in Web Applications

Hadi Hariri

Whether we like to admit it or not, dynamic languages are very popular, especially when it comes to web development. They offer a series of benefits over statically typed language that can enhance productivity. With the introduction of the new dynamic keyword in C# 4.0, we’ll examine certain ways of using it to obtain some of the advantages dynamic languages provide us in a statically-typed world and how used appropriately, the benefits it offers outweigh any potential disadvantages.

ReST Architectures with ASP.NET MVC

Hadi Hariri

Creating ReST architectures with ASP.NET MVC is more than just decorating actions with verbs. It’s about leveraging HTTP as an application protocol to its full potential. In doing so, we can create robust and scalable applications, not only from a performance point of view but also in terms of change and maintainability. ASP.NET MVC offers us great potential to create ReST architectures that can be consumed by computers and humans alike, reducing the amount of effort involved. Come to this session to learn what ReST is really about and how we can create simple yet powerful systems with ASP.NET MVC.

JetBrains @ BASTA!

image Last week of February I will be at BASTA!, an awesome .NET conference that is held twice a year in Germany (Spring and Autumn Editions). In this occasion, JetBrains, as a Special Sponsor, will be holding a JetBrains Community Night. This will be in-line with similar events we’ve recently been holding at conferences, where we show you some tips and tricks, some of the things we are working on, answer any questions you might have, and in general just spend some quality time with you, our users. We’ll top it off with snacks and beer (yes, all you can drink beer!).

The Agenda

- Working Effectively with ReSharper for MDD (a.k.a Mouseless Driven Development)

- Upcoming Features in ReSharper 6

- Code Coverage with dotCover

The Community Night will kick off on Tuesday 22nd of February from 7:00 pm and is open to everyone.

IMPORTANT: Whether you are attending BASTA! or not, you do need to register for this event

I’ll also be giving two sessions at BASTA!, one on ReST with MVC (Tuesday) and another on CouchDB (Wednesday).

Join us at BASTA!

Using a ToDo list more effectively

Have you ever had the need to place a TODO in your code? I’m sure we’ve all done so, for some reason or another. Normally it’s just a temporary reminder that we’ll get back to after finishing off something else, in an attempt to avoid breaking the expensive flow we get our minds into when writing code.

Similar to comments however, TODO’s are only valuable if they have meaningful information, and much like comments, we developers, aren’t necessarily to attentive to such things. A TODO can be a bug, a code smell, an optimization or even a feature that would need to be logged. As such, it would be more valuable if things TODO’s were defined correctly, something that doesn’t often happen (specially when considering the whole flow thing…). That translates into expecting TODO’s inline with:

// TODO: this needs cleaning up

// FEATURE: Need to add support for XYZ

but in turn we get:

// this is some stinky piece of code

// ultimately we need to support feature XYZ

// this code smells worse than a dark alley next to a Club on a Sunday morning

The problem with this, apart from the inconsistency that can cause you sleepless nights, is that things can get lost. The TaskList feature in Visual Studio requires these kind of comments to follow a certain pattern, and even when that occurs, the way they are presented leaves a bit to be desired.

image

[Visual Studio Task List]

Enhancing ToDo’s

ReSharper ToDo management adds several benefits over Visual Studio’s built-in. But before we see these, let’s first examine how we can solve the previous problem. To recall, what we want to do is be able to support multiple formats when it comes to defining comments, so // TODO: fix this and // add this to the list of ToDo’s to fix both would appear under the list of ToDo’s.

Fortunately, the way ReSharper allows us to define ToDo items make this very simple. First, in order to access the definitions, we go to ReSharper| Options | ToDo Items

image

Selecting any of the items (for instance the first one) and double-clicking or clicking on Edit, we get the definition dialog box:

SNAGHTMLd8e0cd3

As opposed to the default Visual Studio, with ReSharper we use regular expression. This provides us with the flexibility required. The above example for instance is telling ReSharper to search for any pattern that contains the word TODO in it. By default, normally these patterns are searched for in comments, although we can optionally look in strings and identifiers too. We do not have to worry about defining case-sensitivity in the regular expression. Instead we can just mark the Case sensitive checkbox if we require it. Finally, we can define the color and icon we want displayed when viewing the list of items (which we’ll see later on).

Adding new Items

By default, out of the box, ReSharper comes with four items (Todo, Bug, Note and NotImplemented). We can easily extend this to offer support for other items such as identifying code smells, features, etc. Easiest way is to simply click on an existing item and Duplicate it:

SNAGHTMLdbf5c1b

Searching and Filtering Items

Having the items defined, we can now display a list of them by invoking the Todo Items Explorer from ReSharper | Tools | To-do Items, or pressing Ctrl+Alt+D (VS Scheme)

SNAGHTMLdc547b1

The advantage of course is that it is not required for items to begin with a certain word, as this can be in any position of the string. ReSharper also allows us to filter items so that we can focus on a specific type of task by using the Filter option:

image 

which can also be customized using under Tools | Options (accessible too from the To-do Explorer [icon to the left of Filter]). Last but not least, we can also group items by a variety of options, from namespaces to projects, to types, etc.

SNAGHTMLdc90bf9

Now that’s what I call a colorful, albeit long list of tasks!

We are coming to Stockholm!

 

 

JetBrains is coming to Stockholm. After the great feedback we have been receiving at the different community nights we’ve held, we’re doing more. On the 9th of February we’ll be coming to Stockholm where we’ll hold a free event for our users. We’ll dive into the less known features of ReSharper, show you some of the upcoming treats and also learn about setting up environments for Continuous Integration.

Seats are limited, so if you are interested please register soon (link also contains more detailed information).

 

image

 

On the Thursday I’ll also be taking part in the .NET Community Day in Göteborg, and I’ll be back in Stockholm again the next day to repeat the same event there.

 

[Image © C.C. Sébastien Bertrand]

EasyHttp

As of late, much of the code I write, somehow or other has to communicate with an HTTP server. Be it a “ReSTful” service or a “Wanna-be-ReSTful” service, I’ve had the need to make GET, POST, PUT et al operations and work with JSON.

After writing smaller wrappers around WebRequest on a few occasions, I decided it’s time to formalize the wrapper. This has given way to EasyHttp. It’s been sitting on GitHub for quite some time and both myself and others have been using it for several projects, so I think it’s reached a point where more people can try it out if they wish.

Best way to describe the features of EasyHttp is with some code

var http = new HttpClient
           {
               Request = {Accept = HttpContentTypes.ApplicationJson}
           };

var response = http.Get("http://domain.com/customer/25");

var customer = response.StaticBody<Customer>();

The code is self-describing: we create an instance of HttpClient and indicate that we accept content-type application/json (since in this case the server sends us json). By specifying this Accept header, EasyHttp knows how to decode the request.

How do we obtain the response? In the code above we are using the StaticBody method which gives us back a strongly-typed Customer. But we have other options:

var http = new HttpClient
           {
               Request = {Accept = HttpContentTypes.ApplicationJson}
           };

var response = http.Get("http://domain.com/customer/25&quot;);

dynamic customer = response.DynamicBody();

Console.WriteLine(customer.Name);
Console.WriteLine(customer.Email);

 

In this case we want to return a dynamic type so we call the DynamicBody method. EasyHttp will automatically deserialize the response to a dynamic object. This allows us to access properties without having to declare types ahead of time (quite useful when working with JSON). Finally we can also get access to the raw response via the RawText property.

If we want to stream to a file, we simply do:

  var http = new HttpClient();

  http.GetAsFile("http://hadihariri.com/header.png&quot;, @"C:\Temp\header.png");

Working with other verbs is pretty much the same process. Let’s say we want to create a customer calling a service:

var http = new HttpClient();

var customer = new Customer()
                    {
                        Name = "Joe Smith",
                        Email = "Joe@Gmail.com"
                    };

http.Post("http://domain.com/customer&quot;, customer, HttpContentTypes.ApplicationJson);

 

In this case we are posting a Customer object and asking EasyHttp to encode it using application/json. Similar to when receiving a response, when making a request that requires a body, we can also use dynamic objects. As such, this would also work:

   var http = new HttpClient();

   dynamic customer = new ExpandoObject();

   customer.Name = "Joe Smith";
   customer.Email = "Joe@Gmail.com";

   http.Post("http://domain.com/customer&quot;, customer, HttpContentTypes.ApplicationJson);

 

Internally, EasyHttp is using the excellent JsonFX which currently provides support for JSON and XML encoding/decoding. EasyHttp extends this by adding encoding support for www-form-urlencoded. Extending it with other format should be pretty easy.

As well as GET and POST, EasyHttp also provides support for PUT, DELETE and HEAD. Request and Response headers are surfaced as properties, so instead of having to add headers manually, we can just assign them individually (some of these are surfaced from the existing WebRequest).

Summary

That’s pretty much all there is to it. As I mentioned, I’ve been using it myself to talk to CouchDB, as part of YouTrackSharp and a few other projects. It’s far from feature complete, but I’m adding things as I or the few that are using it request them.

Feel free to download it and play with it. The source code is on GitHub and Issue Tracker is on CodeBetter. If you are interested in running the tests, you will need CouchDB. I originally wrote this because I needed to do some things for CouchDB and it served as a good platform for testing different Http Verbs (yes, they are integrations tests and not unit tests).

In-depth look at Customizing Type Layout with ReSharper

When we run Code Cleanup with ReSharper, one of the options it has is to re-order the member layout in classes. This means that some ugly layout like this

image

can be turned into this

image

(you need to have Reorder Type Members checked).

The advantage is that we don’t need to constantly worry about making sure properties and fields are declared in their correct position, wasting time manually re-arranging code.

What happens however when we don’t agree with ReSharper’s choice in layouts? Recently I came across this situation when I ran the clean-up (by mistake) on my Specifications project. I use MSpec and I like to keep certain things in certain places. In particular, with MSpec you make use of statics and I like to have them placed at the bottom of each class where I can ignore them.

image

Of course, when I ran ReSharper clean up, I ended up with

image

So what to do? Well, I am aware of the possibility of modifying how type members are ordered in ReSharper, the problem with it however is that it’s global, that is, you can’t change it per project. What hadn’t occurred to me (talk about not looking at the default pattern. Thanks Alex) was to bind the customization to MSpec’s Subject attribute that specifications have (albeit it is not required but nice practice).  Although much of the work is done, I thought it would be a good opportunity to delve a bit more into customizing layouts since it could probably benefit others. So here goes…

Customizing Type Layouts

Layout is defined in ReSharper using XML which is defined under ReSharper | Options | Languages | C# | Type Member Layout

SNAGHTML70374c6

To get access to the default pattern and customize it, we need to uncheck the Use Default Patterns checkbox, which then causes the editor to display the text. Don’t be scared!

image 

What we see is the XML file that defines the pattern layout. Most of the text is actually comments defining how things are layout. The actual patterns start lower down (although there’s no scrollbar, you can scroll). Here is the same contents in a nicely XML highlighted view

image

A Pattern (<Pattern></Pattern>) consists of multiple entries (<Entry></Entry>). Each entry in turn represents some type of member. The order of these entries define the order in which the code is laid out. Let’s take a look at an entry in more detail

image

Each entry consists of a <Match> element and optionally a <Sort> and <Group> element. <Match> in turn consist of one or more Operands combined using <And>/<Or> and negated with <Not>. An Operand can be:

Operand $val can be..
<Kind Is=”$val” [Order=”$val”]>

class, struct, interface, enum, delegate, type, constructor, destructor, property, indexer, method, operator, field, constant, event or member

<Name Is=”$val” [IgnoreCase=”true/false”]> Regular expression. IgnoreCase indicates whether to ignore case
<HasAttribute CLRName=”$val” [Inherit=”true/false”]> Regular expression. Inherit indicates if it applies to inherited classes.
<Access Is=”$val”> public, protected, internal, protected internal, private
<Static/>
<Abstract/>
<Virtual/>
<Sealed/>
<Readonly/>
<ImplementsInterface CLRName=”$val” [Immediate=”true/false”]> Regular expression
<HandlesEvent/>  

Taking this into account, if we look at the previous pattern, we see that we are trying to match constructors, specifying (optional) that static constructors should be ordered first. Let’s take a look now at a more “complicated” pattern

image

This pattern is for matching instance fields that are not static. What we do is identify fields using the Kind Operand and passing field as the value for the Is attribute. Since we are interested in non static fields, we add a <Not> operator around a <Static/> operand. We need to wrap this in an <And> operator (using Polish notation). Finally, let’s look at static fields and constant

image

Here the pattern should match a constant or (<Kind Is=”constant”>) <And> a static field (<Kind Is=”field”>) which is <Not> static (<Static/>). Again, if we look at this using Polish (or prefix) notation, it is easy to understand.

Defining Multiple Patterns

Having understood the basics of how patterns are defined, we can now come back to solving our issue with MSpec. Our issue is where statics are located. One solution would be to move the static pattern to the lower part of the pattern. Problem of course is that this would effect all classes. We only want it to effect classes that are of MSpec, that is, have the Subject attribute.

The key in solving this problem is to define a different pattern for MSpec classes. In the Pattern definition file, we can have multiple patterns. What we can therefore do, is add a new pattern specific for our MSpec classes. How will ReSharper choose which pattern to use? That’s solved easily by defining a <Match> as the first element of each Pattern

image

We have defined a new pattern that has a <Match> element with an <HasAttribute> for the Subject attribute of MSpec. When we now run Code Cleanup, ReSharper will match the pattern with MSpec classes and apply the appropriate layout. In our case, the only thing we have defined is that static fields should be after all other entries (indicated by using the <Entry/> element). This means that we are leaving layout as is for everything else (in real-world scenarios, this might not be the case. The MSpec file defined by Alex in fact has a full nice layout for MSpec).

Giving Matches Weights

In the previous pattern definition, there would not be any conflicts between the default patter and that of MSpec because the <HasAttribute> element discriminates correctly only MSpec classes. What would happen however if two patterns would match? That is where the weight factor comes in. Each <Match> element can have a Weight attribute associated with it. In case of conflicts, the one with the highest weight wins.  

Sorting, Grouping and Regions

In addition to matching elements and defining their positions, we can also specify sorting and grouping options with patterns. By providing a <Sort> element

 image

and defining the Operand by which it is to be sorted, elements that match the pattern will follow the specified order. In a similar way, using the <Group> element, we can group similar constructs and optionally wrap them in regions. Many of these operands can take as attribute values the variable they represent. In the previous pattern, we are specifying as the region name the variable ${Name} which will be instantiated to the name of the type.

One final option is the possibility (which many of us are thankful for) of removing regions on cleanup. Each <Pattern> element has an attribute RemoveAllRegions which can be set to true or false. By setting it to the latter, regions will be removed on code cleanup.

As we can see, the possibilities of laying out type members when performing code cleanup are quite unlimited. The process is a little bit cumbersome, mostly due to the editor, although there are already planned improvements for ReSharper 6. Nonetheless, if you have any feedback, please send it now or log it in YouTrack.

[Download the XSD Schema here]

CodeMash, here we come!

image

What is there to do in Sandusky, Ohio, in the middle of Winter with sub-zero temperatures and snow? Well CodeMash of course, which takes place from the 12th to the 14th of January.

 

JetBrains is not only Adamantium sponsor, but will also be there! We will have a booth and a vendor session where we’ll show some of the upcoming features in ReSharper 6 as well as some of our other tools.

I’d love to say that if you’ve not signed up to CodeMash, make sure you do, but it would be useless. They sold out on the 3rd day! So if you’re one of the lucky ones that has a ticket, please stop by and say hello! 

Our vendor Session will be on Thursday from 3 pm. I’ll also be doing a session on CouchDB on Thursday at 4:50 pm.

This is the first of a series of great events planned for 2011, so stay tuned!

Happy New Year!

That dreaded M in ASP.NET MVC

When it comes to working with Models in MVC, I’ve tried many approaches, some good, others not so much. I’ve ended up settling on ViewModels, whereby the Model I submit is dictated by the View I’m working with. This allows me the flexibility of displaying or gathering only the information I need. It also allows me to provide additional information on the view that isn’t necessarily required by my domain.

It works, but it also adds a lot of friction. Be it mapping, be it validation, it’s continuously repeating same processes over and over again. Even automating some of this still requires constant set up. Every time I work with ASP.NET MVC, I dread having to deal with all this. Way too much friction.

I’ve often wondered whether I’m overly complicating myself by trying to add so much flexibility. I mean if the Rails guys can work with ActiveRecord, why can’t I? Granted that maybe much of the drawbacks of ActiveRecord can be remedied in some way in Rails because of Ruby being a dynamic language and allowing for things such as Mixins, but still, what about the other stuff? The mapping to an actual domain model. What happens when they need a list of countries? What happens when they have to update only 2 out of 7 fields of their domain model?

I decided to ask Shay how he works. As a guy who works with both ASP.NET MVC and Rails, and has written a book on IronRuby, I thought he’d be a good candidate. Plus, he’s a nice guy.

I have to say I wasn’t really surprised by his answer. He binds directly to his Domain Model in ASP.NET MVC. I asked how he dealt with additional info: Html Helpers. I asked how he solved partial updates: In the controller. Although, not surprising, it was interesting. As a guy that’s worked heavily in Rails, he seems to cope fine with this approach in C#.

So again I wonder, am I focusing on too much flexibility? I decided to ask others by running a quick survey on Twitter asking how people worked with M in MVC.

1. First the disqualifying question. Are you using Strongly-Typed views?

image

98% voted they are. I’m guessing more than 2 people were not, but since the Survey was focused on strongly-typed views, they probably didn’t take part.

2. Now the question to see if I am the odd one out using ViewModels

image

Apparently not. 78% of people use ViewModels.

3. The next question was how one deals with only partially updating some fields of a Domain Model if binding directly to them.

image

4. What about that damn list of countries?

image

(I’ve actually found another way to solve this problem, partially based on conventions, and we might even build it in to AutoReST. But that’s for another post).

5. Key question the following. Mappings (read friction). If you use ViewModels, do you manually map information or use something like AutoMapper?

image

Surprised by the number of people doing manual mapping. You would think that if AutoMapper’s only responsibility is to do mapping for you, why not use it? Could it be again the same issue? Too much friction to setup? NuGet to the rescue? Too much ceremony?

6. Here’s another one. Validation.

SNAGHTMLaa90b6d

So pretty much everyone (79%), some way or other has to deal with decorating their models with attributes.

7. Finally, I was curious how people felt in general with the development process. Did they also encounter friction?

image

Not surprisingly, 70% find some level of friction in doing web development.

Conclusions

First off, this is not a stab at ASP.NET MVC. If you take it like that, you’re barking up the wrong tree. I’m sure in one way or another, any platform or language has a certain level of friction when it comes to developing applications. No, this is more of a self-stabbing.

I also agree that on the whole, there’s too much friction. However, I’m not sure how much of that friction is caused by the platform vs the mentality of us developers to think big and try to build in so much unneeded flexibility. Are we really applying YAGNI? Are we really applying KISS? Maybe adding so much flexibility in terms of ViewModels because, and I quote, “when dealing with complex scenarios, simple approaches fall apart” only actually solve a 5% edge case that could be remedied in a different way.

Maybe we should stop being afraid of trying to be too strict and not flexible enough. Maybe we should take the concept of conventions more seriously than just what folders our Views, Controllers and Models reside in. Maybe we should push conventions to the limit and see if we actually reduce this friction.

And that’s the next journey I’m going to embark on. It might be time to drop the ViewModel, it might not be. What I do know is that writing good software shouldn’t be so complex.