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; }
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); }
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); }
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); }
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); }
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); }
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()); }
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."); }
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); }
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); }
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()); }
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()); }
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); }
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); }
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()); }
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); }
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; }
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; }
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; }); }
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"); } } } } }
public void FromException_returns_task_with_exception() { var exception = new InvalidOperationException(); var exceptionTask = TaskHelper.FromException<int>(exception); Assert.True(exceptionTask.IsCompleted); Assert.False(exceptionTask.IsCanceled); Assert.True(exceptionTask.IsFaulted); Assert.Same(exception, exceptionTask.Exception.InnerExceptions.Single()); }
internal static void GetHttpWebResponse(InvalidOperationException exception, ref HttpWebResponse response) { if (null == response) { WebException webexception = (exception as WebException); if (null != webexception) { response = (HttpWebResponse)webexception.Response; } } }
public void ExceptionTest() { AppDomainUtils.RunInSeparateAppDomain(() => { var msg = "This is an error message"; var e = new InvalidOperationException(msg); var page = new ApplicationStartPageTest().CreateStartPage(p => { throw e; }); var ex = Assert.Throws<HttpException>(() => page.ExecuteStartPage()); Assert.Equal(msg, ex.InnerException.Message); Assert.Equal(e, ApplicationStartPage.Exception); }); }
public void ExceptionGet_ReturnsSpecifiedInstance() { // Arrange Exception expectedException = new InvalidOperationException(); ExceptionContext context = new ExceptionContext(expectedException, ExceptionCatchBlocks.HttpServer); ExceptionLoggerContext product = CreateProductUnderTest(context); // Act Exception exception = product.Exception; // Assert Assert.Same(expectedException, exception); }
public void GetGeographyAsync_wraps_exceptions() { var mockDbSpatialDataReader = new Mock<DbSpatialDataReader> { CallBase = true }; var exception = new InvalidOperationException(); mockDbSpatialDataReader.Setup(m => m.GetGeography(0)).Throws(exception); var task = mockDbSpatialDataReader.Object.GetGeographyAsync(0, CancellationToken.None); Assert.Same(exception, task.Exception.InnerExceptions.Single()); }
public void CreateODataError_CopiesInnerExceptionInformation() { Exception innerException = new ArgumentException("innerException"); Exception exception = new InvalidOperationException("exception", innerException); var error = new HttpError(exception, true); ODataError oDataError = error.CreateODataError(); Assert.Equal("An error has occurred.", oDataError.Message); Assert.Equal("exception", oDataError.InnerError.Message); Assert.Equal("System.InvalidOperationException", oDataError.InnerError.TypeName); Assert.Equal("innerException", oDataError.InnerError.InnerError.Message); Assert.Equal("System.ArgumentException", oDataError.InnerError.InnerError.TypeName); }
public void TaskToAwaitConversionFault() { var r = new TaskCompletionSource<int>(); var rt = r.Task.AsIAwaitable().AsTask(); var rv = ((Task)r.Task).AsIAwaitable().AsTask(); Task.WhenAny(rv, rt).AssertNotCompleted(); var ex = new InvalidOperationException(); r.SetException(ex); // worked before rt.AssertFailed<InvalidOperationException>().AssertEquals(ex); rv.AssertFailed<InvalidOperationException>().AssertEquals(ex); // works after r.Task.AsIAwaitable().AsTask().AssertFailed<InvalidOperationException>().AssertEquals(ex); ((Task)r.Task).AsIAwaitable().AsTask().AssertFailed<InvalidOperationException>().AssertEquals(ex); }
public void Debug_With_Message_And_Exception_Traces() { // Arrange TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); InvalidOperationException exception = new InvalidOperationException(); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, "testCategory", TraceLevel.Debug) { Kind = TraceKind.Trace, Message = "The formatted message", Exception = exception }, }; // Act traceWriter.Debug(request, "testCategory", exception, "The {0} message", "formatted"); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:Initialize the InvalidOperationException instance"); try { InvalidOperationException myException = new InvalidOperationException(); if (myException == null) { TestLibrary.TestFramework.LogError("001", "the InvalidOperationException instance creating failed"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2:Initialize the InvalidOperationException instance with message 2"); try { string message = null; InvalidOperationException myException = new InvalidOperationException(message); if (myException == null || myException.Message == null) { TestLibrary.TestFramework.LogError("003", "Initialize the InvalidOperationException instance with null message not create"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; }
private void DeleteDelegateSettings(string applicationname, RegistryKey rootKey, string Registry_Path, IGroupPolicyObject GPO) { WSManHelper wSManHelper = new WSManHelper(this); int num = 0; bool flag = false; try { string str = string.Concat(Registry_Path, "\\CredentialsDelegation"); RegistryKey registryKey = rootKey.OpenSubKey(string.Concat(str, "\\", wSManHelper.Key_Allow_Fresh_Credentials), true); if (registryKey != null) { string[] valueNames = registryKey.GetValueNames(); if ((int)valueNames.Length > 0) { Collection <string> strs = new Collection <string>(); string[] strArrays = valueNames; for (int i = 0; i < (int)strArrays.Length; i++) { string str1 = strArrays[i]; object value = registryKey.GetValue(str1); if (value != null && !value.ToString().StartsWith(applicationname, StringComparison.OrdinalIgnoreCase)) { strs.Add(value.ToString()); flag = true; } registryKey.DeleteValue(str1); } foreach (string str2 in strs) { registryKey.SetValue(Convert.ToString(num + 1, CultureInfo.InvariantCulture), str2, RegistryValueKind.String); num++; } } } if (!flag) { RegistryKey registryKey1 = rootKey.OpenSubKey(str, true); if (registryKey1 != null) { object obj = registryKey1.GetValue(wSManHelper.Key_Allow_Fresh_Credentials); if (obj != null) { registryKey1.DeleteValue(wSManHelper.Key_Allow_Fresh_Credentials, false); } object value1 = registryKey1.GetValue(wSManHelper.Key_Concatenate_Defaults_AllowFresh); if (value1 != null) { registryKey1.DeleteValue(wSManHelper.Key_Concatenate_Defaults_AllowFresh, false); } if (registryKey1.OpenSubKey(wSManHelper.Key_Allow_Fresh_Credentials) != null) { registryKey1.DeleteSubKeyTree(wSManHelper.Key_Allow_Fresh_Credentials); } } } GPO.Save(true, true, new Guid("35378EAC-683F-11D2-A89A-00C04FBBCFA2"), new Guid("6AD20875-336C-4e22-968F-C709ACB15814")); } catch (InvalidOperationException invalidOperationException1) { InvalidOperationException invalidOperationException = invalidOperationException1; ErrorRecord errorRecord = new ErrorRecord(invalidOperationException, "InvalidOperation", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord); } catch (ArgumentException argumentException1) { ArgumentException argumentException = argumentException1; ErrorRecord errorRecord1 = new ErrorRecord(argumentException, "InvalidArgument", ErrorCategory.InvalidArgument, null); base.WriteError(errorRecord1); } catch (SecurityException securityException1) { SecurityException securityException = securityException1; ErrorRecord errorRecord2 = new ErrorRecord(securityException, "SecurityException", ErrorCategory.SecurityError, null); base.WriteError(errorRecord2); } catch (UnauthorizedAccessException unauthorizedAccessException1) { UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1; ErrorRecord errorRecord3 = new ErrorRecord(unauthorizedAccessException, "UnauthorizedAccess", ErrorCategory.SecurityError, null); base.WriteError(errorRecord3); } }
private static List <Type> GetSupportedChannelTypes(StuffPerListenUriInfo stuff) { Binding originalBinding = stuff.Endpoints[0].Binding; CustomBinding binding = new CustomBinding(originalBinding); // All types are supported to start bool reply = true; bool replySession = true; bool input = true; bool inputSession = true; bool duplex = true; bool duplexSession = true; string sessionContractName = null; string datagramContractName = null; // each endpoint adds constraints for (int i = 0; i < stuff.Endpoints.Count; ++i) { ContractDescription contract = stuff.Endpoints[i].Contract; if (contract.SessionMode == SessionMode.Required) { sessionContractName = contract.Name; } if (contract.SessionMode == SessionMode.NotAllowed) { datagramContractName = contract.Name; } System.Collections.IList endpointTypes = GetSupportedChannelTypes(contract); if (!endpointTypes.Contains(typeof(IReplyChannel))) { reply = false; } if (!endpointTypes.Contains(typeof(IReplySessionChannel))) { replySession = false; } if (!endpointTypes.Contains(typeof(IInputChannel))) { input = false; } if (!endpointTypes.Contains(typeof(IInputSessionChannel))) { inputSession = false; } if (!endpointTypes.Contains(typeof(IDuplexChannel))) { duplex = false; } if (!endpointTypes.Contains(typeof(IDuplexSessionChannel))) { duplexSession = false; } } if ((sessionContractName != null) && (datagramContractName != null)) { string text = SR.Format(SR.SFxCannotRequireBothSessionAndDatagram3, datagramContractName, sessionContractName, binding.Name); Exception error = new InvalidOperationException(text); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error); } // TODO: Restrict list further based on SessionMode constraints var supportedChannelTypes = new List <Type>(); if (input) { supportedChannelTypes.Add(typeof(IInputChannel)); } if (inputSession) { supportedChannelTypes.Add(typeof(IInputSessionChannel)); } if (reply) { supportedChannelTypes.Add(typeof(IReplyChannel)); } if (replySession) { supportedChannelTypes.Add(typeof(IReplySessionChannel)); } if (duplex) { supportedChannelTypes.Add(typeof(IDuplexChannel)); } if (duplexSession) { supportedChannelTypes.Add(typeof(IDuplexSessionChannel)); } return(supportedChannelTypes); }
private async ValueTask <ForwarderError> HandleUpgradedResponse(HttpContext context, HttpResponseMessage destinationResponse, ActivityCancellationTokenSource activityCancellationSource) { ForwarderTelemetry.Log.ForwarderStage(ForwarderStage.ResponseUpgrade); // SocketHttpHandler and similar transports always provide an HttpContent object, even if it's empty. // Note as of 5.0 HttpResponse.Content never returns null. // https://github.com/dotnet/runtime/blame/8fc68f626a11d646109a758cb0fc70a0aa7826f1/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs#L46 if (destinationResponse.Content == null) { throw new InvalidOperationException("A response content is required for upgrades."); } // :: Step 7-A-1: Upgrade the client channel. This will also send response headers. var upgradeFeature = context.Features.Get <IHttpUpgradeFeature>(); if (upgradeFeature == null) { var ex = new InvalidOperationException("Invalid 101 response when upgrades aren't supported."); destinationResponse.Dispose(); context.Response.StatusCode = StatusCodes.Status502BadGateway; ReportProxyError(context, ForwarderError.UpgradeResponseDestination, ex); return(ForwarderError.UpgradeResponseDestination); } RestoreUpgradeHeaders(context, destinationResponse); Stream upgradeResult; try { upgradeResult = await upgradeFeature.UpgradeAsync(); } catch (Exception ex) { destinationResponse.Dispose(); ReportProxyError(context, ForwarderError.UpgradeResponseClient, ex); return(ForwarderError.UpgradeResponseClient); } using var clientStream = upgradeResult; // :: Step 7-A-2: Copy duplex streams using var destinationStream = await destinationResponse.Content.ReadAsStreamAsync(); var requestTask = StreamCopier.CopyAsync(isRequest: true, clientStream, destinationStream, StreamCopier.UnknownLength, _clock, activityCancellationSource, activityCancellationSource.Token).AsTask(); var responseTask = StreamCopier.CopyAsync(isRequest: false, destinationStream, clientStream, StreamCopier.UnknownLength, _clock, activityCancellationSource, activityCancellationSource.Token).AsTask(); // Make sure we report the first failure. var firstTask = await Task.WhenAny(requestTask, responseTask); var requestFinishedFirst = firstTask == requestTask; var secondTask = requestFinishedFirst ? responseTask : requestTask; ForwarderError error; var(firstResult, firstException) = await firstTask; if (firstResult != StreamCopyResult.Success) { error = ReportResult(context, requestFinishedFirst, firstResult, firstException); // Cancel the other direction activityCancellationSource.Cancel(); // Wait for this to finish before exiting so the resources get cleaned up properly. await secondTask; } else { var(secondResult, secondException) = await secondTask; if (secondResult != StreamCopyResult.Success) { error = ReportResult(context, !requestFinishedFirst, secondResult, secondException !); } else { error = ForwarderError.None; } } return(error); ForwarderError ReportResult(HttpContext context, bool reqeuest, StreamCopyResult result, Exception exception) { var error = result switch { StreamCopyResult.InputError => reqeuest ? ForwarderError.UpgradeRequestClient : ForwarderError.UpgradeResponseDestination, StreamCopyResult.OutputError => reqeuest ? ForwarderError.UpgradeRequestDestination : ForwarderError.UpgradeResponseClient, StreamCopyResult.Canceled => reqeuest ? ForwarderError.UpgradeRequestCanceled : ForwarderError.UpgradeResponseCanceled, _ => throw new NotImplementedException(result.ToString()), }; ReportProxyError(context, error, exception); return(error); } }
/// <summary> /// Inspects an exception for type and determines the appropriate custom or generic exception that should be rethrown. /// </summary> /// <param name="e">The exception caught by a consumer-facing method.</param> internal static BaseResult HandleException(Exception e) { AvaTaxException avaEx; Exception ex; AvaLogger _avaLog1 = AvaLogger.GetLogger(); if ((e.GetType() == typeof(System.Reflection.TargetInvocationException)) && (e.InnerException != null)) { ex = e.InnerException; } else if (e.InnerException != null && (e.InnerException.GetType() == typeof(System.Net.WebException))) { ex = e.InnerException; } else { ex = e; } if (ex.GetType() == typeof(System.Net.WebException)) { System.Net.WebException webEx = (System.Net.WebException)ex; _avaLog1.Error(webEx.Message); ProxyBaseResult proxyResult = new ProxyBaseResult(); proxyResult.ResultCode = ProxySeverityLevel.Error; proxyResult.Messages = new ProxyMessage[1]; proxyResult.Messages[0] = new ProxyMessage(); proxyResult.Messages[0].Severity = ProxySeverityLevel.Error; proxyResult.Messages[0].Summary = webEx.Message; proxyResult.Messages[0].Source = webEx.Source; proxyResult.Messages[0].HelpLink = webEx.HelpLink; proxyResult.Messages[0].Name = webEx.GetType().ToString(); BaseResult result = new BaseResult(); result.CopyFrom(proxyResult); return(result); } else if (ex.GetType() == typeof(SoapException)) { SoapException soapEx = (SoapException)ex; _avaLog1.Fail(soapEx.Message); avaEx = new AvaTaxException(soapEx); throw avaEx; } else if (ex.GetType() == typeof(SoapHeaderException)) { SoapHeaderException soapHeaderEx = (SoapHeaderException)ex; avaEx = new AvaTaxException(soapHeaderEx); _avaLog1.Fail(soapHeaderEx.Message); throw avaEx; } else if (ex.GetType() == typeof(InvalidOperationException)) { InvalidOperationException operationEx = (InvalidOperationException)ex; _avaLog1.Fail(operationEx.Message); if (operationEx.InnerException != null) { throw operationEx.InnerException; } else { throw operationEx; } } else { _avaLog1.Fail(ex.Message); throw ex; } }
//public ActionResult BatchDataKount(DataManager dataManager) //{ // IEnumerable DataSource = context.WebTemplate_ARV_PhysicalCount.ToList(); // DataResult result = new DataResult(); // result.result = DataSource; // result.count = context.WebTemplate_ARV_PhysicalCount.Count(); // return Json(result.count, JsonRequestBehavior.AllowGet); //} public int SavePC(int FacilityCode, DateTime DateOfPhysicalCount, int product_code, string BatchNo, string Quantity_Dispensary, string Quantity_Store, DateTime?ExpiryDate, string Total, string Comment) { order_hiv_rapid_test_kit_PhysicalCount obj = new order_hiv_rapid_test_kit_PhysicalCount(); int recstat = 0; obj.FacilityCode = FacilityCode; obj.DateOfPhysicalCount = DateOfPhysicalCount; obj.product_code = System.Convert.ToInt32(product_code); obj.BatchNo = BatchNo; if (Quantity_Dispensary != null && !string.IsNullOrEmpty(Quantity_Dispensary)) { obj.Quantity_Dispensary = System.Convert.ToDouble(Quantity_Dispensary); } if (Quantity_Store != null && !string.IsNullOrEmpty(Quantity_Store)) { obj.Quantity_Store = System.Convert.ToDouble(Quantity_Store); } obj.ExpiryDate = ExpiryDate; if (Total != null && !string.IsNullOrEmpty(Total)) { obj.Total = System.Convert.ToDouble(Total); } obj.Comment = Comment; try { //Check for the existance of the record var ca = context.order_hiv_rapid_test_kit_PhysicalCount.FirstOrDefault(c => c.FacilityCode == FacilityCode && c.DateOfPhysicalCount == DateOfPhysicalCount && c.product_code == product_code && c.BatchNo == BatchNo); if (ca == null) { context.order_hiv_rapid_test_kit_PhysicalCount.Add(obj); obj.DateAdded = DateTime.Now; obj.AddedBy = new UserManagement().getCurrentuser(); recstat = context.SaveChanges(); // recstat = obj.household_number; } else { order_hiv_rapid_test_kit_PhysicalCount table = context.order_hiv_rapid_test_kit_PhysicalCount.FirstOrDefault(c => c.FacilityCode == FacilityCode && c.DateOfPhysicalCount == DateOfPhysicalCount && c.product_code == product_code && c.BatchNo == BatchNo); // obj.household_number = ca.household_number ; context.Entry(table).CurrentValues.SetValues(obj); obj.DateAdded = DateTime.Now; obj.AddedBy = new UserManagement().getCurrentuser(); context.Entry(table).State = EntityState.Modified; recstat = context.SaveChanges(); //recstat = ca.household_number; } } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException raise = new InvalidOperationException(message, raise); } } throw raise; } return(recstat); }
public Dictionary <string, object> addCompany(HttpFileCollectionBase files, string FreeTrail, SCL_CompanyRegistration UserFormData, string Browser) { Dictionary <string, object> dic = new Dictionary <string, object>(); var subDate = DateTime.Now; var SubEndDate = DateTime.Now; if (FreeTrail.Equals("YES")) { SubEndDate = subDate.AddDays(30); } else { SubEndDate = subDate.AddDays(10); } using (var tran = gc.db.Database.BeginTransaction()) { try { string file_name = ""; string fname = ""; List <string> fileNameList = new List <string>(); if (files.Count > 0) { // Get all files from Request object for (int i = 0; i < files.Count; i++) { HttpPostedFileBase file = files[i]; if (Browser == "IE" || Browser == "INTERNETEXPLORER") { string[] testfiles = file.FileName.Split(new char[] { '\\' }); fname = testfiles[testfiles.Length - 1]; } else { fname = file.FileName; } fname = file.FileName; file_name = string.Format("{0}-{1}", DateTime.Now.ToString("ddMMMyyyyHHmmss"), fname.Replace("-", "")); fname = Path.Combine(HttpContext.Current.Server.MapPath("~/Attachments/"), file_name); file.SaveAs(fname); fileNameList.Add(file_name); } } //string password_ln = CreateRandomPassword(8); string body = "Welcome to Leads Portal.\n\nYour Account Details are \n\n username: "******"\n\n Password: "******"\n\n\n Thank You\n\n"; UserFormData.company_status = "Active"; UserFormData.cdate = subDate; UserFormData.Flag = FreeTrail; UserFormData.SubscriptionEndDate = SubEndDate; UserFormData.company_uniqueID = "Not Required"; UserFormData.ProfilePicture = fileNameList[0]; gc.db.SCL_CompanyRegistration.Add(UserFormData); int n = gc.db.SaveChanges(); if (n > 0) { SCL_UserRoles role = new SCL_UserRoles(); role.RoleName = "Admin"; role.CreatedBy = UserFormData.CID; role.CompanyID = UserFormData.CID; role.CreatedDateTime = subDate; role.Status = "Active"; gc.db.SCL_UserRoles.Add(role); gc.db.SaveChanges(); SCL_UserDepartments dep = new SCL_UserDepartments(); dep.DepartmentName = "Admin"; dep.CreatedBy = UserFormData.CID; dep.CompanyID = UserFormData.CID; dep.CreatedDateTime = subDate; dep.Status = "Active"; gc.db.SCL_UserDepartments.Add(dep); gc.db.SaveChanges(); SCL_Users users = new SCL_Users(); users.UserName = UserFormData.company_email; users.UserPass = UserFormData.company_password; users.RoleID = role.ID; users.DepartmentID = dep.DepartmentID; users.FirstName = UserFormData.first_name; users.LastName = UserFormData.last_name; users.EmailID = UserFormData.company_email; users.CompanyID = UserFormData.CID; users.Status = "Active"; users.CreatedBy = UserFormData.CID; users.CreatedDateTime = subDate; users.userType = "Admin"; gc.db.SCL_Users.Add(users); int x = gc.db.SaveChanges(); List <SCL_UserRoleScreenMapping> RoleScreenList = gc.db.SCL_UserRoleScreenMapping .Where(u => u.RoleID == users.RoleID && u.CompanyID == users.CompanyID).ToList(); foreach (SCL_UserRoleScreenMapping g in RoleScreenList) { SCL_UserwiseScreenMapping USM = new SCL_UserwiseScreenMapping(); USM.CompanyID = users.CompanyID; USM.CreatedBy = users.CompanyID; USM.CreatedDateTime = subDate; USM.ScreenID = g.ScreenID; USM.UserID = users.ID; gc.db.SCL_UserwiseScreenMapping.Add(USM); } gc.db.SaveChanges(); SCL_Login login = new SCL_Login(); login.CID = UserFormData.CID; login.username = UserFormData.company_email; login.password = UserFormData.company_password; login.status = "Active"; login.cdate = subDate; login.type = "ADMIN"; login.SubscriptionEndDate = SubEndDate; login.Flag = FreeTrail; gc.db.SCL_Login.Add(login); int m = gc.db.SaveChanges(); if (m > 0 && x > 0) { Elasticmail.SendEmail(UserFormData.company_email, "Leads Account Details", body, "", "*****@*****.**", "Leads", ""); tran.Commit(); dic.Add("success", "success"); } else { tran.Rollback(); dic.Add("Error", "Error"); } } else { dic.Add("error", "No results found!"); } } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { tran.Rollback(); Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException raise = new InvalidOperationException(message, raise); } } dic.Add("error", raise.Message); } } return(dic); }
void ReadIndexInternal(byte[] key, PakFilter filter, out Exception exc) { if (Initialized) { exc = new InvalidOperationException("Index is already initialized"); return; } if (Info.bEncryptedIndex && key == null) { exc = new ArgumentException("Index is encrypted but no key was provided", nameof(key)); return; } Stream.Position = Info.IndexOffset; BinaryReader IndexReader; if (Info.bEncryptedIndex) { IndexReader = new BinaryReader(new MemoryStream(AESDecryptor.DecryptAES(Reader.ReadBytes((int)Info.IndexSize), key))); int stringLen = IndexReader.ReadInt32(); if (stringLen > 512 || stringLen < -512) { exc = new ArgumentException("The provided key is invalid", nameof(key)); return; } if (stringLen < 0) { IndexReader.BaseStream.Position += (stringLen - 1) * 2; if (IndexReader.ReadUInt16() != 0) { exc = new ArgumentException("The provided key is invalid", nameof(key)); return; } } else { IndexReader.BaseStream.Position += stringLen - 1; if (IndexReader.ReadByte() != 0) { exc = new ArgumentException("The provided key is invalid", nameof(key)); return; } } IndexReader.BaseStream.Position = 0; } else { IndexReader = Reader; } Dictionary <string, FPakEntry> tempFiles; if (Info.Version >= EPakVersion.PATH_HASH_INDEX) { ReadIndexUpdated(IndexReader, key, out tempFiles, filter); } else { // https://github.com/EpicGames/UnrealEngine/blob/bf95c2cbc703123e08ab54e3ceccdd47e48d224a/Engine/Source/Runtime/PakFile/Private/IPlatformFilePak.cpp#L4509 MountPoint = IndexReader.ReadFString(); if (MountPoint.StartsWith("../../..")) { MountPoint = MountPoint.Substring(8); } else { // Weird mount point location... MountPoint = "/"; } if (!CaseSensitive) { MountPoint = MountPoint.ToLowerInvariant(); } var NumEntries = IndexReader.ReadInt32(); tempFiles = new Dictionary <string, FPakEntry>(NumEntries); for (int i = 0; i < NumEntries; i++) { var entry = new FPakEntry(IndexReader, Info.Version, CaseSensitive, FileName); // if there is no filter OR the filter passes if (filter == null || filter.CheckFilter(MountPoint + entry.Name, CaseSensitive)) { // Filename is without the MountPoint concatenated to save memory tempFiles[entry.Name] = entry; } } } Paks.Merge(tempFiles, out var files, MountPoint); Entries = files; DebugHelper.WriteLine("{0} {1} {2} {3}", "[FModel]", "[PakFileReader]", "[ReadIndexInternal]", $"{FileName} contains {Entries.Count} files, mount point: \"{this.MountPoint}\", version: {(int)this.Info.Version}"); if (Info.bEncryptedIndex) { // underlying stream is a MemoryStream of the decrypted index, might improve performance with a crypto stream of some sort IndexReader.Dispose(); } Reader.Dispose(); Initialized = true; exc = null; }
public static bool WaitOneAndPump(this WaitHandle handle, int millisecondsTimeout) { using (var operationPendingMre = new ManualResetEvent(false)) { bool result = false; Exception error = null; var startTick = Environment.TickCount; var handles = new[] { handle.SafeWaitHandle.DangerousGetHandle(), operationPendingMre.SafeWaitHandle.DangerousGetHandle() }; var dispatcher = Dispatcher.CurrentDispatcher; var frame = new DispatcherFrame(); Func <uint> getTimeout; if (Timeout.Infinite == millisecondsTimeout) { getTimeout = () => INFINITE; } else { getTimeout = () => (uint)Math.Max(0, millisecondsTimeout + startTick - Environment.TickCount); } DispatcherHookEventHandler onOperationPosted = (s, e) => { // this may occur on a random thread, // trigger a helper event and // unblock MsgWaitForMultipleObjectsEx inside onDispatcherInactive operationPendingMre.Set(); }; DispatcherHookEventHandler onOperationCompleted = (s, e) => { // this should occur on the Dispather thread Debug.Assert(Thread.CurrentThread == dispatcher.Thread); // do an instant handle check var nativeResult = WaitForSingleObject(handles[0], 0); if (nativeResult == WAIT_OBJECT_0) { result = true; } else if (nativeResult == WAIT_ABANDONED_0) { error = new AbandonedMutexException(-1, handle); } else if (getTimeout() == 0) { result = false; } else if (nativeResult == WAIT_TIMEOUT) { return; } else { error = new InvalidOperationException("WaitForSingleObject"); } // end the nested Dispatcher loop frame.Continue = false; }; EventHandler onDispatcherInactive = (s, e) => { operationPendingMre.Reset(); // wait for the handle or a message var timeout = getTimeout(); var nativeResult = MsgWaitForMultipleObjectsEx( (uint)handles.Length, handles, timeout, QS_EVENTMASK, MWMO_INPUTAVAILABLE); if (nativeResult == WAIT_OBJECT_0) { result = true; // handle signalled } else if (nativeResult == WAIT_TIMEOUT) { result = false; // timed-out } else if (nativeResult == WAIT_ABANDONED_0) { error = new AbandonedMutexException(-1, handle); } else if (nativeResult != WAIT_OBJECT_0 + 1 && nativeResult != WAIT_OBJECT_0 + 2) { error = new InvalidOperationException("MsgWaitForMultipleObjectsEx"); } else { // a Windows message or a Dispatcher operation is pending if (timeout == 0) { result = false; // timed-out } else { return; } } // end the nested Dispatcher loop frame.Continue = false; }; dispatcher.Hooks.OperationCompleted += onOperationCompleted; dispatcher.Hooks.OperationPosted += onOperationPosted; dispatcher.Hooks.DispatcherInactive += onDispatcherInactive; try { // onDispatcherInactive will be called on the new frame, // as soon as Dispatcher becomes idle Dispatcher.PushFrame(frame); } finally { dispatcher.Hooks.OperationCompleted -= onOperationCompleted; dispatcher.Hooks.OperationPosted -= onOperationPosted; dispatcher.Hooks.DispatcherInactive -= onDispatcherInactive; } if (error != null) { throw error; } return(result); } }
public Person CreatePerson(string firstName, string lastName, string knownAs, int?identificationTypeId, string identificationNumber, bool isPivaValidated, string pivaTransactionId, DateTime?dateOfBirth, int?age, bool isEstimagedAge, int?Sexual_Orientation_Id, int?languageId, int?genderId, int?maritalStatusId, int?religionId, int?preferredContactTypeId, string phoneNumber, string mobilePhoneNumber, string emailAddress, int?populationGroupId, int?nationalityId, int?disabilityId, int?Citizenship_Id, DateTime dateCreated, string createdBy, bool isActive, bool isDeleted) { Person newPerson; using (var dbContext = new SDIIS_DatabaseEntities()) { var person = new Person() { First_Name = firstName, Last_Name = lastName, Known_As = knownAs, Identification_Type_Id = identificationTypeId, Identification_Number = identificationNumber, Is_Piva_Validated = isPivaValidated, Piva_Transaction_Id = pivaTransactionId, Date_Of_Birth = dateOfBirth, Age = age, Is_Estimated_Age = isEstimagedAge, Sexual_Orientation_Id = Sexual_Orientation_Id, Language_Id = languageId, Gender_Id = genderId, Marital_Status_Id = maritalStatusId, Religion_Id = religionId, Preferred_Contact_Type_Id = preferredContactTypeId, Phone_Number = phoneNumber, Mobile_Phone_Number = mobilePhoneNumber, Email_Address = emailAddress, Population_Group_Id = populationGroupId, Nationality_Id = nationalityId, Disability_Type_Id = disabilityId, Citizenship_Id = Citizenship_Id, Date_Created = dateCreated, Created_By = createdBy, Is_Active = isActive, Is_Deleted = isDeleted }; try { newPerson = dbContext.Persons.Add(person); dbContext.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message1 = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException raise = new InvalidOperationException(message1, raise); } } throw raise; } } return(newPerson); }
private async Task ProcessOperation(HttpContext httpContext, IServiceProvider serviceProvider) { Message responseMessage; //Reload the body to ensure we have the full message var memoryStream = new MemoryStream((int)httpContext.Request.ContentLength.GetValueOrDefault(1024)); await httpContext.Request.Body.CopyToAsync(memoryStream).ConfigureAwait(false); memoryStream.Seek(0, SeekOrigin.Begin); httpContext.Request.Body = memoryStream; //Return metadata if no request, provided this is a GET request if (httpContext.Request.Body.Length == 0 && httpContext.Request.Method?.ToLower() == "get") { if (_options.WsdlFileOptions != null) { await ProcessMetaFromFile(httpContext); } else { await ProcessMeta(httpContext); } return; } // Get the encoder based on Content Type var messageEncoder = _messageEncoders[0]; foreach (var encoder in _messageEncoders) { if (encoder.IsContentTypeSupported(httpContext.Request.ContentType)) { messageEncoder = encoder; break; } } Message requestMessage; //Get the message try { requestMessage = await ReadMessageAsync(httpContext, messageEncoder); } catch (Exception ex) { await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, null, messageEncoder, httpContext); return; } var messageFilters = serviceProvider.GetServices <IMessageFilter>().ToArray(); var asyncMessageFilters = serviceProvider.GetServices <IAsyncMessageFilter>().ToArray(); //Execute request message filters try { foreach (var messageFilter in messageFilters) { messageFilter.OnRequestExecuting(requestMessage); } foreach (var messageFilter in asyncMessageFilters) { await messageFilter.OnRequestExecuting(requestMessage); } } catch (Exception ex) { await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, messageEncoder, httpContext); return; } var messageInspector = serviceProvider.GetService <IMessageInspector>(); object correlationObject; try { correlationObject = messageInspector?.AfterReceiveRequest(ref requestMessage); } catch (Exception ex) { await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, messageEncoder, httpContext); return; } var messageInspector2s = serviceProvider.GetServices <IMessageInspector2>(); var correlationObjects2 = default(List <(IMessageInspector2 inspector, object correlationObject)>); try { correlationObjects2 = messageInspector2s.Select(mi => (inspector: mi, correlationObject: mi.AfterReceiveRequest(ref requestMessage, _service))).ToList(); } catch (Exception ex) { await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, messageEncoder, httpContext); return; } // for getting soapaction and parameters in (optional) body // GetReaderAtBodyContents must not be called twice in one request XmlDictionaryReader reader = null; if (!requestMessage.IsEmpty) { reader = requestMessage.GetReaderAtBodyContents(); } try { var soapAction = HeadersHelper.GetSoapAction(httpContext, reader); requestMessage.Headers.Action = soapAction; var operation = _service.Operations.FirstOrDefault(o => o.SoapAction.Equals(soapAction, StringComparison.Ordinal) || o.Name.Equals(HeadersHelper.GetTrimmedSoapAction(soapAction), StringComparison.Ordinal)); if (operation == null) { var ex = new InvalidOperationException($"No operation found for specified action: {requestMessage.Headers.Action}"); await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, messageEncoder, httpContext); return; } _logger.LogInformation($"Request for operation {operation.Contract.Name}.{operation.Name} received"); try { //Create an instance of the service class var serviceInstance = serviceProvider.GetRequiredService(_service.ServiceType); SetMessageHeadersToProperty(requestMessage, serviceInstance); // Get operation arguments from message var arguments = GetRequestArguments(requestMessage, reader, operation, httpContext); ExecuteFiltersAndTune(httpContext, serviceProvider, operation, arguments, serviceInstance); var invoker = serviceProvider.GetService <IOperationInvoker>() ?? new DefaultOperationInvoker(); var responseObject = await invoker.InvokeAsync(operation.DispatchMethod, serviceInstance, arguments); if (operation.IsOneWay) { httpContext.Response.StatusCode = (int)HttpStatusCode.Accepted; return; } var resultOutDictionary = new Dictionary <string, object>(); foreach (var parameterInfo in operation.OutParameters) { resultOutDictionary[parameterInfo.Name] = arguments[parameterInfo.Index]; } responseMessage = CreateResponseMessage( operation, responseObject, resultOutDictionary, soapAction, requestMessage, messageEncoder); httpContext.Response.ContentType = httpContext.Request.ContentType; httpContext.Response.Headers["SOAPAction"] = responseMessage.Headers.Action; correlationObjects2.ForEach(mi => mi.inspector.BeforeSendReply(ref responseMessage, _service, mi.correlationObject)); messageInspector?.BeforeSendReply(ref responseMessage, correlationObject); SetHttpResponse(httpContext, responseMessage); await WriteMessageAsync(messageEncoder, responseMessage, httpContext); } catch (Exception exception) { if (exception is TargetInvocationException targetInvocationException) { exception = targetInvocationException.InnerException; } _logger.LogError(0, exception, exception?.Message); responseMessage = await WriteErrorResponseMessage(exception, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, messageEncoder, httpContext); } } finally { reader?.Dispose(); } // Execute response message filters try { foreach (var messageFilter in messageFilters) { messageFilter.OnResponseExecuting(responseMessage); } foreach (var messageFilter in asyncMessageFilters.Reverse()) { await messageFilter.OnResponseExecuting(responseMessage); } } catch (Exception ex) { responseMessage = await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, messageEncoder, httpContext); } }
public static Response insertOrUpdate(User requester, Task task) { try { nova_ataEntities db = new nova_ataEntities(); if (task.getTaskId() < 0) { if (!task.getCriticalActivity().Equals("5000")) { int taskId = Math.Abs(task.getTaskId()); task.setTaskId(taskId); return(TaskDAO.delete(requester, task)); } else { return(new Response(task.getTaskId(), "Failed. Launch Exetution activity can't be deleted", task.getHash())); } } bool isNew = false; bool isChangeAllowed = false; int projectId = task.getProjectId(); var project = (from p in db.projects where p.projectId == projectId select p).First(); if (ProjectDAO.stageCorrespondence(project.productProjectStage) <= 3) { isChangeAllowed = true; } var t = (dynamic)null; if (task.getTaskId() == 0) { isNew = true; t = db.tasks.Create(); t.createdBy = requester.getUserId(); t.creationDate = string.Format("{0:dd/MM/yyyy}", DateTime.Now); t.wasDeleted = "false"; t.reworkCount = 0; if (!isChangeAllowed) { t.wasInsertedAfterFreezing = "true"; t.isFreezed = "true"; } else { t.wasInsertedAfterFreezing = "false"; t.isFreezed = "false"; } } else { isNew = false; t = db.tasks.Find(task.getTaskId()); if (t == null) { return(new Response(task.getTaskId(), "Fail. Result not found", task.getHash())); } if (!isChangeAllowed && t.wasInsertedAfterFreezing.Equals("false")) { t.pWork = task.getPWork(); t.status = task.getStatus(); t.hash = task.getHash(); if (!task.getStart().Equals(t.start)) { t.newStart = task.getStart(); } if (!task.getFinish().Equals(t.finish)) { t.newFinish = task.getFinish(); } t.criticalActivity = task.getCriticalActivity(); t.activityTitle = task.getActivityTitle(); t.activityDescription = task.getActivityDescription(); t.parent = task.getParent(); t.grandParent = task.getGrandParent(); t.responsible = task.getResponsible(); t.ident = task.getIdent(); db.SaveChanges(); return(new Response(task.getTaskId(), "Edited", task.getHash())); } } t.projectId = task.getProjectId(); t.notifyMe = task.getNotifyMe(); t.meetingDate = task.getMeetingDate(); t.product = task.getProduct(); /*if (task.getPWork().Equals("100") || task.getStatus().ToUpper().Equals("COMPLETO")) * { * t.status = "Completo"; * t.pWork = "100"; * t.actualFinishDate = string.Format("{0:dd/MM/yyyy}", DateTime.Now); * } * else * { * if (!isNew) * { * if (!task.getStatus().ToUpper().Equals("COMPLETO") && t.status.ToUpper().Equals("COMPLETO")) * { * t.reworkCount = Convert.ToInt32(t.reworkCount) + 1; * } * } * else * { * t.reworkCount = task.getReworkCount(); * } * t.status = task.getStatus(); * t.pWork = task.getPWork(); * t.actualFinishDate = task.getActualFinishDate(); * }*/ if (!isNew) { if (!task.getStatus().ToUpper().Equals("COMPLETO") && t.status.ToUpper().Equals("COMPLETO")) { t.reworkCount = Convert.ToInt32(t.reworkCount) + 1; t.status = task.getStatus(); t.pWork = task.getPWork(); } else if (task.getActivityOrigin().ToUpper().Equals("PROJECT")) { t.status = task.getStatus(); t.pWork = task.getPWork(); } } else { t.status = task.getStatus(); t.pWork = task.getPWork(); } t.criticalActivity = task.getCriticalActivity(); t.activityTitle = task.getActivityTitle(); t.activityDescription = task.getActivityDescription(); t.parent = task.getParent(); t.grandParent = task.getGrandParent(); t.responsible = task.getResponsible(); t.start = task.getStart(); t.finish = task.getFinish(); t.activityOrigin = task.getActivityOrigin(); t.idProjectTask = task.getIdProjectTask(); t.idParentProjectTask = task.getIdParentProjectTask(); t.ident = task.getIdent(); t.hash = task.getHash(); t.newStart = task.getNewStart(); t.newFinish = task.getNewFinish(); if (isNew) { db.tasks.Add(t); } db.SaveChanges(); if (isNew) { return(new Response(task.getTaskId(), "Created", task.getHash())); } else { return(new Response(task.getTaskId(), "Edited", task.getHash())); } } catch (DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); raise = new InvalidOperationException(message, raise); } } throw raise; } }
private static ServicePoint FindServicePointHelper(Uri address, bool isProxyServicePoint) { GlobalLog.Enter("ServicePointManager::FindServicePointHelper() address:" + address.ToString()); if (isProxyServicePoint) { if (address.Scheme != Uri.UriSchemeHttp) { Exception exception = new NotSupportedException(SR.GetString(SR.net_proxyschemenotsupported, address.Scheme)); GlobalLog.LeaveException("ServicePointManager::FindServicePointHelper() proxy has unsupported scheme:" + address.Scheme.ToString(), exception); throw exception; } } // // Search for the correct proxy host, // then match its acutal host by using ConnectionGroups // which are located on the actual ServicePoint. // string tempEntry = MakeQueryString(address, isProxyServicePoint); // lookup service point in the table ServicePoint servicePoint = null; GlobalLog.Print("ServicePointManager::FindServicePointHelper() locking and looking up tempEntry:[" + tempEntry.ToString() + "]"); lock (s_ServicePointTable) { // once we grab the lock, check if it wasn't already added WeakReference servicePointReference = s_ServicePointTable[tempEntry] as WeakReference; GlobalLog.Print("ServicePointManager::FindServicePointHelper() lookup returned WeakReference#" + ValidationHelper.HashString(servicePointReference)); if (servicePointReference != null) { servicePoint = (ServicePoint)servicePointReference.Target; GlobalLog.Print("ServicePointManager::FindServicePointHelper() successful lookup returned ServicePoint#" + ValidationHelper.HashString(servicePoint)); } if (servicePoint == null) { // lookup failure or timeout, we need to create a new ServicePoint if (s_MaxServicePoints <= 0 || s_ServicePointTable.Count < s_MaxServicePoints) { // Determine Connection Limit int connectionLimit = InternalConnectionLimit; string schemeHostPort = MakeQueryString(address); bool userDefined = s_UserChangedLimit; if (ConfigTable.ContainsKey(schemeHostPort)) { connectionLimit = (int)ConfigTable[schemeHostPort]; userDefined = true; } servicePoint = new ServicePoint(address, s_ServicePointIdlingQueue, connectionLimit, tempEntry, userDefined, isProxyServicePoint); GlobalLog.Print("ServicePointManager::FindServicePointHelper() created ServicePoint#" + ValidationHelper.HashString(servicePoint)); servicePointReference = new WeakReference(servicePoint); s_ServicePointTable[tempEntry] = servicePointReference; GlobalLog.Print("ServicePointManager::FindServicePointHelper() adding entry WeakReference#" + ValidationHelper.HashString(servicePointReference) + " key:[" + tempEntry + "]"); } else { Exception exception = new InvalidOperationException(SR.GetString(SR.net_maxsrvpoints)); GlobalLog.LeaveException("ServicePointManager::FindServicePointHelper() reached the limit count:" + s_ServicePointTable.Count.ToString() + " limit:" + s_MaxServicePoints.ToString(), exception); throw exception; } } } GlobalLog.Leave("ServicePointManager::FindServicePointHelper() servicePoint#" + ValidationHelper.HashString(servicePoint)); return(servicePoint); }
private MigrationTools._EngineV1.DataContracts.WorkItemData ReplayRevisions(List <MigrationTools._EngineV1.DataContracts.RevisionItem> revisionsToMigrate, MigrationTools._EngineV1.DataContracts.WorkItemData sourceWorkItem, MigrationTools._EngineV1.DataContracts.WorkItemData targetWorkItem, int current) { try { var skipToFinalRevisedWorkItemType = _config.SkipToFinalRevisedWorkItemType; string finalDestType = revisionsToMigrate.Last().Type; if (skipToFinalRevisedWorkItemType && Engine.TypeDefinitionMaps.Items.ContainsKey(finalDestType)) { finalDestType = Engine.TypeDefinitionMaps.Items[finalDestType].Map(); } //If work item hasn't been created yet, create a shell if (targetWorkItem == null) { string targetType = revisionsToMigrate.First().Type; if (Engine.TypeDefinitionMaps.Items.ContainsKey(targetType)) { targetType = Engine.TypeDefinitionMaps.Items[targetType].Map(); } targetWorkItem = CreateWorkItem_Shell(Engine.Target.WorkItems.Project, sourceWorkItem, skipToFinalRevisedWorkItemType ? finalDestType : targetType); } if (_config.CollapseRevisions) { var data = revisionsToMigrate.Select(rev => { var revWi = sourceWorkItem.GetRevision(rev.Number); return(new { revWi.Id, revWi.Rev, revWi.ChangedDate, // According to https://docs.microsoft.com/en-us/azure/devops/reference/xml/reportable-fields-reference?view=azure-devops-2020 Revised Date was misused here revWi.Fields }); }); var fileData = JsonConvert.SerializeObject(data, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.None }); var filePath = Path.Combine(Path.GetTempPath(), $"{sourceWorkItem.Id}_PreMigrationHistory.json"); // todo: Delete this file after (!) WorkItem has been saved File.WriteAllText(filePath, fileData); targetWorkItem.ToWorkItem().Attachments.Add(new Attachment(filePath, "History has been consolidated into the attached file.")); revisionsToMigrate = revisionsToMigrate.GetRange(revisionsToMigrate.Count - 1, 1); TraceWriteLine(LogEventLevel.Information, " Attached a consolidated set of {RevisionCount} revisions.", new Dictionary <string, object>() { { "RevisionCount", data.Count() } }); } foreach (var revision in revisionsToMigrate) { var currentRevisionWorkItem = sourceWorkItem.GetRevision(revision.Number); TraceWriteLine(LogEventLevel.Information, " Processing Revision [{RevisionNumber}]", new Dictionary <string, object>() { { "RevisionNumber", revision.Number } }); // Decide on WIT string destType = currentRevisionWorkItem.Type; if (Engine.TypeDefinitionMaps.Items.ContainsKey(destType)) { destType = Engine.TypeDefinitionMaps.Items[destType].Map(); } WorkItemTypeChange(targetWorkItem, skipToFinalRevisedWorkItemType, finalDestType, revision, currentRevisionWorkItem, destType); PopulateWorkItem(currentRevisionWorkItem, targetWorkItem, destType); // Todo: Ensure all field maps use WorkItemData.Fields to apply a correct mapping Engine.FieldMaps.ApplyFieldMappings(currentRevisionWorkItem, targetWorkItem); // Todo: Think about an "UpdateChangedBy" flag as this is expensive! (2s/WI instead of 1,5s when writing "Migration") targetWorkItem.ToWorkItem().Fields["System.ChangedBy"].Value = currentRevisionWorkItem.Fields["System.ChangedBy"]; targetWorkItem.ToWorkItem().Fields["System.History"].Value = currentRevisionWorkItem.Fields["System.History"]; //Debug.WriteLine("Discussion:" + currentRevisionWorkItem.Revisions[revision.Index].Fields["System.History"].Value); TfsReflectedWorkItemId reflectedUri = (TfsReflectedWorkItemId)Engine.Source.WorkItems.CreateReflectedWorkItemId(sourceWorkItem); if (!targetWorkItem.ToWorkItem().Fields.Contains(Engine.Target.Config.AsTeamProjectConfig().ReflectedWorkItemIDFieldName)) { var ex = new InvalidOperationException("ReflectedWorkItemIDField Field Missing"); Log.LogError(ex, " The WorkItemType {WorkItemType} does not have a Field called {ReflectedWorkItemID}", targetWorkItem.Type, Engine.Target.Config.AsTeamProjectConfig().ReflectedWorkItemIDFieldName); throw ex; } targetWorkItem.ToWorkItem().Fields[Engine.Target.Config.AsTeamProjectConfig().ReflectedWorkItemIDFieldName].Value = reflectedUri.ToString(); targetWorkItem.SaveToAzureDevOps(); TraceWriteLine(LogEventLevel.Information, " Saved TargetWorkItem {TargetWorkItemId}. Replayed revision {RevisionNumber} of {RevisionsToMigrateCount}", new Dictionary <string, object>() { { "TargetWorkItemId", targetWorkItem.Id }, { "RevisionNumber", revision.Number }, { "RevisionsToMigrateCount", revisionsToMigrate.Count } }); } if (targetWorkItem != null) { ProcessWorkItemAttachments(sourceWorkItem, targetWorkItem, false); ProcessWorkItemLinks(Engine.Source.WorkItems, Engine.Target.WorkItems, sourceWorkItem, targetWorkItem); if (_config.GenerateMigrationComment) { var reflectedUri = targetWorkItem.ToWorkItem().Fields[Engine.Target.Config.AsTeamProjectConfig().ReflectedWorkItemIDFieldName].Value; var history = new StringBuilder(); history.Append( $"This work item was migrated from a different project or organization. You can find the old version at <a href=\"{reflectedUri}\">{reflectedUri}</a>."); targetWorkItem.ToWorkItem().History = history.ToString(); } targetWorkItem.SaveToAzureDevOps(); attachmentEnricher.CleanUpAfterSave(); TraceWriteLine(LogEventLevel.Information, "...Saved as {TargetWorkItemId}", new Dictionary <string, object> { { "TargetWorkItemId", targetWorkItem.Id } }); } } catch (Exception ex) { TraceWriteLine(LogEventLevel.Information, "...FAILED to Save"); Log.LogInformation("==============================================================="); if (targetWorkItem != null) { foreach (Field f in targetWorkItem.ToWorkItem().Fields) { TraceWriteLine(LogEventLevel.Information, "{FieldReferenceName} ({FieldName}) | {FieldValue}", new Dictionary <string, object>() { { "FieldReferenceName", f.ReferenceName }, { "FieldName", f.Name }, { "FieldValue", f.Value } }); } } Log.LogInformation("==============================================================="); Log.LogError(ex.ToString(), ex); Log.LogInformation("==============================================================="); } return(targetWorkItem); }
protected override void When() { _exception = Assert.Throws <InvalidOperationException>(() => GetMockForEnumerableOf <IWidget>(5)); }
public static InvalidOperationException ArgumentOutOfRange(InvalidOperationException e) { return(e); }
/// <summary> /// Removes the registered instance from the dictionary. /// </summary> internal static void DeregisterHandle(IntPtr handle, SKObject instance) { if (handle == IntPtr.Zero) { return; } if (instance is ISKSkipObjectRegistration) { return; } instancesLock.EnterWriteLock(); try { var existed = instances.TryGetValue(handle, out var weak); if (existed && (!weak.IsAlive || weak.Target == instance)) { instances.Remove(handle); } else { #if THROW_OBJECT_EXCEPTIONS InvalidOperationException ex = null; if (!existed) { // the object may have been replaced if (!instance.IsDisposed) { // recoverable error // there was no object there, but we are still alive ex = new InvalidOperationException( $"A managed object did not exist for the specified native object. " + $"H: {handle.ToString ("x")} Type: {instance.GetType ()}"); } } else if (weak.Target is SKObject o && o != instance) { // there was an object in the dictionary, but it was NOT this object if (!instance.IsDisposed) { // recoverable error // there was a new living object there, but we are still alive ex = new InvalidOperationException( $"Trying to remove a different object with the same native handle. " + $"H: {handle.ToString ("x")} Type: ({o.GetType ()}, {instance.GetType ()})"); } } if (ex != null) { if (instance.fromFinalizer) { exceptions.Add(ex); } else { throw ex; } } #endif } } finally { instancesLock.ExitWriteLock(); } }
private void ProcessMarketDataMessage(IMessageAdapter adapter, MarketDataMessage message) { var key = _subscriptionKeys.TryGetValue(message.OriginalTransactionId) ?? CreateKey(message); var enumerator = _subscriptionQueue.TryGetValue(key); var state = _subscriptionStates.TryGetValue2(key); var error = message.Error; var isOk = !message.IsNotSupported && error == null; var isSubscribe = message.IsSubscribe; switch (state) { case SubscriptionStates.Subscribed: break; case SubscriptionStates.Subscribing: isSubscribe = true; if (isOk) { _subscriptions.Add(key, adapter); _subscriptionStates[key] = SubscriptionStates.Subscribed; } else if (error != null) { _subscriptions.Remove(key); _subscriptionStates.Remove(key); } break; case SubscriptionStates.Unsubscribing: isSubscribe = false; _subscriptions.Remove(key); _subscriptionStates.Remove(key); break; case null: if (isOk) { if (message.IsSubscribe) { _subscriptions.Add(key, adapter); _subscriptionStates.Add(key, SubscriptionStates.Subscribed); break; } } _subscriptions.Remove(key); _subscriptionStates.Remove(key); break; default: throw new ArgumentOutOfRangeException(); } if (message.IsNotSupported) { if (enumerator != null) { ProcessSubscriptionAction(enumerator, message, message.OriginalTransactionId); } else { if (error == null) { error = new InvalidOperationException(LocalizedStrings.Str633Params.Put(message.SecurityId, message.DataType)); } } } _subscriptionQueue.Remove(key); _subscriptionKeys.Remove(message.OriginalTransactionId); RaiseMarketDataMessage(adapter, message.OriginalTransactionId, error, isSubscribe); }
public List <IItemInstance> AddItemToPocket(IItemInstance newItem, PocketType?type, short?slot) { var invlist = new List <IItemInstance>(); // override type if necessary if (type.HasValue) { newItem.Type = type.Value; } // check if item can be stapled if (slot == null && newItem.Type != PocketType.Bazaar && (newItem.Item.Type == PocketType.Etc || newItem.Item.Type == PocketType.Main)) { var slotNotFull = this.ToList().Select(s => s.Value).Where(i => i.Type != PocketType.Bazaar && i.Type != PocketType.PetWarehouse && i.Type != PocketType.Warehouse && i.Type != PocketType.FamilyWareHouse && i.ItemVNum.Equals(newItem.ItemVNum) && i.Amount < Configuration.MaxItemAmount); var freeslot = Configuration.BackpackSize + ((IsExpanded ? 1 : 0) * 12) - this.Count(s => s.Value.Type == newItem.Type); IEnumerable <IItemInstance> itemInstances = slotNotFull as IList <IItemInstance> ?? slotNotFull.ToList(); if (newItem.Amount <= (freeslot * Configuration.MaxItemAmount) + itemInstances.Sum(s => Configuration.MaxItemAmount - s.Amount)) { foreach (var slotToAdd in itemInstances) { var max = slotToAdd.Amount + newItem.Amount; max = max > Configuration.MaxItemAmount ? Configuration.MaxItemAmount : max; newItem.Amount = (short)(slotToAdd.Amount + newItem.Amount - max); slotToAdd.Amount = (short)max; invlist.Add(slotToAdd); } } } if (newItem.Amount <= 0) { return(invlist); } // create new item var freeSlot = newItem.Type == PocketType.Wear ? (LoadBySlotAndType <IItemInstance>((short)newItem.Item.EquipmentSlot, PocketType.Wear) == null ? (short?)newItem.Item.EquipmentSlot : null) : GetFreeSlot(newItem.Type); if (!slot.HasValue && !freeSlot.HasValue) { return(invlist); } newItem.Slot = slot ?? freeSlot.Value; if (ContainsKey(newItem.Id)) { var e = new InvalidOperationException("Cannot add the same ItemInstance twice to pocket."); _logger.Error(e.Message, e); return(null); } if (this.Any(s => s.Value.Slot == newItem.Slot && s.Value.Type == newItem.Type) || newItem.Slot >= Configuration.BackpackSize + ((IsExpanded ? 1 : 0) * 12)) { return(null); } if (newItem.Type == PocketType.Specialist && !(newItem is SpecialistInstance)) { var e = new InvalidOperationException( "Cannot add an item of type Specialist without beeing a SpecialistInstance."); _logger.Error(e.Message, e); return(null); } if ((newItem.Type == PocketType.Equipment || newItem.Type == PocketType.Wear) && !(newItem is WearableInstance) && !(newItem is SpecialistInstance)) { var e = new InvalidOperationException( "Cannot add an item of type Equipment or Wear without beeing a WearableInstance or a SpecialistInstance."); _logger.Error(e.Message, e); return(null); } this[newItem.Id] = newItem; invlist.Add(newItem); return(invlist); }
public Dictionary <string, object> addCustomer(string FirstName, string LastName, string Email, string Password, string Telephone) { Dictionary <string, object> dic = new Dictionary <string, object>(); using (var tran = gc.db.Database.BeginTransaction()) { try { //string body = "Welcome to SCL Portal.\n\nYour Account Details are \n\n username: "******"\n\n Password: "******"\n\n\n Thank You\n\n"; SCL_Customer cr = new SCL_Customer(); cr.FirstName = FirstName; cr.LastName = LastName; cr.EmailAddress = Email; cr.Username = Email; cr.Telephone = Telephone; cr.Password = Password; cr.Status = "Active"; cr.IsActive = true; cr.CustomerID = 1; cr.CreatedDateTime = DateTime.Now; gc.db.SCL_Customer.Add(cr); int n = gc.db.SaveChanges(); if (n > 0) { SCL_Login login = new SCL_Login(); login.CID = cr.CustomerID; login.username = cr.EmailAddress; login.password = cr.Password; login.status = "Active"; login.cdate = DateTime.Now; login.type = "CUSTOMER"; gc.db.SCL_Login.Add(login); int m = gc.db.SaveChanges(); if (m > 0) { tran.Commit(); dic.Add("success", "success"); } else { tran.Rollback(); dic.Add("Error", "Error"); } } else { dic.Add("error", "No results found!"); } } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { tran.Rollback(); Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException raise = new InvalidOperationException(message, raise); } } dic.Add("error", raise.Message); } } return(dic); }
public IItemInstance MoveInPocket(short sourceSlot, PocketType sourceType, PocketType targetType, short?targetSlot, bool swap) { if (sourceSlot == targetSlot && sourceType == targetType) { var e = new InvalidOperationException("SourceInstance can't be moved on the same spot"); _logger.Error(e.Message, e); return(null); } var sourceInstance = LoadBySlotAndType <IItemInstance>(sourceSlot, sourceType); if (!(sourceInstance is WearableInstance || sourceInstance is SpecialistInstance)) { var e = new InvalidOperationException("SourceInstance can't be moved between pockets"); _logger.Error(e.Message, e); return(null); } if (sourceInstance is WearableInstance && targetType != PocketType.Equipment && targetType != PocketType.Costume && targetType != PocketType.Wear) { var e = new InvalidOperationException("WearableInstance can't be move to this inventory"); _logger.Error(e.Message, e); return(null); } if (sourceInstance is SpecialistInstance && targetType != PocketType.Equipment && targetType != PocketType.Specialist && targetType != PocketType.Wear) { var e = new InvalidOperationException("SpecialistInstance can't be move to this inventory"); _logger.Error(e.Message, e); return(null); } if (targetSlot.HasValue) { var targetInstance = LoadBySlotAndType <IItemInstance>(targetSlot.Value, targetType); if (swap && targetInstance != null) { // swap sourceInstance.Slot = targetSlot.Value; sourceInstance.Type = targetType; targetInstance.Slot = sourceSlot; targetInstance.Type = sourceType; } else if (targetInstance == null) { sourceInstance.Slot = targetSlot.Value; sourceInstance.Type = targetType; } else { var e = new InvalidOperationException("Source can not be swapped"); _logger.Error(e.Message, e); return(null); } return(sourceInstance); } // check for free target slot short?nextFreeSlot; if (targetType == PocketType.Wear) { nextFreeSlot = LoadBySlotAndType <IItemInstance>((short)sourceInstance.Item.EquipmentSlot, targetType) == null ? (short)sourceInstance.Item.EquipmentSlot : (short)-1; } else { nextFreeSlot = GetFreeSlot(targetType); } if (nextFreeSlot.HasValue) { sourceInstance.Type = targetType; sourceInstance.Slot = nextFreeSlot.Value; } else { return(null); } return(sourceInstance); }
/// <summary> /// Implements the record processing for this cmdlet /// </summary> protected override void ProcessRecord() { ProviderInfo provider = null; Collection <string> filePaths; try { if (Context.EngineSessionState.IsProviderLoaded(Context.ProviderNames.FileSystem)) { filePaths = SessionState.Path.GetResolvedProviderPathFromPSPath(_path, out provider); } else { filePaths = new Collection <string>(); filePaths.Add(_path); } } catch (ItemNotFoundException) { string message = StringUtil.Format(Modules.ModuleNotFound, _path); FileNotFoundException fnf = new FileNotFoundException(message); ErrorRecord er = new ErrorRecord(fnf, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, _path); WriteError(er); return; } // Make sure that the path is in the file system - that's all we can handle currently... if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { // "The current provider ({0}) cannot open a file" throw InterpreterError.NewInterpreterException(_path, typeof(RuntimeException), null, "FileOpenError", ParserStrings.FileOpenError, provider.FullName); } // Make sure at least one file was found... if (filePaths == null || filePaths.Count < 1) { string message = StringUtil.Format(Modules.ModuleNotFound, _path); FileNotFoundException fnf = new FileNotFoundException(message); ErrorRecord er = new ErrorRecord(fnf, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, _path); WriteError(er); return; } if (filePaths.Count > 1) { // "The path resolved to more than one file; can only process one file at a time." throw InterpreterError.NewInterpreterException(filePaths, typeof(RuntimeException), null, "AmbiguousPath", ParserStrings.AmbiguousPath); } string filePath = filePaths[0]; ExternalScriptInfo scriptInfo = null; string ext = System.IO.Path.GetExtension(filePath); if (ext.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) { // Create a script info for loading the file... string scriptName; scriptInfo = GetScriptInfoForFile(filePath, out scriptName, false); // we should reserve the Context.ModuleBeingProcessed unchanged after loadModuleManifest(), otherwise the module won't be importable next time. PSModuleInfo module; string _origModuleBeingProcessed = Context.ModuleBeingProcessed; try { module = LoadModuleManifest( scriptInfo, ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings /* but don't stop on first error and don't load elements */, null, null, null, null); if (module != null) { //Validate file existence if (module.RequiredAssemblies != null) { foreach (string requiredAssembliespath in module.RequiredAssemblies) { if (!IsValidFilePath(requiredAssembliespath, module, true) && !IsValidGacAssembly(requiredAssembliespath)) { string errorMsg = StringUtil.Format(Modules.InvalidRequiredAssembliesInModuleManifest, requiredAssembliespath, filePath); var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidRequiredAssembliesInModuleManifest", ErrorCategory.ObjectNotFound, _path); WriteError(errorRecord); } } } //RootModule can be null, empty string or point to a valid .psm1, , .cdxml, .xaml or .dll. Anything else is invalid. if (module.RootModule != null && module.RootModule != "") { string rootModuleExt = System.IO.Path.GetExtension(module.RootModule); if ((!IsValidFilePath(module.RootModule, module, true) && !IsValidGacAssembly(module.RootModule)) || (!rootModuleExt.Equals(StringLiterals.PowerShellModuleFileExtension, StringComparison.OrdinalIgnoreCase) && !rootModuleExt.Equals(".dll", StringComparison.OrdinalIgnoreCase) && !rootModuleExt.Equals(".cdxml", StringComparison.OrdinalIgnoreCase) && !rootModuleExt.Equals(".xaml", StringComparison.OrdinalIgnoreCase)) ) { string errorMsg = StringUtil.Format(Modules.InvalidModuleManifest, module.RootModule, filePath); var errorRecord = new ErrorRecord(new ArgumentException(errorMsg), "Modules_InvalidRootModuleInModuleManifest", ErrorCategory.InvalidArgument, _path); WriteError(errorRecord); } } Hashtable data = null; Hashtable localizedData = null; bool containerErrors = false; LoadModuleManifestData(scriptInfo, ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out data, out localizedData, ref containerErrors); ModuleSpecification[] nestedModules; GetScalarFromData(data, scriptInfo.Path, "NestedModules", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out nestedModules); if (nestedModules != null) { foreach (ModuleSpecification nestedModule in nestedModules) { if (!IsValidFilePath(nestedModule.Name, module, true) && !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellILAssemblyExtension, module, true) && !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellNgenAssemblyExtension, module, true) && !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellModuleFileExtension, module, true) && !IsValidGacAssembly(nestedModule.Name)) { Collection <PSModuleInfo> modules = GetModuleIfAvailable(nestedModule); if (0 == modules.Count) { string errorMsg = StringUtil.Format(Modules.InvalidNestedModuleinModuleManifest, nestedModule.Name, filePath); var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidNestedModuleinModuleManifest", ErrorCategory.ObjectNotFound, _path); WriteError(errorRecord); } } } } ModuleSpecification[] requiredModules; GetScalarFromData(data, scriptInfo.Path, "RequiredModules", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out requiredModules); if (requiredModules != null) { foreach (ModuleSpecification requiredModule in requiredModules) { var modules = GetModule(new[] { requiredModule.Name }, all: false, refresh: true); if (modules.Count == 0) { string errorMsg = StringUtil.Format(Modules.InvalidRequiredModulesinModuleManifest, requiredModule.Name, filePath); var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidRequiredModulesinModuleManifest", ErrorCategory.ObjectNotFound, _path); WriteError(errorRecord); } } } string[] fileListPaths; GetScalarFromData(data, scriptInfo.Path, "FileList", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out fileListPaths); if (fileListPaths != null) { foreach (string fileListPath in fileListPaths) { if (!IsValidFilePath(fileListPath, module, true)) { string errorMsg = StringUtil.Format(Modules.InvalidFilePathinModuleManifest, fileListPath, filePath); var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidFilePathinModuleManifest", ErrorCategory.ObjectNotFound, _path); WriteError(errorRecord); } } } ModuleSpecification[] moduleListModules; GetScalarFromData(data, scriptInfo.Path, "ModuleList", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out moduleListModules); if (moduleListModules != null) { foreach (ModuleSpecification moduleListModule in moduleListModules) { var modules = GetModule(new[] { moduleListModule.Name }, all: false, refresh: true); if (modules.Count == 0) { string errorMsg = StringUtil.Format(Modules.InvalidModuleListinModuleManifest, moduleListModule.Name, filePath); var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidModuleListinModuleManifest", ErrorCategory.ObjectNotFound, _path); WriteError(errorRecord); } } } if (module.CompatiblePSEditions.Any()) { // The CompatiblePSEditions module manifest key is supported only on PowerShell version '5.1' or higher. // Ensure that PowerShellVersion module manifest key value is '5.1' or higher. // var minimumRequiredPowerShellVersion = new Version(5, 1); if ((module.PowerShellVersion == null) || module.PowerShellVersion < minimumRequiredPowerShellVersion) { string errorMsg = StringUtil.Format(Modules.InvalidPowerShellVersionInModuleManifest, filePath); var errorRecord = new ErrorRecord(new ArgumentException(errorMsg), "Modules_InvalidPowerShellVersionInModuleManifest", ErrorCategory.InvalidArgument, _path); WriteError(errorRecord); } } } } finally { Context.ModuleBeingProcessed = _origModuleBeingProcessed; } DirectoryInfo parent = null; try { parent = Directory.GetParent(filePath); } catch (IOException) { } catch (UnauthorizedAccessException) { } catch (ArgumentException) { } Version version; if (parent != null && Version.TryParse(parent.Name, out version)) { if (!version.Equals(module.Version)) { string message = StringUtil.Format(Modules.InvalidModuleManifestVersion, filePath, module.Version.ToString(), parent.FullName); var ioe = new InvalidOperationException(message); ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidModuleManifestVersion", ErrorCategory.InvalidArgument, _path); ThrowTerminatingError(er); } WriteVerbose(Modules.ModuleVersionEqualsToVersionFolder); } if (module != null) { WriteObject(module); } } else { string message = StringUtil.Format(Modules.InvalidModuleManifestPath, filePath); InvalidOperationException ioe = new InvalidOperationException(message); ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidModuleManifestPath", ErrorCategory.InvalidArgument, _path); ThrowTerminatingError(er); } }
private void SaveExecute() { try { tblEmploye newEmploye = new tblEmploye(); newEmploye.FirstName = Employe.FirstName; newEmploye.Surname = Employe.Surname; newEmploye.JMBG = Employe.JMBG; newEmploye.Salary = Convert.ToInt32(Employe.Salary); newEmploye.Account = Employe.Account; newEmploye.Pasword = Employe.Pasword; newEmploye.Username = Employe.Username; newEmploye.Position = Employe.Position; newEmploye.Email = Employe.Email; string birthdate = CalculateBirth(Employe.JMBG); CreateManager cm = new CreateManager(); cm.tbJMBG.Text = ""; //method checks if jmbg already exists in database AND ONLY IF NOT proceeds to save employe if (KeyCheck(newEmploye.JMBG) == true && PasswordCheck(newEmploye.Pasword) == true && UsernameCheck(newEmploye.Username) == true && NumbersOnly(newEmploye.JMBG) == true) { newEmploye.DateOfBirth = CalculateBirth(Employe.JMBG); context.tblEmployes.Add(newEmploye); context.SaveChanges(); tblManager newManager = new tblManager(); newManager.EmployeID = newEmploye.EmployeID; newManager.SectorID = Sector.SectorID; newManager.LevelID = Level.LevelID; context.tblManagers.Add(newManager); context.SaveChanges(); MessageBox.Show("Manager is created."); if (!worker.IsBusy) { worker.RunWorkerAsync(); } } else { MessageBox.Show("JMBG or password or username already exists"); } } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException MessageBox.Show(message); raise = new InvalidOperationException(message, raise); } } throw raise; } }
public ActionResult New(Ad A) { //int adId=32; try { if (ModelState.IsValid) { A.Date_start = DateTime.Now; A.UserId = (Session["LogedUserID"] as User).Id; //A.Id = 23; db.Ad.Add(A); //db.SaveChanges(); try { db.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException raise = new InvalidOperationException(message, raise); } } throw raise; } ModelState.Clear(); } else { SwapDropDownList(A.Swap); SizeDropDownList(A.SizeId); BrandDropDownList(A.BrandId); ColorDropDownList(A.ColorId); ConditionDropDownList(A.ConditionId); SubcategoryDropDownList(A.SubcategoryId); return(View(A)); } } catch (RetryLimitExceededException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log.) ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator."); } SwapDropDownList(A.Swap); SizeDropDownList(A.SizeId); BrandDropDownList(A.BrandId); ColorDropDownList(A.ColorId); ConditionDropDownList(A.ConditionId); SubcategoryDropDownList(A.SubcategoryId); int adId = (from ad in db.Ad select ad.Id).Max(); //return View(A); return(RedirectToAction("Photo1", "Ad", new { id = adId })); }
private void DisableClientSideSettings() { WSManHelper wSManHelper = new WSManHelper(this); IWSManSession wSManSession = base.CreateWSManSession(); if (wSManSession != null) { try { try { string str = wSManSession.Get(wSManHelper.CredSSP_RUri, 0); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(str); XmlNamespaceManager xmlNamespaceManagers = new XmlNamespaceManager(xmlDocument.NameTable); xmlNamespaceManagers.AddNamespace("cfg", wSManHelper.CredSSP_XMLNmsp); XmlNode xmlNodes = xmlDocument.SelectSingleNode(wSManHelper.CredSSP_SNode, xmlNamespaceManagers); if (xmlNodes == null) { InvalidOperationException invalidOperationException = new InvalidOperationException(); ErrorRecord errorRecord = new ErrorRecord(invalidOperationException, wSManHelper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord); return; } else { string str1 = "<cfg:Auth xmlns:cfg=\"http://schemas.microsoft.com/wbem/wsman/1/config/client/auth\"><cfg:CredSSP>false</cfg:CredSSP></cfg:Auth>"; wSManSession.Put(wSManHelper.CredSSP_RUri, str1, 0); if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) { ThreadStart threadStart = new ThreadStart(this.DeleteUserDelegateSettings); Thread thread = new Thread(threadStart); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); } else { this.DeleteUserDelegateSettings(); } if (!wSManHelper.ValidateCreadSSPRegistryRetry(false, null, "wsman")) { wSManHelper.AssertError(wSManHelper.GetResourceMsgFromResourcetext("DisableCredSSPPolicyValidateError"), false, null); } } } catch (XPathException xPathException1) { XPathException xPathException = xPathException1; ErrorRecord errorRecord1 = new ErrorRecord(xPathException, "XpathException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord1); } } finally { if (!string.IsNullOrEmpty(wSManSession.Error)) { wSManHelper.AssertError(wSManSession.Error, true, null); } if (wSManSession != null) { this.Dispose(wSManSession); } } return; } else { return; } }
public void ThrowsForInvalidClientTypes() { InvalidOperationException exception = Assert.Throws <InvalidOperationException>(() => InstrumentClient(new InvalidTestClient())); Assert.AreEqual("Client type contains public non-virtual async method MethodAsync", exception.Message); }
// // FindServicePoint - Query using an Uri for a given server point // /// <devdoc> /// <para>Findes an existing <see cref='System.Net.ServicePoint'/> or creates a new <see cref='System.Net.ServicePoint'/> to manage communications to the specified <see cref='System.Uri'/> /// instance.</para> /// </devdoc> internal static ServicePoint FindServicePoint(string host, int port) { if (host == null) { throw new ArgumentNullException("address"); } GlobalLog.Enter("ServicePointManager::FindServicePoint() host:" + host.ToString()); string tempEntry = null; bool isProxyServicePoint = false; // // Search for the correct proxy host, // then match its acutal host by using ConnectionGroups // which are located on the actual ServicePoint. // tempEntry = "ByHost:" + host + ":" + port.ToString(CultureInfo.InvariantCulture); // lookup service point in the table ServicePoint servicePoint = null; GlobalLog.Print("ServicePointManager::FindServicePoint() locking and looking up tempEntry:[" + tempEntry.ToString() + "]"); lock (s_ServicePointTable) { // once we grab the lock, check if it wasn't already added WeakReference servicePointReference = s_ServicePointTable[tempEntry] as WeakReference; GlobalLog.Print("ServicePointManager::FindServicePoint() lookup returned WeakReference#" + ValidationHelper.HashString(servicePointReference)); if (servicePointReference != null) { servicePoint = (ServicePoint)servicePointReference.Target; GlobalLog.Print("ServicePointManager::FindServicePoint() successfull lookup returned ServicePoint#" + ValidationHelper.HashString(servicePoint)); } if (servicePoint == null) { // lookup failure or timeout, we need to create a new ServicePoint if (s_MaxServicePoints <= 0 || s_ServicePointTable.Count < s_MaxServicePoints) { // Determine Connection Limit int connectionLimit = InternalConnectionLimit; bool userDefined = s_UserChangedLimit; string schemeHostPort = host + ":" + port.ToString(CultureInfo.InvariantCulture); if (ConfigTable.ContainsKey(schemeHostPort)) { connectionLimit = (int)ConfigTable[schemeHostPort]; userDefined = true; } servicePoint = new ServicePoint(host, port, s_ServicePointIdlingQueue, connectionLimit, tempEntry, userDefined, isProxyServicePoint); GlobalLog.Print("ServicePointManager::FindServicePoint() created ServicePoint#" + ValidationHelper.HashString(servicePoint)); servicePointReference = new WeakReference(servicePoint); s_ServicePointTable[tempEntry] = servicePointReference; GlobalLog.Print("ServicePointManager::FindServicePoint() adding entry WeakReference#" + ValidationHelper.HashString(servicePointReference) + " key:[" + tempEntry + "]"); } else { Exception exception = new InvalidOperationException(SR.GetString(SR.net_maxsrvpoints)); GlobalLog.LeaveException("ServicePointManager::FindServicePoint() reached the limit count:" + s_ServicePointTable.Count.ToString() + " limit:" + s_MaxServicePoints.ToString(), exception); throw exception; } } } GlobalLog.Leave("ServicePointManager::FindServicePoint() servicePoint#" + ValidationHelper.HashString(servicePoint)); return(servicePoint); }
public StationModel ActivateInformationTable(string stationId) { InformationTable defaultInformationTable; var defaultContent = new Content() { ContentType = ContentType.FORECAST, Id = Guid.NewGuid().ToString(), InnerContent = stationId, TimeOut = 15 }; var station = db.Stations .Any(s => s.Id == stationId) ? db.Stations .FirstOrDefault(s => s.Id == stationId) : null; var moduleType = db.ModuleTypes .Any() ? db.ModuleTypes .FirstOrDefault() : null; if (station == null || moduleType == null) { return(null); } if (station.InformationTable == null) { defaultInformationTable = new InformationTable() { Id = Guid.NewGuid() .ToString(), AccessCode = Guid.NewGuid() .ToString(), ServiceType = 0, PasswordDevice = "", IpDevice = "", UserNameDevice = "", HeightWithModule = 2, WidthWithModule = 4, RowCount = 4 }; defaultInformationTable.Contents .Add(defaultContent); db.InformationTables.Add(defaultInformationTable); try { db.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = $"{validationErrors.Entry.Entity}:{validationError.ErrorMessage}"; raise = new InvalidOperationException(message, raise); } } } var informationTable = db.InformationTables .Any(i => string.Equals(i.Id, defaultInformationTable.Id)) ? db.InformationTables .FirstOrDefault(i => string.Equals(i.Id, defaultInformationTable.Id)) : null; if (informationTable == null) { return(null); } informationTable.ModuleType = moduleType; station.InformationTable = informationTable; } station.Active = true; try { db.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = $"{validationErrors.Entry.Entity}:{validationError.ErrorMessage}"; raise = new InvalidOperationException(message, raise); } } } return(station); }
public static void ThrowIfNecessary( this Error error, [CanBeNull] Func <Error, string> message = null) { if (error == Error.Ok) { return; } var code = Enum.GetName(typeof(Error), error); var arg = message?.Invoke(error) ?? $"Operation failed with code: '{code}(error)'"; Exception exception; switch (error) { case Error.Unauthorized: case Error.FileNoPermission: exception = new UnauthorizedAccessException(arg); break; case Error.ParameterRangeError: exception = new ArgumentOutOfRangeException(null, arg); break; case Error.OutOfMemory: exception = new OutOfMemoryException(arg); break; case Error.FileBadDrive: case Error.FileBadPath: case Error.FileNotFound: exception = new FileNotFoundException(arg); break; case Error.FileAlreadyInUse: case Error.FileCantOpen: case Error.FileCantRead: case Error.FileCorrupt: case Error.FileMissingDependencies: case Error.FileUnrecognized: exception = new FileLoadException(arg); break; case Error.FileEof: exception = new EndOfStreamException(arg); break; case Error.FileCantWrite: case Error.CantAcquireResource: case Error.CantOpen: case Error.CantCreate: case Error.AlreadyInUse: case Error.Locked: exception = new IOException(arg); break; case Error.Timeout: exception = new TimeoutException(arg); break; case Error.InvalidData: exception = new InvalidDataException(arg); break; case Error.InvalidParameter: exception = new ArgumentException(null, arg); break; default: exception = new InvalidOperationException(arg); break; } throw exception; }
/// This will set value to be the new value of this property on the /// component by invoking the setXXX method on the component. If the /// value specified is invalid, the component should throw an exception /// which will be passed up. The component designer should design the /// property so that getXXX following a setXXX should return the value /// passed in if no exception was thrown in the setXXX call. public override void SetValue(object component, object value) { // Argument, state checking. Is it ok to set this event? // if (IsReadOnly) { Exception ex = new InvalidOperationException("Tried to set a read only event."); throw ex; } if (value != null && !(value is string)) { Exception ex = new ArgumentException("Cannot set to value " + value.ToString() + "."); throw ex; } string name = (string)value; if (name != null && name.Length == 0) { name = null; } // Obtain the site for the component. Note that this can be a site // to a parent component if we can get to the reference service. // ISite site = null; if (component is IComponent) { site = ((IComponent)component).Site; } if (site == null) { IReferenceService rs = _eventSvc._provider.GetService(typeof(IReferenceService)) as IReferenceService; if (rs != null) { IComponent baseComponent = rs.GetComponent(component); if (baseComponent != null) { site = baseComponent.Site; } } } if (site == null) { Exception ex = new InvalidOperationException("There is no site for component " + component.ToString() + "."); throw ex; } // The dictionary service is where we store the actual event method name. // IDictionaryService ds = (IDictionaryService)site.GetService(typeof(IDictionaryService)); if (ds == null) { Exception ex = new InvalidOperationException("Cannot find IDictionaryService"); throw ex; } // Get the old method name, ensure that they are different, and then continue. // ReferenceEventClosure key = new ReferenceEventClosure(component, this); string oldName = (string)ds.GetValue(key); if (object.ReferenceEquals(oldName, name)) { return; } if (oldName != null && name != null && oldName.Equals(name)) { return; } // Before we continue our work, ensure that the name is // actually valid. // if (name != null) { _eventSvc.ValidateMethodName(name); } // Ok, the names are different. Fire a changing event to make // sure it's OK to perform the change. // IComponentChangeService change = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); if (change != null) { try { change.OnComponentChanging(component, this); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw; } } // Less chance of success of adding a new method name, so // don't release the old name until we verify that adding // the new one actually succeeded. // if (name != null) { _eventSvc.UseMethod(component, _eventDesc, name); } if (oldName != null) { _eventSvc.FreeMethod(component, _eventDesc, oldName); } ds.SetValue(key, name); if (change != null) { change.OnComponentChanged(component, this, oldName, name); } OnValueChanged(component, EventArgs.Empty); }
public Content CreateContent(string stationId, Content newContent) { if (newContent == null) { return(null); } var station = db.Stations .Any(s => string.Equals(s.Id, stationId)) ? db.Stations .FirstOrDefault(s => string.Equals(s.Id, stationId)) : null; if (station == null) { return(null); } var informationTable = station.InformationTable; if (informationTable == null) { return(null); } var content = new Content() { ContentType = newContent.ContentType, Id = newContent.Id ?? Guid.NewGuid() .ToString(), InnerContent = newContent.InnerContent ?? "", TimeOut = newContent.TimeOut }; db.Contents.Add(content); try { db.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry .Entity, validationError.ErrorMessage); raise = new InvalidOperationException(message, raise); } } } var newDbContent = db.Contents.Any(c => string.Equals(c.Id, content.Id)) ? db.Contents.FirstOrDefault(c => string.Equals(c.Id, content.Id)) : null; if (newDbContent == null) { return(null); } informationTable.Contents.Add(newDbContent); try { db.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = $"{validationErrors.Entry.Entity}:{validationError.ErrorMessage}"; raise = new InvalidOperationException(message, raise); } } } return(newDbContent); }