Alexander Beletsky's development blog

My profession is engineering

Speeches Hat-Trick For This Weekend

It’s been great weekend. It started Friday evening with Kiev ALT.NET meet-up which been in idle for a while and everybody missed that. There was a three planned speeches: by @_TKL on Continuous Testing (NCrunch, MightyMoose), NancyFX framework by me and FubuMVC by @skalinets.

I would not say I got great experience on Nancy so far. But I’m pretty exited on frameworks features and super-dupper-happy-path. Almost all knowledge I gathered thought hacking of IdeaStrike, listening to Herding Code episode and reading documentation. But anyway, I believe it turns out to be good introductory presentation.


Right after my Nancy talk I moved to central train station, since I was about to visit Ciklum .NET Saturday in Dnepropetrovsk. .NET Saturday’s is just great initiative by Ciklum company. I’s free event, everybody welcome, content is usually nice. I highly recommend to follow their events.

I had two talks there. First one about “Continuous Delivery” that I did on Agile Base Camp 2012. Besides of the talk I also did a quick and improvised demo of Candidate application. Even if I had some technical issues the demo went fine.

Another one is for logging and tracking unhandled exceptions in ASP.NET / ASP.NET MVC application based on ELMAH. I showed some basics features as well easiness of ELMAH integration to ASP.NET MVC with ELMAH.MVC NuGet package. It was very light and funny talk, especially discussing Troy Hunt’s ELMAH attack.

I also really much enjoyed Anton Samarskyy talk on jQuery deffered objects and Vitaly Koval did great hacking session of WinRT.

I some of you been listening to me on those speeches and still have any questions or concerns, feel free to contact me by comments or through twitter. See you next time!

Foundation Framework for Web Sites Production

The Foundation framework is something I discovered by accident browsing through some github project pages. I really liked how one of the sites looked on my iPad. I was also pleased to see how HTML crafted, using clear names for classes and HTML5 semantics. As it turned out, that site was using Foundation Framework by Zurb - design agency in San Francisco Bay area.

I checked out the documentation and Foundation appears to be pretty solid framework for web applications prototyping and production. It contained everything needed: Grid Layouts, Buttons, Forms and UI. And of cause, all of that is open source hosted on github.

During my preparation of project page for candidate I decided to try it out. I was really happy of the experience.

Object Oriented CSS

Have you heard of OOCSS? Initially I thought that idea is almost non-sense, but I’m changing my opinion now. I think Foundation fully conforms to OOCSS style of development - each behavior or UI you want to apply to HTML element is done by applying of corresponding class.

Great thing is that you see how it’s done in framework and do same in your code as well. I remember the times I started to do HTML/CSS and I higly used #id’s, applying the styles by element Id. The code was awful and styles applied on #id’s were not re-usable at all, so if I needed the same margin/padding or text color I have to copy the section of CSS and move it into next #some-id { ... }.

With OOCSS you rely on classed. Here some example,

<div class="container darker-grey light-border small-padding">
 <div class="row smaller-fonts">
  <div class="four columns"></div>
  <div class="four columns"></div>
  <div class="four columns"></div>
 </div>
</div>

Look, no #id’s - classes only. With classes I control: position, colors, borders and margin/paddings. This is really cool, since all of that classes are easy reusable in any part of page.

Grid system

Grid systems is really cool concept and allows to develop much faster. Instead of writing own CSS that would position elements, you stick to Grid System. The classical grid system is probably 960.gs. It’s really great and blown my mind as I first time tried it, but currently it little outdated: 960px wide is small for modern monitor and it is not adaptive. Modern web design demands site looks great both on PC and Mobile devices, adapt it’s content based on screen size.

Here is a quote of Foundation documentation.

The grid is built around three key elements: containers, rows, and columns. Containers create base padding for the page; rows create a max-width and contain the columns; and columns create the final structure. Everything on your page that you don’t give a specific structural style to should be within a container, row and column.

You develop the layout based on planned number of row and columns that compose the row. Again, code is done in OOCSS way with clean classes names, so you write almost “plain” English in HTML.

<div class="container">
  <div class="row">
    <div class="eight columns">
      Eight columns
    </div>
    <div class="four columns">
      Four columns     
    </div>
  </div>
</div>

After design is ready, you just open it on iPad and.. Surprise, it looks great there! Text and columns are adaptively fits the screen size.

Buttons and Forms

Buttons and Forms are same important as Colors and Fonts in your web site. You can’t get good site appearance if buttons and forms are ugly. I usually spend a lot of time on “beautifying” those, but still unhappy with results at the end of the day. With Foundation it’s easier. You got nice styles from the box.

Forms:


foundation forms

Buttons:


foundation buttons

Recently, I’ve submitted green button style, so I hope it will be available soon.

UI stuff

Besides those primary things you got nice bonus. That’s different UI elements commonly used through different web sites. It includes: Alerts, Labels, Warnings, Tooltips, Tabs etc.

For candidate site I successfully used Pagination UI element.


foundation ui

Conclusions

Currently Bootstrap from Twitter is obvious leader in that niche. But I really think Foundation will get it’s place. Easy to use, great documentation repository is very active, so we might expected further great features in Foundation.

And by the way.. To payback Foundation, I got idea for small product: inspired by Bootswatch I’m about to create bunch of “ready-to-use” Foundation themes, that you just download and start to use immediately. It will work great for people who are about to create one page product presentation or simple blog. Hope it will go fine and I release it soon.

Candidate v.0.0.1rc - Released

You may notice that I stick to original project name at the end of the day, even thought I wish to change it. That happened for 2 reasons: first, I really get used to candidate and it’s good enough project name.. second, I spent some hours of brainstorming but found out nothing better that existing.

This weekend I also finally concluded project web site and hosted it as github pages - http://alexbeletsky.github.com/candidate/. So, ladies and gentlemen - please welcome, Candidate v0.0.1rc is ready to be shown to the world.


candidate web site

What’s the goal?

Thinking about nearest “competitors” in this area I would re-call Octopus by Paul Stovell. Octopus uses Build Server / Tentacle (Agent) architecture principal, while Candidate is simple Agent architecture - you host it the same machine as your environment is (stage, production) providing both integration and deployment functionality.

My goal is stabilize and improve Candidate through this year, so it fulfill different requirements including performance and scalability. I switched all my projects to use Candidate now, so it would give me some initial feedback.

Nevertheless, Candidate may turn out to be a powerful deployment application I’m still thinking about “Deployement as Service” product like AppHabor and Heroku or Travis-CI as it was original idea.

What’s next?

Following the principle “Build product X to learn technology Y” I’m going to proceed with Candidate to shape following areas that I wish to improve now:

  • Processes, threads, synchronization in .NET
  • Async, Tasks library
  • Robust applications architecture
  • Different deployment scenarios for .NET platform

Technological stack is still ASP.NET MVC3 / C#/ jQuery. Currently application requires to be hosted on IIS, with application pool Process Identity equals to Admin. This does not suite all users. So, I’m looking forward to create self-hosted version using NancyFX.

I also try to target UI / UX issues as much as possible.

Wanna join?

I would be happy to. I’ll much encourage you to download application, install it, perform simple testing (scenario could be found here). Let me know what you think, that would be great initial contribution. As for any github hosted project, you are absolutely free to fork, hack it out and send pull request.

Thanks for you help.

Few Things I Learned From IdeaStrike Project

First of all, I have to say Code52 team is doing just amazing job. It’s very original initiative, cool ideas and highly productive team. Each time they announce next thing to build I have “product envy” inside me. Check out their blog or github account to be updated.

My attention this time was attracted by IdeaStrike project. It suppose to be analog of uservoice for OS community. As always, first release was very fast and I was very curious what’s inside. So, I cloned the repo and did small hacker session. I’ve spend some hours with it and would like to share some initial thoughts.

Build script is small and clean

Project contains build.cmd as I run it downloaded all dependencies by NuGet, build web site and run all unit test. Basically, all you need for any small project. Then I looked inside, it turns out like:

@echo Off
set config=%1
if "%config%" == "" (
   set config=Debug
)

%WINDIR%\Microsoft.NET\Framework\v4.0.30319\msbuild build.proj /p:Configuration="%config%" /t:AppHarbor /m /v:M /fl /flp:LogFile=msbuild.log;Verbosity=Normal /nr:false

At the time I first looked in it also contained small script for running tests, but later they moved that to .csproj as separate target.

Use NuGet without committing to SCM

I was amazed, how fast git repository was cloned and as I checked out packages folder with all dependencies were just empty. How can it be? As I said in #1 as I run build script they just automatically downloaded for me. As it turns out, this is feature of NuGet that allows to work with dependencies, without real necessity of committing those to SCM. This is very cool, especially if you have big project, so cloning and branching appears to be prolonged operations. The implementation details is on nuget site.

Deploy application DB at first launch

IdeaStrike is based on EF 4.3 Beta 1 currently, using Code First approach. EF Code First also includes very cool feature called Migrations. This is something I really lack first time I tried EF Code First approach. You define the Context, DbConfiguration class and migration scripts (that’s also, just a C# code), so at application bootstrap you call the code like:

private static void DoMigrations()
{
    var settings = new IdeastrikeDbConfiguration();
    var migrator = new DbMigrator(settings);
    migrator.Update();
}

The database and schema will be automatically deployed on first application run.

Social login with Janrain

As I clicked to Sign In button, I’ve been showed nice dialog to select my existing social account to login.


social login

JanRain is very cool solution. I remember I tried to investigate something like that for ASP.NET MVC and was really disappointed, because I actually found nothing. For all of existing solutions you have to read OAuth spec and write own code. JanRain does all dirty job for you. As user authorized you receive POST on given URL, with a special token. By given token you request the details about the user, like name and email and so on (see LoginModule.cs). It has fair plans for hobby projects and bloggers.

Bootstrap your CSS and HTML

Bootstrap neither new nor very unique, at least I know several good CSS/HTML frameworks. But IdeaStrike proved one more time - it has no sense to invent the wheel. Take advantage of results produced by people who are smarter than you, that’s the rule of pragmatic programmer.

Dear future me, please never ever again start your application with HTML/CSS from scratch, you can build nothing more as shit. Bootstrap is great for different kind of projects and prototypes. Taking into account number of watches and forks on github I expect even more improvements and features in future.

Nancy as web framework

I’ve heard about Nancy many times, but it’s only now I got a change to touch it. For me it’s just alternative reality comparing to ASP.NET MVC. It is not hard to understand what the code does. It is not hard to apply changes there. You are very explicit of what you are doing, by specifying HTTP verb, route and action as lambda. First class citizen in Nancy is Module, all module’s logic is placed inside the constructor:

public FeatureModule(IIdeaRepository ideas, IFeatureRepository features, IUserRepository users)
    : base("/idea")
{
    _ideas = ideas;
    _features = features;

    this.RequiresAuthentication();

    Post["/{idea}/feature"] = _ =>
    {
        int id = _.Idea;
        var feature = new Feature
                        {
                            Time = DateTime.UtcNow,
                            Text = Request.Form.feature,
                            User = Context.GetCurrentUser(users)
                        };
        _features.Add(id, feature);

        return Response.AsRedirect(string.Format("/idea/{0}#{1}", id, feature.Id));
    };
}

Nancy application could be hosted as ASP.NET / WCF / Self hosted runtimes, it supports different View Engines (including Razor). In short, it is great ALT.NET tool and will find a lot of applications in different projects. More details on Nancy github account.

Conclusions

IdeaStrike is great example of open source project you can learn something from. I would not say I got only positive impressions, moreover there are some obstacles that block me from my normal development flow. I’ll try to share my observations on next blog posts.

NancyFX, probably be my next web framework to learn, since I need to move out of ASP.NET MVC which is comfortable zone for me now. I’ll be keep looking for IdeaStrike and hope to do some pull requests as well.

New Tools in My TDD Arsenal

Recently my TDD arsenal has been enhanced with 3 new cool tools, which I’m about to share with you. More precisely it one tool and two frameworks. Let’s go for it.

NCrunch

NCrunch is just amazing extension for Visual Studio created by @remcomulder. It automatically detects all your tests and re-running those as soon as source code changes happen. Forget about manual test re-running, it’s just waste of time. You even do not need to press Ctrl + S, just continue coding as you usually do.

Initially I had big doubts about such kind of tools, but NCrunch changed my mind. It supports major unit test frameworks NUnit, XUnit, MSpec etc. Besides of that it allows to collect code coverage metrics (and show it just in VS editor), run tests under debugger, supports multi-core systems etc.

In short, NCruch is something that makes your TDD very smooth, allowing to focusing on important things and forgot about some routine.


ncrunch

NSubstitute

I stick to Moq for quite awhile and saw no reason to switch it.. Till I saw NSubsitute. I hardly could imagine someone who staring “yet another mocking framework project”, it looks like absolute non-sense.. But those guys proves me wrong.

Well, what’s so new there? First of all it have very clean API. No more new Mock() or MockGenerator.GenerateMock(), creation of test doubles are nothing more as Substitute.For<IEntityToMock>(). Mocking properties, multiple return values, events etc. in very easy fashion. Check out their getting started materials for further info.

Best feature as for me, that by using extension methods they got rid of lambdas for setting up mocks. It makes test code more readable and clean. See this small gist there I placed just some Moq and NSubstitue tests together.

I would not say that Rhino or Moq is now much worse that NSubstitute.. No, I would just say NSubstitute is a little better. Even same functionality, with less amount of code is already big argument for me.

[Test]
public void should_send_an_email_if_users_signs_up_nsub()
{ 
 // arrange
 var emailService = Substitute.For<IEMailService>();
 var controller = new LoginController(emailService);

 // act
 controller.SignUp(new SignUpModel { Email = "a@a.com", Password = "xxx" });

 // assert
 emailService.Received().SendEmail(Arg.Any<EmailMessage>(), "current");
}

FluentAssertions

Again, for years I followed classic NUnit’s Assert.That() method. I also played a bit with SharpTestsEx, but FluentAssertions by @ddoomen is going to change that.

FluentAssertions are based on extension methods and allows you to get rid of Assert.That call and just wrote your assertion directly to object. Here some example:

{
    // NUnit.Assert style..
    Assert.That(result, Is.EqualTo(3));

    // FluentAssert style..
    result.Should().Be(3);
}

This is very simple example. The power of FluentAssertions arise then you need to have either multiple assertions or assertions on complex objects. Multiple assertion could be combined by And, like:

{
    "somestring".Should().Contain("some").And.HaveLength(10);
}

It also provides great support for working with Collections, DateTimes, Guids, Exceptions, XML etc. Project is hosted on codeplex, here is documentation. Easy start, easy go.

Conclusions

Now, I’m sharpening my axe on those tools and have very nice impressions so far. Special thanks goes to @skalinets who introduced me with those tools.

Agile Base Camp 2012

Past Saturday I was a part of big Ukrainian event Agile Base Camp: From Idea to Product. It’s been organized by ScrumGuides, pioneers on Agile in Ukraine and organizers of famous Agilee series of conferences.

The conference named “From Idea to Product” and focused on product development issues. There was 3 stages there: Main, XP, UX. Main is for more or less common topics as budgeting, motivation etc.. XP is practical stage for developers and UX for user experience engineers. The program of conference was really interesting, but I spend all my day on XP stage (no surprise).

There were great speeches by Dmytro Mindra, Sergey Kalinets. Probably most valuable for me were ones by Vitaliy Stakhov and Anatoly Kolesnik, Vitaliy shared Hypermedia concepts of RESTfull systems and that looks very promising. Anatoly did great NoSQL introduction that is very actual at the moment. I also enjoyed Dmitry Efimenko speech about testing in product company. He did it in quite tough style, so crowd was a little shocked and kept silence till the last words. I got some interesting points for myself.

I did a talk about - Continues Delivery / Deployment / Production. This practical field is very interesting to me not only because I’m trying to build a product for that and I want to adapt for all project I work to.


alexander beletsky

I’ve got very nice feedback and questions after my speech, totally collected 15 donuts (a special cards that listeners give to speaker if they like the speech), so I was quite happy about. If you interested, here is my slides on speaker deck.


I really much enjoyed after party and evening we spent in Work’N’Roll, the co-working office of ScrumGuides. Appreciate organizers for that job and wish you good luck of all next events.

Convention based IoC configuration

What’s your favorite IoC container framework? For quite long time I stick to Ninject. First time I read about it in Steve Sanders ASP.NET MVC2 book and it’s my favorite container since then. But this blog post does not aim particular IoC framework, rather approach you can use. For code examples I’ll still be using Ninject, through.

What’s are conventions?

Convention over configuration is very popular trend nowadays. Many frameworks trying to adopt it, including ASP.NET MVC. In short, that means you are relying on some front-know conventions, like names of files, folder or classes and system does something meaningful, based on those conventions. Like, all controllers in ASP.NET MVC should have “Controller” postfix, so the framework is able to find and instantiate it.

Conventions make a developer’s life a little easier, you are no longer spending efforts on configuration, instead following some simple rules.

What we have for IoC?

My “Shu” level of IoC containers learning was configuration based. This is something you learn at very beginning. So, in case of Ninject, sooner of later you have huge file with dependencies configuration:

/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
 kernel.Bind<ISettingsManager>().To<SettingsManager>();
 kernel.Bind<IDirectoryProvider>().To<DirectoryProvider>().InSingletonScope();
 kernel.Bind<ISetupFactory>().To<SetupFactory>();
 kernel.Bind<ITargetsObjectBuilder>().To<DefaultTargetsObjectBuilder>();
 kernel.Bind<ITargetsBuilder>().To<TargetsBuilder>();
 kernel.Bind<IBounceFactory>().To<BounceFactory>();
 kernel.Bind<ITargetsRetriever>().To<TargetsRetriever>();
 kernel.Bind<IConfigObjectBuilder>().To<ConfigObjectBuilder>();
 kernel.Bind<ILoggerFactory>().To<LoggerFactory>();
 kernel.Bind<IHashService>().To<HashService>();
 kernel.Bind<IAuthentication>().To<Authentication>();
 kernel.Bind<IConfigurationsFactory>().To<ConfigurationsFactory>();
 
 // More, more, more...
}

As more your application grows, as more services, repositories, factories you have. As long RegisterServices method becomes longer, as more you forgot to correct correct it after some new dependency added, so you see YSOD during application run.

But please, put your attention to interface and class names. What we have here - ISettingsManager and SettingsManager; IDirectoryProvider and DirectoryProvider.. ILoggerFactory and LoggerFactory. Do you see pattern here? Exactly, it is [“I” + entity name] for interfaces and [entity name] for implementation.

Here we go for “Ha” level of IoC and apply convention based configuration.

Convention over configuration

Let’s take an advance of the fact above and shrink our configuration code. First of all, you need to get great extension for Ninject, called ninject.extensions.conventions.

After the package is installed, the simples Ninject start-up code ever would be:

/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
 kernel.Scan(scanner =>
     {
      scanner.FromCallingAssembly();
      scanner.BindWithDefaultConventions();
     }
  );
}

What it does? It has an abstraction called “scanner”. You instruct scanner what to do. In this example, I said - take calling assembly and bind all interfaces to implementation class having Default conventions. The default conventions are ones that I shown above.

That’s it, all those lines of code are simply gone away, since we rely on conventions and Ninject is aware how to deal with those conventions. If you added new dependency and followed convention, nothing you should do manually any more.

I have some questions!?

Ok, typically you have something little more complex. I’ll try to predict some questions you might have.

I have a lot of assemblies in my application, but want only particular ones to be scanned?

You can easily use only assemblies that matches particular patterns, like:

private static void RegisterServices(IKernel kernel)
{
 kernel.Scan(scanner =>
     {
      scanner.FromAssembliesMatching("Candidate.*");
      scanner.BindWithDefaultConventions();
     }
  );
}

Is it only default conventions I can use?

No, you can specify your own rules. Scanner has BindWith method, that receives IBindingGenerator type. You can implement your own binding generator for custom conventions.

private static void RegisterServices(IKernel kernel)
{
 kernel.Scan(scanner =>
     {
      scanner.FromAssembliesMatching("Candidate.*");
      scanner.BindWith<MyCustomConventionsGenerator>();
     }
  );
}

What if I have several cases of convention violations?

You are still able to bind in exactly same way as before:

private static void RegisterServices(IKernel kernel)
{
 kernel.Scan(scanner =>
     {
      scanner.FromAssembliesMatching("Candidate.*");
      scanner.BindWith<MyCustomConventionsGenerator>();
     }
  );

    // classes that violates conventions
    kernel.Bind<IMyInterface>().To<MyImpl>();
}

What is I have dependencies in different assemblies?

Best thing is to go with Ninject modules. First, correct the scanner:

private static void RegisterServices(IKernel kernel)
{
 kernel.Scan(scanner =>
     {
      scanner.FromAssembliesMatching("Candidate.*");
                        scanner.AutoLoadModules();
      scanner.BindWith<MyCustomConventionsGenerator>();
     }
  );
}

Now, each assembly should include module instance:

namespace Candidate.Core
{
    public class CoreModule : NinjectModule
    {
        public override void Load()
        {
            // place convention-violation classes here
   // Bind&lt;IMyInterface&gt;().To&lt;MyImpl&gt;();
        }
    }
}

Another one good feature of Convention based IoC is - “Config and forget”. Once done, use always and forget about manual binding once and for all.

I’ve heard about this on XP Days 2011 conference, by Mark Seemann. I think it’s nice approach.. I adopt it and going to use in my projects.

Pre-announce of Release Candidate

For those, who already forgot what the candidate is I’ll do a small reminder :). This is an application for Continues Deployment for .NET projects. I started the project at Hackatone that took place in summer 2011, in Kyiv. I liked the results I got there, so I didn’t throw it away after the contest, but slowly progressed on that through last several months.


welcome

The goal of application is very simple. Provide you with easy to setup and use tool Continues Deployment. I’m still very confused now with all those terms - Continuous Deployment/Delivery/Production/Release.. but in general it is nothing more as next step of Continues Integration. Rebuild and retest the application and deploy it in case of successful results.


welcome

I’m building that in mind of my own needs, how I see it might work for my projects. My own projects are really simple ones, so the candidate is really simple now. Of cause, I would like to be as general as possible, to cover common needs. I’m pretty much sure it would be rewritten hundred of times to reach the level of mass adoption and I’m looking forward to that.


config

Yesterday, I reached very important milestone of candidate.net. It is now feature completed. I would like to stop on current functionality and show it to you. It would take some time to prepare website and instructions, but please stay tuned for official release of project!


config

By the way, I’m still looking for new name! It turns out that finding the good name, could be even harder than finding process running bugs. I would be really happy if you do such early contribution proposing some nice name. Please do not hesitate and share your ideas just in comments.

Using ASP.NET MVC Validation Mechanism without ASP.NET MVC

I get used to DataAnnotations for model validation very quickly. Indeed, it is great approach. You attribute you model with corresponding attributes, rest is done by framework. It is only ModelState.IsValid, all you have to do before starting working with model.

During implementation of some feature for candidate I thought to myself, that I need need exactly same validation for my model class, but out of MVC framework. Namely, for some model class, like Github.cs I just want to know, is it “configured” or not. And configured == valid in my context. Instead of writing custom code with checking all required properties to have some values I wished to do the same as ASP.NET MVC does, through DataAnnotations. It turned out to be possible and really easy.

Basic start

Assume you have such model:

public class SimpleModel
{
 [Required]
 public string SomeProperty { get; set; }

 [Range(0,50)]
 public int SomeAnotherProperty { get; set; }
}
    

If your goal is just to get answer “yes or no”, you can create such function:

public bool ValidateSimpleModel(SimpleModel validate)
{
 return Validator.TryValidateObject(validate, new ValidationContext(validate, null, null), null);
}
    

Validator is a static class in DataAnnotations namespace. It takes target object, validation context and validation results collection. But due, to it just “tries” to perform validation, most of all parameters could be null.

Use validation results

If you need more specific information, like which field is exactly invalid you need to have ICollection<ValidationResult>

public ICollection<ValidationResult> ValidateSimpleModel(SimpleModel validate)
{
 var validationResults = new List<ValidationResult>();
 Validator.TryValidateObject(validate, new ValidationContext(validate, null, null), validationResults);

 return validationResults;
}
    

In case of invalid object it would return non-empy collection of ValidationResult, that would contain all relevant information.

Wrapping up to extension method

Finally, you can create simple extension extension method and apply DataAnnotations validation to any kind of object:

public static class ValidatorExtensions
{
    public static bool TryValidateObject(this object validate)
    {
        return Validator.TryValidateObject(validate, new ValidationContext(validate, null, null), null);
    }
}
    

So, the model could just have IsValid() method, like:

public bool IsValid()
{
 return this.TryValidateObject();
}
    

It works great for such simple task I need to accomplish.

Approval Tests: Locking down an output

We have seen how Approval Tests are useful for locking down some legacy code. You might say, that on practice we are having much more bigger problem, like some code that executes queries against the database. We need somehow to be able to work with that code, without worries of brake it down. Approvals could help here.

The case

Again I just imagine some legacy code that works with DB, it might look something like that:

public class ClassThatOutputsSomething
{
 private static Connection _connection;

 public void MethodThatProduceSomeResults(string parameterOne, int parameterTwo)
 {
  if (!IsConnectionOpened())
  {
   OpenConnection();
  }

  var connection = GetConnection();

  var value = HugeAndScarryLegacyCode.TheUgliesMethodYouMightEverSeen(parameterOne, parameterTwo, 'c');

  var query = string.Format("INSERT INTO TableName (SomeColumn) VALUES ({0})", value);
  connection.ExecuteQuery(query);
 }

    // ...
    

The MethodThatProduceSomeResults takes some arguments, call another method to get value and then store value to database. It will be problematic to tests what exactly is happening there. We might consider approach to check the difference in TableName before code execution and after, but we will go smarter and easier way.

Let’s prepare the test for that code.

Tests

The great thing with Approvals is the tests are really elegant. Just 2 steps - DO and VERIFY.

[Test]
public void should_be_able_to_test()
{
 // DO
 var some = new ClassThatOutputsSomething();
 some.MethodThatProduceSomeResults('some_input', 221);

 // VERIFY
 Approvals.Approve(...);
}
    

But you can see, the problem here is that we don’t have any return value of that method. Instead, it does something inside and keep that action in secret. We need some how to log all internal activities and than verify that log. Approval.Utilities contains exactly what we need.

[Test]
public void should_be_able_to_test()
{
 // DO
 var output = ApprovalUtilities.SimpleLogger.Logger.LogToStringBuilder();
 new ClassThatOutputsSomething().MethodThatProduceSomeResults('some_input', 221);

 // VERIFY
 Approvals.Approve(output);
}
    

I have just added logger ApprovalUtilities.SimpleLogger.Logger.LogToStringBuilder and do approve against it. But if I run this test I could see that output is just empty. Sure, we need to change MethodThatProduceSomeResults a little.

public class ClassThatOutputsSomething
{
 private static Connection _connection;

 public void MethodThatProduceSomeResults(string parameterOne, int parameterTwo)
 {
        // ...

        connection.ExecuteQuery(query);
        ApprovalUtilities.SimpleLogger.Logger.Event(query);
 }
    

So, in the place where query is being executed, we placed the logger and put exact some query inside it. Now if I run the test I will got application output, that I will approve and use those approved results after.

I’m not limited with only one place I could put logger. On practice, would more that one places to grab the results, as well as more that one argument for MethodThatProduceSomeResults method. By analysis of particular practical case, it is possible to place logger exactly where it’s needed, plus prepare best matching inputs. Just for example: after code examination it might happen that parameterOne is ProductId, but parameterTwo is ProductPrice. In my test I could query the database to select all products and prices and call MethodThatProduceSomeResults in loop, to get all potential output. That approved test will give me much confidence during refactoring.

Conclusion

Locking down output is very powerful technique, you can use it for any kind of objects that are “hidden” inside legacy classes, like SQL or console outputs.

On Herding Code episode Llewellyn describes the case of some legacy project he worked on. There was a kind of report generator and it’s code was just a big mess. He did copy of production database and put it in “Read-Only” mode. By running the report, he was able to find all places where code was accessing DB, since exception is thrown in that place. Putting in just the same log instructions as I did above, he managed to grab all SQL queries that run for that particular report. Everything were just in one file.

That’s the good example of reaching 100% code coverage just with one test.