/// <summary> /// Constructs <see langword="await"/> expression. /// </summary> /// <param name="expression">An expression providing asynchronous result in the form or <see cref="Task"/> or any other TAP pattern.</param> /// <param name="configureAwait"><see langword="true"/> to call <see cref="Task.ConfigureAwait(bool)"/> with <see langword="false"/> argument.</param> /// <exception cref="ArgumentException">Passed expression doesn't implement TAP pattern.</exception> public AwaitExpression(Expression expression, bool configureAwait = false) { const BindingFlags PublicInstanceMethod = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy; if (configureAwait) { var configureMethod = expression.Type.GetMethod(nameof(Task.ConfigureAwait), PublicInstanceMethod, Type.DefaultBinder, new[] { typeof(bool) }, Array.Empty <ParameterModifier>()); if (!(configureMethod is null)) { expression = expression.Call(configureMethod, false.Const()); } } //expression type must have type with GetAwaiter() method var getAwaiter = expression.Type.GetMethod(nameof(Task.GetAwaiter), PublicInstanceMethod, Type.DefaultBinder, Array.Empty <Type>(), Array.Empty <ParameterModifier>()); GetAwaiter = expression.Call(getAwaiter ?? throw new ArgumentException(ExceptionMessages.MissingGetAwaiterMethod(expression.Type))); GetResultMethod = GetAwaiter.Type.GetMethod(nameof(TaskAwaiter.GetResult), PublicInstanceMethod, Type.DefaultBinder, Array.Empty <Type>(), Array.Empty <ParameterModifier>()); if (GetResultMethod is null) { throw new ArgumentException(ExceptionMessages.MissingGetResultMethod(GetAwaiter.Type)); } }
/// <summary> /// Creates a Dummy object of the specified type if it's supported by the supplied factories. /// </summary> /// <param name="typeOfDummy">The type of Dummy object to create.</param> /// <param name="fakeObject">The Dummy object that was created, if the method returns true.</param> /// <returns>True if a Dummy object can be created.</returns> public bool TryCreateDummyObject(Type typeOfDummy, out object fakeObject) { var dummyFactory = this.cachedDummyFactories.GetOrAdd( typeOfDummy, type => this.allDummyFactories.FirstOrDefault(factory => factory.CanCreate(type))); if (dummyFactory == null) { fakeObject = null; return(false); } try { fakeObject = dummyFactory.Create(typeOfDummy); } catch (Exception ex) { throw new UserCallbackException(ExceptionMessages.UserCallbackThrewAnException($"Dummy factory '{dummyFactory.GetType()}'"), ex); } return(true); }
public async Task Request_Get_WordCount_Returns_400(string name, string contentType) { const string fileName = "TestFileWithNoData.txt"; var path = Path.Combine(Environment.CurrentDirectory, "TestData/TestFileWithNoData.txt"); using var formContent = new MultipartFormDataContent(); formContent.Headers.ContentType.MediaType = contentType; Stream fileStream = File.OpenRead(path); formContent.Add(new StreamContent(fileStream), "file", fileName); var response = await _client.PostAsync(RequestUrl, formContent); var content = await response.Content.ReadAsStringAsync(); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); var errorContent = JsonConvert.DeserializeObject <ErrorMessage>(content); errorContent.Error.Should() .Be(ExceptionMessages.InvalidInput(name)); }
public decimal GetRate(Currency currFrom, Currency currTo) { if (currFrom == currTo) { return(1m); } TimeSpan difference = DateTime.Now - _updateTime; if (difference >= _updateDifference) { UpdateRate(currFrom); } foreach (Rate c in _rates) { if (c.Curr1 == currFrom && c.Curr2 == currTo) { return(c.Coefficient); } } throw new InvalidOperationException(ExceptionMessages.ExchangeRatesNoFittedRate()); }
public virtual void Apply(IInterceptedFakeObjectCall fakeObjectCall) { Guard.AgainstNull(fakeObjectCall, nameof(fakeObjectCall)); foreach (var action in this.Actions) { try { action.Invoke(fakeObjectCall); } catch (Exception ex) when(!(ex is FakeConfigurationException)) { throw new UserCallbackException(ExceptionMessages.UserCallbackThrewAnException("Callback"), ex); } } this.applicator.Invoke(fakeObjectCall); this.ApplyOutAndRefParametersValueProducer(fakeObjectCall); if (this.CallBaseMethod) { fakeObjectCall.CallBaseMethod(); } }
public async Task <TransactionCheckResult> TransactionAsync(string accFromName, string userFromName, string accToName, string userToName, decimal amount) { TransactionCheckResult result = new TransactionCheckResult(); if (accFromName == accToName && userFromName == userToName) { result.IsSameAccs = true; return(result); } AccountEntity accEntityFrom = await GetAccountEntityAsync(accFromName, userFromName); AccountEntity accEntityTo = await GetAccountEntityAsync(accToName, userToName); Account accFrom = new Account(accEntityFrom, AccountCreationOptions.EmptyName); Account accTo = new Account(accEntityTo, AccountCreationOptions.EmptyName); decimal coefficient = await _globalRates.GetRateAsync(accFrom.Money.Curr, accTo.Money.Curr); accFrom.Money.AdjustExchangeRate(accFrom.Money.Curr, accTo.Money.Curr, coefficient); accTo.Money.AdjustExchangeRate(accFrom.Money.Curr, accTo.Money.Curr, coefficient); AccountManager accManager = await GetAccountManagerAsync(accEntityFrom, userFromName); AccountEntity commissionAccEntity = await GetCommissionAccount(); CommissionAccount commissionAcc = new CommissionAccount(commissionAccEntity, AccountCreationOptions.CurrencyOnly); commissionAcc.SubscribeToCommission(accManager); try { accManager.Transaction(accFrom, accTo, amount); } catch (Exception ex) { if (ex.Message == ExceptionMessages.TransactionInsufficientFunds()) { result.IsEnough = false; return(result); } else { throw new Exception(ex.Message); } } commissionAcc.UnsubscribeFromCommission(accManager); result.IsEnough = true; result.SendAmount = accEntityFrom.Amount - accFrom.Money.Amount; result.Commission = result.SendAmount - amount; result.Receive = accTo.Money.Amount - accEntityTo.Amount; result.CommissionOwner = commissionAccEntity.User.UserName; result.CommissionAccName = commissionAccEntity.AccountName; result.CurrFrom = accEntityFrom.Currency; result.CurrTo = accEntityTo.Currency; accEntityFrom.Amount = accFrom.Money.Amount; accEntityTo.Amount = accTo.Money.Amount; commissionAccEntity.Amount += commissionAcc.Money.Amount; DBContext.Accounts.Update(accEntityFrom); DBContext.Accounts.Update(accEntityTo); DBContext.Accounts.Update(commissionAccEntity); await DBContext.SaveChangesAsync(); return(result); }
/// <summary> /// Initializes a new exception indicating that requested property doesn't exist. /// </summary> /// <param name="declaringType">The inspected type.</param> /// <param name="propertyName">The name of the missing property.</param> /// <param name="propertyType">The type of the missing property.</param> public MissingPropertyException(Type declaringType, string propertyName, Type propertyType) : base(declaringType, ExceptionMessages.MissingProperty(propertyName, propertyType, declaringType)) { PropertyType = propertyType; PropertyName = propertyName; }
private InvalidOperationException OperatorNotExists() => new InvalidOperationException(ExceptionMessages.MissingOperator(operatorType));
internal static IResolveConstraint FrameControlIsNotOfFrameControlType(object frameControl, Type frameControlType) { var message = ExceptionMessages.FrameControlIsNotOfFrameControlType(frameControl, frameControlType); return(Throws.ArgumentException.And.Message.EqualTo(message)); }
public AwaitExpression(Expression expression, bool configureAwait = false) { const BindingFlags PublicInstanceMethod = BindingFlags.Public | BindingFlags.Instance; if (configureAwait) { MethodInfo?configureMethod = expression.Type.GetMethod(nameof(Task.ConfigureAwait), PublicInstanceMethod, Type.DefaultBinder, new[] { typeof(bool) }, null); if (configureMethod is not null) { expression = expression.Call(configureMethod, false.Const()); } } // expression type must have type with GetAwaiter() method MethodInfo?getAwaiter = expression.Type.GetMethod(nameof(Task.GetAwaiter), PublicInstanceMethod, Type.DefaultBinder, Array.Empty <Type>(), null); GetAwaiter = expression.Call(getAwaiter ?? throw new ArgumentException(ExceptionMessages.MissingGetAwaiterMethod(expression.Type))); getAwaiter = GetAwaiter.Type.GetMethod(nameof(TaskAwaiter.GetResult), PublicInstanceMethod, Type.DefaultBinder, Array.Empty <Type>(), null); GetResultMethod = getAwaiter ?? throw new ArgumentException(ExceptionMessages.MissingGetResultMethod(GetAwaiter.Type)); }
internal static string GetMessage(this ExceptionMessages message, params string[] args) => string.Format(message.GetDescription(), args);
private async ValueTask <TResult> ReadAsync <TResult>(LogEntryConsumer <IRaftLogEntry, TResult> reader, DataAccessSession session, long startIndex, long endIndex, CancellationToken token) { if (startIndex > state.LastIndex) { throw new IndexOutOfRangeException(ExceptionMessages.InvalidEntryIndex(endIndex)); } if (endIndex > state.LastIndex) { throw new IndexOutOfRangeException(ExceptionMessages.InvalidEntryIndex(endIndex)); } var length = endIndex - startIndex + 1L; if (length > int.MaxValue) { throw new InternalBufferOverflowException(ExceptionMessages.RangeTooBig); } LogEntry entry; ValueTask <TResult> result; if (partitionTable.Count > 0) { using var list = entryPool.Invoke((int)length, true); var listIndex = 0; for (Partition?partition = null; startIndex <= endIndex; list[listIndex++] = entry, startIndex++) { if (startIndex > 0L && TryGetPartition(startIndex, ref partition, out var switched)) { // handle regular record entry = await partition.ReadAsync(session, startIndex, true, switched, token).ConfigureAwait(false); } else if (snapshot.Length > 0 && startIndex <= state.CommitIndex) { // probably the record is snapshotted entry = await snapshot.ReadAsync(session, token).ConfigureAwait(false); // skip squashed log entries startIndex = SquashedIndex; } else { Debug.Assert(startIndex == 0L); // handle ephemeral entity entry = initialEntry; } } return(await reader.ReadAsync <LogEntry, InMemoryList <LogEntry> >(list.Memory.Slice(0, listIndex), list[0].SnapshotIndex, token).ConfigureAwait(false)); } else if (snapshot.Length > 0) { entry = await snapshot.ReadAsync(session, token).ConfigureAwait(false); result = reader.ReadAsync <LogEntry, SingletonEntryList <LogEntry> >(new SingletonEntryList <LogEntry>(entry), entry.SnapshotIndex, token); } else { result = startIndex == 0L ? reader.ReadAsync <LogEntry, SingletonEntryList <LogEntry> >(new SingletonEntryList <LogEntry>(initialEntry), null, token) : reader.ReadAsync <LogEntry, LogEntry[]>(Array.Empty <LogEntry>(), null, token); } return(await result.ConfigureAwait(false)); }
/// <summary> /// Returns resource entry as a stream. /// </summary> /// <param name="culture">An object that represents the culture for which the resource is localized.</param> /// <returns>The stream representing resource entry.</returns> /// <exception cref="InvalidOperationException">The value of the specified resource is not <see cref="Stream"/>.</exception> /// <exception cref="MissingManifestResourceException">No usable set of resources has been found, and there are no resources for the default culture.</exception> /// <exception cref="MissingSatelliteAssemblyException">The default culture's resources reside in a satellite assembly that could not be found.</exception> public Stream AsStream(CultureInfo?culture = null) => Manager.GetStream(Name, culture ?? CultureInfo.CurrentUICulture) ?? throw new InvalidOperationException(ExceptionMessages.ResourceEntryIsNull(Name));
/// <summary> /// Initializes a new exception indicating that requested operator doesn't exist. /// </summary> /// <param name="target">The inspected type.</param> /// <param name="operator">Missing operator.</param> public MissingOperatorException(Type target, ExpressionType @operator) : base(target, ExceptionMessages.MissingOperator(@operator)) { }
public static T ThrowNotFoundException(string paramName, string id) => throw new ArgumentNullException(paramName, ExceptionMessages.NotFound(id));
private IEnumerable <Command> CreateCommandFromElement(XElement element) { Debug.Assert(element.HasAttributes, element.ToString()); switch (element.LocalName()) { case ElementNames.Set: { foreach (XAttribute attribute in element.Attributes()) { yield return(CreateCommandFromAttribute(attribute)); } break; } case ElementNames.Append: { foreach (XAttribute attribute in element.Attributes()) { yield return(new AppendCommand(GetPropertyName(attribute), GetValue(attribute))); } break; } case ElementNames.Prefix: { foreach (XAttribute attribute in element.Attributes()) { yield return(new PrefixCommand(GetPropertyName(attribute), GetValue(attribute))); } break; } case ElementNames.Tag: { XAttribute attribute = element .Attributes() .FirstOrDefault(f => f.LocalName() == AttributeNames.Value); if (attribute != null) { yield return(new AddTagCommand(GetValue(attribute))); } break; } case ElementNames.Add: { foreach (XAttribute attribute in element.Attributes()) { string propertyName = GetAttributeName(attribute); PropertyDefinition property = Entity.FindProperty(propertyName); if (property == null) { Throw(ExceptionMessages.PropertyIsNotDefined(propertyName)); } else if (!property.IsCollection) { Throw(ExceptionMessages.CannotAddItemToNonCollectionProperty(propertyName)); } yield return(new AddItemCommand(propertyName, GetValue(attribute))); } break; } default: { Throw(ExceptionMessages.CommandIsNotDefined(element.LocalName())); break; } } }
/// <summary> /// Initializes a new exception indicating that requested field doesn't exist. /// </summary> /// <param name="declaringType">The inspected type.</param> /// <param name="fieldName">The name of the missing field.</param> /// <param name="fieldType">The type of the missing field.</param> public MissingFieldException(Type declaringType, string fieldName, Type fieldType) : base(declaringType, ExceptionMessages.MissingField(fieldName, fieldType, declaringType)) { FieldType = fieldType; FieldName = fieldName; }
/// <summary> /// Wraps the command to the log entry. /// </summary> /// <param name="command">The payload of the command.</param> /// <param name="term">The term of the local node.</param> /// <typeparam name="TCommand">The type of the command.</typeparam> /// <returns>The instance of the log entry containing the command.</returns> /// <exception cref="GenericArgumentException"><typeparamref name="TCommand"/> type doesn't have registered <see cref="IFormatter{TCommand}"/>.</exception> /// <exception cref="OperationCanceledException">The operation has been canceled.</exception> public LogEntry <TCommand> CreateLogEntry <TCommand>(TCommand command, long term) where TCommand : struct => formatters.TryGetValue(typeof(TCommand), out var formatter) ? new LogEntry <TCommand>(term, command, formatter.GetFormatter <TCommand>(), formatter.Id) : throw new GenericArgumentException <TCommand>(ExceptionMessages.MissingCommandFormatter <TCommand>(), nameof(command));
public void AddExceptionMessage(string message, params string[] args) { ExceptionMessages.Add(String.Format(message, args)); }
public AuthorizationException(ExceptionMessages message) : base(message) { }
internal UsingExpression(Expression resource) { disposeMethod = resource.Type.GetDisposeMethod() ?? throw new ArgumentNullException(ExceptionMessages.DisposePatternExpected(resource.Type)); if (resource is ParameterExpression param) { assignment = null; Resource = param; } else { assignment = Assign(Resource = Variable(resource.Type, "resource"), resource); } }
internal UnknownCommandException(int id) : base(ExceptionMessages.UnknownCommand(id)) { CommandId = id; }
private void ScanDeclarations(IEnumerable <XElement> elements, out ExtendedKeyedCollection <string, PropertyDefinition> properties, out ExtendedKeyedCollection <string, Variable> variables) { properties = null; variables = null; foreach (XElement element in elements) { Current = element; switch (element.Kind()) { case ElementKind.Variable: { if (variables == null) { variables = new ExtendedKeyedCollection <string, Variable>(DefaultComparer.StringComparer); } string variableName = element.AttributeValueOrThrow(AttributeNames.Name); if (variables.Contains(variableName)) { Throw(ExceptionMessages.ItemAlreadyDefined(ElementNames.Variable, variableName)); } var variable = new Variable( variableName, element.AttributeValueOrThrow(AttributeNames.Value)); variables.Add(variable); break; } case ElementKind.Property: { if (properties == null) { properties = new ExtendedKeyedCollection <string, PropertyDefinition>(); } string propertyName = element.AttributeValueOrThrow(AttributeNames.Name); if (properties.Contains(propertyName)) { Throw(ExceptionMessages.ItemAlreadyDefined(ElementNames.Property, propertyName)); } var property = new PropertyDefinition( propertyName, PropertyDefinition.DefaultType, element.AttributeValueOrDefault(AttributeNames.DefaultValue), element.AttributeValueAsBooleanOrDefault(AttributeNames.IsCollection), element); properties.Add(property); break; } default: { ThrowHelper.UnknownElement(element); break; } } Current = null; } }
/// <summary> /// Initializes a new exception indicating that requested constructor doesn't exist. /// </summary> /// <param name="target">The inspected type.</param> /// <param name="parameters">An array of types representing constructor parameters.</param> public MissingConstructorException(Type target, params Type[] parameters) : base(target, ExceptionMessages.MissingCtor(target, parameters)) { Parameters = parameters; }
private readonly PropertyInfo?count; // if null then object supports Slice method with Range parameter /// <summary> /// Initializes a new slice of collection or array. /// </summary> /// <param name="collection">The collection or array.</param> /// <param name="range">The requested range of collection or array. Should of type <see cref="Range"/>.</param> /// <exception cref="ArgumentException"><paramref name="collection"/> doesn't implement <c>Slice</c> method, <c>Length</c> or <c>Count</c> property; or <paramref name="range"/> is not of type <see cref="Range"/>.</exception> public SliceExpression(Expression collection, Expression range) { if (collection is null) { throw new ArgumentNullException(nameof(collection)); } if (range is null) { throw new ArgumentNullException(nameof(range)); } if (range.Type != typeof(Range)) { throw new ArgumentException(ExceptionMessages.TypeExpected <Range>(), nameof(range)); } var resolved = false; if (collection.Type.IsSZArray) { slice = null; count = null; resolved = true; } else if (collection.Type == typeof(string)) { slice = new Func <string, Range, string>(StringExtensions.Substring).Method; count = null; resolved = true; } else { foreach (var slice in GetSliceMethods(collection.Type)) { var parameters = slice.GetParameters(); if (parameters.LongLength == 1L && parameters[0].ParameterType == typeof(Range)) { count = null; this.slice = slice; resolved = true; break; } var intType = typeof(int); if (parameters.LongLength == 2L && parameters[0].ParameterType == intType && parameters[1].ParameterType == intType) { count = CollectionAccessExpression.GetCountProperty(collection.Type) ?? throw new ArgumentException(ExceptionMessages.CollectionExpected(collection.Type), nameof(collection)); this.slice = slice; resolved = true; break; } } } Range = resolved ? range : throw new ArgumentException(ExceptionMessages.CollectionExpected(collection.Type), nameof(collection)); Collection = collection; }
internal UsingExpression(Expression resource, bool configureAwait) { disposeMethod = resource.Type.GetDisposeAsyncMethod() ?? throw new ArgumentException(ExceptionMessages.DisposePatternExpected(resource.Type), nameof(resource)); if (resource is ParameterExpression param) { assignment = null; Resource = param; } else { assignment = Assign(Resource = Variable(resource.Type, "resource"), resource); } this.configureAwait = configureAwait; }
static ExceptionMessages() { Current = new ExceptionMessages(); }
/// <summary> /// Registers command handler. /// </summary> /// <remarks> /// <see cref="CommandAttribute.Formatter"/> is ignored by this method. /// </remarks> /// <param name="handler">The command handler.</param> /// <param name="formatter">Serializer/deserializer of the command type.</param> /// <typeparam name="TCommand">The type of the command supported by the handler.</typeparam> /// <returns>This builder.</returns> /// <exception cref="ArgumentNullException"><paramref name="handler"/> or <paramref name="formatter"/> is <see langword="null"/>.</exception> /// <exception cref="GenericArgumentException">Type <typaparamref name="TCommand"/> is not annotated with <see cref="CommandAttribute"/> attribute.</exception> public Builder Add <TCommand>(Func <TCommand, CancellationToken, ValueTask> handler, IFormatter <TCommand> formatter) where TCommand : struct { if (handler is null) { throw new ArgumentNullException(nameof(handler)); } if (formatter is null) { throw new ArgumentNullException(nameof(formatter)); } var id = typeof(TCommand).GetCustomAttribute <CommandAttribute>()?.Id ?? throw new GenericArgumentException <TCommand>(ExceptionMessages.MissingCommandAttribute <TCommand>()); interpreters.Add(id, new CommandHandler <TCommand>(formatter, handler)); formatters.Add(typeof(TCommand), FormatterInfo.Create(formatter, id)); return(this); }
/// <summary> /// Initializes a new exception indicating that requested event doesn't exist. /// </summary> /// <param name="declaringType">The inspected type.</param> /// <param name="eventName">The name of the event.</param> /// <param name="handlerType">The type of the event handler.</param> public MissingEventException(Type declaringType, string eventName, Type handlerType) : base(declaringType, ExceptionMessages.MissingEvent(eventName, handlerType, declaringType)) { HandlerType = handlerType; EventName = eventName; }
internal RaftClusterMember(IHostingContext context, Uri remoteMember, Uri resourcePath) : base(context.CreateHttpHandler(), true) { this.resourcePath = resourcePath; this.context = context; status = new AtomicEnum <ClusterMemberStatus>(ClusterMemberStatus.Unknown); BaseAddress = remoteMember; Endpoint = remoteMember.ToEndPoint() ?? throw new UriFormatException(ExceptionMessages.UnresolvedHostName(remoteMember.Host)); DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(UserAgent, (GetType().Assembly.GetName().Version ?? new Version()).ToString())); }