public static void CloseAfariaServiceDevice(DevicesServiceClient svcDevice) { try { if (svcDevice != null) { // Get the state of the service System.ServiceModel.CommunicationState commState = svcDevice.State; // If the service is faulted, we still need to abort if (commState == System.ServiceModel.CommunicationState.Faulted) { svcDevice.Abort(); } // If the state is not already closed or in the process of closing, we should close the context else if (commState != System.ServiceModel.CommunicationState.Closing || commState != System.ServiceModel.CommunicationState.Closed) { // Get the context info to get the context ID, although we saved this in the context string variable Devices.ContextInfo ci = svcDevice.GetContextInfo(); // Assure that there is a valid context ID if (!string.IsNullOrWhiteSpace(ci.ContextId)) { // Close the context svcDevice.CloseContext(); } // Now close the service svcDevice.Close(); } // If the channel is closing/closed, attempt to close out the context, but don't need to close state else { // We will likely throw an exception here. svcDevice.CloseContext(); } svcDevice = null; } } catch (Exception ex) { // Just ouput the exception, proper handling should initiate a new service, initiate the context to the previous, // and then close out the context and service Console.WriteLine(ex.Message.ToString()); logger.Error("Error while closing Device service", ex); } }
public static DevicesServiceClient GetAfariaServiceDevices(Dictionary<string, string> server, Dictionary<string, string> credentials) { string devicesApiAddr = String.Format("net.tcp://{0}:{1}/AfariaService/{2}", server["IPAddr"], server["Port"], "Devices"); DevicesServiceClient svcDevice = new DevicesServiceClient("NetTcpBinding_IDevicesService", devicesApiAddr); svcDevice.ClientCredentials.Windows.ClientCredential.Domain = credentials["Domain"]; svcDevice.ClientCredentials.Windows.ClientCredential.UserName = credentials["UserName"]; svcDevice.ClientCredentials.Windows.ClientCredential.Password = credentials["Password"]; logger.Info("Creating Devices service: {0}", devicesApiAddr); return svcDevice; }