Commit ded9cfb

mo khan <mo@mokhan.ca>
2010-07-09 00:03:58
got the client and the server to play ping pong.
1 parent 91a73b3
code/client/Client.cs
@@ -11,7 +11,7 @@ namespace client
 {
     class Client
     {
-        static void Main(string[] args)
+        static void Main()
         {
             Process.Start(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\server\bin\Debug\server.exe")));
 
@@ -65,7 +65,7 @@ namespace client
             builder.Register<AsynchronousCommandProcessor>().As<CommandProcessor>().SingletonScoped();
 
 
-            builder.Register<StartedApplicationHandler>().As<Handler>();
+            builder.Register<RequestHandler>().As<Handler>();
 
             Resolve.the<IEnumerable<NeedStartup>>().each(x => x.run());
             Resolve.the<CommandProcessor>().run();
code/client/client.csproj
@@ -54,7 +54,6 @@
   <ItemGroup>
     <Compile Include="Client.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
-    <Compile Include="StartedApplicationHandler.cs" />
     <Compile Include="StartServiceBus.cs" />
   </ItemGroup>
   <ItemGroup>
code/client/StartedApplicationHandler.cs
@@ -1,13 +0,0 @@
-using common;
-using common.messages;
-
-namespace client
-{
-    public class StartedApplicationHandler : AbstractHandler<StartedApplication>
-    {
-        public override void handle(StartedApplication item)
-        {
-            "received {0}".log(item.message);
-        }
-    }
-}
\ No newline at end of file
code/client/StartServiceBus.cs
@@ -14,7 +14,11 @@ namespace client
                 handler.handler(x);
             });
             Resolve.the<CommandProcessor>().add(receiver);
-            Resolve.the<ServiceBus>().publish<StartedApplication>(x => x.message = "client");
+            Resolve.the<ServiceBus>().publish<Message>(x =>
+            {
+                x.source = "client";
+                x.message = "ping";
+            });
         }
     }
 }
\ No newline at end of file
code/common/messages/StartedApplication.cs → code/common/messages/Message.cs
@@ -1,18 +1,21 @@
-using System;
-using ProtoBuf;
-
-namespace common.messages
-{
-    [Serializable]
-    [ProtoContract]
-    public class StartedApplication
-    {
-        [ProtoMember(1)]
-        public string message { get; set; }
-
-        public override string ToString()
-        {
-            return base.ToString() + message;
-        }
-    }
+using System;
+using ProtoBuf;
+
+namespace common.messages
+{
+    [Serializable]
+    [ProtoContract]
+    public class Message
+    {
+        [ProtoMember(1)]
+        public string source { get; set; }
+
+        [ProtoMember(2)]
+        public string message { get; set; }
+
+        public override string ToString()
+        {
+            return base.ToString() + source;
+        }
+    }
 }
\ No newline at end of file
code/common/AbstractHandler.cs
@@ -1,24 +1,22 @@
-using System;
-
-namespace common
-{
-    public abstract class AbstractHandler<T> : Handler<T>, Handler
-    {
-        bool can_handle(Type type)
-        {
-            this.log().debug("{0} can handle {1} = {2}", this, type, typeof (T).Equals(type));
-            return typeof (T).Equals(type);
-        }
-
-        public void handle(object item)
-        {
-            if (can_handle(item.GetType()))
-            {
-                this.log().debug("handling... {0}", item);
-                handle((T) item);
-            }
-        }
-
-        public abstract void handle(T item);
-    }
+using System;
+
+namespace common
+{
+    public abstract class AbstractHandler<T> : Handler<T>, Handler
+    {
+        bool can_handle(Type type)
+        {
+            return typeof (T).Equals(type);
+        }
+
+        public void handle(object item)
+        {
+            if (can_handle(item.GetType()))
+            {
+                handle((T) item);
+            }
+        }
+
+        public abstract void handle(T item);
+    }
 }
\ No newline at end of file
code/common/Command.cs
@@ -0,0 +1,7 @@
+namespace common
+{
+    public interface Command
+    {
+        void run();
+    }
+}
\ No newline at end of file
code/common/common.csproj
@@ -1,84 +1,86 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <PropertyGroup>
-    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
-    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
-    <ProductVersion>8.0.30703</ProductVersion>
-    <SchemaVersion>2.0</SchemaVersion>
-    <ProjectGuid>{B34D543A-B443-4344-BD0E-2CFC6283D643}</ProjectGuid>
-    <OutputType>Library</OutputType>
-    <AppDesignerFolder>Properties</AppDesignerFolder>
-    <RootNamespace>common</RootNamespace>
-    <AssemblyName>common</AssemblyName>
-    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
-    <FileAlignment>512</FileAlignment>
-  </PropertyGroup>
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
-    <DebugSymbols>true</DebugSymbols>
-    <DebugType>full</DebugType>
-    <Optimize>false</Optimize>
-    <OutputPath>bin\Debug\</OutputPath>
-    <DefineConstants>DEBUG;TRACE</DefineConstants>
-    <ErrorReport>prompt</ErrorReport>
-    <WarningLevel>4</WarningLevel>
-  </PropertyGroup>
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
-    <DebugType>pdbonly</DebugType>
-    <Optimize>true</Optimize>
-    <OutputPath>bin\Release\</OutputPath>
-    <DefineConstants>TRACE</DefineConstants>
-    <ErrorReport>prompt</ErrorReport>
-    <WarningLevel>4</WarningLevel>
-  </PropertyGroup>
-  <ItemGroup>
-    <Reference Include="Autofac">
-      <HintPath>..\..\external\auto.fac\Autofac.dll</HintPath>
-    </Reference>
-    <Reference Include="protobuf-net">
-      <HintPath>..\..\external\proto-buf.net\protobuf-net.dll</HintPath>
-    </Reference>
-    <Reference Include="Rhino.Queues">
-      <HintPath>..\..\external\rhino.queues\Rhino.Queues.dll</HintPath>
-    </Reference>
-    <Reference Include="System" />
-    <Reference Include="System.Core" />
-    <Reference Include="System.Transactions" />
-    <Reference Include="System.Xml.Linq" />
-    <Reference Include="System.Data.DataSetExtensions" />
-    <Reference Include="Microsoft.CSharp" />
-    <Reference Include="System.Data" />
-    <Reference Include="System.Xml" />
-  </ItemGroup>
-  <ItemGroup>
-    <Compile Include="AbstractHandler.cs" />
-    <Compile Include="AsynchronousCommandProcessor.cs" />
-    <Compile Include="AutofacDependencyRegistry.cs" />
-    <Compile Include="AutofacDependencyRegistryBuilder.cs" />
-    <Compile Include="CommandProcessor.cs" />
-    <Compile Include="DependencyRegistry.cs" />
-    <Compile Include="EmptyCommand.cs" />
-    <Compile Include="FuncExtensions.cs" />
-    <Compile Include="Handler.cs" />
-    <Compile Include="Iterating.cs" />
-    <Compile Include="Logging.cs" />
-    <Compile Include="MessageHandler.cs" />
-    <Compile Include="messages\StartedApplication.cs" />
-    <Compile Include="NeedStartup.cs" />
-    <Compile Include="Observer.cs" />
-    <Compile Include="Properties\AssemblyInfo.cs" />
-    <Compile Include="Receiver.cs" />
-    <Compile Include="Resolve.cs" />
-    <Compile Include="RhinoPublisher.cs" />
-    <Compile Include="RhinoReceiver.cs" />
-    <Compile Include="ServiceBus.cs" />
-    <Compile Include="StringFormatting.cs" />
-  </ItemGroup>
-  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
-  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
-       Other similar extension points exist, see Microsoft.Common.targets.
-  <Target Name="BeforeBuild">
-  </Target>
-  <Target Name="AfterBuild">
-  </Target>
-  -->
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProductVersion>8.0.30703</ProductVersion>
+    <SchemaVersion>2.0</SchemaVersion>
+    <ProjectGuid>{B34D543A-B443-4344-BD0E-2CFC6283D643}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>common</RootNamespace>
+    <AssemblyName>common</AssemblyName>
+    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="Autofac">
+      <HintPath>..\..\external\auto.fac\Autofac.dll</HintPath>
+    </Reference>
+    <Reference Include="protobuf-net">
+      <HintPath>..\..\external\proto-buf.net\protobuf-net.dll</HintPath>
+    </Reference>
+    <Reference Include="Rhino.Queues">
+      <HintPath>..\..\external\rhino.queues\Rhino.Queues.dll</HintPath>
+    </Reference>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Transactions" />
+    <Reference Include="System.Xml.Linq" />
+    <Reference Include="System.Data.DataSetExtensions" />
+    <Reference Include="Microsoft.CSharp" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="AbstractHandler.cs" />
+    <Compile Include="AsynchronousCommandProcessor.cs" />
+    <Compile Include="AutofacDependencyRegistry.cs" />
+    <Compile Include="AutofacDependencyRegistryBuilder.cs" />
+    <Compile Include="Command.cs" />
+    <Compile Include="CommandProcessor.cs" />
+    <Compile Include="DependencyRegistry.cs" />
+    <Compile Include="EmptyCommand.cs" />
+    <Compile Include="FuncExtensions.cs" />
+    <Compile Include="Handler.cs" />
+    <Compile Include="Iterating.cs" />
+    <Compile Include="Logging.cs" />
+    <Compile Include="MessageHandler.cs" />
+    <Compile Include="messages\Message.cs" />
+    <Compile Include="NeedStartup.cs" />
+    <Compile Include="Observer.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="Receiver.cs" />
+    <Compile Include="Resolve.cs" />
+    <Compile Include="RhinoPublisher.cs" />
+    <Compile Include="RhinoReceiver.cs" />
+    <Compile Include="ServiceBus.cs" />
+    <Compile Include="RequestHandler.cs" />
+    <Compile Include="StringFormatting.cs" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
 </Project>
\ No newline at end of file
code/common/Logging.cs
@@ -1,44 +1,18 @@
 using System;
-using System.IO;
 using System.Reflection;
 
 namespace common
 {
     static public class Logging
     {
-        static public Logger log<T>(this T item)
-        {
-            return new TextLogger(Console.Out);
-        }
-
         static public void log(this string item, params object[] arguments)
         {
-            new TextLogger(Console.Out).debug(item, arguments);
+            Console.Out.WriteLine("{0}: {1}".format(Assembly.GetEntryAssembly().GetName().Name, item.format(arguments)));
         }
 
         static public void add_to_log(this Exception item)
         {
-            new TextLogger(Console.Out).debug(item.Message);
+            item.Message.log();
         }
     }
-
-    public class TextLogger : Logger
-    {
-        readonly TextWriter writer;
-
-        public TextLogger(TextWriter writer)
-        {
-            this.writer = writer;
-        }
-
-        public void debug(string message, params object[] arguments)
-        {
-            writer.WriteLine("{0}: {1}".format(Assembly.GetEntryAssembly().GetName().Name, message.format(arguments)));
-        }
-    }
-
-    public interface Logger
-    {
-        void debug(string message, params object[] arguments);
-    }
 }
\ No newline at end of file
code/common/MessageHandler.cs
@@ -1,37 +1,33 @@
-using System;
-using System.IO;
-using System.Runtime.Serialization.Formatters.Binary;
-using ProtoBuf;
-using Rhino.Queues.Model;
-
-namespace common
-{
-    public class MessageHandler
-    {
-        BinaryFormatter formatter = new BinaryFormatter();
-        DependencyRegistry registry;
-
-        public MessageHandler(DependencyRegistry registry)
-        {
-            this.registry = registry;
-        }
-
-        public void handler(Message item)
-        {
-            var payload = parse_payload_from(item);
-            this.log().debug("received: {0}", payload);
-            registry
-                .get_all<Handler>()
-                .each(x => x.handle(payload));
-        }
-
-        object parse_payload_from(Message item)
-        {
-            using (var stream = new MemoryStream(item.Data))
-            {
-                //return formatter.Deserialize(stream);
-                return Serializer.NonGeneric.Deserialize(Type.GetType(item.Headers["type"]), stream);
-            }
-        }
-    }
+using System;
+using System.IO;
+using ProtoBuf;
+using Rhino.Queues.Model;
+
+namespace common
+{
+    public class MessageHandler
+    {
+        DependencyRegistry registry;
+
+        public MessageHandler(DependencyRegistry registry)
+        {
+            this.registry = registry;
+        }
+
+        public void handler(Message item)
+        {
+            var payload = parse_payload_from(item);
+            registry
+                .get_all<Handler>()
+                .each(x => x.handle(payload));
+        }
+
+        object parse_payload_from(Message item)
+        {
+            using (var stream = new MemoryStream(item.Data))
+            {
+                return Serializer.NonGeneric.Deserialize(Type.GetType(item.Headers["type"]), stream);
+            }
+        }
+    }
 }
\ No newline at end of file
code/common/NeedStartup.cs
@@ -1,6 +1,4 @@
-namespace common
-{
-    public interface NeedStartup : Command {}
-
-    public interface Command { void run();}
+namespace common
+{
+    public interface NeedStartup : Command {}
 }
\ No newline at end of file
code/common/RequestHandler.cs
@@ -0,0 +1,28 @@
+using System;
+using System.Reflection;
+using System.Threading;
+using common.messages;
+
+namespace common
+{
+    public class RequestHandler : AbstractHandler<Message>
+    {
+        ServiceBus bus;
+
+        public RequestHandler(ServiceBus bus)
+        {
+            this.bus = bus;
+        }
+
+        public override void handle(Message item)
+        {
+            "received from {0}: {1} {2}".log(item.source, item.message, DateTime.Now);
+            Thread.Sleep(5000);
+            bus.publish<Message>(x =>
+            {
+                x.message = item.message.Equals("ping") ? "pong" : "ping";
+                x.source = Assembly.GetEntryAssembly().GetName().Name;
+            });
+        }
+    }
+}
\ No newline at end of file
code/common/RhinoPublisher.cs
@@ -1,60 +1,55 @@
-using System;
-using System.IO;
-using System.Runtime.Serialization.Formatters.Binary;
-using System.Transactions;
-using ProtoBuf;
-using Rhino.Queues;
-
-namespace common
-{
-    public class RhinoPublisher : ServiceBus
-    {
-        BinaryFormatter formatter = new BinaryFormatter();
-        readonly int port;
-        string destination_queue;
-        IQueueManager sender;
-
-        public RhinoPublisher(string destination_queue, int port, IQueueManager manager)
-        {
-            this.port = port;
-            this.destination_queue = destination_queue;
-            sender = manager;
-        }
-
-        public void publish<T>() where T : new()
-        {
-            publish(new T());
-        }
-
-        public void publish<T>(T item) where T : new()
-        {
-            using (var transaction = new TransactionScope())
-            {
-                var destination = "rhino.queues://localhost:{0}/{1}".format(port, destination_queue);
-                this.log().debug("sending {0} to {1}", item, destination);
-                sender.Send(new Uri(destination), create_payload_from(item));
-                transaction.Complete();
-            }
-        }
-
-        MessagePayload create_payload_from<T>(T item)
-        {
-            using (var stream = new MemoryStream())
-            {
-                Serializer.Serialize(stream, item);
-                //formatter.Serialize(stream, item);
-
-                var payload = new MessagePayload {Data = stream.ToArray()};
-                payload.Headers["type"] = typeof (T).FullName;
-                return payload;
-            }
-        }
-
-        public void publish<T>(Action<T> configure) where T : new()
-        {
-            var item = new T();
-            configure(item);
-            publish(item);
-        }
-    }
+using System;
+using System.IO;
+using System.Transactions;
+using ProtoBuf;
+using Rhino.Queues;
+
+namespace common
+{
+    public class RhinoPublisher : ServiceBus
+    {
+        readonly int port;
+        string destination_queue;
+        IQueueManager sender;
+
+        public RhinoPublisher(string destination_queue, int port, IQueueManager manager)
+        {
+            this.port = port;
+            this.destination_queue = destination_queue;
+            sender = manager;
+        }
+
+        public void publish<T>() where T : new()
+        {
+            publish(new T());
+        }
+
+        public void publish<T>(T item) where T : new()
+        {
+            using (var transaction = new TransactionScope())
+            {
+                var destination = "rhino.queues://localhost:{0}/{1}".format(port, destination_queue);
+                sender.Send(new Uri(destination), create_payload_from(item));
+                transaction.Complete();
+            }
+        }
+
+        MessagePayload create_payload_from<T>(T item)
+        {
+            using (var stream = new MemoryStream())
+            {
+                Serializer.Serialize(stream, item);
+                var payload = new MessagePayload {Data = stream.ToArray()};
+                payload.Headers["type"] = typeof (T).FullName;
+                return payload;
+            }
+        }
+
+        public void publish<T>(Action<T> configure) where T : new()
+        {
+            var item = new T();
+            configure(item);
+            publish(item);
+        }
+    }
 }
\ No newline at end of file
code/server/Server.cs
@@ -9,7 +9,7 @@ namespace server
 {
     class Server
     {
-        static void Main(string[] args)
+        static void Main()
         {
             try
             {
@@ -46,26 +46,15 @@ namespace server
             Resolve.initialize_with(registry);
 
             builder.Register(x => registry).As<DependencyRegistry>().SingletonScoped();
-            //needs startups
             builder.Register<StartServiceBus>().As<NeedStartup>();
 
-            // infrastructure
-
             var manager = new QueueManager(new IPEndPoint(IPAddress.Loopback, 2200), "server.esent");
             manager.CreateQueues("server");
             builder.Register(x => new RhinoPublisher("client", 2201, manager)).As<ServiceBus>().SingletonScoped();
             builder.Register(x => new RhinoReceiver(manager.GetQueue("server"), x.Resolve<CommandProcessor>())).As<RhinoReceiver>().As<Receiver>().SingletonScoped();
 
-            // commanding
             builder.Register<AsynchronousCommandProcessor>().As<CommandProcessor>().SingletonScoped();
-            builder.Register<StartedApplicationHandler>().As<Handler>();
-
-            // queries
-
-            // repositories
-            //builder.Register<NHibernatePersonRepository>().As<PersonRepository>().FactoryScoped();
-            //builder.Register<NHibernateAccountRepository>().As<AccountRepository>().FactoryScoped();
-
+            builder.Register<RequestHandler>().As<Handler>();
 
             Resolve.the<IEnumerable<NeedStartup>>().each(x => x.run());
             Resolve.the<CommandProcessor>().run();
code/server/server.csproj
@@ -52,7 +52,6 @@
   <ItemGroup>
     <Compile Include="Server.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
-    <Compile Include="StartedApplicationHandler.cs" />
     <Compile Include="StartServiceBus.cs" />
   </ItemGroup>
   <ItemGroup>
code/server/StartedApplicationHandler.cs
@@ -1,13 +0,0 @@
-using common;
-using common.messages;
-
-namespace server
-{
-    public class StartedApplicationHandler : AbstractHandler<StartedApplication>
-    {
-        public override void handle(StartedApplication item)
-        {
-            "received {0}".log(item.message);
-        }
-    }
-}
\ No newline at end of file
code/server/StartServiceBus.cs
@@ -13,13 +13,16 @@ namespace server
             {
                 //using (var unit_of_work = Resolve.the<IUnitOfWorkFactory>().create())
                 //{
-                    handler.handler(x);
-                    //unit_of_work.commit();
+                handler.handler(x);
+                //unit_of_work.commit();
                 //}
             });
             Resolve.the<CommandProcessor>().add(receiver);
-            //ThreadPool.QueueUserWorkItem(x => receiver.run());
-            Resolve.the<ServiceBus>().publish<StartedApplication>(x => x.message = "server");
+            Resolve.the<ServiceBus>().publish<Message>(x =>
+            {
+                x.source = "server";
+                x.message = "ping";
+            });
         }
     }
 }
\ No newline at end of file