• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# InvalidOperationException类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中InvalidOperationException的典型用法代码示例。如果您正苦于以下问题:C# InvalidOperationException类的具体用法?C# InvalidOperationException怎么用?C# InvalidOperationException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



InvalidOperationException类属于命名空间,在下文中一共展示了InvalidOperationException类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: UnreachableAlways

 public static Exception UnreachableAlways(Exception exception, string message)
 {
   Internal.ContractHelper.TriggerFailure(ContractFailureKind.Assert, message, null, null, null);
   if (exception == null)
     exception = new InvalidOperationException(message);
   throw exception;
 }
开发者ID:Biegal,项目名称:Afterthought,代码行数:7,代码来源:ContractsEx.cs


示例2: OnReadFromStreamAsync_Traces_And_Faults_When_Inner_Faults

        public void OnReadFromStreamAsync_Traces_And_Faults_When_Inner_Faults()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException("test");
            Mock<MediaTypeFormatter> mockFormatter = new Mock<MediaTypeFormatter>() { CallBase = true };
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
            tcs.TrySetException(exception);

            mockFormatter.Setup(
                f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContentHeaders>(), It.IsAny<IFormatterLogger>())).
                Returns(tcs.Task);
            TestTraceWriter traceWriter = new TestTraceWriter();
            HttpRequestMessage request = new HttpRequestMessage();
            request.Content = new StringContent("");
            MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request);
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ReadFromStreamAsync" },
                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "ReadFromStreamAsync" }
            };

            // Act
            Task<object> task = tracer.ReadFromStreamAsync(typeof(string), new MemoryStream(), request.Content.Headers, null);

            // Assert
            Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait());
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:30,代码来源:MediaTypeFormatterTracerTest.cs


示例3: Create_Throws_And_Traces_When_Inner_Throws

        public void Create_Throws_And_Traces_When_Inner_Throws()
        {
            // Arrange
            Mock<ApiController> mockController = new Mock<ApiController>();
            Mock<IHttpControllerActivator> mockActivator = new Mock<IHttpControllerActivator>() { CallBase = true };
            InvalidOperationException exception = new InvalidOperationException("test");
            mockActivator.Setup(b => b.Create(It.IsAny<HttpRequestMessage>(), It.IsAny<HttpControllerDescriptor>(), It.IsAny<Type>())).Throws(exception);
            HttpRequestMessage request = new HttpRequestMessage();
            TestTraceWriter traceWriter = new TestTraceWriter();
            HttpControllerActivatorTracer tracer = new HttpControllerActivatorTracer(mockActivator.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "Create" },
                new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "Create" }
            };

            // Act & Assert
            Exception thrown = Assert.Throws<InvalidOperationException>(() => ((IHttpControllerActivator)tracer).Create(request, controllerDescriptor: null, controllerType: mockController.Object.GetType()));

            // Assert
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:25,代码来源:HttpControllerActivatorTracerTest.cs


示例4: ExecuteAsync_Faults_And_Traces_When_Inner_Faults

        public void ExecuteAsync_Faults_And_Traces_When_Inner_Faults()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException();
            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
            tcs.TrySetException(exception);
            Mock<ApiController> mockController = new Mock<ApiController>() { CallBase = true };
            mockController.Setup(b => b.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<CancellationToken>())).Returns(tcs.Task);

            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: new HttpRequestMessage());
            controllerContext.ControllerDescriptor = _controllerDescriptor;
            controllerContext.Controller = mockController.Object;

            HttpActionContext actionContext = ContextUtil.CreateActionContext(controllerContext, actionDescriptor: _mockActionDescriptor.Object);

            TestTraceWriter traceWriter = new TestTraceWriter();
            HttpControllerTracer tracer = new HttpControllerTracer(mockController.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin },
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Error) { Kind = TraceKind.End }
            };

            // Act
            Exception thrown = Assert.Throws<InvalidOperationException>(() => ((IHttpController)tracer).ExecuteAsync(controllerContext, CancellationToken.None).Wait());

            // Assert
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:32,代码来源:HttpControllerTracerTest.cs


示例5: TryCreateFaultMessage

        public bool TryCreateFaultMessage(Exception exception, out Message message)
        {
            bool created = this.OnTryCreateFaultMessage(exception, out message);

            if (created)
            {
                if (message == null)
                {
                    string text = SR.Format(SR.FaultConverterDidNotCreateFaultMessage, this.GetType().Name);
                    Exception error = new InvalidOperationException(text);
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
                }
            }
            else
            {
                if (message != null)
                {
                    string text = SR.Format(SR.FaultConverterCreatedFaultMessage, this.GetType().Name);
                    Exception error = new InvalidOperationException(text);
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
                }
            }

            return created;
        }
开发者ID:SoumikMukherjeeDOTNET,项目名称:wcf,代码行数:25,代码来源:FaultConverter.cs


示例6: ExecuteExceptionFilterAsync_Faults_And_Traces_When_Inner_Faults

        public void ExecuteExceptionFilterAsync_Faults_And_Traces_When_Inner_Faults()
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage();
            HttpResponseMessage response = new HttpResponseMessage();
            Mock<IExceptionFilter> mockFilter = new Mock<IExceptionFilter>() { CallBase = true };
            InvalidOperationException exception = new InvalidOperationException("test");
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(null);
            tcs.TrySetException(exception);
            mockFilter.Setup(a => a.ExecuteExceptionFilterAsync(It.IsAny<HttpActionExecutedContext>(), It.IsAny<CancellationToken>())).Returns(tcs.Task);
            HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);
            TestTraceWriter traceWriter = new TestTraceWriter();
            ExceptionFilterTracer tracer = new ExceptionFilterTracer(mockFilter.Object, traceWriter);
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteExceptionFilterAsync" },
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = "ExecuteExceptionFilterAsync" }
            };

            // Act
            Task task = ((IExceptionFilter)tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None);


            // Assert
            Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait());
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:29,代码来源:ExceptionFilterTracerTest.cs


示例7: SendAsync_Traces_And_Throws_When_Inner_Throws

        public void SendAsync_Traces_And_Throws_When_Inner_Throws()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException("test");
            MockDelegatingHandler mockHandler = new MockDelegatingHandler((rqst, cancellation) => { throw exception; });

            TestTraceWriter traceWriter = new TestTraceWriter();
            MessageHandlerTracer tracer = new MessageHandlerTracer(mockHandler, traceWriter);

            // DelegatingHandlers require an InnerHandler to run.  We create a mock one to simulate what
            // would happen when a DelegatingHandler executing after the tracer throws.
            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) => { throw exception; });
            tracer.InnerHandler = mockInnerHandler;

            HttpRequestMessage request = new HttpRequestMessage();
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "SendAsync" },
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "SendAsync" }
            };

            MethodInfo method = typeof(DelegatingHandler).GetMethod("SendAsync",
                                                                     BindingFlags.Public | BindingFlags.NonPublic |
                                                                     BindingFlags.Instance);

            // Act
            Exception thrown =
                Assert.Throws<TargetInvocationException>(
                    () => method.Invoke(tracer, new object[] { request, CancellationToken.None }));

            // Assert
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown.InnerException);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
开发者ID:brianly,项目名称:aspnetwebstack,代码行数:35,代码来源:MessageHandlerTracerTest.cs


示例8: ExecuteBindingAsync_Faults_And_Traces_When_Inner_Faults

        public void ExecuteBindingAsync_Faults_And_Traces_When_Inner_Faults()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException();
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
            tcs.TrySetException(exception);
            Mock<HttpActionBinding> mockBinder = new Mock<HttpActionBinding>() { CallBase = true };
            mockBinder.Setup(b => b.ExecuteBindingAsync(
                 It.IsAny<HttpActionContext>(),
                 It.IsAny<CancellationToken>())).
                    Returns(tcs.Task);

            TestTraceWriter traceWriter = new TestTraceWriter();
            HttpActionBindingTracer tracer = new HttpActionBindingTracer(mockBinder.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(_actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin },
                new TraceRecord(_actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Error) { Kind = TraceKind.End }
            };

            // Act
            Task task = tracer.ExecuteBindingAsync(_actionContext, CancellationToken.None);

            // Assert
            Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait());
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:30,代码来源:HttpActionBindingTracerTest.cs


示例9: SendAsync_Traces_And_Faults_When_Inner_Faults

        public void SendAsync_Traces_And_Faults_When_Inner_Faults()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException("test");
            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
            tcs.TrySetException(exception);
            TestTraceWriter traceWriter = new TestTraceWriter();
            RequestMessageHandlerTracer tracer = new RequestMessageHandlerTracer(traceWriter);

            // DelegatingHandlers require an InnerHandler to run.  We create a mock one to simulate what
            // would happen when a DelegatingHandler executing after the tracer returns a Task that throws.
            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) => { return tcs.Task; });
            tracer.InnerHandler = mockInnerHandler;

            HttpRequestMessage request = new HttpRequestMessage();
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.RequestCategory, TraceLevel.Info) { Kind = TraceKind.Begin },
                new TraceRecord(request, TraceCategories.RequestCategory, TraceLevel.Error) { Kind = TraceKind.End }
            };

            MethodInfo method = typeof(DelegatingHandler).GetMethod("SendAsync",
                                                                     BindingFlags.Public | BindingFlags.NonPublic |
                                                                     BindingFlags.Instance);

            // Act
            Task<HttpResponseMessage> task =
                method.Invoke(tracer, new object[] { request, CancellationToken.None }) as Task<HttpResponseMessage>;

            // Assert
            Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait());
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
开发者ID:marojeri,项目名称:aspnetwebstack,代码行数:35,代码来源:RequestMessageHandlerTracerTest.cs


示例10: PageRetrieverMustReturnNoMoreThanPageSize

            public void PageRetrieverMustReturnNoMoreThanPageSize()
            {
                var expectedEx = new InvalidOperationException(Exceptions.PageSizeExceeded.FormatWith(10));
                var actualEx = Assert.Throws<InvalidOperationException>(() => new PagedResult<Int32>(10, (lastResult, page) => Enumerable.Repeat(1, 11)).ToList());

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
开发者ID:SparkSoftware,项目名称:infrastructure,代码行数:7,代码来源:PagedResultTests.cs


示例11: Ctor3

        public static void Ctor3()
        {
            string message = "Test message.";
            string innerMsg = "Invalid Op Message.";
            Exception innerException = new InvalidOperationException(innerMsg);
            EncoderFallbackException ex = new EncoderFallbackException(message, innerException);
            Assert.Equal(default(char), ex.CharUnknown);
            Assert.Equal(default(char), ex.CharUnknownHigh);
            Assert.Equal(default(char), ex.CharUnknownLow);
            Assert.Equal(default(int), ex.Index);

            Assert.Null(ex.StackTrace);
            Assert.Equal(0, ex.Data.Count);

            Assert.Equal(innerException, ex.InnerException);
            Assert.Equal(innerMsg, ex.InnerException.Message);

            Assert.Equal(message, ex.Message);

            message = "";
            ex = new EncoderFallbackException(message, null);
            Assert.Equal(default(char), ex.CharUnknown);
            Assert.Equal(default(char), ex.CharUnknownHigh);
            Assert.Equal(default(char), ex.CharUnknownLow);
            Assert.Equal(default(int), ex.Index);

            Assert.Equal(message, ex.Message);
            Assert.Null(ex.InnerException);
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:29,代码来源:EncoderFallbackExceptionTests.cs


示例12: ReadFromStream_Traces_And_Throws_When_Inner_Throws

        public void ReadFromStream_Traces_And_Throws_When_Inner_Throws()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException("test");
            Mock<BufferedMediaTypeFormatter> mockFormatter = new Mock<BufferedMediaTypeFormatter>() { CallBase = true };
            mockFormatter.Setup(
                f => f.ReadFromStream(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<IFormatterLogger>())).Throws(exception);

            TestTraceWriter traceWriter = new TestTraceWriter();
            HttpRequestMessage request = new HttpRequestMessage();
            request.Content = new StringContent("");
            BufferedMediaTypeFormatterTracer tracer = new BufferedMediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request);
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ReadFromStream" },
                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "ReadFromStream" }
            };

            // Act
            Exception thrown = Assert.Throws<InvalidOperationException>(() => tracer.ReadFromStream(typeof(string), new MemoryStream(), request.Content, null));

            // Assert
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
开发者ID:brianly,项目名称:aspnetwebstack,代码行数:26,代码来源:BufferedMediaTypeFormatterTracerTest.cs


示例13: TryCreateException

        public bool TryCreateException(Message message, MessageFault fault, out Exception exception)
        {
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }
            if (fault == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("fault");
            }

            bool created = this.OnTryCreateException(message, fault, out exception);

            if (created)
            {
                if (exception == null)
                {
                    string text = SR.Format(SR.FaultConverterDidNotCreateException, this.GetType().Name);
                    Exception error = new InvalidOperationException(text);
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
                }
            }
            else
            {
                if (exception != null)
                {
                    string text = SR.Format(SR.FaultConverterCreatedException, this.GetType().Name);
                    Exception error = new InvalidOperationException(text, exception);
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
                }
            }

            return created;
        }
开发者ID:SoumikMukherjeeDOTNET,项目名称:wcf,代码行数:34,代码来源:FaultConverter.cs


示例14: ExecuteBindingAsync_Traces_And_Throws_When_Inner_Throws

        public void ExecuteBindingAsync_Traces_And_Throws_When_Inner_Throws()
        {
            // Arrange
            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };
            mockParamDescriptor.Setup(d => d.ParameterName).Returns("paramName");
            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));
            Mock<FormatterParameterBinding> mockBinding = new Mock<FormatterParameterBinding>(mockParamDescriptor.Object, new MediaTypeFormatterCollection(), null) { CallBase = true };
            InvalidOperationException exception = new InvalidOperationException("test");
            mockBinding.Setup(
                b =>
                b.ExecuteBindingAsync(It.IsAny<ModelMetadataProvider>(), It.IsAny<HttpActionContext>(),
                                      It.IsAny<CancellationToken>())).Throws(exception);

            TestTraceWriter traceWriter = new TestTraceWriter();
            FormatterParameterBindingTracer tracer = new FormatterParameterBindingTracer(mockBinding.Object, traceWriter);
            HttpActionContext actionContext = ContextUtil.CreateActionContext();
            ModelMetadataProvider metadataProvider = new EmptyModelMetadataProvider();

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteBindingAsync" },
                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "ExecuteBindingAsync" }
            };

            // Act & Assert
            Exception thrown = Assert.Throws<InvalidOperationException>(() => tracer.ExecuteBindingAsync(metadataProvider, actionContext, CancellationToken.None));

            // Assert
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:32,代码来源:FormatterParameterBindingTracerTest.cs


示例15: ExecuteAuthorizationFilterAsync_Faults_And_Traces_When_Inner_Faults

        public void ExecuteAuthorizationFilterAsync_Faults_And_Traces_When_Inner_Faults()
        {
            // Arrange
            Mock<IAuthorizationFilter> mockAttr = new Mock<IAuthorizationFilter>() { CallBase = true };
            HttpResponseMessage response = new HttpResponseMessage();
            InvalidOperationException exception = new InvalidOperationException("test");
            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(response);
            tcs.TrySetException(exception);
            mockAttr.Setup(a => a.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>(), It.IsAny<Func<Task<HttpResponseMessage>>>())).Returns(tcs.Task);
            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };
            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));
            HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);
            Func<Task<HttpResponseMessage>> continuation = () => TaskHelpers.FromResult<HttpResponseMessage>(response);
            TestTraceWriter traceWriter = new TestTraceWriter();
            AuthorizationFilterTracer tracer = new AuthorizationFilterTracer(mockAttr.Object, traceWriter);
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteAuthorizationFilterAsync" },
                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = "ExecuteAuthorizationFilterAsync" }
            };

            // Act & Assert
            Task task = ((IAuthorizationFilter)tracer).ExecuteAuthorizationFilterAsync(actionContext, CancellationToken.None, continuation);
            Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait());

            // Assert
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
开发者ID:brianly,项目名称:aspnetwebstack,代码行数:31,代码来源:AuthorizationFilterTracerTest.cs


示例16: SyncWithActionCapturesException

        public void SyncWithActionCapturesException()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException("Some exception text.");

            Mock<SynchronizationContext> mockSyncContext = new Mock<SynchronizationContext>();
            mockSyncContext
                .Setup(sc => sc.Send(It.IsAny<SendOrPostCallback>(), null))
                .Callback(
                    delegate(SendOrPostCallback d, object state)
                    {
                        try
                        {
                            d(state);
                        }
                        catch
                        {
                            // swallow exceptions, just like AspNetSynchronizationContext
                        }
                    });

            // Act & assert
            SynchronousOperationException thrownException = Assert.Throws<SynchronousOperationException>(
                delegate { SynchronizationContextUtil.Sync(mockSyncContext.Object, () => { throw exception; }); },
                @"An operation that crossed a synchronization context failed. See the inner exception for more information.");

            Assert.Equal(exception, thrownException.InnerException);
        }
开发者ID:huangw-t,项目名称:aspnetwebstack,代码行数:28,代码来源:SynchronizationContextUtilTest.cs


示例17: SqlLocalDbException_Constructor_For_Serialization_Can_Be_Serialized

        public void SqlLocalDbException_Constructor_For_Serialization_Can_Be_Serialized()
        {
            // Arrange
            InvalidOperationException innerException = new InvalidOperationException();
            const int ErrorCode = 337519;
            string instanceName = Guid.NewGuid().ToString();
            string message = Guid.NewGuid().ToString();

            // Act
            SqlLocalDbException target = new SqlLocalDbException(message, ErrorCode, instanceName, innerException);

            BinaryFormatter formatter = new BinaryFormatter();

            SqlLocalDbException deserialized;

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

            // Assert
            Assert.IsNotNull(deserialized, "The exception was not deserialized.");
            Assert.AreEqual(deserialized.ErrorCode, target.ErrorCode, "The ErrorCode property is incorrect.");
            Assert.AreEqual(deserialized.InstanceName, target.InstanceName, "The InstanceName property is incorrect.");
            Assert.AreEqual(deserialized.Message, target.Message, "The Message property is incorrect.");
        }
开发者ID:gitter-badger,项目名称:sqllocaldb,代码行数:28,代码来源:SqlLocalDbExceptionTests.cs


示例18: ExecuteExceptionFilterAsync_Throws_And_Traces_When_Inner_OnException_Throws

        public void ExecuteExceptionFilterAsync_Throws_And_Traces_When_Inner_OnException_Throws()
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage();
            HttpResponseMessage response = new HttpResponseMessage();
            Mock<ExceptionFilterAttribute> mockAttr = new Mock<ExceptionFilterAttribute>() { CallBase = true };
            InvalidOperationException exception = new InvalidOperationException("test");
            mockAttr.Setup(a => a.OnException(It.IsAny<HttpActionExecutedContext>())).Throws(exception);
            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };
            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));
            HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);
            TestTraceWriter traceWriter = new TestTraceWriter();
            ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttr.Object, traceWriter);
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "OnException" },
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = "OnException" }
            };

            // Act
            Exception thrown =
                Assert.Throws<InvalidOperationException>(
                    () => ((IExceptionFilter) tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None));

            // Assert
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:30,代码来源:ExceptionFilterAttributeTracerTest.cs


示例19: Create_Instance_With_Type_And_InnerException

 public void Create_Instance_With_Type_And_InnerException()
 {
     var operationException = new InvalidOperationException();
     var exception = new ServiceBusMessageException(typeof(string), operationException);
     Assert.Equal(exception.MessageType, typeof(string));
     Assert.Equal(exception.InnerException, operationException);
     Assert.Equal(exception.Message, "Could not send messageType 'System.String'");
     Assert.Throws<ServiceBusMessageException>(() => { throw exception; });
 }
开发者ID:BclEx,项目名称:BclEx-Abstract,代码行数:9,代码来源:ServiceBusMessageExceptionTests.cs


示例20: ValidateTransactionFlow

        static void ValidateTransactionFlow(ServiceEndpoint endpoint)
        {
            Exception exception = new InvalidOperationException("BindingRequirementAttribute requires transaction flow enabled, but the binding for the '" + endpoint.Contract.ContractType + "' endpoint has it disabled");

            foreach (OperationDescription operation in endpoint.Contract.Operations)
            {
                foreach (IOperationBehavior behavior in operation.Behaviors)
                {
                    if (behavior is TransactionFlowAttribute)
                    {
                        TransactionFlowAttribute attribute = behavior as TransactionFlowAttribute;
                        if (attribute.Transactions == TransactionFlowOption.Allowed)
                        {
                            if (endpoint.Binding is NetTcpBinding)
                            {
                                NetTcpBinding tcpBinding = endpoint.Binding as NetTcpBinding;
                                if (tcpBinding.TransactionFlow == false)
                                {
                                    throw exception;
                                }
                                break;
                            }
                            if (endpoint.Binding is NetNamedPipeBinding)
                            {
                                NetNamedPipeBinding ipcBinding = endpoint.Binding as NetNamedPipeBinding;
                                if (ipcBinding.TransactionFlow == false)
                                {
                                    throw exception;
                                }
                                break;
                            }
                            if (endpoint.Binding is WSHttpBindingBase)
                            {
                                WSHttpBindingBase wsBinding = endpoint.Binding as WSHttpBindingBase;
                                if (wsBinding.TransactionFlow == false)
                                {
                                    throw exception;
                                }
                                break;
                            }
                            if (endpoint.Binding is WSDualHttpBinding)
                            {
                                WSDualHttpBinding wsDualBinding = endpoint.Binding as WSDualHttpBinding;
                                if (wsDualBinding.TransactionFlow == false)
                                {
                                    throw exception;
                                }
                                break;
                            }
                            throw new InvalidOperationException("BindingRequirementAttribute requires transaction flow enabled, but binding for the endpoint with contract " + endpoint.Contract.ContractType + " does not support transaction flow");
                        }
                    }
                }
            }
        }
开发者ID:sajjadahmadi,项目名称:wcf-examples,代码行数:55,代码来源:BindingRequirementAttribute.cs



注:本文中的InvalidOperationException类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Inventor类代码示例发布时间:2022-05-24
下一篇:
C# InvGameItem类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap