Adding NETWORKSERVICE as a dbo user in SQL Server

If you want to enable integrated security in your SQL Server connection string, and don’t want to have to update your App Pool with a username across different machines you can simply add ‘NT AUTHORITY\NETWORK SERVICE’ as a dbo for the database you’re querying.

Obviously this isn’t recommended for production use, and shouldn’t really be used in larger teams or multi-environments (staging, live-staging, live) setups.

Roadkill reaches the magical 1000 unit test mark

Warning: this post contains large amounts of pro-automated-testing propaganda.

Roadkill is now up to over 1000 tests (around 1150) as it gets near the version 2 release coming in 2014. Around three hundred of these come from the Markdown parser that Jeff Atwood wrote, and the HTML sanitizing toolkit, but the others have all accumulated over the past year including a lot of retro-fitted tests which were written to aid refactors. The test coverage is now around the 75% mark according to Jetbrain’s DotCover tool:

coverage

Continue reading

Using the this keyword with Typescript and a jQuery function

When you write Typescript, you’re forced by the compiler to use the “this” keyword when you want to access member variables or methods. If they’re static, you’re forced to use the name of the class (as you usually would in C#, although it’s syntactical).

This can cause problems when you bind jQuery button clicks to your own methods, and want to access member variables inside that method, as you are now inside the scope of the jQuery event and no longer your class. It’s one of the great ‘features’ of Javascript that the C# team overcame quite easily with lambdas, and in standard Javascript you usually overcome it by referencing the class instance in a variable named “that”, if you’re use Douglas Crockford’s pattern.

Continue reading

Anti-XSS .NET libraries in 2013

One of the more important parts in Roadkill Wiki is removing malicious HTML from the markup that’s entered, even when the markup (Creole and Markdown) is controlled.

The markup you enter is converted into HTML, and then sanitized internally to remove any HTML that is bad, the markup can also contain HTML itself – the Creole parser allows this as does the Markdown parser to an extent.

Malicious HTML usually comes in the form of XSS (Cross Site Scripting) attacks but can also be more innocuous but annoying things like showing Javascript alert() messages on the page or doing a Myspace style butchering of the stylesheets on the page.

For the most part Roadkill Wiki doesn’t need this level of sophistication in its text parsing,
Continue reading

Measuring the quality of code in Roadkill

One of the subjects I recently studied in my part time university course was how to measure a software system’s complexity, including quality measures for your code. These are statistical ways of measuring code or system complexity date back to before the SOLID principles became popular and with a little bit of insight give a fairly good marker of how complicated or clean your code is.

With Roadkill almost 3 years old, I thought I’d give some of the metrics a try on the source. There’s basically two ways of measuring system complexity: before you start the project and after/during the project.

Continue reading

Syncing Github with Codeplex

Assuming you have used the Github Windows gui (or the console) to clone a Github repository, you can push it up to Codeplex in the console by using something like this:

git push --all https://git01.codeplex.com/roadkill

I use this Mercurial plugin on an Ubuntu box to synchronise my Bitbucket Mercurial repository onto Github. It’s a crazy setup to have 3 repositories, but this comes from the problem that Bitbucket gets very little exposure to the .NET community while Codeplex is used heavily. Git is probably a close second behind Codeplex for exposure but I still prefer Mercurial to Git, at least for the 1-man Roadkill project.

Why not sync Bitbucket with a Codeplex mercurial repository? The Codeplex Mercurial support is terrible by their own admission, and pushing any large changes simply times out, so I have to jump through these hoops to sync everything up.

Introduction to Genetic Algorithms in C#

Get the code

A long time ago I mentioned in this post that I was planning on writing up some notes I made at university about Genetic Algorithms (from now on, known as GAs) and my version of a very simple example in C#. Years later…here it is! C# isn’t the most popular choice for artificial or natural intelligence programming, that job is largely the domain of Java or other more academic friendly languages. This means there aren’t a great deal of C# examples out there for neural networks, search and genetic algorithms and programming.

Continue reading

Installing MVC3 on Mono with Ubuntu

I managed to get the wiki engine I spend a lot of more spare time writing, Roadkill working on Ubuntu with Mono this weekend. Unfortunately for me, a lot of the documentation is patchy which meant it took a few hours to get it up and running by scouring Stackoverflow, blogs and news groups. It is infact very simple to get MVC3 working with Apache on Linux, provided you have the right Apache config settings and are willing to add a few hacks into your code to cater for the gaps (NotImplementedExceptions) in the Mono framework.

Below are two snippets for getting Mono and MVC3 going with Ubuntu. The majority of the credit goes to:

Continue reading

How to Write a Spelling Corrector in C#

Peter Norvig’s spelling corrector is fairly famous in nerd-circles as it describes the first steps in creating a Google-style spelling corrector that will take something like “Speling”, recognise its closest word and reply “Did you mean Spelling?”.

His original is a few years old now, and only 21 lines of compact Python. Below is my attempt to convert it to C#. There are already some links to C# conversions on Peter Norvig’s page, however I wanted one that was closer to C# and didn’t rely on a 3rd party library for collection helpers, as Frederic Torres’s does. The other C# version was a 404 last time I looked.

Continue reading

Moving away from NHibernate in Roadkill

In the next version of Roadkill (1.6) I’ve moved away from NHibernate, the ORM that has been powering it for two years since version 1 and to a commercially supported ORM called Lightspeed.

Unlike the Umbraco drama that emerged last year this wasn’t for performance reasons or a badly engineered business layer. I give myself a big pat on back infact, as it was really simple to switch firstly to a Mongodb repository and then over to Lightspeed. Nor was it from lack of NH experience as I’ve used NH day to day for 3 or so years.

Continue reading

Creating an instance from a string or type name in StructureMap

As part of the refactor I’m doing for Roadkill, I’m loading custom types from the config file as default instances, via StructureMap. The types are defined as strings in the config file, and in future more plugins will be loaded this way.

This took me around 4 hours to figure out over the past few days, partly from lots of false leads out there but also missing the blindingly object ObjectFactory.Model property. The way you can achieve it is fairly straightforward in 2.5+. I have a base UserManager type, and a concrete type that implements it.

ObjectFactory.Initialize(x =>
{
	x.Scan(scanner =>
	{
		scanner.TheCallingAssembly();
		scanner.SingleImplementationsOfInterface();
		scanner.WithDefaultConventions();

		// Plugin UserManagers
		if (Directory.Exists(pluginPath))
			scanner.AssembliesFromPath(pluginPath);
		
		// etc.
	}
});
ObjectFactory.Configure(x =>
{
	string pluginName = "Roadkill.SomePlugin.MyCustomUserManager";
	InstanceRef userManagerRef = ObjectFactory.Model.InstancesOf<UserManager>().FirstOrDefault(t => t.ConcreteType.FullName == pluginName);
	x.For<UserManager>().HybridHttpOrThreadLocalScoped().TheDefault.Is.OfConcreteType(userManagerRef.ConcreteType);
});

Three things worth noting if you want to do this:

  1. You want to get the InstancesOf and not instances – you don’t want it create an instance of you plugin type before everything else is registered.
  2. You may need to perform this inside Configure(), as Initialize scans for types.
  3. An obsolete message shows for TheDefault.Is.OfConcreteType but the method it tells you to use doesn’t work with a Type

The full implementation is on Bitbucket Roadkill repository under

Roadkill / src / Roadkill.Core / IoC / IocSetup.cs

Moqs versus Stubs (2013 edition)

This is an age old debate which I’ll chirp in with my opinion. According to Gojko Adzic there’s two types of TDD people in the world: classic stubbers and the new(ish)-school Moqers (or Mockito in the Java world). MOQ is an amazing tool, but consider the following test code:

_mockRepository = new Mock();
_mockRepository.Setup(x => x.GetPageById(It.IsAny<int>())).Returns<int>(x => _pageList.FirstOrDefault(p => p.Id == x));
_mockRepository.Setup(x => x.FindPagesContainingTag(It.IsAny<string>())).Returns<string>(x => _pageList.Where(p => p.Tags.ToLower().Contains(x.ToLower())));

Eeek. Is that easy to read? Does FindPagesContainingTag return a string? No, an IEnumerable of Page objects. Compare this to a stub implementation (the classical way of mocking) of the IRepository:

public class RepositoryStub : IRepository
{
    public IEnumerable<Page>FindPagesContainingTag(string tag)
    {
        return _pageList.Where(p => p.Tags.ToLower().Contains(tag.Tolower()));
    }
}

The other problem I have with the Moq example is you essentially have the stub class’s source in your [Setup] method most of the time. The advice Bob Martin gives for tests is they’re meant to be very easy to read for the next author, there should be no confusion at all. It’s fairly clear Moq doesn’t promote this, or at least not the messy way I write the mocks. So I’m probably in the classical camp, but is there no half-way house for the two in .NET?

From Squarespace to WordPress

The site is now powered by WordPress, having tried it out a few years ago and rejected it, I’ve come to like it and its plugin architecture – it’s fairly slick now and supports everything I needed. It has a wealth of themes which Squarespace doesn’t have, far more flexible and about the same price.

The move was frustrating, as Squarespace exports its content in Typepad format, a terrible non-structured export format which meant I lost all the formatting of the snippets. I ended up having to reformat all 130 or so blog post snippets (around 200 chunks of C#/XML blocks in total) putting the majority of them on Github which retains the formatting.

I also moved away from Disqus at the same time, to keep the comments in one place. So, stick to WordPress for code blogs would be my advice to any other dev thinking of starting up a repository of snippets and code snippets.

Fixing “No response from server for url http://localhost:7055/hub/session/” problems with Selenium

If you’re using a Windows Server 2008 R2 for your CI builds and tests, you may run into issues with running Selenium tests that Server 2003 didn’t have. It took me a good 1/2 day of trial and error to fix the problem, but it’s so obscure I thought I’d share. The error you’ll see from Selenium is usually this one:

“No response from server for url http://localhost:7055/hub/session/…”

Continue reading