本文整理汇总了C#中System.InvalidOperationException类的典型用法代码示例。如果您正苦于以下问题:C# InvalidOperationException类的具体用法?C# InvalidOperationException怎么用?C# InvalidOperationException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
InvalidOperationException类属于System命名空间,在下文中一共展示了InvalidOperationException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ValidateDirectory
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;
}
}
示例2: Done
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();
}
}
示例3: SetUp
public void SetUp ()
{
_exception = new InvalidOperationException ("What");
_evaluatedExpression = ExpressionHelper.CreateExpression (typeof (double));
_exceptionExpression = new PartialEvaluationExceptionExpression (_exception, _evaluatedExpression);
}
示例4: Main
/// <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);
}
}
示例5: PerformAuthorizeCapturePayment
/// <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;
}
示例6: TestDisposeExceptions
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();
}
示例7: BeginProcessing
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);
}
}
示例8: Unwrap_TypeOk
public void Unwrap_TypeOk()
{
Exception ex = new InvalidOperationException("test message");
var copy = Subject.Unwrap(Subject.Wrap(ex));
Assert.IsType<InvalidOperationException>(copy);
}
示例9: ContinuationErrorTimeoutNotHitTest
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]);
}
示例10: ProcessRecord
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);
}
}
}
}
}
示例11: Evaluate
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);
}
示例12: Main
/// <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()");
}
示例13: AnalyzeUsage
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));
}
}
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:25,代码来源:PropertyReferenceExpression.cs
示例14: OnError
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;
});
}
}
示例15: ProcessRecord
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);
}
}