public override async Task BindAsync(BindingContext context)
        {
            context.Attributes = _attributes.ToArray();

            if (_binding.DefaultType == typeof(IAsyncCollector<byte[]>))
            {
                await BindAsyncCollectorAsync<byte[]>(context);
            }
            else if (_binding.DefaultType == typeof(IAsyncCollector<JObject>))
            {
                await BindAsyncCollectorAsync<JObject>(context);
            }
            else if (_binding.DefaultType == typeof(IAsyncCollector<string>))
            {
                await BindAsyncCollectorAsync<string>(context);
            }
            else if (_binding.DefaultType == typeof(Stream))
            {
                await BindStreamAsync(context, Access);
            }
            else if (_binding.DefaultType == typeof(JObject))
            {
                await BindJTokenAsync<JObject>(context, Access);
            }
            else if (_binding.DefaultType == typeof(JArray))
            {
                await BindJTokenAsync<JArray>(context, Access);
            }
            else
            {
                throw new NotSupportedException($"ScriptBinding type {_binding.DefaultType} is not supported");
            }
        }
        public override async Task BindAsync(BindingContext context)
        {
            DocumentDBAttribute attribute = new DocumentDBAttribute(DatabaseName, CollectionName)
            {
                CreateIfNotExists = CreateIfNotExists,
                ConnectionString = ConnectionString,
                Id = Id
            };
            RuntimeBindingContext runtimeContext = new RuntimeBindingContext(attribute);

            if (Access == FileAccess.Read && _bindingDirection == BindingDirection.In)
            {
                JObject input = await context.Binder.BindAsync<JObject>(runtimeContext);
                if (input != null)
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(input.ToString());
                    using (MemoryStream stream = new MemoryStream(byteArray))
                    {
                        stream.CopyTo(context.Value);
                    }
                }
            }
            else if (Access == FileAccess.Write && _bindingDirection == BindingDirection.Out)
            {
                await BindAsyncCollectorAsync<JObject>(context.Value, context.Binder, runtimeContext);
            }
        }
        public override async Task BindAsync(BindingContext context)
        {
            EasyTableAttribute attribute = new EasyTableAttribute
            {
                TableName = TableName,
                Id = Id,
                MobileAppUri = MobileAppUri,
                ApiKey = ApiKey
            };

            RuntimeBindingContext runtimeContext = new RuntimeBindingContext(attribute);

            if (Access == FileAccess.Read && _bindingDirection == BindingDirection.In)
            {
                JObject input = await context.Binder.BindAsync<JObject>(runtimeContext);
                if (input != null)
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(input.ToString());
                    using (MemoryStream stream = new MemoryStream(byteArray))
                    {
                        stream.CopyTo(context.Value);
                    }
                }
            }
            else if (Access == FileAccess.Write && _bindingDirection == BindingDirection.Out)
            {
                await BindAsyncCollectorAsync<JObject>(context.Value, context.Binder, runtimeContext);
            }
        }
        protected virtual async Task ProcessInputBindingsAsync(object input, string functionInstanceOutputPath, Binder binder,
            Collection<FunctionBinding> inputBindings, Collection<FunctionBinding> outputBindings,
            Dictionary<string, object> bindingData, Dictionary<string, string> environmentVariables)
        {
            // if there are any input or output bindings declared, set up the temporary
            // output directory
            if (outputBindings.Count > 0 || inputBindings.Any())
            {
                Directory.CreateDirectory(functionInstanceOutputPath);
            }

            // process input bindings
            foreach (var inputBinding in inputBindings)
            {
                string filePath = Path.Combine(functionInstanceOutputPath, inputBinding.Metadata.Name);
                using (FileStream stream = File.OpenWrite(filePath))
                {
                    // If this is the trigger input, write it directly to the stream.
                    // The trigger binding is a special case because it is early bound
                    // rather than late bound as is the case with all the other input
                    // bindings.
                    if (inputBinding.Metadata.IsTrigger)
                    {
                        if (input is string)
                        {
                            using (StreamWriter sw = new StreamWriter(stream))
                            {
                                await sw.WriteAsync((string)input);
                            }
                        }
                        else if (input is byte[])
                        {
                            byte[] bytes = input as byte[];
                            await stream.WriteAsync(bytes, 0, bytes.Length);
                        }
                        else if (input is Stream)
                        {
                            Stream inputStream = input as Stream;
                            await inputStream.CopyToAsync(stream);
                        }
                    }
                    else
                    {
                        // invoke the input binding
                        BindingContext bindingContext = new BindingContext
                        {
                            Binder = binder,
                            BindingData = bindingData,
                            DataType = DataType.Stream,
                            Value = stream
                        };
                        await inputBinding.BindAsync(bindingContext);
                    }
                }

                environmentVariables[inputBinding.Metadata.Name] = Path.Combine(functionInstanceOutputPath,
                    inputBinding.Metadata.Name);
            }
        }
        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);
        }
        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.Value, Access, context.Binder, runtimeContext);
        }
        public override async Task BindAsync(BindingContext context)
        {
            // Only output bindings are supported.
            if (Access == FileAccess.Write && _bindingDirection == BindingDirection.Out)
            {
                NotificationHubAttribute attribute = new NotificationHubAttribute
                {
                    TagExpression = TagExpression,
                    ConnectionString = ConnectionString,
                    HubName = HubName
                };

                RuntimeBindingContext runtimeContext = new RuntimeBindingContext(attribute);
                await BindAsyncCollectorAsync<string>(context.Value, context.Binder, runtimeContext);
            }
        }
Ejemplo n.º 8
0
        public override Task BindAsync(BindingContext context)
        {
            HttpRequestMessage request = (HttpRequestMessage)context.TriggerValue;

            object content = context.Value;
            if (content is Stream)
            {
                // for script language functions (e.g. PowerShell, BAT, etc.) the value
                // will be a Stream which we need to convert to string
                ConvertStreamToValue((Stream)content, DataType.String, ref content);
            }

            HttpResponseMessage response = CreateResponse(request, content);
            request.Properties[ScriptConstants.AzureFunctionsHttpResponseKey] = response;

            return Task.CompletedTask;
        }
        public override async Task BindAsync(BindingContext context)
        {
            HttpRequestMessage request = (HttpRequestMessage)context.Input;

            string content;
            using (StreamReader streamReader = new StreamReader(context.Value))
            {
                content = await streamReader.ReadToEndAsync();
            }

            HttpResponseMessage response = null;
            try
            {
                // attempt to read the content as a JObject
                JObject jsonObject = JObject.Parse(content);

                // TODO: This logic needs to be made more robust
                // E.g. we might decide to use a Regex to determine if
                // the json is a response body or not
                if (jsonObject["status"] != null && jsonObject["body"] != null)
                {
                    HttpStatusCode statusCode = (HttpStatusCode)jsonObject.Value<int>("status");
                    string body = jsonObject.Value<string>("body");

                    response = new HttpResponseMessage(statusCode);
                    response.Content = new StringContent(body);
                }
            }
            catch (JsonException)
            {
                // not a json response
            }

            if (response == null)
            {
                // if unable to parse a json response just send
                // the raw content
                response = new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new StringContent(content)
                };
            }

            request.Properties[HttpResponsePropertyKey] = response;
        }
        public async Task BindAsyncCollectorAsync_JObjectCollection()
        {
            JArray values = new JArray();
            for (int i = 1; i <= 3; i++)
            {
                JObject jsonObject = new JObject
                {
                    { "prop1", "value1" },
                    { "prop2", true },
                    { "prop3", 123 }
                };
                values.Add(jsonObject);
            }

            string json = values.ToString();
            var results = new JArray();
            var collectorMock = new Mock<IAsyncCollector<JObject>>(MockBehavior.Strict);
            collectorMock.Setup(p => p.AddAsync(It.IsAny<JObject>(), CancellationToken.None))
                .Callback<JObject, CancellationToken>((mockObject, mockToken) =>
                {
                    results.Add(mockObject);
                }).Returns(Task.CompletedTask);

            var binderMock = new Mock<Binder>(MockBehavior.Strict);
            var attributes = new Attribute[] { new QueueAttribute("test") };
            binderMock.Setup(p => p.BindAsync<IAsyncCollector<JObject>>(attributes, CancellationToken.None)).ReturnsAsync(collectorMock.Object);

            BindingContext bindingContext = new BindingContext
            {
                Attributes = attributes,
                Binder = binderMock.Object,
                Value = json
            };

            await FunctionBinding.BindAsyncCollectorAsync<JObject>(bindingContext);

            Assert.Equal(3, results.Count);
            for (int i = 0; i < 3; i++)
            {
                JObject jsonObject = (JObject)results[i];
                Assert.Equal("value1", (string)jsonObject["prop1"]);
                Assert.Equal(true, (bool)jsonObject["prop2"]);
                Assert.Equal(123, (int)jsonObject["prop3"]);
            }
        }
        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);
            }
        }
        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);
        }
        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);
            }
        }
        public override async Task BindAsync(BindingContext context)
        {
            string boundQueueName = QueueOrTopicName;
            if (context.BindingData != null)
            {
                boundQueueName = _queueOrTopicNameBindingTemplate.Bind(context.BindingData);
            }

            boundQueueName = Resolve(boundQueueName);

            var attribute = new ServiceBusAttribute(boundQueueName);
            Attribute[] additionalAttributes = null;
            if (!string.IsNullOrEmpty(Metadata.Connection))
            {
                additionalAttributes = new Attribute[]
                {
                    new ServiceBusAccountAttribute(Metadata.Connection)
                };
            }
            RuntimeBindingContext runtimeContext = new RuntimeBindingContext(attribute, additionalAttributes);

            await BindAsyncCollectorAsync<string>(context.Value, context.Binder, runtimeContext);
        }
        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 BlobAttribute(boundBlobPath, Access);
            Attribute[] additionalAttributes = null;
            if (!string.IsNullOrEmpty(Metadata.Connection))
            {
                additionalAttributes = new Attribute[]
                {
                    new StorageAccountAttribute(Metadata.Connection)
                };
            }

            RuntimeBindingContext runtimeContext = new RuntimeBindingContext(attribute, additionalAttributes);
            await BindStreamAsync(context.Value, Access, context.Binder, runtimeContext);
        }
        private static async Task ProcessOutputBindingsAsync(
            Collection<FunctionBinding> outputBindings, object input, IBinder binder, Dictionary<string, string> bindingData, 
            IDictionary<string, object> functionOutputs)
        {
            if (outputBindings == null || functionOutputs == null)
            {
                return;
            }

            foreach (FunctionBinding binding in outputBindings)
            {
                // get the output value from the script
                object value = null;
                if (functionOutputs.TryGetValue(binding.Name, out value))
                {
                    if (value.GetType() == typeof(ExpandoObject))
                    {
                        value = JsonConvert.SerializeObject(value);
                    }

                    byte[] bytes = null;
                    if (value.GetType() == typeof(string))
                    {
                        bytes = Encoding.UTF8.GetBytes((string)value);
                    }

                    using (MemoryStream ms = new MemoryStream(bytes))
                    {
                        BindingContext bindingContext = new BindingContext
                        {
                            Input = input,
                            Binder = binder,
                            BindingData = bindingData,
                            Value = ms
                        };
                        await binding.BindAsync(bindingContext);
                    }
                }
            }
        }
        private async Task ProcessInputBindingsAsync(string functionInstanceOutputPath, IBinder binder, Dictionary<string, string> bindingData, Dictionary<string, string> environmentVariables)
        {
            // if there are any input or output bindings declared, set up the temporary
            // output directory
            var nonTriggerInputBindings = _inputBindings.Where(p => !p.IsTrigger);
            if (_outputBindings.Count > 0 || nonTriggerInputBindings.Any())
            {
                Directory.CreateDirectory(functionInstanceOutputPath);
            }

            // process input bindings
            foreach (var inputBinding in nonTriggerInputBindings)
            {
                string filePath = System.IO.Path.Combine(functionInstanceOutputPath, inputBinding.Name);
                using (FileStream stream = File.OpenWrite(filePath))
                {
                    BindingContext bindingContext = new BindingContext
                    {
                        Binder = binder,
                        BindingData = bindingData,
                        Value = stream
                    };
                    await inputBinding.BindAsync(bindingContext);
                }

                environmentVariables[inputBinding.Name] = Path.Combine(functionInstanceOutputPath, inputBinding.Name);
            }
        }
        private static async Task ProcessOutputBindingsAsync(Collection<FunctionBinding> outputBindings, object input, IBinderEx binder, 
            Dictionary<string, string> bindingData, Dictionary<string, object> scriptExecutionContext, object functionResult)
        {
            if (outputBindings == null)
            {
                return;
            }

            // if the function returned binding values via the function result,
            // apply them to context.bindings
            var bindings = (Dictionary<string, object>)scriptExecutionContext["bindings"];
            IDictionary<string, object> functionOutputs = functionResult as IDictionary<string, object>;
            if (functionOutputs != null)
            {
                foreach (var output in functionOutputs)
                {
                    bindings[output.Key] = output.Value;
                }
            }

            foreach (FunctionBinding binding in outputBindings)
            {
                // get the output value from the script
                // we support primatives (int, string, object) as well as arrays of these
                object value = null;
                if (bindings.TryGetValue(binding.Metadata.Name, out value))
                {
                    // we only support strings, objects, or arrays of those (not primitive types like int)
                    if (value.GetType() == typeof(ExpandoObject) ||
                        value is Array)
                    {
                        value = JsonConvert.SerializeObject(value);
                    }

                    if (!(value is string))
                    {
                        throw new InvalidOperationException(string.Format("Invalid value specified for binding '{0}'", binding.Metadata.Name));
                    }

                    byte[] bytes = Encoding.UTF8.GetBytes((string)value);
                    using (MemoryStream ms = new MemoryStream(bytes))
                    {
                        BindingContext bindingContext = new BindingContext
                        {
                            Input = input,
                            Binder = binder,
                            BindingData = bindingData,
                            Value = ms
                        };
                        await binding.BindAsync(bindingContext);
                    }
                }
            }
        }
        private async Task ProcessInputBindingsAsync(IBinder binder, Dictionary<string, object> executionContext, Dictionary<string, string> bindingData)
        {
            var nonTriggerInputBindings = _inputBindings.Where(p => !p.IsTrigger);
            foreach (var inputBinding in nonTriggerInputBindings)
            {
                string value = null;
                using (MemoryStream stream = new MemoryStream())
                {
                    BindingContext bindingContext = new BindingContext
                    {
                        Binder = binder,
                        BindingData = bindingData,
                        Value = stream
                    };
                    await inputBinding.BindAsync(bindingContext);

                    stream.Seek(0, SeekOrigin.Begin);
                    StreamReader sr = new StreamReader(stream);
                    value = sr.ReadToEnd();
                }

                executionContext[inputBinding.Name] = value;
            }
        }
        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.º 21
0
        internal static async Task BindStringAsync(BindingContext context)
        {
            string str = await context.Binder.BindAsync <string>(context.Attributes);

            context.Value = str;
        }
        protected virtual async Task ProcessOutputBindingsAsync(string functionInstanceOutputPath, Collection<FunctionBinding> outputBindings,
            object input, Binder binder, Dictionary<string, object> bindingData)
        {
            if (outputBindings == null)
            {
                return;
            }

            try
            {
                foreach (var outputBinding in outputBindings)
                {
                    string filePath = System.IO.Path.Combine(functionInstanceOutputPath, outputBinding.Metadata.Name);
                    if (File.Exists(filePath))
                    {
                        using (FileStream stream = File.OpenRead(filePath))
                        {
                            BindingContext bindingContext = new BindingContext
                            {
                                TriggerValue = input,
                                Binder = binder,
                                BindingData = bindingData,
                                Value = stream
                            };
                            await outputBinding.BindAsync(bindingContext);
                        }
                    }
                }
            }
            finally
            {
                // clean up the output directory
                if (outputBindings.Any() && Directory.Exists(functionInstanceOutputPath))
                {
                    Directory.Delete(functionInstanceOutputPath, recursive: true);
                }
            }
        }
        public override async Task BindAsync(BindingContext context)
        {
            HttpRequestMessage request = (HttpRequestMessage)context.Input;

            string content;
            using (StreamReader streamReader = new StreamReader(context.Value))
            {
                content = await streamReader.ReadToEndAsync();
            }

            HttpResponseMessage response = null;
            try
            {
                // attempt to read the content as a JObject
                JObject jsonObject = JObject.Parse(content);

                // TODO: This logic needs to be made more robust
                // E.g. we might decide to use a Regex to determine if
                // the json is a response body or not
                if (jsonObject["body"] != null)
                {
                    HttpStatusCode statusCode = HttpStatusCode.OK;
                    if (jsonObject["status"] != null)
                    {
                        statusCode = (HttpStatusCode)jsonObject.Value<int>("status");
                    }

                    string body = jsonObject["body"].ToString();

                    response = new HttpResponseMessage(statusCode);
                    response.Content = new StringContent(body);

                    // we default the Content-Type here, but we override below with any
                    // Content-Type header the user might have set themselves
                    // TODO: rather than newing up an HttpResponseMessage investigate using
                    // request.CreateResponse, which should allow WebApi Content negotiation to
                    // take place.
                    if (Utility.IsJson(body))
                    {
                        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    }

                    // apply any user specified headers
                    JObject headers = (JObject)jsonObject["headers"];
                    if (headers != null)
                    {
                        foreach (var header in headers)
                        {
                            AddResponseHeader(response, header);
                        }
                    }
                }
            }
            catch (JsonException)
            {
                // not a json response
            }

            if (response == null)
            {
                // if unable to parse a json response just send
                // the raw content
                response = new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new StringContent(content)
                };
            }

            request.Properties[ScriptConstants.AzureFunctionsHttpResponseKey] = response;
        }
        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 abstract Task BindAsync(BindingContext context);
        private async Task ProcessInputBindingsAsync(IBinderEx binder, Dictionary<string, object> executionContext, Dictionary<string, string> bindingData)
        {
            var bindings = (Dictionary<string, object>)executionContext["bindings"];

            // create an ordered array of all inputs and add to
            // the execution context. These will be promoted to
            // positional parameters
            List<object> inputs = new List<object>();
            inputs.Add(bindings[_trigger.Name]);

            var nonTriggerInputBindings = _inputBindings.Where(p => !p.Metadata.IsTrigger);
            foreach (var inputBinding in nonTriggerInputBindings)
            {
                string stringValue = null;
                using (MemoryStream stream = new MemoryStream())
                {
                    BindingContext bindingContext = new BindingContext
                    {
                        Binder = binder,
                        BindingData = bindingData,
                        Value = stream
                    };
                    await inputBinding.BindAsync(bindingContext);

                    stream.Seek(0, SeekOrigin.Begin);
                    StreamReader sr = new StreamReader(stream);
                    stringValue = sr.ReadToEnd();
                }

                // if the input is json, try converting to an object
                object convertedValue = stringValue;
                convertedValue = TryConvertJsonToObject(stringValue);

                bindings.Add(inputBinding.Metadata.Name, convertedValue);
                inputs.Add(convertedValue);
            }

            executionContext["inputs"] = inputs;
        }
        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.º 28
0
 public abstract Task BindAsync(BindingContext context);