Monitor Service Bus Connection Status
A couple customers requested for sample code that would let them monitor the connection status of their service listening on the Windows Azure Service Bus.
Relevant documentation:
- Microsoft.ServiceBus namespace provides ConnectionStatusBehavior class that you can plug in to WCF endpoint behavior. It provides access to the connection status of service listening on the Windows Azure Service Bus. ConnectionStatusBehavior Class - https://msdn.microsoft.com/en-us/library/windowsazure/microsoft.servicebus.connectionstatusbehavior.aspx
Solution:
I've attached the sample that's based on Service Bus Echo Service sample hosting in IIS. In order to run the sample, just input the Service Bus Namespace, IssuerKey/SharedSecretValue attributes in the web.config For more information, check this TechNet article.
Since hosting is in IIS, any changes to the service endpoint would require overriding the default service host creation.
- A custom class deriving from ServiceHostFactory and overriding CreateServiceHost method is what you need. Please see the code below.
…………………
public class CustomSeviceHostFactory: ServiceHostFactory
{
static Random _r = new Random();
static string sSource = "ServiceBusConnecter";
static string sLog = "Application";
static string sEvent = "Sample Event";
public override System.ServiceModel.ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
{
ServiceHostBase hostBase = base.CreateServiceHost(constructorString, baseAddresses);
ConnectionStatusBehavior connectionBehavior = null;
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource,sLog);
foreach (var endpoint in hostBase.Description.Endpoints)
{
connectionBehavior = endpoint.Behaviors.Find<ConnectionStatusBehavior>();
}
connectionBehavior.Connecting += connectionBehavior_Connecting;
connectionBehavior.Online += connectionBehavior_Online;
connectionBehavior.Offline += connectionBehavior_Offline;
return hostBase;
}
void connectionBehavior_Offline(object sender, EventArgs e)
{
EventLog.WriteEntry(sSource,"Service Bus Disconnected");
}
void connectionBehavior_Online(object sender, EventArgs e)
{
Process prc = new Process();
prc = System.Diagnostics.Process.GetCurrentProcess();
EventLog.WriteEntry(sSource,"Connected to Service Bus:" + prc.Id);
}
void connectionBehavior_Connecting(object sender, EventArgs e)
{
EventLog.WriteEntry(sSource, "Connecting to Service Bus Namespace: " + _r.Next().ToString());
}
}
- Finally, don't forget to update the WCF service markup to reflect the overriding of service host factory.
<%@ ServiceHost Language="C#" Debug="true" Service="ServiceBusOnIIS.EchoService" Factory="ServiceBusOnIIS.CustomSeviceHostFactory"%>