Saturday, October 30, 2010

Connection was Unexpectedly Closed

I encountered an issue were a web service was calling a mainframe web service and every other time I would get the following error.

Error: "The underlying connection was closed: A connection that was expected to be kept alive was closed by the server."

As it turned out the mainframe was not setup to keep connections alive. Due to limitations with the mainframe, changing this functionality was not an option. So a simple partial class handled this automatically.

namespace <webservicenamespace> 
{
  public partial class <webserviceproxy> 
  {
    protected override System.Net.WebRequest GetWebRequest(Uri uri) {
      System.Net.HttpWebRequest webRequest = base.GetWebRequest(uri);

      webRequest.KeepAlive = false;

      return webRequest;
    }
  }
}

Saturday, October 2, 2010

Handling Enumerations from a Web Service with Generic Functions

Looking back at some code I ran across a handy piece of code that I wrote to save a good deal of typing, increase maintainability and readability.

Dealing with enumerations from a web service can be confusing at first. The enumeration field names are the same on both sides (client and server) of the web service, however the values are likely not going to be the same. This is especially true if the enumeration is defined with specific values that don't start with 1. The client side will give the enumeration values starting with 1. This means that when saving the value back to a web service object with a property of the enumeration type, you must make sure that the correct enumeration value is returned.

We run into situations where the enumeration value needs to be resolved from enumeration field name and the enumeration field name needs to be resolved from a value. The to just handle this inline can be rather hard to read and requires duplicate typing. Generic functions to the rescue.

Public Shared Function ParseEnum(Of T)(ByVal value As String) As T
    Return CType(System.Enum.Parse(GetType(T), value, True), T)
End Function


Public Function ResolveEnumToValue(Of T)(ByVal value As Object) As String
    Dim genericType As Type = GetType(T)
    Return [Enum].GetName(genericType, value)
End Function