Refactoring advice across multiple WCF Service with boilerplate error handling
$begingroup$
I have several (12) WCF services which are structured like this:
I have inherited a very large 10-year-old project, I've introduced some inheritance so that I can have 1 echo method where I can control the timeout and not have duplicate code everywhere.
The PostalAddressFinderServiceService (Shittly named I appreciate) is the autogenerated WCF class locally, this GetWebRequest method is overridden in all the WVF service that I have - the AddressFinderService is a smaller service so I want to analyse that, all the other service follow the exact same pattern but I will omit them for brevity.
public class LocalAddressFinderServerService : PostalAddressFinderServiceService, IWrapAutoGenService
{
/// <summary>
/// Get the web request
/// </summary>
/// <remarks>
/// In some cases the first call to the web service works just fine,
/// but if in the following few minutes no new call to the web service is made,
/// the next call would throw the exception shown above.
/// This problem could be solved by altering the generated proxy class;
/// in the GetWebRequest function the KeepAlive property must be set to false
/// see http://weblogs.asp.net/jan/archive/2004/01/28/63771.aspx
/// </remarks>
/// <param name="uri">The uri</param>
/// <returns>The web request</returns>
protected override WebRequest GetWebRequest(Uri uri)
{
var webRequest = (HttpWebRequest) base.GetWebRequest(uri);
webRequest.KeepAlive = false;
if (Globals.CompressResponse == true)
{
webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
return webRequest;
}
}
This local service is consumed by the generic wrapper that pulls in the abstract "ServiceWrapper" class.
/// <summary>
/// A class to represent the service for the address finder
/// </summary>
public class AddressServiceWrapper : ServiceWrapper<LocalAddressFinderServerService>
{
/// <summary>
/// The single instance of the address service
/// </summary>
public static readonly AddressServiceWrapper Service = new AddressServiceWrapper();
/// <summary>
/// Prevents a default instance of the <see cref="AddressServiceWrapper" /> class from being created
/// </summary>
private AddressServiceWrapper()
{
}
protected override LocalAddressFinderServerService AppWebService
{
get
{
if (_webService == null)
{
_webService = base.AppWebService;
_webService.findAddressCompleted += PAFFindAddressCompleted;
}
return _webService;
}
}
/// <summary>
/// Gets the display name for the web service
/// </summary>
public override string DisplayName => "Address Finder Service";
/// <summary>
/// Gets the service reference string this is used within
/// the <see cref="ServiceURLs" /> settings file
/// </summary>
public override string RefString => "Address_Finder";
/// <summary>
/// The find address completed event
/// </summary>
public event findAddressCompletedEventHandler FindAddressCompleted;
/// <summary>
/// Attempt an address search
/// </summary>
/// <param name="request">The request parameters</param>
/// <param name="user">The logged in user</param>
public void BeginSearch(FindAddressRequest request, User user)
{
try
{
AppWebService.findAddressAsync(user.ToServiceType(), request.ToServiceType());
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
}
/// <summary>
/// Format a single address into name value pairs
/// </summary>
/// <param name="request">The format address request</param>
/// <param name="user">The logged in user</param>
/// <returns>The format address response</returns>
public FormatAddressRes FormatAddress(FormatAddressReq request, ServiceClient.askPAF.User user)
{
try
{
return AppWebService.formatAddress(user, request);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
}
/// <summary>
/// Get a list of selection criteria and filters
/// </summary>
/// <param name="user">The logged in user</param>
/// <param name="findType">The name of the selection choices being populated</param>
/// <returns>The selection criteria</returns>
public FindResponse GetFind(User user, string findType)
{
try
{
return new FindResponse(AppWebService.getFind(user.ToServiceType(), findType));
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
}
/// <summary>
/// Login to the postal address finder service
/// </summary>
/// <param name="request">The login request</param>
/// <returns>The login response</returns>
public LoginResponse Login(LoginRequest request)
{
return new LoginResponse(CallServiceSafely(AppWebService.login, request.ToServiceType()));
}
/// <summary>
/// Handle the find address completed event
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void PAFFindAddressCompleted(object sender, findAddressCompletedEventArgs e)
{
if (!e.Cancelled && FindAddressCompleted != null)
{
FindAddressCompleted(sender, e);
}
}
}
As you can see there is a TON of duplicate try catch code. This makes the classes quite bloated and this is the smallest one. The largest one is north of 15,000 lines of repeated try, method pass through and catch. I've applied the refactoring to the Login method of the previous class to show the reduction in code.
This is the abstract, generic class I have inserted so I have somewhere to introduce common logic. I've put in the "CallServiceSafely" methods that take "Funcs" and "Actions".
public abstract class ServiceWrapper<S> : IService
where S : IWrapAutoGenService, new()
{
/// <summary>
/// The local web service
/// </summary>
protected static S _webService;
/// <summary>
/// Gets the reference to the web service
/// </summary>
protected virtual S AppWebService
{
get
{
if (_webService == null)
{
_webService = new S {Timeout = 100000};
if (URL != null)
{
_webService.Url = URL;
}
}
return _webService;
}
}
/// <summary>
/// Gets the display name for the web service
/// </summary>
public abstract string DisplayName { get; }
/// <summary>
/// Send an echo request to the server to test
/// the availability of the service
/// </summary>
/// <param name="echo">The text to send</param>
/// <returns>The text returned by the service</returns>
public virtual string Echo(string echo)
{
var originalTimeOut = AppWebService.Timeout;
AppWebService.Timeout = 5000;
var result = CallServiceSafely(AppWebService.echo, echo);
AppWebService.Timeout = originalTimeOut;
return result;
}
protected void CallServiceSafely(Action serviceMethod)
{
try
{
serviceMethod.Invoke();
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T>(Action<T> serviceMethod,T firstParam)
{
try
{
serviceMethod.Invoke(firstParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T, TU>(Action<T, TU> serviceMethod,T firstParam, TU secondParam)
{
try
{
serviceMethod.Invoke(firstParam, secondParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T, TU, TV>(Action<T, TU, TV> serviceMethod,T firstParam, TU secondParam, TV thirdParam)
{
try
{
serviceMethod.Invoke(firstParam, secondParam, thirdParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T, TU, TV, TX>(Action<T, TU, TV, TX> serviceMethod,T firstParam, TU secondParam, TV thirdParam, TX fourthParam)
{
try
{
serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TR>(Func<TU, TR> serviceMethod, TU firstParam)
{
try
{
return serviceMethod.Invoke(firstParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TR>(Func<TU, TA, TR> serviceMethod, TU firstParam, TA secondParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TV, TR>(Func<TU, TA, TV, TR> serviceMethod, TU firstParam, TA secondParam, TV thirdParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam, thirdParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TV,TX, TR>(Func<TU, TA, TV, TX, TR> serviceMethod, TU firstParam, TA secondParam, TV thirdParam, TX fourthParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TV,TX,TY, TR>(Func<TU, TA, TV, TX, TY, TR> serviceMethod, TU firstParam, TA secondParam, TV thirdParam, TX fourthParam, TY fifthParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam, fifthParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
/// <summary>
/// Create an error description from the WCF FaultException
/// It may need further fixed after more implementations of WCF as is only currently used for the document printing
/// </summary>
/// <param name="ex"></param>
/// <returns></returns>
private static ErrorDescription CreateErrorDescriptionInstance(FaultException ex)
{
if (ex.Reason.ToString().IndexOf((char)255) != -1)
{
string elements = ex.Reason.ToString().Split((char)255);
ErrorDescription errorDescription = new ErrorDescription(elements[3], elements[1], elements[2], elements[0]);
return errorDescription;
}
string severity = ex.Reason.ToString();
string reason = ex.Reason.ToString();
string message = ex.Message;
object details = ex.StackTrace;
ErrorDescription errorDesc = new ErrorDescription(severity, reason, message, details);
return errorDesc;
}
/// <summary>
/// Gets or sets a value indicating whether the service is
/// available
/// </summary>
public bool ServiceAvailable { get; set; }
/// <summary>
/// Gets or sets the url of the service
/// </summary>
public string URL { get; set; }
public abstract string RefString { get; }
/// <summary>
/// Clear data cached in the service
/// </summary>
public virtual void ClearCachedData()
{
}
}
public interface IService
{
string DisplayName { get; }
bool ServiceAvailable { get; set; }
string URL { get; set; }
string RefString { get; } //Uid for the Iservice, used in Esprit as the name of the setting that contains the url for the service
string Echo(string @string);
//Used to clear the cached user on logoff
//this is done within EspritServiceStateController for each module
void ClearCachedData();
}
The ServiceWrapped class now contains many CallWebServiceSafely methods. Is there a way I can have one block of try catch code or will I have to maintain all the blocks as I have now?
Final interface for completeness.
/// <summary>
/// Provides access to autogenerated WSDL services that allow you to "Echo" them to check for their
/// prescence
/// </summary>
public interface IWrapAutoGenService
{
int Timeout { get; set; }
string Url { get; set; }
//It needs to be lower case as that is what the wsdl presents to us.
// ReSharper disable once InconsistentNaming
string echo(string echo);
}
Sorry for the wall of text, thanks for getting through it all.
c# wcf
$endgroup$
add a comment |
$begingroup$
I have several (12) WCF services which are structured like this:
I have inherited a very large 10-year-old project, I've introduced some inheritance so that I can have 1 echo method where I can control the timeout and not have duplicate code everywhere.
The PostalAddressFinderServiceService (Shittly named I appreciate) is the autogenerated WCF class locally, this GetWebRequest method is overridden in all the WVF service that I have - the AddressFinderService is a smaller service so I want to analyse that, all the other service follow the exact same pattern but I will omit them for brevity.
public class LocalAddressFinderServerService : PostalAddressFinderServiceService, IWrapAutoGenService
{
/// <summary>
/// Get the web request
/// </summary>
/// <remarks>
/// In some cases the first call to the web service works just fine,
/// but if in the following few minutes no new call to the web service is made,
/// the next call would throw the exception shown above.
/// This problem could be solved by altering the generated proxy class;
/// in the GetWebRequest function the KeepAlive property must be set to false
/// see http://weblogs.asp.net/jan/archive/2004/01/28/63771.aspx
/// </remarks>
/// <param name="uri">The uri</param>
/// <returns>The web request</returns>
protected override WebRequest GetWebRequest(Uri uri)
{
var webRequest = (HttpWebRequest) base.GetWebRequest(uri);
webRequest.KeepAlive = false;
if (Globals.CompressResponse == true)
{
webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
return webRequest;
}
}
This local service is consumed by the generic wrapper that pulls in the abstract "ServiceWrapper" class.
/// <summary>
/// A class to represent the service for the address finder
/// </summary>
public class AddressServiceWrapper : ServiceWrapper<LocalAddressFinderServerService>
{
/// <summary>
/// The single instance of the address service
/// </summary>
public static readonly AddressServiceWrapper Service = new AddressServiceWrapper();
/// <summary>
/// Prevents a default instance of the <see cref="AddressServiceWrapper" /> class from being created
/// </summary>
private AddressServiceWrapper()
{
}
protected override LocalAddressFinderServerService AppWebService
{
get
{
if (_webService == null)
{
_webService = base.AppWebService;
_webService.findAddressCompleted += PAFFindAddressCompleted;
}
return _webService;
}
}
/// <summary>
/// Gets the display name for the web service
/// </summary>
public override string DisplayName => "Address Finder Service";
/// <summary>
/// Gets the service reference string this is used within
/// the <see cref="ServiceURLs" /> settings file
/// </summary>
public override string RefString => "Address_Finder";
/// <summary>
/// The find address completed event
/// </summary>
public event findAddressCompletedEventHandler FindAddressCompleted;
/// <summary>
/// Attempt an address search
/// </summary>
/// <param name="request">The request parameters</param>
/// <param name="user">The logged in user</param>
public void BeginSearch(FindAddressRequest request, User user)
{
try
{
AppWebService.findAddressAsync(user.ToServiceType(), request.ToServiceType());
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
}
/// <summary>
/// Format a single address into name value pairs
/// </summary>
/// <param name="request">The format address request</param>
/// <param name="user">The logged in user</param>
/// <returns>The format address response</returns>
public FormatAddressRes FormatAddress(FormatAddressReq request, ServiceClient.askPAF.User user)
{
try
{
return AppWebService.formatAddress(user, request);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
}
/// <summary>
/// Get a list of selection criteria and filters
/// </summary>
/// <param name="user">The logged in user</param>
/// <param name="findType">The name of the selection choices being populated</param>
/// <returns>The selection criteria</returns>
public FindResponse GetFind(User user, string findType)
{
try
{
return new FindResponse(AppWebService.getFind(user.ToServiceType(), findType));
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
}
/// <summary>
/// Login to the postal address finder service
/// </summary>
/// <param name="request">The login request</param>
/// <returns>The login response</returns>
public LoginResponse Login(LoginRequest request)
{
return new LoginResponse(CallServiceSafely(AppWebService.login, request.ToServiceType()));
}
/// <summary>
/// Handle the find address completed event
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void PAFFindAddressCompleted(object sender, findAddressCompletedEventArgs e)
{
if (!e.Cancelled && FindAddressCompleted != null)
{
FindAddressCompleted(sender, e);
}
}
}
As you can see there is a TON of duplicate try catch code. This makes the classes quite bloated and this is the smallest one. The largest one is north of 15,000 lines of repeated try, method pass through and catch. I've applied the refactoring to the Login method of the previous class to show the reduction in code.
This is the abstract, generic class I have inserted so I have somewhere to introduce common logic. I've put in the "CallServiceSafely" methods that take "Funcs" and "Actions".
public abstract class ServiceWrapper<S> : IService
where S : IWrapAutoGenService, new()
{
/// <summary>
/// The local web service
/// </summary>
protected static S _webService;
/// <summary>
/// Gets the reference to the web service
/// </summary>
protected virtual S AppWebService
{
get
{
if (_webService == null)
{
_webService = new S {Timeout = 100000};
if (URL != null)
{
_webService.Url = URL;
}
}
return _webService;
}
}
/// <summary>
/// Gets the display name for the web service
/// </summary>
public abstract string DisplayName { get; }
/// <summary>
/// Send an echo request to the server to test
/// the availability of the service
/// </summary>
/// <param name="echo">The text to send</param>
/// <returns>The text returned by the service</returns>
public virtual string Echo(string echo)
{
var originalTimeOut = AppWebService.Timeout;
AppWebService.Timeout = 5000;
var result = CallServiceSafely(AppWebService.echo, echo);
AppWebService.Timeout = originalTimeOut;
return result;
}
protected void CallServiceSafely(Action serviceMethod)
{
try
{
serviceMethod.Invoke();
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T>(Action<T> serviceMethod,T firstParam)
{
try
{
serviceMethod.Invoke(firstParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T, TU>(Action<T, TU> serviceMethod,T firstParam, TU secondParam)
{
try
{
serviceMethod.Invoke(firstParam, secondParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T, TU, TV>(Action<T, TU, TV> serviceMethod,T firstParam, TU secondParam, TV thirdParam)
{
try
{
serviceMethod.Invoke(firstParam, secondParam, thirdParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T, TU, TV, TX>(Action<T, TU, TV, TX> serviceMethod,T firstParam, TU secondParam, TV thirdParam, TX fourthParam)
{
try
{
serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TR>(Func<TU, TR> serviceMethod, TU firstParam)
{
try
{
return serviceMethod.Invoke(firstParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TR>(Func<TU, TA, TR> serviceMethod, TU firstParam, TA secondParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TV, TR>(Func<TU, TA, TV, TR> serviceMethod, TU firstParam, TA secondParam, TV thirdParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam, thirdParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TV,TX, TR>(Func<TU, TA, TV, TX, TR> serviceMethod, TU firstParam, TA secondParam, TV thirdParam, TX fourthParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TV,TX,TY, TR>(Func<TU, TA, TV, TX, TY, TR> serviceMethod, TU firstParam, TA secondParam, TV thirdParam, TX fourthParam, TY fifthParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam, fifthParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
/// <summary>
/// Create an error description from the WCF FaultException
/// It may need further fixed after more implementations of WCF as is only currently used for the document printing
/// </summary>
/// <param name="ex"></param>
/// <returns></returns>
private static ErrorDescription CreateErrorDescriptionInstance(FaultException ex)
{
if (ex.Reason.ToString().IndexOf((char)255) != -1)
{
string elements = ex.Reason.ToString().Split((char)255);
ErrorDescription errorDescription = new ErrorDescription(elements[3], elements[1], elements[2], elements[0]);
return errorDescription;
}
string severity = ex.Reason.ToString();
string reason = ex.Reason.ToString();
string message = ex.Message;
object details = ex.StackTrace;
ErrorDescription errorDesc = new ErrorDescription(severity, reason, message, details);
return errorDesc;
}
/// <summary>
/// Gets or sets a value indicating whether the service is
/// available
/// </summary>
public bool ServiceAvailable { get; set; }
/// <summary>
/// Gets or sets the url of the service
/// </summary>
public string URL { get; set; }
public abstract string RefString { get; }
/// <summary>
/// Clear data cached in the service
/// </summary>
public virtual void ClearCachedData()
{
}
}
public interface IService
{
string DisplayName { get; }
bool ServiceAvailable { get; set; }
string URL { get; set; }
string RefString { get; } //Uid for the Iservice, used in Esprit as the name of the setting that contains the url for the service
string Echo(string @string);
//Used to clear the cached user on logoff
//this is done within EspritServiceStateController for each module
void ClearCachedData();
}
The ServiceWrapped class now contains many CallWebServiceSafely methods. Is there a way I can have one block of try catch code or will I have to maintain all the blocks as I have now?
Final interface for completeness.
/// <summary>
/// Provides access to autogenerated WSDL services that allow you to "Echo" them to check for their
/// prescence
/// </summary>
public interface IWrapAutoGenService
{
int Timeout { get; set; }
string Url { get; set; }
//It needs to be lower case as that is what the wsdl presents to us.
// ReSharper disable once InconsistentNaming
string echo(string echo);
}
Sorry for the wall of text, thanks for getting through it all.
c# wcf
$endgroup$
add a comment |
$begingroup$
I have several (12) WCF services which are structured like this:
I have inherited a very large 10-year-old project, I've introduced some inheritance so that I can have 1 echo method where I can control the timeout and not have duplicate code everywhere.
The PostalAddressFinderServiceService (Shittly named I appreciate) is the autogenerated WCF class locally, this GetWebRequest method is overridden in all the WVF service that I have - the AddressFinderService is a smaller service so I want to analyse that, all the other service follow the exact same pattern but I will omit them for brevity.
public class LocalAddressFinderServerService : PostalAddressFinderServiceService, IWrapAutoGenService
{
/// <summary>
/// Get the web request
/// </summary>
/// <remarks>
/// In some cases the first call to the web service works just fine,
/// but if in the following few minutes no new call to the web service is made,
/// the next call would throw the exception shown above.
/// This problem could be solved by altering the generated proxy class;
/// in the GetWebRequest function the KeepAlive property must be set to false
/// see http://weblogs.asp.net/jan/archive/2004/01/28/63771.aspx
/// </remarks>
/// <param name="uri">The uri</param>
/// <returns>The web request</returns>
protected override WebRequest GetWebRequest(Uri uri)
{
var webRequest = (HttpWebRequest) base.GetWebRequest(uri);
webRequest.KeepAlive = false;
if (Globals.CompressResponse == true)
{
webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
return webRequest;
}
}
This local service is consumed by the generic wrapper that pulls in the abstract "ServiceWrapper" class.
/// <summary>
/// A class to represent the service for the address finder
/// </summary>
public class AddressServiceWrapper : ServiceWrapper<LocalAddressFinderServerService>
{
/// <summary>
/// The single instance of the address service
/// </summary>
public static readonly AddressServiceWrapper Service = new AddressServiceWrapper();
/// <summary>
/// Prevents a default instance of the <see cref="AddressServiceWrapper" /> class from being created
/// </summary>
private AddressServiceWrapper()
{
}
protected override LocalAddressFinderServerService AppWebService
{
get
{
if (_webService == null)
{
_webService = base.AppWebService;
_webService.findAddressCompleted += PAFFindAddressCompleted;
}
return _webService;
}
}
/// <summary>
/// Gets the display name for the web service
/// </summary>
public override string DisplayName => "Address Finder Service";
/// <summary>
/// Gets the service reference string this is used within
/// the <see cref="ServiceURLs" /> settings file
/// </summary>
public override string RefString => "Address_Finder";
/// <summary>
/// The find address completed event
/// </summary>
public event findAddressCompletedEventHandler FindAddressCompleted;
/// <summary>
/// Attempt an address search
/// </summary>
/// <param name="request">The request parameters</param>
/// <param name="user">The logged in user</param>
public void BeginSearch(FindAddressRequest request, User user)
{
try
{
AppWebService.findAddressAsync(user.ToServiceType(), request.ToServiceType());
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
}
/// <summary>
/// Format a single address into name value pairs
/// </summary>
/// <param name="request">The format address request</param>
/// <param name="user">The logged in user</param>
/// <returns>The format address response</returns>
public FormatAddressRes FormatAddress(FormatAddressReq request, ServiceClient.askPAF.User user)
{
try
{
return AppWebService.formatAddress(user, request);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
}
/// <summary>
/// Get a list of selection criteria and filters
/// </summary>
/// <param name="user">The logged in user</param>
/// <param name="findType">The name of the selection choices being populated</param>
/// <returns>The selection criteria</returns>
public FindResponse GetFind(User user, string findType)
{
try
{
return new FindResponse(AppWebService.getFind(user.ToServiceType(), findType));
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
}
/// <summary>
/// Login to the postal address finder service
/// </summary>
/// <param name="request">The login request</param>
/// <returns>The login response</returns>
public LoginResponse Login(LoginRequest request)
{
return new LoginResponse(CallServiceSafely(AppWebService.login, request.ToServiceType()));
}
/// <summary>
/// Handle the find address completed event
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void PAFFindAddressCompleted(object sender, findAddressCompletedEventArgs e)
{
if (!e.Cancelled && FindAddressCompleted != null)
{
FindAddressCompleted(sender, e);
}
}
}
As you can see there is a TON of duplicate try catch code. This makes the classes quite bloated and this is the smallest one. The largest one is north of 15,000 lines of repeated try, method pass through and catch. I've applied the refactoring to the Login method of the previous class to show the reduction in code.
This is the abstract, generic class I have inserted so I have somewhere to introduce common logic. I've put in the "CallServiceSafely" methods that take "Funcs" and "Actions".
public abstract class ServiceWrapper<S> : IService
where S : IWrapAutoGenService, new()
{
/// <summary>
/// The local web service
/// </summary>
protected static S _webService;
/// <summary>
/// Gets the reference to the web service
/// </summary>
protected virtual S AppWebService
{
get
{
if (_webService == null)
{
_webService = new S {Timeout = 100000};
if (URL != null)
{
_webService.Url = URL;
}
}
return _webService;
}
}
/// <summary>
/// Gets the display name for the web service
/// </summary>
public abstract string DisplayName { get; }
/// <summary>
/// Send an echo request to the server to test
/// the availability of the service
/// </summary>
/// <param name="echo">The text to send</param>
/// <returns>The text returned by the service</returns>
public virtual string Echo(string echo)
{
var originalTimeOut = AppWebService.Timeout;
AppWebService.Timeout = 5000;
var result = CallServiceSafely(AppWebService.echo, echo);
AppWebService.Timeout = originalTimeOut;
return result;
}
protected void CallServiceSafely(Action serviceMethod)
{
try
{
serviceMethod.Invoke();
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T>(Action<T> serviceMethod,T firstParam)
{
try
{
serviceMethod.Invoke(firstParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T, TU>(Action<T, TU> serviceMethod,T firstParam, TU secondParam)
{
try
{
serviceMethod.Invoke(firstParam, secondParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T, TU, TV>(Action<T, TU, TV> serviceMethod,T firstParam, TU secondParam, TV thirdParam)
{
try
{
serviceMethod.Invoke(firstParam, secondParam, thirdParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T, TU, TV, TX>(Action<T, TU, TV, TX> serviceMethod,T firstParam, TU secondParam, TV thirdParam, TX fourthParam)
{
try
{
serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TR>(Func<TU, TR> serviceMethod, TU firstParam)
{
try
{
return serviceMethod.Invoke(firstParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TR>(Func<TU, TA, TR> serviceMethod, TU firstParam, TA secondParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TV, TR>(Func<TU, TA, TV, TR> serviceMethod, TU firstParam, TA secondParam, TV thirdParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam, thirdParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TV,TX, TR>(Func<TU, TA, TV, TX, TR> serviceMethod, TU firstParam, TA secondParam, TV thirdParam, TX fourthParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TV,TX,TY, TR>(Func<TU, TA, TV, TX, TY, TR> serviceMethod, TU firstParam, TA secondParam, TV thirdParam, TX fourthParam, TY fifthParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam, fifthParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
/// <summary>
/// Create an error description from the WCF FaultException
/// It may need further fixed after more implementations of WCF as is only currently used for the document printing
/// </summary>
/// <param name="ex"></param>
/// <returns></returns>
private static ErrorDescription CreateErrorDescriptionInstance(FaultException ex)
{
if (ex.Reason.ToString().IndexOf((char)255) != -1)
{
string elements = ex.Reason.ToString().Split((char)255);
ErrorDescription errorDescription = new ErrorDescription(elements[3], elements[1], elements[2], elements[0]);
return errorDescription;
}
string severity = ex.Reason.ToString();
string reason = ex.Reason.ToString();
string message = ex.Message;
object details = ex.StackTrace;
ErrorDescription errorDesc = new ErrorDescription(severity, reason, message, details);
return errorDesc;
}
/// <summary>
/// Gets or sets a value indicating whether the service is
/// available
/// </summary>
public bool ServiceAvailable { get; set; }
/// <summary>
/// Gets or sets the url of the service
/// </summary>
public string URL { get; set; }
public abstract string RefString { get; }
/// <summary>
/// Clear data cached in the service
/// </summary>
public virtual void ClearCachedData()
{
}
}
public interface IService
{
string DisplayName { get; }
bool ServiceAvailable { get; set; }
string URL { get; set; }
string RefString { get; } //Uid for the Iservice, used in Esprit as the name of the setting that contains the url for the service
string Echo(string @string);
//Used to clear the cached user on logoff
//this is done within EspritServiceStateController for each module
void ClearCachedData();
}
The ServiceWrapped class now contains many CallWebServiceSafely methods. Is there a way I can have one block of try catch code or will I have to maintain all the blocks as I have now?
Final interface for completeness.
/// <summary>
/// Provides access to autogenerated WSDL services that allow you to "Echo" them to check for their
/// prescence
/// </summary>
public interface IWrapAutoGenService
{
int Timeout { get; set; }
string Url { get; set; }
//It needs to be lower case as that is what the wsdl presents to us.
// ReSharper disable once InconsistentNaming
string echo(string echo);
}
Sorry for the wall of text, thanks for getting through it all.
c# wcf
$endgroup$
I have several (12) WCF services which are structured like this:
I have inherited a very large 10-year-old project, I've introduced some inheritance so that I can have 1 echo method where I can control the timeout and not have duplicate code everywhere.
The PostalAddressFinderServiceService (Shittly named I appreciate) is the autogenerated WCF class locally, this GetWebRequest method is overridden in all the WVF service that I have - the AddressFinderService is a smaller service so I want to analyse that, all the other service follow the exact same pattern but I will omit them for brevity.
public class LocalAddressFinderServerService : PostalAddressFinderServiceService, IWrapAutoGenService
{
/// <summary>
/// Get the web request
/// </summary>
/// <remarks>
/// In some cases the first call to the web service works just fine,
/// but if in the following few minutes no new call to the web service is made,
/// the next call would throw the exception shown above.
/// This problem could be solved by altering the generated proxy class;
/// in the GetWebRequest function the KeepAlive property must be set to false
/// see http://weblogs.asp.net/jan/archive/2004/01/28/63771.aspx
/// </remarks>
/// <param name="uri">The uri</param>
/// <returns>The web request</returns>
protected override WebRequest GetWebRequest(Uri uri)
{
var webRequest = (HttpWebRequest) base.GetWebRequest(uri);
webRequest.KeepAlive = false;
if (Globals.CompressResponse == true)
{
webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
return webRequest;
}
}
This local service is consumed by the generic wrapper that pulls in the abstract "ServiceWrapper" class.
/// <summary>
/// A class to represent the service for the address finder
/// </summary>
public class AddressServiceWrapper : ServiceWrapper<LocalAddressFinderServerService>
{
/// <summary>
/// The single instance of the address service
/// </summary>
public static readonly AddressServiceWrapper Service = new AddressServiceWrapper();
/// <summary>
/// Prevents a default instance of the <see cref="AddressServiceWrapper" /> class from being created
/// </summary>
private AddressServiceWrapper()
{
}
protected override LocalAddressFinderServerService AppWebService
{
get
{
if (_webService == null)
{
_webService = base.AppWebService;
_webService.findAddressCompleted += PAFFindAddressCompleted;
}
return _webService;
}
}
/// <summary>
/// Gets the display name for the web service
/// </summary>
public override string DisplayName => "Address Finder Service";
/// <summary>
/// Gets the service reference string this is used within
/// the <see cref="ServiceURLs" /> settings file
/// </summary>
public override string RefString => "Address_Finder";
/// <summary>
/// The find address completed event
/// </summary>
public event findAddressCompletedEventHandler FindAddressCompleted;
/// <summary>
/// Attempt an address search
/// </summary>
/// <param name="request">The request parameters</param>
/// <param name="user">The logged in user</param>
public void BeginSearch(FindAddressRequest request, User user)
{
try
{
AppWebService.findAddressAsync(user.ToServiceType(), request.ToServiceType());
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
}
/// <summary>
/// Format a single address into name value pairs
/// </summary>
/// <param name="request">The format address request</param>
/// <param name="user">The logged in user</param>
/// <returns>The format address response</returns>
public FormatAddressRes FormatAddress(FormatAddressReq request, ServiceClient.askPAF.User user)
{
try
{
return AppWebService.formatAddress(user, request);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
}
/// <summary>
/// Get a list of selection criteria and filters
/// </summary>
/// <param name="user">The logged in user</param>
/// <param name="findType">The name of the selection choices being populated</param>
/// <returns>The selection criteria</returns>
public FindResponse GetFind(User user, string findType)
{
try
{
return new FindResponse(AppWebService.getFind(user.ToServiceType(), findType));
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
}
/// <summary>
/// Login to the postal address finder service
/// </summary>
/// <param name="request">The login request</param>
/// <returns>The login response</returns>
public LoginResponse Login(LoginRequest request)
{
return new LoginResponse(CallServiceSafely(AppWebService.login, request.ToServiceType()));
}
/// <summary>
/// Handle the find address completed event
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void PAFFindAddressCompleted(object sender, findAddressCompletedEventArgs e)
{
if (!e.Cancelled && FindAddressCompleted != null)
{
FindAddressCompleted(sender, e);
}
}
}
As you can see there is a TON of duplicate try catch code. This makes the classes quite bloated and this is the smallest one. The largest one is north of 15,000 lines of repeated try, method pass through and catch. I've applied the refactoring to the Login method of the previous class to show the reduction in code.
This is the abstract, generic class I have inserted so I have somewhere to introduce common logic. I've put in the "CallServiceSafely" methods that take "Funcs" and "Actions".
public abstract class ServiceWrapper<S> : IService
where S : IWrapAutoGenService, new()
{
/// <summary>
/// The local web service
/// </summary>
protected static S _webService;
/// <summary>
/// Gets the reference to the web service
/// </summary>
protected virtual S AppWebService
{
get
{
if (_webService == null)
{
_webService = new S {Timeout = 100000};
if (URL != null)
{
_webService.Url = URL;
}
}
return _webService;
}
}
/// <summary>
/// Gets the display name for the web service
/// </summary>
public abstract string DisplayName { get; }
/// <summary>
/// Send an echo request to the server to test
/// the availability of the service
/// </summary>
/// <param name="echo">The text to send</param>
/// <returns>The text returned by the service</returns>
public virtual string Echo(string echo)
{
var originalTimeOut = AppWebService.Timeout;
AppWebService.Timeout = 5000;
var result = CallServiceSafely(AppWebService.echo, echo);
AppWebService.Timeout = originalTimeOut;
return result;
}
protected void CallServiceSafely(Action serviceMethod)
{
try
{
serviceMethod.Invoke();
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T>(Action<T> serviceMethod,T firstParam)
{
try
{
serviceMethod.Invoke(firstParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T, TU>(Action<T, TU> serviceMethod,T firstParam, TU secondParam)
{
try
{
serviceMethod.Invoke(firstParam, secondParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T, TU, TV>(Action<T, TU, TV> serviceMethod,T firstParam, TU secondParam, TV thirdParam)
{
try
{
serviceMethod.Invoke(firstParam, secondParam, thirdParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected void CallServiceSafely<T, TU, TV, TX>(Action<T, TU, TV, TX> serviceMethod,T firstParam, TU secondParam, TV thirdParam, TX fourthParam)
{
try
{
serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TR>(Func<TU, TR> serviceMethod, TU firstParam)
{
try
{
return serviceMethod.Invoke(firstParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TR>(Func<TU, TA, TR> serviceMethod, TU firstParam, TA secondParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TV, TR>(Func<TU, TA, TV, TR> serviceMethod, TU firstParam, TA secondParam, TV thirdParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam, thirdParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TV,TX, TR>(Func<TU, TA, TV, TX, TR> serviceMethod, TU firstParam, TA secondParam, TV thirdParam, TX fourthParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
protected TR CallServiceSafely<TU, TA, TV,TX,TY, TR>(Func<TU, TA, TV, TX, TY, TR> serviceMethod, TU firstParam, TA secondParam, TV thirdParam, TX fourthParam, TY fifthParam)
{
try
{
return serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam, fifthParam);
}
catch (SoapException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (WebException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (ApplicationException ex)
{
throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));
}
catch (FaultException ex)
{
throw new ServiceException(CreateErrorDescriptionInstance(ex));
}
}
/// <summary>
/// Create an error description from the WCF FaultException
/// It may need further fixed after more implementations of WCF as is only currently used for the document printing
/// </summary>
/// <param name="ex"></param>
/// <returns></returns>
private static ErrorDescription CreateErrorDescriptionInstance(FaultException ex)
{
if (ex.Reason.ToString().IndexOf((char)255) != -1)
{
string elements = ex.Reason.ToString().Split((char)255);
ErrorDescription errorDescription = new ErrorDescription(elements[3], elements[1], elements[2], elements[0]);
return errorDescription;
}
string severity = ex.Reason.ToString();
string reason = ex.Reason.ToString();
string message = ex.Message;
object details = ex.StackTrace;
ErrorDescription errorDesc = new ErrorDescription(severity, reason, message, details);
return errorDesc;
}
/// <summary>
/// Gets or sets a value indicating whether the service is
/// available
/// </summary>
public bool ServiceAvailable { get; set; }
/// <summary>
/// Gets or sets the url of the service
/// </summary>
public string URL { get; set; }
public abstract string RefString { get; }
/// <summary>
/// Clear data cached in the service
/// </summary>
public virtual void ClearCachedData()
{
}
}
public interface IService
{
string DisplayName { get; }
bool ServiceAvailable { get; set; }
string URL { get; set; }
string RefString { get; } //Uid for the Iservice, used in Esprit as the name of the setting that contains the url for the service
string Echo(string @string);
//Used to clear the cached user on logoff
//this is done within EspritServiceStateController for each module
void ClearCachedData();
}
The ServiceWrapped class now contains many CallWebServiceSafely methods. Is there a way I can have one block of try catch code or will I have to maintain all the blocks as I have now?
Final interface for completeness.
/// <summary>
/// Provides access to autogenerated WSDL services that allow you to "Echo" them to check for their
/// prescence
/// </summary>
public interface IWrapAutoGenService
{
int Timeout { get; set; }
string Url { get; set; }
//It needs to be lower case as that is what the wsdl presents to us.
// ReSharper disable once InconsistentNaming
string echo(string echo);
}
Sorry for the wall of text, thanks for getting through it all.
c# wcf
c# wcf
asked 10 mins ago
d347hm4nd347hm4n
576516
576516
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212203%2frefactoring-advice-across-multiple-wcf-service-with-boilerplate-error-handling%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212203%2frefactoring-advice-across-multiple-wcf-service-with-boilerplate-error-handling%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown