MSpec BDD framework installer

Posted by – November 23, 2009

.NET LogoInstallation of MSpec BDD framework from source code is quite annoying. With each release you have to deploy everything manually one more time what in fact is hard to accept in 21th century. I know that work on Open Source project requires a lot of time (I have my own project called ByteCarrot) and you cannot do everything. Because of that I decided to help a little bit creators of MSpec and I have prepared an installer for this BDD framework. It is based on WiX and latest release of MSpec witch is version 0.3.

The installer is able to automatically integrate MSpec with TestDriven.NET and ReSharper (4.1, 4.5, 5.0). This is first version of the installer and of course like always there can be some bugs so please let me know if you find something.

Download installer for MSpec 0.3

Rake in .NET projects – installation and setup

Posted by – November 18, 2009

.NET Logo
Recently I have rewritten all MSBuild scripts which I used in ByteCarrot project to Rake. I made the decision about changing build solution mostly because I required something what works not only under Windows but also on other operating systems. After rewriting turned out that Rake is a great solution for tasks for which it was created and can be used not only with Ruby/RoR projects but also with other technologies like .NET and Mono. It is really awesome multi-purpose tool. Today I would like to show you how to install and configure Rake on Windows operating system in order to start using it in your projects. Ruby installation First of all, because Rake is based on Ruby language, you will need an interpreter. You can download Ruby distribution from its official website but I do not recommend that because there is only installer for version 1.8.6 which is quite old. Other packages for Windows on this website are in a form of compressed archives and do not contain some additional, required libraries. In my opinion the best option is to download one of preview version of installer for Ruby 1.9.1-p129 (rubyinstaller-1.9.1-p129-preview1.exe) available on RubyForge. ByteCarrot project to Rake. I made the decision about changing build solution mostly because I required something what works not only under Windows but also on other operating systems. After rewriting turned out that Rake is a great solution for tasks for which it was created and can be used not only with Ruby/RoR projects but also with other technologies like .NET and Mono. It is really awesome multi-purpose tool. Today I would like to show you how to install and configure Rake on Windows operating system in order to start using it in your projects.

Ruby installation

First of all, because Rake is based on Ruby language, you will need an interpreter. You can download Ruby distribution from its official website but I do not recommend that because there is only installer for version 1.8.6 which is quite old. Other packages for Windows on this website are in a form of compressed archives and do not contain some additional, required libraries. In my opinion the best option is to download one of preview version of installer for Ruby 1.9.1-p129 (rubyinstaller-1.9.1-p129-preview1.exe) available on RubyForge.

Ruby Logo

When the installer is on your hard drive, start installation. There is nothing magic in the installation process but you should remember that Rake does not work properly when Ruby in installed in C:\Program Files directory (probably because of space in the path). Because of that leave the default installation path or change it to something without spaces like for example C:\Ruby.

Last thing you should do to be able to use Ruby is adding the location of its binaries to the %Path% environment variable. In my case this variable was extended with C:\Ruby\bin path.

Now you can check if everything works by executing from command line two following commands:

ruby –v
gem -v

The output from console should be:

C:\>ruby –v
ruby 1.9.1p129 (2009-05-12 revision 23412) [i386-mingw32]
C:\>gem –v
1.3.4

Rake installation

Now, when Ruby is installed and you are sure that it works you can take care of Rake. The most popular and safe way to install Ruby extensions and libraries (including Rake) is mechanism called Gems. In order to install Rake using Gems execute following command from command line:

C:\>gem install --remote rake

The output from console should be:

C:\>gem install --remote rake
Successfully installed rake-0.8.7
1 gem installed
Installing ri documentation for rake-0.8.7...
Updating class cache with 0 classes...
Installing RDoc documentation for rake-0.8.7...

When the command will finish do not close command line window yet. At the end execute one more command to be sure that Rake is installed properly:

C:\>rake –V

The output from console should be:

C:\>rake –V
rake, version 0.8.3

Congratulations! You have managed to install Rake and you are ready to write your first build script. More about Rake can be found on official site of the project. Example Rake scripts can be found in ByteCarrot source code on CodePlex.

ASP.NET MVC 2 Beta – new features

Posted by – November 18, 2009

.NET LogoYesterday at PDC 09 Bob Muglia announced the release of ASP.NET MVC 2 Beta. This release contains a lot of new, interesting stuff. Below you can find a list of new features taken from official release notes.

New RenderAction method

Html.RenderAction (and its counterpart Html.Action) is an HTML helper method that calls into an action method from within a view and renders the output of the action method in place. Html.RenderAction writes directly to the response, whereas Html.Action returns a string with the output. RenderAction works only with actions that render views.

Strongly typed UI helpers

ASP.NET MVC 2 includes new expression-based versions of existing HTML helper methods. The new helpers include the following:

  • ValidationMessageFor
  • TextAreaFor
  • TextBoxFor
  • HiddenFor
  • DropDownListFor

TempDataDictionary improvements

The behavior of the TempDataDictionary class has been changed slightly to address scenarios where temp data was either removed prematurely or persisted longer than necessary. For example, in cases where temp data was read in the same request in which it was set, the temp data was persisting for the next request even though the intent was to remove it. In other cases, temp data was not persisted across multiple consecutive redirects.

To address these scenarios, the TempDataDictionary class was changed so that all the keys survive indefinitely until the key is read from the TempDataDictionary object. The Keep method was added to TempDataDictionary to let you indicate that the value should not be removed after reading. The RedirectToActionResult is an example where the Keep method is called in order to retain all the keys for the next request.

Client validation library

MicrosoftMvcAjax.js now includes a client-side validation library that is used to provide client validation for models in ASP.NET MVC. To enable client validation, include the following two scripts in your view.

  • MicrosoftAjax.js
  • MicrosoftMvcAjax.js

The following example shows a view with client validation enabled.

<script type="text/javascript" src="MicrosoftAjax.js"></script><script type="text/javascript" src="MicrosoftMvcAjax.js"></script>

  //...

“Add Area” dialog box

ASP.NET MVC 2 Beta includes a new Add Area context menu item when you right-click either the root project node or the Areas folder (if one exists). If a root Areas folder does not already exist, the command creates one, and it then creates the files and folders for the area that you specify.

Calling action methods asynchronously

The AsyncController class is a base class for controllers that enables action methods to be called asynchronously. This lets an action method call external services such as a Web service without blocking the current thread. For more information, see Using an Asynchronous Controller in ASP.NET MVC In the ASP.NET MVC 2 documentation.

Blank project template

In response to customer feedback, an empty ASP.NET MVC project template is now included with ASP.NET MVC 2 Beta. This empty project template contains a minimal set of files used to build a new ASP.NET MVC project.

Multiple model validator providers

ASP.NET MVC 2 Beta lets you register multiple validation providers. The following example shows how to register multiple providers.

protected void Application_Start() {
    ModelValidatorProviders.Providers.Add(new MyXmlModelValidatorProvider());
    ModelValidatorProviders.Providers.Add(new MyDbModelValidatorProvider());
    //...
}

Multiple value provider registration

In ASP.NET MVC 2 Beta, the single value provider that was available in ASP.NET MVC 1.0 has been split into multiple value providers, one for each source of request data. The new value providers include the following:

  • FormValueProvider
  • RouteDataValueProvider
  • QueryStringValueProvider
  • HttpFileCollectionValueProvider

These value providers are registered by default. You can register additional value providers that pull data from other sources. The following example shows how to register additional value providers in the in Global.asax file.

protected void Application_Start() {
    ValueProviders.Providers.Add(new JsonValueProvider());
    //...
}

Download full ASP.NET MVC 2 Beta Release Notes

Metadata based validation with jQuery

Posted by – October 8, 2009

jQuery Validation enabled form

Recently I spent some time prototyping my own validation for ASP.NET MVC. Why did not I reuse any of existing solutions? This is a story for another post so I did not want to bring this topic up now. One of the things which I had to figure out during prototyping was how to implement client side validation. Of course I wanted to utilize capabilities of some well known JavaScript framework (no I am not so crazy to write it for my own). I made small evaluation comparing available options and at the end I decided to incorporate jQuery and its Validation plugin. One of the things which were crucial to my decision was ability of this framework to use metadata stored as JSON in class attribute of HTML element. The concept of metadata available in jQuery is amazing and gives possibility to describe validation rules for specified input control inside itself. In my case this was very important feature because I wanted to render validation using my custom HtmlHelper extensions together with corresponding input controls. Second thing which convinced me to jQuery Validation was easy setup which I want to show you now.

If you want to use jQuery Validation in your project first of all you will need of course jQuery library which can be downloaded here, jQuery Metadata plugin which is available here and jQuery Validation plugin downloadable from here.

When you collected all required prerequisites you have to add reference to them in your HTML. Simply add code shown below to the body of tag but remember to ensure that paths lead to place where JavaScript files are located.

<script type="text/javascript" src="jquery-1.3.2.min.js"></script><script type="text/javascript" src="jquery.validate.min.js"></script>
<script type="text/javascript" src="jquery.metadata.js"></script>

When jQuery libraries are already where they should be you can specify validation rules using metadata. In order to do it extend your input control tag with class attribute and set its value to {required:true}. This will tell Validationplugin that this specified input control should contain a value before it can be send back to server. Of course this is very simple rule but below I have listed few more, complex definitions.

<input class="{required:true, maxlength:100, messages:{required:'This field is required.', maxlength:'This field can contain maximum 100 characters.'}}" type="text" />
<input class="{maxlength:50, email:true, equalTo:'#Email',  messages:{required:'This field is required.', maxlength:'This field can contain maximum 100 characters.', email:'This is not a valid email.', equalTo:'Value entered in this field should equal to value of Email field.'}}" type="text" />

Listing below shows this validation metadata in wider context.

</pre>
<form id="MyForm" action="/Registration" method="post"><label for="DisplayName">Username:</label> <input id="DisplayName" class="{required:true, maxlength:100, messages:{required:'This field is required.', maxlength:'This field can contain maximum 100 characters.'}}" type="text" name="DisplayName" /> <input type="submit" value="Submit!" /></form>
<pre>

At the end when you have defined all validation rules only thing you should do is adding following code after closing tag and that is it.

<script type="text/javascript">// <![CDATA[
    $("#MyForm").validate({
        errorElement: "span"
    });
// ]]></script>

Now when you will click Submit! button your form will be validated and in case of errors apropriate messages will be displayed below corresponding input control.

Because I know that described example can be not enough to fully understand how all it works I have prepared more complex, example form which can be downloaded from here: download.

My favorite System.String extension methods

Posted by – September 27, 2009

.NET LogoEach business applications developer spends a lot of the time working with strings. Strings are everywhere and we do not avoid that, but we can make our life simpler. How many times each day do you use String.Format(), String.Trim() or String.IsNullOrEmpty()? This are of course very helpful method but turned out that in my case they do not provide a functionality I require. I found out that almost all the time I am treating null, an empty string and a string with whitespaces only as the same “undefined/unkown” value. I am doing that mostly with strings received from outside of my applications where I an interested in “real values” instead of for instance a string with spaces only. In this case, methods mentioned above do not meet my needs. Because of that I have created replacement for them as an extension methods and they became my favorite tools to work with strings (I am using them everywhere instead of out of the box methods).

StringExtensions class defining extension methods:

using System;

namespace ByteCarrot.Shared.Infrastructure
{
    public static class StringExtensions
    {
        public static string NullTrim(this string s)
        {
            if (s == null)
            {
                return null;
            }

            s = s.Trim();
            return s == String.Empty ? null : s;
        }

        public static bool IsSet(this string s)
        {
            return s.NullTrim() != null;
        }

        public static string AsFormat(
            this string s, params object[] args)
        {
            return String.Format(s, args);
        }
    }
}

IsSet() extension method – returns true only if string contains at least one “printable” character:

if (!this.Commands.IsSet())
{
    this.Logger.LogError(&quot;Commands not specified.&quot;);
}

NullTrim() extension method – returns string trimmed from both sides and null when base string was null or after trimming turned out that output is an empty string:

var commands = this.Commands.NullTrim();

AsFormat() extension method – shorter replacement for System.String:

Resources.RequiredField.AsFormat(&quot;First name&quot;);

It is nothing fancy but make my life easier.

ReSharper’s Live Templates for MSpec BDD framework

Posted by – September 23, 2009

Few days ago Pawel Lesnikowski has blogged about his Live Templates for ReSharper. Because I think it is good idea to share such things with other developers I decided to show my Live Templates I have made to be able to create BDD specifications with MSpec faster. Here they are:

specc – Short template for MSpec BDD context

public abstract class with_$Context$
{
	Establish context = () =>
	{
		$END$
	};
}

specf – Full template for MSpec BDD specification

[Subject(typeof($Subject$))]
public class when_$Specification$
{
	Establish context = () =>
	{

	};

	Because of = () =>
	{

	};

	It should_$Behaviour$;$END$
}

specs – Short template for MSpec BDD specification

[Subject(typeof($Subject$))]
public class when_$Specification$
{
	It should_$Behaviour$;$END$
}

spect – Default template for MSpec BDD specification

[Subject(typeof($Subject$))]
public class when_$Specification$ : with_$Context$
{
	Because of = () =>
	{

	};

	It should_$Behaviour$;$END$
}

Here you can download definition of all mentioned templates which can be imported to your ReSharper: MSpec.LiveTemplates

ASP.NET MVC in a corporation – part #2

Posted by – September 10, 2009

.NET LogoIn my previous post I have mentioned that I am currently evaluating the ASP.NET MVC in context of usage for building internal corporate applications. During the evaluation I have made my small SWOT analysis and I want to share it with you in order to get to know what your opinion on this topic is. Because my all thoughts reside in a mind map I have dumped them to the plain list:

Strengths:

  • It is based on the Convention over Configuration principle, what means less ceremony in code and more time to focus on business rules;
  • It is highly extensible with many points of extension in every part of application lifecycle.
  • It is highly testable no matter if you are using the TDD or BDD style of unit testing;
  • It is provided by Microsoft – big player on the market, what at least in theory guarantee that the solution will be supported for a long time;
  • It contains a lot of elements known from classic ASP.NET like notion of session, modules, handlers, HTTP context, views based on ASPX pages and ASCX controls. This is quite important if employees have to switch to the ASP.NET MVC and previously they have used classic ASP.NET, because the learning curve is smaller;
  • It does not use the ASP.NET postback and view state models what improves testability and separation between user interface and business logic;
  • It has a routing functionality what enables cleaner URLs;
  • It gives the full control over all aspects of developed application. Many elements of the ASP.NET MVC can be easily replaced with its custom implementation (i.e. view engine, controller factory);
  • It gives the full control over HTML and how views are rendered;
  • It has a great AJAX and JSON support so usage of JavaScript frameworks like jQuery is trivial;
  • It can be easily integrated with any of popular Inversion of Control frameworks;
  • It has quite big community, there is a lot of online documentation and books;

Weaknesses:

  • It is based on the Convention over Configuration principle, what means more magic working in a background (probably harder debugging in some cases);
  • It is not event driven, so can be difficult for people who know only ASP.NET Web Forms to wrap their minds around it;
  • Third party libraries support is not that strong. Not to many companies write extensions for this framework what means more work for internal team;
  • Current version (1.0) requires some additional effort to reduce usage of magic strings to the minimum;

Opportunities:

  • Allows for Test Driven Development – it is build with TDD in mind, so it is much easier to write unit tests, mock objects and to intercept the program flow;

Threats:

  • Bigger ramp-up and training time is required for developers with no or little experience in web application development;

For the time being this is all what came up to my mind. If you have some other thought I will be grateful if you will share them with me.

ASP.NET MVC in a corporation – part #1

Posted by – August 25, 2009

.NET LogoEach big organization like this in which I work is mostly based on processes. Everything from purchase orders to computer hardware is described by them. To be honest I am not a big fan of this way of work. My mind is closer to Agile way of thinking rather than stiff procedures for solving problems but from a bigger perspective this approach seems to work because my current employer has over 100 years and is in very good health.

One thing which is quite funny with processes is that someone has to figure out how each of them should work. In case of my department, which is very young and in its nature very different than rest of the organization, there is no process for many things and we have to develop them for our own. One of our processes is “software development process”. Because the department consists of about 300 developers, administrators and IT specialists and we are using wide range of tools and technologies, the process I mentioned above is very general and describes things in a high level. In order to be able to use it and be safe in case of internal or external audit we need many supporting documents which customize it to a needs of particular team. This detailed documents describe how we should do development in a particular technology (for example .NET Framework), what tools, libraries, methodologies can we use etc. Of course we do not choose tools with which we will work only basing on our subjective opinions and feelings. During choosing process each technology or tool is evaluated by a group of specialist (developers, administrators) and compared to its competitors/equivalents which are available on the market.

Currently I have a pleasure to initialize a process of ASP.NET MVC evaluation. Its purpose is to check if this framework can be used as the replacement for ASP.NET Web Forms and Model-View-Presenter pattern which we are using now. Because the evaluation process does not touch only ASP.NET MVC but also other presentation framework for web .NET application me and my teammates had to prepare a list of things to check and evaluate:

  • Data binding
  • Validation
  • Navigation
  • State saving
  • Embedded controls support
  • Testability
  • Security
  • Collaboration between developers and UI designers
  • Adoption to existing projects
  • Extensibility
  • Community support
  • Documentation availability
  • Development tools support

Order in which topics on the list appear is accidental and all items are in my meaning equal in theirs importance.

Because I am currently at the beginning of the ASP.NET MVC evaluation I do not have to much more I could share with you. Only thing I have prepared is a mind map with detailed topics I will have to take a look at. I will provide more information about pros and cons of the framework for a big companies in a next posts. If you would like to hear about something regarding this topic please leave your comment below.

My beginnings with Ruby

Posted by – August 23, 2009

Ruby LogoSince some time I have had a feeling that I should turn my eyes in direction other than .NET and technologies connected to it. Maybe not as a new path of career, because I have invested a lot of time to get to the point where I am now, but as something additional what can give me some new perspective and help to become a better developer. Because I cannot learn all available technologies I had to choose one and only one of them. After reading some blogs and mostly because of Jeremy D. Miller’s opinion my choice fell on Ruby and the Rails. So many developers are excited about this technology, I decided to find out what is a source of theirs excitement.

So how am I going to learn Ruby? First of all I always try to start from a book. In this case I am going to read (in fact I have already started yesterday) Polish translation of “Ruby in a Nutshell” by Yukihiro Matsumoto. I think and the author has the same opinion that this is not the book for someone who is new to programming and wants to learn his first language. The “Ruby in a Nutshell” is something like language reference but in more accessible form so for me (developer with above 8 years of commercial experience) is perfect. I do not need 20 pages of description how to use while loop or what are iterators and where can be used.

I am not able to read this type of book from end to end without touching computer so during reading I am going to play a little bit with the language itself in a more practical manner. In order to do it I had to setup a development environment and there I faced first problems. Turned out that current version of Ruby (1.9) for Windows does not have official all-in-one installer. There is installer for version 1.8 and some preview installers for 1.9 which do not work perfectly (at least on my Windows 7 machine). Because of this I had to install Ruby manually using binary distribution and again I had problems. Of course binaries were in a form of compressed file so I uncompressed them and moved to C:\Ruby directory. Secondly I have added C:\Ruby\bin\ path to the environment variables. In my opinion this should be all I have to do to start learning but turned out that I was wrong. The official binary distribution does not contain all required libraries and was crashing from time to time. After some googling I have found very useful blog post (unfortunately I have lost its address) which solved my problems pointing where I can find missing libraries and where should I put them.

When I had Ruby environment ready to work, theoretically I was able to start playing with it but … I am .NET developer and I used to use reach IDEs with syntax highlighting, suggestions, debugging, refactoring tools etc. I decided to find such tool but about it, learning progress and my thoughts about Ruby from perspective of my quite long experience with .NET I am going to write in some of future posts.