Archive

Archive for the ‘Tools’ Category

AutoHotkey – the essential tool for all “automate-it-all” practioners

November 2nd, 2013 No comments

AutoHotkey logo
Introduction
This post is about a tool I always feel very crippled without, namely the incredibly useful AutoHotkey. I always install this onto new machines and I rely on it heavily every day. The strange thing is that rather few people I meet know about it so I thought I’d remedy that ignorance somewhat by posting an overview here on my blog.

So what is it? AutoHotkey allows you to map keypresses to custom macros.

This key press mapping works in any application by default and the macros that are possible are very flexible.

Some examples
The most common use is probably to start applications for a given key combination. Here’s one I use:

!#n::Run Notepad++8

This starts Notepad++ when I press Ctrl-Alt-N

You can also write a little more complex macro code (the macro language is a custom one for AutoHotkey, here’s some documentation)

^!Enter::
	FormatTime, CurrentDateTime,, yyyy-MM-dd
	EnvGet, UserName, UserName
	SendInput /%CurrentDateTime% %UserName%
	return

This inserts a timestamp with my username when I press Ctrl-Alt-Enter.
Example: /2013-11-02 emila

Note that this works in any application since AutoHotkey sends standard Windows messages simulating keypresses for the text. So there’s no problem to use this macro in Notepad, for example.

To take this one step further, the key code trigger does not have to be based on qualifier keys such as Ctrl, Alt etc, it can also be a sequence of standard characters. Here’s one example of this:

; Today
::tdy::
	FormatTime, CurrentDateTime,, yyyy-MM-dd
	SendInput %CurrentDateTime%
	return

This creates a macro that inserts the current date every time I type the sequence “tdy” followed by a word delimiter (space, tab, dot, comma, etc). This simple macro is probably the one I use the most, it’s so incredibly useful to have easy access to the current date when taking notes, creating folders, etc.

I also have a few code snippets I use a lot when programming:

::isne::String.IsNullOrEmpty
::isnw::String.IsNullOrWhiteSpace
::sfm::String.Format 

This way I never feel tempted to write string comparisons such as if (s == null) { ... }, it’s just as easy to write if (String.IsNullOrEmpty(s) { ... } using my snippet. And this kind of snippet works even in Notepad :-)

This ability to replace character sequences is also very useful for correcting my common spelling errors:

::coh::och
::elelr::eller
::perosn::person
::teh::the

I try to detect common operations that I often perform that can be automated and try to write an AutoHotkey macro for them. An example of this is that I have noted I often have to write a valid Swedish social security number (personnummer) when testing applications I write. This can be a pain since the number has to end with a correct checksum digit, so I wrote a simple web service that creates a random SSN and returns it. This service can be called from AutoHotkey like this:

; Anropa web service för att skapa personnummer
::pnr::
	EnvGet tmpDir,TEMP
	UrlDownloadToFile http://kreverautils.azurewebsites.net/api/testdata/personnummer,%tmpDir%\random.pnr.txt
	FileRead, pnrRaw, %tmpDir%\random.pnr.txt
	StringReplace, pnrClean, pnrRaw, ", , All
	SendInput %pnrClean%
	return

This is really convenient, I just type “pnr” and it’s replaced with a valid SSN. This really lowers the mental barrier when testing applications where this data is required, resulting in better testing. (Mental barriers when testing applications are very interesting and is perhaps worth a separate blog post some time…)

Summing it up
The above examples absolutely just scratch the surface of what you can do with AutoHotkey, so why not give it a try? It’s free, so it’s just a matter of downloading it and start experimenting. Download it from its home page.

Final tip
I like to have all my computers share the same AuoHotkey setup so I have created my main macro file (general.ahk) in a DropBox folder. I also create a shortcut in my startup folder with this target string:

C:\Users\emila\Dropbox\Utils\AutoHotKey\general.ahk

Since AutoHotkey associates itself to the “.ahk” file extension, this is enough start start the script on startup. Any change I make to the macro is automatically propagated to all my computers.

Good luck with your automations!

/Emil

Categories: Tools Tags: , ,

Using NDepend 4 to analyze code usage

September 5th, 2012 No comments

This week I was assigned the task to analyze the usage of an ASMX web service we are planning to remove since it has a number of problems (which is another story) and switch to new and better written WCF services. As the service is rather large and has been around for years the first step was to analyze if it had methods that no client actually used anymore.

For this task I decided to use the brilliant code query functionality built into NDepend 4. I have briefly reviewed earlier versions of this tool on this blog but this time I thought an actual example of how to use it in a specific situation would be illuminating.

The first step was retrieve a list of the methods in the web service. To do that, I added an NDepend project to the web service solution. Se below for an example of the dialog used for this:

Attaching an NDepend project to a Visual Studio solution

After this NDepend performed an analysis of my solution, after which I was able to start querying my code using the CQLinq querying language. NDepend has for a long time had its SQL-like CQL (Code Querying Language) but for some reason I never got around to using it. NDepend 4 introduces CQLinq which is much nicer syntactically and has a good editor for writing code queries, including IntelliSense. For more info about CQLinq, see this introduction.

What I needed was a list of methods on my Web Service class. To retrieve this, I opened the “Queries and Rules Edit” window (Alt-Q) and typed:

from m in Methods
where m.ParentType.FullName == 
   "ActiveSolution.Lernia.Butler.EducationSI.Education" && m.IsPublic
select m

The CQLinq query window.

The results is displayed in the bottom pane. I exported the list to an Excel file for further processing.

The next step was to see which of the web service methods the different clients used, so I analyzed each client with NDepend. Note that I excluded their test projects from the NDepend analysis to make sure that no lingering old integration tests affected the results.

For each client I listed those methods of their respective web service proxy classes that they were actually calling. A query for that can look like this:

from m in Methods  
where m.ParentType.FullName == "ActiveSolution.Lernia.SFI.WinClientFacade.Butler_EducationSI.Education"  
&& m.IsPublic  
&& !m.Name.StartsWith("Begin") 
&& !m.Name.StartsWith("End") 
&& !m.Name.Contains("Completed") 
&& !m.Name.Contains("Async") 
&& m.NbMethodsCallingMe > 0 
select m

The ParentType is of course the proxy class that gets generated when adding web service references. For this type, I list all public methods (except the asynchronous helper methods that we don’t use anyway) that are used by at least one other method. The results were copied into the already mentioned Excel document and when all clients’ data was retrieved I was able to do some Excel magic to get this result:

The resulting Excel report listing the reference count for each method in the web service class.

The columns B through G contains ’1′ of the respective client is calling it. Rows with a sum of zero in column H are not used by any client and can be safely removed. Mission accomplished.

This has absolutely just scratched scratched the surface of what can be done using CQLinq, and there is much more functionality in NDepend than just queries (the diagram tools, for example). It’s a great product for anyone that is seriously interested in code quality. And we all should be, right?

/Emil

Categories: Reviews, Tools Tags:

Viewing assembly binding logs using fuslogvw.exe

March 7th, 2012 No comments

Sometimes it’s very useful analyze how an application binds to referenced assemblies but this process is fairly hidden from us. However, Microsoft has given us a way to look into this process via the fuslogvw tool. This tool is not overly documented so this post describes how to install it on a computer that has neither Visual Studio nor the Windows SDK installed, such as a server.

Follow these steps:

Copy the following files from a computer with Visual Studio or the Windows SDK installed:

  • "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\FUSLOGVW.exe"
  • "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\1033\flogvwrc.dll"

Put them into a folder on the target computer.

Create logging folder, e.g. c:\fuslog

Start FUSLOGVW.exe. Update the following settings:

  • Log all binds to disk
  • Enable Custom log path
  • Custom lag path = c:\fuslog\

Finally, enable assembly binding logging in the registry by setting the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion to 1.

Click Refresh in FUSLOGVW.exe and behold! A list of assembly binding events are displayed:

The individual events contain useful details:

/Emil

Categories: .Net programming, Tools Tags:

NDepend 3

June 1st, 2010 No comments

In case you missed it, there’s a very powerful tool called NDepend that helps you analyze your code structure and detect potential problems very easily. A new version, NDepend 3, was released earlier this year and the biggest new feature is probably Visual Studio integration:

It still has all the code metrics you’ll probably ever need, a custom made code query language, diagrams (some of which are still a little difficult to read) and graphs to help with analysis. See my post about the previous version for some examples.

Here are a few live examples of using NDepend: http://www.ndepend.com/Features.aspx#Tour

If you’re into code analysis you should give NDepend a try. With this new version it’s more usable than before and it still has the same very powerful analysis engine under the hood. Check out http://www.ndepend.com for more info.

/Emil

Categories: .Net programming, Reviews, Tools Tags:

Running .Net 4 RC NUnits tests in TeamCity

March 16th, 2010 No comments

Today, we finally found a way to run NUnit tests in .Net 4 assemblies in TeamCity! Here’s the solution:

Problem with NUnit runner when using MSBuild 4.0

/Emil

NUnit with SQLite and .Net 4.0 Beta 2

November 20th, 2009 14 comments

SQLite and unit testing is a great combination for testing database operations without having to manage database files. You can simply create an in-memory database in your setup code and work with that instance. Perfect in combination with NHibernate, for example.

If you want to do this in the current .Net 4.0 beta you’re out of luck though, you’ll get an exception:

System.IO.FileLoadException: Mixed mode assembly is built against version 'v2.0.50727' of the runtime
and cannot be loaded in the 4.0 runtime without additional configuration information.

The solution is pointed out by Jomo Fisher. What you do is to include this snippet in the application config file:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0"/>
</startup>

When unit testing assemblies that references System.Data.SQLite.DLL then you have to put that snippet in NUnit’s config file (C:\Program Files\NUnit 2.5.2\bin\net-2.0\nunit.exe.config).

If you combine this with the tip in my post NUnit with Visual Studio 2010 Beta 2, you should insert the following

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0"/>
  <requiredRuntime version="v4.0.20506" />
</startup>

plus

<loadFromRemoteSources enabled="true" />

under the runtime tag.

This works for me, hopefully it will for you as well.

/Emil

log4net configuration Xml Schema

November 19th, 2009 No comments

I just found a very useful XSD for editing log4net configurations:

http://csharptest.net/?p=38

Just copy the schema file to C:\Program Files\Microsoft Visual Studio *\Xml\Schemas and add the correct namespace to the log4net element in your config file:

<log4net xsi:noNamespaceSchemaLocation="http://csharptest.net/downloads/schema/log4net.xsd" 
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

/Emil

Categories: Tools Tags:

NUnit with Visual Studio 2010 Beta 2

November 16th, 2009 No comments

Here’s a tip of how to run NUnit tests in .Net 4 code:

Running NUnit 2.5 against Visual Studio 2010 .Net 4 code

Note that it’s the NUnit.exe.config file in C:\Program Files\NUnit 2.5.2\bin\net-2.0 that should be updated.

NDepend – first impressions

October 21st, 2009 No comments

I was recently contacted by Patrick Smacchia, one of the developers behind NDepend and he asked me if I’d like to try it out, which I did. This is a report of my first impressions.

If you’re not familiar with NDepend, it can be described as a tool to analyze a set of .Net assemblies for code quality. I suppose its name indicates that it originally was focused on analyzing dependencies but these days that name is rather misleading, in my opinion, as it can do much more that that. I’ll go through some of its capabilities below.

When you first analyze a set of assemblies, NDepend displays a screen similar to this:

NDepend main screen

If you’re like me, then you didn’t check out any tutorials or web casts before running the tool and your first reaction is likely “Holy cow! What’s all this?” or something similar. :-)

It turns out that there is a ton of useful information in these displays but you have to know how to interpret them which takes a little learning.

Briefly, here’s what I gathered so far:

  • The Metrics display (with the gray blobs) lets you select a metric (such as the number of lines of code) and display it on the selected code level (method, field, type, namespace or assembly). The the blobs represent code entities of the given level and their sizes correspond to the metric’s value. All children blobs of the parent level are grouped together to indicate which parents have high accumulated values of the metric. This display was really bewildering to me at first but once you decode its structure then it’s really powerful.
  • The Dependency graph is more intuitive and let’s you see call dependencies between code components of different levels. Works well on small numbers of components but once you start to display larger dependency chanins, e.g. between methods, then it quickly becomes very difficult to use.
  • The Dependency matrix is also fairly unintuitive at first, but very powerful.
    NDepend depenency matrix
    It contains the so called Dependency Structure Matrix with displays dependencies between code elements. Each non-empty cell in the matrix represents a dependency but the number can have different meaning depending on user selections in the GUI. Green and blue cells indicate one-way dependencies (hover mouse over a cell to display a small arrow indicating the direction) while black cells represent bidirectional dependencies, which might be a cause for concern. This display can really show many interesting aspects of usage dependencies and it can also be used to generate dependency graphs for subsets of these dependencies (try the popup menu to see what I mean).
  • Finally, there the CQL query display where you can use the NDepend Code Query Language to further analyze your code. By default a set of standard queries are executed, listing potentional problems with naming, performance, and many others.

In addition to the displays described above, an HTML report is also generated after analyzing assemblies. It displays much of the same information as the graphical and interactive displays above, but also contains the “Abstract vs instability diagram”:

NDepend AbstractnessVSInstability diagram

Obviously you want to be in the green area with all your assemblies, but the dimensions used might not be completely clear at first sight. This seems to be a good article describing it it detail.

So, what are my first impressions? Well, I must say that NDepend really is a very powerful tool for analyzing code but it does require investing some time to use its many features properly. To me, that seems like an investment well worth doing.

/Emil

Categories: .Net programming, Reviews, Tools Tags:

Switch to our mobile site

Web Analytics