public Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // Determine whether we should bind to the current parameter
            ParameterInfo parameter = context.Parameter;
            SampleAttribute attribute = parameter.GetCustomAttribute<SampleAttribute>(inherit: false);
            if (attribute == null)
            {
                return Task.FromResult<IBinding>(null);
            }

            // TODO: Include any other parameter types this binding supports in this check
            IEnumerable<Type> supportedTypes = StreamValueBinder.GetSupportedTypes(FileAccess.ReadWrite);
            if (!ValueBinder.MatchParameterType(context.Parameter, supportedTypes))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, 
                    "Can't bind SampleAttribute to type '{0}'.", parameter.ParameterType));
            }

            return Task.FromResult<IBinding>(new SampleBinding(parameter));
        }
        public Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ParameterInfo parameter = context.Parameter;
            ServiceBusAttribute attribute = parameter.GetCustomAttribute<ServiceBusAttribute>(inherit: false);

            if (attribute == null)
            {
                return Task.FromResult<IBinding>(null);
            }

            string queueOrTopicName = Resolve(attribute.QueueOrTopicName);
            IBindableServiceBusPath path = BindableServiceBusPath.Create(queueOrTopicName);
            ValidateContractCompatibility(path, context.BindingDataContract);

            IArgumentBinding<ServiceBusEntity> argumentBinding = InnerProvider.TryCreate(parameter);

            if (argumentBinding == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Can't bind ServiceBus to type '{0}'.", parameter.ParameterType));
            }

            ServiceBusAccount account = ServiceBusAccount.CreateFromConnectionString(_config.ConnectionString);

            IBinding binding = new ServiceBusBinding(parameter.Name, argumentBinding, account, path, attribute.Access);
            return Task.FromResult(binding);
        }
        public void CreateDefaultMessage_CreatesExpectedMessage(SlackAttribute attribute, SlackConfiguration config, Dictionary<string, object> bindingData, INameResolver nameResolver,SlackMessage targetMessage, String targetUrl)
        {
            ParameterInfo parameter = GetType().GetMethod("TestMethod", BindingFlags.Static | BindingFlags.NonPublic).GetParameters().First();
            Dictionary<string, Type> contract = new Dictionary<string, Type>
            {
                {"ChannelParam", typeof(string) },
                {"IconParam", typeof(string) },
                {"TextParam", typeof(string) },
                {"UsernameParam", typeof(string) },
                {"WebHookUrlParam", typeof(string) }
            };

            BindingProviderContext context = new BindingProviderContext(parameter, contract, CancellationToken.None);
            SlackBinding binding = new SlackBinding(parameter, attribute, config, nameResolver, context);
            
            // Generate message with input data
            SlackMessage message = binding.CreateDefaultMessage(bindingData);

            // Check that the right values were used to initialize the funtion
            Assert.Equal(targetMessage.Channel, message.Channel);
            Assert.Equal(targetMessage.IconEmoji, message.IconEmoji);
            Assert.Equal(targetMessage.Text, message.Text);
            Assert.Equal(targetMessage.Username, message.Username);
            Assert.Equal(targetMessage.Mrkdwn, message.Mrkdwn);
            Assert.Equal(targetUrl, binding._client.BaseUrl);
        }
            public SendGridBinding(ParameterInfo parameter, SendGridAttribute attribute, SendGridConfiguration config, BindingProviderContext context)
            {
                _parameter = parameter;
                _attribute = attribute;
                _config = config;

                _sendGrid = new Web(_config.ApiKey);

                if (!string.IsNullOrEmpty(_attribute.To))
                {
                    _toFieldBinding = new BindablePath(_attribute.To);
                    _toFieldBinding.ValidateContractCompatibility(context.BindingDataContract);
                }

                if (!string.IsNullOrEmpty(_attribute.Subject))
                {
                    _subjectFieldBinding = new BindablePath(_attribute.Subject);
                    _subjectFieldBinding.ValidateContractCompatibility(context.BindingDataContract);
                }

                if (!string.IsNullOrEmpty(_attribute.Text))
                {
                    _textFieldBinding = new BindablePath(_attribute.Text);
                    _textFieldBinding.ValidateContractCompatibility(context.BindingDataContract);
                }
            }
        public Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ParameterInfo parameter = context.Parameter;
            EventHubAttribute attribute = parameter.GetCustomAttribute<EventHubAttribute>(inherit: false);

            if (attribute == null)
            {
                return Task.FromResult<IBinding>(null);
            }

            string name = attribute.EventHubName;
            var resolvedName = _nameResolver.ResolveWholeString(name);

            Func<string, EventHubClient> invokeStringBinder = (invokeString) => _eventHubConfig.GetEventHubClient(invokeString);

            IBinding binding = BindingFactory.BindCollector<EventData, EventHubClient>(
                parameter,
                _converterManager,
                (client, valueBindingContext) => new EventHubAsyncCollector(client),
                resolvedName,
                invokeStringBinder);

            return Task.FromResult(binding);
        }
        public SlackBinding(ParameterInfo parameter, SlackAttribute attribute, SlackConfiguration config, INameResolver nameResolver, BindingProviderContext context)
        {
            _parameter = parameter;
            _attribute = attribute;
            _config = config;
            _nameResolver = nameResolver;
            
            if(!string.IsNullOrEmpty(_attribute.WebHookUrl))
            {
                _webHookUrlBindingTemplate = CreateBindingTemplate(_attribute.WebHookUrl, context.BindingDataContract);
            }

            if (!string.IsNullOrEmpty(_attribute.Text))
            {
                _textBindingTemplate = CreateBindingTemplate(_attribute.Text, context.BindingDataContract);
            }

            if (!string.IsNullOrEmpty(_attribute.Username))
            {
                _usernameBindingTemplate = CreateBindingTemplate(_attribute.Username, context.BindingDataContract);
            }

            if (!string.IsNullOrEmpty(_attribute.IconEmoji))
            {
                _iconEmojiBindingTemplate = CreateBindingTemplate(_attribute.IconEmoji, context.BindingDataContract);
            }

            if (!string.IsNullOrEmpty(_attribute.Channel))
            {
                _channelBindingTemplate = CreateBindingTemplate(_attribute.Channel, context.BindingDataContract);
            }
        }
        /// <inheritdoc/>
        public Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // Determine whether we should bind to the current parameter
            ParameterInfo parameter = context.Parameter;
            FileAttribute attribute = parameter.GetCustomAttribute<FileAttribute>(inherit: false);
            if (attribute == null)
            {
                return Task.FromResult<IBinding>(null);
            }

            // first, verify the file path binding (if it contains binding parameters)
            string path = attribute.Path;
            if (_nameResolver != null)
            {
                path = _nameResolver.ResolveWholeString(path);
            }
            BindingTemplate bindingTemplate = BindingTemplate.FromString(path);
            bindingTemplate.ValidateContractCompatibility(context.BindingDataContract);

            IEnumerable<Type> types = StreamValueBinder.GetSupportedTypes(attribute.Access)
                .Union(new Type[] { typeof(FileStream), typeof(FileInfo) });
            if (!ValueBinder.MatchParameterType(context.Parameter, types))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, 
                    "Can't bind FileAttribute to type '{0}'.", parameter.ParameterType));
            }

            return Task.FromResult<IBinding>(new FileBinding(_config, parameter, bindingTemplate));
        }
        public void Binding_UsesNameResolver()
        {
            ParameterInfo parameter = GetType().GetMethod("TestMethod", BindingFlags.Static | BindingFlags.NonPublic).GetParameters().First();
            SendGridAttribute attribute = new SendGridAttribute
            {
                To = "%param1%",
                From = "%param2%",
                Subject = "%param3%",
                Text = "%param4%"
            };
            SendGridConfiguration config = new SendGridConfiguration
            {
                ApiKey = "12345"
            };

            Dictionary<string, Type> contract = new Dictionary<string, Type>();
            BindingProviderContext context = new BindingProviderContext(parameter, contract, CancellationToken.None);

            var nameResolver = new TestNameResolver();
            nameResolver.Values.Add("param1", "*****@*****.**");
            nameResolver.Values.Add("param2", "*****@*****.**");
            nameResolver.Values.Add("param3", "Value3");
            nameResolver.Values.Add("param4", "Value4");

            SendGridBinding binding = new SendGridBinding(parameter, attribute, config, nameResolver, context);
            Dictionary<string, object> bindingData = new Dictionary<string, object>();
            SendGridMessage message = binding.CreateDefaultMessage(bindingData);

            Assert.Equal("*****@*****.**", message.To.Single().Address);
            Assert.Equal("*****@*****.**", message.From.Address);
            Assert.Equal("Value3", message.Subject);
            Assert.Equal("Value4", message.Text);
        }
        public Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ParameterInfo parameter = context.Parameter;
            SlackAttribute attribute = parameter.GetCustomAttribute<SlackAttribute>(inherit: false);
            if(attribute == null)
            {
                return Task.FromResult<IBinding>(null);
            }

            if(context.Parameter.ParameterType != typeof(SlackMessage) && 
                context.Parameter.ParameterType != typeof(SlackMessage).MakeByRefType())
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Can't bind SlackAttribute to type '{0}'.", parameter.ParameterType));
            }

            if(string.IsNullOrEmpty(_config.WebHookUrl))
            {
                throw new InvalidOperationException(
                    string.Format("You must specify a Slack WebHook URL via a '{0}' app setting, via a '{0}' environment variable, or directly in code via SlackConfiguration.WebHookUrl",
                    SlackConfiguration.AzureWebJobsSlackWebHookKeyName));
            }

            return Task.FromResult<IBinding>(new SlackBinding(parameter, attribute, _config, _nameResolver, context));
        }
        public async Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            ParameterInfo parameter = context.Parameter;
            QueueAttribute queueAttribute = parameter.GetCustomAttribute<QueueAttribute>(inherit: false);

            if (queueAttribute == null)
            {
                return null;
            }

            string queueName = Resolve(queueAttribute.QueueName);
            IBindableQueuePath path = BindableQueuePath.Create(queueName);
            path.ValidateContractCompatibility(context.BindingDataContract);

            IArgumentBinding<IStorageQueue> argumentBinding = _innerProvider.TryCreate(parameter);
            if (argumentBinding == null)
            {
                throw new InvalidOperationException("Can't bind Queue to type '" + parameter.ParameterType + "'.");
            }

            IStorageAccount account = await _accountProvider.GetStorageAccountAsync(context.Parameter, context.CancellationToken);
            StorageClientFactoryContext clientFactoryContext = new StorageClientFactoryContext
            {
                Parameter = parameter
            };
            IStorageQueueClient client = account.CreateQueueClient(clientFactoryContext);
            IBinding binding = new QueueBinding(parameter.Name, argumentBinding, client, path);
            return binding;
        }
        public Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ParameterInfo parameter = context.Parameter;
            RedisAttribute attribute = parameter.GetCustomAttribute<RedisAttribute>(inherit: false);

            if (attribute == null)
            {
                return Task.FromResult<IBinding>(null);
            }

            IArgumentBinding<RedisEntity> argumentBinding = Provider.TryCreate(parameter);

            if (argumentBinding == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
                    "Can't bind to type '{0}'.", parameter.ParameterType));
            }

            var account = RedisAccount.CreateDbFromConnectionString(_config.ConnectionString);

            IBinding binding = new RedisBinding(parameter.Name, argumentBinding, account, attribute, context, _trace);

            return Task.FromResult(binding);
        }
        public SendGridBinding(ParameterInfo parameter, SendGridAttribute attribute, SendGridConfiguration config, INameResolver nameResolver, BindingProviderContext context)
        {
            _parameter = parameter;
            _attribute = attribute;
            _config = config;
            _nameResolver = nameResolver;

            _sendGrid = new Web(_config.ApiKey);

            if (!string.IsNullOrEmpty(_attribute.To))
            {
                _toFieldBindingTemplate = CreateBindingTemplate(_attribute.To, context.BindingDataContract);
            }

            if (!string.IsNullOrEmpty(_attribute.From))
            {
                _fromFieldBindingTemplate = CreateBindingTemplate(_attribute.From, context.BindingDataContract);
            }

            if (!string.IsNullOrEmpty(_attribute.Subject))
            {
                _subjectFieldBindingTemplate = CreateBindingTemplate(_attribute.Subject, context.BindingDataContract);
            }

            if (!string.IsNullOrEmpty(_attribute.Text))
            {
                _textFieldBindingTemplate = CreateBindingTemplate(_attribute.Text, context.BindingDataContract);
            }
        }
        public Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ParameterInfo parameter = context.Parameter;
            SendGridAttribute attribute = parameter.GetCustomAttribute<SendGridAttribute>(inherit: false);
            if (attribute == null)
            {
                return Task.FromResult<IBinding>(null);
            }

            if (context.Parameter.ParameterType != typeof(SendGrid.SendGridMessage))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, 
                    "Can't bind SendGridAttribute to type '{0}'.", parameter.ParameterType));
            }

            if (string.IsNullOrEmpty(_config.ApiKey))
            {
                throw new InvalidOperationException(
                    string.Format("The SendGrid ApiKey must be set either via a '{0}' app setting, via a '{0}' environment variable, or directly in code via SendGridConfiguration.ApiKey.", 
                    SendGridConfiguration.AzureWebJobsSendGridApiKeyName));
            }

            return Task.FromResult<IBinding>(new SendGridBinding(parameter, attribute, _config, context));
        }
        public async Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ParameterInfo parameter = context.Parameter;
            ServiceBusAttribute attribute = parameter.GetCustomAttribute<ServiceBusAttribute>(inherit: false);

            if (attribute == null)
            {
                return null;
            }

            string queueOrTopicName = Resolve(attribute.QueueOrTopicName);
            IBindableServiceBusPath path = BindableServiceBusPath.Create(queueOrTopicName);
            ValidateContractCompatibility(path, context.BindingDataContract);

            IArgumentBinding<ServiceBusEntity> argumentBinding = InnerProvider.TryCreate(parameter);
            if (argumentBinding == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Can't bind ServiceBus to type '{0}'.", parameter.ParameterType));
            }

            string connectionName = ServiceBusAccount.GetAccountOverrideOrNull(context.Parameter);
            ServiceBusAccount account = new ServiceBusAccount
            {
                MessagingFactory = await _config.MessagingProvider.CreateMessagingFactoryAsync(queueOrTopicName, connectionName),
                NamespaceManager = _config.MessagingProvider.CreateNamespaceManager(connectionName)
            };

            IBinding binding = new ServiceBusBinding(parameter.Name, argumentBinding, account, path, attribute.Access);
            return binding;
        }
        public async Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            ParameterInfo parameter = context.Parameter;
            TableAttribute tableAttribute = parameter.GetCustomAttribute<TableAttribute>(inherit: false);

            if (tableAttribute == null)
            {
                return null;
            }

            string tableName = Resolve(tableAttribute.TableName);
            IStorageAccount account = await _accountProvider.GetStorageAccountAsync(context.Parameter, context.CancellationToken);
            StorageClientFactoryContext clientFactoryContext = new StorageClientFactoryContext
            {
                Parameter = context.Parameter
            };
            IStorageTableClient client = account.CreateTableClient(clientFactoryContext);

            bool bindsToEntireTable = tableAttribute.RowKey == null;
            IBinding binding;

            if (bindsToEntireTable)
            {
                IBindableTablePath path = BindableTablePath.Create(tableName);
                path.ValidateContractCompatibility(context.BindingDataContract);

                IStorageTableArgumentBinding argumentBinding = _tableBindingProvider.TryCreate(parameter);

                if (argumentBinding == null)
                {
                    throw new InvalidOperationException("Can't bind Table to type '" + parameter.ParameterType + "'.");
                }

                binding = new TableBinding(parameter.Name, argumentBinding, client, path);
            }
            else
            {
                string partitionKey = Resolve(tableAttribute.PartitionKey);
                string rowKey = Resolve(tableAttribute.RowKey);
                IBindableTableEntityPath path = BindableTableEntityPath.Create(tableName, partitionKey, rowKey);
                path.ValidateContractCompatibility(context.BindingDataContract);

                IArgumentBinding<TableEntityContext> argumentBinding = _entityBindingProvider.TryCreate(parameter);

                if (argumentBinding == null)
                {
                    throw new InvalidOperationException("Can't bind Table entity to type '" + parameter.ParameterType + "'.");
                }

                binding = new TableEntityBinding(parameter.Name, argumentBinding, client, path);
            }

            return binding;
        }
 private static BindingProviderContext CreateBindingContext(string parameterName, Type parameterType)
 {
     ParameterInfo parameter = new StubParameterInfo(parameterName, parameterType);
     Dictionary<string, Type> bindingDataContract = new Dictionary<string, Type>
     {
         { parameterName, parameterType }
     };
     BindingProviderContext context = new BindingProviderContext(parameter, bindingDataContract,
         CancellationToken.None);
     return context;
 }
        public async Task TryCreateAsync_DefaultAccount()
        {
            _mockMessagingProvider.Setup(p => p.CreateNamespaceManager(null)).Returns<NamespaceManager>(null);
            _mockMessagingProvider.Setup(p => p.CreateMessagingFactoryAsync("test", null)).ReturnsAsync(null);

            ParameterInfo parameter = GetType().GetMethod("TestJob").GetParameters()[0];
            BindingProviderContext context = new BindingProviderContext(parameter, new Dictionary<string, Type>(), CancellationToken.None);

            IBinding binding = await _provider.TryCreateAsync(context);

            _mockMessagingProvider.VerifyAll();
        }
        public RedisBinding(string parameterName, IArgumentBinding<RedisEntity> argumentBinding,
            RedisAccount account, RedisAttribute attribute, BindingProviderContext context, TraceWriter trace)
        {
            _parameterName = parameterName;
            _argumentBinding = argumentBinding;
            _account = account;
            _attribute = attribute;
            _mode = attribute.Mode;

            _channelOrKeyPath = BindingTemplate.FromString(attribute.ChannelOrKey);
            _trace = trace;
        }
        public async Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            foreach (IBindingProvider provider in _providers)
            {
                IBinding binding = await provider.TryCreateAsync(context);
                if (binding != null)
                {
                    return binding;
                }
            }

            return null;
        }
        public Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (context.Parameter.ParameterType != typeof(ExecutionContext))
            {
                return Task.FromResult<IBinding>(null);
            }

            return Task.FromResult<IBinding>(new ExecutionContextBinding(context.Parameter));
        }
        public Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));
            var parameter = context.Parameter;
            var attribute = parameter.GetCustomAttributes(typeof(FtpAttribute), inherit: false);
            if (attribute == null || attribute.Length == 0)
                return Task.FromResult<IBinding>(null);

            // TODO: Include any other parameter types this binding supports in this check
            var supportedTypes = new List<Type> { typeof(FtpMessage) };
            if (!ValueBinder.MatchParameterType(context.Parameter, supportedTypes))
                throw new InvalidOperationException($"Can't bind {nameof(FtpAttribute)} to type '{parameter.ParameterType}'.");

            return Task.FromResult<IBinding>(new FtpBinding(_config, parameter, _trace, (FtpAttribute)attribute[0]));
        }
        private static bool CanBind(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // first, verify the file path binding (if it contains binding parameters)
            ParameterInfo parameter = context.Parameter;
            FileAttribute attribute = parameter.GetCustomAttribute<FileAttribute>(inherit: false);
            BindablePath path = new BindablePath(attribute.Path);
            path.ValidateContractCompatibility(context.BindingDataContract);

            // next, verify that the type is one of the types we support
            IEnumerable<Type> types = StreamValueBinder.SupportedTypes.Union(new Type[] { typeof(FileStream) });
            return ValueBinder.MatchParameterType(parameter, types);
        }
        public Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ParameterInfo parameter = context.Parameter;
            if (parameter.ParameterType != typeof(TraceWriter) &&
                parameter.ParameterType != typeof(TextWriter))
            {
                return Task.FromResult<IBinding>(null);
            }

            IBinding binding = new TraceWriterBinding(parameter);
            return Task.FromResult(binding);
        }
        public void CreateDefaultMessage_CreatesExpectedMessage()
        {
            ParameterInfo parameter = GetType().GetMethod("TestMethod", BindingFlags.Static | BindingFlags.NonPublic).GetParameters().First();
            SendGridAttribute attribute = new SendGridAttribute
            {
                To = "{Param1}",
                Subject = "Test {Param2}",
                Text = "Test {Param3}"
            };
            SendGridConfiguration config = new SendGridConfiguration
            {
                ApiKey = "12345",
                FromAddress = new MailAddress("*****@*****.**", "Test2"),
                ToAddress = "*****@*****.**"
            };
            Dictionary<string, Type> contract = new Dictionary<string, Type>();
            contract.Add("Param1", typeof(string));
            contract.Add("Param2", typeof(string));
            contract.Add("Param3", typeof(string));
            BindingProviderContext context = new BindingProviderContext(parameter, contract, CancellationToken.None);

            var nameResolver = new TestNameResolver();
            SendGridBinding binding = new SendGridBinding(parameter, attribute, config, nameResolver, context);
            Dictionary<string, object> bindingData = new Dictionary<string, object>();
            bindingData.Add("Param1", "*****@*****.**");
            bindingData.Add("Param2", "Value2");
            bindingData.Add("Param3", "Value3");
            SendGridMessage message = binding.CreateDefaultMessage(bindingData);

            Assert.Same(config.FromAddress, message.From);
            Assert.Equal("*****@*****.**", message.To.Single().Address);
            Assert.Equal("Test Value2", message.Subject);
            Assert.Equal("Test Value3", message.Text);

            // If no To value specified, verify it is defaulted from config
            attribute = new SendGridAttribute
            {
                Subject = "Test {Param2}",
                Text = "Test {Param3}"
            };
            binding = new SendGridBinding(parameter, attribute, config, nameResolver, context);
            message = binding.CreateDefaultMessage(bindingData);
            Assert.Equal("*****@*****.**", message.To.Single().Address);
        }
Ejemplo n.º 25
0
        public Task <IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var parameter = context.Parameter;
            var typeUser  = parameter.ParameterType;

            if (typeUser.IsByRef)
            {
                return(Task.FromResult <IBinding>(null));
            }

            var type    = typeof(ExactBinding <>).MakeGenericType(typeof(TAttribute), typeof(TType), typeUser);
            var method  = type.GetMethod("TryBuild", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
            var binding = BindingFactoryHelpers.MethodInvoke <IBinding>(method, this, context);

            return(Task.FromResult <IBinding>(binding));
        }
Ejemplo n.º 26
0
        public Task <IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ParameterInfo parameter       = context.Parameter;
            TAttribute    attributeSource = parameter.GetCustomAttribute <TAttribute>(inherit: false);

            if (attributeSource == null)
            {
                return(Task.FromResult <IBinding>(null));
            }

            var cloner = new AttributeCloner <TAttribute>(attributeSource, context.BindingDataContract, _nameResolver);

            IBinding binding = new Binding(cloner, parameter, _builder);

            return(Task.FromResult(binding));
        }
        public Task <IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            Type parametertype = context.Parameter.ParameterType;

            var attr = context.Parameter.GetCustomAttribute <TAttribute>();

            var cloner           = new AttributeCloner <TAttribute>(attr, context.BindingDataContract, _nameResolver);
            var attrNameResolved = cloner.GetNameResolvedAttribute();

            // This may do validation and throw too.
            bool canBind = _predicate(attrNameResolved, parametertype);

            if (!canBind)
            {
                return(Task.FromResult <IBinding>(null));
            }
            return(_inner.TryCreateAsync(context));
        }
Ejemplo n.º 28
0
        public async Task <IBinding> TryCreateAsync(BindingProviderContext context)
        {
            var attr = context.Parameter.GetCustomAttribute <TAttribute>();

            if (attr == null)
            {
                return(null);
            }

            if (_validator != null)
            {
                // Expected this will throw on errors.
                Type parameterType    = context.Parameter.ParameterType;
                var  cloner           = new AttributeCloner <TAttribute>(attr, context.BindingDataContract, _nameResolver);
                var  attrNameResolved = cloner.GetNameResolvedAttribute();
                _validator(attrNameResolved, parameterType);
            }

            foreach (IBindingProvider provider in _providers)
            {
                IBinding binding = await provider.TryCreateAsync(context);

                if (binding != null)
                {
                    return(binding);
                }
            }

            // Nobody claimed it.
            string       resourceName = typeof(TAttribute).Name;
            const string Suffix       = "Attribute";

            if (resourceName.EndsWith(Suffix))
            {
                resourceName = resourceName.Substring(0, resourceName.Length - Suffix.Length);
            }
            throw new InvalidOperationException("Can't bind " + resourceName + " to type '" + context.Parameter.ParameterType + "'.");
        }
        /// <inheritdoc/>
        public Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // Determine whether we should bind to the current parameter
            ParameterInfo parameter = context.Parameter;
            FileAttribute attribute = parameter.GetCustomAttribute<FileAttribute>(inherit: false);
            if (attribute == null)
            {
                return Task.FromResult<IBinding>(null);
            }

            if (!CanBind(context))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
                    "Can't bind FileAttribute to type '{0}'.", parameter.ParameterType));
            }

            return Task.FromResult<IBinding>(new FileBinding(_config, parameter));
        }
        public Task <IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var parameter = context.Parameter;
            var typeUser  = parameter.ParameterType;

            if (typeUser.IsByRef)
            {
                typeUser = typeUser.GetElementType(); // Can't generic instantiate a ByRef.
            }

            var type   = typeof(StreamBinding);
            var method = type.GetMethod("TryBuild", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

            method = method.MakeGenericMethod(typeUser);
            var binding = BindingFactoryHelpers.MethodInvoke <IBinding>(method, this, context);

            return(Task.FromResult <IBinding>(binding));
        }
Ejemplo n.º 31
0
        public Task <IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ParameterInfo parameter = context.Parameter;

            if (parameter.ParameterType != typeof(ILogger))
            {
                return(Task.FromResult <IBinding>(null));
            }

            if (_loggerFactory == null)
            {
                throw new ArgumentException("A parameter of type ILogger cannot be used without a registered ILoggerFactory.");
            }

            IBinding binding = new ILoggerBinding(parameter, _loggerFactory);

            return(Task.FromResult(binding));
        }
Ejemplo n.º 32
0
        public async Task <IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var binding = await _inner.TryCreateAsync(context);

            if (binding != null)
            {
                // Only run the validator if the inner binding claims it.
                // Expected this will throw on errors.
                Type parameterType = context.Parameter.ParameterType;
                var  attr          = context.Parameter.GetCustomAttribute <TAttribute>();

                var cloner           = new AttributeCloner <TAttribute>(attr, context.BindingDataContract, _configuration, _nameResolver);
                var attrNameResolved = cloner.GetNameResolvedAttribute();
                _validator(attrNameResolved, parameterType);
            }

            return(binding);
        }
        public Task<IBinding> TryCreateAsync(BindingProviderContext context)
        {
            ParameterInfo parameter = context.Parameter;

            FakeQueueAttribute attribute = parameter.GetCustomAttribute<FakeQueueAttribute>(inherit: false);

            if (attribute == null)
            {
                return Task.FromResult<IBinding>(null);
            }

            string resolvedName = "fakequeue";
            Func<string, FakeQueueClient> invokeStringBinder = (invokeString) => _client;

            IBinding binding = BindingFactory.BindCollector<FakeQueueData, FakeQueueClient>(
                parameter,
                _converterManager,
                (client, valueBindingContext) => client,
                resolvedName,
                invokeStringBinder
            );

            return Task.FromResult(binding);
        }
            public static ExactBinding <TUserType> TryBuild(
                TriggerAdapterBindingProvider <TAttribute, TTriggerValue> parent,
                BindingProviderContext context)
            {
                IConverterManager cm = parent._converterManager;

                var converter = cm.GetConverter <TTriggerValue, TUserType, TAttribute>();

                if (converter == null)
                {
                    return(null);
                }

                var parameter       = context.Parameter;
                var attributeSource = TypeUtility.GetResolvedAttribute <TAttribute>(parameter);

                return(new ExactBinding <TUserType>
                {
                    _converter = converter,
                    _directInvoker = GetDirectInvoker(cm),
                    _getInvokeString = GetDirectInvokeString(cm),
                    _attribute = attributeSource
                });
            }
            public static ExactBinding <TMessage> TryBuild(
                AsyncCollectorBindingProvider <TAttribute, TType> parent,
                Mode mode,
                BindingProviderContext context)
            {
                var patternMatcher = parent._patternMatcher;

                var parameter       = context.Parameter;
                var attributeSource = TypeUtility.GetResolvedAttribute <TAttribute>(parameter);

                FuncAsyncConverter buildFromAttribute;
                FuncAsyncConverter <TMessage, TType> converter = null;

                // Prefer the shortest route to creating the user type.
                // If TType matches the user type directly, then we should be able to directly invoke the builder in a single step.
                //   TAttribute --> TUserType
                var checker = OpenType.FromType <TType>();

                if (checker.IsMatch(typeof(TMessage)))
                {
                    buildFromAttribute = patternMatcher.TryGetConverterFunc(
                        typeof(TAttribute), typeof(IAsyncCollector <TMessage>));
                }
                else
                {
                    var converterManager = parent._converterManager;

                    // Try with a converter
                    // Find a builder for :   TAttribute --> TType
                    // and then couple with a converter:  TType --> TParameterType
                    converter = converterManager.GetConverter <TMessage, TType, TAttribute>();
                    if (converter == null)
                    {
                        // Preserves legacy behavior. This means we can only have 1 async collector.
                        // However, the collector's builder object can switch.
                        throw NewMissingConversionError(typeof(TMessage));
                    }

                    buildFromAttribute = patternMatcher.TryGetConverterFunc(
                        typeof(TAttribute), typeof(IAsyncCollector <TType>));
                }

                if (buildFromAttribute == null)
                {
                    context.BindingErrors.Add(String.Format(Constants.BindingAssemblyConflictMessage, typeof(TType).AssemblyQualifiedName, typeof(TMessage).AssemblyQualifiedName));
                    return(null);
                }

                ParameterDescriptor param;

                if (parent.BuildParameterDescriptor != null)
                {
                    param = parent.BuildParameterDescriptor(attributeSource, parameter, parent._nameResolver);
                }
                else
                {
                    param = new ParameterDescriptor
                    {
                        Name         = parameter.Name,
                        DisplayHints = new ParameterDisplayHints
                        {
                            Description = "output"
                        }
                    };
                }

                var cloner = new AttributeCloner <TAttribute>(attributeSource, context.BindingDataContract, parent._nameResolver);

                return(new ExactBinding <TMessage>(cloner, param, mode, buildFromAttribute, converter));
            }
Ejemplo n.º 36
0
            public static ExactBinding TryBuild(
                BindToInputBindingProvider <TAttribute, TType> parent,
                BindingProviderContext context)
            {
                var cm             = parent._converterManager;
                var patternMatcher = parent._patternMatcher;

                var parameter       = context.Parameter;
                var userType        = parameter.ParameterType;
                var attributeSource = TypeUtility.GetResolvedAttribute <TAttribute>(parameter);

                var cloner = new AttributeCloner <TAttribute>(attributeSource, context.BindingDataContract, parent._configuration, parent._nameResolver);

                FuncAsyncConverter buildFromAttribute;
                FuncAsyncConverter converter = null;

                // Prefer the shortest route to creating the user type.
                // If TType matches the user type directly, then we should be able to directly invoke the builder in a single step.
                //   TAttribute --> TUserType
                var checker = OpenType.FromType <TType>();

                if (checker.IsMatch(userType))
                {
                    buildFromAttribute = patternMatcher.TryGetConverterFunc(typeof(TAttribute), userType);
                }
                else
                {
                    // Try with a converter
                    // Find a builder for :   TAttribute --> TType
                    // and then couple with a converter:  TType --> TParameterType
                    converter = cm.GetConverter <TAttribute>(typeof(TType), userType);
                    if (converter == null)
                    {
                        var targetType = typeof(TType);
                        context.BindingErrors.Add(String.Format(Resource.BindingAssemblyConflictMessage, targetType.AssemblyQualifiedName, userType.AssemblyQualifiedName));
                        return(null);
                    }

                    buildFromAttribute = patternMatcher.TryGetConverterFunc(typeof(TAttribute), typeof(TType));
                }

                if (buildFromAttribute == null)
                {
                    return(null);
                }

                ParameterDescriptor param;

                if (parent.BuildParameterDescriptor != null)
                {
                    param = parent.BuildParameterDescriptor(attributeSource, parameter, parent._nameResolver);
                }
                else
                {
                    param = new ParameterDescriptor
                    {
                        Name         = parameter.Name,
                        DisplayHints = new ParameterDisplayHints
                        {
                            Description = "input"
                        }
                    };
                }

                return(new ExactBinding(cloner, param, buildFromAttribute, converter, userType));
            }
            public static IBinding TryBuild <TUserType>(
                BindToStreamBindingProvider <TAttribute> parent,
                BindingProviderContext context)
            {
                // Allowed Param types:
                //  Stream
                //  any T with a Stream --> T conversion
                // out T, with a Out<Stream,T> --> void conversion

                var parameter     = context.Parameter;
                var parameterType = parameter.ParameterType;


                var attributeSource = TypeUtility.GetResolvedAttribute <TAttribute>(parameter);

                // Stream is either way; all other types are known.
                FileAccess?declaredAccess = GetFileAccessFromAttribute(attributeSource);

                Type argHelperType;
                bool isRead;

                IConverterManager cm     = parent._converterManager;
                INameResolver     nm     = parent._nameResolver;
                IConfiguration    config = parent._configuration;

                object converterParam = null;

                {
                    if (parameter.IsOut)
                    {
                        var outConverter = cm.GetConverter <ApplyConversion <TUserType, Stream>, object, TAttribute>();
                        if (outConverter != null)
                        {
                            converterParam = outConverter;
                            isRead         = false;
                            argHelperType  = typeof(OutArgBaseValueProvider <>).MakeGenericType(typeof(TAttribute), typeof(TUserType));
                        }
                        else
                        {
                            throw new InvalidOperationException($"No stream converter to handle {typeof(TUserType).FullName}.");
                        }
                    }
                    else
                    {
                        var converter = cm.GetConverter <Stream, TUserType, TAttribute>();
                        if (converter != null)
                        {
                            converterParam = converter;

                            if (parameterType == typeof(Stream))
                            {
                                if (!declaredAccess.HasValue)
                                {
                                    throw new InvalidOperationException("When binding to Stream, the attribute must specify a FileAccess direction.");
                                }
                                switch (declaredAccess.Value)
                                {
                                case FileAccess.Read:
                                    isRead = true;

                                    break;

                                case FileAccess.Write:
                                    isRead = false;
                                    break;

                                default:
                                    throw new NotImplementedException("ReadWrite access is not supported. Pick either Read or Write.");
                                }
                            }
                            else
                            {
                                // For backwards compat, we recognize TextWriter as write;
                                // anything else should explicitly set the FileAccess flag.
                                if (typeof(TextWriter).IsAssignableFrom(typeof(TUserType)))
                                {
                                    isRead = false;
                                }
                                else
                                {
                                    isRead = true;
                                }
                            }


                            argHelperType = typeof(ValueProvider <>).MakeGenericType(typeof(TAttribute), typeof(TUserType));
                        }
                        else
                        {
                            // This rule can't bind.
                            // Let another try.
                            context.BindingErrors.Add(String.Format(Resource.BindingAssemblyConflictMessage, typeof(Stream).AssemblyQualifiedName, typeof(TUserType).AssemblyQualifiedName));
                            return(null);
                        }
                    }
                }

                VerifyAccessOrThrow(declaredAccess, isRead);
                if (!parent.IsSupportedByRule(isRead))
                {
                    return(null);
                }

                var cloner = new AttributeCloner <TAttribute>(attributeSource, context.BindingDataContract, config, nm);

                ParameterDescriptor param;

                if (parent.BuildParameterDescriptor != null)
                {
                    param = parent.BuildParameterDescriptor(attributeSource, parameter, nm);
                }
                else
                {
                    param = new ParameterDescriptor
                    {
                        Name         = parameter.Name,
                        DisplayHints = new ParameterDisplayHints
                        {
                            Description = isRead ? "Read Stream" : "Write Stream"
                        }
                    };
                }

                var      fileAccess = isRead ? FileAccess.Read : FileAccess.Write;
                IBinding binding    = new StreamBinding(cloner, param, parent, argHelperType, parameterType, fileAccess, converterParam);

                return(binding);
            }
Ejemplo n.º 38
0
            public static ExactBinding <TMessage> TryBuild(
                AsyncCollectorBindingProvider <TAttribute, TType> parent,
                Mode mode,
                BindingProviderContext context)
            {
                var patternMatcher = parent._patternMatcher;

                var        parameter       = context.Parameter;
                TAttribute attributeSource = parameter.GetCustomAttribute <TAttribute>(inherit: false);

                Func <TAttribute, Task <TAttribute> > hookWrapper = null;

                if (parent.PostResolveHook != null)
                {
                    hookWrapper = (attrResolved) => parent.PostResolveHook(attrResolved, parameter, parent._nameResolver);
                }

                Func <object, object> buildFromAttribute;
                FuncConverter <TMessage, TAttribute, TType> converter = null;

                // Prefer the shortest route to creating the user type.
                // If TType matches the user type directly, then we should be able to directly invoke the builder in a single step.
                //   TAttribute --> TUserType
                var checker = ConverterManager.GetTypeValidator <TType>();

                if (checker.IsMatch(typeof(TMessage)))
                {
                    buildFromAttribute = patternMatcher.TryGetConverterFunc(
                        typeof(TAttribute), typeof(IAsyncCollector <TMessage>));
                }
                else
                {
                    var converterManager = parent._converterManager;

                    // Try with a converter
                    // Find a builder for :   TAttribute --> TType
                    // and then couple with a converter:  TType --> TParameterType
                    converter = converterManager.GetConverter <TMessage, TType, TAttribute>();
                    if (converter == null)
                    {
                        // Preserves legacy behavior. This means we can only have 1 async collector.
                        // However, the collector's builder object can switch.
                        throw NewMissingConversionError(typeof(TMessage));
                    }

                    buildFromAttribute = patternMatcher.TryGetConverterFunc(
                        typeof(TAttribute), typeof(IAsyncCollector <TType>));
                }

                if (buildFromAttribute == null)
                {
                    return(null);
                }

                ParameterDescriptor param;

                if (parent.BuildParameterDescriptor != null)
                {
                    param = parent.BuildParameterDescriptor(attributeSource, parameter, parent._nameResolver);
                }
                else
                {
                    param = new ParameterDescriptor
                    {
                        Name         = parameter.Name,
                        DisplayHints = new ParameterDisplayHints
                        {
                            Description = "output"
                        }
                    };
                }

                var cloner = new AttributeCloner <TAttribute>(attributeSource, context.BindingDataContract, parent._nameResolver, hookWrapper);

                return(new ExactBinding <TMessage>(cloner, param, mode, buildFromAttribute, converter));
            }
Ejemplo n.º 39
0
            public static ExactBinding <TUserType> TryBuild(
                BindToInputBindingProvider <TAttribute, TType> parent,
                BindingProviderContext context)
            {
                var cm             = parent._converterManager;
                var patternMatcher = parent._patternMatcher;

                var        parameter       = context.Parameter;
                TAttribute attributeSource = parameter.GetCustomAttribute <TAttribute>(inherit: false);

                Func <TAttribute, Task <TAttribute> > hookWrapper = null;

                if (parent.PostResolveHook != null)
                {
                    hookWrapper = (attrResolved) => parent.PostResolveHook(attrResolved, parameter, parent._nameResolver);
                }

                var cloner = new AttributeCloner <TAttribute>(attributeSource, context.BindingDataContract, parent._nameResolver, hookWrapper);

                Func <object, object> buildFromAttribute;
                FuncConverter <TType, TAttribute, TUserType> converter = null;

                // Prefer the shortest route to creating the user type.
                // If TType matches the user type directly, then we should be able to directly invoke the builder in a single step.
                //   TAttribute --> TUserType
                var checker = ConverterManager.GetTypeValidator <TType>();

                if (checker.IsMatch(typeof(TUserType)))
                {
                    buildFromAttribute = patternMatcher.TryGetConverterFunc(typeof(TAttribute), typeof(TUserType));
                }
                else
                {
                    // Try with a converter
                    // Find a builder for :   TAttribute --> TType
                    // and then couple with a converter:  TType --> TParameterType
                    converter = cm.GetConverter <TType, TUserType, TAttribute>();
                    if (converter == null)
                    {
                        return(null);
                    }

                    buildFromAttribute = patternMatcher.TryGetConverterFunc(typeof(TAttribute), typeof(TType));
                }

                if (buildFromAttribute == null)
                {
                    return(null);
                }

                ParameterDescriptor param;

                if (parent.BuildParameterDescriptor != null)
                {
                    param = parent.BuildParameterDescriptor(attributeSource, parameter, parent._nameResolver);
                }
                else
                {
                    param = new ParameterDescriptor
                    {
                        Name         = parameter.Name,
                        DisplayHints = new ParameterDisplayHints
                        {
                            Description = "input"
                        }
                    };
                }

                return(new ExactBinding <TUserType>(cloner, param, buildFromAttribute, converter));
            }