public void GetValue_ValueFactoryThrows(bool specifyJtf)
        {
            var exception            = new InvalidOperationException();
            var completeValueFactory = new AsyncManualResetEvent();
            var jtf  = specifyJtf ? new JoinableTaskContext().Factory : null; // use our own so we don't get main thread deadlocks, which isn't the point of this test.
            var lazy = new AsyncLazy <GenericParameterHelper>(() => throw exception, jtf);

            // Verify that we throw the right exception the first time.
            Assert.Same(exception, Assert.Throws(exception.GetType(), () => lazy.GetValue()));

            // Assert that we rethrow the exception the second time.
            Assert.Same(exception, Assert.Throws(exception.GetType(), () => lazy.GetValue()));
        }
        public static void MetadataApiException_Constructor_For_Serialization_Can_Be_Serialized()
        {
            // Arrange
            InvalidOperationException innerException = new InvalidOperationException();
            string message = Guid.NewGuid().ToString();

            // Act
            MetadataApiException target = new MetadataApiException(message, innerException);

            BinaryFormatter formatter = new BinaryFormatter();

            MetadataApiException deserialized;

            using (MemoryStream stream = new MemoryStream())
            {
                formatter.Serialize(stream, target);
                stream.Seek(0L, SeekOrigin.Begin);
                deserialized = formatter.Deserialize(stream) as MetadataApiException;
            }

            // Assert
            Assert.NotNull(deserialized);
            Assert.NotNull(deserialized.InnerException);
            Assert.IsType(innerException.GetType(), deserialized.InnerException);
            Assert.Equal(deserialized.Message, target.Message);
        }
Exemple #3
0
        public void TestPropIfItThrewException()
        {
            InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => this.database =
                                                                                         new Database(new int[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }));

            Assert.AreEqual(ex.GetType(), typeof(InvalidOperationException));
        }
Exemple #4
0
        public void Execute_ExceptionIsPassedToInterceptors()
        {
            var executable = A.Fake <IExecutable <string, string> >();
            var exception  = new InvalidOperationException();

            A.CallTo(() => executable.Execute("parameter hello")).Throws(exception);

            var generalInterceptor1 = A.Fake <IExecutionInterceptor>();

            A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);

            var generalInterceptor2 = A.Fake <IExecutionInterceptor>();

            A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);

            var specificInterceptor = A.Fake <IExecutionInterceptor <IExecutable <string, string>, string, string> >();

            A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);

            ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
            var             executor        = serviceProvider.GetRequiredService <IExecutor>();

            _ = Assert.Throws(exception.GetType(), () => executor.Execute <IExecutable <string, string>, string, string>("parameter hello"));

            // interceptors called in ascending OrderIndex order
            _ = A.CallTo(() => generalInterceptor1.Before(executable, "parameter hello")).MustHaveHappenedOnceExactly()
                .Then(A.CallTo(() => specificInterceptor.Before(executable, "parameter hello")).MustHaveHappenedOnceExactly())
                .Then(A.CallTo(() => generalInterceptor2.Before(executable, "parameter hello")).MustHaveHappenedOnceExactly())
                // executable called
                .Then(A.CallTo(() => executable.Execute("parameter hello")).MustHaveHappenedOnceExactly())
                // interceptors called in descending OrderIndex order
                .Then(A.CallTo(() => generalInterceptor2.After(executable, "parameter hello", default(string), exception)).MustHaveHappenedOnceExactly())
                .Then(A.CallTo(() => specificInterceptor.After(executable, "parameter hello", default(string), exception)).MustHaveHappenedOnceExactly())
                .Then(A.CallTo(() => generalInterceptor1.After(executable, "parameter hello", default(string), exception)).MustHaveHappenedOnceExactly());
        }
Exemple #5
0
        public void Output_ExceptionProperties()
        {
            // Arrange
            var testEnricher   = new TestEnricher();
            var testOutputSink = new TestSinkWithFormatter(new NewRelicFormatter());
            var testLogger     = TestHelpers.GetLogger(testOutputSink, testEnricher);
            var testException  = new InvalidOperationException(TestErrMsg);

            // Act
            try
            {
                TestHelpers.CreateStackTracedError(0, testException, 3);
            }
            catch (Exception ex)
            {
                testLogger.Error(ex, LogMessage);
            }

            // Assert
            Asserts.NoSerilogErrorsCountOutputs(_testRunDebugLogs, testOutputSink.InputsAndOutputs, LogMessage);

            var resultDic = TestHelpers.SerializeOutputJSON(testOutputSink.InputsAndOutputs[0]);

            Asserts.PropertyCountsMatch(testEnricher, countIntrinsicProperties + 3, resultDic);
            Asserts.KeyAndValueMatch(resultDic, "error.message", TestErrMsg);
            Asserts.KeyAndValueMatch(resultDic, "error.class", testException.GetType().FullName);
            Asserts.KeyAndValueMatch(resultDic, "error.stack", testException.StackTrace);
        }
        public void ValidateToken_ISecurityTokenValidator_WhenFailure_ExpectInnerException()
        {
            var token = Guid.NewGuid().ToString();
            var validationParameters = new TokenValidationParameters();

            var expectedException = new InvalidOperationException("test");

            var mockHandler = new Mock <TestJwtPayloadTokenHandler> {
                CallBase = true
            };

            mockHandler.Setup(x => x.ValidateToken(token, validationParameters))
            .Returns(new TokenValidationResult
            {
                IsValid   = false,
                Exception = expectedException
            });

            SecurityToken parsedToken = null;
            var           exception   = Assert.Throws(
                expectedException.GetType(),
                () => mockHandler.Object.ValidateToken(token, validationParameters, out parsedToken));

            parsedToken.Should().BeNull();
            exception.Should().Be(expectedException);
        }
Exemple #7
0
        public void ProcessError_LoggingWorksWithUnrecognizedExceptionObject()
        {
            ILog log = Substitute.For <ILog>();
            IProcessWrapperFactory procFactory = Substitute.For <IProcessWrapperFactory>();

            procFactory.CreateProcess().Returns(new FakeStandardProcess());
            var serviceApp = new ServiceApp {
                Name = "Test", AppVersion = new Version()
            };
            ServiceAppProcess appProcToTest = new ServiceAppProcess(serviceApp, log, procFactory);
            Exception         testException = new InvalidOperationException("test");

            string exceptionMessage = string.Format(@"{{ error: {{
                    details: {{
                        type: ""{0}"",
                        message: ""{1}"",
                        source: ""{2}"",
                        stackTrace: ""{3}""
                    }},
                    exception: ""xxxxx""
                }} }}",
                                                    testException.GetType().ToString(),
                                                    testException.Message,
                                                    testException.Source,
                                                    testException.StackTrace);

            bool shouldExit = appProcToTest.ProcessMessage(exceptionMessage);

            log.Received().Warn(Arg.Any <string>());
            Assert.IsFalse(shouldExit, "Process message was not meant to return true");
        }
Exemple #8
0
        private void HandleOperationException(InvalidOperationException e, HttpWebResponse response)
        {
            Func <Stream> getResponseStream      = null;
            Descriptor    descriptor             = base.ChangedEntries[base.entryIndex];
            Dictionary <string, string> headers  = null;
            HttpStatusCode internalServerError   = HttpStatusCode.InternalServerError;
            Version        parsedResponseVersion = null;

            if (response != null)
            {
                headers = WebUtil.WrapResponseHeaders(response);
                base.HandleOperationResponseHeaders(response.StatusCode, headers);
                if (getResponseStream == null)
                {
                    getResponseStream = () => WebUtil.GetResponseStream(response, (DataServiceContext)this.Source);
                }
                e = BaseSaveResult.HandleResponse(base.RequestInfo, response.StatusCode, response.Headers["DataServiceVersion"], getResponseStream, false, out parsedResponseVersion);
                internalServerError = response.StatusCode;
            }
            else
            {
                headers = new Dictionary <string, string>(StringComparer.Ordinal);
                headers.Add("Content-Type", "text/plain");
                if (e.GetType() != typeof(DataServiceClientException))
                {
                    e = new DataServiceClientException(e.Message, e);
                }
            }
            this.cachedResponses.Add(new CachedResponse(descriptor, headers, internalServerError, parsedResponseVersion, null, e));
            base.perRequest = null;
            this.CheckContinueOnError();
        }
Exemple #9
0
        // This snapshot won't contain full normal data for Function.FullName, Function.ShortName and Function.Parameters.
        // (All we know is an unavailable function ID; which function location method info to use is a mystery.)
        private static FunctionCompletedMessage CreateFailedMessage(CallAndOverrideMessage message)
        {
            DateTimeOffset startAndEndTime = DateTimeOffset.UtcNow;
            Exception      exception       = new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
                                                                                         "No function '{0}' currently exists.", message.FunctionId));

            // In theory, we could also set HostId, HostInstanceId and WebJobRunId; we'd just have to expose that data
            // directly to this Worker class.
            return(new FunctionCompletedMessage
            {
                FunctionInstanceId = message.Id,
                Function = new FunctionDescriptor
                {
                    Id = message.FunctionId
                },
                Arguments = message.Arguments,
                ParentId = message.ParentId,
                Reason = message.Reason,
                StartTime = startAndEndTime,
                EndTime = startAndEndTime,
                Failure = new FunctionFailure
                {
                    Exception = exception,
                    ExceptionType = exception.GetType().FullName,
                    ExceptionDetails = exception.Message
                }
            });
        }
        public void can_create_degraded_with_exception_info()
        {
            var exception       = new InvalidOperationException();
            var exceptionString = $"EXCEPTION: {exception.GetType().Name} - {exception.Message}";
            var result          = HealthCheckResult.Degraded(exception);

            result.Message.Should().StartWith(exceptionString);
            result.Status.Should().Be(HealthCheckStatus.Degraded);
        }
        public void ReportException_ExceptionWithMessage_ReportsToGitHub()
        {
            var exception = new InvalidOperationException("Moon exploded :(");

            reporter.ReportException(new UnhandledExceptionEventArgs(exception, true));

            Assert.StartsWith("https://github.com/waf/replay-csharp/issues/new", reportedUrl);
            Assert.Contains(Uri.EscapeDataString(exception.Message), reportedUrl);
            Assert.Contains(Uri.EscapeDataString(exception.GetType().Name), reportedUrl);
        }
Exemple #12
0
        public void IndexViewResultRedirectCorrect()
        {
            InvalidOperationException exception = new InvalidOperationException();

            ErrorController controller = new ErrorController();

            ViewResult result = controller.Index(exception.GetType().Name) as ViewResult;

            Assert.AreEqual("NotFound", result.ViewName);
        }
        public void TestCreateMatroshika()
        {
            var value  = new InvalidOperationException(Guid.NewGuid().ToString(), new Exception());
            var result = ExceptionDispatchInfo.CreateMatroshika(value);

            Assert.That(result, Is.Not.Null);
            Assert.That(result, Is.TypeOf(value.GetType()));
            Assert.That(result.Message, Is.EqualTo(value.Message));
            Assert.That(result.InnerException, Is.SameAs(value));
        }
Exemple #14
0
    public void Ctor_CopyFrom_InnerExceptions()
    {
        var template  = new InvalidOperationException("outer", new InvalidCastException("inner"));
        var errorData = new CommonErrorData(template);

        Assert.Equal(template.GetType().FullName, errorData.TypeName);
        Assert.Equal(template.Message, errorData.Message);
        Assert.Equal(template.InnerException.GetType().FullName, errorData.Inner?.TypeName);
        Assert.Equal(template.InnerException.Message, errorData.Inner?.Message);
    }
        /// <summary>
        /// get packet from packet cache or decode from buffer.
        /// </summary>
        /// <param name="timeout">
        /// a TimeSpan object that specifies the timeout
        /// </param>
        /// <param name="removeEvent">
        /// a bool value that indicates whether need to remove the event from buffer.
        /// </param>
        /// <param name="remoteEndPoint">
        /// an object that specifies the remote endpoint.
        /// </param>
        /// <returns>
        /// a StackPacket object that contains the decoded packet.
        /// </returns>
        private StackPacket GetPacket(TimeSpan timeout, bool removeEvent, out object remoteEndPoint)
        {
            // get the packet in packet list.
            IPEndPointStackPacket packet = Utility.GetOne <IPEndPointStackPacket>(this.packetCache, null);

            if (packet != null)
            {
                remoteEndPoint = packet.RemoteEndPoint;

                return(packet.Packet);
            }

            UdpReceivedBytes bytes = this.buffer.Dequeue(timeout);

            remoteEndPoint = bytes.RemoteEndPoint;

            // exception event arrived
            if (bytes.Packet == null)
            {
                if (!removeEvent)
                {
                    this.buffer.Enqueue(bytes);
                }

                InvalidOperationException exc =
                    new InvalidOperationException("exception arrived when expect packet from udp.");

                // identify this exception.
                exc.Data.Add(exc.GetType().Name, true);

                throw exc;
            }

            // decode packets using data in buffer.
            int consumedLength = 0;
            int expectedLength = 0;

            StackPacket[] packets = this.decoder(remoteEndPoint, bytes.Packet, out consumedLength, out expectedLength);

            // if no packet, drop the recieved data and continue.
            if (packets == null || packets.Length == 0)
            {
                throw new InvalidOperationException("udp client failed to decode udp packet");
            }

            // if packet arrived, add to packet list, and return the first.
            foreach (StackPacket item in packets)
            {
                this.packetCache.Enqueue(
                    new IPEndPointStackPacket(item, bytes.RemoteEndPoint, bytes.LocalEndPoint));
            }

            // set timeout to zero. when packet is decoded, must not wait.
            return(GetPacket(new TimeSpan(), removeEvent, out remoteEndPoint));
        }
Exemple #16
0
        public void When_log_exception_Then_exception_is_in_output()
        {
            var message          = "Exception message.";
            var exceptionMessage = "Test exception thrown!";
            var exception        = new InvalidOperationException(exceptionMessage);

            Assert.Empty(output.Output);
            Log.Error(exception, message);
            Assert.Contains(message, output.Output);
            Assert.Contains(exception.GetType().FullName, output.Output);
            Assert.Contains(exceptionMessage, output.Output);
        }
        public void TestAddNewProp()
        {
            // TODO: AAA
            mod1 = new AllPropsRegisteredModel(PropBagTypeSafetyMode.AllPropsMustBeRegistered,
                                               _amHelpers.StoreAccessCreator, _amHelpers.PropFactory_V1);

            InvalidOperationException kk = new InvalidOperationException();

            Type tt = kk.GetType();

            Assert.Throws(tt, () => mod1["System.String", "NewProperty"] = "This is a a test.");
        }
Exemple #18
0
        public void Log_Sanitizes()
        {
            string secretReplacement = "[Hidden Credential]";
            string secretString      = "{ \"AzureWebJobsStorage\": \"DefaultEndpointsProtocol=https;AccountName=testAccount1;AccountKey=mykey1;EndpointSuffix=core.windows.net\", \"AnotherKey\": \"AnotherValue\" }";
            string sanitizedString   = $"{{ \"AzureWebJobsStorage\": \"{secretReplacement}\", \"AnotherKey\": \"AnotherValue\" }}";

            string secretException           = "Invalid string: \"DefaultEndpointsProtocol=https;AccountName=testaccount;AccountKey=testkey;BlobEndpoint=https://testaccount.blob.core.windows.net/;QueueEndpoint=https://testaccount.queue.core.windows.net/;TableEndpoint=https://testaccount.table.core.windows.net/;FileEndpoint=https://testaccount.file.core.windows.net/;\"";
            string sanitizedDetails          = $"System.InvalidOperationException : Invalid string: \"{secretReplacement}\"";
            string sanitizedExceptionMessage = $"Invalid string: \"{secretReplacement}\"";

            string    functionInvocationId = Guid.NewGuid().ToString();
            Exception ex = new InvalidOperationException(secretException);

            string properties = null;

            _mockEventGenerator.Setup(p => p.LogAzureMonitorDiagnosticLogEvent(LogLevel.Error, _websiteHostName, AzureMonitorDiagnosticLogger.AzureMonitorOperationName, AzureMonitorDiagnosticLogger.AzureMonitorCategoryName, _regionName, It.IsAny <string>()))
            .Callback <LogLevel, string, string, string, string, string>((t, r, o, c, l, p) =>
            {
                // Store off the properties for later validation
                properties = p;
            });

            using (CreateScope(functionName: _functionName, functionInvocationId: functionInvocationId))
            {
                _logger.LogError(ex, secretString);
            }

            _mockEventGenerator.VerifyAll();

            var level = LogLevel.Error;

            JObject actual   = JObject.Parse(properties);
            JObject expected = JObject.FromObject(new
            {
                appName          = _appServiceOptionsWrapper.CurrentValue.AppName,
                roleInstance     = _roleInstance,
                category         = _category,
                exceptionDetails = sanitizedDetails,
                exceptionMessage = sanitizedExceptionMessage,
                exceptionType    = ex.GetType().ToString(),
                functionInvocationId,
                functionName   = _functionName,
                hostInstanceId = _hostInstanceId,
                hostVersion    = ScriptHost.Version,
                level          = level.ToString(),
                levelId        = (int)level,
                message        = sanitizedString,
                processId      = _processId
            });

            Assert.True(JToken.DeepEquals(actual, expected), $"Actual: {actual.ToString()}{Environment.NewLine}Expected: {expected.ToString()}");
        }
Exemple #19
0
        public void SerializesProperties()
        {
            var exception = new InvalidOperationException("Some message")
            {
                HelpLink = "http://example.com"
            };
            var errors = new ErrorSerializer().Serialize(new ApiError(exception))["errors"][0];

            Assert.Equal(exception.Message, errors.Value <string>("title"));
            Assert.Equal(exception.HelpLink, errors["links"].Value <string>("about"));
            Assert.Equal(exception.GetType().FullName, errors.Value <string>("code"));
            Assert.Equal(exception.ToString(), errors.Value <string>("detail"));
        }
        public void Can_Log_Exceptions_On_Messages()
        {
            //In your code you'll want to inject the logger in the constructor,
            //generally from the .NET Core Dependency Injection framework.
            var logger = GetLogger <Basic_Logging_Tests>();

            var ex = new InvalidOperationException("The App Can't Do That");

            //We can associate an exception with a log message so it's available as data
            //but not necessarily in the message text itself
            logger.LogError(ex, "This message is an Error with an exception attached as data.");

            //Usually you'll want to include some information from the exception in your message.
            logger.LogError(ex, $"Unable to do what you wanted due to {ex.GetType()}\r\n" +
                            $"{ex.Message}");

            //Exceptions can be associated with any severity:  Just because it has
            //an exception as data doesn't necessarily mean it's an error; it could
            //be a retryable error like a network timeout.
            logger.LogDebug(ex, $"Retrying operation due to transient error {ex.GetType()}\r\n" +
                            $"{ex.Message}");
        }
//        private static string GetMessage(ModelValidationException ex)
//        {
//            var errors = new StringBuilder();
//            errors.AppendLine();
//#if DEBUG
//            errors.AppendLine($"[{ex.GetType().Name}]");
//#endif
//            errors.AppendLine($"داده های ارسالی به ساختار داده ای نامعتبر می باشد");
//            return errors.ToString();
//        }

        private static string GetMessage(InvalidOperationException ex)
        {
            var errors = new StringBuilder();

            errors.AppendLine();
#if DEBUG
            errors.AppendLine($"[{ex.GetType().Name}]");
#endif
            if (ex.Message.Contains("The model backing"))
            {
                errors.AppendLine("نسخه ی پایگاه داده با نسخه ی برنامه مطابقت ندارد.");
            }
            //  Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
            else if (ex.Message.Contains("maxJsonLength"))
            {
                errors.AppendLine("طول داده ی خروجی از حد مجاز تجاوز نموده است.");
            }
            else
            {
                errors.AppendLine($"{ex.GetType().Name}: {ex.Message}");
            }
            return(errors.ToString());
        }
        public void BuildMailMessageSubject_SubjectFormatStringWithExeptionTypeFormatItem_ReturnsExceptionType()
        {
            // Arrange
            string subjectFormatString = "{3}";
            var    expectedException   = new InvalidOperationException();
            var    entry = new LogEntry(LoggingEventType.Debug, "Some message", null, expectedException);

            // Act
            string subject =
                MailLoggingProvider.BuildMailMessageSubject(subjectFormatString, entry, DateTime.MaxValue);

            // Assert
            Assert.AreEqual(expectedException.GetType().Name, subject);
        }
        public void write_log_exception()
        {
            var ex = new InvalidOperationException("Fake Exception");

            _logger.ErrorException(_uniqueMessage, ex);


            VerifyLog(StoredModel, LogLevel.Error);
            StoredModel.Message.Should().Be(_uniqueMessage + ": " + ex.Message);
            StoredModel.ExceptionType.Should().Be(ex.GetType().ToString());
            StoredModel.Exception.Should().Be(ex.ToString());

            ExceptionVerification.ExpectedErrors(1);
        }
        public void TestAddNewProp()
        {
            // TODO: AAA
            mod1 = new OnlyTypedAccessModel(PropBagTypeSafetyMode.Tight, _amHelpers.StoreAccessCreator,
                                            _amHelpers.PropFactory_V1, "PropBagLib.Tests.OnlyTypedAccessModel");

            //mod1["System.String", "NewProperty"] = "This is a a test.";

            InvalidOperationException aa = new InvalidOperationException();

            Type tt = aa.GetType();

            Assert.Throws(tt, () => mod1["System.String", "NewProperty"] = "This is a a test.");
        }
Exemple #25
0
        private IDbSet <TEntity> CreateSet()
        {
            _tracer.LogInfo("CreateSet Called");

            if (_unitOfWork != (IUnitOfWork)null)
            {
                IDbSet <TEntity> objectSet = _unitOfWork.CreateSet <TEntity>();
                return(objectSet);
            }
            else
            {
                var err = new InvalidOperationException("");
                _tracer.LogError(err.GetType().ToString(), err);
                throw err;
            }
        }
Exemple #26
0
        public void TestDequeueFromEmptyQueue()
        {
            var queue             = new CustomQueue <int>();
            var actualException   = new Exception();
            var expectedException = new InvalidOperationException();

            try
            {
                queue.Dequeue();
            }
            catch (Exception exception)
            {
                actualException = exception;
            }
            Assert.AreEqual(expectedException.GetType(), actualException.GetType());
        }
Exemple #27
0
        /// <summary>operation with exception</summary>
        /// <param name="e">exception object</param>
        /// <param name="response">response object</param>
        private void HandleOperationException(InvalidOperationException e, IODataResponseMessage response)
        {
            Debug.Assert(this.entryIndex >= 0 && this.entryIndex < this.ChangedEntries.Count, string.Format(System.Globalization.CultureInfo.InvariantCulture, "this.entryIndex = '{0}', this.ChangedEntries.Count = '{1}'", this.entryIndex, this.ChangedEntries.Count));

            Descriptor       current    = this.ChangedEntries[this.entryIndex];
            HeaderCollection headers    = null;
            HttpStatusCode   statusCode = HttpStatusCode.InternalServerError;

            Version responseVersion = null;

            if (response != null)
            {
                headers    = new HeaderCollection(response);
                statusCode = (HttpStatusCode)response.StatusCode;

                this.HandleOperationResponseHeaders(statusCode, headers);
                e = BaseSaveResult.HandleResponse(
                    this.RequestInfo,
                    statusCode,
                    response.GetHeader(XmlConstants.HttpODataVersion),
                    response.GetStream,
                    false /*throwOnFailure*/,
                    out responseVersion);
            }
            else
            {
                headers = new HeaderCollection();
                headers.SetHeader(XmlConstants.HttpContentType, XmlConstants.MimeTextPlain);

                // In V2 we used to merge individual responses from a call to SaveChanges() into a single batch response payload and then process that.
                // When we encounter an exception at this point in V2, we used to write the exception to the batch response payload and later on when we
                // process through the batch response, we create a DataServiceClientException for each failed operation.
                // For backcompat reason, we will always convert the exception type to DataServiceClientException here.
                Debug.Assert(e != null, "e != null");
                if (e.GetType() != typeof(DataServiceClientException))
                {
                    e = new DataServiceClientException(e.Message, e);
                }
            }

            // For error scenarios, we never invoke the ReadingEntity event.
            this.cachedResponses.Add(new CachedResponse(current, headers, statusCode, responseVersion, null, e));
            this.perRequest = null;
            this.CheckContinueOnError();
        }
        public void Output_Exception()
        {
            // Arrange
            LogManager.ShutdownRepository(Assembly.GetEntryAssembly());
            Mock.Arrange(() => _testAgent.GetLinkingMetadata()).Returns(new Dictionary <string, string>()
            {
                { "NewRelicFakeMetaDataKey", "NewRelicFakeMetatDaValue" }
            });

            //Set the the NewRelicAppender at the root logger
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            BasicConfigurator.Configure(logRepository, _testAppender);

            TextWriter tw = null;

            Mock.Arrange(() => _layout.Format(Arg.IsAny <TextWriter>(), Arg.IsAny <LoggingEvent>())).DoInstead((TextWriter textWriter, LoggingEvent loggingEvent) =>
            {
                tw = textWriter;
            }).CallOriginal();

            var testLogger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

            var testExceptionMessage = "This is an exception.";
            var testException        = new InvalidOperationException(testExceptionMessage);

            // Act
            try
            {
                TestHelpers.CreateStackTracedError(0, testException, 3);
            }
            catch (Exception ex)
            {
                testLogger.Error("Something has occurred!!!", ex);
            }

            //// Act
            var serializedMessage   = tw.ToString();
            var deserializedMessage = TestHelpers.DeserializeOutputJSON(serializedMessage);

            // Assert
            Asserts.KeyAndValueMatch(deserializedMessage, "error.message", testExceptionMessage);
            Asserts.KeyAndValueMatch(deserializedMessage, "error.class", testException.GetType().FullName);
            Asserts.KeyAndValueMatch(deserializedMessage, "error.stack", testException.StackTrace);
        }
Exemple #29
0
        /// <summary>
        /// Filters set of data of type <typeparamref name="T"/>. Returns filterd data set. Throws <see cref="ArgumentNullException"/> if <paramref name="predicate"/> is null
        /// or <see cref="InvalidOperationException"/> if cannot filter data.
        /// </summary>
        /// <typeparam name="T">The type of entity to set be filtered.</typeparam>
        /// <param name="predicate">A function to test each element for a condition.</param>
        /// <returns>Filterd <see cref="IEnumerable{T}"/>.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="predicate"/> is null.</exception>
        /// <exception cref="InvalidOperationException">If cannot filter data.</exception>
        protected virtual IEnumerable <BasicEntity> GetByPredicate <T>(Expression <Func <T, bool> > predicate) where T : BasicEntity
        {
            _logger.LogDebug($"Starting method '{nameof(GetByPredicate)}'.");

            if (predicate is null)
            {
                throw new ArgumentNullException(nameof(predicate), $"Argument '{nameof(predicate)}' cannot be null.");
            }

            try
            {
                IEnumerable <T> result;

                if (typeof(T) == typeof(Ticket))
                {
                    result = (IEnumerable <T>)_dbContext.Tickets.IncludeDetails().Where(predicate as Expression <Func <Ticket, bool> >).AsEnumerable();
                }
                else if (typeof(T) == typeof(VisitInfo))
                {
                    result = (IEnumerable <T>)_dbContext.Info.Include(x => x.OpeningHours).Where(predicate as Expression <Func <VisitInfo, bool> >).AsEnumerable();
                }
                else if (typeof(T) == typeof(SightseeingGroup))
                {
                    result = (IEnumerable <T>)_dbContext.Groups.Include(x => x.Tickets).Where(predicate as Expression <Func <SightseeingGroup, bool> >).AsEnumerable();
                }
                else
                {
                    result = _dbContext.Set <T>().Where(predicate).AsEnumerable();
                }

                _logger.LogDebug($"Finished method '{nameof(GetByPredicate)}'.");
                return(result);
            }
            catch (ArgumentNullException ex)
            {
                var exception = new InvalidOperationException($"Cannot apply '{nameof(predicate)}' to filter data. See the inner exception for more details.", ex);
                _logger.LogError($"{exception.GetType().Name} - {exception.Message}", exception);
                throw exception;
            }
            catch (Exception ex)
            {
                _logger.LogError($"{ex.GetType().Name} - {ex.Message}", ex);
                throw;
            }
        }
Exemple #30
0
        public void write_log_exception()
        {
            var ex = new InvalidOperationException("Fake Exception");

            //Act

            Logger.ErrorException(UniqueMessage, ex);

            //Assert
            var logItem = Db.Fetch <Log>().Single();

            VerifyLog(logItem, LogLevel.Error);
            logItem.Message.Should().Be(UniqueMessage + ": " + ex.Message);
            logItem.ExceptionType.Should().Be(ex.GetType().ToString());
            logItem.Exception.Should().Be(ex.ToString());

            ExceptionVerification.ExpectedErrors(1);
        }