Click or drag to resize

ServiceBusService Class

A service bus for event-based messaging between disjoint systems.
Inheritance Hierarchy
SystemObject
  SystemMarshalByRefObject
    GSF.AdaptersAdapter
      GSF.ServiceModelSelfHostingService
        GSF.ServiceBusServiceBusService

Namespace: GSF.ServiceBus
Assembly: GSF.ServiceBus (in GSF.ServiceBus.dll) Version: 2.4.207-beta
Syntax
[ServiceBehaviorAttribute(InstanceContextMode = InstanceContextMode.Single, UseSynchronizationContext = false)]
public class ServiceBusService : SelfHostingService, 
	IServiceBusService, ISelfHostingService, IAdapter, ISupportLifecycle, IDisposable, 
	IProvideStatus, IPersistSettings
View Source

The ServiceBusService type exposes the following members.

Constructors
 NameDescription
Public methodServiceBusService Initializes a new instance of the ServiceBusService class.
Top
Properties
 NameDescription
Public propertyAllowCrossDomainAccess Gets or sets flag that indicates if web services will enable cross-domain access for Silverlight and Flash applications.
(Inherited from SelfHostingService)
Public propertyAllowedDomainList Gets or sets comma separated list of allowed domains when AllowCrossDomainAccess is true. Use * for domain wildcards, e.g., *.consoto.com.
(Inherited from SelfHostingService)
Public propertyAutomaticFormatSelectionEnabled Gets or sets a value that determines if automatic format selection is enabled for Web HTTP bindings.
(Inherited from SelfHostingService)
Public propertyBufferThreshold Gets or sets the maximum number of Messages that can be buffered for distribution by the ServiceBusService before the the oldest buffered Messages are discarded to keep memory consumption in check by avoiding Message flooding.
Public propertyContractInterface Gets or sets the FullName of the contract interface implemented by the web service.
(Inherited from SelfHostingService)
Public propertyDefaultOutgoingRequestFormat Gets and sets the default outgoing request format for Web HTTP bindings.
(Inherited from SelfHostingService)
Public propertyDefaultOutgoingResponseFormat Gets and sets the default outgoing response format for Web HTTP bindings.
(Inherited from SelfHostingService)
Public propertyDomain Gets the AppDomain in which the Adapter is executing.
(Inherited from Adapter)
Public propertyEnabled Gets or sets a boolean value that indicates whether the ServiceBusService is currently enabled.
(Overrides SelfHostingServiceEnabled)
Public propertyEndpoints Gets or sets a semicolon delimited list of URIs where the web service can be accessed.
(Inherited from SelfHostingService)
Public propertyFaultExceptionEnabled Gets or sets the flag that specifies whether a FaultException is generated when an internal server error(HTTP status code: 500) occurs for Web HTTP bindings.
(Inherited from SelfHostingService)
Public propertyHostFile Gets or sets the path to the file where the Adapter is housed.
(Inherited from Adapter)
Public propertyIsDisposed Gets a flag that indicates whether the object has been disposed.
(Inherited from Adapter)
Public propertyJsonFaultHandlingEnabled Gets or sets a value that determines if JSON formatted fault messages should be returned during exceptions.
(Inherited from SelfHostingService)
Public propertyMemoryUsage Gets the memory utilization of the Adapter in bytes if executing in a separate AppDomain, otherwise NaN.
(Inherited from Adapter)
Public propertyName Gets the unique identifier of the Adapter.
(Inherited from Adapter)
Public propertyPersistSettings Gets or sets a boolean value that indicates whether Adapter settings are to be saved to the config file.
(Inherited from Adapter)
Public propertyProcessingMode Gets or sets the MessageProcessingMode used by the ServiceBusService for processing Message distribution.
Public propertyProcessorUsage Gets the % processor utilization of the Adapter if executing in a separate AppDomain otherwise NaN.
(Inherited from Adapter)
Public propertyPublishMetadata Gets or sets a boolean value that indicates whether web service metadata is to made available at all web service Endpoints.
(Inherited from SelfHostingService)
Public propertySecurityPolicy Gets or sets the FullName of IAuthorizationPolicy to be used for securing all web service Endpoints.
(Inherited from SelfHostingService)
Public propertyServiceEnabled Gets or sets a boolean value that indicates whether the web service is to be enabled at startup.
(Inherited from SelfHostingService)
Public propertyServiceHost Gets the WebServiceHost hosting the web service.
(Inherited from SelfHostingService)
Public propertySettingsCategory Gets or sets the category under which Adapter settings are to be saved to the config file if the PersistSettings property is set to true.
(Inherited from Adapter)
Public propertySingleton Gets or sets a boolean value that indicates whether the ServiceHost will use the current instance of the web service for processing requests or base the web service instance creation on InstanceContextMode specified in its ServiceBehaviorAttribute.
(Inherited from SelfHostingService)
Public propertyStatus Gets the descriptive status of the ServiceBusService.
(Overrides AdapterStatus)
Public propertyTypeName Gets or sets the text representation of the Adapter's TypeName.
(Inherited from Adapter)
Public propertyWindowsAuthentication Gets or sets a boolean value that indicates whether Windows Authentication is to be enabled.
(Inherited from SelfHostingService)
Top
Methods
 NameDescription
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Inherited from MarshalByRefObject)
Public methodDispose Releases all the resources used by the Adapter.
(Inherited from Adapter)
Protected methodDispose(Boolean) Releases the unmanaged resources used by the ServiceBusService object and optionally releases the managed resources.
(Overrides SelfHostingServiceDispose(Boolean))
Public methodEqualsDetermines whether the specified object is equal to the current object.
(Inherited from Object)
Protected methodFinalize Releases the unmanaged resources before the Adapter is reclaimed by GC.
(Inherited from Adapter)
Public methodGetClients Gets a list of all clients connected to the ServiceBusService.
Public methodGetFlashPolicy Gets policy stream for Flash applications.
(Inherited from SelfHostingService)
Public methodGetHashCodeServes as the default hash function.
(Inherited from Object)
Public methodGetLatestMessage Gets the latest Message distributed to the subscribers of the specified topic.
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Public methodGetQueues Gets a list of all Queues registered on the ServiceBusService.
Protected methodGetServiceAddress Gets an address where the ServiceHost will host the service.
(Inherited from SelfHostingService)
Public methodGetSilverlightPolicy Gets policy stream for Silverlight applications.
(Inherited from SelfHostingService)
Public methodGetTopics Gets a list of all Topics registered on the ServiceBusService.
Public methodGetTypeGets the Type of the current instance.
(Inherited from Object)
Protected methodGetUnusedPort Get an unused port number.
(Inherited from SelfHostingService)
Public methodInitialize Initializes the ServiceBusService.
(Overrides SelfHostingServiceInitialize)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Protected methodInitializeServiceHost Initializes the ServiceHost.
(Inherited from SelfHostingService)
Public methodLoadSettings Loads saved ServiceBusService settings from the config file if the PersistSettings property is set to true.
(Overrides SelfHostingServiceLoadSettings)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object.
(Inherited from Object)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object.
(Inherited from MarshalByRefObject)
Protected methodOnDisposed Raises the Disposed event.
(Inherited from Adapter)
Protected methodOnExecutionException Raises the ExecutionException event.
(Inherited from Adapter)
Protected methodOnServiceHostCreated Raises the ServiceHostCreated event.
(Overrides SelfHostingServiceOnServiceHostCreated)
Protected methodOnServiceHostStarted Raises the ServiceHostStarted event.
(Inherited from SelfHostingService)
Protected methodOnServiceProcessException Raises the ServiceProcessException event.
(Inherited from SelfHostingService)
Protected methodOnStatusUpdate Raises the StatusUpdate event.
(Inherited from Adapter)
Public methodPublish Sends the message to the ServiceBusService for distribution amongst its registered consumers.
Public methodRegister Registers with the ServiceBusService to produce or consume Messages.
Public methodSaveSettings Saves ServiceBusService settings to the config file if the PersistSettings property is set to true.
(Overrides SelfHostingServiceSaveSettings)
Public methodToStringReturns a string that represents the current object.
(Inherited from Object)
Public methodUnregister Unregisters a previous registration with the ServiceBusService to produce or consume Messages
Top
Events
 NameDescription
Public eventDisposed Occurs when Adapter is disposed.
(Inherited from Adapter)
Public eventExecutionException Occurs when the IAdapter encounters an Exception during execution.
(Inherited from Adapter)
Public eventServiceHostCreated Occurs when the ServiceHost has been created with the specified Endpoints.
(Inherited from SelfHostingService)
Public eventServiceHostStarted Occurs when the ServiceHost has can process requests via all of its endpoints.
(Inherited from SelfHostingService)
Public eventServiceProcessException Occurs when an Exception is encountered when processing a request.
(Inherited from SelfHostingService)
Public eventStatusUpdate Occurs when the Adapter wants to provide a status update.
(Inherited from Adapter)
Top
Fields
 NameDescription
Public fieldStatic memberDefaultBufferThreshold Specifies the default value for the BufferThreshold property.
Public fieldStatic memberDefaultProcessingMode Specifies the default value for the ProcessingMode property.
Top
Extension Methods
 NameDescription
Public Extension MethodGetEnumValueOrDefault Gets the enumeration constant for value, if defined in the enumeration, or a default value.
(Defined by EnumExtensions)
Public Extension MethodGetEnumValueOrDefaultT Gets the enumeration constant for this value, if defined in the enumeration, or a default value.
(Defined by EnumExtensions)
Top
Example
This example shows how to host ServiceBusService inside a console application:
C#
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Threading;
using GSF;
using GSF.ServiceBus;

class Program
{
    static void Main(string[] args)
    {
        // Prompt for security option.
        Console.Write("Enable security (Y/N): ");
        bool enableSecurity = Console.ReadLine().ParseBoolean();

        // Initialize service bus.
        ServiceBusService service = new ServiceBusService();
        service.Singleton = true;
        service.PublishMetadata = true;
        service.PersistSettings = false;
        service.Endpoints = "http.duplex://localhost:4501; net.tcp://locahost:4502";
        if (enableSecurity)
            service.SecurityPolicy = typeof(ServiceBusSecurityPolicy).FullName;
        service.Initialize();

        // Show service bus status.
        if (service.ServiceHost.State == CommunicationState.Opened)
        {
            Console.WriteLine("\r\n{0} is running:", service.GetType().Name);
            foreach (ServiceEndpoint endpoint in service.ServiceHost.Description.Endpoints)
            {
                Console.WriteLine("- {0} ({1})", endpoint.Address, endpoint.Binding.GetType().Name);
            }

            new Thread(delegate() 
                {
                    while (service.ServiceHost.State == CommunicationState.Opened)
                    {
                        Console.WriteLine();
                        Console.WriteLine();
                        Console.WriteLine("Status of {0}:", service.Name);
                        Console.WriteLine(service.Status);
                        Console.Write("Press Enter key to stop...");

                        Thread.Sleep(5000);
                    }
                }).Start();
        }
        else
        {
            Console.WriteLine("\r\n{0} could not be started", service.GetType().Name);
        }

        // Shutdown.
        Console.ReadLine();
        service.Dispose();
    }
}
This example shows how to host ServiceBusService inside a web application:
C#
<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="categorizedSettings" type="GSF.Configuration.CategorizedSettingsSection, GSF.Core" />
  </configSections>
  <categorizedSettings>
    <serviceBusService>
      <add name="Endpoints" value="" description="Semicolon delimited list of URIs where the web service can be accessed."
        encrypted="false" />
      <add name="Contract" value="GSF.ServiceBus.IServiceBusService, GSF.ServiceBus"
        description="Assembly qualified name of the contract interface implemented by the web service."
        encrypted="false" />
      <add name="Singleton" value="True" description="True if the web service is singleton; otherwise False."
        encrypted="false" />
      <add name="SecurityPolicy" value="" description="Assembly qualified name of the authorization policy to be used for securing the web service."
        encrypted="false" />
      <add name="PublishMetadata" value="True" description="True if the web service metadata is to be published at all the endpoints; otherwise False."
        encrypted="false" />
      <add name="BufferThreshold" value="-1" description="Maximum number of messages that can be queued for distribution before the oldest ones are discarded."
        encrypted="false" />
      <add name="ProcessingMode" value="Sequential" description="Processing mode (Parallel; Sequential) to be used for the distribution of messages."
        encrypted="false" />
    </serviceBusService>
  </categorizedSettings>
  <system.serviceModel>
    <services>
      <service name="GSF.ServiceBus.ServiceBusService">
        <endpoint address="" contract="GSF.ServiceBus.IServiceBusService" binding="wsDualHttpBinding" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true">
      <serviceActivations>
        <add relativeAddress="ServiceBusService.svc" service="GSF.ServiceBus.ServiceBusService, GSF.ServiceBus" />
      </serviceActivations>
    </serviceHostingEnvironment>
  </system.serviceModel>
</configuration>
This example shows how to publish Messages to ServiceBusService:
C#
using System;
using System.ServiceModel;
using System.Threading;

class Program : IServiceBusServiceCallback
{
    static void Main(string[] args)
    {
        // NOTE: Service reference to the service bus service must be added to generate the service proxy.

        // Initialize auto-generated service bus service proxy.
        InstanceContext callbackContext = new InstanceContext(new Program());
        ServiceBusServiceClient serviceBusService = new ServiceBusServiceClient(callbackContext, "NetTcpBinding_IServiceBusService");

        // Create registration request for publishing messages.
        RegistrationRequest registration = new RegistrationRequest();
        registration.MessageType = MessageType.Topic;
        registration.MessageName = "Topic.Frequency";
        registration.RegistrationType = RegistrationType.Produce;
        serviceBusService.Register(registration);

        // Start publishing messages to the bus asynchronously.
        new Thread(delegate() 
            {
                Message message = new Message();
                message.Type = registration.MessageType;
                message.Name = registration.MessageName;
                message.Format = "application/octet-stream";

                Random random = new Random(59);
                while (serviceBusService.State == CommunicationState.Opened)
                {
                    message.Time = DateTime.UtcNow;
                    message.Content = BitConverter.GetBytes(random.Next(61));
                    serviceBusService.Publish(message);

                    Thread.Sleep(5000);
                }
            }).Start();

        // Shutdown.
        Console.Write("Press Enter key to stop...");
        Console.ReadLine();
        serviceBusService.Close();
    }

    public void ProcessMessage(Message message)
    {
        // This method will not be invoked since we are not consuming messages.
        throw new NotSupportedException();
    }
}
This example shows how to subscribe to ServiceBusService for receiving Messages:
C#
using System;
using System.ServiceModel;

class Program : IServiceBusServiceCallback
{
    static void Main(string[] args)
    {
        // NOTE: Service reference to the service bus service must be added to generate the service proxy.

        // Initialize auto-generated service bus service proxy.
        InstanceContext callbackContext = new InstanceContext(new Program());
        ServiceBusServiceClient serviceBusService = new ServiceBusServiceClient(callbackContext, "NetTcpBinding_IServiceBusService");

        // Subscribe with service bus service to receive messages.
        RegistrationRequest registration = new RegistrationRequest();
        registration.MessageType = MessageType.Topic;
        registration.MessageName = "Topic.Frequency";
        registration.RegistrationType = RegistrationType.Consume;
        serviceBusService.Register(registration);

        // Shutdown.
        Console.WriteLine("Press Enter key to stop...");
        Console.WriteLine();
        Console.ReadLine();
        serviceBusService.Close();
    }

    public void ProcessMessage(Message message)
    {
        if (message.Format != "application/octet-stream")
            Console.WriteLine("Message format '{0}' is not supported", message.Format);
        else
            Console.WriteLine("Message received: {0} Hz", BitConverter.ToInt32(message.Content, 0));
    }
}
This example shows how to monitor ServiceBusService remotely:
C#
using System;
using System.ServiceModel;
using System.Threading;
using GSF;

class Program : IServiceBusServiceCallback
{
    static void Main(string[] args)
    {
        // NOTE: Service reference to the service bus service must be added to generate the service proxy.

        // Initialize auto-generated service bus service proxy.
        InstanceContext callbackContext = new InstanceContext(new Program());
        ServiceBusServiceClient serviceBusService = new ServiceBusServiceClient(callbackContext, "NetTcpBinding_IServiceBusService");
        serviceBusService.ChannelFactory.Open();

        // Start querying service bus service status asynchronously.
        new Thread(delegate()
        {
            while (serviceBusService.State == CommunicationState.Opened)
            {
                Console.Clear();
                Console.WriteLine(new string('-', 79));
                Console.WriteLine("|" + "Service Bus Status".CenterText(77) + "|");
                Console.WriteLine(new string('-', 79));
                Console.WriteLine();

                // Show clients.
                Console.Write("Client ID".PadRight(25));
                Console.Write(" ");
                Console.Write("Connected".PadRight(21));
                Console.Write(" ");
                Console.Write("Msg. Produced".PadRight(15));
                Console.Write(" ");
                Console.Write("Msg. Consumed".PadRight(15));
                Console.WriteLine();
                Console.Write(new string('-', 25));
                Console.Write(" ");
                Console.Write(new string('-', 21));
                Console.Write(" ");
                Console.Write(new string('-', 15));
                Console.Write(" ");
                Console.Write(new string('-', 15));
                Console.WriteLine();
                foreach (ClientInfo client in serviceBusService.GetClients())
                {
                    Console.Write(client.SessionId.TruncateRight(25).PadRight(25));
                    Console.Write(" ");
                    Console.Write(client.ConnectedAt.ToString("MM/dd/yy hh:mm:ss tt").PadRight(21));
                    Console.Write(" ");
                    Console.Write(client.MessagesProduced.ToString().PadRight(15));
                    Console.Write(" ");
                    Console.Write(client.MessagesConsumed.ToString().PadRight(15));
                    Console.WriteLine();
                }
                Console.WriteLine();

                // Show queues.
                Console.Write("Queue Name".PadRight(25));
                Console.Write(" ");
                Console.Write("Producers".PadRight(10));
                Console.Write(" ");
                Console.Write("Consumers".PadRight(10));
                Console.Write(" ");
                Console.Write("Msg. Received".PadRight(15));
                Console.Write(" ");
                Console.Write("Msg. Processed".PadRight(15));
                Console.WriteLine();
                Console.Write(new string('-', 25));
                Console.Write(" ");
                Console.Write(new string('-', 10));
                Console.Write(" ");
                Console.Write(new string('-', 10));
                Console.Write(" ");
                Console.Write(new string('-', 15));
                Console.Write(" ");
                Console.Write(new string('-', 15));
                Console.WriteLine();
                foreach (RegistrationInfo queue in serviceBusService.GetQueues())
                {
                    Console.Write(queue.MessageName.PadRight(25));
                    Console.Write(" ");
                    Console.Write(queue.Producers.Length.ToString().PadRight(15));
                    Console.Write(" ");
                    Console.Write(queue.Consumers.Length.ToString().PadRight(15));
                    Console.Write(" ");
                    Console.Write(queue.MessagesReceived.ToString().PadRight(15));
                    Console.Write(" ");
                    Console.Write(queue.MessagesProcessed.ToString().PadRight(15));
                    Console.WriteLine();
                }
                Console.WriteLine();

                // Show topics.
                Console.Write("Topic Name".PadRight(25));
                Console.Write(" ");
                Console.Write("Producers".PadRight(10));
                Console.Write(" ");
                Console.Write("Consumers".PadRight(10));
                Console.Write(" ");
                Console.Write("Msg. Received".PadRight(15));
                Console.Write(" ");
                Console.Write("Msg. Processed".PadRight(15));
                Console.WriteLine();
                Console.Write(new string('-', 25));
                Console.Write(" ");
                Console.Write(new string('-', 10));
                Console.Write(" ");
                Console.Write(new string('-', 10));
                Console.Write(" ");
                Console.Write(new string('-', 15));
                Console.Write(" ");
                Console.Write(new string('-', 15));
                Console.WriteLine();
                foreach (RegistrationInfo topic in serviceBusService.GetTopics())
                {
                    Console.Write(topic.MessageName.PadRight(25));
                    Console.Write(" ");
                    Console.Write(topic.Producers.Length.ToString().PadRight(15));
                    Console.Write(" ");
                    Console.Write(topic.Consumers.Length.ToString().PadRight(15));
                    Console.Write(" ");
                    Console.Write(topic.MessagesReceived.ToString().PadRight(15));
                    Console.Write(" ");
                    Console.Write(topic.MessagesProcessed.ToString().PadRight(15));
                    Console.WriteLine();
                }
                Console.WriteLine();
                Console.Write("Press Enter key to stop...");

                Thread.Sleep(5000);
            }
        }).Start();

        // Shutdown.
        Console.ReadLine();
        serviceBusService.Close();
    }

    public void ProcessMessage(Message message)
    {
        // This method will not be invoked since we are not consuming messages.
        throw new NotSupportedException();
    }
}
See Also