EventHandler<T> or Action<T>

If you’ve used C# for any length of time, you’ve used events. Most likely, you wrote something like this:

  1.  
  2. public class MyCoolCSharpClass {
  3. public event EventHandler MyCoolEvent;
  4. }
  5.  
  6. public class MyOtherClass {
  7. public void MyOtherMethod(MyCoolCSharpClass obj)
  8. {
  9. obj.MyCoolEvent += WhenTheEventFires;
  10. }
  11.  
  12. private void WhenTheEventFires(object sender, EventArgs args)
  13. {
  14. Console.WriteLine("Hello World!");
  15. }
  16. }
  17.  

Later, you need parameters to be passed in along with the event, so you changed it to something like this:

  1.  
  2. public event EventHandler<MyEventArgs> MyCoolEvent;
  3.  
  4. public class MyEventArgs : EventArgs
  5. {
  6. public string Name { get; set; }
  7. public DateTime WhenSomethingHappened { get; set; }
  8. }
  9. ...
  10. private void WhenTheEventFires(object sender, MyEventArgs args)
  11. {
  12. var theCoolCSharpSendingClass = (MyCoolCSharpClass)sender;
  13. Console.WriteLine("Hello World! Good to meet you " + args.Name);
  14. }
  15.  

You add two or three more events, some property change and changing events, and finally a class with about 4 properties, 3 events, and a little bit of code now has 3 supporting EventArgs classes, casts for every time you need the sender class instance (In this example, I’m assuming the event is always fired by MyCoolCSharpClass, and not through a method from a 3rd class). There’s a lot of code there to maintain even for just a simple class with some very simple functionality.

Lets look at this for a minute. First, EventHandler and EventHandler<T> are simply delegates, nothing more nothing less (If you’re not sure what a delegate is, don’t sweat it, it’s not really the point of this discussion). What makes the magic happen for events is that little event keyword the prefaces the event that turns that internally turns the delegate type into a subscribe-able field. Essentially, it simplifies adding and removing multiple methods that are all called when the event is invoked. With the introduction of generics in C# 2.0, and the introduction of LINQ in 3.5, we have generic forms of most of the delegates we could ever use in the form of Action<T1, T2, T3...> and Func<TRes, T1, T2...>. What this means, is that we can change an event declarations to use whatever delegate we want. Something like this is perfectly valid:

  1.  
  2. public event Action<MyCoolCSHarpClass, string, DateTime> MyCoolEvent;
  3.  

And what about when we subscribe? Well, now we get typed parameters:

  1.  
  2. ...
  3. private void WhenTheEventFires(MyCoolCSHarpClass sender, string name, DateTime theDate)
  4. {
  5. Console.WriteLine("Hello World! Good to meet you " + name);
  6. }
  7.  

That’s cool. I’ve now reduced the amount of code I have to maintain from 4 classes to 1 and I don’t have to cast my sender. As a matter of fact, I don’t even have to pass a sender. How often have you written an event that’s something like this:

  1.  
  2. public event EventHandler TheTableWasUpdatedGoCheckIt;
  3.  

Whoever is subscribed to this event doesn’t care about who sent it, or what data specifically was updated, all the subscribe cares about was that it was fired, nothing more than that. Even then, in a “you can only use EventHandler delegate world” you’re still stuck creating a method to subscribe to the event that looks like this:

  1.  
  2. private void WhenTheTableWasUpdated(object sender, EventArgs args)
  3. {
  4. // Go check the database and update stuff...
  5. }
  6.  

If we use what we’ve learned and change the event to something like this:

  1.  
  2. public event Action TheTableWasUpdatedGoCheckIt;
  3.  

We can write our method like this:

  1.  
  2. private void WhenTheTableWasUpdated()
  3. {
  4. // Go check the database and update stuff...
  5. }
  6.  

Since we never cared about the parameters in the first place.

Thats awesome fine and dandy, but just blindly replacing every instance of EventHandler delegates to Actions isn’t always the best idea, there are a few caveats:

First, there are some practical physical limitations of using Action<T1, T2, T2... > vs using a derived class of EventArgs, three main ones that I can think of:

  • If you change the number or types of parameters, every method that subscribes to that event will have to be changed to conform to the new signature. If this is a public facing event that 3rd party assemblies will be using, and there is any possibility that the number or type of arguments would change, its a very good reason to use a custom class that can later be inherited from to provide more parameters. Remember, you can still use an Action<MyCustomClass>, but deriving from EventArgs is still the Way Things Are Done
  • Using Action<T1, T2, T2... > will prevent you from passing feedback BACK to the calling method unless you have a some kind of object (with a Handled property for instance) that is passed along with the Action, and if you’re going to make a class with a handled property, making it derive from EventArgs is completely reasonable.
  • You don’t get named parameters by using Action<T1, T2 etc...> so if you’re passing 3 bool‘s, an int, two string‘s, and a DateTime, you won’t immediately know what the meaning of those values. Passing a custom args class provides meaning to those parameters.

Secondly, consistency implications. If you have a large system you’re already working with, it’s nearly always better to follow the way the rest of the system is designed unless you have an very good reason not too. If you have publicly facing events that need to be maintained, the ability to substitute derived classes for args might be important.

Finally, real life practice, I personally find that I tend to create a lot of one off events for things like property changes that I need to interact with (Particularly when doing MVVM with view models that interact with each other) or where the event has a single parameter. Most of the time these events take on the form of public event Action<[classtype], bool> [PropertyName]Changed; or public event Action SomethingHappened;. In these cases, there are two benefits that you might be able to guess from what you’ve already seen.

  • I get a type for the issuing class. If MyClass declares and is the only class firing the event, I get an explicit instance of MyClass to work with in the event handler.
  • For simple events such as property change events, the meaning of the parameters is obvious and stated in the name of the event handler and I don’t have to create a myriad of classes for these kinds of events.

Food for thought. If you have any comments, feel free to leave them in the comment section below.

Merging a WPF application into a single EXE

I always dislike handing off little applications to people. Not because I can’t, but because of the steps involved to make sure it all just works. Small apps are the most problematic because I never want to take the time to create a whole installer project for just a few assemblies, and packaging up a zip file must be accompanied by “Unzip this into a folder in your programs directory and create a shortcut…” which brings us back to the whole installer business we started with.

There are a few tools already out there such as ILMerge by Microsoft Research (Which works great for most .NET-y things, but chokes on WPF applications) and a few paid tools by third party vendors that you could fork over a few hundred for to get. But, I’m a developer, which means I want to do it the Hard Way™. I did a little research and found the following blog posts on setting up and merging in DLL’s as resources into the main assembly and then extracting and loading them into memory when you run your application.

Links:

There were a few things I didn’t like about each solution. The first one (richarddingwall.name) ends up having you directly adding the .dll’s as resources directly. I hate maintaining things manually, especially when it will run fine on my machine but break when when I move it somewhere else because I forgot to update the resources when I added a new project. The one from blog.mahop.net builds on the previous one and changes the resolve location to a custom class with its own startup method. Better, because it resolves the resources earlier. Finally, the one from Daniel Chambers (digitallycreated.net) added in the final piece that automatically including the assemblies as resources. Unfortunately, the way he looks for culture specific assemblies didn’t work and I had to remove / change it to be closer to the one on mahop.net.

Final solution I’m currently using is as follows:

To the main executable project, unload and edit the .csproj file, and below the following line:

  1. <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

Add this XML to the project file, save, and load it back up.

  1. <Target Name="AfterResolveReferences">
  2. <ItemGroup>
  3. <EmbeddedResource Include="@(ReferenceCopyLocalPaths)" Condition="'%(ReferenceCopyLocalPaths.Extension)' == '.dll'">
  4. <LogicalName>%(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>
  5. </EmbeddedResource>
  6. </ItemGroup>
  7. </Target>

It should look something like this when your done:

You’ll then add a new code file to the main project and add the following code to it (modified to fit how your application is named / structured, in a WPF application, a good place to put it would be App.xaml.cs):

  1. [STAThread]
  2. public static void Main()
  3. {
  4. AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
  5.  
  6. App.Main(); // Run WPF startup code.
  7. }
  8.  
  9. private static Assembly OnResolveAssembly(object sender, ResolveEventArgs e)
  10. {
  11. var thisAssembly = Assembly.GetExecutingAssembly();
  12.  
  13. // Get the Name of the AssemblyFile
  14. var assemblyName = new AssemblyName(e.Name);
  15. var dllName = assemblyName.Name + ".dll";
  16.  
  17. // Load from Embedded Resources - This function is not called if the Assembly is already
  18. // in the same folder as the app.
  19. var resources = thisAssembly.GetManifestResourceNames().Where(s => s.EndsWith(dllName));
  20. if (resources.Any())
  21. {
  22.  
  23. // 99% of cases will only have one matching item, but if you don't,
  24. // you will have to change the logic to handle those cases.
  25. var resourceName = resources.First();
  26. using (var stream = thisAssembly.GetManifestResourceStream(resourceName))
  27. {
  28. if (stream == null) return null;
  29. var block = new byte[stream.Length];
  30.  
  31. // Safely try to load the assembly.
  32. try
  33. {
  34. stream.Read(block, 0, block.Length);
  35. return Assembly.Load(block);
  36. }
  37. catch (IOException)
  38. {
  39. return null;
  40. }
  41. catch(BadImageFormatException)
  42. {
  43. return null;
  44. }
  45. }
  46. }
  47.  
  48. // in the case the resource doesn't exist, return null.
  49. return null;
  50. }

Finally, make sure you update the target method for your main application to be the main method for the project you just added:

And, that’s it!

When you build your application you’ll still see all the assemblies in the output directory, but you should be able to take just the executable, move it somewhere else, and run it just as it is.

The Evolution of Generics in C# 4.0

Before I begin, let me point out that I'm primarily writing this post to solidify my own understanding of the new generic structures and put it into my own words, there are already some great posts that already explain this in much greater depth and detail: (Generic Variance in C# 4.0 by Discord & Rhyme, What's the difference between covariance and assignment compatibility? By Eric Lippert)

So that being said, let start off with the problem that generics solve in the first place. (If you have a good understanding, you can jump to the new features in C# 4.0)

C# Prior to 2.0

Lets say I have the following class hierarchy:

  1. public abstract class Fruit { }
  2.  
  3. public class Apple : Fruit { }
  4.  
  5. public class Orange : Fruit { }
  6.  
  7. public class FruitBasket
  8. {
  9. public Fruit[] Fruit { get; set; }
  10. }
  11.  
  12. public class Tree
  13. {
  14. public Fruit[] PickFruit()
  15. {
  16. Fruit[] daFruit = new Fruit[2];
  17. daFruit[0] = new Apple();
  18. daFruit[1] = new Orange();
  19. return daFruit;
  20. }
  21. }

We have a hierarchy of objects, a base Fruit class, an Apple class, which is a Fruit, and an Orange class, which is also a Fruit. In addition, we have a FruitBasket which has an enumerable of Fruit, and a Tree which I can "PickFruit()" from.

Now, lets say I want to have an instance of a fruit basket, however, I also want another one that deals with only Oranges (I don't want it to even be possible to put apples in the basket) so that I can make orange juice, apples just ruin a good glass of orange juice. I have two possibilities, I can create another fruit basket and ASSUME that I only put oranges in, or I create another classes that only allows oranges to be inserted in. Because I decide that I want the compiler to absolutely not allow apples in with the oranges, I now have to create a new class:

  1. public class OrangeBasket
  2. {
  3. public Oranges[] Oranges { get; set; }
  4. }

Or if I now want to have a basket that holds potatoes, I have to build another class:

  1. public class PotatoBasket
  2. {
  3. public Potato[] Potatos { get; set; }
  4. }

Right. Pattern. We are repeatedly creating virtually identical objects that simply contain other objects or that apply some sort of processing to those specific elements, all because we want the consumer (the person that is using this object) to be able to put an specifically typed object in and get a specifically typed object out, without having to cast it.

C# 2.0 - 3.5

With the release of C# 2.0 Microsoft introduced this concept of "generics" in programming. It allows programmers to create generalized algorithms that take and receive specific objects, store or process them, and return them, without knowing the creator of the object being worked on or knowing specific type. C# 2.0 also included a number of generic collections and interfaces that implemented these features, the most useful in my mind being the generic IEnumerable<T> interface. This now allows us to rewrite our basket class like follows:

  1. public class Basket<T>
  2. {
  3. IEnumerable<T> Contents{ get; set; }
  4. }

Now, instead of having a PotatoBasket, a FruitBasket, and a OrangeBasket we can replace it like so while still using the same class:

  1. Basket<Potato>
  2. Basket<Fruit>
  3. Basket<Orange>

And our Tree class now becomes:

  1. public class Tree
  2. {
  3. public IEnumerable<Fruit> PickFruit()
  4. {
  5. yield return new Apple();
  6. yield return new Orange();
  7. }
  8. }

So now, we have a Basket of Potatos, a Basket of Fruit, and a Basket of Oranges. Yet, we didn't have to duplicate the classes, and any the implementations still preserves type safety.

This is where it gets… Interesting.

Lets say I have an instance of a Tree class, and an instance of my Basket<Fruit> class. Now, it’s simple to do an assignment like this:

  1. var fruitBasket = new Basket<Fruit>();
  2. var Tree = new Tree();
  3. fruitBasket.Contents = tree.PickFruit();

BUT if I have a tree that has a PickApples() method like this:

  1. public IEnumerable<Apples> PickApples()
  2. {
  3. yield return new Apple();
  4. yield return new Apple();
  5. yield return new Apple();
  6. }

And I attempt to do the same assignment as before but with the PickApples() method instead, C# 3.5 will not compile it because the generic parameters are not the same:

  1. var fruitBasket = new Basket<Fruit>();
  2. var Tree = new Tree();
  3. fruitBasket.Contents = tree.PickApples();

That sucks. Why?

The reason has to do with the relationships of types, covariance / contra-variance / invariance (Erick Lipperts post on the difference between covariance and assignment compatibility is a much better source for it's relation with mathematics and type hierarchies). With versions prior to 4.0 the C# compiler does NOT allow generics of one type to be assigned to generics of another type. Thus, an IEnumerable<Apple> cannot be assigned to a variable of IEnumerable<Fruit>. But lets say we were allowed to do this, why would it be a problem? Lets say I have an IList<Fruit> and an IList<Apple>; it seems to make perfect sense that I could so the following assignment:

  1. var fruitList = new List<Fruit>();
  2. var appleList = new List<Apple>();
  3. fruitList = appleList;

Right?

Wrong.

This assignment would actually be plausable for IEnumerable<T> because IEnumerable<T> is immutable, it can not change, there's no way to "Insert" a new element into an IEnumerable. However, with an IList<T> it defines an Add(T item) method. An IList can be altered. In the previous example, if I were to take fruitList and look at the Add method in intellisense, it would show that I can insert any object that is a fruit into the add method of the fruitList, however, fruitlist isn't technically a list of fruits anymore given this senario, its a pointer to a List<Apple>. So in this flawed example, I could now call fruitList.Add(new Orange()); which would now be a runtime error because I can't insert an Orange into a List<Apple>. Bad. (In C# however, there is an edge case where this sort of error can occur with arrays. For instance, if you have a object[] objarray = new string[10]; you can then assign a fruit to one of the slots and cause a runtime exception. For more detail on this, see Erick Lipperts post on Covariance and Contravariance in C# arrays) So we have two things that should be solved. We know that there are certain situations where IEnumerable<X> should be assignable to IEnumerable<T>, specifically when X is a subclass of T, but we also realize that something like IList<X> should not be assignable to a variable of IList<T>.

C# 4.0

Enter variance modifiers for generic types that have now been introduced in C# 4.0.

out and in.

First, these can only be applied to generic type parameters of interfaces and delegates, in can only be applied to generic parameters that are contra-variant or invariant valid, and out can only be applied to generic parameters that are co-variant or invariant valid.

Gulp.

First, invariance, contra-variance, and covariance. In terms of types, if I have T1 and T2, those types are Invariant if they are the same type. For instance, a Fruit and a Fruit are invariant, a Fruit and an Apple is not invariant even though a Fruit variable can hold an Apple object.

Co-variant is where the inheritance chains are kept, if I have T1 and T2, the projection of T1 to T2 is covariant if T2 is lower in the inheritance chain than T1. For instance, a Fruit to Apple is Co-variant because Apple is an instance of Fruit.

Contra-variant is where the inheritance chain is reversed, if I have T1 and T2, the projection of T1 to T2 is contra-variant if T2 is higher up the inheritance chain than T1. For instance, an Apple to Fruit is contra-variant because Apple is an instance of Fruit, the relationship is reversed, flipped.

So, it allows me to do the following in C# 4.0 with the new variant structure:

  1. var fruitBasket = new Basket<Fruit>();
  2. var Tree = new Tree();
  3. fruitBasket.Contents = tree.PickApples();

Because IEnumerable is defined as follows:

  1. IEnumerable<out T> { /* .. */ }

Remembering that out is co-variant because it can return the item or a subclass of that item, in this case PickApples() is returning an IEnumerable that is lower in the inheritance chain than the variable it's being assigned to (by lower, I mean that its a subclass, or sub-sub..n class of the other object)

To demonstrate a class with contra-variance with an in parameter, lets say we have an interface and classes like so:

  1. IPieMaker<in T> where T : Fruit
  2. {
  3. Pie MakePie(IEnumerable<T> fruits);
  4. }
  5.  
  6. ApplePieMaker : IPieMaker<Apple> { /* ... Some implementation ...*/ }
  7. FruitPieMaker : IPieMaker<Fruit> { /* ... Some implementation ...*/ }

Now, because the input parameter is contra-variant, I can have a variable declaration like so:

  1. IPieMaker<Apple> applePieMaker = new FruitPieMaker();

Wait. Seem odd? Because T is not specifying what Pie we are making only what is put IN to make the pie, I can put apples into a FruitPieMaker. It’s contra-variant.

Try and wrap you head around that :)

Note: There's a good possibility that I didn't accurately describe the terms covariance and contra-variance in relation to mathematical projection and ordering, corrections and better descriptions are greatly appreciated.

Additional Links:

Building a REALLY simple WCF P2P application

Often times when I’m looking at playing with a new technology that it becomes extremely difficult to find a simple stripped down easy-to-use chunk of code that also walks through, in-depth, the concepts and reasoning behind the code. This particular code chunk began as I started exploring the Microsoft WCF’s P2P networking services and found a rather distinct lack of code that explained the hows and whys of building a Peer to Peer network.

P2P Basics

Ok. Low level building blocks.

First, everybody (who’s interested in P2P) should already understand the client server paradigm, if not, there are many wonderfully detailed articles to explain the details. In short we have N clients all connected to 1 server. Client A sends a message to the server, the server decides what to do, and then may or may not send a response to Client A and / or Client B, Client C… etc… In a peer to peer network on the other hand, everyone is the client, everyone is a server. Because of this, the client / server naming scheme goes away by popular vote and everyone is called a node or a peer. When a node is connected to other nodes that whole group is called a mesh (or graph, or cloud).

Now, in a pure P2P network there is no central authority to help or govern how nodes find each other to form a mesh or how meshes are initially created.  Every node is connected to some number of other nodes, which are then connected to more nodes and so on. When one node wishes to communicate with another node (or nodes) the message is first passed on to the nodes that the first node knows about. These nodes in turn pass along the message on to other nodes that they know about and so on until finally everybody has seen the message.

One of the best, and probably most used, examples of a peer to peer network is the chat room. Until someone creates it, the chat room does not exist, but once it’s created people can be invited, join, and send messages that appear on everybody else’s screen. Even if the original person leaves the chat room, the room still exists as long as there are participants logged in. Once the last person leaves the chat room no longer exists.

Ping – The P2P Application

Note: I really dislike configuration files in demos or tutorials unless it’s a large application or showing how a particular aspect of a configuration file works. The fact that I can tell a static factory to build me something with a string name that corresponds to another file that somehow gets found, loaded, and happens to reference compiled type that then has a hidden class generated that implements that interface and is passed, bugs me when I’m trying to learn something.

If your going to follow along with this, your going to need .NET 3.5 installed and be running XP SP3, Vista, Win7 or Server 08. Visual Studio doesn’t hurt either.

To set up your project crack open Visual Studio and spin up a new Console Application, call it SimpleP2PExample. Once you have that open go over to the project, right click and Add Service Reference to System.ServiceModel, this allows you to use .NET’s WCF stuff in your app. You can choose to split up each class or interface into its own file or not: Up to you.

IPing
  1. //Contract for our network. It says we can 'ping'
  2. [ServiceContract(CallbackContract = typeof(IPing))]
  3. public interface IPing
  4. {
  5. [OperationContract(IsOneWay = true)]
  6. void Ping(string sender, string message);
  7. }

Alright, first of all, attributes. If you don’t know what they are, then here’s the low down mouthful one line explanation:

Attributes are essentially binary metadata associated with a class, method, property or whatever that provides additional information about whatever it’s “Decorating”.

The first attribute is the service contract. Wait a second. Contracts.

In our node-talking-to-other-nodes scenario, somehow they have to know how to talk to each other, if I asked what the size of the door was and you handed me a window, I have NO idea what that means or what that represents. A contract defines exactly what I’m telling you, what I’m expecting back, how, and when.

In this case we’re defining a contract that has one operation, a method called Ping. We know that when node A talks to node B that if node A says “Hey, Ping(“MyName”, “Hello.”) to Node B that node B will know what to do with that and how to pass it along to other nodes. It’s also specifies that I don’t expect Node B to give me anything back.

Now, the implementation.

PingImplementation
  1. //implementation of our ping class
  2. public class PingImplementation : IPing
  3. {
  4. public void Ping(string sender, string message)
  5. {
  6. Console.WriteLine("{0} says: {1}", sender, message);
  7. }
  8. }

Fairly simple, whenever we receive a ping from another node, this method will be executed.

The Peer Class

Alright, now the fun, magic, and games begin. We’re going to create a class called peer, which will contain all our service start / stop code and also hold our implementation of PingImplementation.

Peer
  1. public class Peer
  2. {
  3. public string Id { get; private set; }
  4.  
  5. public IPing Channel;
  6. public IPing Host;
  7.  
  8. public Peer(string id)
  9. {
  10. Id = id;
  11. }
  12. }

In order to identify an individual node in the network, so that we know who’s who and don’t get everything mixed up, it’s customary to have a unique Id that’s assigned to the peer. Now, we have two IPing variables, the best way to describe them would be incoming and outgoing. An instance of the PingImplementation class will go in Host since it will be receiving any incoming communication from other nodes; The Channel is used to communicate out to other nodes and is built up via a factory.

Peer
  1. public void StartService()
  2. {
  3. var binding = new NetPeerTcpBinding();
  4. binding.Security.Mode = SecurityMode.None;
  5.  
  6. var endpoint = new ServiceEndpoint(
  7. ContractDescription.GetContract(typeof(IPing)),
  8. binding,
  9. new EndpointAddress("net.p2p://SimpleP2P"));
  10.  
  11. Host = new PingImplementation();
  12.  
  13. _factory = new DuplexChannelFactory(
  14. new InstanceContext(Host),
  15. endpoint);
  16.  
  17. var channel = _factory.CreateChannel();
  18.  
  19. ((ICommunicationObject)channel).Open();
  20.  
  21. // wait until after the channel is open to allow access.
  22. Channel = channel;
  23. }
  24. private DuplexChannelFactory<IPing>; _factory;

This is what we will use to start the peer.  This is the part where I’ve built up what could have been done in the configuration file with code instead.

Lets take it from the top.  First off, we have our binding; this defines what communication protocol we are going to be using, and as this is a PeerToPeer app… we use NetPeerTcpBinding().  You’ll also notice that in the next line I set the security mode to none; this is done for simplicities sake. There’s three types of security modes, including None, Message, Transport and TransportWithMessageCredential. Its a bit beyond the scope of this post, but Message security ensures that the message was not tampered with as it was passed from peer to peer, Transport security ensures that the connection between nodes is secure, and TransportWithMessageCredential does both.

Now, our application needs an endpoint, essentially, an service endpoint is a set of information that is exposed outside of the application (in this case on the network as well) so that others can access it. The endpoint defines the address it can be reached at, the contract, and the method that should be used to communicate. In this case, we build up our endpoint by using ContractDescription.GetContract to generate a contract class off of our IPing interface, our network type binding, and an endpoint address where this endpoint can be reached.

Finally, we create a new instance of our PingImplementation class as the Host, and we create our channel factory. A DuplexChannelFactory allows for two way communication, the first parameter is the object that you want to receive incoming calls, and the endpoint is where those calls are coming from. The factory then creates the channel and a whole bunch of magical things happen.

If you’ll remember, our channel is of type IPing, the Duplex Factory performs some magic and generates a concrete implementation of your interface (it also implements ICommunicationObject, which is why you’ll sometimes see people create another interface called something like “IPingChannel : IPing, ICommunicationObject”, it does make it so that you don’t have to cast it, but for the purpose of this post it’s not necessary). Imagine that it takes your interface, implements all the methods and properties with all the cool DuplexChannel code needed to talk back and fourth, creates an instance, and returns it to you.

Finally, I call open on my channel to let the world see that my brand new channel and endpoint are ready for business.

Peer
  1. public void StopService()
  2. {
  3. ((ICommunicationObject)Channel).Close();
  4. if (_factory != null)
  5. _factory.Close();
  6. }

Now, it’s all well and good, until your done. Then you need to close you channel and factory, this should be pretty self explanatory at this point.  Remember our channel is an ICommunicationObject in addition to being a IPing object, so we cast and close, then check to see if our factory is null, and if not, close that as well.

Threading The Peer Class

Something I chose to do was make the peer threaded. This allows me to drop it into an application, in a thread, and receive and push stuff into it at my leisure. To do this I add in a:

Peer
  1. private readonly AutoResetEvent _stopFlag = new AutoResetEvent(false);

This will allow me to block a method of the thread until I decide fire it (When I stop the peer).

Peer
  1. public void Run()
  2. {
  3. Console.WriteLine("[ Starting Service ]");
  4. StartService();
  5.  
  6. Console.WriteLine("[ Service Started ]");
  7. _stopFlag.WaitOne();
  8.  
  9. Console.WriteLine("[ Stopping Service ]");
  10. StopService();
  11.  
  12. Console.WriteLine("[ Service Stopped ]");
  13. }
  14.  
  15. public void Stop()
  16. {
  17. _stopFlag.Set();
  18. }

The run method embodies the lifecycle of this peer. When the peer thread starts into the run method it will start the service, wait until the stop flag is fired (when the Stop() method is called), and then stop and dispose the service.

Putting It All Together
Program
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Count() <= 1)
  6. {
  7. for (int i = 0; i < 4; i++)
  8. {
  9. Process.Start("SimpleP2PExample.exe");
  10. }
  11. }
  12.  
  13. new Program().Run();
  14. }
  15.  
  16. public void Run()
  17. {
  18. Console.WriteLine("Starting the simple P2P demo.");
  19.  
  20. var peer = new Peer("Peer(" + Guid.NewGuid() + ")");
  21. var peerThread = new Thread(peer.Run) {IsBackground = true};
  22. peerThread.Start();
  23.  
  24. //wait for the server to start up.
  25. Thread.Sleep(1000);
  26.  
  27. while (true)
  28. {
  29. Console.Write("Enter Something: ");
  30. string tmp = Console.ReadLine();
  31.  
  32. if (tmp == "") break;
  33.  
  34. peer.Channel.Ping(peer.Id, tmp);
  35. }
  36.  
  37. peer.Stop();
  38. peerThread.Join();
  39. }
  40. }

From top to bottom, the Main method of the application checks to see if it’s the first one of this application to have started up, if it its, then it starts four additional processes (Note that if you called your project something other than SimpleP2PExample, you will need to replace the the string in Process.Start to be the name as the executable file your project generates).

The run method is also fairly simple, it creates a new instance of the Peer class, assigns it a GUID, creates a thread for the peer’s run method, starts up the thread and pauses to wait for the peer’s thread to start.  We then enter a loop until the user presses enter without inputting any text. Any text that is put in is transmitted over the peer channel using the peer’s id and the message. Once we’ve finished, we stop the session and wait for the peerThread to exit and join back up with the main thread. We then exit.

Wrap Up

I hope this helps someone out there get a better understanding of the basic concepts of a simple Peer to Peer application. Feel free to leave feedback!

Paul Rohde

WCF Manual Service Hosing on Windows Vista and Windows 7

With the new security features introduced in Windows Vista and now in Windows 7 there are some, not so obvious, problems that have crept in and cause weird errors in even simple code. I was building a simple web service for the first time a simple HelloWorld in a console application to make it easy to debug and output trace information. Nothing complicated, a little different because I was configuring everything manually in code as opposed to using configuration file. Here’s the code for my simple, stripped down HelloWorld service:

ConsoleServer.cs
  1.  
  2. using System;
  3. using System.ServiceModel;
  4.  
  5. namespace ConsoleServer
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. Console.Write("Server...");
  12.  
  13. ServiceHost serviceHost = new ServiceHost(typeof(HelloWorldService),
  14. new Uri("http://localhost:9000/TestService"));
  15.  
  16. serviceHost.AddServiceEndpoint(
  17. typeof(IHelloWorldService),
  18. new WSHttpBinding(),
  19. "");
  20.  
  21. serviceHost.Open();
  22.  
  23. Console.WriteLine("Started");
  24.  
  25. Console.ReadLine();
  26. }
  27. }
  28.  
  29. //operation contract
  30. [ServiceContract]
  31. public interface IHelloWorldService
  32. {
  33. [OperationContract]
  34. string HelloWorld();
  35. }
  36.  
  37. public class HelloWorldService : IHelloWorldService
  38. {
  39. public void HelloWorld()
  40. {
  41. System.Threading.Thread.Sleep(1000); //sleep for one second
  42. return "Hello World Service";
  43. }
  44. }
  45. }
  46.  

And the client:

ConsoleClient.cs
  1.  
  2. using System;
  3. using System.ServiceModel;
  4. using ConsoleServer;
  5.  
  6. namespace Client
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. Console.WriteLine("Client");
  13.  
  14. ChannelFactory<IHelloWorldService> myChannelFactory =
  15. new ChannelFactory<IHelloWorldService>(
  16. new WSHttpBinding(),
  17. new EndpointAddress
  18. ("http://localhost:9000/TestService"));
  19. IHelloWorldService wcfClient = myChannelFactory.CreateChannel();
  20.  
  21.  
  22. System.Threading.Thread.Sleep(3000);
  23. Console.WriteLine("Calling Hello World");
  24. for (int i = 0; i < 5; i++)
  25. {
  26. Console.WriteLine(wcfClient.HelloWorld());
  27. Console.WriteLine("- Called HelloWorld");
  28. }
  29.  
  30. Console.WriteLine("Done");
  31.  
  32. Console.ReadLine();
  33.  
  34.  
  35. }
  36. }
  37. }
  38.  

The code is fairly straight forward as far as services go, running it however I began getting the following error:

HTTP could not register URL http://localhost:9000/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).

Extremely unhelpful, and the link provided by Microsoft offers no solutions (insert eye roll here) so I went off to consult Google… After a bit of research I discovered that it was the security features in Window 7 and Windows Vista that had been causing the problem, mostly because I’m trying to do everything manually in code some of the permission requests or other behind the scenes magic that normally occurs when Visual Studio 2008 creates and hosts a service from an application configuration file don’t happen. (My guess is that when visual studio installs it sets up permissions for Cassini, it’s inbuilt web server, and that when you run your service the ‘normal’ way that it automatically wraps your service in Cassini, effectively bypassing the normal application security measures, but that’s another story). Long and the short of it is that if you want to do this yourself you need to add some permissions to your user (by default even administrator accounts in Windows 7 and I *think* Windows Vista run in a restricted mode) to allow you to register your service with windows. (The original article is here)

Run a Command Prompt with Administrator privileges (Actually right click and select it), type and run the following command (replace the port number with whatever port you are using, 9000 for the code above, and your domain(or computername if your not on a domain) and username).

netsh http add urlacl url=http://+:8000/ user=DOMAIN\UserName

And *BAM* everything magically works. Cool huh?

– Paul Rohde