コード例 #1
0
        public void Log(LogLevel logLevel, Exception ex, string memberName = null, int lineNumber = 0, string memberType = null)
        {
            if (ex == null)
            {
                return;
            }

            var    formatter = new ExceptionFormatter();
            string message   = formatter.Format(ex, this);

            Log(logLevel, message, memberName, lineNumber, memberType);
        }
コード例 #2
0
        public void OnlyRootExceptionsAreStoredInLoggerDataContainer()
        {
            var ex1 = new Exception("Exception 1",
                                    new Exception("Exception 2")
                                    );

            var ex2 = new Exception("Exception 3",
                                    new Exception("Inner exception 4",
                                                  new Exception("Inner exception 5")
                                                  )
                                    );

            Logger logger = new Logger();

            var formatter = new ExceptionFormatter();

            formatter.Format(ex1, logger);
            formatter.Format(ex2, logger);

            int count = logger.DataContainer.Exceptions.Count();

            Assert.AreEqual(2, count);
        }
コード例 #3
0
    /// <summary>
    /// Gets a <see cref="IRenderable"/> representation of the exception.
    /// </summary>
    /// <param name="exception">The exception to format.</param>
    /// <param name="settings">The exception settings.</param>
    /// <returns>A <see cref="IRenderable"/> representing the exception.</returns>
    public static IRenderable GetRenderable(this Exception exception, ExceptionSettings settings)
    {
        if (exception is null)
        {
            throw new ArgumentNullException(nameof(exception));
        }

        if (settings is null)
        {
            throw new ArgumentNullException(nameof(settings));
        }

        return(ExceptionFormatter.Format(exception, settings));
    }
コード例 #4
0
ファイル: ExceptionHandler.cs プロジェクト: videolib/dotnet
        static public void HandleException(System.Exception ex, string message = "An errror occured in LBF Video Lib", bool ignoreException = true)
        {
            // Format the exception message.
            ExceptionFormatter formater          = new ExceptionFormatter();
            string             formatedException = formater.Format(message, ex);

            // Log error message in production category.
            // If severity is critical then it also send error to config mail address.
            TextFileLogger.Log(formatedException, ErrorLogFileName);

            if (!ignoreException)
            {
                throw ex;
            }
        }
コード例 #5
0
ファイル: AbstractEvent.cs プロジェクト: Agnael/Sero.Loxy
        public virtual void Prepare()
        {
            if (_isPrepared)
            {
                return;
            }

            Type = TypeUtils.GetFriendlyName(this.GetType());

            if (_exception != null)
            {
                this.Exception = ExceptionFormatter.Format(_exception);
            }

            _isPrepared = true;
        }
コード例 #6
0
        public void AppendExceptionDetailsOptions()
        {
            CommonTestHelpers.ResetContext();

            KissLogConfiguration.Options.AppendExceptionDetails((Exception ex) =>
            {
                if (ex is NotImplementedException implementedException)
                {
                    return("We should implement this method");
                }

                return(null);
            });

            var    formatter = new ExceptionFormatter();
            string result    = formatter.Format(new NotImplementedException(), new Logger());

            Assert.IsTrue(result.Contains("We should implement this method"));
        }
コード例 #7
0
 // If your activity returns a value, derive from CodeActivity<TResult>
 // and return the value from the Execute method.
 protected override void Execute(CodeActivityContext context)
 {
     try {
         int entityType = (int)NotificationType.Get(context);
         if (entityType == (int)EnumNotificationEntity.Scale)
         {
             string       conString = System.Configuration.ConfigurationManager.ConnectionStrings["smARTDBContext"].ConnectionString;
             ScaleLibrary scaleLib  = new ScaleLibrary(conString);
             Scale        scale     = scaleLib.GetByID(EntityID.Get(context), new string[] { "Dispatch_Request_No", "Party_ID", "Purchase_Order", "Container_No", "Party_Address", "Sales_Order", "Invoice" });
             scale.Send_Mail = true;
             scaleLib.Modify(scale, new string[] { "Dispatch_Request_No", "Party_ID", "Purchase_Order", "Container_No", "Party_Address", "Sales_Order", "Invoice" });
         }
     }
     catch (Exception ex) {
         ExceptionFormatter formater          = new ExceptionFormatter();
         string             formatedException = formater.Format("Send mail update log error", ex);
         Common.MessageLogger.Instance.LogMessage(ex, formatedException, Common.Priority.High, 0, System.Diagnostics.TraceEventType.Critical, "WF Email Error", "Email");
         throw ex;
     }
 }
コード例 #8
0
        private string CreateMessage(Exception exception, Guid handlingInstanceID)
        {
            StringWriter  writer        = null;
            StringBuilder stringBuilder = null;

            try
            {
                writer = CreateStringWriter();
                ExceptionFormatter formatter = CreateFormatter(writer, exception, handlingInstanceID);
                formatter.Format();
                stringBuilder = writer.GetStringBuilder();
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
            return(stringBuilder.ToString());
        }
コード例 #9
0
        /// <summary>
        /// Creates a exception message.
        /// </summary>
        /// <param name="exception">Exception to be logged.</param>
        /// <param name="handlingInstanceID">Exception Id.</param>
        /// <returns>A string to be logged</returns>
        private string CreateMessage(Exception exception, Guid handlingInstanceID)
        {
            if (formatterCreator != null)
            {
                using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
                {
                    ExceptionFormatter formatter = formatterCreator(writer, exception, handlingInstanceID);

                    if (formatter != null)
                    {
                        formatter.Format();
                    }

                    return(writer.ToString());
                }
            }
            else
            {
                return(string.Empty);
            }
        }
コード例 #10
0
        public void Log(LogLevel logLevel, Args args, JsonSerializeOptions options = null, string memberName = null, int lineNumber = 0, string memberType = null)
        {
            if (args == null)
            {
                return;
            }

            List <string> values = new List <string>();

            foreach (var arg in args.GetArgs())
            {
                string message = null;

                if (arg is string stringArg)
                {
                    message = stringArg;
                }
                else if (arg is Exception exceptionArg)
                {
                    var formatter = new ExceptionFormatter();
                    message = formatter.Format(exceptionArg, this);
                }
                else
                {
                    message = KissLogConfiguration.JsonSerializer.Serialize(arg, options);
                }

                if (string.IsNullOrEmpty(message))
                {
                    continue;
                }

                values.Add(message);
            }

            string value = string.Join(Environment.NewLine, values);

            Log(logLevel, value, memberName, lineNumber, memberType);
        }
コード例 #11
0
        public void AllExceptionsAreLogged()
        {
            string exception1 = $"Exception: {Guid.NewGuid()}";
            string exception2 = $"Exception 2: {Guid.NewGuid()}";
            string exception3 = $"Exception 3: {Guid.NewGuid()}";
            string exception4 = $"Exception 4: {Guid.NewGuid()}";

            var ex = new Exception(exception1,
                                   new Exception(exception2,
                                                 new Exception(exception3,
                                                               new Exception(exception4)
                                                               )
                                                 )
                                   );

            var    formatter = new ExceptionFormatter();
            string result    = formatter.Format(ex, new Logger());

            Assert.IsTrue(result.Contains(exception1));
            Assert.IsTrue(result.Contains(exception2));
            Assert.IsTrue(result.Contains(exception3));
            Assert.IsTrue(result.Contains(exception4));
        }
コード例 #12
0
        protected Exception CyclicDependencyException(InjectionContext currentContext)
        {
            var errMsg = ExceptionFormatter.Format(currentContext, Resources.CyclicDependencyFoundWhileBuildingInstanceForType, _description.ConcreteType.ToTypeName());

            return(new CyclicDependencyException(errMsg));
        }
コード例 #13
0
        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            try {
                // Can read this information from config file.

                NotificationDefinition message    = NotificationDef.Get(context) as NotificationDefinition;
                SmtpClient             SmtpServer = ReadSMTPConfigurationInfo(message);


                MailMessage mail = new MailMessage();

                // Sender
                mail.From = message.Sender;

                // Add attachments
                foreach (var attachment in message.Attachments)
                {
                    mail.Attachments.Add(attachment);
                }

                // To Receipients
                foreach (var toRecept in message.ToRecipients)
                {
                    mail.To.Add(toRecept);
                }

                // Cc Receipients
                if (message.CCRecipients != null)
                {
                    foreach (var ccRecept in message.CCRecipients)
                    {
                        mail.To.Add(ccRecept);
                    }
                }

                // Bcc Receipients
                if (message.BCCRecipients != null)
                {
                    foreach (var bccRecept in message.BCCRecipients)
                    {
                        mail.To.Add(bccRecept);
                    }
                }

                // Subject.
                mail.Subject = message.Subject;

                // Body.
                mail.Body = NotificationHelper.XSLTransform(XSLPath.Get(context), CustomerName.Get(context), EntityID.Get(context), CompanyName.Get(context), UserName.Get(context), BookingID.Get(context), SOID.Get(context));

                // Body Type
                mail.IsBodyHtml = message.FormatType == EnumFormatType.HTML;

                // Send email.
                SmtpServer.Send(mail);

                Result.Set(context, EntityID.Get(context));
            }
            catch (Exception ex) {
                ExceptionFormatter formater          = new ExceptionFormatter();
                string             formatedException = formater.Format("Send mail error", ex);
                Common.MessageLogger.Instance.LogMessage(ex, formatedException, Common.Priority.High, 0, System.Diagnostics.TraceEventType.Critical, "WF Email Error", "Email");
                throw ex;
            }
        }
コード例 #14
0
        public void FormatThrowsExceptionForNullLogger()
        {
            var formatter = new ExceptionFormatter();

            formatter.Format(new Exception(), null);
        }
コード例 #15
0
 protected void Log(Exception ex, [CallerMemberName] string MethodName = null)
 {
     Logger.Log(ID, ModuleName, MethodName, LogLevels.Error, $"An unexpected exception occured in {ModuleName}:{MethodName} ({ExceptionFormatter.Format(ex)})");
 }
コード例 #16
0
 internal static Exception DependencyUnregistered(Type targetType)
 {
     return(new DependencyNotFoundException(
                ExceptionFormatter.Format(Resources.ObjectBuilderRegisteredWithTypeCanNotBeFound, targetType.ToTypeName())));
 }
コード例 #17
0
        private void ProcessInserts(BindingList <RecordToAdd> recordsToAdd, EntityBatch entityBatch, string tableName)
        {
            for (int i = 0; i < recordsToAdd.Count; i++)
            {
                var recordToAdd = recordsToAdd[i];

                PostgresSqlInsertFactory insertFactory;
                if (entityBatch.EntityDefinition.PrimaryKeyGenerationType == PrimaryKeyGenerationType.Custom)
                {
                    insertFactory = new PostgresSqlInsertFactory(tableName, entityBatch.EntityDefinition.PrimaryKeyColumnNames[0], entityBatch.EntityDefinition.CustomCommand, recordToAdd.FieldValuePairs);
                }
                else
                {
                    insertFactory = new PostgresSqlInsertFactory(tableName, entityBatch.EntityDefinition.PrimaryKeyColumnNames[0], recordToAdd.FieldValuePairs);
                }

                if (entityBatch.EntityDefinition.AutoBindingForeignKeys != null)
                {
                    foreach (var autoBindingForeignKey in entityBatch.EntityDefinition.AutoBindingForeignKeys)
                    {
                        EntityRecord parentRecord    = null;
                        string       primaryKeyValue = null;

                        try
                        {
                            parentRecord = recordToAdd.Parents[autoBindingForeignKey.Relationship.Name];
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(string.Format("Relationship with name '{0}' was not found within parents for entity record '{1}' with primary key field '{2}' to bind to parent field(s) '{3}'.  Data only values for the failed record are: {4}.",
                                                              autoBindingForeignKey.Relationship.Name, entityBatch.EntityDefinition.TechnicalEntityName,
                                                              autoBindingForeignKey.FieldNameToUpdate, StringHelper.GetDelimitedString(autoBindingForeignKey.Relationship.ChildFieldNamesToMatchOn),
                                                              recordToAdd.GetDataOnlyValuesAsText()), ex);
                        }

                        if (parentRecord is EntityRecordWithDataChange)
                        {
                            var parentRecordWithChange = (EntityRecordWithDataChange)parentRecord;

                            if (parentRecordWithChange.HasError)
                            {
                                recordsToAdd[i].HasError     = true;
                                recordsToAdd[i].ErrorMessage = "See parent record for error details.";
                                continue;
                            }
                        }

                        try
                        {
                            primaryKeyValue = parentRecord.PrimaryKeyValues[autoBindingForeignKey.ParentPrimaryKeyColumnIdx];
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(string.Format("Primary key index '{0}' was not found for parent entity record '{1}' with primary key value(s) '{2}' and data only field(s): {3}.",
                                                              autoBindingForeignKey.Relationship.Name, entityBatch.EntityDefinition.TechnicalEntityName,
                                                              StringHelper.GetDelimitedString(parentRecord.PrimaryKeyValues),
                                                              parentRecord.GetDataOnlyValuesAsText()), ex);
                        }

                        insertFactory.AddField(autoBindingForeignKey.FieldNameToUpdate, primaryKeyValue);
                    }
                }

                string recordId = "";

                try
                {
                    recordsToAdd[i].CommandText = insertFactory.GetSQL();

                    recordId = ExecuteCommand(recordsToAdd[i].CommandText).ToString();

                    recordsToAdd[i].PrimaryKeyValues.Add(recordId);
                }
                catch (Exception ex)
                {
                    recordsToAdd[i].HasError = true;

                    recordsToAdd[i].ErrorMessage = ExceptionFormatter.Format(ex);

                    recordsToAdd[i].Exception = ex;
                }
                finally
                {
                    recordsToAdd[i].HasBeenProcessed = true;
                }
            }
        }
 public static void Error(AppException ex)
 {
     Logger.Error(_exceptionFormatter.Format(ex));
 }