public static IContentAssert <JToken> HasProperty(this IContentAssert <JToken> content, string jsonPath) { if (content.Value is null) { throw DynamicException.Create("ContentNull", "There is no content."); } return (content.Value.SelectToken(jsonPath) != null ? content : throw DynamicException.Create("ContentPropertyNotFound", $"There is no such property as '{jsonPath}'")); }
protected override Constant <IExpression> InvokeCore() { var expressions = Scope.Context.Get(Namespace, x => x.References); var path = Path.StartsWith("R.", StringComparison.OrdinalIgnoreCase) ? Path : $"R.{Path}"; if (expressions.TryGetValue(path, out var expression)) { return(Path, expression); } else { throw DynamicException.Create("RefNotFound", $"Could not find a reference to '{path}'."); } }
public async Task ExecuteAsync(string commandLineString, CancellationToken cancellationToken) { if (commandLineString.IsNullOrEmpty()) { throw DynamicException.Create( $"CommandStringNullOrEmpty", $"You need to specify at least one command." ); } var commandLines = _commandLineParser.Parse(commandLineString); await ExecuteAsync(commandLines, cancellationToken); }
public static IContentAssert <JValue> Value(this IContentAssert <JToken> content, string jsonPath) { if (content.Value is null) { throw DynamicException.Create("ContentNull", "There is no content."); } return (content.Value.SelectToken(jsonPath) is JValue value ? new ContentAssert <JValue>(value) { Path = jsonPath } : throw DynamicException.Create("ContentPropertyNotFound", $"There is no such property as '{jsonPath}'")); }
// key.Property.Property --> session[key].Property.Property // this.Property.Property --> @this.Property.Property protected object FindItem(Func <string, string> configurePath = default) { var names = Path.Split('.'); var key = names.First(); var obj = key == "this" ? Scope.Context.Get(Namespace, x => x.This) : Scope.Context.TryGetValue(key, out var item) ? item : throw DynamicException.Create("ItemNotFound", $"Could not find an item with the key '{Path}'."); obj = names.Skip(1).Aggregate(obj, (current, name) => current.GetType().GetProperty(name).GetValue(current)); return(obj); }
private async Task <(Stream Content, string MimeType)> InvokeAsync(UriString uri, HttpMethod method, IImmutableSession metadata) { using (var request = new HttpRequestMessage(method, uri)) { var content = metadata.Get(Use <IHttpNamespace> .Namespace, x => x.Content); if (content != null) { request.Content = new StreamContent(content.Rewind()); request.Content.Headers.ContentType = new MediaTypeHeaderValue(metadata.Get(Use <IHttpNamespace> .Namespace, x => x.ContentType)); } Metadata.Get(Use <IHttpNamespace> .Namespace, x => x.ConfigureRequestHeaders, _ => { })(request.Headers); metadata.Get(Use <IHttpNamespace> .Namespace, x => x.ConfigureRequestHeaders)(request.Headers); using (var response = await _client.SendAsync(request, HttpCompletionOption.ResponseContentRead, metadata.Get(Use <IAnyNamespace> .Namespace, x => x.CancellationToken))) { var responseContentCopy = new MemoryStream(); if (response.Content.Headers.ContentLength > 0) { await response.Content.CopyToAsync(responseContentCopy); } var clientErrorClass = new Range <int>(400, 499); var serverErrorClass = new Range <int>(500, 599); var classOfStatusCode = clientErrorClass.ContainsInclusive((int)response.StatusCode) ? "Client" : serverErrorClass.ContainsInclusive((int)response.StatusCode) ? "Server" : null; if (classOfStatusCode is null) { return(responseContentCopy, response.Content.Headers.ContentType.MediaType); } using (var responseReader = new StreamReader(responseContentCopy.Rewind())) { throw DynamicException.Create ( classOfStatusCode, $"StatusCode: {(int)response.StatusCode} ({response.StatusCode}){Environment.NewLine}{await responseReader.ReadToEndAsync()}" ); } } } }
public static async Task <T> Deserialize <T>(Stream value, IImmutableSession metadata) { var format = metadata.Get(Use <IResourceNamespace> .Namespace, x => x.Format); if (format == MimeType.Text) { return((T)(object) await DeserializeTextAsync(value)); } if (format == MimeType.Binary) { return((T) await DeserializeBinaryAsync <object>(value)); } throw DynamicException.Create("Format", $"Unsupported value format: '{format}'."); }
public async Task <(DataTable Data, string Query)> GetDataAsync(string path, IRuntimeFormatter formatter) { Debug.Assert(!(formatter is null)); var connectionString = ConnectionString.FormatWith(formatter); var query = GetQuery(path, formatter); var scope = Logger.BeginScope().AttachElapsed(); try { Logger.Log(Abstraction.Layer.Database().Composite(new { properties = new { connectionString, query } })); using (var conn = new SqlConnection(connectionString)) { conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = query; cmd.CommandType = CommandType.Text; using (var dataReader = await cmd.ExecuteReaderAsync()) { var dataTable = new DataTable(); dataTable.Load(dataReader); EvaluateAttachments(dataTable); Logger.Log(Abstraction.Layer.Database().Meta(new { DataTable = new { RowCount = dataTable.Rows.Count, ColumnCount = dataTable.Columns.Count } })); Logger.Log(Abstraction.Layer.Database().Routine(nameof(GetDataAsync)).Completed()); return(dataTable, query); } } } } catch (Exception ex) { throw DynamicException.Create("DataSource", $"Unable to get data for {Id}.", ex); } finally { scope.Dispose(); } }
public static T ThrowIfInvalid <T>([NotNull] this BouncerPolicyCheckLookup <T> checkLookup) { if (checkLookup == null) { throw new ArgumentNullException(nameof(checkLookup)); } return (checkLookup ? checkLookup : throw DynamicException.Create ( $"{typeof(T).ToPrettyString()}Validation", $"Object does not meet one or more requirements.{Environment.NewLine}{Environment.NewLine}" + $"{checkLookup[false].Select(Func.ToString).Join(Environment.NewLine)}" )); }
private static IEqualityComparer <T> Create() { var equalityProperties = ( from property in typeof(T).GetPropertiesMany(BindingFlags.Public | BindingFlags.Instance) where property.IsDefined(typeof(AutoEqualityPropertyAttribute)) let attribute = property.GetCustomAttribute <AutoEqualityPropertyAttribute>() select(property, attribute) ).ToList(); if (equalityProperties.Empty()) { throw DynamicException.Create("AutoEqualityPropertyNotFound", $"Could not find any '{nameof(AutoEqualityPropertyAttribute)}' on '{typeof(T).ToPrettyString()}'"); } return(Create(equalityProperties)); }
protected override Constant <object> InvokeCore() { using (var e = Body.GetEnumerator()) { if (!e.MoveNext()) { throw DynamicException.Create("EmptyBlockBody", "Block's Body has to contain at least one element."); } var last = e.Current.Invoke(); while (e.MoveNext()) { last = e.Current.Invoke(); } return(last.Name, last.Value); } }
/// <summary> /// Gets the value of a Constant expression if it's of the specified type T or throws an exception. /// </summary> public static T Value <T>(this IConstant constant) { if (typeof(T) == typeof(object)) { return((T)constant.Value); } else { return (constant.Value is T value ? value : throw DynamicException.Create ( "ValueType", $"Expected {typeof(Constant<T>).ToPrettyString()} but found {constant.GetType().ToPrettyString()}." )); } }
public ResponseInfo Next(HttpRequest request) { while (_responses.Any()) { var next = _responses.Peek(); var response = next(request); if (response is null) { _responses.Dequeue(); } else { return(response); } } throw DynamicException.Create("OutOfResponses", "There are not more responses"); }
private static object[] CreateDataItem(MethodInfo testMethod, object item) { var itemProperties = item.GetType().GetProperties().ToDictionary(p => p.Name, p => p, SoftString.Comparer); var testMethodParameters = testMethod.GetParameters(); var dataItem = new object[testMethodParameters.Length]; // We need the index to set the correct item in the result array. foreach (var(testMethodParameter, i) in testMethodParameters.Select((x, i) => (x, i))) { if (itemProperties.TryGetValue(testMethodParameter.Name, out var itemProperty)) { if (testMethodParameter.ParameterType.IsAssignableFrom(itemProperty.PropertyType)) { dataItem[i] = itemProperty.GetValue(item); } else { throw DynamicException.Create ( $"ParameterTypeMismatch", $"Cannot assign value of type '{itemProperty.PropertyType.ToPrettyString()}' " + $"to the parameter '{testMethodParameter.Name}' of type '{testMethodParameter.ParameterType.ToPrettyString()}'." ); } } else { if (testMethodParameter.IsOptional) { dataItem[i] = testMethodParameter.DefaultValue; } else { throw DynamicException.Create ( $"ParameterNotOptional", $"Data item does not specify the required parameter '{testMethodParameter.Name}'." ); } } } return(dataItem); }
public CommandRegistrationBuilder Add <TCommand>(Action <CommandRegistration> customize = default) where TCommand : IConsoleCommand { try { var registration = new CommandRegistration(_parameterConverter, typeof(TCommand), CommandHelper.GetCommandId(typeof(TCommand))); customize?.Invoke(registration); _commands.Add(registration); return(this); } catch (Exception inner) { throw DynamicException.Create ( $"RegisterCommand", $"An error occured while trying to register '{typeof(TCommand).ToPrettyString()}'. See the inner-exception for details.", inner ); } }
public object Deserialize(object value, Type targetType) { if (value == null) { throw new ArgumentNullException(nameof(value)); } try { return (value.GetType() == targetType ? value : DeserializeCore(value, targetType)); } catch (Exception ex) { throw DynamicException.Create(nameof(Deserialize), Format($"Error converting '{value.GetType()}' to '{targetType}'. See the inner exception for details.", TypeFormatProvider.Default), ex); } }
protected override object[] ConvertDataItem(MethodInfo testMethod, object item) { try { return(CreateDataItem(testMethod, item)); } catch (Exception inner) { throw DynamicException.Create ( $"DataItemConversion", $"Could not convert '{item.GetType().ToPrettyString()}' for '{GetTestMethodInfo()}'. See the inner exception for details.", inner ); } // Creates text: MyTest.TestMethod string GetTestMethodInfo() => $"{testMethod.DeclaringType.ToPrettyString()}.{testMethod.Name}"; }
public static async Task <T> GetItemAsync <T>(this IResourceProvider resources, UriString uri, IImmutableSession metadata = default) { using (var item = await resources.GetAsync(uri, metadata)) { var itemFormat = item.Metadata.Get(Use <IResourceNamespace> .Namespace, x => x.Format); if (item.Exists) { using (var memoryStream = new MemoryStream()) { await item.CopyToAsync(memoryStream); if (itemFormat == MimeType.Text) { using (var streamReader = new StreamReader(memoryStream.Rewind())) { return((T)(object)await streamReader.ReadToEndAsync()); } } if (itemFormat == MimeType.Binary) { return((T)await ResourceHelper.DeserializeBinaryAsync <object>(memoryStream.Rewind())); } } throw DynamicException.Create ( $"ItemFormat", $"Item's '{uri}' format is '{itemFormat}' but only '{MimeType.Binary}' and '{MimeType.Text}' are supported." ); } else { throw DynamicException.Create ( $"ItemNotFound", $"Could not find '{uri}' that maps to '{item.Metadata.Get(Use<IResourceNamespace>.Namespace, x => x.ActualName) ?? "N/A"}'." ); } } }
public static Merge Parse(string merge) { // _Global/301?base //var joinTypes = Enum.GetNames(typeof(JoinType)).Join("|"); //var mergeMatch = Regex.Match(merge, $"(?<otherFileName>[_a-z]+)\\/(?<otherId>\\d+)\\?(?<type>{joinTypes})", RegexOptions.IgnoreCase); var mergeMatch = Regex.Match(merge, $"(?<otherFileName>[_a-z0-9-]+)\\/(?<otherId>[_a-z0-9-]+)", RegexOptions.IgnoreCase); if (!mergeMatch.Success) { throw DynamicException.Create($"InvalidMergeExpression", $"{merge.QuoteWith("'")} is not a valid merge expression. Expected: 'Name/Id'."); } return(new Merge ( mergeMatch.Groups["otherFileName"].Value, mergeMatch.Groups["otherId"].Value //(JoinType)Enum.Parse(typeof(JoinType), mergeMatch.Groups["type"].Value, ignoreCase: true) )); }
private IEnumerable <(IConsoleCommand Command, ICommandLine CommandLine)> GetCommands(IEnumerable <ICommandLine> commandLines) { return(commandLines.Select((commandLine, i) => { try { var commandName = commandLine.CommandId(); return (GetCommand(commandName), commandLine); } catch (DynamicException inner) { throw DynamicException.Create ( $"CommandLine", $"Command line at {i} is invalid. See the inner-exception for details.", inner ); } })); }
public static T SingleOrThrow <T>([NotNull] this IEnumerable <T> source, Func <T, bool> predicate, Func <Exception> onEmpty = null, Func <Exception> onMultiple = null) { if (source == null) { throw new ArgumentNullException(nameof(source)); } var result = default(T); var count = 0; using (var enumerator = source.GetEnumerator()) { while (enumerator.MoveNext()) { if (predicate(enumerator.Current)) { if (++count > 1) { throw onMultiple?.Invoke() ?? DynamicException.Create ( $"{source.GetType().ToPrettyString()}ContainsMoreThanOneElement", $"There is more than one element that matches the specified predicate." ); } result = enumerator.Current; } } } if (count == 0) { throw onEmpty?.Invoke() ?? DynamicException.Create ( $"{source.GetType().ToPrettyString()}Empty", $"There is no element that match the specified predicate." ); } return(result); }
// These wrappers are to provide helpful exceptions. public async Task CopyToAsync(Stream stream) { if (!Exists) { throw new InvalidOperationException($"Resource '{Uri}' does not exist."); } try { await CopyToAsyncInternal(stream); } catch (Exception inner) { throw DynamicException.Create ( "Resource", $"An error occured while trying to copy the '{Uri}'. See the inner exception for details.", inner ); } }
protected virtual void RenderParameterList(ICommandLineReader <IHelpParameter> parameter) { var commandId = new Identifier(parameter.GetItem(x => x.Command)); var commandType = _commandTypes.SingleOrDefault(t => CommandHelper.GetCommandId(t) == commandId); if (commandType is null) { throw DynamicException.Create ( $"CommandNotFound", $"Could not find a command with the name '{parameter.GetItem(x => x.Command)}'" ); } // Headers var captions = new[] { "NAME", "ABOUT" }.Pad(ColumnWidths); Logger.WriteLine(p => p.text(string.Join(string.Empty, captions))); // Separators var separators = captions.Select(c => new string('-', c.Trim().Length)).Pad(ColumnWidths); Logger.WriteLine(p => p.text(string.Join(string.Empty, separators))); var bagType = commandType.GetBagType(); var parameters = from commandParameter in bagType.GetParameters() orderby commandParameter.Id.Default.ToString() select commandParameter; foreach (var commandParameter in parameters) { var defaultId = commandParameter.Id.Default.ToString(); var aliases = string.Join("|", commandParameter.Id.Aliases.Select(x => x.ToString())); var description = commandParameter.Description ?? "N/A"; var row = new[] { $"{defaultId} ({(aliases.Length > 0 ? aliases : "-")})", description }.Pad(ColumnWidths); Logger.WriteLine(p => p.text(string.Join(string.Empty, row))); } }
public static IRequestBuilder Occurs(this IRequestBuilder builder, int exactly) { var counter = 0; return(builder.Add(request => { if (request is null) { if (counter != exactly) { throw DynamicException.Create(nameof(Occurs), $"Resource {builder.Uri} was requested {counter} time(s) but expected {exactly}."); } } else { if (++counter > exactly) { throw DynamicException.Create(nameof(Occurs), $"Resource {builder.Uri} was requested {counter} time(s) but expected {exactly}."); } } }, true)); }
public void SetValue(UpdateQuery query) { if (query == null) { throw new ArgumentNullException(nameof(query)); } var providerName = query.ProviderName ?? (_settingProviderNames.TryGetValue(query.SettingName, out var pn) ? pn : throw DynamicException.Create( "MissingSettingProviderName", $"You need to specify a provider for '{query.SettingName}'." ) ); _providers .Single(p => p.Name == providerName) .Write(query); CacheProvider(query.SettingName, providerName); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var keyType = objectType.GetGenericArguments()[0]; var valueType = objectType.GetGenericArguments()[1]; var dictionaryType = typeof(Dictionary <,>).MakeGenericType(keyType, valueType); var modules = (IDictionary)Activator.CreateInstance(dictionaryType); while (reader.Read()) { if (reader.TokenType == JsonToken.PropertyName) { var moduleName = reader.Value.ToString(); if (reader.Read() && reader.TokenType == JsonToken.StartObject) { var moduleToken = JToken.ReadFrom(reader); var module = serializer.Deserialize(moduleToken.CreateReader(), ModuleTypes[moduleName]); modules.Add(moduleName, module); } else { throw DynamicException.Create ( $"DictionaryNotFound", $"Expected a JsonObject but found {reader.TokenType}" ); } } else if (reader.TokenType == JsonToken.EndObject) { // Stop reading the current object. // If we keep going then we break the parsing for the rest of the json. break; } } return(modules); }
public object Serialize(object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } var targetType = _supportedTypes.Contains(value.GetType()) ? value.GetType() : _fallbackType; try { return (value.GetType() == targetType ? value : SerializeCore(value, targetType)); } catch (Exception ex) { throw DynamicException.Create(nameof(Serialize), Format($"Error converting '{value.GetType()}' to '{targetType}'. See the inner exception for details.", TypeFormatProvider.Default), ex); } }
public static Exception InitializationException(Exception inner, [CallerMemberName] string memberName = null) { return(DynamicException.Create(memberName, $"Could not initialize application.", inner)); }
private static IDictionary <int, object> Parse(this string input, string pattern, RegexOptions options) { if (string.IsNullOrEmpty(input)) { throw new ArgumentException($"{nameof(input)} must not be null or empty."); } if (string.IsNullOrEmpty(pattern)) { throw new ArgumentException($"{nameof(pattern)} must not be null or empty."); } var inputMatch = Regex.Match(input, pattern, RegexOptions.ExplicitCapture | options); var result = inputMatch.Success ? inputMatch .Groups .Cast <Group>() .Skip(1) // The first group is the entire match that we don't need. .Where(g => g.Success) .Select( g => { var ordinal = Regex.Match(g.Name, @"^(?:T(?<ordinal>\d+))").Groups["ordinal"]; return ( Ordinal: ordinal.Success && int.TryParse(ordinal.Value, out var x) && x > 0 ? x : throw DynamicException.Create("InvalidTypeIndex", $"Type index '{g.Name}' must begin with the upper-case 'T' and be followed by a 1 based index, e.g. 'T1'."), Value: string.IsNullOrEmpty(g.Value) ? null : g.Value ); } ) .Where(g => g.Value.IsNotNull()) .ToDictionary( g => g.Ordinal, g => (object)g.Value ) : new Dictionary <int, object>(); result[Tupleizer.SuccessKey] = inputMatch.Success; return(result); }
private void Map <TBag>(TBag bag, ICommandLine commandLine, CommandParameter parameter) where TBag : ICommandBag, new() { if (commandLine.TryGetArgumentValues(parameter.Id, parameter.Position, out var values)) { if (parameter.Type.IsEnumerableOfT(except: typeof(string))) { if (!values.Any()) { throw DynamicException.Factory.CreateDynamicException( "EmptyCollection", "Collection parameter and must have at least one value." ); } var value = _converter.Convert(values, parameter.Type); parameter.SetValue(bag, value); } else { if (values.Count > 1) { throw DynamicException.Create( "TooManyValues", "Simple parameter must have exactly one value." ); } if (parameter.Type == typeof(bool)) { if (values.Any()) { var value = _converter.Convert(values.Single(), typeof(bool)); parameter.SetValue(bag, value); } else { if (parameter.DefaultValue is bool defaultValue) { parameter.SetValue(bag, !defaultValue); } else { // Without a DefaultValue assume false but using the parameter negates it so use true. parameter.SetValue(bag, true); } } } else { var value = _converter.Convert(values.Single(), parameter.Type); parameter.SetValue(bag, value); } } } else { if (parameter.IsRequired) { throw DynamicException.Factory.CreateDynamicException( "MissingValue", "Required parameter must specify a value." ); } if (parameter.DefaultValue.IsNotNull()) { var value = parameter.DefaultValue is string ?_converter.Convert(parameter.DefaultValue, parameter.Type) : parameter.DefaultValue; parameter.SetValue(bag, value); } } }