Ejemplo n.º 1
0
            public string TemplateBind(PropertyInfo propInfo, Attribute attribute, BindingTemplate template, IReadOnlyDictionary <string, object> bindingData)
            {
                FakeQueueAttribute queueAttribute = (FakeQueueAttribute)attribute;

                if (propInfo.Name == nameof(CustomPolicy))
                {
                    queueAttribute.State1 += "value1";
                }

                if (propInfo.Name == nameof(ConstructorCustomPolicy))
                {
                    queueAttribute.State2 += "value2";
                }

                return(template.Bind(bindingData));
            }
        public override async Task BindAsync(BindingContext context)
        {
            string eventHubName = this.EventHubName;

            if (context.BindingData != null)
            {
                eventHubName = _eventHubNameBindingTemplate.Bind(context.BindingData);
            }

            eventHubName = Resolve(eventHubName);

            var attribute = new ServiceBus.EventHubAttribute(eventHubName);
            RuntimeBindingContext runtimeContext = new RuntimeBindingContext(attribute);

            await BindAsyncCollectorAsync <string>(context.Value, context.Binder, runtimeContext);
        }
        internal static bool IsDisabledBySetting(string settingName, MethodInfo method, INameResolver nameResolver)
        {
            if (nameResolver != null)
            {
                settingName = nameResolver.ResolveWholeString(settingName);
            }

            BindingTemplate             bindingTemplate = BindingTemplate.FromString(settingName);
            Dictionary <string, object> bindingData     = new Dictionary <string, object>();

            bindingData.Add("MethodName", string.Format(CultureInfo.InvariantCulture, "{0}.{1}", method.DeclaringType.Name, method.Name));
            bindingData.Add("MethodShortName", method.Name);
            settingName = bindingTemplate.Bind(bindingData);

            return(ConfigurationUtility.IsSettingEnabled(settingName));
        }
Ejemplo n.º 4
0
        public string GetBoundScopeId(string scopeId, IReadOnlyDictionary <string, object> bindingData = null)
        {
            if (_nameResolver != null)
            {
                scopeId = _nameResolver.ResolveWholeString(scopeId);
            }

            if (bindingData != null)
            {
                BindingTemplate bindingTemplate = BindingTemplate.FromString(scopeId);
                return(bindingTemplate.Bind(bindingData));
            }
            else
            {
                return(scopeId);
            }
        }
        public void DateTimeFormats()
        {
            var dt         = DateTime.UtcNow;
            var parameters = new Dictionary <string, object>
            {
                { "dt", dt }
            };


            var             format   = "YYYYMMdd";
            BindingTemplate template = BindingTemplate.FromString(@"{dt:" + format + "}");

            string expected = dt.ToString(format, CultureInfo.InvariantCulture);
            string result   = template.Bind(parameters);

            Assert.Equal(expected, result);
        }
        public override async Task BindAsync(BindingContext context)
        {
            string boundBlobPath = Path;

            if (context.BindingData != null)
            {
                boundBlobPath = _pathBindingTemplate.Bind(context.BindingData);
            }

            boundBlobPath = Resolve(boundBlobPath);

            var attribute = new ApiHubFileAttribute(Key, boundBlobPath, Access);

            RuntimeBindingContext runtimeContext = new RuntimeBindingContext(attribute);

            await BindStreamAsync(context, Access, runtimeContext);
        }
        public void GuidFormats()
        {
            var g          = Guid.NewGuid();
            var parameters = new Dictionary <string, object>
            {
                { "g", g }
            };

            foreach (var format in new string[] { "N", "D", "B", "P", "X", "" })
            {
                BindingTemplate template = BindingTemplate.FromString(@"{g:" + format + "}");

                string expected = g.ToString(format, CultureInfo.InvariantCulture);
                string result   = template.Bind(parameters);

                Assert.Equal(expected, result);
            }
        }
Ejemplo n.º 8
0
        public string GetBoundScopeId(string scopeId, IReadOnlyDictionary <string, object> bindingData = null)
        {
            if (_nameResolver != null)
            {
                scopeId = _nameResolver.ResolveWholeString(scopeId);
            }

            if (bindingData != null)
            {
                BindingTemplate bindingTemplate = BindingTemplate.FromString(scopeId);
                IReadOnlyDictionary <string, string> parameters = BindingDataPathHelper.ConvertParameters(bindingData);
                return(bindingTemplate.Bind(parameters));
            }
            else
            {
                return(scopeId);
            }
        }
        /// <summary>
        /// Bind the <see cref="BindingTemplate"/> using the specified binding data.
        /// </summary>
        /// <param name="bindingTemplate">The binding template to validate.</param>
        /// <param name="bindingData">The binding data to apply to the template.</param>
        /// <returns>The bound template string.</returns>
        public static string Bind(this BindingTemplate bindingTemplate, IReadOnlyDictionary <string, object> bindingData)
        {
            if (bindingTemplate == null)
            {
                throw new ArgumentNullException("bindingTemplate");
            }

            if (bindingData == null ||
                !bindingTemplate.ParameterNames.Any())
            {
                return(bindingTemplate.Pattern);
            }

            IReadOnlyDictionary <string, string> parameters = BindingDataPathHelper.ConvertParameters(bindingData);
            string path = bindingTemplate.Bind(parameters);

            return(path);
        }
        public override async Task BindAsync(BindingContext context)
        {
            string boundQueueName = QueueOrTopicName;

            if (context.BindingData != null)
            {
                boundQueueName = _queueOrTopicNameBindingTemplate.Bind(context.BindingData);
            }

            boundQueueName = Resolve(boundQueueName);

            // only an output binding is supported
            using (StreamReader reader = new StreamReader(context.Value))
            {
                // TODO: only string supported currently - need to support other types
                IAsyncCollector <string> collector = context.Binder.Bind <IAsyncCollector <string> >(new ServiceBusAttribute(boundQueueName));
                string data = reader.ReadToEnd();
                await collector.AddAsync(data);
            }
        }
Ejemplo n.º 11
0
        public override async Task BindAsync(BindingContext context)
        {
            string boundBlobPath = Path;

            if (context.BindingData != null)
            {
                boundBlobPath = _pathBindingTemplate.Bind(context.BindingData);
            }

            boundBlobPath = Resolve(boundBlobPath);

            Stream blobStream = context.Binder.Bind <Stream>(new BlobAttribute(boundBlobPath, FileAccess));

            if (FileAccess == FileAccess.Write)
            {
                await context.Value.CopyToAsync(blobStream);
            }
            else
            {
                await blobStream.CopyToAsync(context.Value);
            }
        }
Ejemplo n.º 12
0
        public override async Task BindAsync(BindingContext context)
        {
            string boundQueueName = QueueName;

            if (context.BindingData != null)
            {
                boundQueueName = _queueNameBindingTemplate.Bind(context.BindingData);
            }

            boundQueueName = Resolve(boundQueueName);

            // only an output binding is supported
            IAsyncCollector <byte[]> collector = context.Binder.Bind <IAsyncCollector <byte[]> >(new QueueAttribute(boundQueueName));

            byte[] bytes;
            using (MemoryStream ms = new MemoryStream())
            {
                context.Value.CopyTo(ms);
                bytes = ms.ToArray();
            }
            await collector.AddAsync(bytes);
        }
Ejemplo n.º 13
0
        public string TemplateBind(PropertyInfo propInfo, Attribute resolvedAttribute, BindingTemplate bindingTemplate, IReadOnlyDictionary <string, object> bindingData)
        {
            if (bindingTemplate == null)
            {
                throw new ArgumentNullException(nameof(bindingTemplate));
            }

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

            CosmosDBAttribute docDbAttribute = resolvedAttribute as CosmosDBAttribute;

            if (docDbAttribute == null)
            {
                throw new NotSupportedException($"This policy is only supported for {nameof(CosmosDBAttribute)}.");
            }

            // build a SqlParameterCollection for each parameter
            SqlParameterCollection paramCollection = new SqlParameterCollection();

            // also build up a dictionary replacing '{token}' with '@token'
            IDictionary <string, string> replacements = new Dictionary <string, string>();

            foreach (var token in bindingTemplate.ParameterNames.Distinct())
            {
                string sqlToken = $"@{token}";
                paramCollection.Add(new SqlParameter(sqlToken, bindingData[token]));
                replacements.Add(token, sqlToken);
            }

            docDbAttribute.SqlQueryParameters = paramCollection;

            string replacement = bindingTemplate.Bind(new ReadOnlyDictionary <string, string>(replacements));

            return(replacement);
        }
        public string TemplateBind(PropertyInfo propInfo, Attribute resolvedAttribute, BindingTemplate bindingTemplate,
                                   IReadOnlyDictionary <string, object> bindingData)
        {
            if (bindingTemplate == null)
            {
                throw new ArgumentNullException(nameof(bindingTemplate));
            }

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

            var @attribute = resolvedAttribute as MsSqlDbAttribute;

            if (attribute is null)
            {
                throw new NotSupportedException($"This policy is only supported for {nameof(MsSqlDbAttribute)}.");
            }

            var paramCollection = new List <SqlParameter>();

            var replacements = new Dictionary <string, object>();

            foreach (var token in bindingTemplate.ParameterNames.Distinct())
            {
                var sqlToken = $"@{token}";
                paramCollection.Add(new SqlParameter(sqlToken, bindingData[token]));
                replacements.Add(token, sqlToken);
            }

            attribute.SqlQueryParameters = paramCollection.AsEnumerable();

            var replacement = bindingTemplate.Bind(new ReadOnlyDictionary <string, object>(replacements));

            return(replacement);
        }
        public Task <IValueProvider> BindAsync(BindingContext context)
        {
            string boundFileName = _bindingTemplate.Bind(context.BindingData);

            return(this.BindAsync(boundFileName, context.ValueContext));
        }
Ejemplo n.º 16
0
        public override async Task BindAsync(BindingContext context)
        {
            string boundPartitionKey = PartitionKey;
            string boundRowKey       = RowKey;
            string boundFilter       = Filter;

            IReadOnlyDictionary <string, string> bindingData = null;

            if (context.BindingData != null)
            {
                bindingData = context.BindingData.ToStringValues();
            }

            if (context.BindingData != null)
            {
                if (_partitionKeyBindingTemplate != null)
                {
                    boundPartitionKey = _partitionKeyBindingTemplate.Bind(bindingData);
                }

                if (_rowKeyBindingTemplate != null)
                {
                    boundRowKey = _rowKeyBindingTemplate.Bind(bindingData);
                }

                if (_filterBindingTemplate != null)
                {
                    boundFilter = _filterBindingTemplate.Bind(bindingData);
                }
            }

            if (!string.IsNullOrEmpty(boundPartitionKey))
            {
                boundPartitionKey = Resolve(boundPartitionKey);
            }

            if (!string.IsNullOrEmpty(boundRowKey))
            {
                boundRowKey = Resolve(boundRowKey);
            }

            if (!string.IsNullOrEmpty(boundFilter))
            {
                boundFilter = Resolve(boundFilter);
            }

            Collection <Attribute> attributes = new Collection <Attribute>();

            if (!string.IsNullOrEmpty(Metadata.Connection))
            {
                attributes.Add(new StorageAccountAttribute(Metadata.Connection));
            }

            if (Access == FileAccess.Write)
            {
                attributes.Insert(0, new TableAttribute(TableName));
                IAsyncCollector <DynamicTableEntity> collector = await context.Binder.BindAsync <IAsyncCollector <DynamicTableEntity> >(attributes.ToArray());

                ICollection entities = ReadAsCollection(context.Value);

                foreach (JObject entity in entities)
                {
                    // Here we're mapping from JObject to DynamicTableEntity because the Table binding doesn't support
                    // a JObject binding. We enable that for the core Table binding in the future, which would allow
                    // this code to go away.
                    DynamicTableEntity tableEntity = CreateTableEntityFromJObject(boundPartitionKey, boundRowKey, entity);
                    await collector.AddAsync(tableEntity);
                }
            }
            else
            {
                string json = null;
                if (!string.IsNullOrEmpty(boundPartitionKey) &&
                    !string.IsNullOrEmpty(boundRowKey))
                {
                    // singleton
                    attributes.Insert(0, new TableAttribute(TableName, boundPartitionKey, boundRowKey));
                    DynamicTableEntity tableEntity = await context.Binder.BindAsync <DynamicTableEntity>(attributes.ToArray());

                    if (tableEntity != null)
                    {
                        json = ConvertEntityToJObject(tableEntity).ToString();
                    }
                }
                else
                {
                    // binding to multiple table entities
                    attributes.Insert(0, new TableAttribute(TableName));
                    CloudTable table = await context.Binder.BindAsync <CloudTable>(attributes.ToArray());

                    string finalQuery = boundFilter;
                    if (!string.IsNullOrEmpty(boundPartitionKey))
                    {
                        var partitionKeyPredicate = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, boundPartitionKey);
                        if (!string.IsNullOrEmpty(boundFilter))
                        {
                            finalQuery = TableQuery.CombineFilters(boundFilter, TableOperators.And, partitionKeyPredicate);
                        }
                        else
                        {
                            finalQuery = partitionKeyPredicate;
                        }
                    }

                    TableQuery tableQuery = new TableQuery
                    {
                        TakeCount    = Take,
                        FilterString = finalQuery
                    };

                    var    entities    = table.ExecuteQuery(tableQuery);
                    JArray entityArray = new JArray();
                    foreach (var entity in entities)
                    {
                        entityArray.Add(ConvertEntityToJObject(entity));
                    }

                    json = entityArray.ToString(Formatting.None);
                }

                if (json != null)
                {
                    if (context.DataType == DataType.Stream)
                    {
                        // We're explicitly NOT disposing the StreamWriter because
                        // we don't want to close the underlying Stream
                        StreamWriter sw = new StreamWriter((Stream)context.Value);
                        await sw.WriteAsync(json);

                        sw.Flush();
                    }
                    else
                    {
                        context.Value = json;
                    }
                }
            }
        }
Ejemplo n.º 17
0
        public override async Task BindAsync(BindingContext context)
        {
            string boundPartitionKey = PartitionKey;
            string boundRowKey       = RowKey;

            if (context.BindingData != null)
            {
                if (_partitionKeyBindingTemplate != null)
                {
                    boundPartitionKey = _partitionKeyBindingTemplate.Bind(context.BindingData);
                }

                if (_rowKeyBindingTemplate != null)
                {
                    boundRowKey = _rowKeyBindingTemplate.Bind(context.BindingData);
                }
            }

            if (!string.IsNullOrEmpty(boundPartitionKey))
            {
                boundPartitionKey = Resolve(boundPartitionKey);
            }

            if (!string.IsNullOrEmpty(boundRowKey))
            {
                boundRowKey = Resolve(boundRowKey);
            }

            Attribute[] additionalAttributes = null;
            if (!string.IsNullOrEmpty(Metadata.Connection))
            {
                additionalAttributes = new Attribute[]
                {
                    new StorageAccountAttribute(Metadata.Connection)
                };
            }

            if (Access == FileAccess.Write)
            {
                RuntimeBindingContext runtimeContext           = new RuntimeBindingContext(new TableAttribute(TableName), additionalAttributes);
                IAsyncCollector <DynamicTableEntity> collector = await context.Binder.BindAsync <IAsyncCollector <DynamicTableEntity> >(runtimeContext);

                ICollection <JToken> entities = ReadAsCollection(context.Value);

                foreach (JObject entity in entities)
                {
                    // any key values specified on the entity override any values
                    // specified in the binding
                    string keyValue = (string)entity["partitionKey"];
                    if (!string.IsNullOrEmpty(keyValue))
                    {
                        boundPartitionKey = Resolve(keyValue);
                        entity.Remove("partitionKey");
                    }

                    keyValue = (string)entity["rowKey"];
                    if (!string.IsNullOrEmpty(keyValue))
                    {
                        boundRowKey = Resolve(keyValue);
                        entity.Remove("rowKey");
                    }

                    DynamicTableEntity tableEntity = new DynamicTableEntity(boundPartitionKey, boundRowKey);
                    foreach (JProperty property in entity.Properties())
                    {
                        EntityProperty entityProperty = EntityProperty.CreateEntityPropertyFromObject((object)property.Value);
                        tableEntity.Properties.Add(property.Name, entityProperty);
                    }

                    await collector.AddAsync(tableEntity);
                }
            }
            else
            {
                string json = null;

                if (!string.IsNullOrEmpty(boundPartitionKey) &&
                    !string.IsNullOrEmpty(boundRowKey))
                {
                    // singleton
                    RuntimeBindingContext runtimeContext = new RuntimeBindingContext(new TableAttribute(TableName, boundPartitionKey, boundRowKey), additionalAttributes);
                    DynamicTableEntity    tableEntity    = await context.Binder.BindAsync <DynamicTableEntity>(runtimeContext);

                    if (tableEntity != null)
                    {
                        json = ConvertEntityToJObject(tableEntity).ToString();
                    }
                }
                else
                {
                    // binding to entire table (query multiple table entities)
                    RuntimeBindingContext runtimeContext = new RuntimeBindingContext(new TableAttribute(TableName, boundPartitionKey, boundRowKey), additionalAttributes);
                    CloudTable            table          = await context.Binder.BindAsync <CloudTable>(runtimeContext);

                    var entities = table.ExecuteQuery(_tableQuery);

                    JArray entityArray = new JArray();
                    foreach (var entity in entities)
                    {
                        entityArray.Add(ConvertEntityToJObject(entity));
                    }

                    json = entityArray.ToString(Formatting.None);
                }

                if (json != null)
                {
                    // We're explicitly NOT disposing the StreamWriter because
                    // we don't want to close the underlying Stream
                    StreamWriter sw = new StreamWriter(context.Value);
                    await sw.WriteAsync(json);

                    sw.Flush();
                }
            }
        }
Ejemplo n.º 18
0
 public string TemplateBind(PropertyInfo propInfo, Attribute attribute, BindingTemplate template, IReadOnlyDictionary <string, object> bindingData)
 {
     return(template.Bind(bindingData));
 }
Ejemplo n.º 19
0
        public override async Task BindAsync(BindingContext context)
        {
            string boundPartitionKey = PartitionKey;
            string boundRowKey       = RowKey;

            if (context.BindingData != null)
            {
                boundPartitionKey = _partitionKeyBindingTemplate.Bind(context.BindingData);
                if (_rowKeyBindingTemplate != null)
                {
                    boundRowKey = _rowKeyBindingTemplate.Bind(context.BindingData);
                }
            }

            boundPartitionKey = Resolve(boundPartitionKey);
            if (!string.IsNullOrEmpty(boundRowKey))
            {
                boundRowKey = Resolve(boundRowKey);
            }

            if (FileAccess == FileAccess.Write)
            {
                // read the content as a JObject
                JObject jsonObject = null;
                using (StreamReader streamReader = new StreamReader(context.Value))
                {
                    string content = await streamReader.ReadToEndAsync();

                    jsonObject = JObject.Parse(content);
                }

                // TODO: If RowKey has not been specified in the binding, try to
                // derive from the object properties (e.g. "rowKey" or "id" properties);

                IAsyncCollector <DynamicTableEntity> collector = context.Binder.Bind <IAsyncCollector <DynamicTableEntity> >(new TableAttribute(TableName));
                DynamicTableEntity tableEntity = new DynamicTableEntity(boundPartitionKey, boundRowKey);
                foreach (JProperty property in jsonObject.Properties())
                {
                    EntityProperty entityProperty = EntityProperty.CreateEntityPropertyFromObject((object)property.Value);
                    tableEntity.Properties.Add(property.Name, entityProperty);
                }

                await collector.AddAsync(tableEntity);
            }
            else
            {
                if (!string.IsNullOrEmpty(boundPartitionKey) &&
                    !string.IsNullOrEmpty(boundRowKey))
                {
                    // singleton
                    DynamicTableEntity tableEntity = context.Binder.Bind <DynamicTableEntity>(new TableAttribute(TableName, boundPartitionKey, boundRowKey));
                    if (tableEntity != null)
                    {
                        string json = ConvertEntityToJObject(tableEntity).ToString();
                        using (StreamWriter sw = new StreamWriter(context.Value))
                        {
                            await sw.WriteAsync(json);
                        }
                    }
                }
                else
                {
                    // binding to entire table (query multiple table entities)
                    CloudTable table    = context.Binder.Bind <CloudTable>(new TableAttribute(TableName, boundPartitionKey, boundRowKey));
                    var        entities = table.ExecuteQuery(_tableQuery);

                    JArray entityArray = new JArray();
                    foreach (var entity in entities)
                    {
                        entityArray.Add(ConvertEntityToJObject(entity));
                    }

                    string json = entityArray.ToString(Formatting.None);
                    using (StreamWriter sw = new StreamWriter(context.Value))
                    {
                        await sw.WriteAsync(json);
                    }
                }
            }
        }
        public static string Format(BindingTemplate template, IReadOnlyDictionary <string, object> bindingData)
        {
            if (!template.HasParameters)
            {
                return(template.Pattern);
            }

            if (template.ParameterNames.Count() == 1)
            {
                // Special case where the entire filter expression
                // is a single parameter. We let this go through as is
                string parameterName = template.ParameterNames.Single();
                if (template.Pattern == $"{{{parameterName}}}")
                {
                    return(template.Bind(bindingData));
                }
            }

            // each distinct parameter can occur one or more times in the template
            // so group by parameter name
            var parameterGroups = template.ParameterNames.GroupBy(p => p);

            // for each parameter, classify it as a string literal or other
            // and perform value validation
            var convertedBindingData = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            foreach (var kv in bindingData)
            {
                convertedBindingData[kv.Key] = kv.Value;
            }
            foreach (var parameterGroup in parameterGroups)
            {
                // perform any OData specific formatting on the values
                string parameterName = parameterGroup.Key;
                object originalValue;
                if (bindingData.TryGetValue(parameterName, out originalValue))
                {
                    if (originalValue is DateTime)
                    {
                        // OData DateTime literals should be ISO 8601 formatted (e.g. 2009-03-18T04:25:03Z)
                        convertedBindingData[parameterName] = ((DateTime)originalValue).ToUniversalTime().ToString("o");
                    }
                    else if (originalValue is DateTimeOffset)
                    {
                        convertedBindingData[parameterName] = ((DateTimeOffset)originalValue).UtcDateTime.ToString("o");
                    }
                }

                // to classify as a string literal, ALL occurrences in the template
                // must be string literals (e.g. of the form '{p}')
                // note that this will also capture OData expressions of the form
                // datetime'{p}', guid'{p}', X'{p}' which is fine, because single quotes
                // aren't valid for those values anyways.
                bool   isStringLiteral = true;
                string stringParameterFormat = $"'{{{parameterName}}}'";
                int    count = 0, idx = 0;
                while (idx >= 0 && idx < template.Pattern.Length && count++ < parameterGroup.Count())
                {
                    idx = template.Pattern.IndexOf(stringParameterFormat, idx, StringComparison.OrdinalIgnoreCase);
                    if (idx < 0)
                    {
                        isStringLiteral = false;
                        break;
                    }
                    idx++;
                }

                // validate and format the value based on its classification
                object objValue = null;
                if (convertedBindingData.TryGetValue(parameterName, out objValue))
                {
                    string value = BindingDataPathHelper.ConvertParameterValueToString(objValue);
                    if (isStringLiteral)
                    {
                        convertedBindingData[parameterName] = value.Replace("'", "''");
                    }
                    else if (!TryValidateNonStringLiteral(value))
                    {
                        throw new InvalidOperationException($"An invalid parameter value was specified for filter parameter '{parameterName}'.");
                    }
                }
            }

            return(template.Bind(convertedBindingData));
        }