If you use Github (Git) or Bitbucket (Mercurial) you are familiar with the ability to fork a project into your own repository in those sites.  Once forked you can start working in your own repo and once you are ready to integrate you will send a pull request to the master repository. Codeplex recently started using Mercurial but it doesn’t have (or I couldn’t find) a way to clone a project directly from inside Codeplex. UPDATED March 5: Yesterday Codeplex added support for forks, check this article here. First, cloning to your local computer You need to have TortoiseHg installed on your computer before going forward with this tutorial. First you need to check out the project you want to fork using the clone url: Go to the source control page of the project and click on the source control connection instructions. Copy the clone url and open the TortoiseHg clone window. Enter the repository url as the source path and select a folder where to clone the repository. If you don’t have a folder already created for this repo, just add the name in the destination path text field and the folder will be create. Second create a project on Codeplex and add as a Sync source. Log into Codeplex (or create an account) and create a project where you want to work on, make sure you select Mercurial as your source control. You should be able to also use Google code to host your clone, everything should work the same, just make sure you use Mercurial as well. Once the project is created go to your new project source control page and copy the address to your repository. In your computer open the properties of your cloned repository (the one we cloned in the previous step). Go to the sync tab and click in the Add button. Notice that the default (an only) repository is the original one, we want to add the repo to our newly created project and set it as default. If you are using https authentication make sure you add your username and password following this form: https://username:password@hg01.codeplex.com/repository Add any Alias name but not “default”, not now. Click Ok. Select the Remote repository marked as default and click the edit button, change the alias from default to “origin” Now in the sync dialog select the new repository (the one pointing to your project) and click the Set as default button. Once done you should have something like this, the name of the projects should reflect the projects you are working with. At this moment you are ready to push the code to your new project, just open the synchronize window from TortoiseHg and click push. Once this is done, go to the source code tab in Codeplex and take a look, notice that you should have all commits from the original project plus any new commits done into your clone, in this case I added three commits after cloning.   From inside Visual Studio Or course this works from inside Visual Studio as well if you have the Hg plug-in installed 
I’m a proponent of dynamic languages and I love Ruby and Cucumber but I have to admit that this is cool. I was writing a set of specifications with SpecFlow today and suddenly I saw this error in Visual Studio. Double clicking the line takes you to the misspelling error in the Specification file. I though that was really cool, specially for the slightly dyslexic programmers like myself.
I recently posted about how to integrate Git with Visual Studio. Of course Git is not the only DVCS out there. Mercurial is another source control system similar to Git that is having more and more relevance. Google code have been supporting it for quite a while and recently Microsoft announced that Codeplex is adding it as an option for new projects. (Codeplex already supported TFS and Subversion). At work we use Fogbugz as our bug tracking/project management tool. A few months ago the people at Fogcreek started a beta for Kiln a code review/source control system that runs on top of mercurial. I sign up for the beta and have been running a pilot project on it. Since I really like it I decided to start moving all our projects to Kiln and ditch Subversion. The piece that I was missing was a good integration into VS for the rest of my team. A few day ago I found Mercurial VSS an integration package for Mercurial into VS. The installation is very simple, just select the version of VS you want to install against (version 1.0.7 released today integrates without problems with both VS 2008 and 2010 RC). After installed go to Tools –> Options and make sure you select display all options (only in VS 2008).  Select the Source Control option and in the Plug-in Selection option change it to Mercurial. After open a project (even one that is already under source control) you will need to select the Add to source control option from the contextual menu inside the Solution explorer. After added you will se a tilde besides each project. This are the options available from the contextual menu. And a few screen captures of the different options. Change log  Commit  History  Pull  Push  Revert  Tags  Update Conclusion WIth the support from Codeplex and Google code to Mercurial and the tight integration that this plug in presents I see no reason why people will not use it as the DVCS of choice for .net open source projects hosted on those sites.
I started to use Git seriously 5 months ago when I sign up for my Github account on September 1st 2009. Before that I was a very happy subversion user. One of the things that I really like about Git is the speed. I decided to use Git from the command line to learn and understand the commands really well. I occasionally used the GUI to perform some tasks that seemed easier to do that way. Git within VS. Even when I really enjoy working from the command line I know that some developers prefer to stay within the IDE and I understand that. Yesterday while installing VS 2010 RC in my newly paved laptop I decided to check out the Git Extensions. After installing it VS presents a new menu item for Git. From this menu you have access to the most common commands for Git. For example you can commit after doing some work on your project (Note: It looks like you have to be in at the project level and not at the solution level in the solution explorer for the commands to work. Although they work in the whole solution as expected.) One thing to notice is that the dialog pick up changes to files modified or added outside the IDE as well. This is the push dialog box, you can select the Remote to push to and the branch from where you want to push. If you need to enter a passphrase a command prompt window pops up: After entering the passphrase you get a confirmation dialog: You can also pull from remote, where you can select to merge, do a rebase or just pull changes. Conclusion. I don’t see myself moving away from the command line but I think is a good alternative
Last week I wrote about using cucumber to test your web applications outside in. In the post I showed a simple example (actually comes with cucumber) to open a browser, go to a site and perform some actions. I showed the same to my team at work and they mention that could be nice to been able to use c# and Visual Studio to do something similar. After thinking about it I decided to give another try to a tool I check a few month ago. SpecFlow. SpecFlow is a tool and a set of libraries to write specifications using Gherkin. You can check the screencast here or read this post from Ryan Lanciaux. SpecFlow can use either NUnit or MsTest as the engine. Now I needed something to drive the browser. WatiN is the .Net port of WatiR and is very easy to use. The problem is that needs to run in a single thread process, so when called from inside an NUnit test we need to add the STAThreadAttribute to the Test method. Of course, this is not a problem when you are writing the Test methods yourself but the way SpecFlow works is that the actual Test method is generated by a tool from your .feature file. The code looks like this (actually I edited it a little bit to make it nicer). So you need to add the STAThreadAttribute to this method. This works great and I was able to drive the browser and write a few test in no time. The problem is that if you edit every time you edit the .feature file this class will be re-generated and you will have to re-add this attribute. (Note: I forked the repo on GitHub, made a change to the source code and sent a pull request to add this attribute by default, not sure if it will be accepted or not). I think that the integration from SpecFlow with VS is great. If you or your team feel very strong on using VS this is a very good tool (there are versions for both VS 2008 and 2010). After writing the features and running the test you will have hints and code to copy and paste from the TestRunner into the specification class. You will generate the specification from an item template. Conclusion: I think that this is a great tool, specially if you are using it to develop desktop apps or library code in c#. You can use tools like R# to generate your classes and methods from the step definition class directly. For using with WatiN or similar tools to drive the browser I will probably keep using pure cucumber with Ruby at least until the STAThread issue gets solved.
On my new project I want to start using end to end testing. The idea is to write an specification run it against an outer interface. Gui, Web service, etc. It fails. So you start implementing the feature using TDD until the Spec pass. You write a second scenario and you start again. If everything works as supposed I should have a fairly well tested application, not only at the unit level but at the integration and user acceptance level as well. Since the application will be written in c# I look around for some tool to write the Scenarios in the same language. There are some options but none of them was as elegant as using Cucumber. So I tried cuke4nuke but I have no luck with it. I kept getting an error about server not running or something. It looks like a permission problems with win 7. I’m sure I could have figure it out (some confidence I have on my abilities ) but after giving it a second though I decided to go with Cucumber and RSpec for those test. Drive the browser with Watir and hit the web services end points with webrat, sometimes even script the UI with webrat when the browser is not really need it. Installing all the gems is easy just gem install cucumber gem install webrat gem install mechanizer gem install watir gem install rspec |
and you are done (at least in my case). Of course you need to have ruby installed in your system. I have 1.8.6
Since I haven’t really used Cucumber before and my Ruby is still very flaky, I decided to use RubyMine as my IDE to write the specs, specially because you can generate the step definitions from the features in a similar way as how you generate code with R# in VS.
You start writing an Spec with one scenario like this:
Then you run it via the console and have this result.
Note the yellow squiggly lines on the step definitions for the scenario? If you move the mouse over them a prompt will indicate that the step haven’t been created yet:
Hit Alt+Enter to see a suggested solution:
Click enter and you have some options, to use an existing step definition file or create a new. If you hit create a new one and you don’t have an step_definitions folder RubyMine will create it for you.
In this case I select the existing bing_steps.rb file
Notice that the values between quotes are replaced by a regular expression, hit tab to modify the different tokens of the method template. After generating all the methods and adding the necessary code, this is the result.
And when running via the console this is the result:

In this case we are running this specs against an existing piece of software, in my case I will run this against a new un-written site. So to see the scenario pass I should write the feature as well.
Since I started using Git a few months ago, and particularly GitHub since last September, my life have been good in DVCS land.
I used to be a Subversion user and I was happy*, maybe because I didn’t know anything better. Of course I heard all the cool kids (specially in the Ruby world) talking about Git and bragging about it, but I was being loyal to my old pal SVN. But this was slowing me down and I wasn’t aware of it. I’m not sure what make me install msysgit for the first time. After struggling a little bit at the beginning and wrapping my head around the concepts and the commands I noticed that my flow started to change.
This change was good. Was more Agile. Doing small commits for little changes of code seems natural since the speed of this commits was almost instantaneous (remember the commits happens in your own machine). I’m talking of commits been done almost at the line of code level. Change this line, run the test, commit. Write another test. Make it fail. Write some code. Make it pass. Commit. Refactor. Run test. Commit. Keep going.
Once It was time to push those changes to the master a single command push every change + every comment at blasting speed. Since them I started using Mercurial as well and the experience was very similar. In the case of Mercurial I just use TortoiseHg but I stick with the command line for Git for most of my operations and I’m glad of that decision. I wasn’t planning on writing this post today but I just happen to grab the code for edgecase Ruby Koans from GitHub and it took me all of 1 minute to do everything. Here is the flow: Open Console2 and launch the Git bash. Type the following sequence of commands. Welcome to Git (version 1.6.4-preview20090730)
Run 'git help git' to display the help index.
Run 'git help <command>' to display help for specific commands.
Hernan@HERNAN-STUDIO /c/Development
$ cd Code/Ruby/Koans_unresolved/
Hernan@HERNAN-STUDIO /c/Development/Code/Ruby/Koans_unresolved
$ git pull git://github.com/edgecase/ruby_koans.git
fatal: Not a git repository (or any of the parent directories): .gi
t
Hernan@HERNAN-STUDIO /c/Development/Code/Ruby/Koans_unresolved
$ git init
Initialized empty Git repository in c:/Development/Code/Ruby/Koans_
unresolved/.git/
Hernan@HERNAN-STUDIO /c/Development/Code/Ruby/Koans_unresolved (mas
ter)
$ git help
Hernan@HERNAN-STUDIO /c/Development/Code/Ruby/Koans_unresolved (mas
ter)
$ git pull git://github.com/edgecase/ruby_koans.git
remote: Counting objects: 294, done.
remote: Compressing objects: 100% (286/286), done.
remote: Total 294 (delta 184), reused 0 (delta 0)Receiving objects: 44% (130/29Receiving objects: 45% (133/294)
Receiving objects: 100% (294/294), 51.84 KiB, done.
Resolving deltas: 100% (184/184), done.
From git://github.com/edgecase/ruby_koans
* branch HEAD -> FETCH_HEAD
Hernan@HERNAN-STUDIO /c/Development/Code/Ruby/Koans_unresolved (master)
$
Notice that I had to type help because I didn’t remember if I had to add a remote or I was able to do a pull right away (I removed the help output from the console output fro brevity).
Of course the Ruby Koans are just a bunch of very simple text files but the whole process took me less than 2 minutes. I think that is not just because Git is faster but also using the command line for this type of task tends to be a lot faster than using a Gui tool.
If you haven’t try it yet go ahead and take the plunge. Go distributed, even if you work alone, you want regret it.
*I’m still using Subversion at work, looking forward to have the time to switch but we are dealing with some time sensitive projects so I don’t want to mess around with that.
I try to be pragmatic in my approach to development and one of the things that change the most are the tools I use to deliver software. There are several reasons why I change tools so often. - The evolution of the software I write call for new or different tools.
- Search for efficiency and eliminate pain points.
- I change my approach to software development and new methodologies need new tools.
- I just love to try new stuff
 In this post I want to concentrate in the tools used to manage projects and builds. Until recently my favoured tools in this context consisted of NAnt, CC.Net/Hudson and Subversion. For bug tracking I used the bug tracker in Google code for my OSS projects integrated to TortoiseSVN or BugTracker.Net. (Note: At work we use FogBugz and we are very happy with it.) Subversion was the first to go. Subversion is a great VCS but I usually have two problems with it. Speed and problems with complex merges. When I work alone, merges are not an issue of course, but speed still is. At the same time more and more people seems to be switching to DVCS (Distributed or Decentralized) systems like Git or Mercurial. After taking a quick look at GitHub and follow their tutorials I was able to move some of my projects there in a few hours. (Most of the time spent on reading and learning from other people mistakes). Git is fast, Fast, FAST! The whole idea of local commits and clone repositories is fantastic and they really help me with my workflow in the sense that I can do one or two changes, commit, one or two more, commit, find a bug, revert change, finish a story, push to GitHub. To manage Git I’m using a combination of command line and graphic interface using Git gui. So far I haven’t feel the need to use/install TortoiseGit. I still have some projects hosted in google code and I’m using Subversion with them, I’m thinking on switch them over to GitHub once I start working on them again. Nant followed it. I don’t have a problem with XML so the fact that Nant is XML based does not bothers me, really. But I also like the power of a good scripting language to manage repetitive tasks. I decided to move away from Nant and try to adopt some of the newest build systems. I took a look at psake and them I read “How a net developer learned ruby and rake to build net apps in windows” by Derrick Bailey and that convinced me to take the plunge. My knowledge of Ruby is extremely rudimentary but I even with that handicap I was able to have a Rake build script up and running in less than 90 minutes. This script cleans the build target, create the Package folder, builds the VS solution, run Nunit test on two dll's, generate the NUnit report as an xml file, and run the migrations from Migrator.Net (that last part is not working yet, I will need to take a closer look at Migrator.Net command line args). The most useful resource on Derik's post was Laribee's OMG Rake!. Laribee’s sample code and a few queries to Google was all I need. (No, I did not copy and paste ALL Laribee’s code, just use it as a reference) Agile Zen or project management made easy. I got a free account on Agile Zen the first week after they went live. I remember creating the account, playing around on the Board and leaving the site. My thoughts at the moment were something like. This is actually cool. Very nice design. Good usability. I should give it a proper test drive with some real project. Of course, I never came back until last Friday. While working in a few features for Pronghorn I decided that it was time I stop spiking and started to write proper user stories to drive the framework. I remembered Agile Zen and went back. The site looks great and there are some improvements since that last time I saw it. What really amazed me is how intuitive the whole process is. There is no waste generated by using this tool. Creating stories is 1 click. Editing stories, another one. Color coding two clicks. Double click in a field to edit them, etc. Very easy, very intuitive. There is even a bar at the bottom with hints that I decided to hide and I didn’t miss it. The site is very responsive and the only thing I miss is integration with a VCS system. They have a very simple API for paying accounts, but in the docs it looks like is read only, so no hooks in there (If anybody knows otherwise, please leave a comment). I will keep using it for another week or so before making a final decision but so far everything indicates that I will be upgrading the account to a paying one pretty soon. (The free account only allows for one project and one developers, what is more than fair.) Tying it up all together with CI. As I mentioned before my main experience have been using CruiseControl.Net and Hudson as the CI servers. I installed TeamCity a long time ago to give it a try but I never use it. My first choice was to look for some hosted solution. After searching I only found a few and non of them worked with .Net (at least not at the moment). I was going to go back once more with Hudson but I wasn’t able to connect to the Hudson site to download the code. (Their site is up now). So I decided to take a new look at JetBrain’s TeamCity. At the moment of this writing they are running the EAP for version 5. I wanted to install it and use my newly crafted Rake build script with the .Net project and have my test report integrated in the dashboard. First I got the msi from the daily builds for version 5.00. Double click on it to install the server and the agent and after a few minutes and two (three?) questions, the home page of the serve shows up in the browser. Creating the first project and associated build profile was a breeze. I just followed along the instructions in the screen. A few times when I wasn’t sure what a given label meant, I made use of the contextual help. I did have an issue but it was my fault when setting some relative path to the build file and the build target, for running test and creating the Package folder. From downloading the installer to having the project building successfully took me between 10 to 15 minutes. Conclusion. This new setup makes me more productive since I have better tools that save me time in different areas like. Setting things up, working around their idiosyncrasies, configuration heavy or too verbose a language. While this is a combination that works for me, yours may be completely different. The important part is to have tools that feel this roles and make sure that they are really working with and for you and not the other way around.
The NoSql movement is gaining more and more inertia. A year or two ago I took a look at CouchDb but this time I wanted to try MongoDB. I have been hearing a lot of nice things about MongoDB, mostly about how simple is to query it and how fast is. So I decided that it was time to actually take it for a spin. A quick search point me to this odetocode post that was a great starting point to have Mongo running in my dev machine using the defaults and the Driver for C#. So, go and read K. Scott Allen’s post if you want to follow along with the code in the rest of this post. Detour (some background on NoSql and MongoDB): If you already know about this you can skip all this paragraph. The so called NoSql movement is based on the notion that using RDBMS may not be the right choice in some cases. They propose using alternative databases, like key-value pair storages and document databases. To perform operations on the data some make use of Map-Reduce, others like MongoDB use a query mechanism that resembles Sql. One of the most attractive features of this db’s is the ability to easily run clusters and do data sharding. Most of them support both features without a lot of fuss, or that I heard. MongoDB is a document based db, that stores the information as Binary Json. End of detour. What’s a document? A document is not the equivalent to a Row. A document can be seen as a key-value pair collection of objects. It’s actually a complete object Graph, persisted as Json. Documents are organized into Collections. Now, to be usable in C# we need to have some mapping from the Document object to our object graph. We could use the Document directly but will be like going back to use DataTables, not very pretty. 1: var movieName = movie["Name"].ToString();
2: var actors = JsonConvert.DeserializeObject<Dictionary<int,string>>(movie["Actors"].ToString());
The simple way to go from Json to an object should be to pass the load of a document to a JsonDeserializer like Json.Net and just get the object back, like this: 1: var movie = JsonConvert.DeserializeObject<Movie>(document.ToString());
But while trying to do so I got an error in the id of the document. Looking at the paymoad of the document the Id looks like this: 1: "_id": ObjectId("4eebf0006829c72c1d000000")
The problem is in the ObjectId function. But do not despair, there is an alternative.
From a document to a fully usable object graph.
The alternative is not pretty but works and is easy to implement. Just pass the document to the root of your object graph, an access the underlying collection via the objects properties. Let’s see how this can look like. (Note: Yes there are some hardcoded strings in there that should be removed. I’m also never closing the connection to the Db, when I probably should). 1: using System;
2: using System.Collections.Generic; 3: using Newtonsoft.Json;
4: using MongoDB.Driver;
5:
6: public class Repository
7: {
8: private Database _db;
9:
10: public Database Db()
11: {
12: if(_db != null) return _db;
13: var server = new Mongo();
14: server.Connect();
15: _db = server.getDB("DynamicProgrammer");
16: return _db;
17: }
18:
19: public void Insert(Document document, string collectionName)
20: {
21: var collection = Db().GetCollection(collectionName);
22: collection.Insert(document);
23: }
24:
25: public IEnumerable<TDocument> getListOf<TDocument>(string whereClause, string fromCollection) where TDocument : IMongoEntity
26: {
27: var docs = Db().GetCollection(fromCollection)
28: .Find(whereClause).Documents;
29: return docsToCollection<TDocument>(docs);
30:
31: }
32:
33: private IEnumerable<TDocument> docsToCollection<TDocument>(IEnumerable<Document> documents) where TDocument : IMongoEntity
34: {
35: var list = new List<TDocument>();
36: var settings = new JsonSerializerSettings();
37:
38: foreach (var document in documents)
39: {
40: var docType = Activator.CreateInstance<TDocument>();
41: docType.InternalDocument = document;
42: list.Add(docType);
43: }
44: return list;
45: }
46:
47: }
48:
IMongoEntity is a simple interface to force our entities to expose the Doc property. 1: public interface IMongoEntity
2: {
3: Document InternalDocument { get; set; }
4: }
5:
And our Movie Entity will look like: 1: public class Movie : IMongoEntity
2: {
3: public string Name
4: {
5: get { return InternalDocument["Name"].ToString(); }
6: set { InternalDocument["Name"] = value; }
7: }
8:
9: public int ProductionYear
10: {
11: get { return (int)InternalDocument["Year"]; }
12: set { InternalDocument["Year"] = value; }
13: }
14:
15: public Dictionary<int, string> Actors
16: {
17: get { return JsonConvert.DeserializeObject<Dictionary<int, string>>(InternalDocument["Actors"].ToString()); }
18: set { InternalDocument["Actors"] = value; }
19: }
20:
21: public Document InternalDocument { get; set; }
22: }
Notice I’m using JsonConverter to return a complex type, we should probably encapsulate that functionality in some kind of base class, maybe convert IMongoEntity into an abstract class that provides some basic utilities.
I will try to dig deeper into MongoDB, seems to be really suited to a Domain first approach. I wasn’t able to have anything but the most simple queries working, so I will have to take a closer look at the syntax.
Some time ago I heard about the intent of putting together a package manager for .net ala gems or pear. I wasn’t aware that this project was actually under way. The name of the project, Horn. Please check the links in the project home page on how to get started with Horn. It’s very simple and actually works as promised. One thing you need to remember is that you will have to install a subversion client and a Git client for Horn to check out the source code from the projects you want to build. I had two issues in my Win7 machine, where I tested. The first issue is related to Git really and not to Horn and/or Win7. Make sure that you have the path to your git.cmd into the PATH of your computer. It’s usually %PROGRAMFILES%/Git/cmd, if you don’t when trying to do a horn –install on a project using Git, Windsor (the Ioc container used by Horn) will throw an exception. The other issue seems to be a concurrency issue when trying to read a Temp file. Not sure how this files is been created just yet. This happens while trying to build complex projects like MvcContrib. Re-issuing the install command will “resume” the build. It took me three attempts to build MvcContrib. Even with this issue (that may not be a Horn issue at all) I think that this is a very important project for the .Net community. It makes building this complex projects with all the dependencies a routine task. You don’t have to spend hours tracking down the project, the source code and pray that everything builds and works well together.
One new feature in the code editor is the ability to put sticky notes in the code while debugging. This sticky notes are actually attached to a given variable and you can see the actual value of it in the note (similar to using the watch window). To make use of this sticky notes you just need to hover your mouse over a variable while on a debugging session and in the hint for the value of the variable you will see a little note icon. Click in the icon and a sticky note will be placed near the location of the cursor, you can move this note around in VS so it doesn’t interfere with the code. Notice that the value is null since the variable have not been evaluated yet. You can click in the button of the note to add a comment. If we continue running the program we can see that the value have been updated. This variable will hold an array of squares, so the value is the Length of the array. Click in the plus sign and you can see each value, now each value has an sticky note icon besides it as well, clicking them will add this variables into the same sticky note. The notes disappear once the debug session ends, but starting a new session will bring up all the notes back. 
I needed to do some screen captures for a future post I’m writing. This is usually not a problem but in this laptop I don’t have an screen capture utility installed. So I did a search in Windows 7 just typing screen capture in the Search Programs and Files box to see if it has something already before downloading one of the two tools I usually use. And the result was Record Steps to Reproduce a problem. I was, of course, curious about it. So I clicked and a recording bar displays on top of my applications. After clicking the Start Record button, whenever you click in the screen a red dot fades in and the screen gets capture. Now, this does not records video but still images, every click a new image, a new step. You can also add comments while recording. Click the stop button and will prompt you for a place to save a zip file. The zip file contains and mht file (MHTML Document) I guess the M stands for Microsoft, that can be opened by IE. This document has all the screens in the proper order they were captured with a highlight of the area clicked, plus a detailed step by step trace of your workflow, like application, document open, where you click, etc. Also the comments will be added to the proper step. You can even review the error reported as a slide show. I’m not sure if this was there before on Vista or XP. On Windows 7 you can find it in the Control Panel, under Troubleshooting, but the only way I can make it show up is using the search function. This can be very helpful if you need to see what a user is doing on their computer with a piece of software you wrote.
I have been playing at home for the last few days with different migrations strategies for db development. The one that I like the most so far is Migrator.Net. Here are the things I really like. The migration project/code is independent from the technology you use to persist your data, so changing persistence strategies does not affect your migrations. You have a good migration history, since each new migration is it’s own class. It provides an Up and a down method to run the migration or undo it. You mostly don’t have to write SQL, but you can if you need/want. Let me clarify that point. I’m not one to mind writing SQL, I rather enjoy it and take pride to been able to write some clever statements. At the same time I recognize that most of the time you write very boring and repetitive task, but what bother’s me the most is the constant context switching from VS to Enterprise Manager. That has to affect your productivity. The fluent interface is very easy to use, and I only had to consult the documentation to set up the MSBuild file to run the migrations from inside VS, mostly because my experience with MSBuild is very limited. I was tempted to use Nant that I’m very familiar with and they provide a custom task for it, but I use this opportunity as a way to get my hands dirty with MSBuild. Writing migrations involves creating a new class that derives from Migrations and implement two methods Up and Down, you also need to add a [Migration()] attribute and specify the migration number in it. I decided to use a date+time migration number of the form “yyyyMMddhhmmss” that translates to something like: 20090726120152. You can also use numbers like 1,2,3,etc… I prefer the date time format to work in a team, less chances of two people creating migrations at the same time. But the title of the post is about a template for Resharper to create most of the work for you. So that was what I did, and you can download this Zip file with the template in it.
Tonight I added LinqPad to my toolbox. I did try this before but I guess I wasn’t very inspired because I didn’t stick with it. Let me tell you, that was a mistake. I have been playing with it for an hour or so and I’m loving it. What is LinqPad you may ask? The name comes from the ability to write Linq queries in it, but it’s actually much more. I will just use this snipped from their home page: it's a highly ergonomic code snippet IDE that instantly executes any C#/VB expression, statement block or program – the ultimate in dynamic development. Put an end to those hundreds of Visual Studio Console projects cluttering your source folder! One of the options that impressed me the most of the ability to write small programs directly in LinqPad, hit F5 and they are running. No more open VS to write a quick console app to do some admin task. (Yes, I know that I can use PowerShell or some dynamic language for that.) But using this tool brings this feature to your favourite language C# or VB. Add this as an external tool to VS and doing quick exploratory testing will be a non issue. You can also execute SQL if you need to and you can add references to your own types to do complex queries on them or just to consume them from a program. Dimecasts.net has a series of videos on how to use the tool and some other video links can be found in the external links section of LinqPad’s site. Just don’t make my mistake, download it, install it and start using it. The tool is free, if you want auto completion you have to shell just 19 bucks (I’m seriously considering it).
You can find this text in the the wiki for Pronghorn on Code plex. http://pronghorn.codeplex.com Pronghorn is still a work in progress and the architecture+design is changing very fast. At this moment the main focus is on the ViewEngine because is what will provide most of the value for my actual employer. Most LOB applications can be done using just one or two master pages and one area of content per URL. In this context ASP.NET MVC can be used out of the box with no or just a few changes. HTML.RenderAction can be used in lieu of widgets in the page without a big penalty on composition. But there is also a need for more complex applications, those where web pages are build from a collection of discrete components (widgets). These widgets should be added or removed in a dynamic fashion without the involvement of a developer. Those are the scenarios where CMS frameworks come to play. Pronghorn is not a CMS but it provides the tools to make this type of composition on top of ASP.NET MVC. To accomplish that much, Pronghorn has “some opinions" on the way you should build composite applications using MVC. These opinions are expressed via the use of interfaces and base classes that extend and sometime constrain the MVC framework. Controllers should be small and map to only one resource. They should be Rest-like (use the HTTP verbs for the actions names, enforced via the ControllerBase.ExecuteCore). The ControllerBase.OnActionExecuted adds "Areas" for a given view based upon the Controller, Action and SiteContext. This Area loads a collection of widgets in a specific order, that can change from area to area between pages. At this point is where the ProngHorn.ViewEngine kicks in. ProngHorn.ViewEngine is an html based view engine, that uses a similar syntax to the one used in the prototype.js templates. Composition is achieved via some Injection mechanism using DI. Widgets "publish" to the page, called skin in Pronghorn witch css, js files will need. These resources should be minified and combined to reduce network traffic and # of http calls from the browsers to improve performance and load time. To keep up with the project you can subscribe to the project’s wiki RSS. Where you can get all the updates, a bit chatty but may be useful or visit the project’s home page periodically.
In a previous article I mentioned how to integrate VS 2008 with Subversion for free using a few settings and a script. (go read the previous article to get all the code). When I run the script in Windows 7 all the menu items were grey out. The problem was that the script use the variable %PROGRAMFILES%. For whatever reason in Windows 7 this doesn't work and you have to replace with the hard coded path C:Program files and them everything works. I guess that you should be able to do the changes in the vb script file before running it.
One of the main reasons I got ReSharper originally was for it’s ability to do micro code generation. This is a functionality that I found very useful when doing test first development. You can write your test first that will access an object that it doesn’t exist yet and them consume some methods on that object. Them you just go Alt+Enter and ReSharper will generate the stubs for the class, the methods and the properties. VS 2010 incorporate this functionality as well. In ReSharper you can write the initialization of a new class that it have not been create yet and you will see the blue underscore below it. Hit Ctrl+. (Control+dot) and a drop down menu will ask you to generate the class. All this is good and works very similar to ReSharper, but not so powerful. If you are initializing the class with some parameters a constructor will be created for you. The name of the parameters will be inferred (if at all possible) from the name of the variable that you are using in your code. For example in this code the MyNewClass didn’t exist before hand. 1: public void CreateClassFromusage()
2: {
3: var obj = new MyNewCLass("someVariable");
4: obj.GetSumOfTwoNumbers(3, 5);
5: var originalString = "This is the title.";
6: var stringsToAdd = new[]{"First line","Second line"};
7: string concatenatedString = obj.ConcatTwoStrings(originalString, stringsToAdd);
8: }
After writing the code I when Ctrl+dot and create the class (it was created in a new file by default, nice) and the methods.
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5:
6: namespace dynamicDemo
7: {
8: public class MyNewCLass
9: {
10: private string p;
11:
12: public MyNewCLass(string p)
13: {
14: // TODO: Complete member initialization
15: this.p = p;
16: }
17:
18: public int GetSumOfTwoNumbers(int p, int p_2)
19: {
20: return p+p_2;
21: }
22:
23: public string ConcatTwoStrings(string originalString, string[] stringsToAdd)
24: {
25: throw new NotImplementedException();
26: }
27: }
28: }
Notice the name of the parameters, in those ones where I used variables the parameters have proper names, the other parameters names are kind of ugly and I hope they fix that (p, p_2?). My suggestion will be to use the type plus some contextual information or at least the type plus the word parameter and them a number if you need it. In the case of strings the whole string or the first word if it’s a phrase. All in all it’s a nice feature to come with the IDE.
A very good presentation with lots of code to learn and appreciate some of the niceties of ActiveRecord.
- Common List E-book (free online)
- OpenDBDiff
- The latest release was a month ago and is looking really good. I plan to give it a try later this week or next week.
- Ioke
- Now runs on the CLR. Ola Bini has also a few posts about writing the implementation in C# and F#. Ioke is a very interesting young language and Ola have been posting about the decision made and the though process behind the design of it.
- NRegex and Ioke.Math
- As a side effect of implementing Ioke on the CLR, Ola Bini created NRegex. According to the author NRegex is: "a perl5.6 compatible regular expression engine. It supports named groups, is thread safe, supports look ahead and look behind, and is compliant with level 1 of Unicode Regular Expression Guidelines.” Thanks, Ola. To download NRegex just download Ioke and you will find the NRegex.dll in the bin folder or get the source code from the Git repository.
- Bini also implemented BigNumbers and other nice types in the Ioke.Math library. “One thing that really surprised me about .NET was that there is still no support for arbitrary precision math - neither big nums nor big decimals. I ended up implementing that myself, so now there is at least one open source library with liberal license that people can use.”
In a previous post I mention about a fix to been able to open a new window both in IE and Firefox using the Lightweight Test Framework. Today I want to talk about how to hook into the newly opened window or any other window opened by the testing framework. Let me said this, it’s not very difficult but is kind of convoluted, I won’t be surprised if there is a better way to do this, but I can’t seem to find it. The key resides in the BrowserCommandTarget object. This object has a property WindowIndex that maps to the index of the _windowCollection array on the client side code (the JavaScript implementation of the framework). The next thing we need to do is figure out how to send a BrowserCommand to this window, and sure enough BrowserCommand has a target property that takes a BrowserCommandTarget. So here is the code to click a button in a window that was open after calling window.open in the main window. 1 [WebTestMethod] 2 public void OpenNewWindow() 3 { 4 var page = new HtmlPage("../SiteToTest/HTMLPage.htm"); 5 page.Elements.Find("openWindow").Click(WaitFor.None); 6 7 var handler = new BrowserCommandHandler 8 { 9 PopupAction = PopupAction.None, 10 RequiresElementFound = true, 11 ClientFunctionName = BrowserCommand.FunctionNames.ClickElement 12 }; 13 var target = new BrowserCommandTarget 14 { 15 WindowIndex = 1, 16 Id = "clickedOnTheSecondWindow" 17 }; 18 handler.SetArguments(false); 19 var command = new BrowserCommand(BrowserCommand.FunctionNames.ClickElement) 20 { 21 Description = "Click", 22 Target = target, 23 Handler = handler 24 }; 25 var info = page.ExecuteCommand(command); 26 } Lines 4 and 5 is just the normal way you click in an element. In this case I look for an element with the Id of “openWindow” and do a Click. This is the html of the page we are testing. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head> <title>My page</title>
<script> function doConfirm() {
if (confirm("Do you confirm this?")) {
document.getElementById("mySpan").innerHTML = "OK";
} else {
document.getElementById("mySpan").innerHTML = "CANCEL";
}
}
function openNewWindow () {
window.open("HTMLPage.htm","_blank","toolbar=no",false); }
function addsAMessage () {
document.getElementById("message").innerHTML = "This message should only appear on the second window."
} </script>
</head>
<body>
<input type="button" name="myButtom" value="Do confirm" onclick="doConfirm();" />
<span id="mySpan"></span>
<input type="button" name="openWindow" value="Open new window" onclick="openNewWindow();" />
<input type="button" name="clickedOnTheSecondWindow" value="Clicked on the second window" onclick="addsAMessage();" /> <span id="message"></span> </body> </html>
After this page opens I want to click the button with the name “clickedOnTheSecondWindow” in the newly opened window. For that I create a BrowserCommandHandler that knows how to handle the onclick event. A BrowserCommandTarget with the Id of the element to be checked and I pass the index (1) for the newly opened window, the original window already opened in the test frame is index 0.
Then I create a BrowserCommand and assign the target and the handler to it.
Finally I call ExecuteCommand in the page object passing the newly created command.
This may sound counter intuitive since page is the same object we used before to click “openWindow” in the test frame. But page.ExecuteCommand takes all the data from the passed in command argument. I consider that it should be a better way to do this and maybe this is a smell on the API or me not figuring out the right way to use it.
I mentioned before that BrowserCommandTarget.Id takes the Id of the element, I’m sure that you notice that none of the buttons have an Id but only a name. The framework will first search by Id and then by name always using the value passed to the Id property.
So far I haven’t figured out how to make an assertion in the new window though, I guess that will be something to deal with in another post.
As I mentioned in a previous post I have been playing with the Microsoft Lightweight Test Automation Framework. The Lightweight framework handle alert and confirms without any problem, both in IE and Firefox out of the box. I guess it won’t be an issue on the Mac either. Now window.open is another issue, a JavaScript error was thrown in both browsers. So here is how I fix it so far (so far because I still need to deal with a nasty bug on Firefox). Window.open is not working (and a solution). After digging around and thanks to Firebug (and at a lesser degree, the new Developer tools for IE8) I found that the problem seems to be in two places. Wait until the end of the post to change anything on your files. My first approach. First open the following file (in the source code solution for the framework). Engine/Resources/ScripFiles/BrowserFrame.js We will change the following line: frame._originalOpen = frame.open;
to
this._originalOpen = frame.open;
Engine/Resources/ScripFiles/TestExecutorBase.js
Search for openWindowAndRegister: this is the function that will be assigned to window.open by the framework to handle the calls get a new window object and add it to the browser windows collection of the TestExecutor object.
We will change the following line:
var newWindow = TestExecutor.get_activeWindow().get_activeFrame().get_jsFrame()._originalOpen(url, name, features, replace);
with the following code:
var activeWindow = TestExecutor.get_activeWindow();
var activeFrame = activeWindow.get_activeFrame();
var newWindow = activeFrame._originalOpen(url, name, features, replace);
The temp variables are there just to help when debugging. Notice that we are calling _originalOpen on activeFrame and not activeFrame.get_jsFrame()
Now this will make window.open functions work in IE but not in Firefox where I get an “Illegal operation on WrappedNative prototype object" exception, this seems to be a known regression on Firefox since at least version 1.07.
Upon thinking about this I notice that we should be able to actual use window.open directly inside openWindowAndRegister.
So here goes the solution that works, I kept the changes to BrowserFrame.js but the changes to TestExecutorBase are now as follow replace :
var newWindow = TestExecutor.get_activeWindow().get_activeFrame().get_jsFrame()._originalOpen(url, name, features, replace);
with the following code:
var newWindow = window.open(url, name, features, replace);
window.open returns a windows object and them we can register it to the _windowCollection internal array of the TestExecutor. So far I like this solution, now I need to figure out how to write test against this new window. I guess I will leave that for another post.
UPDATE: There is another way to do this. Check this post from the QA team blog. This is a quick post. In the samples for the framework the test are written in the same system to test. This is not terrible, since you can easily remove those files for the final compilation, but I prefer to have my test in a different project. Well that’s very easy to do. Just create another web application and follow the same conventions that in the sample to create your test. Add a reference to the framework, create an App_Code folder if you don’t have one, add a Tests folder inside and create all your test fixtures in it. Them when loading the pages to test just use a relative path. The important thing is to run the test runner under the same domain of the app you want to test.
I have been playing with the Microsoft Lightweight Test Automation Framework, that’s a mouthful for the Microsoft’s Web testing framework. I think that (in general) looks like a nice alternative to some of the other frameworks around (like Watir or Selenium). I will try to give a quick overview of what I have been using so far and what I like and don’t like. For more information on the framework, take a look at the Forum. What I like. - Open Source (you can download the source from Codeplex).
- A first sample is included
- Since the library is written in c# you can write the test in your language of choice inside VS. This may encourage to write the UI test first. This can be even written by the same developer that is implementing the UI.
- Nice API, providing methods, properties and objects that represent an HTML page and help to navigate the DOM.
- No problem handling JavaScript’s alert and confirm dialogs.
- Look’s to been able to handle asynchronous Ajax calls (I haven’t tried it yet).
- Cross browser, cross platform.
What I think needs improvement. - Documentation (*).
- Some internal objects should be public, like the BrowserInfo. (*)
- Setup, Teardown attributes (not very high on my list, but may be useful). (*)
- Provide a way to attach to a new window, or even Assert that a new window was open. (The JavaScript engine already contains a collection of newly opened windows, so this should be easy to implement).
*. The Roadmap document mention these issues as forthcoming or in consideration. In following posts I will try to find solutions to some of these issues.
Today I have the pleasure to listen to a really good episode of The Herding Code. The episode title was NHibernate performance. In the episode Ayende, David Penton and Ben Scheirman talked about NHibernate and the performance of the tool when compared with writing SQL directly to the database and other scenarios. David Penton is a DBA and he was looking at NHibernate from that perspective and he made some points about why he is doubtful of some of the claim made from the NHibernate team (or any ORM for that matter). Ayende and Ben were able to answer most questions and offer solutions. In some cases they promise to look into the specifics and come back to him with an answer. What I liked about the episode, was the intelligent conversion. How people that not necessarily agree can sit together and talk and collaborate to make the tools and technology better. David offered his assistance to look over queries generated by NHibernate in some situations that may not be optimal and help to improve the tool. Ayende accepted the help and thanked David for the offering. I applaud (as an NHibernate user and as a technologist in general) this attitude. These are the things that will make the community better.
Ok, first let me be really clear, I’m not a JetBrains fan boy. Yes, I use ReSharper and yes, I also use TeamCity at home as my Continuous Integration server for some of my projects. I also use Cruise Control.Net and Hudson in other projects (sometimes both in the same project, to do different things) But the guys from JetBrains do really good products, ex: TeamCity is ,IMHO, the most friendly CI server of the three to set up and ReSharper makes practicing TDD or BDD not just possible but highly enjoyable. So when I came across RubyMine a few months ago I decided to give it a try. I have been using different IDE’s and Editors on my adventures into the Ruby world but even when I found some of them really good I never really feel at home. NetBeans with Ruby support was the one that provided the best IDE experience for me so far, and for text editors I mostly used Scite that comes with Ruby. (I do all my programming on a PC so no TextMate for me and for whatever reason e didn’t click with me. I also tried PSPad, my favorite text editor for everything else, but it didn’t work with ruby. I guess my very basic knowledge of the language didn’t help either. So here are some of the features I like on RubyMine some of them shared by NetBeans. Note: I’m not giving out on NetBeans since it’s free and has support for PHP. Easy code navigation. From a view clicking in the A icon will open the proper controller and position the cursor in the right action.  Now if you are in a controller and click in the View icon besides the action you will navigate to the view if it exist. If the views is not available yet RubyMine will open a prompt to create it. Also some classes have a (dependencies?) icon beside its declaration that help you to browse to base classes and partial implementations  Code hints and code analysis The familiar (for ReSharper users) yellow light bulb, shows up in some cases giving you hints on how to improve your code. In this case I positioned the cursor on the ‘new’ string and the id understands that I’m referring to the new action, so it suggest to use a symbol instead. On the right hand you have hints (yellow, red) about your code. Even on html code. In this case makes the sensible suggestion of get rid off the B tag and replace with some CSS or the STRONG tag: Refactorings Of course you have some Refactorings available for you. Code analysis: And find usages: Conclusion This are just some of the features, for a complete list visit the JetBrains site, most of them also work in JavaScript files and html files, so you can use them in other projects not just Ruby ones.
Today I move the code of LaTrompa.Validation into it’s own package, with no external dependencies (besides the framework of course). I added a class to validate XmlNodes. The string validation now has a IsOneOf method to match the string against a list of options. var options = new[] { "0056", "0256", "0512", "0752", "1100" }; new Validator().CheckThat(() => _stringToTest).IsOneOf(options) .ThrowFirst(); I still need to add a generic version for this method, I guess it pass by me. Also in the string validation there are two new validations to check if a string can be converted into an Int32 or a Boolean. new Validator().CheckThat(()=> "true").CanConvertToBool().Throw(); new Validator().CheckThat(()=>"23").CanConvertToInt32().ThrowFirst(); The whole conversion validation looks like a good candidate for refactoring and generalize it into a base class. that way it will be easy to offer conversion checking against all types. I added the ThrowFirst method into the Validator class. This method was available only in the CheckThat classes. var secondVariable = 45; var validator = new Validator(); validator.CheckThat(() => _stringToTest).HasNoSpaces().LengthLessThan(4); validator.CheckThat(() => secondVariable).IsBetween(56, 100); validator.ThrowFirst(); I moved all the Throw methods into their own class ErrorThrower (I should rename this to ExceptionThrower). Previously I was doing almost the same thing in two different places. Not very DRY.
In my previous post I mentioned how to integrate Visual Studio with Subversion for free and without having to install fancy plug-ins. Now, with Gurtle you install this issue tracker provider that will log into your Google code account and pull all your issues into the commit dialog box for TortoiseSVN. Another small download and easy install. The configuration is a non issue and you should be up an running in minutes if not seconds.
We all know that VisualSVN is a really good plug-in to integrate with Subversion from inside Visual Studio. The free plug-in alternative is Ankhsvn. Now there is another choice and is a set of configuration options to access TortoiseSVN from inside Visual Studio. The set of configurations provide a tools menus, context menu, and menu bar. The following Subversion/TortoiseSVN features are covered in the integration: - Commit - Commit the files to the repository
- Update - Update the current working version
- History - Get the history for the selected file
- Diff - Get the diff compared to the base version
- Blame - Find out who committed the crimes in the file
- Revert - Undo local changes
- Modifications - Check to see if any files have been modified
- Edit Conflicts - Edit the conflicts that arise from merging/updating
- Resolve - Mark the file as resolved for conflicts
- Repository - View the repository on the server
- Project History - Get the history of the entire project
- Add Solution - Add the solution being edited to source control
- Branch/Tag - Perform a branch or tag on the current working copy
- Settings - Set up TortoiseSVN
The menu bar uses the right logos and everything works very well. The only missing piece is marking the files with a little icon the way that Ankhsvn or VisualSVN do. The true is that this set of configurations was easy to install and provides all the functionality you will ever need. I recently use them in my old laptop to commit from inside Visual Studio into Google code and I’m very pleased with the way it works.
I just finished a complete re write of my validation framework. This re write was due to feedback received from some of my co workers so I owe to them my thanks. The validator is not an static class anymore, so you need to create an instance of it. This allow to do multiple checks at once. Like this. var list = new Validator().CheckThat(() => _stringToTest) .IsNotNullOrEmpty<ArgumentException>(null) .LengthLessOrEqualTo<ArgumentException>(10, null) .Match<ArgumentException>("/abc/", null) .HasNoSpaces<ArgumentException>(null) .List(); In this case I call the execution method List() to return a list that contains all the exceptions found. Actually it returns an IDictionary<string,List<Exception>> where the key is the name of the variable we are checking. In this case I’m using the CheckCondition that returns a custom Exception per error, this are Generic methods that need an object[] for the constructor parameters to use in the custom exceptions and a Type that inherits from Exception. The framework also has a simple signature, where the CheckCondition will raise a pre defined Type of Exception, building the Exception message with enough detail in it, like variable name, actual value and expected value or value range. var list = new Validator().CheckThat(() => _stringToTest) .IsNullOrEmpty() .LengthLessOrEqualTo(10) .HasNoSpaces() .List(); This will return the following exceptions with these messages: //Exception type: LaTrompa.Validation.NotNullOrEmptyStringException - Message: The string _stringToTest should be empty or null //Exception type: LaTrompa.Validation.InvalidSizeException - Message: _stringToTest length is 17 but it should be less or equal to 10 //Exception type: LaTrompa.Validation.InvalidFormatException - Message: The string _stringToTest shouldn't have empty characters. The new validator also allows us to check multiple variables at the same time, like this. var validator = new Validator(); validator.CheckThat(() => _stringToTest).IsNotNullOrEmpty().IsEmail(); validator.CheckThat(() => datetime).IsAfter(new DateTime(2000, 10, 10)); validator.Throw(); Throw will throw an exception of type ErrorsCollectionException, this class inherits from Exception but contains a property called ErrorsCollection that exposes the same IDictionary<string,List<Exception>> you can access using List(). This is useful in cases where you want to communicate all errors at once, for example when an end user is entering data in a form and you want to send all the errors back so he doesn’t have to fix each one at a time. Sometimes you want to check only one thing and throw the specific exception for that given check and not the ErrorsCollectionException, this is very useful to program by contract, where each exception should be handled independently. new Validator().CheckThat(() => _stringToTest).IsUrl().ThrowFirst(); What if you want to do multiple checks and throw only one custom exception? Well you do it like this: new Validator().CheckThat(()=>_stringToTest) .HasNoSpaces().LengthLessThan(4).Throw<ArgumentNullException>(null); This also applies when checking more than one variable. var secondVariable = 45; var validator = new Validator(); validator.CheckThat(() => _stringToTest).HasNoSpaces().LengthLessThan(4); validator.CheckThat(() => secondVariable).IsBetween(56, 100); validator.Throw<ArgumentException>(new[]{"Please check the data entered and try again."})
The code can be download as always from: http://code.google.com/p/latrompa/
You can find this new ORM framework at http://code.msdn.microsoft.com/XGENOORM. Starting with it is fairly easy. Just add a reference on your project to the very small (32K) dll (only one!) and you can start playing with it. First impressions. My observations come from reading the documentation and not from using it. What I like. It uses the ActiveRecord pattern what I like personally prefer for simple applications. Since this claim to be a simple ORM this is acceptable. You should understand that this mean that your objects need to inherit from a base class that provides the CRUD operations. If you want to use just POCO’s without dependencies on your ORM this won’t be a good choice. This is an issue with the pattern though and not this particular ORM. Mapping is done using Attributes For Example if you create a new class Dog and you want to mapped into a table Animal you do this [Table(Name = “Animal”] public class Dog { [Column(Name = "Id")] public int Id {get; set;} [Column(Name = "Name")] public string Name {get; set;} }
One of the problems I found from my liked is the querying capabilities, no the lack of but the way they are implementing. You pass a Condition object to the Find method, but this object make use of strings, what it’s ugly and doesn’t work well with Refactoring tools like ReSharper.
If we want to find all dogs where the name starts with A we will do something like this.
var condition = New Condition("Name", "like", "A%");
Not only is using strings for the Column name but also for the operand of the condition. I would prefer a different notation, something like this:
var condition = New Condition<Dog>(d=>d.Name, Operand.Like, "A%");
At this point relationships are not supported they are promising this for the next release.
A nice feature is the Audit Attributes, this Attributes are used to mark some properties of your object to save data as modification dates, creation dates and user that changed the objects. All this is done automatically for you, what it’s a very nice idea.
In conclusion if you need something extremely simple and you don’t care about the relationships you may be able to use it. If you need something more mature using the same pattern I will stick with Castle ActiveRecord at this moment.
As a side note this doesn’t seem to be open source, so there may not be any support from the community, an strength of the Castle project
Methods and Tools its a free online magazine, download as pdf, the winter issue has a very good article about BDDD (Behavior Driven Database Development) and the value of Test. They edit four numbers a year and you can have all the issues on the website since 1999.
Once in a while I like to browse around Codeplex to see what’s new and if I found anything interesting. Today I found this Gem of a project called Catharsis. To be able to use it you will need VS 2008 with SP1. The Guidance Automation Toolkit and I also installed the GAX SP1. The ASP.NET MVC (BETA) installed via the installer. What is Catharsis? You may ask. It’s a complete application framework that uses ASP.NET MVC for the UI layer, they mention to support WPF projects as well but I haven’t see it yet, maybe 1.0 version, the current release is 0.95. But it’s more than that. It’s also a set of tools that integrate with Visual Studio and provide several Wizards to do most task in a very simple way. The solution created is quite complicate but very well organized. Installing Catharsis In the documentation of how to install Catharsis they recommend using the msi file, but I couldn’t find it in the release, so I have to open the Guidance projects, do a build and them run the msi. This was a non issue, you will be prompted to remove the references to Source Control from the solution when you open it for the first time, just click yes. Creating your first project. It’s very simple open the Create new project dialog and you will see a new Catharsis type of project Enter the Name and click Ok, another window shows Click Finish, sit and wait. At this moment you should be able to set up you Web project as the startup project and the Default.aspx file as the Star up page, hit F5 and see it work. I had a few issues at this point. The first one was that the project did not compile: The problem was an extra comma on the file: BaseEntityControllers.cs in the Controllers project under the Project.Web folder. This comma is in the list of Interfaces the class implements. Once fixed the project compiled with no problems but when trying to run it I had my second issue, the tables in the database have not been created. So I had to run the scripts located at DB_SQLServer in order 01_ first and 02_ afterwards. Notice that the connection string I provide in the wizard was correct since NHibernate can connect to the database, so no sure why the scripts didn’t run. Note: To run the scripts make sure you change the first line of them to point to your database (they are pointing to a Catalog called Project, maybe this is the problem during the setup wizard?) Once you have done this, make sure you rebuild the project and hit F5 again and, another problem (the last one). The log4net.dll wasn’t copy into the bin folder of the web solution, so copy it from Assemblies/Log4Net into the proper bin or add a reference from you web project to the log4net dll and rebuild. After that everything worked fine for me. I will try to port an old asp classic application using this architecture and see what I like and what I don’t, but I suggest you give it a try. There are several articles at CodeProject on how to do different things and in more details about the architecture, Ioc, Tracking Changes and more.
My previous post got me thinking, what are the things I will considered as minimum requirements for me to work in a project even when I have serious constrains on time? In requirements I mean methodologies and practices that I will need to use. After some thinking this is what I came up with. There are at least three things, commonly associated to an Agile project that I will want to have in place. - Source control (yes, there are still companies that don’t know what this is). Installing Subversion (VisualSVN server + TortoiseSVN) usually takes 30/60 minutes.
- Continuous Integration server, CC.net, TeamCity: install and configuration 3 hours maybe half a day.
- Using TDD as a design tool at least for the domain but only If I can use ReSharper or a similar tool (I can do with the free version of CodeRush as well).
This is the type of things that I use, even when writing some demo code or my own applications that I’m playing with. At home I have Subversion installed in my dev machine and in and old Pentium 4 that runs TeamCity. I don’t think that this will add any significant amount of time and the benefits are such that I can see myself not using them. I will probably don’t do much in the sense of integration test, (of any at all) in the automated UI test fields and code coverage. I like to do that but not in circumstances as described in the previous post.
Derick Bailey is doing a very good series on Kanban. So far he posted about: The board, queues, order points, pipelines, handling bugs and emergency fixes. You can find all the posts under the Kanban tag.
CAT is a Visual Studio Add-in that analyze your code and all the references in your project looking for vulnerabilities to common attacks. According to the copy in the download page this version deals with: - Cross Site Scripting
- SQL Injection
- Process Command Injection
- File Canonicalization
- Exception Information
- LDAP Injection
- XPATH Injection
- Redirection to User Controlled Site
In my machine at work I can’t install ASP.NET MVC (it installs but fails to install the project templates, I don’t know why and I haven’t had time to look into it). When I installed Sharp Architecture everything went well, but running the project template yields and error. I was doing this at a Starbuck’s, trying to build a proof of concept and was a bit frustrating. I was sure that the culprit was related to the error I had installing MVC. Last night I run across a thread entitled Removed dependency on installed ASP.NET MVC Beta on the Sharp Architecture discussion group. In this thread in reference to a post by Kyle Baley where he mentions the same problem, Billy McCafferty notes that the reference to the MVC templates have been removed on the trunk. Kyle’s post mentions a few alternative solutions and further down the thread there is a discussion about losing the item templates for the MVC project and Replacing them with ReSharper templates. I will suggest just that you can also use Visual Studio Item Templates, creating them yourself in case you don’t have ReSharper. You can see an example on building this item templates in this old post of mine Nant build scripts template for Visual Studio.
SVN Notifier is a nice little tool that sits on your Tray and let you know when a folder under source control on your system goes out of date. It’s useful is you are working on several projects with several developers or you follow the trunk of an open source project. This will let you know as soon as your project gets outdate. You will need to have TortoiseSVN and a Svn client installed in your machine, I use SilkSvn. Once installed you configure witch folders you want the tool to monitor. The icon on your system tray will be Green or Orange to indicate if your projects are up to date or not. Right click on it and you can Update all or open the status window (double click on it also opens the status window). You can also use this tool to do commits for each project. This is really nice, sometimes I work using just a simple text editor and I don’t want to navigate to the folders to do the commits, with this tool I just click in the System Tray icon, right click in the project I want to commit and that’s it, the TortoiseSVN dialog will open and you go from there like you usually do. The other thing is nice is that before updating you can check all the logs right clicking in the project and selecting Change log. 
This is a plug-in for Resharper that allows you to use Reflector and and the .Net framework source code to navigate your code. You can download it from the Google code project page. Install it is a non issue. Once installed open VS and the Resharper options page. Under environment go to Search and Navigation-> Scout Clicking into it will ask you if you want to download Reflector, click Yes if you haven’t done this before. Since I already have Reflector I just browse to the exe file. You can them can set some configuration options like using the same instance of Reflector each time or set some configuration per solution or custom. To configure the MS server reference follow the instructions on Scott Gu site. Once you are done you can do right click in a class or method and hit Go to declaration, is the class is in an external assembly reflector will open up and navigate to the given method showing the code in it. For example HttpContext.Cache(). Very powerful.
Ok, the patch can be downloaded from the Issue tracker of the project. This support the following notation in the app.config. <setting name="IncludedProjects" serializeAs="Xml"> <value> <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <string>CCNet</string> <string>Ivy.NET</string> </ArrayOfString> </value> </setting>
Where each <string> is the name of a project. The project names are case sensitive. If you set a RegEx to filter the projects, the expression will be evaluated first.
This patch have been done over the Revision 125 of the Trunk.
Enjoy!
This looks very interesting. (from their site) ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment. Once ELMAH has been dropped into a running web application and configured appropriately, you get the following facilities without changing a single line of your code: - Logging of nearly all unhandled exceptions.
- A web page to remotely view the entire log of recoded exceptions.
- A web page to remotely view the full details of any one logged exception.
- In many cases, you can review the original yellow screen of death that ASP.NET generated for a given exception, even with customErrors mode turned off.
- An e-mail notification of each error at the time it occurs.
- An RSS feed of the last 15 errors from the log.
- A number of backing storage implementations for the log, including in-memory, Microsoft SQL Server and several contributed by the community.
I haven’t use it yet, but it really sounds like something that I see myself incorporating into my tool box. You can download it from Google code.
I have looking for a simple to use, fast, ubiquous to do list for a long time. I used several different solutions. Web and desktop application. So far none of them really worked for me. Some of them are too simple, other too complex. One that I still use is Task Coach. A nice little application that allows me to create sets of task (projects) and set hierarchies of task. I usually use it when I start a new project. It's a nice tool to just add requirements in a very easy and fast way, also organize those requirements upon dependencies. But for my everyday task I needed something different. I always went back to the pen and paper or the notepad document open on the desktop. Enter Ta-Da ListsThis is a product from 37 signals, the same guys that gave us rails. Ta-Da List is easy to use. Create an account, a simple process, with a short form. You are done. Now you can create one or most lists. And add task to your lists, you can reorder the task (AJAX, so no round trip to the server). Once you are done, check off the task and it's moved to the bottom with all the other checked off task (AJAX again so you can keep working). Since is on the web, no need to synchronize anything between computers. My only issue is that I didn't want to have to click in a link or open the browser and go to my favorites, or change the home page as it is today. Chrome comes to the rescue. I opened Ta-Da list in chrome and I created an "application". I added the shortcut to my launch bar and now it's another icon, like Visual Studio or PSPad. This may sound silly. I know that if somebody mentioned this to me I would said something on the line off, what's the matter with open Firefox and navigate to the page? The true is, there is nothing wrong with that, but this is more convenient. I can't really explain how, but it works great for me.
I was listening to episode 27 of the Herding code podcast and they mentioned this tool called IE tester, so I decided to give it a try. IE tester is a browser that can render pages using four different IE rendering engines for HTML, CSS and JavaScript. The versions supported are 5.5, 6, 7 and 8 beta 2. The interface is very slick, using the ribbon control. One of the nicer features is that you can open different tabs, each using a different engine and compare the rendering side by side. Each tab using only a portion of the screen. They have this nice screen cast on the usage:
ScreenCast IETester from WebInventif.fr on Vimeo.
I have been looking for a tool to drive my web sites smoke and regression test for quite a while, between the tools I used I want to mention Sahi and Selenium, really good tools. In the company I'm working right now we have a framework that is used by several companies to drive their websites. They can change the skinning a little bit but all the sites have the same structure and there a minimum of artifacts that remain from page to page (even when they look different). Trying to test this with Selenium wasn't easy, since I don't want to create a complete suite of test for each site, I need to modify the test suite after it was created and imported on the language of choice. At that moment a disconnect is produced between the tester using the recorder and whoever will maintain the test code. So I decided that we needed something different, some kind of scripting tool to drive the test. I took a look a Watir a year ago or so and at that time it was mostly IE specific. That was a deal breaker for me. Recently I decided to initiate the search once more and I found out that Watir now come with FireWatir integrated so it can drive both IE and Firefox and also there is Safariwatir to run test against Safari. So, I downloaded, installed and run it. It was quite simple and I enjoyed that uses Ruby as the language to create test. In a few minutes I was able to put together a very simple test to log into our site and log out, interacting with some AJAX in the process. Please note that my Ruby is quite basic and it was my first time using the Watir library. A few more minutes and I was able to refactor the test to load username, password, site domain and browser from a YAML file. So now I can have a configuration file and a single test that will run against as many sites (domains really) I want, with as many different users, even invalid one. The next step is to encapsulate this functionality in a library and them use either RSpec or TestUnit to drive the tests and generate a report. So far I'm very excited and enjoying it.
As you may already know by now, Google released Google Chrome a new web browser. The launch was announce on monday and today everybody I know was going crazy trying to get it. I was able to download and install it around 2 Pm Eastern time. In the meantime I read the comic used by Google to explain the rationale behind the browser. This got me very exited, this comic book talks a lot about the technology used in this browser. One of the things that really got me interested was the JavaScript Virtual Machine, called V8. This is extremely important, since this means that the JavaScript loaded in a page will be "compiled" and them run as a compiled language and not an interpreted language. This should provide more stability and performance. We still need to evaluate compatibility.Talking about V8 is something for a whole new post, since it should be able to run stand alone and is supported in Windows (XP/Vista), Mac OS X 10.5 (Leopard) and Linux systems. This may bring JavaScript to a whole new level.Installing Chrome can't be any simpler. You download a loader that weights less than 455K, you run it and it downloads the rest of the application for you and start installing it. By default will import settings from your default browser (Firefox in my case) but won't over write any of your configurations, like for example setting itself as the default.  You can easily customize the default settings clicking in the link. This will present you with a more elaborate dialog box.  As you can see by default Google chrome won't force itself as the default, what is really polite and a good example for other software manufactures to follow. The actual install time was just a few seconds. If you have Firefox open when Chrome tries to import the setting will throw an error like this.  Closing Firefox and hitting continue fix the problem and Chrome installs and launches. Notice the help dialog that indicates witch is your default Search engine (this configuration is imported from Firefox) and Dan Wahlin's posted that respects whatever you have there even if it's not Google.com.  The home page is nice and you will notice right away a quick set of link to your Bookmarks and the recently closed tabs.  The six grey panels will be replaced by captions of your recently visited sites after you browse for a little bit.  There is also a convenient link to Show the full history.  On top of the history for each day you have a link to delete all the items on that day and on top of the page itself you have a search bar that should make a breeze to find anything in the history.  Notice that after visiting the page a caption and a description gets populated. This happens because the items in the history have been imported from Firefox, from now on each time you visit a page the history will keep a thumbnail and a short description, similar to a Google search result page.Adding a bookmark can't be any easier. You just click in the start besides the location/search box and voila, item added to your Bookmarks.  There is a lot more and you can visit the welcome page and the videos to learn more.
After I wrote my last post I remembered that some time ago I did intall an Add-In for Visual Studio called CopySource-AsHTML. So I decided that it was time to try it. I love it almost inmidiatly. The reason I like it better than the previous tool I mention is that this preserves my VS style, so the code looks exactly how it looks in my editing window. But even more important I just copy the code from VS and paste it into my blog editor. The usage is dead simple, you just highlight what you want to publish and doing right click on it you are presented with an option in the contextual menu to Copy Source As HTML.
The tool have some pretty good options and they are presented to you after clicking in the menu item:
You should be able to get the tool from here: http://www.jtleigh.com/people/colin/software/CopySourceAsHtml/ but it doesn't seem to be up at this moment. There is a link to a zip file in this blog post as well: Guy Burstein's Blog.
Browsing around I landed on opgenorth.net blog an drift into his software tools page. Most of the tools I either knew or actually use, but this one I didn't. C# format is an online tool to format your C#, VB, HTML, XML, T-SQL or MSH code into valid HTML 4.01 complaint code to put online. The usage is dead simple, you just paste your code in a textarea, select a few options and click a button, voila! Your code have been formated and is ready for you to copy and paste in your HTML page or blog post.Between the options available you have: include line numbers, alternate code line background colours and embed the stylesheet. If you choose not to embed the stylesheet, you need to download the provided stylesheet and insert it in your page.I like this tool, I think that I will start using it from now on for my code post.
There is a feature of Refactor that I really like and is the posibility to re-order the code (grouping fields, properties, private and public methods together) and order them alfabetically. I'm a Resharper user and I was looking for some add-in to help to achieve something similar when I came across NArrange. Install NArrange takes no time at all, this is not a VS Add-in but a console app that can be execute from within VS as an External tool. I only found one problem using it and is tha tif I have the file open whem running the tool it breaks the encoding, but I ran it in another machine and I didn't find the same issue, so I need to figure out what is different between the VS configuration in those machines. I also make a configuration to run it for only one page and the only changes are that in the arguments you need to use ItemPath and in the initial directory ItemDir:
The only problem is that when running it for a single file the using statements are moved inside the namespace:
A coworker of mine (Amy) came up with the solution of passing a custom configuration file in the Arguments line as so: $(ItemPath) /c
In the last few days two of my favorite pieces of software released new versions.NHibernate released version 2.0 final version and Json.NET came up with the 3.0 version.Documentation for the new version of NHibernate can be found in this wiki.I just wanted to say thank as a user of both libraries to all the developers involved in a project as massive as NHibernate and in particular to James Newton for his fabulous Json.Net.
Here is a list of some projects that look interesting for me. Extension Methods Extravaganza: A collection of some extension methods. You can find extension to the object the ICollection, IEnumerable, IList, String and StringBuilder. I specially like the StringBuilder and IList methods. I know I will be able to make good use of them. Reflector AddIns: The always useful Reflector gains power in a level of magnitude with this collection of AddIns. Special attention to Diff, FileDisassembler, ClassView, CodeModelViewer, CodeSearch and Deblector (allows to debug processes within Reflector). ProMesh MVC Framework: I saw this framework for the first time six or seven month ago and I was impressed. Later on the Microsoft ASP.NET MVC got my full attention and kind of forgot about this one. Take a look at it, there are some interesting ideas on it. CoolStorage.NET: It's a lightweight ORM framework very easy to use. I haven't use it in production yet but I played around with it and the learning curve is non existent, it comes with a very well written and detailed manual. ···Thinks you may like: No XML configuration required at all (I personally don't mind mapping files but I know that a lot of developers do.)···Thinks you may not like: All entities need to inherit from a base class. Entities expose methods like New(), Read(), Filter(), Save() etc. LazyParser From the same Philippe Leybaertfather of ProMesh and CoolStorage. An expression parser with support for C# syntax, very powerful. Utilities.NET From James Newton-King a complete set of utilities that you should have in your bag of tricks. Json.NETAgain from James Newton-King the bare bones for my REST services libraries. More to come in a future post...
In my previous post I show how to integrate PartCover reports into CC.Net and promise to look into make the reports look a bit nicer and try to integrate the Coverage metrics into the statistics reports. So I dust off my xslt, pick up two of my favorite books on XML (XML Hacks and XML for the world wide web) open PSPad and started to play around until I got something that I like. Click here to download the stylesheets. The summary reportThe for the summary I want to show a coverage percentage per each assembly in the project so I based my xsl in the assembly.report.xslt provided with PartCover.First I changed the table tag and the first row from this: <table style="border-collapse: collapse;">···<tr style="font-weight:bold; background:whitesmoke;"> <td colspan="2">Coverage by assembly</td> </tr>To:<table width="98%" cellspacing="0" cellpadding="2" border="0" class="section-table"> <tr class="sectionheader"> <td colspan="2">Coverage by assembly</td> </tr> Then I modified the colours used to identify the different percentage of coverages and made the fonts bold. Note: I made move all the styles into a stylesheet later on, for now some stuff is hardcoded in the xsl file, what I don't particulary like. When possible I used pre-defined classes already available in the existing cc.net css files<xsl:variable name="cov0style" select="'background:#ff0000;text-align:right;font-weight:bold;'"/> <xsl:variable name="cov20style" select="'background:#ff6600;text-align:right;font-weight:bold;'"/> <xsl:variable name="cov40style" select="'background:#ffcc00;text-align:right;font-weight:bold;'"/> <xsl:variable name="cov60style" select="'background:#cc9933;text-align:right;font-weight:bold;'"/> <xsl:variable name="cov80style" select="'background:#6699ff;text-align:right;font-weight:bold;'"/> <xsl:variable name="cov100style" select="'background:#00cc00;text-align:right;font-weight:bold;'"/> Then I added this lines of code to alternate the style for each row in the summary. <xsl:if test="position() mod 2 = 0"><xsl:attribute name="class">section-oddrow</xsl:attribute></xsl:if> This code needs to be added after opening the table row <tr> inside the for-each loop and before creating the td element or you will have an error on runtime when the server tries to generated the report.I also decided to modify the colour used for 0% coverage, in the original stylesheet it used the same colour for coverage between 0 and 20 percent.I wanted to use a bright red for assemblies with no coverage, so I added the following line after we calculate the coverage percentage. <xsl:if test="$coverage = 0"> <xsl:attribute name="style"> <xsl:value-of select="$cov0style"/> </xsl:attribute> </xsl:if> And I modified this line: <xsl:if test="$coverage >= 0 and $coverage < 20"> <xsl:attribute name="style"> <xsl:value-of select="$cov20style"/> </xsl:attribute> </xsl:if> to look like this: <xsl:if test="$coverage > 0 and $coverage < 20"> <xsl:attribute name="style"> <xsl:value-of select="$cov20style"/> </xsl:attribute> </xsl:if> notice that now I'm checking for $coverage greater than 0 and I deal with $coverage = to 0 in my new line. Here is the end result: Adding more details to the details report.Again I start using the supplied stylesheet but and I made the same changes (or very similar changes as in the previous file).I wanted to provide not just measures by class, but also have detailed measures by method and I wanted this to work the same way as the Nunit report does.You have an arrow besides the class name than when clicked displays the details for the class.To do so I copy some of the code from the unittest.xsl style from cc.netFirst you need to declare the applicationPath parameter<xsl:param name="applicationPath"/>Them you include the javascript to show and hide the details. Them you include the code to display the arrow and finally you add a for each to select all the methods inside the class and calculate the coverage.I decided to mark anything less than 100% as red.It's not because I think that we should achieve 100% of test coverage and if not the project is not complete, it's just that I wanted and easy way to find methods that may need to be tested on more details.Here is an image of the result with no details showing.

And here with details open
 Adding the statisticsThis actually went very smooth, open your ccnet.config file and add the following under the statistics tag of your project.<statisticList><statistic name="Coverage" xpath="ceiling(100 * (sum(//PartCoverReport/type/method/code/pt[@visit>0]/@len)+0) div (sum(//PartCoverReport/type/method/code/pt/@len)+1))" /></statisticList>The only part that I have to give it any thought at all was in the xpath expression to calculate the project coverage percentage, but I think that I got it, notice the +1 in the second part of the expression, this is to prevent division by zero errors, this shouldn't affect the coverage percentage calculation in any meaningful way.
A few months ago I mentioned that I was using PartCover.Net to measure test coverage in my projects. I have been really busy but I decided that this week I was going to integrate the reports with CC.Net. Cruise Control ships with NCover support out of the box but it's also very easy to integrate other reports as far as they are in xml format and you know (or have) an xml stylesheet to generate html from the report.Partcover comes with two xslt files one to report results by assembly and a second one to report results by class.To use this files in CC.Net you need to make a minor change on them or they don't work.Let start with the class.report.xslt file.Open the file using your favorite text editor (PSPad anybody?) and look for this line:<xsl:for-each select="/PartCoverReport/type">Change it to:<xsl:for-each select="//PartCoverReport/type">Notice the double back slash, this change is needed because the way of CC.Net works is merging all the reports for all your tool together in a big xml file, so at that moment PartCoverReport is not the root element but a child element of the merged xml file.Open the Assembly.report.xslt file and add the "extra" back slash in any mention to /PartCoverReport. Configuring CC.NetCopy the modified xslt files into the stylesheets folder of your webdashboard install, usually CruiseControl.Net\webdashboard\xsl\I like to change the name of the files to indicate what report they affect, in this case I named PartCover.assembly.report.xsl and PartCover.class.report.xsl (notice that I drop the "t" from the extension, I don't thing this is important, but all the files in this folder have an xsl extension, this way I keep things consistent).Now we need to configure the reports plug ins, open dashboard.config usually at CruiseControl.Net\webdashborad and under <buildPlugins> <buildReportBuildPlugin> <xslFileNames> You enter:<xslFile>xsl\PartCover.assembly.report.xsl</xslFile> This will add a summary on the build report page. Then under <buildPlugins> <buildReportBuildPlugin>······<buildLogBuildPlugin /> Enter:<xslReportBuildPlugin description="PartCover Details" actionName="PartCoverDetailsBuildReport" xslFileName="xsl\PartCover.class.report.xsl" /> This will add a link on the right navigation bar to see the details of the report for this build.You need to restart IIS for CC.Net to pick up the changes. You will see a menu item to the PartCover report on the side.  Clicking on the link you will see a simple report like this:  (I had to hide the name of the company) but you will see the qualified name for the class. Running PartCover.Net from NantI decided to Run PartCover from Nant using and exec task.This is an example: <property name="partCoverReportPath" value="D:\BuildReports\PartCover\${projectName}\" /> <property name="nunitExePath" value="D:/NUnit-2.4.7/bin/nunit-console.exe" /> <target name="testCoverage" depends="UnitTest" description="Measures how much code have been covered by the test"> <mkdir dir="${partCoverReportPath}" unless="${directory::exists(partCoverReportPath)}"/> <exec program="D:/PartCover/PartCover.exe" failonerror="false"> <arg value="--target=${nunitExePath}" /> <arg value="--target-work-dir=${buildPath}" /> <arg value="--target-args=${projectTests}.dll" /> <arg value="--include=[LaTrompa]*" /> <arg value="--output=${partCoverReportPath}\${projectTests}-Results.xml" /> </exec> </target> ${projectName} is a property where I store the name of my project. ${projectTest} is a property where I store the name of the project that has all the unit test. ${buildPath} is a property where I store the build folder. Let me explain each argument: --target is the Path to your nunit-console.exe --target-work-dir is the Path to the folder where the dll(s) that contains the test resides. --target-args is the name of the dll --include is used to indicate witch namespaces and classes to include in the report, in this cases I'm saying any class under the LaTrompa namespace --output is where I want to save my report, this is the complete path with the name of the fileThere is another argument that is very useful --exclude is used to ignore some classes or namespaces from the report. Adding the report to the buildNow you need to configure your project in CC.Net to merge the report generated by PartCover.To do this, inside the project tag in your ccnet.config file lock for the publishers tag and add a new file under <publishers> <merge> <files> <file>D:\BuildReports\PartCover\LaTrompaLibraries\UnitTesting-Results.xml</file> ......After doing this you can run a build for the project and your PartCover results will be added. Next stepsI will try in a future post to modify the xsl to have more data, make it look nicer and integrate a bit more with the general look and feel of the CC.Net dashboard.I think that I will be able to provide detailed information per class and method and I will also see how can I modify the Dojo based statistics plugin to include this data.
We were having a problem with our build in the CC.Net server. The problem was that when doing the clean of the build folder sometimes it was failing with the following error. "Can't delete folder is not empty". The first thing was to check that not other process was accessing the folder. The second step was to make a search on google to figure out if somebody else had the same problem. We only found one case but was too all and they were mentioning to use Nant 0.84 to solve the problem, that is not an option for us since we need support for .Net 3.5. We have several projects running in the same server with almost identical build scripts, but only three projects have this problem. They have in common that all of them have a large and deep folder structure. Another characteristic of the problem was that the error wasn't always in the same folder, it seemed totally random. Forcing the build usually solve the problem, but sometimes we have to force the build more than one time, since it keep failing in different folders. A build that fails randomly is not a good thing to have in a Continuous integration environment. You want your build to fail for good reasons, like a failing test or a threshold on simian or FxCop, in a few words, you want that when a build fails people pay attention to it. (Actually the ideal situation is that your build never fails because developers are running the build on their machines first, but you may have integration errors). So after hitting my head into the wall for a few hours I decided to write a custom nant task to solve the problem. The idea is that we have a task (forceDelete) that take two parameters, a target directory and a number of attempts. Internally the task will try to delete recursivelly the given folder and any folder below it, if there is an error will try again for as many times as indicated in the attempts parameter. I'm including a zip file with the compile dll and another one with the source code. To being able to compile the source code you will need to add a reference to Nant.Core.dll, located in the bin folder of your Nant location. To use the task you just need to copy LaTrompa.NantTasks.dll inside the bin folder of your Nant install (or whatever is that Nant.Core.dll is in your machine). LaTrompa.NantTasks.zip LaTrompa.NantTasks.source.zip NotesThis task is super simple and at this moment it's not raising and error, something that you may want to do to make your script fails if you still can't delete the given folder after all the attempts.
I was creating for the 10th time today a nant build file from Visual Studio when I came to the realization that I needed to automate the process a bit more. So I created an item template to include build files. You just need to copy this zip file into the ItemTemplate folder inside your Templates. Usually is My Documents\Visual Studio 2008\Templates\ItemTemplates After that just right click on a project or solution and select Add New Item, at the bottom of the dialog you will see a section called My Templates.
Notice the new Nant build file item.

Adding intellisense to edit the fileThere are a few other post out there to do this on VS 2005 on VS 2008 there are a few changes. The most important one is where to install the schemas. - Copy the nant.xsd schema file from your Nant folder, inside a subfolder called schema
- Paste the file on the schemas folder for VS 2008; C:\Program Files\Microsoft Visual Studio 9.0\Xml\Schemas
- Open Visual Studio and use the new item template to create a build file
If you type <g; you will see a list of options  TroubleshootingIf it doesn't work for you it may be possible that you have a different version of schema files. On VS with the build file open click on Xml ->Schemas Locate the entry for the build file and check the target namespace, it should be the same as the xmlns attribute of your project tag xmlns="http://nant.sf.net/release/0.86-beta1/nant.xsd"  If it's not change the attribute value with the value displayed in the schemas dialog. More to doYou may want to customize the item template and add the most common options for your build files, like add the automatic execution of your unit test, Ncover, FxCop, package, etc. I notice that I usually end up with a similar script in most cases, you can them save the script as an item template using File->Export Template, when asked choose to import the template into VS.
During Scott's Hanselmann presentation on Dynamic Data at the TVBUG he show a little trick that I didn't know about and I want to show it here.It always annoy me that every time you click run ina a web application using VS it runs using the ASP.Net development server and starts in a random port.So if you want to make sure that the projects starts always at the same port, all you need to do is right click on the solution and select propertiesIn the property sheet for the solution click on the Web tab:Change the default Auto-assign Port to Specific port and type a port of your liking.
Testing is fundamental to get your code into shape and to be sure that what you are doing is behaving as expected. New methodologies like Test Driven Design (TDD) point to that goal. We (developers) are lazy and very self confident, we normally write the code and run it a few times without paying a lot of attention of the requirements, if the code works as we think it should we are happy and move to code something else (or write some blog post ). So the idea behind TDD is that instead of write your code first and test it later, you start by writing your test (hopefully something that tries to follows the requirements, if not there is no much good on the practice either), them you run your test you see it fail and run the code that will make the test pass. This post is not about TDD, there are tons of articles out there on how to do it. This post is about how to do TDD on web development (even if you don't use web controls). You can write test in different ways, but the most effective one is creating the test in a way that they can be run automatically, and that the test suite can evolving with your code and incorporating more and more test while your code evolve. For that reason in the .Net world there are some frameworks that allow you to write Unit test and run them the console, inside a GUI or as part of your automatic build (within or without a CC process). Nunit is my framework of choice (for no particular reason besides that I have been using it for a while), please try others as well, there have been a lot of talk about MbUnit. Nunit works very well for me to test libraries or console apps, what is great because we all know that most of your code should reside on libraries, but the reality is that I am a web developer and you like it or not you need to put code in your code behind classes (even if is just to glue everything together) and for testing this code you will need an extension to Nunit called NunitAsp. Follow the instructions from the NunitAsp site to download, install and set up your testing project, you will need to install Nunit as well if you haven't done so. The examples in the NunitAsp are great but they all assume that you are using webcontrols something that I don't do and I know that I'm not alone. I don't think that Web controls are evil or anything like it, I just like to have full control on my markup and JavaScript. I did use them once in a while for small sites that don't need a lot of complication, but for large projects I use my own libraries that output html to the browser. So let's see the differences in the code. Let's say that you have a page with this html markup and this code behind. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ala_sureflix.aspx.cs" Inherits="ala_sureflix" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <script type="text/javascript"> function SendForm(){ document.getElementById("SureAction").value = "ChangeDiv"; document.getElementById("form1").submit(); } </script> </head>
<body> <form id="form1" runat="server"> <input type="hidden" id="SureAction" name="SureAction" value="" runat="server" /> <div> <div id="myDiv" runat="server">Before anything happens here...</div> <input type="button" id="btnSend" value="Send" runat="server" onclick="SendForm();"/> </div> </form> </body> </html> And this code behind: using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;
public partial class ala_sureflix : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (SureAction.Value == "ChangeDiv") { myDiv.InnerHtml = "After submittting the form."; } } } So your first attemp may be to call the onclick method of the button using the standard, but doing so won't call the javascript method since NunitAsp does not understand JavaScript, the page won't be submitted. So what do you do? The solution is simple, you create a TextBoxTester that will represent your hidden input field (I guess that TextBox works with any input field), change the value of the field modifying the Text property of the object and them use the static Submit method on the CurrentWebForm object. TextBoxTester hid = new TextBoxTester("SureAction"); hid.Text = "ChangeDiv"; CurrentWebForm.Submit();And that's all is to it, now you can start testing your web control free asp.net pages.
A free tool to do code coverage with a nice GUI for the developers to use, that can be run on the command prompt, that generates nice xml based reports (to integrate with your CC server) and best of all for me) that works fine with Static methods. This gem is called PartCover. In the continuous quest to improve my team code quality I'm pushing hard to move more and more into a TDD approach. (I should make a side note here and indicate that at this moment my main concern is have a nice battery of unit test in place even if they are written after the fact). We are having clinics and the senior developers teach the junior guys how to use Nunit, Nant and now we are playing with some Code coverage tools. We were going to jump into NCover since is the one that most of us have experience with, but there was a problem and it was that our massive Utility library is mainly a collection of static methods and NCover doesn't seem to like Static methods, so there are no metrics of how much code have been tested in those libraries. That is a bit of a problem for us. Another issue was that now NCover seems to come in two flavors (or two projects) the free one in sourceforge and a commercial version at Ncover.org. The price for the commercial version is not terrible (169 to 199 USD + service plan if you want) and we thought that we may run it just in the integration server in the worse case scenario. The free project have a note in the home page that discourage us from use it, and that is that the project to cover needs a reference to a Ncover library. We are not sure if they are talking about the testing project (the one with the test fixtures or the actual library that is been tested, something that sounds crazy), but in any case having to include another dependency was a big deterrent for us. The commercial version was fine, fairly easy to set up (even without a lot of documentation, why is documentation for this tools so cryptic?!) and worked well enough, but the lack of measurement in static methods was bad for us. You can argue that you shouldn't use static methods in such a liberal fashion and that make for a bad OO design (something that I agree) and makes your programming model look more and more like procedural and you will be right, only that in this cases there is no major implementation and besides a Network library and a serialization library that needs to be re-written the lions share resides in our Utils class. PartCover to the rescue.I was upset with the compromise and took me almost no time (the second search on google) to stumble upon this free awesome tool. The interface is similar to NCover but more frugal. There is a File menu with four options: Run target (to generate the report) Open Report Save report as Exit It can be more straightforward. To generate the report you will to enter the same data as in NCover. Executable file: should point to the console exe for your testing framework in my case nunit-console.exe Working Directory: This is the folder where the dll with your test fixture resides, for example C:\Project\Project1\UnitTesting\bin\Debug Working arguments: Depends but in the case of nunit is the dll where with the test fixtures (ex: UnitTesting.dll) The tricky part is the fourth text box (a text area really), where you enter "Rules", this rules tell PartCover witch assemblies/classes to look for coverage and what to left out. For example if you have to dll one called Mainframe.dll and another one called desktop.dll and you want to check both of them you will enter a Rule like this +[Mainframe]* +[Desktop]* To exclude the mouse class from the desktop dll you add the following -[Desktop]*mouse* Another nice feature is that the dll with the fixture is not included (another thing that bothered me from NCover). The tool has a command prompt option, so running from Nant is no problem, and the report is generated as xml, so integrate it with CC.net should not be an issue, the even provide two xslt files to display the report based on the assembly or based on the class very neat!!!. UPDATE: Two days after writing this post I found the SharpDevelop will be (is) using PartCover in SharpDevelop 3.0 and beyond.
Virtualbox is a free open source virtual machine software. I have been using it to run, Ubuntu, Fedora, BDS and a virtual XP machine with all the new stuff for testing and I love it. The performance is great, installing the software can't be any easy and configuring the virtual machines is a breeze. I totally recommend you give it a try.
I usually use PSPad as my fire up and hack something together editor. I also use it to do a lot of maintenance, I have been even using it to do some c# editing here and there and relying more and more in Nant to do the builds, it even has a plug-in to synchronize with subversion if you want. When I need something a little bit more powerful I jump to use Eclipse and the myriad of extensions that make this my favorite IDE. I used to renegade from IDE's but I never was able to completely get rid of them, the reality is that in a lot of cases make development easier, faster and allow the developer to concentrate in some productive task instead of trying to remember the exact casing or syntax to any given language. Of course, as a developer using Microsoft technologies I have been using VS since version 5.0, specially for Visual Basic. The only two things I hate from the line was Interdev in the pre-net era and the first version of VS.NET, It was so buggy. VS 2003 was a lot better even when it has some strange behaviors, specially when dealing with html files in edit mode, controls the mysteriously disappear and the odd generated code. VS 2005 and the new 2008 are a lot better and I find them really good to work with. I keep installed in my development machines a copy of Editor4Nant even when I'm not using it a lot lately I find it a little too constraining. It's helpful while you are learning your way around Nant though. To edit Javascript I found the new support presented by VS 2008 really good, but when I need to do some heavy AJAX stuff I use the Eclipse based Aptana IDE, their support for auto completion and documentation is incredible. On the pure text editors front I have used Crimson and still use EditPad Lite and EditPlus, specially powerful when you need to do some text based manipulation. About that, you need The RegEx coach in your machine, to test your regular expressions. Top Style used to be my choice when dealing with css but again Aptana have capture my heart in that area.
I keep searching for the right IDE for my Ruby and Ruby on Rails adventures. I keep changing and playing around with the ones I had and lately I keep using NetBeans 6.0. Yesterday I decide to try again and after looking at The usual suspects, I found one that I missed always before, it's the Eclipse for Rails. It's not an extension but a pre-package Eclipse with some extensions configured in a way that make it Rails ready. You can find it at http://www.napcs.com/. I haven't really try it yet, but a first impression is very favorable. The package even include the Subclipse plugin to connec to a subversion repository. The SQLPlugin to been able to open a database and create, view, edit tables right there. In the site they even have instructions on how you can build the environment on your own from scratch downloading Eclipse and the necessary plug ins. I will try it for my next Ruby project, that I need to start in a day or two and blog a little more about it.
I went today to the Nant site to check some documentation and I saw that the beta 1 of the new version is available, this version supports the .NET 3.5 framework, Mono 3.5, Silverlight 2.0 and Moonlight 2.0 The beta have been available since Decemeber 8, there are a bunch of changes, bug fixes and drop of some features that is important to take into consideration when migrating, some of your scripts may stop working if you are using some deprecated feature like the failure attribute, it have been replaced by the onfailure. I was hoping to see FTP support (ala Ant) between the new additions but I didn't saw it.
I just found this post with detailed instruction on how to make the MVC framework work in IIS. The instructions are very basic and you shouldn't have any problems making it work, but you may not know how to modify the extension handling in IIS, so I thought to add this. http://blog.pagedesigners.co.nz/?p=29
|