Ejemplo n.º 1
0
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            TestOutcome outcome;

            if (severity == LogSeverity.Warning)
            {
                outcome = TestOutcome.Warning;
            }
            else if (severity == LogSeverity.Error)
            {
                outcome = TestOutcome.Error;
            }
            else
            {
                return;
            }

            if (exceptionData != null)
            {
                message = string.Concat(message, "\n", exceptionData.ToString());
            }

            TestRunTextResultMessage resultMessage = new TestRunTextResultMessage(runContext.RunConfig.TestRun.Id, message);

            resultMessage.Outcome = outcome;

            runContext.ResultSink.AddResult(resultMessage);
        }
        private bool TrackException(EventData e, IReadOnlyCollection <EventMetadata> metadata)
        {
            Debug.Assert(metadata != null);
            bool tracked = false;

            foreach (EventMetadata exceptionMetadata in metadata)
            {
                var result = ExceptionData.TryGetData(e, exceptionMetadata, out ExceptionData exceptionData);
                if (result.Status != DataRetrievalStatus.Success)
                {
                    this.healthReporter.ReportWarning("ApplicationInsightsOutput: " + result.Message, EventFlowContextIdentifiers.Output);
                    continue;
                }

                var et = new ExceptionTelemetry();
                et.Exception = exceptionData.Exception;

                AddProperties(et, e);

                telemetryClient.TrackException(et);
                tracked = true;
            }

            return(tracked);
        }
Ejemplo n.º 3
0
        protected static void LogToolNotification(
            IAnalysisLogger logger,
            string message,
            FailureLevel level = FailureLevel.Note,
            Exception ex       = null)
        {
            ExceptionData exceptionData = null;

            if (ex != null)
            {
                exceptionData = new ExceptionData
                {
                    Kind    = ex.GetType().FullName,
                    Message = ex.Message,
                    Stack   = Stack.CreateStacks(ex).FirstOrDefault()
                };
            }

            TextWriter writer = level == FailureLevel.Error ? Console.Error : Console.Out;

            writer.WriteLine(message);

            logger.LogToolNotification(new Notification
            {
                Level   = level,
                Message = new Message {
                    Text = message
                },
                Exception = exceptionData
            });
        }
Ejemplo n.º 4
0
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            StringBuilder fullMessage = new StringBuilder();
            fullMessage.Append(GetCaption(severity));
            fullMessage.Append(": ");
            fullMessage.Append(message);

            if (exceptionData != null)
                fullMessage.Append('\n').Append(exceptionData);

            switch (severity)
            {
                case LogSeverity.Debug:
                    facadeLogger.LogMessage(fullMessage.ToString());
                    break;
                case LogSeverity.Info:
                case LogSeverity.Important:
                case LogSeverity.Warning:
                    facadeLogger.LogMessage(fullMessage.ToString());
                    break;
                case LogSeverity.Error:
                    facadeLogger.LogError(fullMessage.ToString());
                    break;
            }
        }
Ejemplo n.º 5
0
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            if (exceptionData != null)
                message += "\n" + exceptionData;

            switch (severity)
            {
                case LogSeverity.Error:
                    taskLoggingHelper.LogError(message);
                    break;

                case LogSeverity.Warning:
                    taskLoggingHelper.LogWarning(message);
                    break;

                case LogSeverity.Important:
                    taskLoggingHelper.LogMessage(MessageImportance.High, message);
                    break;

                case LogSeverity.Info:
                    taskLoggingHelper.LogMessage(MessageImportance.Normal, message);
                    break;

                case LogSeverity.Debug:
                    taskLoggingHelper.LogMessage(MessageImportance.Low, message);
                    break;
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 带debug的json返回
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="status"></param>
        /// <param name="message"></param>
        /// <param name="debug"></param>
        /// <returns></returns>
        public static string GetJson(object obj, int status, string message, object debug)
        {
            ReturnData data = new JSONHelper.ReturnData();

            data.returntype = status;
            if (obj != null && obj.GetType().Name.IndexOf("DataTable") >= 0)
            {
                data.data = JSONHelper.DataTableToList((DataTable)obj);
            }
            else
            {
                data.data = obj;
            }
#if DEBUG
            if (debug != null && debug.GetType().Name.IndexOf("Exception") >= 0)
            {
                Exception     ex = (Exception)debug;
                ExceptionData de = new ExceptionData();
                de.source  = ex.Source;
                de.message = ex.Message;
                de.trace   = ex.StackTrace;
                debug      = de;
                //LogHelper.Error(ex);
            }
            data.debug = debug;
#endif
            data.returntext = message;
            return(ObjectToJSON(data));
        }
Ejemplo n.º 7
0
        /// <summary>
        ///     Enumerate all protocols to see if they are properly configured and send using the ones that are configured
        ///     as many times as necessary.
        /// </summary>
        /// <param name="reportFile">The file to read the report from.</param>
        /// <returns>
        ///     Returns <see langword="true" /> if the sending was successful.
        ///     Returns <see langword="true" /> if the report was submitted to at least one destination.
        /// </returns>
        private bool EnumerateDestinations(Stream reportFile, ExceptionData exceptionData)
        {
            var sentSuccessfullyAtLeastOnce = false;
            var fileName = Path.GetFileName(((FileStream)reportFile).Name);

            foreach (var destination in Settings.Destinations)
            {
                try
                {
                    Logger.Trace(string.Format("Submitting bug report via {0}.", destination.GetType().Name));
                    if (destination.Send(fileName, reportFile, exceptionData.Report, exceptionData.Exception))
                    {
                        sentSuccessfullyAtLeastOnce = true;
                    }
                }
                catch (Exception exception)
                {
                    Logger.Error(
                        string.Format(
                            "An exception occurred while submitting bug report with {0}. Check the inner exception for details.",
                            destination.GetType().Name),
                        exception);
                }
            }

            return(sentSuccessfullyAtLeastOnce);
        }
Ejemplo n.º 8
0
        private ExceptionData GetDataFromZip(Stream stream)
        {
            var results   = new ExceptionData();
            var zipStorer = ZipStorer.Open(stream, FileAccess.Read);

            using (Stream zipItemStream = new MemoryStream())
            {
                var zipDirectory = zipStorer.ReadCentralDir();
                foreach (var entry in zipDirectory)
                {
                    if (Path.GetFileName(entry.FilenameInZip) == StoredItemFile.Exception)
                    {
                        zipItemStream.SetLength(0);
                        zipStorer.ExtractFile(entry, zipItemStream);
                        zipItemStream.Position = 0;
                        var deserializer = XmlSerializer.FromTypes(new[] { typeof(SerializableException) })[0];
                        //var deserializer = new XmlSerializer(typeof(SerializableException));
                        results.Exception      = (SerializableException)deserializer.Deserialize(zipItemStream);
                        zipItemStream.Position = 0;
                    }
                    else if (Path.GetFileName(entry.FilenameInZip) == StoredItemFile.Report)
                    {
                        zipItemStream.SetLength(0);
                        zipStorer.ExtractFile(entry, zipItemStream);
                        zipItemStream.Position = 0;
                        var deserializer = XmlSerializer.FromTypes(new[] { typeof(Report) })[0];
                        //var deserializer = new XmlSerializer(typeof(Report));
                        results.Report         = (Report)deserializer.Deserialize(zipItemStream);
                        zipItemStream.Position = 0;
                    }
                }
            }

            return(results);
        }
Ejemplo n.º 9
0
        public void PopulatesPropertiesFromRawValues()
        {
            ExceptionData innerData = new ExceptionData("type", "message", "stacktrace", ExceptionData.NoProperties, null);
            ExceptionData outerData = new ExceptionData("type", "message", "stacktrace",
                                                        new PropertySet()
            {
                { "Prop1", "Value1" },
                { "Prop2", "Value2" }
            }, innerData);

            Assert.AreEqual("type", innerData.Type);
            Assert.AreEqual("message", innerData.Message);
            Assert.AreEqual("stacktrace", innerData.StackTrace.ToString());
            Assert.IsNull(innerData.InnerException);

            Assert.AreEqual("type", outerData.Type);
            Assert.AreEqual("message", outerData.Message);
            Assert.AreEqual("stacktrace", outerData.StackTrace.ToString());
            Assert.AreEqual(new PropertySet()
            {
                { "Prop1", "Value1" },
                { "Prop2", "Value2" }
            }, outerData.Properties);
            Assert.AreSame(innerData, outerData.InnerException);
        }
Ejemplo n.º 10
0
        public void PopulatesPropertiesFromException()
        {
            Exception inner = new Exception("Foo");

            PopulateStackTrace(inner);

            SampleException outer = new SampleException("Bar", inner)
            {
                Prop1 = "Value1",
                Prop2 = "Value2"
            };

            PopulateStackTrace(outer);

            ExceptionData outerData = new ExceptionData(outer);

            Assert.AreEqual(outer.GetType().FullName, outerData.Type);
            Assert.AreEqual(outer.Message, outerData.Message);
            Assert.AreEqual(new PropertySet()
            {
                { "Prop1", "Value1" },
                { "Prop2", "Value2" }
            }, outerData.Properties);
            Assert.AreEqual(outer.StackTrace, outerData.StackTrace.ToString());
            Assert.IsNotNull(outerData.InnerException);

            ExceptionData innerData = outerData.InnerException;

            Assert.AreEqual(inner.GetType().FullName, innerData.Type);
            Assert.AreEqual(inner.Message, innerData.Message);
            Assert.AreEqual(inner.StackTrace, innerData.StackTrace.ToString());
            Assert.IsNull(innerData.InnerException);
        }
Ejemplo n.º 11
0
        public void ToStringBareBones()
        {
            ExceptionData data = new ExceptionData("type", "message", "stacktrace", ExceptionData.NoProperties, null);

            Assert.AreEqual("type: message\nstacktrace",
                            data.ToString());
        }
Ejemplo n.º 12
0
        /// <inheritdoc />
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            switch (severity)
            {
            case LogSeverity.Error:
                testListener.WriteLine(message, FacadeCategory.Error);
                break;

            case LogSeverity.Warning:
                testListener.WriteLine(message, FacadeCategory.Warning);
                break;

            case LogSeverity.Important:
            case LogSeverity.Info:
                testListener.WriteLine(message, FacadeCategory.Info);
                break;

            case LogSeverity.Debug:
                testListener.WriteLine(message, FacadeCategory.Debug);
                break;
            }

            if (exceptionData != null)
            {
                testListener.WriteLine(exceptionData.ToString(), FacadeCategory.Error);
            }
        }
        public async Task InsertDiscs()
        {
            if (_discoRepository.Any())
            {
                return;
            }

            var token = await GetToken();

            var listGeneros = typeof(GeneroEnum).GetEnumValuesWithDescription();
            var listDisco   = Disco.ListEmpty();

            foreach (var item in listGeneros)
            {
                var list = await GetDiscsByGenre(token, item);

                listDisco.AddRange(list);
            }

            try
            {
                _discoRepository.AddList(listDisco);
            }
            catch (Exception ex)
            {
                ExceptionData.GetInfoDataException("Disco", ex);
            }
        }
Ejemplo n.º 14
0
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            if (exceptionData != null)
                message += "\n" + exceptionData;

            switch (severity)
            {
                case LogSeverity.Error:
                    task.Log(Level.Error, message);
                    break;

                case LogSeverity.Warning:
                    task.Log(Level.Warning, message);
                    break;

                case LogSeverity.Important:
                    task.Log(Level.Info, message);
                    break;

                case LogSeverity.Info:
                    task.Log(Level.Verbose, message);
                    break;

                case LogSeverity.Debug:
                    task.Log(Level.Debug, message);
                    break;
            }
        }
Ejemplo n.º 15
0
        public async Task Create(ISqlTransactionHandler transactionHandler, ExceptionData exceptionData)
        {
            if (exceptionData.Manager.GetState(exceptionData) == DataState.New)
            {
                await _providerFactory.EstablishTransaction(transactionHandler, exceptionData);

                using (DbCommand command = transactionHandler.Connection.CreateCommand())
                {
                    command.CommandText = "[bll].[CreateException]";
                    command.CommandType = CommandType.StoredProcedure;
                    command.Transaction = transactionHandler.Transaction.InnerTransaction;

                    IDataParameter id = DataUtil.CreateParameter(_providerFactory, "id", DbType.Int64);
                    id.Direction = ParameterDirection.Output;
                    command.Parameters.Add(id);

                    DataUtil.AddParameter(_providerFactory, command.Parameters, "domainId", DbType.Guid, DataUtil.GetParameterValue(exceptionData.DomainId));
                    DataUtil.AddParameter(_providerFactory, command.Parameters, "parentExceptionId", DbType.Int64, DataUtil.GetParameterValue(exceptionData.ParentExceptionId));
                    DataUtil.AddParameter(_providerFactory, command.Parameters, "message", DbType.String, DataUtil.GetParameterValue(exceptionData.Message));
                    DataUtil.AddParameter(_providerFactory, command.Parameters, "typeName", DbType.String, DataUtil.GetParameterValue(exceptionData.TypeName));
                    DataUtil.AddParameter(_providerFactory, command.Parameters, "source", DbType.String, DataUtil.GetParameterValue(exceptionData.Source));
                    DataUtil.AddParameter(_providerFactory, command.Parameters, "appDomain", DbType.String, DataUtil.GetParameterValue(exceptionData.AppDomain));
                    DataUtil.AddParameter(_providerFactory, command.Parameters, "targetSite", DbType.String, DataUtil.GetParameterValue(exceptionData.TargetSite));
                    DataUtil.AddParameter(_providerFactory, command.Parameters, "stackTrace", DbType.String, DataUtil.GetParameterValue(exceptionData.StackTrace));
                    DataUtil.AddParameter(_providerFactory, command.Parameters, "data", DbType.String, DataUtil.GetParameterValue(exceptionData.Data));
                    DataUtil.AddParameter(_providerFactory, command.Parameters, "timestamp", DbType.DateTime2, DataUtil.GetParameterValue(exceptionData.CreateTimestamp));

                    await command.ExecuteNonQueryAsync();

                    exceptionData.ExceptionId = (long)id.Value;
                }
            }
        }
Ejemplo n.º 16
0
        public void error(Exception ex)
        {
            ExceptionData exceptionData = new ExceptionData(ex);

            Consumer.Enqueue(exceptionData);
            Logger.Error(exceptionData);
        }
Ejemplo n.º 17
0
        public static void LogException(this Exception ex)
        {
            var errObject = new ExceptionData(ex);
            var errLogger = new ErrorLogger(errObject);

            errLogger.LogException();
        }
Ejemplo n.º 18
0
            protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
            {
                Assert.AreEqual(LogSeverity.Important, severity);
                Assert.IsNull(exceptionData);

                output.Append(message).Append('\n');
            }
Ejemplo n.º 19
0
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            if (exceptionData != null)
            {
                message += "\n" + exceptionData;
            }

            switch (severity)
            {
            case LogSeverity.Error:
                task.Log(Level.Error, message);
                break;

            case LogSeverity.Warning:
                task.Log(Level.Warning, message);
                break;

            case LogSeverity.Important:
                task.Log(Level.Info, message);
                break;

            case LogSeverity.Info:
                task.Log(Level.Verbose, message);
                break;

            case LogSeverity.Debug:
                task.Log(Level.Debug, message);
                break;
            }
        }
Ejemplo n.º 20
0
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            StringBuilder fullMessage = new StringBuilder();

            fullMessage.Append(GetCaption(severity));
            fullMessage.Append(": ");
            fullMessage.Append(message);

            if (exceptionData != null)
            {
                fullMessage.Append('\n').Append(exceptionData);
            }

            switch (severity)
            {
            case LogSeverity.Debug:
                facadeLogger.LogMessage(fullMessage.ToString());
                break;

            case LogSeverity.Info:
            case LogSeverity.Important:
            case LogSeverity.Warning:
                facadeLogger.LogMessage(fullMessage.ToString());
                break;

            case LogSeverity.Error:
                facadeLogger.LogError(fullMessage.ToString());
                break;
            }
        }
Ejemplo n.º 21
0
        /// <inheritdoc />
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            switch (severity)
            {
                case LogSeverity.Error:
                    testListener.WriteLine(message, FacadeCategory.Error);
                    break;

                case LogSeverity.Warning:
                    testListener.WriteLine(message, FacadeCategory.Warning);
                    break;

                case LogSeverity.Important:
                case LogSeverity.Info:
                    testListener.WriteLine(message, FacadeCategory.Info);
                    break;

                case LogSeverity.Debug:
                    testListener.WriteLine(message, FacadeCategory.Debug);
                    break;
            }

            if (exceptionData != null)
                testListener.WriteLine(exceptionData.ToString(), FacadeCategory.Error);
        }
Ejemplo n.º 22
0
        /// <inheritdoc />
        public void Log(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            if (message == null)
                throw new ArgumentNullException("message");

            LogImpl(severity, message, exceptionData);
        }
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            var warning = exceptionData == null
                   ? message
                   : string.Concat(message, "\n", exceptionData.ToString());

            switch (severity)
            {
                case LogSeverity.Info:
                    _messageLogger.SendMessage(TestMessageLevel.Informational, warning);
                    break;
                case LogSeverity.Warning:
                    _messageLogger.SendMessage(TestMessageLevel.Warning, warning);
                    break;
                case LogSeverity.Debug:
                    _messageLogger.SendMessage(TestMessageLevel.Informational, warning);
                    break;
                case LogSeverity.Important:
                    _messageLogger.SendMessage(TestMessageLevel.Informational, warning);
                    break;
                case LogSeverity.Error:
                    _messageLogger.SendMessage(TestMessageLevel.Error, warning);
                    break;
            }
        }
Ejemplo n.º 24
0
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            if (severity < MinLogSeverity || LogMessage == null)
                return;

            Color color = Color.Black;
            switch (severity)
            {
                case LogSeverity.Error:
                    color = Color.Red;
                    break;

                case LogSeverity.Warning:
                    color = Color.Gold;
                    break;

                case LogSeverity.Important:
                    color = Color.Black;
                    break;

                case LogSeverity.Info:
                    color = Color.Gray;
                    break;

                case LogSeverity.Debug:
                    color = Color.DarkGray;
                    break;
            }

            LogMessage(this, new RuntimeLogEventArgs(message, color));

            if (exceptionData != null)
                LogMessage(this, new RuntimeLogEventArgs(exceptionData.ToString(), color));
        }
Ejemplo n.º 25
0
        public async Task <UsageDataTableResult> GetExceptions(Guid telemetryKey, TelemetryItemTypes itemType, int skip
                                                               , int take, IEnumerable <Tuple <string, bool> > sortBy, ISearch requestSearch
                                                               , List <string> searchableColumns)
        {
            Program program = await this.portalContext.Programs.FirstOrDefaultAsync(x => x.TelemetryKey == telemetryKey).ConfigureAwait(false);

            if (program == null)
            {
                throw new ArgumentException($"Program with key {telemetryKey} does not exist");
            }

            IQueryable <ExceptionInfo> query = this.telemetryContext.Exceptions.Where(x => x.ProgramId == program.Id);
            int totalCount = await this.telemetryContext.Exceptions.CountAsync(x => x.ProgramId == program.Id).ConfigureAwait(false);

            if (take == -1)
            {
                take = totalCount;
            }



            IQueryable <ExceptionInfo> filteredQuery = EntityFilter.Match(query
                                                                          , property => property.Contains(requestSearch.Value)
                                                                          , new List <Expression <Func <ExceptionInfo, string> > >()
            {
                { x => x.Sequence },
                { x => x.Message },
                { x => x.TypeName },
                { x => x.ProgramVersion },
                { x => x.ParsedStack },
                { x => x.UserName },
            });


            List <ExceptionInfo> ordered = await ApplyOrderingQuery(sortBy, filteredQuery, skip, take).ConfigureAwait(false);

            List <ExceptionData> result = new List <ExceptionData>();

            foreach (ExceptionInfo exception in ordered)
            {
                ExceptionData data = new ExceptionData
                {
                    Timestamp        = exception.Timestamp
                    , UserName       = exception.UserName
                    , EntryKey       = exception.TypeName
                    , Note           = exception.Note
                    , ProgramVersion = exception.ProgramVersion
                    , Sequence       = exception.Sequence
                    , ErrorMessage   = exception.Message
                    , StackTrace     = GetStackTrace(exception.ParsedStack)
                    , Properties     = exception.TelemetryUnits.Where(x => x.UnitType == TelemetryUnit.UnitTypes.Property).ToDictionary(x => x.Key, x => x.ValueString)
                    , Metrics        = exception.TelemetryUnits.Where(x => x.UnitType == TelemetryUnit.UnitTypes.Metric).ToDictionary(x => x.Key, x => x.ValueDouble)
                };
                result.Add(data);
            }

            return(new UsageDataTableResult {
                TotalCount = totalCount, FilteredCount = totalCount, UsageData = result
            });
        }
Ejemplo n.º 26
0
        /// <inheritdoc />
        public override ExceptionData HandleException(IErrorDetail detail, Exception ex = null)
        {
            ExceptionData exceptionData = base.HandleException(detail, ex);

            exceptionData.Message = ex == null ? detail.WrapMessage : string.Format(detail.WrapMessage, ex.Message);
            return(exceptionData);
        }
Ejemplo n.º 27
0
        public GetConnectionString()
        {
            var configuration        = GetConfiguration();
            var connectionStringList = configuration.GetSection("DbSettings:ConnectionString").GetChildren().AsEnumerable().ToList();

            for (int i = 0; i < connectionStringList.Count; i++)
            {
                List <ExceptionData> exceptionDataList = new List <ExceptionData>();
                var connection = new SqlConnection(connectionStringList[i].Value);
                connection.Open();
                SqlCommand sqlCommand = new SqlCommand();
                sqlCommand.Connection  = connection;
                sqlCommand.CommandText = "SELECT * FROM ExceptionLog WHERE CreatedDate >= DATEADD(hour, -1, GETDATE())";
                SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
                if (sqlDataReader.HasRows)
                {
                    foreach (var unused in sqlDataReader)
                    {
                        ExceptionData exceptionData = new ExceptionData();
                        exceptionData.Id           = Int32.Parse(sqlDataReader["Id"].ToString() ?? string.Empty);
                        exceptionData.CreatedDate  = DateTime.Parse(sqlDataReader["CreatedDate"].ToString() ?? string.Empty);
                        exceptionData.Message      = sqlDataReader["Message"].ToString();
                        exceptionData.StackTrace   = sqlDataReader["StackTrace"].ToString();
                        exceptionData.DatabaseName = connection.Database;
                        exceptionDataList.Add(exceptionData);
                    }
                    if (exceptionDataList.Count >= 10)
                    {
                        _exceptionData.Add(exceptionDataList);
                    }
                }
                connection.Close();
            }
        }
Ejemplo n.º 28
0
 /// <inheritdoc />
 protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
 {
     if (severity >= minSeverity)
     {
         logger.Log(severity, message, exceptionData);
     }
 }
Ejemplo n.º 29
0
        public void PopulatesPropertiesFromException()
        {
            Exception inner = new Exception("Foo");
            PopulateStackTrace(inner);

            SampleException outer = new SampleException("Bar", inner)
            {
                Prop1 = "Value1",
                Prop2 = "Value2"
            };
            PopulateStackTrace(outer);

            ExceptionData outerData = new ExceptionData(outer);
            Assert.AreEqual(outer.GetType().FullName, outerData.Type);
            Assert.AreEqual(outer.Message, outerData.Message);
            Assert.AreEqual(new PropertySet() {
                    { "Prop1", "Value1" },
                    { "Prop2", "Value2" }
                }, outerData.Properties);
            Assert.AreEqual(outer.StackTrace, outerData.StackTrace.ToString());
            Assert.IsNotNull(outerData.InnerException);

            ExceptionData innerData = outerData.InnerException;
            Assert.AreEqual(inner.GetType().FullName, innerData.Type);
            Assert.AreEqual(inner.Message, innerData.Message);
            Assert.AreEqual(inner.StackTrace, innerData.StackTrace.ToString());
            Assert.IsNull(innerData.InnerException);
        }
Ejemplo n.º 30
0
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            if (exceptionData != null)
            {
                message += "\n" + exceptionData;
            }

            switch (severity)
            {
            case LogSeverity.Error:
                taskLoggingHelper.LogError(message);
                break;

            case LogSeverity.Warning:
                taskLoggingHelper.LogWarning(message);
                break;

            case LogSeverity.Important:
                taskLoggingHelper.LogMessage(MessageImportance.High, message);
                break;

            case LogSeverity.Info:
                taskLoggingHelper.LogMessage(MessageImportance.Normal, message);
                break;

            case LogSeverity.Debug:
                taskLoggingHelper.LogMessage(MessageImportance.Low, message);
                break;
            }
        }
Ejemplo n.º 31
0
        public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Exception != null)
            {
                if (context.Exception is OperationCanceledException || context.Exception is HttpResponseException)
                {
                    // ignore canceled operation
                }
                else
                {
                    var baseException = context.Exception.GetBaseException();
                    var exceptionData = new ExceptionData
                    {
                        Name    = baseException.GetType().Name,
                        Message = baseException.Message
                    };

                    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content      = new ObjectContent <ExceptionData>(exceptionData, JsonFormatter),
                        ReasonPhrase = context.Exception.GetType().Name
                    });
                }
            }
        }
Ejemplo n.º 32
0
        public void ExceptionDataExpectedReadFailure()
        {
            // exceptionProperty points to non-existent property
            EventData eventData = new EventData();

            EventMetadata exceptionMetadata = new EventMetadata("exception");

            exceptionMetadata.Properties.Add("exceptionProperty", "exception");

            var result = ExceptionData.TryGetData(eventData, exceptionMetadata, out ExceptionData exceptionData);

            Assert.Equal(DataRetrievalStatus.DataMissingOrInvalid, result.Status);
            Assert.Contains("The expected event property 'exception'", result.Message);

            // exceptionProperty does not contain and Exception object
            eventData.Payload.Add("exception", Guid.NewGuid());
            result = ExceptionData.TryGetData(eventData, exceptionMetadata, out exceptionData);
            Assert.Equal(DataRetrievalStatus.DataMissingOrInvalid, result.Status);
            Assert.Contains("The expected event property 'exception'", result.Message);

            // Just make sure that after addressing all the issues you can read all the data successfully
            eventData.Payload["exception"] = new Exception();
            result = ExceptionData.TryGetData(eventData, exceptionMetadata, out exceptionData);
            Assert.Equal(DataRetrievalStatus.Success, result.Status);
        }
        public void ListingInitializationFailure(ref ExceptionData ex)
        {
            Complete = true;
            Aborted = true;
            LastException = ex;

        }
Ejemplo n.º 34
0
 private void lblInformation_Click(object sender, EventArgs e)
 {
     if (this.emailSendingError != null)
     {
         ExceptionData errObj = new ExceptionData(this.emailSendingError);
         new ErrorReporter(errObj, false, false, string.Empty).Show();
     }
 }
Ejemplo n.º 35
0
 public Exception(ExceptionData data,
                  IExceptionDataSaver dataSaver,
                  IExceptionFactory exceptionFactory)
 {
     _data             = data;
     _dataSaver        = dataSaver;
     _exceptionFactory = exceptionFactory;
 }
Ejemplo n.º 36
0
        public void Should_not_fail_on_empty_tags()
        {
            var logEventData = ExceptionData.FromTags(HerculesTags.Empty);

            logEventData.Type.Should().BeNull();
            logEventData.Message.Should().BeNull();
            logEventData.InnerExceptions.Should().BeNull();
        }
Ejemplo n.º 37
0
        [HttpPost()]                                                            //Create
        public IActionResult Add([FromBody] Address value)
        {
            try
            {
                if (value.Id != 0)
                {
                    return(StatusCode(StatusCodes.Status406NotAcceptable));
                }
                List <Address> AddressList = _AddressRepo.Create(value);
                if (AddressList == null)
                {
                    return(StatusCode(StatusCodes.Status206PartialContent));
                }
                else if (AddressList != null)
                {
                    return(StatusCode(StatusCodes.Status201Created, AddressList));
                }
                else
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError));
                }
            }
            catch (Helper.RepoException ex)
            {
                switch (ex.Type)
                {
                case EnumResultTypes.INVALIDARGUMENT:
                    return(StatusCode(StatusCodes.Status400BadRequest));

                case EnumResultTypes.NOTFOUND:
                    return(StatusCode(StatusCodes.Status204NoContent));

                case EnumResultTypes.SQLERROR:
                    return(StatusCode(StatusCodes.Status408RequestTimeout));

                case EnumResultTypes.ERROR:
                    return(StatusCode(StatusCodes.Status500InternalServerError));

                default:
                    return(StatusCode(StatusCodes.Status501NotImplemented));
                }
            }
            catch (Exception ex)
            {
                var logObj2 = new ExceptionData(ex);
                logObj2.CustomNumber = 123;
                logObj2.CustomText   = "abs";
                logObj2.Add("start_time", DateTime.UtcNow);
                logObj2.Add("myObject", new
                {
                    TappId = 15,
                    Name   = "Sebastian"
                });
                _logger.Error(logObj2);
                return(StatusCode(StatusCodes.Status501NotImplemented));
            }
        }
Ejemplo n.º 38
0
        /// <excludedoc />
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            message = String.Format("[{0}] {1}", severity.ToString().ToLowerInvariant(), message);

            if (exceptionData != null)
                writer.WriteException(exceptionData, message);
            else
                writer.WriteLine(message);
        }
        /// <summary>
        /// Creates a log event.
        /// </summary>
        /// <param name="severity">The log severity.</param>
        /// <param name="message">The log message.</param>
        /// <param name="exceptionData">The exception data, or null if none.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="message"/> is null.</exception>
        public LogEntrySubmittedEventArgs(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            if (message == null)
                throw new ArgumentNullException("message");

            Severity = severity;
            Message = message;
            ExceptionData = exceptionData;
        }
Ejemplo n.º 40
0
        [HttpGet("{id}")]                                                       //Read
        public IActionResult GetAddress(int Id)
        {
            try
            {
                var Address = _AddressRepo.Read(Id);
                if (Address.Count == 1)
                {
                    return(StatusCode(StatusCodes.Status302Found, Address));
                }
                else if (Address.Count < 1)
                {
                    return(StatusCode(StatusCodes.Status204NoContent));
                }
                else if (Address.Count > 1)
                {
                    return(StatusCode(StatusCodes.Status207MultiStatus));
                }
                else
                {
                    return(StatusCode(StatusCodes.Status400BadRequest));
                }
            }
            catch (Helper.RepoException ex)
            {
                switch (ex.Type)
                {
                case EnumResultTypes.INVALIDARGUMENT:
                    return(StatusCode(StatusCodes.Status400BadRequest));

                case EnumResultTypes.NOTFOUND:
                    return(StatusCode(StatusCodes.Status204NoContent));

                case EnumResultTypes.SQLERROR:
                    return(StatusCode(StatusCodes.Status408RequestTimeout));

                case EnumResultTypes.ERROR:
                    return(StatusCode(StatusCodes.Status500InternalServerError));

                default:
                    return(StatusCode(StatusCodes.Status501NotImplemented));
                }
            }
            catch (Exception ex)
            {
                var logObj1 = new ExceptionData(ex);
                logObj1.CustomNumber = 123;
                logObj1.CustomText   = "abs";
                logObj1.Add("start_time", DateTime.UtcNow);
                logObj1.Add("myObject", new
                {
                    TappId = 15,
                    Name   = "Sebastian"
                });
                _logger.Error(logObj1);
                return(StatusCode(StatusCodes.Status501NotImplemented));
            }
        }
Ejemplo n.º 41
0
        public void ExceptionData_CreateExceptionData_ShouldCreateAValidExceptionData()
        {
            var obj  = default(ExceptionData);
            var obj2 = default(ExceptionData);
            var obj3 = default(ExceptionData);

            try
            {
                throw new Exception("This is a Test");
            }
            catch (Exception ex)
            {
                obj = new ExceptionData(ex);
            }

            try
            {
                throw new OutOfMemoryException("This is 2 a Test");
            }
            catch (Exception ex)
            {
                obj2 = new ExceptionData(ex, true);
            }

            try
            {
                throw new IndexOutOfRangeException("This is a Test #3");
            }
            catch (Exception ex)
            {
                obj3 = new ExceptionData(ex, true);
            }

            obj.Should().NotBeNull(null, null);
            obj.IsUnhandledException.Should().BeFalse(null, null);
            obj.GetAssemblyInfo().Should().NotBeNullOrEmpty(null, null);
            obj.CurrentException.Should().BeOfType <Exception>(null, null);
            obj.CurrentException.Message.Should().Be("This is a Test", null, null);
            obj.SysInfoToString().Should().NotBeNullOrEmpty(null, null);
            obj.GetErrorLocations().Count.Should().BeGreaterThan(0, null, null);
            obj.ExceptionToString().Should().NotBeNullOrEmpty(null, null);
            obj.GetExceptionType().Should().Be("Exception Type:           " + obj.CurrentException.GetType().FullName, null, null);
            obj.GetEnhancedStackTrace().Should().NotBeNullOrEmpty(null, null);

            obj2.Should().NotBeNull(null, null);
            obj2.IsUnhandledException.Should().BeTrue(null, null);
            obj2.GetAssemblyInfo().Should().NotBeNullOrEmpty(null, null);
            obj2.CurrentException.Should().BeOfType <OutOfMemoryException>(null, null);
            obj2.CurrentException.Message.Should().Be("This is 2 a Test", null, null);
            obj2.SysInfoToString().Should().NotBeNullOrEmpty(null, null);
            obj2.GetErrorLocations().Count.Should().BeGreaterThan(0, null, null);
            obj2.ExceptionToString().Should().NotBeNullOrEmpty(null, null);
            obj2.GetExceptionType().Should().Be("Exception Type:           " + obj2.CurrentException.GetType().FullName, null, null);
            obj.GetEnhancedStackTrace().Should().NotBeNullOrEmpty(null, null);

            obj3.IsUnhandledException.Should().BeTrue(null, null);
        }
Ejemplo n.º 42
0
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            if (severity >= LogSeverity.Warning)
            {
                string warning = exceptionData == null
                    ? message
                    : string.Concat(message, "\n", exceptionData.ToString());

                warningHandler.Write(this, new WarningEventArgs(warning));
            }
        }
Ejemplo n.º 43
0
        /// <inheritdoc />
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            textWriter.WriteLine(message);
            if (exceptionData != null)
            {
                textWriter.Write("  ");
                textWriter.WriteLine(exceptionData);
            }

            textWriter.Flush();
        }
Ejemplo n.º 44
0
        public void Log_WhenListenerRegisteredThenUnregistered_DoesNotCallListener()
        {
            DispatchLogger logger = new DispatchLogger();
            ILogger listener = MockRepository.GenerateMock<ILogger>();
            var ex = new ExceptionData(new Exception("foo"));
            logger.AddLogListener(listener);
            logger.RemoveLogListener(listener);

            logger.Log(LogSeverity.Important, "Message", ex);

            listener.VerifyAllExpectations();
        }
Ejemplo n.º 45
0
        /// <inheritdoc />
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            lock (console.SyncRoot)
            {
                bool oldFooterVisible = console.FooterVisible;
                try
                {
                    console.FooterVisible = false;

                    if (!console.IsRedirected)
                    {
                        switch (severity)
                        {
                            case LogSeverity.Error:
                                console.ForegroundColor = ConsoleColor.Red;
                                break;

                            case LogSeverity.Warning:
                                console.ForegroundColor = ConsoleColor.Yellow;
                                break;

                            case LogSeverity.Important:
                                console.ForegroundColor = ConsoleColor.White;
                                break;

                            case LogSeverity.Info:
                                console.ForegroundColor = ConsoleColor.Gray;
                                break;

                            case LogSeverity.Debug:
                                console.ForegroundColor = ConsoleColor.DarkGray;
                                break;
                        }
                    }

                    console.WriteLine(message);

                    if (exceptionData != null)
                        console.WriteLine(Indent(exceptionData.ToString()));

                    if (!console.IsRedirected)
                    {
                        console.ResetColor();
                    }
                }
                finally
                {
                    console.FooterVisible = oldFooterVisible;
                }
            }
        }
Ejemplo n.º 46
0
        /// <inheritdoc />
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            if (severity < LogSeverity.Info)
                return;

            StringBuilder output = new StringBuilder();
            output.AppendLine(message);
            if (exceptionData != null)
            {
                output.Append("  ");
                output.AppendLine(exceptionData.ToString());
            }

            IVsOutputWindowPane outputWindowPane = GetOutputWindowPane();
            outputWindowPane.OutputStringThreadSafe(output.ToString());
        }
Ejemplo n.º 47
0
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            TestOutcome outcome;
            if (severity == LogSeverity.Warning)
                outcome = TestOutcome.Warning;
            else if (severity == LogSeverity.Error)
                outcome = TestOutcome.Error;
            else
                return;

            if (exceptionData != null)
                message = string.Concat(message, "\n", exceptionData.ToString());

            TestRunTextResultMessage resultMessage = new TestRunTextResultMessage(runContext.RunConfig.TestRun.Id, message);
            resultMessage.Outcome = outcome;

            runContext.ResultSink.AddResult(resultMessage);
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Logs a message.
        /// </summary>
        /// <param name="severity">The log message severity.</param>
        /// <param name="message">The message to log.</param>
        /// <param name="exceptionData">The exception to log (it can be null).</param>
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            // The PowerShell logging methods may throw InvalidOperationException
            // or NotImplementedException if the PowerShell host is not connected
            // or does not support the requested service.  So we eat those exceptions.
            cmdlet.PostMessage(delegate
            {
                try
                {
                    if (exceptionData != null)
                        message = string.Concat(message, "\n", exceptionData.ToString());

                    switch (severity)
                    {
                        case LogSeverity.Error:
                            cmdlet.WriteError(new ErrorRecord(new Exception(message), "Error", ErrorCategory.NotSpecified, "Gallio"));
                            break;

                        case LogSeverity.Warning:
                            cmdlet.WriteWarning(message);
                            break;

                        case LogSeverity.Important:
                        case LogSeverity.Info:
                            cmdlet.WriteVerbose(message);
                            break;

                        case LogSeverity.Debug:
                            cmdlet.WriteDebug(message);
                            break;
                    }
                }
                catch (NotImplementedException)
                {
                }
                catch (InvalidOperationException)
                {
                }
            });
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Filters the stack trace information about an exception.
        /// </summary>
        /// <param name="exception">The exception data.</param>
        /// <returns>The filtered exception data.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="exception"/>
        /// is null.</exception>
        public static ExceptionData FilterException(ExceptionData exception)
        {
            if (exception == null)
                throw new ArgumentNullException("exception");

            return new ExceptionData(exception.Type, exception.Message,
                FilterStackFrames(EnumerateStackFrameInfo(exception.StackTrace.ToString())),
                exception.Properties,
                exception.InnerException != null ? FilterException(exception.InnerException) : null);
        }
Ejemplo n.º 50
0
 /// <excludedoc />
 protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
 {
 }
Ejemplo n.º 51
0
        private static object Merge(SentryEvent @event)
        {
            var exception = @event.Exception;
            var extra = @event.Extra;

            if (exception == null && extra == null)
                return null;

            if (extra != null && exception == null)
                return extra;

            var exceptionData = new ExceptionData(exception);

            if (extra == null)
                return exceptionData;

            JObject result;

            if (extra.GetType().IsArray)
            {
                result = new JObject();
                var array = JArray.FromObject(extra);

                foreach (var o in array)
                {
                    var jo = o as JObject;
                    JProperty[] properties;

                    if (jo == null || (properties = jo.Properties().ToArray()).Length != 2 || properties[0].Name != "Key"
                        || properties[1].Name != "Value")
                    {
                        result.Merge(o);
                        continue;
                    }

                    var key = properties[0].Value.ToString();
                    var value = properties[1].Value;
                    result.Add(key, value);
                }
            }
            else
                result = JObject.FromObject(extra);

            var jExceptionData = JObject.FromObject(exceptionData);
            result.Merge(jExceptionData);

            return result;
        }
Ejemplo n.º 52
0
        private ExceptionData GetDataFromZip(Stream stream)
        {
            var results = new ExceptionData();
            var zipStorer = ZipStorer.Open(stream, FileAccess.Read);
            using (Stream zipItemStream = new MemoryStream())
            {
                var zipDirectory = zipStorer.ReadCentralDir();
                foreach (var entry in zipDirectory)
                {
                    if (Path.GetFileName(entry.FilenameInZip) == StoredItemFile.Exception)
                    {
                        zipItemStream.SetLength(0);
                        zipStorer.ExtractFile(entry, zipItemStream);
                        zipItemStream.Position = 0;
                        var deserializer = new XmlSerializer(typeof(SerializableException));
                        results.Exception = (SerializableException)deserializer.Deserialize(zipItemStream);
                        zipItemStream.Position = 0;
                    }
                    else if (Path.GetFileName(entry.FilenameInZip) == StoredItemFile.Report)
                    {
                        zipItemStream.SetLength(0);
                        zipStorer.ExtractFile(entry, zipItemStream);
                        zipItemStream.Position = 0;
                        var deserializer = new XmlSerializer(typeof(Report));
                        results.Report = (Report)deserializer.Deserialize(zipItemStream);
                        zipItemStream.Position = 0;
                    }
                }
            }

            return results;
        }
Ejemplo n.º 53
0
 /// <inheritdoc />
 protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
 {
     inner.Log(severity, SeverityPrefixes[severity] + message, exceptionData);
 }
Ejemplo n.º 54
0
 /// <summary>
 /// Logs a message with an associated exception.
 /// </summary>
 /// <param name="severity">The log message severity.</param>
 /// <param name="message">The log message, not null.</param>
 /// <param name="exceptionData">The associated exception data, or null if none.</param>
 protected abstract void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData);
Ejemplo n.º 55
0
        /// <summary>
        /// Writes an exception within its own section which provides additional cues for interpretation.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The exception will not be terminated by a new line.
        /// </para>
        /// </remarks>
        /// <param name="exception">The exception data to write.</param>
        /// <param name="sectionName">The section name, or null if none.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="exception"/> is null.</exception>
        public void WriteException(ExceptionData exception, string sectionName)
        {
            if (exception == null)
                throw new ArgumentNullException(@"exception");

            using (sectionName != null ? BeginSection(sectionName) : null)
                StackTraceFilter.FilterException(exception).WriteTo(this);
        }
Ejemplo n.º 56
0
 /// <summary>
 /// Writes an exception.
 /// </summary>
 /// <remarks>
 /// <para>
 /// The exception will not be terminated by a new line.
 /// </para>
 /// </remarks>
 /// <param name="exception">The exception data to write.</param>
 /// <exception cref="ArgumentNullException">Thrown if <paramref name="exception"/> is null.</exception>
 public void WriteException(ExceptionData exception)
 {
     WriteException(exception, null);
 }
Ejemplo n.º 57
0
 public void Finished(object result, ExceptionData exception)
 {
     this.result = result;
     this.exception = exception;
     finish.Set();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ExceptionTelemetry"/> class with empty properties.
 /// </summary>
 public ExceptionTelemetry()
 {
     this.Data = new ExceptionData();
     this.context = new TelemetryContext(this.Data.properties, new Dictionary<string, string>());
     this.HandledAt = default(ExceptionHandledAt);
 }
Ejemplo n.º 59
0
        /// <summary>
        /// Enumerate all protocols to see if they are properly configured and send using the ones that are configured
        /// as many times as necessary.
        /// </summary>
        /// <param name="reportFile">The file to read the report from.</param>
        /// <returns>Returns <see langword="true"/> if the sending was successful.
        /// Returns <see langword="true"/> if the report was submitted to at least one destination.</returns>
        private bool EnumerateDestinations(Stream reportFile, ExceptionData exceptionData)
        {
            var sentSuccessfullyAtLeastOnce = false;
            var fileName = Path.GetFileName(((FileStream)reportFile).Name);
            foreach (var destination in Settings.Destinations)
            {
                try
                {
                    Logger.Trace(string.Format("Submitting bug report via {0}.", destination.GetType().Name));
                    if (destination.Send(fileName, reportFile, exceptionData.Report, exceptionData.Exception))
                    {
                        sentSuccessfullyAtLeastOnce = true;
                    }
                }
                catch (Exception exception)
                {
                    Logger.Error(
                        string.Format("An exception occurred while submitting bug report with {0}. Check the inner exception for details.", destination.GetType().Name),
                        exception);
                }
            }

            return sentSuccessfullyAtLeastOnce;
        }
        /// <summary>
        /// Adds an exception to the assertion failure.
        /// </summary>
        /// <param name="ex">The exception data to add.</param>
        /// <returns>The builder, to allow for fluent method chaining.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="ex"/> is null.</exception>
        public AssertionFailureBuilder AddException(ExceptionData ex)
        {
            if (ex == null)
                throw new ArgumentNullException("ex");

            if (exceptions == null)
                exceptions = new List<ExceptionData>();
            exceptions.Add(StackTraceFilter.FilterException(ex));
            return this;
        }