Skip to content
Kévin Lovato edited this page Oct 6, 2015 · 2 revisions

Introduction

In this guide you will see how to create a new service using Zebus.TinyHost. You will create a MakeTeaService which will react when it receives an OrderTeaCommand.

Prerequisites

  • You have pulled the Zebus.TinyHost repository and are able to build the solution

Creating and configuring your first service

  1. Create a new solution TinyHostDemo

  2. Create a new project for your service : MakeTeaService

  3. Add the Zebus NuGet package

  4. Add the Zebus.Directory.Standalone NuGet package

    • Read the Readme and double click on the .exe to start the directory
  5. Add the Abc.Zebus.TinyHost.csproj project to your solution

  6. Reference it in the service project

  7. Create a new Application Configuration File called Abc.Zebus.TinyHost.exe.config

    • Change the property (F4) Copy to Output Directory to Copy if newer
    • Replace its content with:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <appSettings>
    
        <!--IZmqTransportConfiguration-->
        <add key="Bus.InboundEndPoint" value="tcp://*:*"/>
        <add key="Bus.WaitForEndOfStreamAckTimeout" value="00:00:05"/>
    
        <!--IBusConfiguration-->
        <add key="Bus.Directory.EndPoints" value="tcp://localhost:129" />
        <add key="Bus.Directory.RegistrationTimeout" value="00:00:30"/>
        <add key="Bus.Persistence.StartReplayTimeout" value="00:00:30"/>
        <add key="Bus.IsPersistent" value="false"/>
        <add key="Bus.Directory.PickRandom" value="true"/>
    
        <add key="Bus.PeerId" value="MakeTeaService.0" />
        <add key="Bus.Environment" value="Demo" />
    
      </appSettings>
    </configuration>
  8. Create a new Application Configuration File called log4net.config

    • Change the property (F4) BuildAction to Content
    • Change the property (F4) Copy to Output Directory to Copy if newer
    • Replace its content with:
    <?xml version="1.0" encoding="utf-8"?>
    
    <log4net>
      <root>
        <level value="INFO" />
        <appender-ref ref="MainAppender" />
        <appender-ref ref="ConsoleAppender" />
      </root>
    
      <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date{HH:mm:ss.fff} - %-5level - %logger{2} || %message%newline" />
        </layout>
      </appender>
    
      <appender name="MainAppender" type="log4net.Appender.RollingFileAppender">
        <file value="logs\MakeTeaService.0.log" />
        <appendToFile value="true" />
        <rollingStyle value="Composite" />
        <datePattern value=".yyyyMMdd" />
        <maxSizeRollBackups value="5" />
        <maximumFileSize value="100MB" />
        <staticLogFileName value="true" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date - %-5level - %logger || %message%newline" />
        </layout>
      </appender>
      
    </log4net>
  9. Build the whole solution

  10. Change the properties of your MakeTeaService (Alt+Enter when the service is selected)

    • In the Debug tab, check the radio button for "Start external program" and then select the Abc.Zebus.TinyHost.exe file which is in the /bin/Debug directory of your service directory (for the Release configuration, you should select the one in /bin/Release)
  11. Right click on the MakeTeaService project and click on "Set as a startup project"

  12. Run the project

You should now have a correctly configured MakeTeaService, which is able to register itself on the demo directory.

Adding messages

  1. Add a new project to your solution MakeTeaService.Messages

  2. Create two folders

    • Commands
    • Events
  3. Inside the Commands folder, create a new class OrderTeaCommand

    [ProtoContract]
    public class OrderTeaCommand : ICommand
    {
        [ProtoMember(1, IsRequired = true)]
        public int NumberOfCups { get; set; }
    }

Everytime someone wants to order cups of tea he will use this command.

  1. Inside the Events folder, create a new class CupOfTeaPrepared

    [ProtoContract]
    public class CupOfTeaPrepared : IEvent
    {
        
    }

As soon as the service finishes to prepare a cup of tea it will raise this event on the bus.

Handling the command

  1. Inside the MakeTeaService create a Handlers folder

  2. Add a reference to the MakeTeaService.Messages project

  3. In this folder, add a OrderTeaCommandHandler class

    public class OrderTeaCommandHandler : IMessageHandler<OrderTeaCommand>
    {
        private readonly IBus _bus;
    
        public OrderTeaCommandHandler(IBus bus)
        {
            _bus = bus;
        }
    
        public void Handle(OrderTeaCommand message)
        {
            for (int i = 0; i < message.NumberOfCups; i++)
            {
                // Make a cup of tea
                Thread.Sleep(1000);
    
                _bus.Publish(new CupOfTeaPrepared());
            }
        }
    }

This class is responsible doing the work. As you can see, as soon as a cup of tea is finished an event is published on the bus.

Send your command

The MakeTeaService will receive commands from other applications. They can be sent by console applications, Winforms, WPF applications, other services or even from itself! To keep this example simple we will create a console application.

  1. Create a new console application called TeaConsoleClient
  2. Add the Zebus NuGet package
  3. Add a reference to the MakeTeaService.Messages project
  4. Replace your program with :
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Press any key to order 3 cups of tea");
            Console.ReadLine();
    
            var busFactory = new BusFactory().WithScan()
                                             .WithConfiguration("tcp://localhost:129", "Demo")
                                             .WithPeerId("TeaConsoleClient.*");
             
            using (var bus = busFactory.CreateAndStartBus())
            {
                var command = new OrderTeaCommand { NumberOfCups = 3};
                bus.Send(command);
                Console.WriteLine("You ordered {0} cups of tea", command.NumberOfCups);
            }
    
            Console.ReadLine();
        }
    }

Receive the events

You can now test if your service behaves as expected.

  1. Create a new console application called CupOfTeaReceiverConsole

  2. Add the Zebus NuGet package

  3. Add a reference to the MakeTeaService.Messages project

  4. Replace your program by :

        class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Listening if cup of tea are finished");
    
            // Connect to the bus
            var busFactory = new BusFactory().WithScan()
                                             .WithConfiguration("tcp://localhost:129", "Demo")
                                             .WithPeerId("CupOfTeaReceiverConsole.*");
    
            using (var bus = busFactory.CreateAndStartBus())
            {
                Console.ReadLine();
            }
        }
    }
  5. Create a CupOfTeaPreparedHandler class

    public class CupOfTeaPreparedHandler : IMessageHandler<CupOfTeaPrepared>
    {
        public void Handle(CupOfTeaPrepared message)
        {
             Console.WriteLine("A cup of tea is ready !");
        }
    }
  6. Change the solution properties (select the solution and press Alt+Enter)

  • in Common Properties, select Startup Project, check the Multiple Startup projects radio button and change the Action from None to Start for :

    • MakeTeaService
    • TeaConsoleClient
    • CupOfTeaReceiverConsole

When you hit F5 the three applications will start.

Try to press a key on the TeaConsoleClient and you should see the 3 messages displayed on the CupOfTeaReceiverConsole.

Conclusion

This concludes this Getting Started tutorial. We have seen

  • How to create and configure a service using Zebus.TinyHost
  • How to handle commands
  • How to send a command from an application
  • How to receive events