tools, Web

Go to recent tab in Chrome

For a long time I have been searching for such feature in Chrome, but I could not find anything default. And it was difficult to understand, as it is so obvious for a developer. Windows has it (Alt + Tab), Resharper has it (Ctrl + ,), visual studio without plugins has it, same to Sublime Text, vim etc. But not Chrome, a default development tool for most of web developers. At the same time there are extensions, but most of them work far from what I expect. Below I would like to share what useful I have found. Both are fine, but for sure not flawless.

Ctrl + Tab MRU

ctrltabmru

This is the one I like the most. I have it bound to Ctrl + comma. That means that a combination Ctrl + comma, comma take me to the second recently used tab. It’s obvious, but actually this is the first extension I have found, that supports it.

The bad? Several times it had problems to render the list correctly. On the other hand I tried to reproduce it while writing this blog post and I couldn’t.

Quick Tabs

quicktabs

This one is more advanced, as it allows to search in usage history, recently closed and bookmarks. Unfortunately Ctrl + comma, comma, comma does not work as expected (but still it’s worth to have because of searching functionality).

What about you?

Do you have your own solution for that? I would really like to know if there is something better or at least if there is another useful alternative.

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, Web

JavaScript/TypeScript unit testing –11 sample projects for Resharper, Chutzpah and Karma

logoIntroduction

An example is worth a thousand words. But seriously it’s a lot easier to follow some given scenario than searching for tutorials for some tools and then trying to apply them to a project that is not supported in the end. Moreover unit testing the client side of the project is more complicated than the back-end part. Maybe it’s because we’ve got used to creating test projects based on nunit/xunit/mstest/mspec etc. In Javascript world it’s a little bit more tangled: we have Javascript but also move forward to TypeScript. We have plain code without modules or use requirejs to benefit from AMD. For each configuration the setup of unit test project is different. I think having all these samples in one place could help us to start TDD in client-side.
All the sample are based on the sample application from my previous posts about unit testing JavaScript. Actually these are not 11 different sample projects, but 11 versions of the same project so that you can easily catch the difference between the configurations.

Samples (links)

 

JavaScript JavaScript TypeScript TypeScript
NoAMD AMD NoAMD AMD
Resharper link link* link** (none)**
Chutzpah link link link link
Karma link link link link

** Resharper 8.2 should support support TypeScript testing [RSRP-394249]

* AMD support in this sample is artificial, code must be based on named modules that are loaded staticaly.

Tools review

 

Resharper

image

Resharper lets you run unit test for JavaScript. Actually it could be enough to just start using it as a test runner. It’s awesome to right-click on solution, choose “run unit tests” and watch the solution passing all the tests: back-end and front-end in one go. Moreover it’s also super-easy to set up. Unfortunately the practice is more cruel – it’s ok for simple Javascript project without AMD.  TypeScript support is not yet in live and AMD support is not yet even planned. And there is no command line runner to let the tests run in buildserver. Otherwise it would be the perfect choice.

Chutzpah

image

As an alternative we have Chutzpah. To integrate it with Visual Studio  you can install “Chutzpah Test Runner Context menu Extension” or “Chutzpah Test Explorer Adapter” (default one for Visual Studio). You can also download command line tool that will run the tests in console or in buildserver (it even generates code coverage report). It has builtin support for requirejs and TypeScript. Unfortunately tests discovery is a little bit too slow to run it spontaneously after each change.

Karma

image

This runner is a must-have in AngularJS world and is a JavaScript alternative to NCruch (runs tests continuously after saving changes). It’s a little bit tricky to configure but after that it is super cool to play with. It doesn’t have TypeScript support out of the box, but because TypeScript is compiled to javascript it deals with it successfuly. It’s possible to configure karma to use Chrome (or any other favourite browser) to be the test runner and it makes it very fast and natural to debug. It’s also possible to set the “run once” mode to run it on buildserver using phantomJS. The dark side of the tool is that it’s not integrated with VisualStudio and you have to stuck with console window (actually there is one plugin that runs karma in VS output window but it’s still a hidden console and not Test explorer adapter).

Happy testing folks!

BTW: if you like the samples, remember to leave a github star 😉

Refactoring, tools, Web

Removing unused UserControls with NDepend

Untitled2

NDepend is an amazing analysis tool for .NET code. It gives you deep insight into your code and let you manage its quality easier. It lets the user execute LINQ queries on code, generates dependency graphs, metric view, check rules and many many more. In this post I’ll show a very simple trick to detect unused user controls that can be removed from our project.

NDepend was recommended by Scott Hanselman, Greg Young and others. I tried it some time ago in my small project but I couldn’t benefit from the tool. After some time I had to do some cleaning in our legacy system. Then I came back to the the tool and I have to admit that I fell in love with it.

Some time ago I wrote about Finding unused private and public methods with Resharper. It is of course very nice way of doing code clean-up but in rather smaller systems. In my case Resharper found around 2.5 thousand issues and it’s not an amount that I could face in one or two iterations.

Some issues are specific to particular parts of the solution. In WebForms project the highest level of abstraction is Page and Control. If the user removes/refactors page and decide to not use some user control it becomes dead source of other dependencies.

In the first iteration I decided to get rid of unused pages with help of google analytics report from the last few month. The next one was about dead user controls. Resharper doesn’t allow us to find unused types deriving from specific base type. Here is the place for NDepend.

In “Queries and Rules” section I run the following query:

Untitled3

As a result I got the list of around 30 user controls. Unfortunately this is just an input for further filtering because it lists controls that are not used in code, but not saying anything about markup. All in all checking this is not that hard, one solution is to go through all of them and check what compiler says or find all occurences of “<%@ Register Src="~/Path/MyUserControl.ascx" TagPrefix="uc" TagName="MyControl" %>” for each *.ascx file.

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

Desktop, tools, Web

Generating HTML document from template using NVelocity

Web HTMLSometimes there is a need to generate a document (HTML report, e-mail etc.) from a given template. It’s simple when it comes to just replace some tokens, but in case of more complicated operations (dealing with collections, conditions, loops) it’s better to use advanced template engine. Most of us are familiar with many (even unconsciously): WebFormsViewEngine (ASP.NET WebForms), Spark (ASP.NET MVC), Razor (ASP.NET MVC) and probably many more (here’s a nice comparison). Unfortunately these famous ones depend on ASP.NET and it’s rather a big deal to use them in a simple library. Fortunately there is NVelocity that can be used as a standalone tool and gives pretty much flexibility.

NVelocity

NVelocity is a port of very famous template engine from Java world called Apache Velocity that makes it possible to build MVC application (used for example by JIRA or Spring Framework). The latest version of NVelocity is a part of Castle Project and can be downloaded from github (other versions stored on codeplex or sourceforge are no longer supported). You can also use Nuget to do the same.

Velocity alone is documented pretty well, but also the library in Castle Project repository contains a lot of samples (I believe each single keyword has a separate document with sample usage).

NVelocity does not need any extra references but NVelocity.dll that you can build on your own or take it from the sample app in the end of this post.

Sample usage

Here’s is a code showing the sample usage of NVelocity:

Velocity.Init();

var model = new
{
	Header = "Test Header",
	Items = new[]
	{
		new { ID = 1, Name = "Name1", Bold = false},
		new { ID = 2, Name = "Name2", Bold = false},
		new { ID = 3, Name = "Name3", Bold = true}
	}
};
var velocityContext = new VelocityContext();
velocityContext.Put("model", model);

string template = string.Join(Environment.NewLine, new [] {
	"<p>",
	"   This is model.Header: <strong>$model.Header</strong>",
	"</p>",
	"<ul>",
	"#foreach($item in $model.Items)",
	"   <li>",
	"      item.ID: $item.ID,",
	   "#if ($item.Bold)",
	"      item.Name: <b>$item.Name</b>",
	   "#else",
	"      item.Name: $item.Name",
	   "#end",
	"   </li>",
	"#end",
	"</ul>"});

var sb = new StringBuilder();
Velocity.Evaluate(
	velocityContext,
	new StringWriter(sb),
	"test template",
	new StringReader(template));

This should produce the following result:

image

Some explanation

The snippet above is rather self-explanatory, but I’ll just point out the most important clauses. First thing is “Velocity.Init()” that initializes the engine and creates a pool of parsers (NVelocity uses singleton pattern). Next we need to create VelocityContext that is a map of velocity variables and .NET objects. Here I used anonymous objects, but you’re free to pass any .NET object. NVelocity interpret IEnumerable as NVelocity collection, it also supports .NET properties. “Velocity.Evaluate()” applies the context to the given template and produces result using passed TextWriter.

Demo

Feel free to experiment with the solution above: download