示例#1
0
        public void ConvertsFromBooleanString()
        {
            var asTrue  = (bool)_propertyConverter.Convert("True");
            var asFalse = (bool)_propertyConverter.Convert("False");

            Assert.IsTrue(asTrue);
            Assert.IsFalse(asFalse);
        }
        /// <summary>
        /// If supported, convert the provided value into a <see cref="IPropertyToken"/>.
        /// </summary>
        /// <param name="converter">Converter for conversion of additional values.</param>
        /// <param name="value">The value to convert.</param>
        /// <param name="result">Value converted to <see cref="IPropertyToken"/> if conversion was successful.</param>
        /// <returns><c>true</c> if the value could be converted under this policy; <c>false</c> otherwise.</returns>
        public bool TryConvert(IPropertyConverter converter, object value, out IPropertyToken result)
        {
            result = null;

            if (converter == null)
            {
                throw new ArgumentNullException(nameof(converter));
            }

            var enumerable = value as IEnumerable;

            if (enumerable == null)
            {
                return(false);
            }

            // Only dictionaries with 'scalar' keys are permitted, as
            // more complex keys may not serialize to unique values for
            // representation in targets. This check strengthens the expectation
            // that resulting dictionary is representable in JSON as well
            // as richer formats (e.g. XML, .NET type-aware...).
            // Only actual dictionaries are supported, as arbitrary types
            // can implement multiple IDictionary interfaces and thus introduce
            // multiple different interpretations.
            var type = value.GetType();

            if (!type.IsDictionary())
            {
                return(false);
            }

            var typeInfo      = typeof(KeyValuePair <,>).MakeGenericType(type.GenericTypeArguments).GetTypeInfo();
            var keyProperty   = typeInfo.GetDeclaredProperty("Key");
            var valueProperty = typeInfo.GetDeclaredProperty("Value");

            var items = enumerable.Cast <object>();

            if (_config.ItemLimit > 0)
            {
                items = items.Take(_config.ItemLimit);
            }

            var elements = items
                           .Select(kvp =>
                                   new KeyValuePair <ScalarToken, IPropertyToken>(
                                       (ScalarToken)converter.Convert(keyProperty.GetValue(kvp)),
                                       converter.Convert(valueProperty.GetValue(kvp))
                                       )
                                   )
                           .Where(kvp => kvp.Key.Value != null);

            result = new DictionaryToken(elements);
            return(true);
        }
        public Task <TProperty> GetProperty <T>(InitializeContext <T, TInput> context)
            where T : class
        {
            var inputTask = _inputProvider.GetProperty(context);

            if (inputTask.IsCompleted)
            {
                return(context.HasInput
                    ? _converter.Convert(context, inputTask.Result)
                    : TaskUtil.Default <TProperty>());
            }

            return(GetPropertyAsync(context, inputTask));
        }
        private IEnumerable <PropertyToken> GetProperties(object value, IPropertyConverter converter)
        {
            foreach (var property in value.GetType().GetDerivedProperties())
            {
                object propertyValue;

                try
                {
                    propertyValue = property.GetValue(value);
                }
                catch (TargetParameterCountException)
                {
                    // These properties will be ignored since they never produce values they're not
                    // of concern to auditing and exceptions can be suppressed.
                    _logger.Warning(
                        $"The property accessor '{property.DeclaringType.FullName}.{property.Name}' is a non-default indexer");

                    continue;
                }
                catch (TargetInvocationException ex)
                {
                    _logger.Error(ex,
                                  $"The property accessor '{property.DeclaringType.FullName}.{property.Name}' threw an {ex.InnerException.GetType().Name}");

                    propertyValue = $"The property accessor threw an exception: {ex.InnerException.GetType().Name}";
                }

                yield return(new PropertyToken(property.Name, converter.Convert(propertyValue)));
            }
        }
        public void ConvertsFromObjectString()
        {
            var obj       = "object";
            var forObject = _propertyConverter.Convert(obj);

            Assert.AreEqual(forObject, obj);
        }
示例#6
0
 public Task <TProperty> Convert <T>(InitializeContext <T, TInput> context, object propertyValue)
     where T : class
 {
     return(_converter == null
         ? TaskUtil.Default <TProperty>()
         : _converter.Convert(context, (TObject)propertyValue));
 }
        public async Task Apply(InitializeContext <TMessage, TInput> context)
        {
            if (context.HasInput)
            {
                var inputProperty = _inputProperty.Get(context.Input);

                var messageProperty = await _converter.Convert(context, inputProperty).ConfigureAwait(false);

                _messageProperty.Set(context.Message, messageProperty);
            }
        }
        public Task <TProperty> GetProperty <T>(InitializeContext <T, TInput> context)
            where T : class
        {
            if (context.HasInput)
            {
                var propertyValue = _inputProperty.Get(context.Input);

                return(_converter.Convert(context, propertyValue));
            }

            return(Task.FromResult <TProperty>(default));
        public void ConvertsFromDateTimeString()
        {
            var now        = DateTime.Now;
            var dateString = now.ToString();

            var forDateTime = (DateTime)_propertyConverter.Convert(dateString);

            Assert.AreEqual(now.Day, forDateTime.Day);
            Assert.AreEqual(now.Month, forDateTime.Month);
            Assert.AreEqual(now.Year, forDateTime.Year);
            Assert.AreEqual(now.Hour, forDateTime.Hour);
            Assert.AreEqual(now.Minute, forDateTime.Minute);
            Assert.AreEqual(now.Second, forDateTime.Second);
        }
        public Task <TProperty> GetProperty <T>(InitializeContext <T, TInput> context)
            where T : class
        {
            if (!context.HasInput)
            {
                return(TaskUtil.Default <TProperty>());
            }

            var inputTask = _inputProvider.GetProperty(context);

            if (inputTask.IsCompleted)
            {
                return(_converter.Convert(context, inputTask.Result));
            }

            async Task <TProperty> GetPropertyAsync()
            {
                var inputValue = await inputTask.ConfigureAwait(false);

                return(await _converter.Convert(context, inputValue).ConfigureAwait(false));
            }

            return(GetPropertyAsync());
        }
示例#11
0
        internal object GetConvertValue(object value)
        {
            object             result;
            IPropertyConverter propertyConverter = this.PropertyConverter;

            if (propertyConverter != null)
            {
                result = propertyConverter.Convert(value);
            }
            else
            {
                result = value;
            }

            return(result);
        }
        public async Task <IEnumerable <TElement> > GetProperty <T>(InitializeContext <T, TInput> context)
            where T : class
        {
            if (context.HasInput)
            {
                IEnumerable <TInputElement> propertyValue = await _provider.GetProperty(context).ConfigureAwait(false);

                if (propertyValue != null)
                {
                    var results = new List <TElement>();
                    foreach (var element in propertyValue)
                    {
                        var result = await _converter.Convert(context, element).ConfigureAwait(false);

                        results.Add(result);
                    }

                    return(results);
                }
            }

            return(Enumerable.Empty <TElement>());
        }
        public Object ReadProperty(IPropertyConverter converter, string propertyName)
        {
            try
            {
                Int32 indexOfProperty = IniContent.IndexOf(propertyName + " = ");

                if (indexOfProperty == -1)
                {
                    throw new ArgumentException();
                }

                Int32  propertyLength = IniContent.IndexOf(";", indexOfProperty) + 1;
                string propertyString = IniContent.Substring(indexOfProperty, propertyLength - indexOfProperty);
                indexOfProperty = propertyString.IndexOf("= ") + 1;
                string property = propertyString.Substring(indexOfProperty, propertyString.IndexOf(";") - indexOfProperty);
                return(converter.Convert(property));
            }
            catch (ArgumentException ex)
            {
                Debug.Log.AddToFileStreamLog(ex.Message);
                Console.WriteLine(ex.Message);
                throw;
            }
        }
示例#14
0
 public Task <T> Convert <TMessage>(InitializeContext <TMessage> context, TInput?input)
     where TMessage : class
 {
     return(_converter.Convert(context, input ?? default));
 }
        Task <Dictionary <TKey, TElement> > ConvertSync <TMessage>(InitializeContext <TMessage> context,
                                                                   IEnumerable <KeyValuePair <TInputKey, TElement> > input)
            where TMessage : class
        {
            if (input == null)
            {
                return(TaskUtil.Default <Dictionary <TKey, TElement> >());
            }

            var capacity = 0;

            if (input is ICollection <TElement> collection)
            {
                capacity = collection.Count;
                if (capacity == 0)
                {
                    return(Task.FromResult(new Dictionary <TKey, TElement>()));
                }
            }

            var results = new Dictionary <TKey, TElement>(capacity);
            IEnumerator <KeyValuePair <TInputKey, TElement> > enumerator = input.GetEnumerator();
            var disposeEnumerator = true;

            try
            {
                async Task <Dictionary <TKey, TElement> > ConvertAsync(IEnumerator <KeyValuePair <TInputKey, TElement> > asyncEnumerator, Task <TKey> keyTask)
                {
                    try
                    {
                        var key = await keyTask.ConfigureAwait(false);

                        results.Add(key, asyncEnumerator.Current.Value);

                        while (asyncEnumerator.MoveNext())
                        {
                            KeyValuePair <TInputKey, TElement> current = asyncEnumerator.Current;

                            keyTask = _converter.Convert(context, current.Key);
                            if (keyTask.IsCompleted)
                            {
                                results.Add(keyTask.Result, current.Value);
                            }
                            else
                            {
                                key = await keyTask.ConfigureAwait(false);

                                results.Add(key, asyncEnumerator.Current.Value);
                            }
                        }

                        return(results);
                    }
                    finally
                    {
                        asyncEnumerator.Dispose();
                    }
                }

                while (enumerator.MoveNext())
                {
                    KeyValuePair <TInputKey, TElement> current = enumerator.Current;

                    Task <TKey> keyTask = _converter.Convert(context, current.Key);
                    if (keyTask.IsCompleted)
                    {
                        results.Add(keyTask.Result, current.Value);
                    }
                    else
                    {
                        disposeEnumerator = false;
                        return(ConvertAsync(enumerator, keyTask));
                    }
                }
            }
            finally
            {
                if (disposeEnumerator)
                {
                    enumerator.Dispose();
                }
            }

            return(Task.FromResult(results));
        }
示例#16
0
        public void ConvertsFromIntegerString()
        {
            var forInteger = (int)_propertyConverter.Convert("115");

            Assert.AreEqual(forInteger, 115);
        }
        public void ConvertsFromDoubleString()
        {
            var forDouble = (double)_propertyConverter.Convert("1.25");

            Assert.AreEqual(1.25, forDouble);
        }