Stuff for Geeks

Louis Hau├čknecht's blog

MSpec with VB.net

clock April 12, 2012 19:11 by author Louis

 

Hadi Hariri (@hhariri) inspired me to give BDD a try.

Unfortunately I’m currently working in a VB.net shop. So I tried to rewrite the BDD examples in VB.net.

Poor MSpec. Poor VB world. It works but it adds a lot of vb-clutter to the source.  Pay attention to those multiline anonymous functions…

And here is the beautiful C# version:

You can find the whole gits here: https://gist.github.com/2368670



Nancy's Raven

clock August 4, 2011 12:10 by author Louis

For a new project I was keen on taking one of the so called Micro-Web-Frameworks for a test drive.

My favourite Framework is NancyFx. Nancy makes just fun!

It's a HTTP in essence.

But is one fancy new Framework enough for a fresh project? What about persistence? Okay, let's add a some NoSQL flavour to the mix!

I'm following Ayende for years. So reading about RavenDB in his blog and in the newsgroup made me wanting to get my hands on it.

Nancy and RavenDB are all on Nuget, so getting the bits and pieces together is just:

Create empty Web Project
install-package Nancy
install-package Nancy.Hosting.Aspnet
install-package RavenDB

I really like the Idea of working with the database directly without having infrastructure code in my Modules. We are talking about "Session per Request". Every request to the server opens a new unit of work. It should be easy to query for data but also to write and modify.

In a MVC application we wire everything up in global.asax. But there's no global.asax in Nancy.

With nancy your controllers are NancyModules. 

So my goal is to have a Property called DocumentSession in every Module, so that I can work with my datastore frictionless (<- Kudos to Ayende for this cool notion).

@TheCodeJunky gave me a hint on twitter how to do it.

The idea is to have a hook in the building phase of a module (your controller) to inject the Raven session.

But before injecting something you need a source for your session:

 

We lazily initialize a static DocumentStore. Creating a DocumentStore should happen only once in your application. The DocumentStore provides IDocumentSessions.

I've extracted the interface IRavenSessionProvider from this class. 

Now we need to tell Nancy that she sould use this provider to add the session to our module. In your NancyBootstrapper we cutomize the construction process:

 

This tells Nancy to use a custom ModuleBuilder to build our module. And here's where the bird comes to her:

 

In the constructor we add a dependency on IRavenSessionProvider. Dependencies are resolved by the internal TinyIoc. How cool is that!

BuildModule is where the magic happens. We request a new IDocumentSession and store it in the Request Context. When our request ends we want to save all changes and get rid of our session. So we add this action to our AfterRequest-Pipeline.

We can now access our session by accessing the Context-Items. But this is inconvinient and I want to stick with the DRY principle. So lets factor this out.

 

This gives us a base class with the property DocumentSession. And finally here's a sample of our Module in action:

 

 

We have two actions in this Module. If the module receives a HTTP GET request it queries RavenDB for Customers who's name start with the given first letters.

The other action is the PUT action. Put creates a new Customer in the database. 

All actions in one Request are transactional save by the way. This is ravens "Save by Default" approach.

For my project it seems like the perfect combination (+ I can play with cutting edge technology)!



Having trouble with Lambdas in VB.net

clock August 31, 2010 12:35 by author Louis

I’m using NSubstitute in a new TDD project for a component. Normally I prefer to program in C# but the company I’m currently working for is a VB-Shop, so I have to use VB here. (Note: I’m using VS 2008 atm)

NSubstitute is a mocking framework which makes heavy use of Lambdas. This results in compact and very readable Tests.

Here is an example where I want to throw an exception when a specific method on a mock is called (C# version). Given this interface:

image

 

In the test we expect that the Bar() method should throw an ApplicationException.

image

First we create a Substitute (a mock) aSub. By using the Returns() – extension method which comes with NSubstitute, it is possible to define what should be returned by a given method. Here I just define that calling Bar() throws the expected ApplicationMethod.

Calling Bar() throws and our test turns green.

Now turning to the dark side VB side:

image

 

The first thing to notice here is how the VB spoils the nice syntax by the Of Keyword for generics. “Substitute For Of IFoo” is just not as nice as  “Substitute For IFoo”.

But let’s focus on the main part I want to discuss. To satisfy the tests expectations we cannot just use a nice lambda as in C# because throw new ApplicationException just returns nothing, which is not allowed in VB. The workaround is to use a delegate. So let’s point to (AddressOf) our ThrowExForStringFunction.

image

To define this function you have to figure out which signature you have to use. This is not as easy as I thought and ReSharper won’t generate the correct signature for you. Studying the NSubstitute sources and the compiler errors is the way to go. Sadly.

In contrast to the C# example we have to deal with internal details to generate the matching method signature just to throw an exception.

To be fair the method could be generalized by using generics:

 

image

 

And the generic method:

image

Summary: It’s not only NSubstitute which looses the concise syntax. It’s all over the place when using Lambdas in VB.net!  I hope Visual Studio 2010 brings some improvements to the language.



Using LinqPad for ad-hoc text analysis

clock August 19, 2010 17:59 by author Louis

I think almost everybody had the “pleasure” to extract information out of text files. The content may be Logs, Debug outputs or from any other source.

Lately I was asked task to analyze our codebase for some given keywords. I did it by downloading all sources to my local disk, and did a somewhat naive search method using Visual Studio “Find In Files”  (Shortcut is Shift+Ctrl+F).

image 

Visual Studio offers the handy “Find In Files” option. You can specify to look in custom folder collections:

image

After selecting your folders you can start searching. 

In Visual Studio’s output window you see the search results. Copy and paste it into your favorite text editor (I’m, using Notepad++) and save it to disk.

The next step is to extract the information you need from this rather raw txt.

Fire up LinqPad. I suggest you download the latest version for .NET Framework 4.0.

To read in your file use the ReadLines() method which comes with framework 4.0. ReadLines gives you an IEnumerable<string> and yields the results. This means processing large datasets is possible, because only the current element is used. A good article by Paul Jacksonville can be found here.

My goal was to get all Files and the number of places my keyword was found.

So let’s look at how to read in Visual Studios “Find In Files” output:

The format is as follows:

FilePath(LineNumber):Contens

I’m using a regular expression to extract File and Line into an anonymous type:

var filesAndLines = File.ReadLines("c:\\temp\\SearchResults.txt")
                    .Where(x => Regex.IsMatch(x,@"(.+)\([1-9]+\)"))
                    .Select(y => new {  File= Regex.Match(y,@"(.+)\([1-9]+\)").Groups[1].Value, 
                                        Line=Regex.Match(y,@"(.+)\(([1-9]+)\)").Groups[2].Value});

Having this structure, it’s an easy step to group it:
filesAndLines.GroupBy(x => x.File)
              .Select(y=> new {File = y.Key, Count = y.Count()})
              .Dump();
 

That’s it. Hit F5 and see what the beautiful little Dump() – Extension from LinqPad produce:

image

The best thing is, you can easily export it to Excel or Word!

Fazit: LinqPad is a handy and versatile tool. I’m using it not only to understand LINQ better, but even for little tasks as shown here.



Rhino-Queues on Devices

clock July 28, 2010 10:44 by author Louis

I spend some time trying out Rhino-Queues (RQ) and Rhino-ServiceBus. I’m convinced of the potential of these projects, that I’ll add both to my stack of tools for my next projects. It’s so easy to embed Rhino-Queues in your own application without the need to install additional components on the machine. So you have a queuing system out-of-the-box.

At the moment I’m working with Windows CE Devices. I want to implement some features, which could be easily added with a queuing infrastructure at hand. So the next step would be to let our devices talk to the servers through a queue. Preferably to a Rhino-Queue instance ;)

A first look into the source of Rhino-Queues revealed, that there a some dependencies on components, that are not available in the Compact Framework.

Rhino-Queues uses ESENT to reliable store messages. Transactions are managed through System.Transactions. ESENT and System.Transactions are not available in the CF!

My first thought was to just exchange the storage backend, but it is not easily  exchangeable and does not expose a common interface.

After a little spike of RQ as a Smart Device Project targeting Windows CE 5.0 and the CF 3.5 I saw some other pitfalls. Especially around the System.Threading namespace.

My plan for the near future is to make a Rhino-Queues compatible client for the Compact Framework. The storage backend will probably be a Sqlite database.



Solved the Visual Studio code generation issue

clock May 5, 2009 11:53 by author Louis

Yesterday I wrote about an issue with a Visual Studio 2005 Smart Device projects, which were moved to Visual Studio 2008.

Since creating a new project of that type in VS 2008 creates properties instead of public fields there have to be differences in the project description (*.vbproj for a vb.net project). To look for differences I like WinMerge most. So I launched it and compared a fresh VS2008 project file to the upgraded one.

There were many differences in both file. Because comparing both files alone did not help, I investigated a bit in how the code was generated. One evidence was the comment 'This source code was auto-generated by Microsoft.CompactFramework.Design.Data, Version 2.0.50727.3053.'

Visual Studio uses this dll (located in %programfiles%\Microsoft Visual Studio 9.0\common7\ide) to generate the proxy code. There is almost no info available on this assembly, therefore I had to start my favorite toy: Red Gate's Reflector.

The class DeviceDiscoCodeGenerator is responsible for generating the code using standard CodeDom techniques. In CodeDom you can specify CodeGenerationOptions as flags to specify how primitive types are represented (as fields or as properties). The flag I was looking for is GenerateProperies. And indeed, this flag is set in GenerateCode method guarded by an if statement. The if statement evaluates a build property ("FileUpgradeFlags"). Looking back in the project file (*.vbproj), there was an empty FileUpgradeFlags tag:

<FileUpgradeFlags>
    </FileUpgradeFlags>

To set the flag I had to remove this entry. After doing a "Update Webreference" in Visual Studio, CodeDom generated the properties as expected!



Different code generation using upgraded Smart Device Project in Visual Studio 2008

clock May 4, 2009 18:19 by author Louis

We moved our smart device project from Visual Studio 2005 (VS2005) to Visual Studio 2008 (VS2008).

Everything worked after the upgrade except one odd thing: We have a ComboBox, which datasource is bound to a collection which type is provided by a webservice. The client side code to access the webservice was generated using the "Add Webreference" feature. If we start our application, the ComboBox is filled with the correct number of items provided by the datasource property, but every item shows only the name of the class (default ToString() behavior) and not the value, we provided in the DisplayMember property.

After some debugging, I found out, that setting the DisplayMember of the ComboBox has no effect. Retrieving the DisplayMember property gave us a nothing/null value. The reason for this was the designer generated code, which can be found in the Reference.vb file.

image

All properties which we had in the file turned into public fields! We had no compile time errors, but at runtime we now tried to set the DisplayMember of our ComboBox to a public field, instead of a public property. I'm not sure if it is working on a Windows Application if you set the DisplayMember to a public field, but on the Compact Framework it is not working!

The curious thing is, that if you create a new Project in VS2008 and add the same webservice as a reference, all the properties are generated as expected.

I have no solution to this problem yet, but it's a serious issue, if you have to move a lot of VS2005 projects to VS2008 and update the Webreferences because there are no compile-time warnings or errors.

There is a workaround. Use wsdl.exe to generate your client-side stubs and then edit unsupported code as mentioned on msdn.

I'll updated this post as soon as we have a solution for that problem.

Update: Solved this issue. See here.



Team Foundation Server Search in Code (VB.net)

clock April 30, 2009 23:49 by author Louis

The company I’m currently working for has about 100 developers, who are committing their code to SourceSafe.

Since Visual SourceSafe (VSS) has some serious issues and is far away from bein state-of-the-art the company is now in process of testing Team Foundation Server (TFS). Our team is the test team and we have moved our source (without history) to TFS.  

After some days of using the system, we were looking for the feature “Find in Files”, which was used quite often in the VSS era. We installed the TFS Powertoys which gave us a “Wildcard Search”. At first sight this feature looks like the good old VSS “Search in Files” but in fact this option searches only in filenames. After some googling I found this StackOverflow post of some other guy, who was looking for this feature.

For me it’s unbelievable to ship such a big product without basic functionality like “Search in Files”.

There are some answers which pointed me to a cool project: CS2Search.

CS2Search lets you index your code and search with some neat queries like

interface:IFooBar

Obviously this will give you all IFooBar interfaces in your indexed repository.

CS2Search uses Lucene.net to index the code.  Since Lucene.net uses files as input, you have to setup a scheduled task or some triggers/notifications to get the latest code out of the Source Control System.

I really like the CS2Search idea.  But It’s a pity for us, that there is no VB.net parser available out of the box, since the company develops in VB.net. But as simoneb said in this blogpost, it is possible to integrate your own parser through Windsor IoC.

Building a parser is a nice exercise and thanks to Microsoft and it’s missing search-feature in TFS I will dig around in this topic soon.



Setting up my blog environment

clock April 29, 2009 17:14 by author Louis

This will be my first blog entry on my new stuff-for-geeks.com site.

I decided to talk more about my daily life as a consultant and developer in the .net scene.

So here is my little HowTo:

1. Get a decend machine for your site

2. Choose a domain name

3. Choose a blog engine

4. Install and configure the site

5. Install the blog engine

 

Step one:

My choice was a root server with Windows 2008 Web as os.  You can get one with great support at strato.com. The machine was up and running in a few hours. 

Step two:

To start my blog, I needed a pretty domain name. I dug around my parked domains and found stuff-for-geeks.com! I bought this domain back in 2004. The idea was to sell geeky items like the good old IBM Clicky Keyboard. (Well that business was not running very well, but the silver lining was that I'm now proud owner of some rare vintage keyboards...)

Step three:

The Blogengine.

Some days ago the Visual Studio start page pointed me to the MIX 09 Keynote Video. Scott Guthrie introduced the Web Platform. You can get the Web Platform Installer (WPI) here. This little tool makes it really easy to install apps and developer tools on you server or workstation. Included are different Blogenginges. After some googling for the different pieces my decision was to use blogEngine.net.

Step four:

Site Installation

Installation of a site is very easy with the IIS 7 Manager. So I added a new blank site, and told IIS to listen for Host Headerslike stuff-for-geeks.com.

Step five:

Last not least by installing the blogengine was very easy. Just click install in the WPI and choose which site you want your app to be in. That's it. WPI is not just copying the contents to your directory, it configures security settings (BlogEnginge.net needs write access to the AppData Folder) you, so that after the installation you have a ready to go app on your machine!

 



About Louis

Hi, my name is Louis Haußknecht. I'm a freenlancing developer in .net and open source technology.

 

  XING

 

Subscribe in a reader

RecentComments

Comment RSS

Sign in