Uncategorized

Why am I moving from Visual Studio to VIM?

As I mentioned in my previous post I want to use VIM instead of Visual Studio to work on my logcmd project. This would be a kind of an experiment, but I do have some fair reasons behind that decision. Why do I think VIM is a good alternative to Visual Studio?

It encourages automation

If you’ve ever worked in VIM, you know, that the most important & personal thing is _vimrc file. It’s not that all the keybindings and plugins are already there. You have to create them, customize, sometimes create scripts that boosts your development, and you do it all the time. The other things you need to run directly from console. And obviously you do not retype all the kilobytes of commands all the time. After the second try you want to automate it and have a script that works for you. Although it may sound prehistoric to some of you, it has a lot of long-term benefits. You don’t have to teach new people (or even your future “you”) how to validate JavaScript, do merging/branching, compile LESS, deploy to DEV server, upgrade release notes etc. This way you also get stronger in command line scripting.

It cures bad habits of debugging

All the people praise VS for astonishing debuggig features. It’s all true, but I think overused almost all the time. I know it allows to solve the most hardcore and unexpected behaviour that you could imagine, but on the other hand it’s like using excel for simple arithmetic. I experienced it on my own. Do you remeber one of the following:

  • running the application to check some business logic (writing unit test would take too much time (sic!))
  • fixing some hard issue after hours of debugging and forget how to debug again
  • wishing you could debug your application on PROD?

This all is because of relying on Visual Studio “debugger”. Other people not so tightly coupled with debugger invented better approach decades ago. It’s LOGGING. I’m always amazed how people solve their problems with RaspberryPi or Linux problems on discussion boards – it’s always clear after sending the logfile. Having a good habit of logging also works on “debugging” production.

It has better performace

It’s all about automation and the keyboard. Have you ever seen a hacking movie where they open “My computer -> My documents -> my hacking -> Visual Hacking studio -> create new project”? Or drag and drop viruses from “My downloads”. It’s because mouse is slower than keyboard (unless you participate in Quake 3 Arena world championship). Of course it’s slower if you started with mouse, but give it some time. You can self-check how much faster it is to use vim’s “ci(” instead of searching the starting parenthesis, selecting the text with mouse, finding the closing parenthesis and pressing BACKSPACE.
It’s also a better performance of the editor itself. Visual Studio is slow, but how can an application that takes a couple of GB on disk be fast all the time? On the contrary VIM is pretty leighweigh and blazing fast (unless you install everything you find on Github).

It’s more universal

VIM is everywhere, not only C, C++, C#, Java, JavaScript, Go, Haskel and friends. And VIM is there for years (VI released in 1976). It’s important if you hesitate about the future of Microsoft, or feel bored of .NET (or burnt).

It has the spark of extravagance

Have you seen Rob Ashton coding? Have you seen other people’s faces during that? But, that’s mixture of freak and performance.

It’s raw in a positive way

You think programming is not only about writing the code fast? It’s mainly about reading, right? Then even better, because VIM is raw. There are no codelens, different toolbars/toolboxes, variety of windows, resharper rainbow of tips and tricks. You can focus on code only.

Changing your environment is good

It opens up your mind, it’s like being polyglot programmer. In case of programming languages, if you knew C# only, you would solve each and every problem using classes. Same with environment/IDE. It’s obvious for us that using Visual Studio debugger we can set the next statement there and back. I believe other environments also has such obvious things that we are not aware of.

In the end I’d like to share some video of VIM coding in action.

Advertisements
JavaScript, Web

Logging JavaScript exceptions. Custom solution + ELMAH

Development team was reported about critical bug in production. First thing they did was checking server logs but they were empty. Impossible! On the other hand the client sent screenshot with error alert.
Have you ever experienced such scenario? It happened to me many times. And it’s nothing extraordinary – the more code on the client, the more probable to commit a bug. The worst thing is that’s so hard to track such bugs. After all it came out that’s not that hard. Here’s my solution:

  1. (Optional but recommended: use ELMAH. It adds a nice error log and page to browse already caught errors + some extra information about context of such errors)
        Install-package elmah
    or if using ASP.NET MVC
        Install-package elmah.mvc
  2. Listen for client-side errors and send them to the server (custom errorLogging.js script):
    jserror3
    Please note, that the code above does not work on IE7 and below (just to keep it simple). IE supports JavaScript stacktrace from version 10+ that’s why there is “if” clause between lines 16-18.
  3. Add back-end code to listen for exception logsjserror4
    You could use MVC or WebAPI controller, but handlers feels more like infrastructure. If you don’t want to use ELMAH, then replace line 36 with your logging mechanism (or “throw jsException“).
  4. Create exception type specific to JavaScriptjserror5
    It’s particularly important to override ToString() method as it’s used by ELMAH to dump exception details.
  5. Connect it all together: add script reference to errorLogging.js and register JavaScriptErrorHandler class in global.asax.cs

And there it is! If you don’t want to do it yourself go to my github page and download a working sample: Blog.ClientSideExceptionCatching

After playing for some time here are the results. As you can see both server-side and client-side errors are kept together with the time they occurred.
jsError
If you go deeper then you see exception details (message, stacktrace).

jsError2_1

jsError2_2

This is something that we get by our hands. Elmah also gives us a very useful gift as it logs all server variables, including HTTP_USER_AGENT that tells us what browser was used on the client. You don’t need to ask the user for such things. Handy!

Off-topic/final points

  • First I tried jsnlog but failed. It forced me to use Common.Logging and was not working out-of-the-box.
  • Beware of Internet Explorer – it generates localized exception messages (see the first elmah screenshot) and may not support stack trace
JavaScript, test automation, tools, UI Testing, Web

Unit testing JavaScript with VisualStudio and Resharper – running on buildserver + code coverage using Chutzpah

Introduction

Unit tests are priceless but only when run automatically. Otherwise they can become forgotten and stay red (or ignored) for the rest of their lifetime. In the last two posts about unit testing in Javascript [1, 2] we have prepared our solution. Now it’s a very good time to tell our buildserver to run them during the build process. I chose Chutzpah as the test runner.

Chutzpah

Chutzpah, pronounced [hutz-pah] from Yiddish/Hebrew, means “shameless audacity, utter nerve”. It’s a JavaScript tests runner that uses internally PhantomJS, Jasmine/QUnit to run the tests and BlanketJS to generate code coverage. The package contains both VisualStudio extension to run the tests (but I prefer Resharper) and console runner used by buildservers (especially TeamCity). Beside its core functionality chutzpah can also generate report with code coverage of JavaScript. Among all known approaches to run javascript test, in my opinion using Chutzpah is the simplest.

Getting started with Chutzpah

  1. Download Chutzpah and extract it to some well-known place (in my case C:\BuildTools\chutzpah)
  2. Add chutzpah.json configuration file to the test project folder. This step is optional for chutzpah, but in our case we use root path while referencing files in unit tests and this needs to be configured specially in the config file (there is also some additional information about code coverage pattern):3
  3. Run chutzpah console runner with parameters:
    /path – place where all the testes are
    /codecoverage – tell chutzpah to generate html report with code coverage

2

There is also an extra output file with code coverage information:

4

Preparing package for build server

Now we are able to run tests on build server – just run chutzpah.console.exe with specific parameters. the build should fail if any test fails. The other thing is the reporting to the build server about the test result. Fortunately Chutzpah has built-in support for TeamCity (/teamcity command line swith) but also serves XML output (/junit switch).

To have it on Teamcity I needed only to prepare MSBUILD file with the build procedure (I prefer to have everything in source control, especially build procedure, that’s why I don’t believe in TeamCity build steps):1

After adding this file to TeamCity we should see:

5

And after configuring report tab for “JS Code Coverage”:

6

Have fun!

Demo

Download and play with the demo solution:
FrontEndTools_buildserver.zip

JavaScript, test automation, Web

Unit testing JavaScript in VisualStudio with ReSharper – improvements

This is another approach to the previous subject: Unit testing JavaScript in VisualStudio with ReSharper. I kindly encourage you to get back to it before further reading.

Referencing production code in Test project

Last time I suggested “link-referencing” files with production code. Then during the build process files were copied to the test project. This approach was a bit cumbersome:

  • we had code duplication in our solution structure
  • sometimes it wasn’t obvious which file was edited – original file or the file copied to the test project
  • R# was complaining about missing references before the build process
  • You need to prepare test project file (.csproj) to make it work
  • You need to reproduce reference structure and keep it up-to-date while working with tests

Fortunately there is a cleaner approach to referencing production code. The solution is to reference files using root reference path:image

In this case we get the root of the test project, go to parent folder (..) and take the files directly from the project with production code (FrontEndTools). Now the only disadvantage is that each test file should know what’s the name of the folder of the tested project and change it when the folder name is changed – but this is very rare case, isn’t it?

If your Resharper marks the referenced file red, add reference to the tested project (FrontEndTools in my case).

From now on the solution structure looks much cleaner:

image

Switching to Jasmine

Previously I mentioned that I prefer QUnit with its TDD style, but after some time using both I changed my mind. Here are some of my thoughts:

  • Jasmine is more popular – I don’t have any statistics, this is just my feeling after browsing some open source projects and mixing with angularJS communities – I’ve just found Jasmine as a standard
  • Jasmine with its beforeEach/afterEach is more similar to NUnit SetUp/TearDown
  • Jasmine has own (extendable) matchers that simplifies doing even complex assertions
  • Built-in mocking framework is awesome – and this is actually killer feature – in QUnit you should build mocks manually or add external libraries (like SinonJS)
  • Both are supported by default (and only these two) by Resharper
  • Both have very good support and community background (with plugins and extensions)

Other demo solution improvements

  • jasmine.js referenced to test scenarios – Jasmine is by default supported by Resharper, but to get IntelliSense and get rid of Resharper annotations it’s good to reference proper Jasmine.js file explicitly
  • added tests for ColorBoxViewModel with a sample of Jasmine mocking
    image

Download

You can download the demo here: FrontEndTools_Jasmine.zip

tools, UI Testing

Resharper template for unit test method (replacing spaces in the test name with underscore sign)

Resharper live templates are great to automate repetitive work. An example of such work is unit test method. In the first part I’ll show how to create a basic template that will build the structure of a unit test. In the second one I’ll show how to make R# give a correct name to such test based on human-readable description.

Test template

Below we have an example of a test method in AAA style:

[Test]
public void when_doing_something_then_expect_something()
{
   //ARRANGE
   var x = 100;

   //ACT
   var result = this.Calculator.Sqrt(100);

   //ASSERT
   Assert.AreEqual(10, result);
}

As we can see to create a nice structure of AAA unit test we need to remember about three comment labels, attribute, correct test name. Such structure can be easily extracted as resharper live template. To do it:

1. Go to Resharper –> Templates explorer

2. In “Templates explorer” select “C#” section and click “New template”:

image

 

3. Fill in live template form – edit shortcut and content:

image

After that the new template is ready to be used. Just type the shortcut entered before, click ENTER and this is it!

image

Converting a sentence into a valid test name

Another problematic thing in writing unit tests is naming the test. We want to give self-describing names to tests. Sometime it’s a rule, to name tests like “When something then something”. This way we use a human-readable sentence in a place, where spaces between words are not allowed. Thus we are forced to replace them with underscore (‘_’) sign, or capitalize each word – both ways are highly uncomfortable and drive developers mad.

However it is possible to use resharper macros to do additional logic for template fields. We can choose a macro for each field (look at the picture of the template form). Unfortunately here is a first disappointment – there is no bult-in macro to achieve this. It’s even worse, because there is a macro called “Value of another variable, where spaces will be replaced with ‘_’”, but this one cannot be applied to the same variable (test name in our case).

 

To overcome this disadvantage it’s needed to create custom macro applied as a plugin. Below there is a code of the macro:

    [Macro("chsreplacespacewithunderscore",
            LongDescription = "Replace spaces with '_' (i.e. \"should return nothing\" into \"should_return_nothing\")",
            ShortDescription = "Replace spaces with '_'")]
    public class SpacesToUnderstrokesMacro : IMacro
    {
        public static string Evaluate(string text)
        {
            return text.Replace(" ", "_");
        }

        public ParameterInfo[] Parameters
        {
            get { return EmptyArray<ParameterInfo>.Instance; }
        }

        public HotspotItems GetLookupItems(IHotspotContext context, IList<string> arguments)
        {
            return null;
        }

        public string GetPlaceholder(IDocument document)
        {
            return "sentence with spaces";
        }

        public string EvaluateQuickResult(IHotspotContext context, IList<string> arguments)
        {
            if (context.HotspotSession == null || context.HotspotSession.CurrentHotspot == null)
            {
                return null;
            }
            var currentValue = context.HotspotSession.CurrentHotspot.CurrentValue;
            return Evaluate(currentValue);
        }

        public bool HandleExpansion(IHotspotContext context, IList<string> arguments)
        {
            context.HotspotSession.HotspotUpdated += this.CurrentHotspotUpdated;

            return false;
        }

        public void CurrentHotspotUpdated(object sender, System.EventArgs e)
        {
            var hotspotSession = sender as IHotspotSession;
            if (hotspotSession != null)
            {
                hotspotSession.CurrentHotspot.QuickEvaluate();
            }
        }

To compile, it is needed to reference the following R# libraries (from the installed version of R#, in my case R# 7.0):

JetBrains.Platform.ReSharper.DocumentModel.dll
JetBrains.Platform.ReSharper.Shell.dll
JetBrains.Platform.ReSharper.Util.dll
JetBrains.ReSharper.Feature.Services.dll
JetBrains.Platform.ReSharper.ComponentModel.dll

Most of the code is about implementing the standard IMacro interface. Most important here is the method EvaluateQuickResult that evaluates the value of the current field (hotspot) in a template. The same function is invoked each time the HotspotUpdated event is triggered.

Newly build plugin can be now added to resharper. Just copy it to “C:\Users\some.user\AppData\Roaming\JetBrains\ReSharper\v7.0\Plugins” folder and restart VisualStudio. After that the new macro can be added to the template and the test name will be transformed to the valid identifier on the fly.

Download

Instead of building your own plugin, you can also download it from here

Update

I also highly recommend creating another macro just to replace spaces with ‘_’. I’ve got ‘testn’ = ‘test name’ and it’s used extensively for renaming unit tests