public InvalidChannelFactoryException([NotNull] InvalidOperationException configurationChannelFactoryException,
                                       [NotNull] InvalidOperationException channelFactoryException)
     : base()
 {
     this.configurationChannelFactoryException = configurationChannelFactoryException;
     this.channelFactoryException = channelFactoryException;
 }
Esempio n. 2
0
        /// <summary>
        /// The command line to run it is "evaluator.exe evaluator.config"
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            DefaultUnhandledExceptionHandler.Register();

            if (args.Count() != 1)
            {
                var e = new InvalidOperationException("Must supply only the evaluator.config file!");
                Utilities.Diagnostics.Exceptions.Throw(e, logger);
            }

            if (IsDebuggingEnabled())
            {
                AttachDebugger();
            }

            var fullEvaluatorConfiguration = ReadEvaluatorConfiguration(args[0]);
            var injector = TangFactory.GetTang().NewInjector(fullEvaluatorConfiguration);
            var serializer = injector.GetInstance<AvroConfigurationSerializer>();
            var rootEvaluatorConfiguration = 
                TangFactory.GetTang().NewConfigurationBuilder(serializer.FromString(injector.GetNamedInstance<EvaluatorConfiguration, string>()))
                    .BindSetEntry<RuntimeStartHandler, EvaluatorRuntime, IObserver<RuntimeStart>>()
                    .BindSetEntry<RuntimeStopHandler, EvaluatorRuntime, IObserver<RuntimeStop>>()
                    .Build();
            var evaluator = injector.ForkInjector(rootEvaluatorConfiguration).GetInstance<Evaluator>();

            evaluator.Run();
            logger.Log(Level.Info, "Evaluator is returned from Run()");
        }
 public InvalidChannelFactoryException([NotNull] string message,
                                       [NotNull] Exception innerException)
     : base(message, innerException)
 {
     this.configurationChannelFactoryException = null;
     this.channelFactoryException = null;
 }
        public void GetStoreTypes_converts_legacy_ProviderIncompatibleException_to_non_legacy_ProviderIncompatibleException()
        {
            var expectedInnerException = new InvalidOperationException();

            var mockLegacyManifest = new Mock<Legacy.DbProviderManifest>();
            mockLegacyManifest
                .Setup(m => m.GetStoreTypes())
                .Returns(LegacyProviderManifest.GetStoreTypes());

            mockLegacyManifest
                .Setup(m => m.GetFacetDescriptions(It.IsAny<LegacyMetadata.EdmType>()))
                .Throws(new SystemData.ProviderIncompatibleException("Test", expectedInnerException));

            var providerManifestWrapper = new LegacyDbProviderManifestWrapper(mockLegacyManifest.Object);

            // need an SSpace type as the arguemnt
            var edmType = new LegacyDbProviderManifestWrapper(LegacyProviderManifest).GetStoreTypes().First();

            var exception =
                Assert.Throws<ProviderIncompatibleException>(
                    () => providerManifestWrapper.GetFacetDescriptions(edmType));

            Assert.Equal("Test", exception.Message);
            Assert.Same(expectedInnerException, exception.InnerException);
        }
        /// <summary>
        /// Performs the actual work of authorizing and capturing a payment.  
        /// </summary>
        /// <param name="invoice">
        /// The invoice.
        /// </param>
        /// <param name="amount">
        /// The amount.
        /// </param>
        /// <param name="args">
        /// The args.
        /// </param>
        /// <returns>
        /// The <see cref="IPaymentResult"/>.
        /// </returns>
        /// <remarks>
        /// This is a transaction with SubmitForSettlement = true
        /// </remarks>
        protected override IPaymentResult PerformAuthorizeCapturePayment(IInvoice invoice, decimal amount, ProcessorArgumentCollection args)
        {
            var paymentMethodNonce = args.GetPaymentMethodNonce();

            if (string.IsNullOrEmpty(paymentMethodNonce))
            {
                var error = new InvalidOperationException("No payment method nonce was found in the ProcessorArgumentCollection");
                LogHelper.Debug<BraintreeSimpleTransactionPaymentGatewayMethod>(error.Message);
                return new PaymentResult(Attempt<IPayment>.Fail(error), invoice, false);
            }

            var attempt = ProcessPayment(invoice, TransactionOption.Authorize, invoice.Total, paymentMethodNonce);

            var payment = attempt.Payment.Result;

            GatewayProviderService.Save(payment);

            if (!attempt.Payment.Success)
            {
                GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Denied, attempt.Payment.Exception.Message, 0);
            }
            else
            {
                GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Debit, "Braintree transaction - authorized and captured", amount);
            }

            return attempt;
        }
Esempio n. 6
0
		protected override void BeginProcessing()
		{
			try
			{
				string str = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "eventvwr.exe");
				Process.Start(str, this._computerName);
			}
			catch (Win32Exception win32Exception1)
			{
				Win32Exception win32Exception = win32Exception1;
				int nativeErrorCode = win32Exception.NativeErrorCode;
				if (!nativeErrorCode.Equals(2))
				{
					ErrorRecord errorRecord = new ErrorRecord(win32Exception, "Win32Exception", ErrorCategory.InvalidArgument, null);
					base.WriteError(errorRecord);
				}
				else
				{
					string str1 = StringUtil.Format(EventlogResources.NotSupported, new object[0]);
					InvalidOperationException invalidOperationException = new InvalidOperationException(str1);
					ErrorRecord errorRecord1 = new ErrorRecord(invalidOperationException, "Win32Exception", ErrorCategory.InvalidOperation, null);
					base.WriteError(errorRecord1);
				}
			}
			catch (SystemException systemException1)
			{
				SystemException systemException = systemException1;
				ErrorRecord errorRecord2 = new ErrorRecord(systemException, "InvalidComputerName", ErrorCategory.InvalidArgument, this._computerName);
				base.WriteError(errorRecord2);
			}
		}
Esempio n. 7
0
        /// <summary>
        /// The command line to run it is "evaluator.exe evaluator.config"
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            try
            {
                if (args.Count() != 1)
                {
                    var e = new InvalidOperationException("Must supply only the evaluator.config file!");
                    Utilities.Diagnostics.Exceptions.Throw(e, logger);
                }

                if (IsDebuggingEnabled())
                {
                    AttachDebugger();
                }
                AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;

                Evaluator evaluator = TangFactory.GetTang()
                    .NewInjector(ReadClrBridgeConfiguration(), ReadEvaluatorConfiguration(args[0]))
                    .GetInstance<Evaluator>();

                evaluator.Run();
                logger.Log(Level.Info, "Evaluator is returned from Run()");
            }
            catch (Exception e)
            {
                Fail(e);
            }
        }
Esempio n. 8
0
        public void Unwrap_TypeOk()
        {
            Exception ex = new InvalidOperationException("test message");
            var copy = Subject.Unwrap(Subject.Wrap(ex));

            Assert.IsType<InvalidOperationException>(copy);
        }
 public void TestDisposeExceptions()
 {
     var d1 = Substitute.For<IDisposable>();
     var e1 = new ArgumentException();
     d1.When(d=>d.Dispose()).Do(d => { throw e1; });
     var d2 = Substitute.For<IDisposable>();
     var e2 = new InvalidOperationException();
     d2.When(d => d.Dispose()).Do(d => { throw e2; });
     var d3 = Substitute.For<IDisposable>();
     var exceptionThrown = false;
     try
     {
         using (var c = new CompositeDisposable())
         {
             c.Add(d1);
             c.Add(d2);
             c.Add(d3);
         }
     }
     catch (AggregateException e)
     {
         exceptionThrown = true;
         Assert.IsTrue(e.InnerExceptions.Contains(e1));
         Assert.IsTrue(e.InnerExceptions.Contains(e2));
     }
     Assert.IsTrue(exceptionThrown);
     d1.Received(1).Dispose();
     d2.Received(1).Dispose();
     d3.Received(1).Dispose();
 }
Esempio n. 10
0
        public void ContinuationErrorTimeoutNotHitTest()
        {
            var exceptions = new List<Exception>();

            // set up a timer to strike in 3 second
            var cont = AsyncHelpers.WithTimeout(AsyncHelpers.PreventMultipleCalls(exceptions.Add), TimeSpan.FromSeconds(1));

            var exception = new InvalidOperationException("Foo");
            // call success quickly, hopefully before the timer comes
            cont(exception);

            // sleep 2 seconds to make sure timer event comes
            Thread.Sleep(2000);

            // make sure we got success, not a timer exception
            Assert.AreEqual(1, exceptions.Count);
            Assert.IsNotNull(exceptions[0]);

            Assert.AreSame(exception, exceptions[0]);

            // those will be ignored
            cont(null);
            cont(new InvalidOperationException("Some exception"));
            cont(null);
            cont(new InvalidOperationException("Some exception"));

            Assert.AreEqual(1, exceptions.Count);
            Assert.IsNotNull(exceptions[0]);
        }
Esempio n. 11
0
 protected override void ProcessRecord()
 {
     if (!(this.specifiedPath ^ this.isLiteralPath))
     {
         InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyPathAndLiteralPath);
         ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null);
         base.ThrowTerminatingError(errorRecord);
     }
     if (this._paths != null)
     {
         foreach (string str in this._paths)
         {
             using (StreamReader reader = PathUtils.OpenStreamReader(this, str, this.Encoding, this.isLiteralPath))
             {
                 ImportCsvHelper helper = new ImportCsvHelper(this, this._delimiter, this._header, null, reader);
                 try
                 {
                     helper.Import(ref this._alreadyWarnedUnspecifiedNames);
                 }
                 catch (ExtendedTypeSystemException exception2)
                 {
                     ErrorRecord record2 = new ErrorRecord(exception2, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null);
                     base.ThrowTerminatingError(record2);
                 }
             }
         }
     }
 }
        public void SyncWithActionCapturesException() {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException("Some exception text.");

            // Act

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

            // Act & assert
            ExceptionHelper.ExpectInvalidOperationException(
                delegate {
                    SynchronizationContextHelper.Sync(mockSyncContext.Object, () => { throw exception; });
                },
                @"Some exception text.");
        }
        public void Done(IBTDTCCommitConfirm commitConfirm)
        {
            if (this.messages.Count == 0)
            {
                Exception ex = new InvalidOperationException("Send adapter received an emtpy batch for transmission from BizTalk");
                this.transportProxy.SetErrorInfo(ex);

                return;
            }

            //  The Enter/Leave is used to implement the Terminate call from BizTalk.

            //  Do an "Enter" for every message
            int MessageCount = this.messages.Count;
            for (int i = 0; i < MessageCount; i++)
            {
                if (!this.asyncTransmitter.Enter())
                    throw new InvalidOperationException("Send adapter Enter call was false within Done. This is illegal and should never happen."); ;
            }

            try
            {
                new WorkerDelegate(Worker).BeginInvoke(null, null);
            }
            catch (Exception)
            {
                //  If there was an error we had better do the "Leave" here
                for (int i = 0; i < MessageCount; i++)
                    this.asyncTransmitter.Leave();
            }
        }
Esempio n. 14
0
        private void OnError(int? contextId, string error)
        {
            var exception = new InvalidOperationException(error);
            if (contextId == null || contextId == -1)
            {
                _projectContexts.TrySetException(exception);
                _shutdown.RequestShutdown();
            }
            else
            {
                _compileResponses.AddOrUpdate(contextId.Value,
                _ =>
                {
                    var tcs = new TaskCompletionSource<CompileResponse>();
                    tcs.SetException(exception);
                    return tcs;
                },
                (_, existing) =>
                {
                    if (!existing.TrySetException(exception))
                    {
                        var tcs = new TaskCompletionSource<CompileResponse>();
                        tcs.TrySetException(exception);
                        return tcs;
                    }

                    return existing;
                });
            }
        }
        // will either return a valid socket or will set exceptionToBeThrown
        protected UdpSocket GetSendSocket(int interfaceIndex, out Exception exceptionToBeThrown)
        {
            Fx.Assert(this.IsMulticast == true, "This overload should only be used for multicast.");

            UdpSocket result = null;
            exceptionToBeThrown = null;

            lock (ThisLock)
            {
                if (this.State == CommunicationState.Opened)
                {
                    for (int i = 0; i < this.SendSockets.Length; i++)
                    {
                        if (interfaceIndex == this.SendSockets[i].InterfaceIndex)
                        {
                            result = this.SendSockets[i];
                            break;
                        }
                    }

                    if (result == null)
                    {
                        exceptionToBeThrown = new InvalidOperationException(SR.UdpSendFailedInterfaceIndexMatchNotFound(interfaceIndex));
                    }
                }
                else
                {
                    exceptionToBeThrown = CreateObjectDisposedException();
                }
            }

            return result;
        }
		public void Export_ErrorOccurred_RaisesErrorEventArgs()
		{
			// arrange
			var repository = CreateRepository(maxNumberOfLogs: 1);
			var fileSystemHelper = new Mock<IFileSystemHelper>();
			var databaseCreator = new SqlCeDatabaseCreator(fileSystemHelper.Object, new FakeLog());
			var exporter = new ErrorLogExporter(repository, databaseCreator);

			repository.Initialize();

			var error = new InvalidOperationException();
			fileSystemHelper.Setup(x => x.FileExists(It.IsAny<string>())).Throws(error);

			// act
			var eventWasRaised = false;
			exporter.OnError += delegate(object sender, ErrorLogExporterErrorEventArgs args)
			                    	{
			                    		eventWasRaised = true;
										Assert.That(args.Error, Is.EqualTo(error));
			                    	};

			exporter.Export(_databaseFilename);

			// assert
			Assert.That(eventWasRaised, Is.True);
		}
Esempio n. 17
0
 public void Create(Entities.CTB_CONTR Model)
 {
     try
     {
         db.CTB_CONTR.Add(Model);
         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;
     }
 }
Esempio n. 18
0
        public void AddUser(Entities.User u)
        {
            try
              {
            var db = new CapstoneDbContext();
            db.Users.Add(u);

                db.SaveChanges();
              }
              catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) //Catches errors in creating the db User table for the first time
              {
              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;
              }
        }
 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 flag = this.OnTryCreateException(message, fault, out exception);
     if (flag)
     {
         if (exception == null)
         {
             Exception exception2 = new InvalidOperationException(System.ServiceModel.SR.GetString("FaultConverterDidNotCreateException", new object[] { base.GetType().Name }));
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception2);
         }
         return flag;
     }
     if (exception != null)
     {
         Exception exception3 = new InvalidOperationException(System.ServiceModel.SR.GetString("FaultConverterCreatedException", new object[] { base.GetType().Name }), exception);
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception3);
     }
     return flag;
 }
Esempio n. 20
0
 protected override void EndProcessing()
 {
     if ((this._numberRemoved == 0) && !base.MyInvocation.BoundParameters.ContainsKey("WhatIf"))
     {
         bool flag = true;
         bool flag2 = true;
         foreach (string str in this._name)
         {
             if (!InitialSessionState.IsEngineModule(str))
             {
                 flag2 = false;
             }
             if (!WildcardPattern.ContainsWildcardCharacters(str))
             {
                 flag = false;
             }
         }
         if (!flag2 && (!flag || (this._moduleInfo.Length != 0)))
         {
             InvalidOperationException exception = new InvalidOperationException(StringUtil.Format(Modules.NoModulesRemoved, new object[0]));
             ErrorRecord errorRecord = new ErrorRecord(exception, "Modules_NoModulesRemoved", ErrorCategory.ResourceUnavailable, null);
             base.WriteError(errorRecord);
         }
     }
 }
    public void SetUp ()
    {
      _exception = new InvalidOperationException ("What");
      _evaluatedExpression = ExpressionHelper.CreateExpression (typeof (double));

      _exceptionExpression = new PartialEvaluationExceptionExpression (_exception, _evaluatedExpression);
    }
Esempio n. 22
0
 public void ShouldLogAnErrorWhenUpgradeFails()
 {
     var ex = new InvalidOperationException();
     ScriptProvider.GetScripts(Arg.Any<Func<IDbConnection>>()).Returns(provider => { throw ex; });
     DbUpgrader.PerformUpgrade();
     Log.Received().WriteError("Upgrade failed due to an unexpected exception:\r\n{0}", ex.ToString());
 }
 internal override void AnalyzeUsage(CodeExpression expression, RuleAnalysis analysis, bool isRead, bool isWritten, RulePathQualifier qualifier)
 {
     CodePropertyReferenceExpression expression2 = (CodePropertyReferenceExpression) expression;
     CodeExpression targetObject = expression2.TargetObject;
     if (analysis.Validation.ExpressionInfo(targetObject) == null)
     {
         InvalidOperationException exception = new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ExpressionNotValidated, new object[0]));
         exception.Data["ErrorObject"] = targetObject;
         throw exception;
     }
     RulePropertyExpressionInfo info2 = analysis.Validation.ExpressionInfo(expression2) as RulePropertyExpressionInfo;
     if (info2 == null)
     {
         InvalidOperationException exception2 = new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ExpressionNotValidated, new object[0]));
         exception2.Data["ErrorObject"] = expression2;
         throw exception2;
     }
     PropertyInfo propertyInfo = info2.PropertyInfo;
     List<CodeExpression> attributedExprs = new List<CodeExpression>();
     analysis.AnalyzeRuleAttributes(propertyInfo, targetObject, qualifier, null, null, attributedExprs);
     if (!attributedExprs.Contains(targetObject))
     {
         RuleExpressionWalker.AnalyzeUsage(analysis, targetObject, isRead, isWritten, new RulePathQualifier(propertyInfo.Name, qualifier));
     }
 }
 internal override RuleExpressionResult Evaluate(CodeExpression expression, RuleExecution execution)
 {
     CodeCastExpression expression2 = (CodeCastExpression) expression;
     object operandValue = RuleExpressionWalker.Evaluate(execution, expression2.Expression).Value;
     RuleExpressionInfo info = execution.Validation.ExpressionInfo(expression2);
     if (info == null)
     {
         InvalidOperationException exception = new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ExpressionNotValidated, new object[0]));
         exception.Data["ErrorObject"] = expression2;
         throw exception;
     }
     Type expressionType = info.ExpressionType;
     if (operandValue == null)
     {
         if (ConditionHelper.IsNonNullableValueType(expressionType))
         {
             RuleEvaluationException exception2 = new RuleEvaluationException(string.Format(CultureInfo.CurrentCulture, Messages.CastIncompatibleTypes, new object[] { Messages.NullValue, RuleDecompiler.DecompileType(expressionType) }));
             exception2.Data["ErrorObject"] = expression2;
             throw exception2;
         }
     }
     else
     {
         operandValue = Executor.AdjustTypeWithCast(execution.Validation.ExpressionInfo(expression2.Expression).ExpressionType, operandValue, expressionType);
     }
     return new RuleLiteralResult(operandValue);
 }
Esempio n. 25
0
 protected override void ProcessRecord()
 {
     ProviderInfo provider = null;
     Collection<string> resolvedProviderPathFromPSPath;
     try
     {
         if (base.Context.EngineSessionState.IsProviderLoaded(base.Context.ProviderNames.FileSystem))
         {
             resolvedProviderPathFromPSPath = base.SessionState.Path.GetResolvedProviderPathFromPSPath(this._path, out provider);
         }
         else
         {
             resolvedProviderPathFromPSPath = new Collection<string> {
                 this._path
             };
         }
     }
     catch (ItemNotFoundException)
     {
         FileNotFoundException exception = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, this._path));
         ErrorRecord errorRecord = new ErrorRecord(exception, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, this._path);
         base.WriteError(errorRecord);
         return;
     }
     if (!provider.NameEquals(base.Context.ProviderNames.FileSystem))
     {
         throw InterpreterError.NewInterpreterException(this._path, typeof(RuntimeException), null, "FileOpenError", ParserStrings.FileOpenError, new object[] { provider.FullName });
     }
     if ((resolvedProviderPathFromPSPath != null) && (resolvedProviderPathFromPSPath.Count >= 1))
     {
         if (resolvedProviderPathFromPSPath.Count > 1)
         {
             throw InterpreterError.NewInterpreterException(resolvedProviderPathFromPSPath, typeof(RuntimeException), null, "AmbiguousPath", ParserStrings.AmbiguousPath, new object[0]);
         }
         string path = resolvedProviderPathFromPSPath[0];
         ExternalScriptInfo scriptInfo = null;
         if (System.IO.Path.GetExtension(path).Equals(".psd1", StringComparison.OrdinalIgnoreCase))
         {
             string str5;
             scriptInfo = base.GetScriptInfoForFile(path, out str5, false);
             PSModuleInfo sendToPipeline = base.LoadModuleManifest(scriptInfo, ModuleCmdletBase.ManifestProcessingFlags.WriteWarnings | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, null, null);
             if (sendToPipeline != null)
             {
                 base.WriteObject(sendToPipeline);
             }
         }
         else
         {
             InvalidOperationException exception3 = new InvalidOperationException(StringUtil.Format(Modules.InvalidModuleManifestPath, path));
             ErrorRecord record3 = new ErrorRecord(exception3, "Modules_InvalidModuleManifestPath", ErrorCategory.InvalidArgument, this._path);
             base.ThrowTerminatingError(record3);
         }
     }
     else
     {
         FileNotFoundException exception2 = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, this._path));
         ErrorRecord record2 = new ErrorRecord(exception2, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, this._path);
         base.WriteError(record2);
     }
 }
Esempio n. 26
0
        public void Catch3()
        {
            var ex = new InvalidOperationException("Bang!");

            var err = false;
            var xs = new[] { 1, 2, 3 }.ToAsyncEnumerable().Concat(AsyncEnumerable.Throw<int>(ex));
            var ys = new[] { 4, 5, 6 }.ToAsyncEnumerable();

            var res = xs.Catch<int, Exception>(ex_ => { err = true; return ys; });

            var e = res.GetEnumerator();
            HasNext(e, 1);
            HasNext(e, 2);
            HasNext(e, 3);

            Assert.False(err);

            HasNext(e, 4);

            Assert.True(err);

            HasNext(e, 5);
            HasNext(e, 6);
            NoNext(e);
        }
Esempio n. 27
0
        public static void ValidateDirectory(ProviderInfo provider, string directory)
        {
            validateFileSystemPath(provider, directory);

            if (!Directory.Exists(directory))
            {
                Exception exception;

                if (File.Exists(directory))
                {
                    exception = new InvalidOperationException($"{directory} is not a directory.");
                    ExceptionHelper.SetUpException(
                                                   ref exception,
                                                   ERR_NO_DIRECTORY,
                                                   ErrorCategory.InvalidOperation,
                                                   directory);
                }
                else
                {
                    exception =
                        new FileNotFoundException(
                            $"The directory {directory} could not be found.");
                    ExceptionHelper.SetUpException(
                                                   ref exception,
                                                   ERR_NO_DIRECTORY,
                                                   ErrorCategory.InvalidData,
                                                   directory);
                }

                throw exception;
            }
        }
        // will either return a valid socket or will set exceptionToBeThrown
        protected UdpSocket GetSendSocket(IPAddress address, Uri destination, out Exception exceptionToBeThrown)
        {
            Fx.Assert(this.IsMulticast == false, "This overload should only be used for unicast.");

            UdpSocket result = null;
            exceptionToBeThrown = null;
            AddressFamily family = address.AddressFamily;

            lock (ThisLock)
            {
                if (this.State == CommunicationState.Opened)
                {
                    for (int i = 0; i < this.SendSockets.Length; i++)
                    {
                        if (family == this.SendSockets[i].AddressFamily)
                        {
                            result = this.SendSockets[i];
                            break;
                        }
                    }

                    if (result == null)
                    {
                        exceptionToBeThrown = new InvalidOperationException(SR.RemoteAddressUnreachableDueToIPVersionMismatch(destination));
                    }
                }
                else
                {
                    exceptionToBeThrown = CreateObjectDisposedException();
                }
            }

            return result;
        }
            public void ReturnsTrueForInheritingReferenceType()
            {
                var type = typeof(Exception);
                var instance = new InvalidOperationException();

                Assert.IsTrue(type.IsInstanceOfTypeEx(instance));              
            }
Esempio n. 30
0
 public static partial void Method5(ILogger logger, System.InvalidOperationException p1, System.InvalidOperationException p2);
Esempio n. 31
0
        protected override IEnumerator LoadModelFileNetworkedWebGL(string objURL, Action <Exception> OnError)
        {
            bool      isWorking   = true;
            Exception ex          = null;
            float     oldProgress = individualProgress.Value;

            try
            {
                StartCoroutine(DownloadFileWebGL(objURL, individualProgress, (text) =>
                {
                    isWorking  = false;
                    loadedText = text;
                    //loadedText = Encoding.UTF8.GetString(bytes);
                },
                                                 (error) =>
                {
                    ObjectImporter.activeDownloads -= 1;
                    ex = new System.InvalidOperationException("Base model download unsuccessful." + error);
                    ObjectImporter.isException = true;
                    OnError(ex);
                    isWorking = false;
                }));
            }

            catch (Exception exc)
            {
                ObjectImporter.activeDownloads       -= 1;
                individualProgress.Value              = oldProgress;
                ObjectImporter.downloadProgress.Value = (individualProgress.Value / ObjectImporter.activeDownloads) * 100f; isWorking = false;
                isWorking = false;
                OnError(exc);
                ObjectImporter.isException = true;
            }



            while (isWorking)
            {
                yield return(new WaitForSeconds(0.1f));

                ObjectImporter.downloadProgress.Value = (individualProgress.Value / ObjectImporter.activeDownloads) * 100f;
            }


            if (ObjectImporter.isException)
            {
                yield return(null);
            }


            ObjectImporter.downloadProgress.Value = (individualProgress.Value / ObjectImporter.activeDownloads) * 100f;


            //yield return LoadOrDownloadText(url);

            if (string.IsNullOrEmpty(loadedText))
            {
                totalProgress.singleProgress.Remove(objLoadingProgress);
                throw new InvalidOperationException("Failed to load data from the downloaded obj file. The file might be empty or non readable.");
            }
            //Debug.LogFormat("Parsing geometry data in {0}...", www.url);

            try
            {
                ParseGeometryData(loadedText);
            }

            catch (Exception exc)
            {
                OnError(exc);
                ObjectImporter.isException = true;
            }
        }
Esempio n. 32
0
        public static Operation <T> Fold <T>(this IEnumerable <Operation <T> > operations, Func <T, T, T> accumulate)
        {
            using (IEnumerator <Operation <T> > e = operations.GetEnumerator())
            {
                //Make Sure Sequence isn't empty
                if (!e.MoveNext())
                {
                    var ex = new InvalidOperationException("Sequence contains no Elements");
                    return(new Operation <T>(ex)
                    {
                        Message = ex.Message,
                    });
                }

                List <Operation> badOperations = new List <Operation>();

                //Process First Element
                var result = default(T);

                if (e.Current.Succeeded)
                {
                    result = e.Current.Result;
                }
                else
                {
                    badOperations.Add(e.Current);
                }

                //Process the Rest
                while (e.MoveNext())
                {
                    if (e.Current.Succeeded)
                    {
                        result = accumulate(result, e.Current.Result);
                    }
                    else
                    {
                        badOperations.Add(e.Current);
                    }
                }


                //If there are any bad operations
                if (badOperations.Any())
                {
                    string messages = null;
                    for (int i = 0; i < badOperations.Count; i++)
                    {
                        //Get Innermost Exception
                        var badOperation = badOperations[i];

                        //If this this the First Exception then Assign it Directly
                        if (i == 0)
                        {
                            messages = badOperation.Message;
                        }
                        else
                        {
                            //Othewise Concat the Message
                            messages = messages + ", " + badOperation.Message;
                        }
                    }

                    //Aggregate Exceptions
                    var aggregate = new AggregateException(badOperations.Select(o => o.GetException()));

                    return(new Operation <T>(aggregate)
                    {
                        Message = messages,
                        Succeeded = false
                    });
                }
                else
                {
                    return(new Operation <T>()
                    {
                        Succeeded = true,
                        Result = result
                    });
                }
            }
        }
Esempio n. 33
0
    }     //Main

    /// <summary>
    /// Invokes tar and builds the list of files in the archive which are not to be deleted.
    /// </summary>
    /// <param name="CurrentSettings"></param>
    public static void RunCommand(Settings CurrentSettings)
    {
        try
        {
            StringDictionary FileTable     = new StringDictionary();
            ArrayList        DeleteList    = new ArrayList();
            string           DeleteCommand = null;
            string           sep           = Path.DirectorySeparatorChar.ToString();

            StreamWriter OutFile = new StreamWriter(CurrentSettings.DeletionScriptPath +
                                                    Path.DirectorySeparatorChar +
                                                    m_DeleteScriptName);

            switch (CurrentSettings.OSType)
            {
            case OSTypeEnum.Windows:
            {
                DeleteCommand = "@del /f ";
                break;
            }     //case

            case OSTypeEnum.Unix:
            {
                OutFile.WriteLine("#!/bin/sh");
                DeleteCommand = "rm -f -v ";
                break;
            }     //case

            default:
            {
                throw new System.InvalidOperationException("Invalid OSTypeEnum value.");
            }     //case
            } //switch

            string fullCommand = m_CommandArgument + CurrentSettings.TarFileName;
            // Check to see that tar is in path.

            Console.WriteLine();
            // tar fails on the Mac.  Try gnutar first.
            if (ToolInstalled("gnutar"))
            {
                m_CommandName = "gnutar";
                Console.WriteLine("Found utility named: {0}", m_CommandName);
            } //if
            else
            {
                if (ToolInstalled("tar"))
                {
                    m_CommandName = "tar";
                    Console.WriteLine("Found utility named: {0}", m_CommandName);
                    Console.WriteLine("Tar utility may truncate file names on Mac OS X.");
                }    //if
                else //No tar installed.
                {
                    Console.WriteLine("No tar utility found. Exiting...");
                    System.InvalidOperationException ioe = new System.InvalidOperationException("No tar utility found.");
                    throw ioe;
                } //else
            }

            ConsoleProcess toolProc = new ConsoleProcess(m_CommandName, fullCommand);
            Console.WriteLine(m_nl + "Starting command {0} {1}", m_CommandName, fullCommand);
            toolProc.Start();

            // Wait for all IO to complete.
            toolProc.WaitForOutput();

            // Get standard output and error (if any).
            string toolStdOut   = toolProc.StandardOutputString;
            string toolStdError = toolProc.StandardErrorString;

            // If there is output to stdErr or a bad command exit code output warning.
            if (toolStdError != null || toolProc.BaseProcess.ExitCode != 0)
            {
                Console.WriteLine(m_nl +
                                  "*************************** Tool Error ***************************");
                Console.WriteLine(m_nl +
                                  "Exit code: {0}", toolProc.BaseProcess.ExitCode);
                Console.WriteLine(m_nl +
                                  "Error in tool operation: {0}", toolStdError);
                System.Environment.ExitCode = toolProc.BaseProcess.ExitCode;
                return;
            } //if

            if (toolStdOut == null || toolStdOut.Length < 1)
            {
                Console.WriteLine(m_nl + "No file list generated, exiting");
                System.Environment.ExitCode = 1;
                return;
            } //if

            Console.WriteLine(m_nl + "Finished {0} {1}, searching for files to delete ...",
                              m_CommandName,
                              m_CommandArgument);

            StringReader outputList = new StringReader(toolStdOut);
            string       fname      = null;
            string       line       = null;

            while (outputList.Peek() > -1)
            {
                line = outputList.ReadLine();

                // Tar always outputs using forward slashes as the separator char.
                if (CurrentSettings.OSType == OSTypeEnum.Windows)
                {
                    fname = CurrentSettings.SSCLIRootDirectory + sep + line.Replace("/", sep);
                } //if
                else
                {
                    fname = CurrentSettings.SSCLIRootDirectory + sep + line;
                } //else

                if (!Directory.Exists(fname)) // filter out directory names
                {
                    // There is a rare case where the table already contains the name.
                    if (!FileTable.ContainsKey(fname.ToLower()))
                    {
                        FileTable.Add(fname.ToLower(), fname.ToLower());
                    } //if
                }     //if
            }         //while

            CreateDeletionFile(new DirectoryInfo(CurrentSettings.SSCLIRootDirectory),
                               OutFile,
                               FileTable,
                               DeleteList,
                               DeleteCommand,
                               CurrentSettings);
            OutFile.Flush();
            OutFile.Close();

            // Make script executable on Unix
            if (CurrentSettings.OSType == OSTypeEnum.Unix)
            {
                System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo();
                si.FileName  = "chmod";
                si.Arguments = "+x " +
                               CurrentSettings.DeletionScriptPath +
                               Path.DirectorySeparatorChar +
                               m_DeleteScriptName;
                si.UseShellExecute = false;
                System.Diagnostics.Process chmodproc = System.Diagnostics.Process.Start(si);
                chmodproc.WaitForExit();
            } //if

            Console.WriteLine(m_nl +
                              "*********************************************************");
            Console.WriteLine("Deletion script file created at: {0}",
                              CurrentSettings.DeletionScriptPath +
                              Path.DirectorySeparatorChar +
                              m_DeleteScriptName);
        } //try
        catch (Exception e)
        {
            Console.WriteLine("Exception in GenerateFile: {0}", e.ToString());
        } //catch
    }     //GenerateFile()
 private void label1_Click(object sender, EventArgs e)
 {
     System.InvalidOperationException exOne = new System.InvalidOperationException("this operation isn't allowed");
     throw exOne;
 }
Esempio n. 35
0
 public void stuff(int mars)
 {
     System.InvalidOperationException exceptionOne = new System.InvalidOperationException("this operation isn't allowed");
     throw exceptionOne;
     MessageBox.Show("Test");
 }
 public void exceptionHandlerInvalidOperation(System.InvalidOperationException ex, string text)
 {
     Console.WriteLine("No record found: " + text);
     Console.WriteLine("Exception message: " + ex.Message);
 }
Esempio n. 37
0
        protected override async Task LoadModelFileNetworked(string objURL)
        {
            bool isWorking = true;

            byte[]    downloadedBytes = null;
            Exception ex          = null;
            float     oldProgress = individualProgress.Value;

            try
            {
                StartCoroutine(DownloadFile(objURL, individualProgress, (bytes) =>
                {
                    isWorking       = false;
                    downloadedBytes = bytes;
                    //loadedText = Encoding.UTF8.GetString(bytes);
                },
                                            (error) =>
                {
                    ObjectImporter.activeDownloads -= 1;
                    ex        = new System.InvalidOperationException("Failed to download base model." + error);
                    isWorking = false;
                }));
            }

            catch (Exception exc)
            {
                ObjectImporter.activeDownloads       -= 1;
                individualProgress.Value              = oldProgress;
                ObjectImporter.downloadProgress.Value = (individualProgress.Value / ObjectImporter.activeDownloads) * 100f; isWorking = false;
                throw exc;
            }



            while (isWorking)
            {
                //Debug.Log("Stuck in ISWORKING WHILE LOOP");
                ObjectImporter.downloadProgress.Value = (individualProgress.Value / ObjectImporter.activeDownloads) * 100f;
                await Task.Delay(1);
            }

            if (ex != null)
            {
                throw ex;
            }

            ObjectImporter.downloadProgress.Value = (individualProgress.Value / ObjectImporter.activeDownloads) * 100f;

            if (downloadedBytes != null && downloadedBytes.Length > 0)
            {
                using (StreamReader sr = new StreamReader(new MemoryStream(downloadedBytes)))
                {
                    loadedText = await sr.ReadToEndAsync();
                }
            }


            //yield return LoadOrDownloadText(url);

            if (string.IsNullOrEmpty(loadedText))
            {
                totalProgress.singleProgress.Remove(objLoadingProgress);
                throw new InvalidOperationException("Failed to load data from the downloaded obj file. The file might be empty or non readable.");
                // remove this progress to let complete the total loading process
                //return;
            }
            //Debug.LogFormat("Parsing geometry data in {0}...", www.url);

            try
            {
                ParseGeometryData(loadedText);
            }

            catch (Exception exc)
            {
                throw exc;
            }
        }
Esempio n. 38
-1
        public InfluxDbAgent(string url, string databaseName, string userName, string password, TimeSpan? requestTimeout, InfluxVersion influxVersion = InfluxVersion.Auto)
        {
            _databaseName = databaseName;
            _userName = userName;
            _password = password;

            Uri result;
            if (!Uri.TryCreate(url, UriKind.Absolute, out result))
            {
                var exp = new InvalidOperationException("Unable to parse provided connection as url.");
                exp.Data.Add("Url", url);
                throw exp;
            }

            try
            {
                _influxDb = new InfluxDb(url, userName, password, influxVersion, requestTimeout);
            }
            catch (Exception exception)
            {
                var exp = new InvalidOperationException("Could not establish a connection to the database.", exception);
                exp.Data.Add("Url", url);
                exp.Data.Add("Username", userName);
                throw exp;
            }
        }