Calling remote API on Windows service OnShutdown event.

  • Thread starter Thread starter Maddy1989
  • Start date Start date
M

Maddy1989

Guest
Hi,

I have a window service which is detecting the device and system status. I need send a signal to remote API stating system has been shutdown by user. For this we can use following approaches:

1. Use windows service OnShutdown event. But when i am using it, it is never called. I have already set CanShutdown= true.

2. Register Pre-shutdown in service constructor then and then call OnCustomCommand event to send signal to API.

My first approach never worked. Please help me call this event in windows service.

Second approach is working after turning off the Fast Startup in power management. But with this approach, i am able to send data to API when it connected to LAN cable. But on WLAN, i am getting exception of remote server not found.

Please help me resolve this issue, so that this could work with both LAN , WLAN or please suggest another way of doing this.

See my code :

public MonSService()
{
FieldInfo acceptedCommandsFieldInfo = typeof(ServiceBase).GetField("acceptedCommands", BindingFlags.Instance | BindingFlags.NonPublic);
if (acceptedCommandsFieldInfo == null)
throw new ApplicationException("acceptedCommands field not found");

int value = (int)acceptedCommandsFieldInfo.GetValue(this);
acceptedCommandsFieldInfo.SetValue(this, value | SERVICE_ACCEPT_PRESHUTDOWN);

InitializeComponent();

}


protected override void OnCustomCommand(int command)
{

Logger.Instance.LogInfo("Custom pre-shutdown hit..");
if (command == SERVICE_CONTROL_PRESHUTDOWN)
{
Logger.Instance.LogInfo("Custom pre-shutdown hit..");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("", "custom pre-shutting down...")
});
try
{
var client = new HttpClient { BaseAddress = new Uri("http://172.30.68.50:9900") };
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");

var response = client.PostAsync("/api/values", content).Result;
}
catch (Exception ex)
{
Logger.Instance.LogError("api hitting..: "+ ex.InnerException);
}
}
}

Continue reading...
 

Similar threads

P
Replies
0
Views
93
Pradeep Kumar Mukherjee
P
V
Replies
0
Views
125
Vamshi K J
V
B
Replies
0
Views
100
BurakGunduz
B
W
Replies
0
Views
74
want 2 Learn
W
Back
Top