<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tony Williams &#187; C#</title>
	<atom:link href="http://blog.tonywilliams.me.uk/tag/csharp/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.tonywilliams.me.uk</link>
	<description></description>
	<lastBuildDate>Tue, 10 Jan 2012 12:31:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>How I fixed FluentNHibernate.Cfg.FluentConfigurationException on MVC 3</title>
		<link>http://blog.tonywilliams.me.uk/how-i-fixed-fluentnhibernate-cfg-fluentconfigurationexception-on-mvc-3/</link>
		<comments>http://blog.tonywilliams.me.uk/how-i-fixed-fluentnhibernate-cfg-fluentconfigurationexception-on-mvc-3/#comments</comments>
		<pubDate>Wed, 19 Jan 2011 12:55:26 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Asp.Net MVC3]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[Exception]]></category>
		<category><![CDATA[FluentNHibernate]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Ninject]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=123</guid>
		<description><![CDATA[How I fixed the problem in the title.]]></description>
			<content:encoded><![CDATA[<p><strong><span style="text-decoration: underline;">Just to let you know this may not solve your version of this error (since it&#8217;s so vague) but it&#8217;s how I solved it in one of my projects.</span></strong></p>
<p>On a previous <a href="http://blog.tonywilliams.me.uk/nhibernate-leaking-connections-with-unitofwork-pattern-and-transactions/">post </a>I mention I was using NHibernate in one of the projects I&#8217;m working on and as such we&#8217;re using <a href="http://fluentnhibernate.org/">FluentNHibernate</a>.</p>
<p>I&#8217;ve created a class (let&#8217;s call it SessionManager) that handles creating the ISessionFactory instance (and stores it in a static field). The project is built with <a href="http://www.asp.net/mvc/mvc3">MVC 3</a> and makes use of the DI provider along with <a href="http://ninject.org/">Ninject</a> so this code snippet should look familiar. (It&#8217;s where you set up you DI &#8211; usually the AppStart_NinjectMVC3)</p>
<pre class="brush:c#">kernel.Bind&lt;ISessionFactory&gt;().ToConstant(SessionManager.CreateSessionFactory());</pre>
<p>That is the line the caused the problems; not sure how but the aspnet compiler dies. In the end I changed ninject to use &#8220;ToMethod&#8221; instead:</p>
<pre class="brush:c#">kernel.Bind&lt;ISessionFactory&gt;().ToMethod(c =&gt; SessionManager.CreateSessionFactory());</pre>
<p>Since the session manager handles creating the ISessionFactory like I mentioned earlier we don&#8217;t get multiple instances of ISessionFactory.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/how-i-fixed-fluentnhibernate-cfg-fluentconfigurationexception-on-mvc-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Asp.Net MVC 2 Routing SubDomains to Areas</title>
		<link>http://blog.tonywilliams.me.uk/asp-net-mvc-2-routing-subdomains-to-areas/</link>
		<comments>http://blog.tonywilliams.me.uk/asp-net-mvc-2-routing-subdomains-to-areas/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 15:10:51 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Areas]]></category>
		<category><![CDATA[Asp.Net MVC2]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Routing]]></category>
		<category><![CDATA[SubDomain]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=58</guid>
		<description><![CDATA[How to get the sub domains routing to areas in Asp.Net MVC 2]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been building an Asp.Net MVC 2 site with <a href="http://tomhowsam.com/">Tom</a> on the new <a href="http://www.thap.co.uk/">Thap </a>site and we hit a stumbling point regarding sub-domains and areas; you can probably guess what the problem was from the title.</p>
<p>Any way after a bit of googling it looks like no one has figured this out, or that they arn&#8217;t sharing. So it&#8217;s time I shared the solution that worked for us. This requires no libraries or esoteric settings or anything like that, just a little bit of code that will end up making your routes look like this:</p>
<pre class="brush:c#">context.Routes.MapSubDomainRoute(
        "Admin_default", // Name
        "admin", // SubDomain
        "{controller}/{action}/{id}", // Url
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Defaults
        new[] { typeof(Controllers.HomeController).Namespace }); // Namespace</pre>
<p>First we need to create a Route class that can handle subdomains, lucky for you I just happen to have one. What this class does is check the incoming request, if the sub-domain matches it then checks to see if the rest of the url matches the route you specified:</p>
<p><strong>Update: </strong>Since publishing this post I&#8217;ve added an update to the code. The <em>GetVirtualPath </em>function  has been overridden to check if the area of the value matches the sub-domain . This was needed because it messed up the url generation for everything.</p>
<pre class="brush:c#">namespace Your.App
{
  using System.Web;
  using System.Web.Routing;

  /// &lt;summary&gt;
  /// A route class to work with a specific subDomain
  /// &lt;/summary&gt;
  public class SubDomainRoute : Route
  {
    /// &lt;summary&gt;
    /// The subDomain to route against
    /// &lt;/summary&gt;
    private readonly string subDomain;

    /// &lt;summary&gt;
    /// Initializes a new instance of the &lt;see cref="SubDomainRoute"/&gt; class.
    /// &lt;/summary&gt;
    /// &lt;param name="subDomain"&gt;The sub domain.&lt;/param&gt;
    /// &lt;param name="url"&gt;The URL.&lt;/param&gt;
    /// &lt;param name="routeHandler"&gt;The route handler.&lt;/param&gt;
    public SubDomainRoute(string subDomain, string url, IRouteHandler routeHandler) : base(url, routeHandler)
    {
      this.subDomain = subDomain.ToLower();
    }

    /// &lt;summary&gt;
    /// Returns information about the requested route.
    /// &lt;/summary&gt;
    /// &lt;param name="httpContext"&gt;An object that encapsulates information about the HTTP request.&lt;/param&gt;
    /// &lt;returns&gt;
    /// An object that contains the values from the route definition.
    /// &lt;/returns&gt;
    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
      var url = httpContext.Request.Headers["HOST"];
      var index = url.IndexOf(".");

      if (index &lt; 0)
      {
        return null;
      }

      var possibleSubDomain = url.Substring(0, index).ToLower();

      if (possibleSubDomain == subDomain)
      {
        var result =  base.GetRouteData(httpContext);
        return result;
      }

      return null;
    }

    /// &lt;summary&gt;
    /// Returns information about the URL that is associated with the route.
    /// &lt;/summary&gt;
    /// &lt;param name="requestContext"&gt;An object that encapsulates information about the requested route.&lt;/param&gt;
    /// &lt;param name="values"&gt;An object that contains the parameters for a route.&lt;/param&gt;
    /// &lt;returns&gt;
    /// An object that contains information about the URL that is associated with the route.
    /// &lt;/returns&gt;
    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
      // Checks if the area to generate the route against is this same as the subdomain
      // If so we remove the area value so it won't be added to the URL as a query parameter
      if(values != null &amp;&amp; values.ContainsKey("Area"))
      {
        if(values["Area"].ToString().ToLower() == this.subDomain)
        {
          values.Remove("Area");
          return base.GetVirtualPath(requestContext, values);
        }
      }

      return null;
    }
  }
}</pre>
<p>The next step we take is to create a bunch of extensions methods to make mapping the sub-domain a bit easier. I lifted this code straight from the MVC source and made a tiny adjustment.</p>
<pre class="brush:c#">namespace Your.App
{
  using System;
  using System.Diagnostics.CodeAnalysis;
  using System.Web.Mvc;
  using System.Web.Routing;

  public static class RouteCollectionExtensions
  {
    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, null /* defaults */, (object)null /* constraints */);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, object defaults)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, defaults, (object)null /* constraints */);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, object defaults, object constraints)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, defaults, constraints, null /* namespaces */);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, string[] namespaces)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, null /* defaults */, null /* constraints */, namespaces);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, object defaults, string[] namespaces)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, defaults, null /* constraints */, namespaces);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, object defaults, object constraints, string[] namespaces)
    {
      if (routes == null)
      {
        throw new ArgumentNullException("routes");
      }
      if (url == null)
      {
        throw new ArgumentNullException("url");
      }
      if (subDomain == null)
      {
        throw new ArgumentNullException("subDomain");
      }

      Route route = new SubDomainRoute(subDomain, url, new MvcRouteHandler())
      {
        Defaults = new RouteValueDictionary(defaults),
        Constraints = new RouteValueDictionary(constraints)
      };

      if ((namespaces != null) &amp;&amp; (namespaces.Length &gt; 0))
      {
        route.DataTokens = new RouteValueDictionary();
        route.DataTokens["Namespaces"] = namespaces;
      }

      routes.Add(name, route);

      return route;
    }
  }
}</pre>
<p>The final thing to do is set up your routes in the AreaRegistration class</p>
<pre class="brush:c#">context.Routes.MapSubDomainRoute(
        "Admin_default", // Name
        "admin", // SubDomain
        "{controller}/{action}/{id}", // Url
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Defaults
        new[] { typeof(Controllers.HomeController).Namespace }); // Namespace</pre>
<p>Look familiar?</p>
<p>The namespace section is used to distinguish between Identically name controllers, so if you have a home controller in two areas that line will stop any conflicts.</p>
<p>There is one last item to take note of, when you create a new action in a controller of an area you&#8217;ll need to specify the location of the view. If your using the MvcContrib like we do then the T4MVC template comes in vary handy. All the Actions in the areas now look something like this:</p>
<pre class="brush:c#">    public virtual ActionResult Index()
        {
            return View(this.Views.Index);
        }</pre>
<p>Or if you&#8217;re not using the T4MVC then this:</p>
<pre class="brush:c#">    public virtual ActionResult Index()
        {
            return View("~/Areas/Admin/Views/Home/Index.aspx");
        }</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/asp-net-mvc-2-routing-subdomains-to-areas/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Find the transparent pixels in an image &#8211; WPF</title>
		<link>http://blog.tonywilliams.me.uk/find-the-transparent-pixels-in-an-image-wpf/</link>
		<comments>http://blog.tonywilliams.me.uk/find-the-transparent-pixels-in-an-image-wpf/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 14:12:31 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Image Processing]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[WPF 4]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=51</guid>
		<description><![CDATA[Same as the title]]></description>
			<content:encoded><![CDATA[<p>Extracted from: <a href="http://random.tonywilliams.me.uk/post/392778744/find-the-transparent-pixels-in-an-image-wpf">http://random.tonywilliams.me.uk/post/392778744/find-the-transparent-pixels-in-an-image-wpf</a></p>
<div>
<div>
<p>The other day I had to create an image element that contained a png with transparent sections and have it display a hand cursor when the mouse was over the opaque sections.</p>
<p>The first thing I tried (and failed) was to have an image element with the cursor property set to &#8220;Hand&#8221; like so:</p>
<pre class="brush:html">
&lt;Image Source="{Binding SomeImage}" Cursor="Hand" /&gt;
</pre>
<p>That obviously never worked so I was forced to look at each individual pixel and see if it was transparent. What I ended up with was a function that generated a bunch of coordinates.</p>
<p>This is that function:</p>
<pre class="brush:c#">private static Dictionary&lt;Point, object&gt; FindTransparentPixelCoordinates(BitmapSource source)
{
  var points = new Dictionary&lt;Point, object&gt;();

  // Convert the source if the pixel format is not what we expect
  if (source.Format != PixelFormats.Bgra32)
  {
    source = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0);
  }

  int width = source.PixelWidth;
  int height = source.PixelHeight;
  var bytes = new byte[width * height * 4];

  source.CopyPixels(bytes, width * 4, 0);

  var position = 0;

  for (var y = 0; y &lt; height; y++)
  {
    for (var x = 0; x &lt; width; x++)
    {
      var byteOffset = position;

      // The pixel format is stored as 32-bits (4 bytes) with the last byte being the alpha

      if (bytes[byteOffset + 3] == 0)
      {
        points.Add(new Point(x, y), null);
      }

      position += 4;
    }
  }

  return points;
}</pre>
</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/find-the-transparent-pixels-in-an-image-wpf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Serialising / Deserialising objects to Xml in .Net</title>
		<link>http://blog.tonywilliams.me.uk/serialising-deserialising-objects-to-xml-in-net/</link>
		<comments>http://blog.tonywilliams.me.uk/serialising-deserialising-objects-to-xml-in-net/#comments</comments>
		<pubDate>Mon, 12 Jul 2010 08:26:14 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[Serialisation]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=34</guid>
		<description><![CDATA[Extension method for serialisation of classes to xml]]></description>
			<content:encoded><![CDATA[<p>Serialising / Deserialising objects to Xml: from my <a href="http://stackoverflow.com/questions/271398/what-are-your-favorite-extension-methods-for-c-codeplex-com-extensionoverflow/271423#271423">StackOverFlow</a></p>
<pre class="brush:c#">private static readonly Dictionary&lt;Type, XmlSerializer&gt; serialisers = new Dictionary&lt;Type, XmlSerializer&gt;();

/// &lt;summary&gt;Serialises an object of type T in to an xml string&lt;/summary&gt;
/// &lt;typeparam name="T"&gt;Any class type&lt;/typeparam&gt;
/// &lt;param name="objectToSerialise"&gt;Object to serialise&lt;/param&gt;
/// &lt;returns&gt;A string that represents Xml, empty oterwise&lt;/returns&gt;
public static string XmlSerialise&lt;T&gt;(this T objectToSerialise) where T : class, new()
{
  XmlSerializer serialiser;

  var type = typeof(T);
  if (!serialisers.ContainsKey(type))
  {
    serialiser = new XmlSerializer(type);
    serialisers.Add(type, serialiser);
  }
  else
  {
    serialiser = serialisers[type];
  }

  string xml;
  using (var writer = new StringWriter())
  {
    serialiser.Serialize(writer, objectToSerialise);
    xml = writer.ToString();
  }

  return xml;
}

/// &lt;summary&gt;Deserialises an xml string in to an object of Type T&lt;/summary&gt;
/// &lt;typeparam name="T"&gt;Any class type&lt;/typeparam&gt;
/// &lt;param name="xml"&gt;Xml as string to deserialise from&lt;/param&gt;
/// &lt;returns&gt;A new object of type T is successful, null if failed&lt;/returns&gt;
public static T XmlDeserialise&lt;T&gt;(this string xml) where T : class, new()
{
  XmlSerializer serialiser;

  var type = typeof(T);
  if (!serialisers.ContainsKey(type))
  {
    serialiser = new XmlSerializer(type);
    serialisers.Add(type, serialiser);
  }
  else
  {
    serialiser = serialisers[type];
  }

  T newObject;

  using (var reader = new StringReader(xml))
  {
    try { newObject = (T)serialiser.Deserialize(reader); }
    catch { return null; } // Could not be deserialized to this type.
  }

  return newObject;
}</pre>
<p>When building the serialisation I had a help from an online example &#8211; but cannot remeber where it is&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/serialising-deserialising-objects-to-xml-in-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Single instance app in WPF 4 with argument passing</title>
		<link>http://blog.tonywilliams.me.uk/single-instance-app-in-wpf-4-with-argument-passing/</link>
		<comments>http://blog.tonywilliams.me.uk/single-instance-app-in-wpf-4-with-argument-passing/#comments</comments>
		<pubDate>Sun, 11 Jul 2010 13:08:03 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 4]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[WPF 4]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=26</guid>
		<description><![CDATA[How to have a WPF app with only 1 instance with only C# code and argument passing.]]></description>
			<content:encoded><![CDATA[<p>Extracted from: <a href="http://random.tonywilliams.me.uk/post/483779269/single-instance-app-in-wpf-4-with-argument-passing">http://random.tonywilliams.me.uk/post/483779269/single-instance-app-in-wpf-4-with-argument-passing</a></p>
<div>
<p>I was building a WPF app that required the use of JumpLists; the thing with JumpLists is that it calls your app&#8217;s exe with an argument which in turn creates a new instance of your app.</p>
<p>After a quick bit of googling I found a link [now dead] some code that restricts an app to a signle instance by using a mutex and passes the command argument supplied via named pipes.</p>
<p>Only portions of the code was recoverable, the rest I created my self.</p>
<p>Note that the code uses the .Net 4 Tasks, this can be replaced with threads if you want to use it in .Net 3.5. This also only passes the first argument through but can be easily changed to pass multiple.</p>
<pre class="brush:c#">namespace Your.App
{
  using System;
  using System.IO;
  using System.IO.Pipes;
  using System.Threading;
  using System.Threading.Tasks;

  public class SingleInstance : IDisposable
  {
    private readonly bool ownsMutex;
    private Mutex mutex;
    private Guid identifier;

    /// &lt;summary&gt;
    /// Occurs when [arguments received].
    /// &lt;/summary&gt;
    public event EventHandler&lt;GenericEventArgs&lt;string&gt;&gt; ArgumentsReceived;

    /// &lt;summary&gt;
    /// Initializes a new instance of the &lt;see cref="SingleInstance"/&gt; class.
    /// &lt;/summary&gt;
    /// &lt;param name="id"&gt;The id.&lt;/param&gt;
    public SingleInstance(Guid id)
    {
      this.identifier = id;
      mutex = new Mutex(true, identifier.ToString(), out ownsMutex);
    }

    /// &lt;summary&gt;
    /// Gets a value indicating whether this instance is first instance.
    /// &lt;/summary&gt;
    /// &lt;value&gt;
    /// 	&lt;c&gt;true&lt;/c&gt; if this instance is first instance; otherwise, &lt;c&gt;false&lt;/c&gt;.
    /// &lt;/value&gt;
    public bool IsFirstInstance
    {
      get
      {
        return ownsMutex;
      }
    }

    /// &lt;summary&gt;
    /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    /// &lt;/summary&gt;
    public void Dispose()
    {
      if (mutex != null &amp;&amp; ownsMutex)
      {
        mutex.ReleaseMutex();
        mutex = null;
      }
    }

    /// &lt;summary&gt;
    /// Passes the arguments to first instance.
    /// &lt;/summary&gt;
    /// &lt;param name="argument"&gt;The argument.&lt;/param&gt;
    public void PassArgumentsToFirstInstance(string argument)
    {
      using (var client = new NamedPipeClientStream(identifier.ToString()))
      using (var writer = new StreamWriter(client))
      {
        client.Connect(200);
        writer.WriteLine(argument);
      }
    }

    /// &lt;summary&gt;
    /// Listens for arguments from successive instances.
    /// &lt;/summary&gt;
    public void ListenForArgumentsFromSuccessiveInstances()
    {
      Task.Factory.StartNew(() =&gt;
                              {

                                using (var server = new NamedPipeServerStream(identifier.ToString()))
                                using (var reader = new StreamReader(server))
                                {
                                  while (true)
                                  {
                                    server.WaitForConnection();

                                    var argument = string.Empty;
                                    while (server.IsConnected)
                                    {
                                      argument += reader.ReadLine();
                                    }

                                    CallOnArgumentsReceived(argument);
                                    server.Disconnect();
                                  }
                                }
                              });
    }

    /// &lt;summary&gt;
    /// Calls the on arguments received.
    /// &lt;/summary&gt;
    /// &lt;param name="state"&gt;The state.&lt;/param&gt;
    public void CallOnArgumentsReceived(object state)
    {
      if (ArgumentsReceived != null)
      {
        if (state == null)
        {
          state = string.Empty;
        }

        ArgumentsReceived(this, new GenericEventArgs&lt;string&gt;() { Data = state.ToString() });
      }
    }
  }
}</pre>
<p>Here is the Generic Event Args class</p>
<pre class="brush:c#">namespace Your.App
{
  using System;

  public class GenericEventArgs&lt;TEventDataType&gt; : EventArgs
  {
    /// &lt;summary&gt;
    /// Gets or sets the data.
    /// &lt;/summary&gt;
    /// &lt;value&gt;The data.&lt;/value&gt;
    public TEventDataType Data { get; set; }
  }
}</pre>
<p>To use this class create an instance with a GUID for your app like so:</p>
<pre class="brush:c#">private static readonly SingleInstance SingleInstance = new SingleInstance(new Guid("24D910A1-1F03-44BA-85A0-BE7BC2655FFE"));</pre>
<p>Then on Application_Startup run your logic for it</p>
<pre class="brush:c#">private void Application_Startup(object sender, StartupEventArgs e)
{
  if (SingleInstance.IsFirstInstance)
  {
    SingleInstance.ArgumentsReceived += SingleInstanceParameter;
    SingleInstance.ListenForArgumentsFromSuccessiveInstances();
	// Do your other app logic
  }
  else
  {
    // if there is an argument available, fire it
    if (e.Args.Length &gt; 0)
    {
      SingleInstance.PassArgumentsToFirstInstance(e.Args[0]);
    }

    Environment.Exit(0);
  }
}

static void SingleInstanceParameter(object sender, GenericEventArgs e)
{
  // Inform app of new arguments
}</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/single-instance-app-in-wpf-4-with-argument-passing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

