SimpleLogger.SimpleLog.GetExceptionXElement C# (CSharp) Method

GetExceptionXElement() public static method

Gets an XElement for an exception
Recursively adds elements for inner exceptions. For the most inner exception, the stack trace is added. Tags for Exception.Data are added. Specific properties of the exception types SqlException, COMException and AggregateException are recognized, too.
public static GetExceptionXElement ( Exception ex ) : System.Xml.Linq.XElement
ex System.Exception The exception to get the XElement for
return System.Xml.Linq.XElement
        public static XElement GetExceptionXElement(Exception ex)
        {
            if(ex == null)
                return null;

            var xElement = new XElement("Exception");
            xElement.Add(new XAttribute("Type", ex.GetType().FullName));
            xElement.Add(new XAttribute("Source", ex.TargetSite == null || ex.TargetSite.DeclaringType == null ? ex.Source : string.Format("{0}.{1}", ex.TargetSite.DeclaringType.FullName, ex.TargetSite.Name)));
            xElement.Add(new XElement("Message", ex.Message));

            if(ex.Data.Count > 0)
            {
                var xDataElement = new XElement("Data");

                foreach(DictionaryEntry de in ex.Data)
                {
                    xDataElement.Add(new XElement("Entry", new XAttribute("Key", de.Key), new XAttribute("Value", de.Value)));
                }

                xElement.Add(xDataElement);
            }

            if(ex is SqlException)
            {
                var sqlEx = (SqlException)ex;
                var xSqlElement = new XElement("SqlException");
                xSqlElement.Add(new XAttribute("ErrorNumber", sqlEx.Number));

                if(!string.IsNullOrEmpty(sqlEx.Server))
                    xSqlElement.Add(new XAttribute("ServerName", sqlEx.Server));

                if(!string.IsNullOrEmpty(sqlEx.Procedure))
                    xSqlElement.Add(new XAttribute("Procedure", sqlEx.Procedure));

                xElement.Add(xSqlElement);
            }

            if(ex is COMException)
            {
                var comEx = (COMException)ex;
                var xComElement = new XElement("ComException");
                xComElement.Add(new XAttribute("ErrorCode", string.Format("0x{0:X8}", (uint)comEx.ErrorCode)));
                xElement.Add(xComElement);
            }

            if(ex is AggregateException)
            {
                var xAggElement = new XElement("AggregateException");
                foreach(Exception innerEx in ((AggregateException)ex).InnerExceptions)
                {
                    xAggElement.Add(GetExceptionXElement(innerEx));
                }
                xElement.Add(xAggElement);
            }

            xElement.Add(ex.InnerException == null ? new XElement("StackTrace", ex.StackTrace) : GetExceptionXElement(ex.InnerException));

            return xElement;
        }