Just a quick followup post from my previous entry regarding Azure firewall rules and endpoints.
Starting a Service Sample:
class ServiceMonitor
{
public static bool CheckAndStartService(String ServiceName, int StartTimeOutSeconds)
{
ServiceController mySC = new ServiceController(ServiceName);
if (IsServiceStatusOK(mySC.Status) == false)
{
System.Diagnostics.Trace.WriteLine("Starting Service.....");
try
{
mySC.Start();
}
catch(Exception exc)
{
System.Diagnostics.Trace.WriteLine("Exception Occurred:" + exc.Message);
}
mySC.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, StartTimeOutSeconds));
if (IsServiceStatusOK(mySC.Status))
return true;
else
return false;
}
return true;
}
static private bool IsServiceStatusOK(ServiceControllerStatus Status)
{
if (Status != ServiceControllerStatus.Running && Status != ServiceControllerStatus.StartPending && Status != ServiceControllerStatus.ContinuePending)
{
return false;
}
return true;
}
}
To use this helper class from your worker role:
public override void Run()
{
String ServiceName = "SimpleService";
int ServiceFailCount = 0;
const int MAXFAILS = 5;
while (true)
{
// if the service failed more than 5 times return
if (ServiceFailCount >= MAXFAILS)
{
Trace.TraceError(String.Format(String.Format("{0} has failed to start {1} times", ServiceName, ServiceFailCount)));
return;
}
try
{
// Check if the service is running
if (ServiceMonitor.CheckAndStartService(ServiceName, 10) == true)
{
Trace.TraceInformation("Service is Running");
}
else
{
// if not increment the fail count
ServiceFailCount++;
Trace.TraceError("Service is no longer Running");
}
}
catch (Exception e)
{
Trace.TraceError("Exception occurred: " + e.Message);
}
Thread.Sleep(10000);
}
}
Note: Using the ServiceController class from your worker role requires elevation. So you will need to add the following to your worker role configuration:
This should allow connectivity to the service via whatever internal endpoint you have configured without additional firewall configuration.