예제 #1
0
 private Exception MethodNotSupportedException(UriString uri, [CallerMemberName] string memberName = null)
 {
     return(DynamicException.Create
            (
                $"{ExtractMethodName(memberName)}NotSupported",
                Because(memberName, uri, "it doesn't support it.")
            ));
 }
예제 #2
0
 private static T SafeCast(object obj)
 {
     return
         (obj is null
             ? default
             : obj is T parameter
                 ? parameter
                 : throw DynamicException.Create("CommandParameterType", $"Could not cast '{obj.GetType().ToPrettyString()}' to '{typeof(T).ToPrettyString()}'."));
 }
예제 #3
0
        private static Type ValidateIsAnonymous(this Type type)
        {
            var isAnonymous = type.Name.StartsWith("<>f__AnonymousType");

            return
                (isAnonymous
                    ? type
                    : throw DynamicException.Create("Snapshot", "Snapshot must be either an anonymous type of a dictionary"));
        }
예제 #4
0
 private Exception WrapException(UriString uri, IImmutableSession metadata, Exception inner, [CallerMemberName] string memberName = null)
 {
     throw DynamicException.Create
           (
               ExtractMethodName(memberName),
               Because(memberName, uri, "of an error. See inner exception for details."),
               inner
           );
 }
예제 #5
0
        private IEnumerable <T> Merge <T>(TestBundle testBundle, IEnumerable <TestBundle> partials, Func <TestBundle, IEnumerable <T> > selectMergeables) where T : class, IMergeable
        {
            var mergeables = selectMergeables(testBundle);

            foreach (var mergeable in mergeables)
            {
                if (mergeable.Merge is null)
                {
                    yield return(mergeable);

                    continue;
                }

                var merge           = mergeable.Merge;
                var otherTestBundle = partials.SingleOrDefault(p => p.Name == merge.OtherFileName) ?? throw DynamicException.Create("OtherTestBundleNotFound", $"Could not find test bundle '{merge.OtherFileName}'.");
                var otherMergeables = selectMergeables(otherTestBundle).SingleOrDefault(x => x.Id == merge.OtherId) ?? throw DynamicException.Create("OtherMergeableNotFound", $"Could not find mergeable '{merge.OtherId}'.");

                var(first, second) = (mergeable, otherMergeables);

                var merged = (IMergeable)_componentContext.Resolve(mergeable.GetType());
                merged.Id    = mergeable.Id;
                merged.Merge = mergeable.Merge;

                var mergeableProperties = merged.GetType().GetProperties().Where(p => p.IsDefined(typeof(MergableAttribute)));

                foreach (var property in mergeableProperties)
                {
                    var firstValue = property.GetValue(first);
                    var newValue   = property.GetValue(second);
                    switch (firstValue)
                    {
                    case IEnumerable <SoftString> x when newValue is IEnumerable <SoftString> y:
                        newValue = x.Union(y).ToList();
                        break;

                    case IEnumerable <KeyValuePair <SoftString, object> > x when newValue is IEnumerable <KeyValuePair <SoftString, object> > y:
                        newValue = x.Union(y).ToDictionary(p => p.Key, p => p.Value);
                        break;
                    }

                    if (property.GetCustomAttribute <MergableAttribute>().Required&& newValue is null)
                    {
                        throw DynamicException.Create(
                                  "MissingValue",
                                  $"You need to specify a value for '{property.Name}' in '{testBundle.FileName}'. Either directly or via a merge."
                                  );
                    }

                    property.SetValue(merged, newValue);
                }

                yield return((T)merged);
            }
        }
예제 #6
0
 private static string GetMemberName(LambdaExpression xItem)
 {
     return
         (xItem.Body is MemberExpression me
             ? me.Member.Name
             : throw DynamicException.Create
          (
              $"NotMemberExpression",
              $"Cannot use expression '{xItem}' because Get/Set expression must be member-expressions."
          ));
 }
예제 #7
0
        public async Task ExecuteAsync <TContext>(string commandLineString, TContext context, CancellationToken cancellationToken)
        {
            if (commandLineString.IsNullOrEmpty())
            {
                throw DynamicException.Create("CommandLineNullOrEmpty", "You need to specify at least one command.");
            }

            var commandLines = _commandLineParser.Parse(commandLineString);

            await ExecuteAsync(commandLines, context, cancellationToken);
        }
예제 #8
0
 private static Type ValidateHasNoGenericArguments(this Type type)
 {
     return
         (type.GenericTypeArguments.Any()
             ? throw DynamicException.Create
          (
              "GenericTypeArguments",
              "You must not specify generic type arguments explicitly. Leave them empty, e.g. 'List<>' or 'Dictionary<,>'"
          )
             : type);
 }
예제 #9
0
 private IConsoleCommand GetCommand(Identifier id)
 {
     return
         (_commands.TryGetValue(id, out var command)
             ? command
             : throw DynamicException.Create
          (
              $"CommandNotFound",
              $"Could not find command '{id.Default.ToString()}'."
          ));
 }
예제 #10
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var emailMetadata = context.ActionArguments.Values.OfType <IEmailMetadata>().SingleOrDefault();

            if (emailMetadata is null)
            {
                throw DynamicException.Create("EmailArgumentNotFound", $"Could not read the email metadata for '{context.HttpContext.Request.Path.Value}'. This might be due to an invalid model.");
            }

            context.HttpContext.Items[EmailMetadata] = emailMetadata;
        }
예제 #11
0
        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}'"));
        }
예제 #12
0
파일: GetItem.cs 프로젝트: he-dev/reusable
        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}'.");
            }
        }
예제 #13
0
        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}'"));
        }
예제 #14
0
파일: GetItem.cs 프로젝트: he-dev/reusable
        // 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);
        }
예제 #15
0
        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()}"
                              );
                    }
                }
            }
        }
예제 #16
0
        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}'.");
        }
예제 #17
0
        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();
            }
        }
예제 #18
0
        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));
        }
        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)}"
                 ));
        }
예제 #20
0
        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");
        }
예제 #21
0
 /// <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()}."
              ));
     }
 }
예제 #22
0
        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);
            }
        }
예제 #23
0
        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);
        }
예제 #24
0
        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);
            }
        }
예제 #25
0
 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
               );
     }
 }
예제 #26
0
        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}";
        }
예제 #27
0
        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"}'."
                          );
                }
            }
        }
예제 #28
0
파일: Merge.cs 프로젝트: he-dev/gunter
        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)
                   ));
        }
예제 #29
0
 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
             );
         }
     }));
 }
예제 #30
0
        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);
        }