Conquering NServiceBus part 1 – Getting Started

by Mikael Henriksson 8. February 2010 21:37

This post is part of a series:

  1. Conquering NServiceBus part 1 – Getting Started

Before we get started with coding there are a whole new language with terminology to learn so let’s start there.

  • Enterprise Service Bushttp://en.wikipedia.org/wiki/Enterprise_service_bus
  • NServiceBus  – What you use to build an ESB
  • MSMQ – Microsoft Message Queuing used by NServiceBus as transport system
  • (IoC) Container – used to inject dependencies when needed. You get to chose your favorite one to work with (mine is StructureMap)
  • Unicast Bus – The messaging system that NServiceBus ships with. (Currently the only one that works to my knowledge).
  • Serializationhttp://en.wikipedia.org/wiki/Serialization  XmlSerialization based on interfaces preferred for performance. NServiceBus ships with BinarySerialization and XmlSerialization. You can also easily create your own Serializer and use.
  • Subscription – NServiceBus makes publish/subscribe extremely easy. You can tell your message handler to subscribe to a certain type of message.
  • Message Handler – The actual handler of a given message (implementation detail goes inside the handle method)
  • Endpoint Config – The programmatic way of initializing a “bus”.
  • Saga – Long running process with the need for temporary storage before the final result can be processed.
  • Profile – When installing your service you can explicitly tell it to handle only a certain profile which is good if you have multiple environments and want different settings on different machines.

Let’s start from the beginning. I know from start I have a long running process where the client will be generating a lot of hits on a WCF REST service. The exchange will not be data heavy but it will be many requests at a time. That’s why I want to use NServiceBus and the Saga functionality. I also want to invalidate the saga after a given time, something that is supported by the Saga. When the saga completes I want to do expensive (time consuming) work and there for I don’t want the saga to do this which means I need to pass the whole thing on to another sort of service with main purpose of doing this heavy work. That means I can focus on threading and what not in one place only should I ever need to and it will also be extremely easy to measure performance of the various parts of the system and at the same time it will allow me to scale out pretty easily.

Question is, where do I start? Some of you might consider starting with writing tests. Myself I have no idea what kind of tests to write yet or how the application should be created. All I can do now is to try and get the high-level parts of me brain to cooperate with the low-level parts.

Tags:

NServiceBus

Collection all constant values of a class hierarchy using reflection

by Mikael Henriksson 6. February 2010 16:43

I sometimes have to test outgoing messages before we send them out. Since we work in the mobile industry we need to communicate with mobile phones and alas most countries have legal requirements that we much abide to. Because of some Swedish and Norwegian characters like “åäö” message length etc varies. So before we change any messages in production everyone get’s to have a say on the message. To do this I have created a simple unit test where I send the SMS to everyone. though there are quite a few places where this is done and I got bored with copy pasting the numbers or using them one and one to concatenate them so I decided to use reflection for this instead.

 

public class Numbers
{
	public const string EmployeeOne = "xxxxxxxxxx";
	public const string EmployeeTwo = "xxxxxxxxxx";
	public const string EmployeeThree = "xxxxxxxxxx";
	public const string EmployeeFour = "xxxxxxxxxx";
	public const string EmployeeFive = "xxxxxxxxxx";
	public const string EmployeeSix = "xxxxxxxxxx";
	public const string EmployeeSeven = "xxxxxxxxxx";
	public const string EmployeeEight = "xxxxxxxxxx";
	public const string EmployeeNine = "xxxxxxxxxx";
	public const string EmployeeTen = "xxxxxxxxxx";
	public const string EmployeeEleven = "xxxxxxxxxx";
	public const string EmployeeTwelve = "xxxxxxxxxx";
}

 

Wow a class of constants… how beautiful! ;) Well they have their place and this is the place for a class of constants.

Instead of manually handling all the numbers when I need them all is to make good use of reflection. Most reflection starts with a type somehow and in this case we are looking for fields that are public, static and flatten hierarchy means that inherited classes protected and public constants should be searched as well.

We want the Literal (compiled values) and they should not be init (initialized using constructor only).

private const BindingFlags Flags = BindingFlags.Public | 
            BindingFlags.Static | BindingFlags.FlattenHierarchy;

public IEnumerable<string> GetAllNumbers(Type type)
{
	FieldInfo[] fieldInfos = type.GetFields(Flags);
	return fieldInfos.Where(fi => fi.IsLiteral && !fi.IsInitOnly)
		.Select(fi => fi.GetValue(null).ToString());
}

If I wanted to create a tool / library around this I would probably wrap the above method with some generic.

public IEnumerable<string> GetAllNumbers<T>()
{
	return GetAllNumbers(typeof (T));
}

Tags: ,

C# | Reflection

Logging WCF messages generically

by Mikael Henriksson 6. February 2010 15:43

I recently felt the need to log incoming and outgoing messages from WCF without cluttering my operation contract implementations. I believe that this type of “debug” logging in the early stages of a project should if possible be done generically and externally. First of all I started out with following Andreas Öhlund’s post about how to setup WCFusing StructureMap. With this as a ground to stand on it wasn’t too much problem adding the logging part. To begin with I have a “MessageBase” that all my messages inherit from. Any message that inherits from this class does automatically use override ToString() from it’s base class. ToString just used the Serialize method to get a valid xml document. I have a certain logger for this so that I can turn it on and off easily for debugging purposes. Since this is the entry point towards the clients and this communication cant be durable (more info here)  though the rest of the backend is this is a great resource for tracking down potential future problems and something I need myself during integration tests. Anyway enough of the small talk. Let’s get down to business.

 

public interface IMessageBase<T> where T : class
{
    String Serialize(T data);
    T Deserialize(string text);
}

public abstract class MessageBase<T> : IMessageBase<T> 
	where T : class
{
	public String Serialize(T data)
	{
		using (var stringWriter = new StringWriter())
		{
			var settings = new XmlWriterSettings
						   {
							   Encoding = Encoding.UTF8,
							   OmitXmlDeclaration = true
						   };
			using 
			(var writer = XmlWriter.Create(stringWriter, settings))
			{
				var xmlSerializer = new XmlSerializer(typeof (T));
				xmlSerializer.Serialize(writer, data);
			}

			return stringWriter.ToString();
		}
	}

	public T Deserialize(string text)
	{
		T data;

		var settings = new XmlReaderSettings
						   {
							   IgnoreWhitespace = true
						   };

		using (var reader = XmlReader.Create(
			new MemoryStream(
				Encoding.UTF8.GetBytes(text)), 
				settings))
		{
			var xmlSerializer = new XmlSerializer(typeof (T));
			data = (T) xmlSerializer.Deserialize(reader);
		}

		return data;
	}

	public override string ToString()
	{
		return Serialize(this as T);
	}
}

 

Since I already have a UnitOfWorkMessageInspector (thank you Andreas) adding another one for the logging is not a hard thing to do.

Let’s start with the MessageInspector, just like with the UoW one Andreas created we implement the interface IDispatchMessageInspector.

public class LoggingMessageInspector : IDispatchMessageInspector
{
	public object AfterReceiveRequest(ref Message request,
		IClientChannel channel,
		InstanceContext instanceContext)
	{
		LogMessage(ref request);

		return null;
	}

	public void BeforeSendReply(ref Message reply, 
		object correlationState)
	{
		LogMessage(ref reply);
	}

	private void LogMessage(ref Message message)
	{
		LogManager.GetLogger("Messages").Debug(message.ToString());
	}
}

Dead easy right? I have two concerns now:

  1. I have no idea why message.ToString() gives me the actual xml string because Message is a WCF class. I suppose it wraps my MessageBase implementation and use that ToString() I actually didn’t check this yet.
  2. This works very well for messages BUT I have a few scenarios when the message is a Stream and in these cases only …. Stream …. is logged to the text file.

To wire this up in StructureMap is not a big problem. What we need to do now is to replace “Use” (which sets the default instance to use) to “Add“ which adds instances to use in the order they are added to StructureMap.

For<IDispatchMessageInspector>()
	.AddInstances(x =>
			{
				x.Type(typeof (LoggingMessageInspector));
				x.Type(typeof (UnitOfWorkMessageInspector));
			});

It’s not complete yet as I mentioned I need to figure out how to log the stream parameter.

Tags:

WCF

Unit testing private methods

by Mikael Henriksson 8. January 2010 12:54

Sometimes I can’t be bothered about testing the whole shebang. I just want to test what really counts without having to go through mocking external calls just to verify that something returns true.

This is probably not how one should test code but what the helicopter it works.

[Test]
public void Testing_a_private_method()
{
    BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Instance;
    var instance = new SomeInstance();
    Type type = typeof(SomeInstance);
    var para = new SomeParameterClass()
    para.SomeProperty1 = 2;
    para.SomeProperty2 = 1;
    var parameters = new object[] { para };

    MethodInfo method = type.GetMethod("InstanceMethodName", Flags);
    object obj = method.Invoke(instance, parameters);
    Assert.AreEqual(true, Convert.ToBoolean(obj));
}

EDIT: Inspired by Jan Van Ryswyck I decided to add a much cleaner way of doing this using Func<TInput, TOutput>. I recommend you read his post.

[Test]
public void Testing_a_private_method()
{
    var instance = new SomeInstance();
    var para = new SomeParameterClass()
    para.SomeProperty1 = 2;
    para.SomeProperty2 = 1;
    
    var instanceMethodName = (Func<SomeParameterClass, bool>)
    Delegate.CreateDelegate(
		typeof(Func<SomeParameterClass, bool>), instance, "InstanceMethodName"
		);
    Assert.IsTrue(instanceMethodName(para), "This should really return true");
}

Like Jan mentions it does only work for instance methods not static ones but you shouldn’t be creating too many static methods anyway :)

EDIT2: Also worth noting is that Func of course only works for methods that actually return something. If you need to check the values of something that should have been manipulated without the method returning the manipulated value we need to use another Delegate, say hello to Action!

[Test]
public void Testing_a_private_method()
{
    var instance = new SomeInstance();
    var para = new SomeParameterClass()
    para.SomeProperty1 = 2;
    para.SomeProperty2 = 1;
    
    var instanceMethodName = (Action<SomeParameterClass>)
    Delegate.CreateDelegate(
		typeof(Action<SomeParameterClass>), instance, "InstanceMethodName"
		);
    instanceMethodName(para);
    Assert.AreEqual(2, para.SomeProperty2, "Since we set SomeProperty2 to initial value 1 this will throw if it's not been set while InstanceMethodName executed!");
}

Tags:

Testing

An even better way of handling a singleton WURFL in asp.net

by Mikael Henriksson 4. January 2010 20:28

As soon as I find a new cool tool I try to find ways of using it. I have been using StructureMap for a while and love it. Certainly so now that some of the old crap get’s cleaned up for version 3.0 (big thanks to Jeremy for taking the time during holidays). Ideally since it’s a 13 MB file to hold in memory I prefer to have only one instance running and my attempt on a singleton sucked. Initially I did some locking and stuff but when running locally I often found myself running out of ram so it didn’t work and it was slow to initialize (startup time was around a minute). After refactoring “a little” and letting StructureMap handle the instance for me it starts up in less than a second which means I can have IIS refresh the application pool regularly (I find it best to do this when handling really big files in memory) and I am confident someone like Jeremy D Miller writes better code than I do (for now).

This example can of course be refined a lot. It consists of just a few classes. One data class used to hold the xml document, one loader class used to prepare the data we need from the xml document and one navigator class used to search in the data class and one class that implements the below interface and acts as a wrapper for the other two classes.

Could I have some code please?

 

public interface IDetection
{
  string UserAgent { get; set; }
  Handset GetAllInformation(string userAgent);
  string GetBrowserAndVersion();
  string GetCharSet();
  string GetContentType();
  string GetManufacturer();
  string GetModel();
  string GetPlatform();
  string GetScreenSize();
  string GetUAProfile();
  bool IsMobileDevice();
}

 

Note: The Handset class is just a value object used to temporarily hold information. 

The only reason this interface exists is because I want to separate patches from devices. The patches contains information about non-mobile devices like bots and computers and the implementing classes are pretty dumb so I’ll save you the read copy/paste on those.

public interface IDeviceData
{
  SortedList<string, IDictionary<string, string>> DevicesAndCapabilities { get; }
  IDictionary<string, string> DevicesAndFallback { get; }
  IDictionary<string, string> UserAgentsAndDevices { get; }
}	

Now comes one of the main classes I removed all patch loading from this one to save some space. It’s somewhat optimized and I at least like the size of the methods. Managed to get them down to a decent number of lines.

///<summary>
/// Holds mobile _wurfl information from the _wurfl.xml
///</summary>
public class DeviceDataLoader
{
    private const int AproximateNumberOfDevices = 600;
    private static readonly Stopwatch Sw = new Stopwatch();
    private bool _disposed;

    public DeviceDataLoader()
    {
        CapabilityNames = new ArrayList();
        DeviceData = new DeviceData(AproximateNumberOfDevices);
        Patches = new Patches(40);
        CompactAgents = new Dictionary<string, string>();
    }

    ///<summary>
    /// Returns true if the Wurfl document is loaded into memory
    ///</summary>
    public bool IsLoaded { get; private set; }
    public IDeviceData DeviceData { get; private set; }
    public IDeviceData Patches { get; private set; }
    public IDictionary<string, string> CompactAgents { get; set; }
    public ArrayList CapabilityNames { get; private set; }

    /// <exception cref="FileNotFoundException"><c>FileNotFoundException</c>.</exception>
    public IDeviceData Load(string xmlPath)
    {
        if (!File.Exists(xmlPath))
        {
            throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture,
                                                          "The wurfl database was not located in : {0}", xmlPath));
        }

        PrepareXmlDatabaseForusage(xmlPath);
        IsLoaded = true;
        return DeviceData;
    }

    private void PrepareXmlDatabaseForusage(string xmlPath)
    {
        try
        {
            if (!IsLoaded)
            {
                XDocument wurlf = XDocument.Load(xmlPath);
                GetMobileDevices(wurlf.Descendants());
                SetInitialCapabilities();
            }
        }
        catch (Exception ex)
        {
            LogManager.GetLogger("Providers").Error(ex);
        }
    }

    private void GetMobileDevices(IEnumerable<XElement> xElements)
    {
        foreach (XElement xElement in xElements)
        {
            if (xElement.Name == "device")
            {
                string deviceId = GetDeviceId(xElement);
                string userAgent = GetUserAgent(xElement);
                IDictionary<string, string> capabilities = GetCapabilities(xElement);

                AddMobileDevicesCapabilities(deviceId, userAgent, capabilities);
                AddMobileUserAgentsAndDeviceIds(deviceId, userAgent);
                AddMobileDevicesAndFallbacks(xElement, deviceId);

                capabilities.Clear();
            }
        }
    }

    private void GetPatchDevices(IEnumerable<XElement> xElements)
    {
        foreach (XElement xElement in xElements)
        {
            if (xElement.Name == "device")
            {
                string deviceId = GetDeviceId(xElement);
                string userAgent = GetUserAgent(xElement);
                IDictionary<string, string> capabilities = GetCapabilities(xElement);

                AddPatchDevicesCapabilities(deviceId, userAgent, capabilities);
                AddPatchUserAgentsAndDevices(deviceId, userAgent);
                AddPatchDevicesAndFallbacks(xElement, deviceId);

                capabilities.Clear();
            }
        }
    }

    private void AddMobileDevicesAndFallbacks(XElement xElement, string deviceId)
    {
        string value;
        if (!DeviceData.DevicesAndFallback.TryGetValue(deviceId, out value))
        {
            XAttribute x = xElement.Attribute("fall_back");
            if (x != null)
            {
                DeviceData.DevicesAndFallback.Add(deviceId, x.Value);
            }
        }
    }

    private void AddMobileUserAgentsAndDeviceIds(string deviceId, string userAgent)
    {
        string value;
        if (!DeviceData.UserAgentsAndDevices.TryGetValue(userAgent, out value))
        {
            DeviceData.UserAgentsAndDevices.Add(userAgent, deviceId);
        }
    }

    private void AddMobileDevicesCapabilities(string deviceId, string userAgent,
                                              IDictionary<string, string> capabilities)
    {
        string value;
        if (!string.IsNullOrEmpty(deviceId))
        {
            if (!string.IsNullOrEmpty(userAgent) && !DeviceData.DevicesAndCapabilities.ContainsKey(deviceId))
            {
                DeviceData.DevicesAndCapabilities.Add(deviceId, new Dictionary<string, string>(capabilities));
            }
        }
    }

    private static string GetDeviceId(XElement xElement)
    {
        string deviceId = string.Empty;
        if (xElement.Name == "device")
        {
            deviceId = xElement.GetAttributeValue("id");
        }

        return deviceId;
    }

    private static string GetUserAgent(XElement xElement)
    {
        string userAgent = xElement.GetAttributeValue("user_agent") ?? string.Empty;

        if (string.IsNullOrEmpty(userAgent))
        {
            userAgent = "generic";
        }
        return userAgent;
    }

    private static IDictionary<string, string> GetCapabilities(XContainer xElement)
    {
        IDictionary<string, string> capabilities = new Dictionary<string, string>();
        foreach (XElement groups in xElement.Descendants("group"))
        {
            foreach (XElement capability in groups.Descendants("capability"))
            {
                string value;
                if (!capabilities.TryGetValue(capability.GetAttributeValue("name"), out value))
                {
                    capabilities.Add(capability.GetAttributeValue("name"), capability.GetAttributeValue("value"));
                }
            }
        }

        return capabilities;
    }

    private void SetInitialCapabilities()
    {
        DeviceData.DevicesAndCapabilities.TrimExcess();
        IDictionary<string, string> tmp = DeviceData.DevicesAndCapabilities["generic"];
        foreach (string key in tmp.Keys)
        {
            CapabilityNames.Add(key);
        }
        CapabilityNames.Sort();
    }
}


Lastly I created a detection class implementing the first interface. This will be the one instance in the IoC container of choice (mine is StructureMap).  

 

public class WurflDetection : IDetection
{
    private DataNavigator _device;
    public IDeviceData DeviceData { get; private set; }
    private DeviceDataLoader _loader;

    public void Initialize(string pathToXml)
    {
        if (string.IsNullOrEmpty(pathToXml))
        {
            throw new FileNotFoundException("PathToXml :", PathToXml);
        }

        if (_loader == null)
        {
            _loader = new DeviceDataLoader();
        }

        if (!_loader.IsLoaded)
        {
            DeviceData = _loader.Load(PathToXml);
            _device = new DataNavigator(DeviceData.Devices, DeviceData.Patches, DeviceData.CapabilityNames);
        }
    }
}

 

So I add a StructureMap Registry like follows:

 

public class WurflRegistry : Registry
{
  public WurflRegistry()
  {
    IDetectionProvider provider = new DeviceProviderOne(HostingEnvironment.MapPath("/App_Data/wurfl.xml"));

      ForSingletonOf<IDetectionProvider>()
          .Use(provider);
  }
}


The really nice thing about the whole registry approach is that I don’t necessarily need any project or dll references other than to StructureMap I can let the tool scan the assemblies in the output directory for me which is sometimes the only solution visible solutions to some problems. 

 

Tags: ,

IoC | wurfl

How to create overly complex NHibernate queries?

by Mikael Henriksson 15. December 2009 16:06

If I had it my way we would probably have the whole darn thing in one and the same table but that would not work out long term. The problem I was facing was to fetch one entity based on values in the parent and 2 other (to the parent) related entities. Then I want to eagerly fetch information from the parent.

// Create criteria and add sorting based on version
var criteria = work.Session.CreateCriteria<ContactVersion>("v")
    .AddOrder(Order.Desc("v.Version"));

// Create restriction based on that the contact should:
// 1. Not be deleted and
// 2. Match the accountId
criteria.CreateCriteria("v.Contact", "c")
    .Add(Restrictions.IsNull("c.DeletedAt"))
    .Add(Restrictions.Eq("c.Id", accountId));

// Also add a restriction based on uid
criteria.CreateCriteria("c.Devices", "dc")
    .Add(Restrictions.Eq("dc.Id", uid));

// Lastly add a restriction for the current device id and
// eagerly fetch the corresponding contact.
criteria.CreateCriteria("dc.Device", "d")
    .Add(Restrictions.Eq("d.Id", deviceId))
    .SetFetchMode("c.Contact", FetchMode.Join)
    .SetFetchSize(1)
    .SetMaxResults(1);

var c = criteria.UniqueResult<ContactVersion>();

This gives me the desired result and the query looks like follows:

SELECT top 1 * /* removed all the columns */
FROM   contact_version this_
       inner join contact_def c1_
         on this_.contact_id = c1_.contact_id
       inner join contact_device_uid dc2_
         on c1_.contact_id = dc2_.contact_id
       inner join device_def d3_
         on dc2_.device_id = d3_.device_id
WHERE  this_.contact_version_ordinal = 3 /* @p0 */
       and c1_.dte_deleted is null
       and c1_.subscription_id = 4 /* @p1 */
       and dc2_.contact_uid = 1 /* @p2 */
       and d3_.device_id = 1 /* @p3 */

A quick look at the query execution plan shows nothing really strange so I suppose I sort of got it right. At least I got the data that I asked for..

Tags:

NHibernate

How to waste half a day getting R# to run unit tests…

by Mikael Henriksson 10. December 2009 14:11

Today I feel like the most retarded guy on planet earth. I have just wasted half a day trying to get R# to run my unit tests. The tests simply does not even start so they don’t fail either. 
A check of the output window shows that there is a possible chance of a FileNotFoundException which I thought was bullshit. I had a look at the settings for R# Unit Test and no there was nothing that I could do to make it work. Since I AM a smart guy usually (I am just feeling a bit stupid today) I decided to make all exceptions throw so that I could at least find some sort of trace or hint of where the problem actually occurs.

Ctrl+Alt+E takes you to the Visual Studio exceptions settings where I turn everything to throw and then I start debugging the unit tests. After a good few clicks some interesting exceptions shows up. It’s a FileNotFoundException and it looks like this:

System.IO.FileNotFoundException occurred
  Message="Could not load file or assembly 'file:///D:\\Apps\\NUnit 2.5.2\\bin\\net-2.0\\lib\\nunit.core.dll' or one of its dependencies. The system cannot find the file specified."
  Source="mscorlib"
  FileName="file:///D:\\Apps\\NUnit 2.5.2\\bin\\net-2.0\\lib\\nunit.core.dll"
  FusionLog="=== Pre-bind state information ===
  LOG: User = MOBILENORDIC\\mikael
  LOG: Where-ref bind. Location = D:\\Apps\\NUnit 2.5.2\\bin\\net-2.0\\lib\\nunit.core.dll
  LOG: Appbase = file:///D:/Projects/****.IntegrationTests/bin/Debug
  LOG: Initial PrivatePath = NULL
  Calling assembly : (Unknown).===
  LOG: This bind starts in LoadFrom load context.
  WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
  LOG: Using application configuration file: D:/Projects/****.IntegrationTests\\bin\\Debug\\*.IntegrationTests.dll.config
  LOG: Using machine configuration file from C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\config\\machine.config.
  LOG: Attempting download of new URL file:///D:/Apps/NUnit 2.5.2/bin/net-2.0/lib/nunit.core.dll."
  StackTrace:
       at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
       at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
       at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
       at System.Reflection.Assembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, StackCrawlMark& stackMark)
       at System.Reflection.Assembly.LoadFrom(String assemblyFile)
       at JetBrains.ReSharper.UnitTestProvider.nUnit.NUnitTaskRunner.ExecuteRecursive(TaskExecutionNode node) in c:\Agent\work\cc29ccea5bf569df\src\UnitTestProvider.nUnit\src\NUnitTaskRunner.cs:line 103
  InnerException: 

Well interesting, it turned out that it was actually me being stupid. I was positive this had nothing to do with R# but the level of retardness does not stop here! I go back to the R# settings and look for somewhere to change the path to nunit but can’t find anything so I rename my d:\apps\nunit folder to match the one I couldn’t find and try again and now my unit tests run perfectly. I decided the bloody thing had messed with me for the last time! Going back to the settings for Unit Tests in R# I am faced with the following picture:

resharper_unit_test_settings

Now where the heck is that darn setting??? I open up the resharper.user file in notepad2 and search for nunit and at the bottom I found this:

  <UnitTestRunnerNUnit>
    <NUnitInstallDir>D:\Apps\NUnit 2.5.2\bin\net-2.0</NUnitInstallDir>
    <UseAddins>Always</UseAddins>
    <UseSpecifiedNUnit>True</UseSpecifiedNUnit>
  </UnitTestRunnerNUnit>

Now I can change this to the folder where it is REALLY located and that is great when it hits me. I remember changing this in resharper for some stupid reason and I also remember that I did so within the Resharper Unit Test section of the options. While navigating back and clicking on nunit I am looking at the following picture:

resharper_nunit_settings

 

Either I am mentally retarded or that part of the ReSharper options is so pick your choice.

Tags: ,

Testing | FAIL | R#

Hosting WCF in IIS 7.0 / Windows 2008

by Mikael Henriksson 25. November 2009 11:57

If found this to be helpful

  1. Run an elevated command prompt
  2. Run the following command:
    "%windir%\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe" -r -y
  3. Last and also very important is the need for a base address, it seems IIS 7 does not figure this out by itself:
  4. <system.serviceModel>
    	<services>
    		<service name="RESTService.Service" 
    				 behaviorConfiguration="Default">
    			<host>
    				<baseAddresses>
    					<add baseAddress="http://localhost:80/" />
    				</baseAddresses>
    			</host>
    			<endpoint address="" 
    					  behaviorConfiguration="Default" 
    					  binding="webHttpBinding" 
    					  contract="RESTService.Service" />
    		</service>
    	</services>
    </system.serviceModel>

Just speficy the baseAddress and you should be good to go. Navigate to your svc file and you can start consuming it.

Tags:

WCF | Windows Server

NHibernate Profiler a real time-saver

by Mikael Henriksson 13. November 2009 01:34

It’s great for several reasons. I’ll try and cover some of them briefly

  1. It detects possible problems with your configuration / mappings and this is fantastic. You spot those N+1 and Unbounded result sets before someone complains about a crash or performance issues.
  2. It outputs the SQL in a very understandable and readable format. I never could stand watching the SQL Profiler.
  3. It tells you about internal NHibernate errors. I spent too much time opening management studio trying to see if things ended up in the database or not. If there is an error it’s likely I don’t have to bother.
  4. It tells you if a query was read from the cache or database. I had some implementation problems that cause my queries to always be fetched from the database without nh prof it would have taken me some time to figure out why.
  5. It is so easy to use. Add a reference to the Appender.dll and make sure you run Initialize() on the chosen profiler and your done.

Try it out http://nhprof.com/download

Tags:

NHibernate

What does Rob Conery have against strings?

by Mikael Henriksson 12. November 2009 17:08

Well I sort of get it can be a pain in the ass to have to deal with strings. But what if you also have to deal with VB.NET at the same time? I just have to show this nice little helper I have.

Public Function ConvertToDictionary(ByVal input As String) As IDictionary(Of String, String)
	Dim dic As New Dictionary(Of String, String)
	Dim pairsplitter As Char = Char.Parse("&")
	Dim keysplitter As Char = Char.Parse("=")
	Dim stringArray As String() = input.Split(pairsplitter)

	If (input.Length > 0) Then
		If (stringArray(0).Contains("?")) Then
			Dim tmp As String = stringArray(0)
			stringArray(0) = tmp.Remove(0, tmp.IndexOf("?") + 1)
		End If
	End If

	For Each keyvalpair As String In stringArray
		Dim keyarray As String() = keyvalpair.Split(keysplitter)
		dic.Add(keyarray(0), keyarray(1))
	Next

	Return dic
End Function

The fun part is when you have created your unit test and it succeeds. The boring part is revisiting such a bastard after a year trying to figure out what the hell you where doing there in the first place. Oh and to answer your question. The reason for all this is that sometimes the input stream contains the page.aspx? and sometimes it just starts with the key-value pairs and since I don’t want the page.aspx? as a key in the dictionary I remove it and replace whatever is in array(0) :) Fun times…

Tags:

vb.net

About the author

Life architect specialized in programming