ServiceResult class

26.11.2009 00:45Comments
The ServiceResult class is a very simple class that I found useful in certain cases where I need to make a call to a method that performs different actions or validations. I have used it in webservices when a collection of items to operate are passed to a webmethod, and a result has to be returned summarizing the errors and warnings. And I have used it as well in Service calls where complex operations are made. It can also serve as a base class for a "workflow pipeline" framework such as the approach used in the ORM nettiers (see this for further information). The code:
 public class ServiceResult
 {
 #region private members
 private List<string> _errors = new List<string>();
 private List<string> _warnings = new List<string>();
 private string _errorsHeader = "The following errors were encountered:";
 #endregion

 #region properties
 /// <summary>
 /// This string will appear in the header of the errors list.
 /// </summary>
 public string ErrorsHeader {
 get { return _errorsHeader; }
 set { _errorsHeader = value; }
 }
 public string[] Errors { get { return _errors.ToArray(); } }
 public string[] Warnings { get { return _warnings.ToArray(); } }
 public bool HasErros { get { return (_errors.Count > 0); } }
 public bool HasWarnings { get { return (_warnings.Count > 0); } }
 #endregion

 #region methods
 public void AddError(string error)
 {
  _errors.Add(error);
 }
 public void AddWarning(string warning)
 {
  _warnings.Add(warning);
 }
 public string GetFormattedErrors(bool includeHeader)
 {
  StringBuilder sb = new StringBuilder();
  if (includeHeader)
   sb.AppendLine(ErrorsHeader);
  foreach (string error in Errors)
  {
   sb.AppendLine(error);
  }
  return sb.ToString();
 }
 /// <summary>
 /// Takes the errors and warnings from another ServiceResults.
 /// Use this method to compose multiple ServiceResults into one.
 /// </summary>
 /// <param name="serviceResult"></param>
 public void Compose(ServiceResult serviceResult)
 {
  foreach (string error in serviceResult.Errors)
   AddError(error);
  foreach (string warning in serviceResult.Warnings)
   AddWarning(warning);
 }
 #endregion
 }
Then make a call to the method: ServiceResult fooResult = Foo(); Or make several calls and combine the results: ServiceResult theResult = new ServiceResult(); theResult.Compose(FooA()); theResult.Compose(FooB()); //Use the result. if (theResult.HasErrors) Console.Write(theResult.GetFormattedErrors(true));

comments powered by Disqus