Click here to Skip to main content
15,884,472 members
Articles / Web Development / ASP.NET

Take MVC to the Next Level in .NET

Rate me:
Please Sign up or sign in to vote.
4.62/5 (11 votes)
30 Apr 2013GPL315 min read 73.1K   858   75  
How to quickly build reusable and flexible WPF, Silverlight, or ASP.NET applications with the powerful Xomega Framework using the best MVVM principles.
// Copyright (c) 2010-2012 Xomega.Net. All rights reserved.

using System.Collections.Generic;
using System.Resources;
using System.Runtime.Serialization;
using System.ServiceModel;

namespace Xomega.Framework
{
    /// <summary>
    /// A list of error messages and utility methods to manipulate them.
    /// </summary>
    [DataContract]
    public class ErrorList
    {
        /// <summary>
        /// A static resource manager, which can be used to translate the error messages
        /// to the current language.
        /// </summary>
        public static ResourceManager ResourceManager;

        /// <summary>
        /// A singleton current error list to return in the absence of the current operation context.
        /// </summary>
        private static ErrorList current;

        /// <summary>
        /// Returns the error list associated with the current operation context.
        /// Service operations should use this error list to report the errors back to the caller.
        /// </summary>
        public static ErrorList Current
        {
            get
            {
                object errors;
                if (OperationContext.Current == null) errors = current ?? (current = new ErrorList());
                else if (!OperationContext.Current.OutgoingMessageProperties.TryGetValue("Errors", out errors))
                    OperationContext.Current.OutgoingMessageProperties.Add("Errors", errors = new ErrorList());
                return errors as ErrorList;
            }
        }

        /// <summary>
        /// Internal list of error messages.
        /// </summary>
        protected List<ErrorMessage> errors = new List<ErrorMessage>();

        /// <summary>
        /// Gets the text message based on the given error code and parameters.
        /// Uses the resource manager if set to look up the localized message by the error code.
        /// </summary>
        /// <param name="code">The error code.</param>
        /// <param name="parameters">An array of parameters to substitute into the message placeholders.</param>
        /// <returns>Localized message  for the given error code with substituted parameters.</returns>
        private string GetMessage(string code, object[] parameters)
        {
            string message = null;
            if (ResourceManager != null) message = ResourceManager.GetString(code);
            if (message == null) message = code;
            return string.Format(message, parameters);
        }

        /// <summary>
        /// Adds an error to the list with the given error code and additional parameters to substitute.
        /// </summary>
        /// <param name="code">The error code.</param>
        /// <param name="parameters">An array of parameters to substitute into the message placeholders.</param>
        public void AddError(string code, params object[] parameters)
        {
            Add(new ErrorMessage(code, GetMessage(code, parameters), ErrorSeverity.Error));
        }

        /// <summary>
        /// Adds a critical error to the list with the given error code and additional parameters to substitute
        /// and aborts the current operation.
        /// </summary>
        /// <param name="code">The error code.</param>
        /// <param name="parameters">An array of parameters to substitute into the message placeholders.</param>
        public void CriticalError(string code, params object[] parameters) { CriticalError(code, true); }

        /// <summary>
        /// Adds a critical error to the list with the given error code and additional parameters to substitute
        /// and aborts the current operation with the reason being this message if required.
        /// </summary>
        /// <param name="code">The error code.</param>
        /// <param name="abort">True to abort the current operation.</param>
        /// <param name="parameters">An array of parameters to substitute into the message placeholders.</param>
        public void CriticalError(string code, bool abort, params object[] parameters)
        {
            ErrorMessage err = new ErrorMessage(code, GetMessage(code, parameters), ErrorSeverity.Critical);
            Add(err);
            if (abort) Abort(err.Message);
        }

        /// <summary>
        /// Adds a warning to the list with the given error code and additional parameters to substitute.
        /// </summary>
        /// <param name="code">The error code.</param>
        /// <param name="parameters">An array of parameters to substitute into the message placeholders.</param>
        public void AddWarning(string code, params object[] parameters)
        {
            Add(new ErrorMessage(code, GetMessage(code, parameters), ErrorSeverity.Warning));
        }

        /// <summary>
        /// Aborts the current operation with the specified reason by throwing a FaultException.
        /// </summary>
        /// <param name="reason">The reason for aborting the operation.</param>
        public void Abort(string reason)
        {
            FaultCode cd = new FaultCode("Sender");
            throw new FaultException<ErrorList>(this, new FaultReason(reason), cd, null);
        }

        /// <summary>
        /// Aborts the current operation in the current list has any errors.
        /// </summary>
        public void AbortIfHasErrors()
        {
            if (HasErrors()) Abort(ErrorsText);
        }

        /// <summary>
        /// Checks if the current list has any errors or critical errors.
        /// </summary>
        /// <returns>True if the current list has any errors or critical errors, otherwise false.</returns>
        public bool HasErrors()
        {
            foreach (ErrorMessage e in errors) if (e.Severity > ErrorSeverity.Warning) return true;
            return false;
        }

        /// <summary>
        /// Adds the given error message to the list.
        /// </summary>
        /// <param name="err">Error message to add to the list.</param>
        public void Add(ErrorMessage err)
        {
            errors.Add(err);
        }

        /// <summary>
        /// Merges the current list with another error list.
        /// </summary>
        /// <param name="otherList">Another error list to merge the current list with.</param>
        public void MergeWith(ErrorList otherList)
        {
            if (otherList != null) errors.AddRange(otherList.Errors);
        }

        /// <summary>
        /// Clears the error list.
        /// </summary>
        public void Clear() { errors.Clear(); }

        /// <summary>
        /// Returns a read-only collection of error messages from this list.
        /// </summary>
        [DataMember]
        public ICollection<ErrorMessage> Errors
        {
            get { return errors.AsReadOnly(); }
            set
            {
                // this is to support deserialization that doesn't have access to private members (e.g. in Silverlight)
                if (errors == null) errors = new List<ErrorMessage>(value);
            }
        }

        /// <summary>
        ///  Gets a combined error text by concatenating all error messages with a new line delimiter.
        /// </summary>
        public string ErrorsText
        {
            get
            {
                string errText = "";
                foreach (ErrorMessage err in errors)
                {
                    if (!string.IsNullOrEmpty(errText)) errText += "\n";
                    errText += err.Message;
                }
                return errText;
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
Architect Xomega.Net
United States United States
Xomega Team is striving to increase productivity and development quality by utilizing Model Driven Development coupled with Code Generation and the best design practices for application development.
We provide MDD tools, code generators and frameworks for Visual Studio and .Net development.
Visit us at http://www.xomega.net
This is a Organisation

1 members

Comments and Discussions