Common code to open and close a DocumentConverterServiceClient

Below is the common code used to open and close a DocumentConverterServiceClient:

/// <summary>
/// Configure the bindings and endpoints and open the service using the specified address.
/// </summary>
/// <param name="address">URL of the endpoint.</param>
/// <returns>An instance of the web service.</returns>
public static DocumentConverterServiceClient OpenService(string address)
{
DocumentConverterServiceClient client = null;
try
{
BasicHttpBinding binding = new BasicHttpBinding();
// Use standard Windows security.
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
// Increase the client timeout to deal with (very) long running requests.
binding.SendTimeout = TimeSpan.FromMinutes(120);
binding.ReceiveTimeout = TimeSpan.FromMinutes(120);
// Set the maximum document size to 50MB.
binding.MaxReceivedMessageSize = 50 * 1024 * 1024;
binding.ReaderQuotas.MaxArrayLength = 50 * 1024 * 1024;
binding.ReaderQuotas.MaxStringContentLength = 50 * 1024 * 1024;
EndpointAddress epa = new EndpointAddress(new Uri(address));
client = new DocumentConverterServiceClient(binding, epa);
client.OpenAsync();
return client;
}
catch (Exception)
{
CloseService(client);
throw;
}
}
/// <summary>
/// Check if the client is open and then close it.
/// </summary>
/// <param name="client">The client to close.</param>
public static void CloseService(DocumentConverterServiceClient client)
{
if (client != null && client.State == CommunicationState.Opened)
client.CloseAsync().GetAwaiter().GetResult();
}