Exemplo n.º 1
0
        /// <summary>
        /// Create the <see cref="ITriggerBinding"/> (being the <see cref="ResilientEventHubBinding"/>).
        /// </summary>
        /// <param name="context">The <see cref="TriggerBindingProviderContext"/>.</param>
        /// <returns></returns>
        public Task <ITriggerBinding?> TryCreateAsync(TriggerBindingProviderContext context)
        {
            // Get the required attribuite.
            var att = context.Parameter.GetCustomAttribute <ResilientEventHubTriggerAttribute>(false);

            if (att == null)
            {
                return(Task.FromResult <ITriggerBinding?>(null));
            }

            // Resolve the attribute parameters.
            var resolvedEventHubName  = _nameResolver.ResolveWholeString(att.EventHubName);
            var resolvedConsumerGroup = _nameResolver.ResolveWholeString(att.ConsumerGroup ?? PartitionReceiver.DefaultConsumerGroupName);

            if (!string.IsNullOrWhiteSpace(att.Connection))
            {
                var connectionString = _config.GetConnectionStringOrSetting(_nameResolver.ResolveWholeString(att.Connection));
                _options.Value.AddEventHub(resolvedEventHubName, connectionString);
            }

            // Capture the name of the function being executed.
            _options.Value.FunctionName = context.Parameter.Member.GetCustomAttribute <FunctionNameAttribute>().Name;
            _options.Value.FunctionType = context.Parameter.Member.DeclaringType.FullName + "." + context.Parameter.Member.Name;

            // Create the event hub processor.
            var host = _options.Value.GetEventProcessorHost(_config, resolvedEventHubName, resolvedConsumerGroup);

            // Create and return the binding.
            return(Task.FromResult <ITriggerBinding?>(new ResilientEventHubBinding(host, context.Parameter, _options.Value, _config, _logger)));
        }
        public Task <IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            ParameterInfo parameter = context.Parameter;
            var           attribute = TypeUtility.GetResolvedAttribute <ServiceBusAttribute>(parameter);

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

            string queueOrTopicName      = _nameResolver.ResolveWholeString(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));
            }

            attribute.Connection = _nameResolver.ResolveWholeString(attribute.Connection);

            IBinding binding = new ServiceBusBinding(parameter.Name, argumentBinding, path, attribute, _messagingProvider, _clientFactory);

            return(Task.FromResult <IBinding>(binding));
        }
Exemplo n.º 3
0
        internal SignalRTriggerAttribute GetParameterResolvedAttribute(SignalRTriggerAttribute attribute, ParameterInfo parameterInfo)
        {
            //TODO: AutoResolve more properties in attribute
            var hubName                 = attribute.HubName;
            var category                = attribute.Category;
            var @event                  = attribute.Event;
            var parameterNames          = attribute.ParameterNames ?? Array.Empty <string>();
            var connectionStringSetting = attribute.ConnectionStringSetting;

            // We have two models for C#, one is function based model which also work in multiple language
            // Another one is class based model, which is highly close to SignalR itself but must keep some conventions.
            var method       = (MethodInfo)parameterInfo.Member;
            var declaredType = method.DeclaringType;

            string[] parameterNamesFromAttribute;

            if (declaredType != null && IsServerlessHub(declaredType))
            {
                // Class based model
                if (!string.IsNullOrEmpty(hubName) ||
                    !string.IsNullOrEmpty(category) ||
                    !string.IsNullOrEmpty(@event) ||
                    parameterNames.Length != 0)
                {
                    throw new ArgumentException($"{nameof(SignalRTriggerAttribute)} must use parameterless constructor in class based model.");
                }
                parameterNamesFromAttribute = method.GetParameters().Where(IsLegalClassBasedParameter).Select(p => p.Name).ToArray();
                hubName  = declaredType.Name;
                category = GetCategoryFromMethodName(method.Name);
                @event   = GetEventFromMethodName(method.Name, category);
                connectionStringSetting = declaredType.GetCustomAttribute <SignalRConnectionAttribute>()?.Connection ?? attribute.ConnectionStringSetting;
            }
            else
            {
                parameterNamesFromAttribute = method.GetParameters().
                                              Where(p => p.GetCustomAttribute <SignalRParameterAttribute>(false) != null).
                                              Select(p => p.Name).ToArray();

                if (parameterNamesFromAttribute.Length != 0 && parameterNames.Length != 0)
                {
                    throw new InvalidOperationException(
                              $"{nameof(SignalRTriggerAttribute)}.{nameof(SignalRTriggerAttribute.ParameterNames)} and {nameof(SignalRParameterAttribute)} can not be set in the same Function.");
                }

                // If we aren't using the class-based model, make sure we resolve binding expressions for attribute properties here.
                hubName  = _nameResolver.ResolveWholeString(hubName);
                category = _nameResolver.ResolveWholeString(category);
                @event   = _nameResolver.ResolveWholeString(@event);
            }

            parameterNames = parameterNamesFromAttribute.Length != 0
                ? parameterNamesFromAttribute
                : parameterNames;

            return(new SignalRTriggerAttribute(hubName, category, @event, parameterNames)
            {
                ConnectionStringSetting = connectionStringSetting
            });
        }
        public Task <ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

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

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

            string resolvedEventHubName = _nameResolver.ResolveWholeString(attribute.EventHubName);

            string consumerGroup         = attribute.ConsumerGroup ?? EventHubConsumerClient.DefaultConsumerGroupName;
            string resolvedConsumerGroup = _nameResolver.ResolveWholeString(consumerGroup);

            if (!string.IsNullOrWhiteSpace(attribute.Connection))
            {
                var connection       = _nameResolver.ResolveWholeString(attribute.Connection);
                var connectionString = _config.GetConnectionStringOrSetting(connection);
                _options.Value.AddReceiver(resolvedEventHubName, connectionString);
            }

            var eventHostListener = _options.Value.GetEventProcessorHost(resolvedEventHubName, resolvedConsumerGroup);
            var checkpointStoreConnectionString = _options.Value.GetCheckpointStoreConnectionString(_config, resolvedEventHubName);

            Func <ListenerFactoryContext, bool, Task <IListener> > createListener =
                (factoryContext, singleDispatch) =>
            {
                var checkpointStore = new BlobsCheckpointStore(
                    new BlobContainerClient(checkpointStoreConnectionString, _options.Value.LeaseContainerName),
                    _options.Value.EventProcessorOptions.RetryOptions.ToRetryPolicy(),
                    factoryContext.Descriptor.Id,
                    _logger);

                IListener listener = new EventHubListener(
                    factoryContext.Descriptor.Id,
                    factoryContext.Executor,
                    eventHostListener,
                    singleDispatch,
                    () => _options.Value.GetEventHubConsumerClient(resolvedEventHubName, consumerGroup),
                    checkpointStore,
                    _options.Value,
                    _logger);
                return(Task.FromResult(listener));
            };

#pragma warning disable 618
            ITriggerBinding binding = BindingFactory.GetTriggerBinding(new EventHubTriggerBindingStrategy(), parameter, _converterManager, createListener);
#pragma warning restore 618
            return(Task.FromResult(binding));
        }
Exemplo n.º 5
0
        public Task <ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

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

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

            string resolvedEventHubName = _nameResolver.ResolveWholeString(attribute.EventHubName);

            string consumerGroup         = attribute.ConsumerGroup ?? PartitionReceiver.DefaultConsumerGroupName;
            string resolvedConsumerGroup = _nameResolver.ResolveWholeString(consumerGroup);

            string connectionString = null;

            if (!string.IsNullOrWhiteSpace(attribute.Connection))
            {
                attribute.Connection = _nameResolver.ResolveWholeString(attribute.Connection);
                connectionString     = _config.GetConnectionStringOrSetting(attribute.Connection);
                _options.Value.AddReceiver(resolvedEventHubName, connectionString);
            }

            var eventHostListener = _options.Value.GetEventProcessorHost(_config, resolvedEventHubName, resolvedConsumerGroup);

            string storageConnectionString = _config.GetWebJobsConnectionString(ConnectionStringNames.Storage);

            Func <ListenerFactoryContext, bool, Task <IListener> > createListener =
                (factoryContext, singleDispatch) =>
            {
                IListener listener = new EventHubListener(
                    factoryContext.Descriptor.Id,
                    resolvedEventHubName,
                    resolvedConsumerGroup,
                    connectionString,
                    storageConnectionString,
                    factoryContext.Executor,
                    eventHostListener,
                    singleDispatch,
                    _options.Value,
                    _logger);
                return(Task.FromResult(listener));
            };

            ITriggerBinding binding = BindingFactory.GetTriggerBinding(new EventHubTriggerBindingStrategy(), parameter, _converterManager, createListener);

            return(Task.FromResult <ITriggerBinding>(binding));
        }
        public Task <ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            ParameterInfo parameter = context.Parameter;
            var           attribute = TypeUtility.GetResolvedAttribute <ServiceBusTriggerAttribute>(parameter);

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

            attribute.Connection = _nameResolver.ResolveWholeString(attribute.Connection);
            string entityPath;
            ServiceBusEntityType serviceBusEntityType;

            if (attribute.QueueName != null)
            {
                var queueName = _nameResolver.ResolveWholeString(attribute.QueueName);
                entityPath           = queueName;
                serviceBusEntityType = ServiceBusEntityType.Queue;
            }
            else
            {
                var topicName        = _nameResolver.ResolveWholeString(attribute.TopicName);
                var subscriptionName = _nameResolver.ResolveWholeString(attribute.SubscriptionName);
                entityPath           = EntityNameFormatter.FormatSubscriptionPath(topicName, subscriptionName);
                serviceBusEntityType = ServiceBusEntityType.Topic;
            }

            Func <ListenerFactoryContext, bool, Task <IListener> > createListener =
                (factoryContext, singleDispatch) =>
            {
                var       autoCompleteMessagesOptionEvaluatedValue = GetAutoCompleteMessagesOptionToUse(attribute, factoryContext.Descriptor.ShortName);
                IListener listener = new ServiceBusListener(factoryContext.Descriptor.Id, serviceBusEntityType, entityPath, attribute.IsSessionsEnabled, autoCompleteMessagesOptionEvaluatedValue, factoryContext.Executor, _options, attribute.Connection, _messagingProvider, _loggerFactory, singleDispatch, _clientFactory, _concurrencyManager);

                return(Task.FromResult(listener));
            };

#pragma warning disable 618
            ITriggerBinding binding = BindingFactory.GetTriggerBinding(new ServiceBusTriggerBindingStrategy(), parameter, _converterManager, createListener);
#pragma warning restore 618

            return(Task.FromResult <ITriggerBinding>(binding));
        }
        public Task <IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

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

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

            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(FileAccess.Read);

            if (!ValueBinder.MatchParameterType(context.Parameter, types))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
                                                                  "Can't bind FtpAttribute to type '{0}'.", parameter.ParameterType));
            }

            return(Task.FromResult <IBinding>(new FtpBinding(_config, parameter, bindingTemplate)));
        }
            public override Collection <Attribute> GetAttributes()
            {
                Collection <Attribute> attributes = new Collection <Attribute>();

                string schedule     = Context.GetMetadataValue <string>("schedule");
                bool   runOnStartup = Context.GetMetadataValue <bool>("runOnStartup");
                bool   useMonitor   = Context.GetMetadataValue <bool>("useMonitor", true);

                if (_environment.IsWindowsConsumption())
                {
                    // pre-resolve app setting specifiers
                    schedule = _nameResolver.ResolveWholeString(schedule);

                    var options = new CrontabSchedule.ParseOptions()
                    {
                        IncludingSeconds = true
                    };
                    if (CrontabSchedule.TryParse(schedule, options) == null)
                    {
                        throw new ArgumentException(string.Format("'{0}' is not a valid CRON expression.", schedule));
                    }
                }

                attributes.Add(new TimerTriggerAttribute(schedule)
                {
                    RunOnStartup = runOnStartup,
                    UseMonitor   = useMonitor
                });

                return(attributes);
            }
        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));
        }
Exemplo n.º 10
0
        internal static bool IsDisabledBySetting(string settingName, MethodInfo method, INameResolver nameResolver)
        {
            if (nameResolver != null)
            {
                settingName = nameResolver.ResolveWholeString(settingName);
            }

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

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

            // check the target setting and return false (disabled) if the value exists
            // and is "falsey"
            string value = ConfigurationUtility.GetSettingFromConfigOrEnvironment(settingName);

            if (!string.IsNullOrEmpty(value) &&
                (string.Compare(value, "1", StringComparison.OrdinalIgnoreCase) == 0 ||
                 string.Compare(value, "true", StringComparison.OrdinalIgnoreCase) == 0))
            {
                return(true);
            }

            return(false);
        }
        public Task <ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

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

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

            string eventHubName      = attribute.EventHubName;
            string resolvedName      = _nameResolver.ResolveWholeString(eventHubName);
            var    eventHostListener = _eventHubConfig.GetEventProcessorHost(resolvedName);

            var options = _eventHubConfig.GetOptions();
            var hooks   = new EventHubTriggerBindingStrategy();

            Func <ListenerFactoryContext, bool, Task <IListener> > createListener =
                (factoryContext, singleDispatch) =>
            {
                IListener listener = new EventHubListener(factoryContext.Executor, eventHostListener, options, singleDispatch);
                return(Task.FromResult(listener));
            };

            ITriggerBinding binding = BindingFactory.GetTriggerBinding <EventData, EventHubTriggerInput>(hooks, parameter, _converterManager, createListener);

            return(Task.FromResult <ITriggerBinding>(binding));
        }
Exemplo n.º 12
0
        internal static TimerSchedule Create(TimerTriggerAttribute attribute, INameResolver nameResolver)
        {
            TimerSchedule schedule = null;

            if (!string.IsNullOrEmpty(attribute.ScheduleExpression))
            {
                string resolvedExpression = nameResolver.ResolveWholeString(attribute.ScheduleExpression);

                CronSchedule cronSchedule = null;
                if (CronSchedule.TryCreate(resolvedExpression, out cronSchedule))
                {
                    schedule = cronSchedule;

                    DateTime[] nextOccurrences = cronSchedule.InnerSchedule.GetNextOccurrences(DateTime.Now, DateTime.Now + TimeSpan.FromMinutes(1)).ToArray();
                    if (nextOccurrences.Length > 1)
                    {
                        // if there is more than one occurrence due in the next minute,
                        // assume that this is a sub-minute constant schedule and disable
                        // persistence
                        attribute.UseMonitor = false;
                    }
                    else if (!attribute.UseMonitor.HasValue)
                    {
                        // if the user hasn't specified a value
                        // set to true
                        attribute.UseMonitor = true;
                    }
                }
                else
                {
                    TimeSpan periodTimespan = TimeSpan.Parse(resolvedExpression);
                    schedule = new ConstantSchedule(periodTimespan);

                    if (periodTimespan.TotalMinutes < 1)
                    {
                        // for very frequent constant schedules, we want to disable persistence
                        attribute.UseMonitor = false;
                    }
                    else if (!attribute.UseMonitor.HasValue)
                    {
                        // if the user hasn't specified a value
                        // set to true
                        attribute.UseMonitor = true;
                    }
                }
            }
            else
            {
                schedule = (TimerSchedule)Activator.CreateInstance(attribute.ScheduleType);
                if (!attribute.UseMonitor.HasValue)
                {
                    // if the user hasn't specified a value
                    // set to true
                    attribute.UseMonitor = true;
                }
            }

            return(schedule);
        }
Exemplo n.º 13
0
        private string NameResolveWholeStringRecursive(string name)
        {
            if (_nameResolver == null || String.IsNullOrWhiteSpace(name))
            {
                return(name);
            }

            string resolvedName = _nameResolver.ResolveWholeString(name);

            while (false == String.IsNullOrWhiteSpace(resolvedName) && false == resolvedName.Equals(name, StringComparison.Ordinal))
            {
                name         = resolvedName;
                resolvedName = _nameResolver.ResolveWholeString(name);
            }

            return(resolvedName);
        }
        public string Resolve(string channelOrKey)
        {
            if (_nameResolver == null)
            {
                return(channelOrKey);
            }

            return(_nameResolver.ResolveWholeString(channelOrKey));
        }
Exemplo n.º 15
0
        // AutoResolve
        internal static BindingDataResolver GetTemplateResolver(string originalValue, AutoResolveAttribute attr, INameResolver nameResolver, PropertyInfo propInfo, BindingDataContract contract)
        {
            string            resolvedValue = nameResolver.ResolveWholeString(originalValue);
            var               template      = BindingTemplate.FromString(resolvedValue);
            IResolutionPolicy policy        = GetPolicy(attr.ResolutionPolicyType, propInfo);

            template.ValidateContractCompatibility(contract);
            return((newAttr, bindingData) => TemplateBind(policy, propInfo, newAttr, template, bindingData));
        }
        private static string Resolve(string value, INameResolver resolver)
        {
            if (resolver == null)
            {
                return(value);
            }

            return(resolver.ResolveWholeString(value));
        }
        private static string Resolve(string name, INameResolver nameResolver)
        {
            if (nameResolver == null)
            {
                return(name);
            }

            return(nameResolver.ResolveWholeString(name));
        }
        private string Resolve(string queueName)
        {
            if (_nameResolver == null)
            {
                return(queueName);
            }

            return(_nameResolver.ResolveWholeString(queueName));
        }
Exemplo n.º 19
0
        private string Resolve(string blobName)
        {
            if (_nameResolver == null)
            {
                return(blobName);
            }

            return(_nameResolver.ResolveWholeString(blobName));
        }
Exemplo n.º 20
0
            private static string NormalizeQueueName(QueueAttribute attribute, INameResolver nameResolver)
            {
                string queueName = attribute.QueueName;

                if (nameResolver != null)
                {
                    queueName = nameResolver.ResolveWholeString(queueName);
                }
                queueName = queueName.ToLowerInvariant(); // must be lowercase. coerce here to be nice.
                return(queueName);
            }
 private static void ValidateContract(string value, INameResolver nameResolver, IReadOnlyDictionary <string, Type> contract)
 {
     if (!string.IsNullOrEmpty(value))
     {
         if (nameResolver != null)
         {
             value = nameResolver.ResolveWholeString(value);
         }
         BindingTemplate bindingTemplate = BindingTemplate.FromString(value, ignoreCase: true);
         bindingTemplate.ValidateContractCompatibility(contract);
     }
 }
        internal static string ResolveSecureSetting(this IConfiguration config, INameResolver nameResolver, string currentValue)
        {
            if (string.IsNullOrWhiteSpace(currentValue))
            {
                return(currentValue);
            }

            var resolved           = nameResolver.ResolveWholeString(currentValue);
            var resolvedFromConfig = config.GetConnectionStringOrSetting(resolved);

            return(!string.IsNullOrEmpty(resolvedFromConfig) ? resolvedFromConfig : resolved);
        }
Exemplo n.º 23
0
        public Task <ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

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

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

            string resolvedEventHubName = _nameResolver.ResolveWholeString(attribute.EventHubName);

            string consumerGroup         = attribute.ConsumerGroup ?? EventHubConsumerGroup.DefaultGroupName;
            string resolvedConsumerGroup = _nameResolver.ResolveWholeString(consumerGroup);

            if (!string.IsNullOrWhiteSpace(attribute.Connection))
            {
                _eventHubConfig.AddReceiver(resolvedEventHubName, _nameResolver.Resolve(attribute.Connection));
            }

            var eventHostListener = _eventHubConfig.GetEventProcessorHost(resolvedEventHubName, resolvedConsumerGroup);

            var options = _eventHubConfig.GetOptions();

            Func <ListenerFactoryContext, bool, Task <IListener> > createListener =
                (factoryContext, singleDispatch) =>
            {
                IListener listener = new EventHubListener(factoryContext.Executor, eventHostListener, options, singleDispatch);
                return(Task.FromResult(listener));
            };

            ITriggerBinding binding = BindingFactory.GetTriggerBinding(new EventHubTriggerBindingStrategy(), parameter, _converterManager, createListener);

            return(Task.FromResult <ITriggerBinding>(binding));
        }
        public Task <ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context)
        {
            var attribute = context.Parameter.GetCustomAttribute <DiscordMessageTriggerAttribute>();

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

            var binding = new DiscordMessageTriggerBinding(context.Parameter.Name, resolver.ResolveWholeString(attribute.Token));

            return(Task.FromResult <ITriggerBinding>(binding));
        }
Exemplo n.º 25
0
            public override Collection <Attribute> GetAttributes()
            {
                Collection <Attribute> attributes = new Collection <Attribute>();

                string eventHubName = Context.GetMetadataValue <string>("path");

                if (!string.IsNullOrEmpty(eventHubName))
                {
                    eventHubName = _nameResolver.ResolveWholeString(eventHubName);
                }

                string connectionString = Context.GetMetadataValue <string>("connection");

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

                if (Context.IsTrigger)
                {
                    var    attribute     = new EventHubTriggerAttribute(eventHubName);
                    string consumerGroup = Context.GetMetadataValue <string>("consumerGroup");
                    if (consumerGroup != null)
                    {
                        consumerGroup           = _nameResolver.ResolveWholeString(consumerGroup);
                        attribute.ConsumerGroup = consumerGroup;
                    }
                    attributes.Add(attribute);
                    _eventHubConfiguration.AddReceiver(eventHubName, connectionString);
                }
                else
                {
                    attributes.Add(new EventHubAttribute(eventHubName));

                    _eventHubConfiguration.AddSender(eventHubName, connectionString);
                }

                return(attributes);
            }
Exemplo n.º 26
0
            public override Collection <Attribute> GetAttributes()
            {
                Collection <Attribute> attributes = new Collection <Attribute>();

                string eventHubName = Context.GetMetadataValue <string>("path");

                if (!string.IsNullOrEmpty(eventHubName))
                {
                    eventHubName = _nameResolver.ResolveWholeString(eventHubName);
                }

                string connectionString = Context.GetMetadataValue <string>("connection");

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

                if (Context.IsTrigger)
                {
                    attributes.Add(new EventHubTriggerAttribute(eventHubName));

                    string eventProcessorHostName  = Guid.NewGuid().ToString();
                    string storageConnectionString = _storageConnectionString;

                    string consumerGroup = Context.GetMetadataValue <string>("consumerGroup");
                    if (consumerGroup == null)
                    {
                        consumerGroup = Microsoft.ServiceBus.Messaging.EventHubConsumerGroup.DefaultGroupName;
                    }

                    var eventProcessorHost = new Microsoft.ServiceBus.Messaging.EventProcessorHost(
                        eventProcessorHostName,
                        eventHubName,
                        consumerGroup,
                        connectionString,
                        storageConnectionString);

                    _eventHubConfiguration.AddEventProcessorHost(eventHubName, eventProcessorHost);
                }
                else
                {
                    attributes.Add(new EventHubAttribute(eventHubName));

                    var client = Microsoft.ServiceBus.Messaging.EventHubClient.CreateFromConnectionString(connectionString, eventHubName);
                    _eventHubConfiguration.AddEventHubClient(eventHubName, client);
                }

                return(attributes);
            }
        internal static bool IsDisabledBySetting(string settingName, MethodInfo method, INameResolver nameResolver)
        {
            if (nameResolver != null)
            {
                settingName = nameResolver.ResolveWholeString(settingName);
            }

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

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

            return(ConfigurationUtility.IsSettingEnabled(settingName));
        }
        // AutoResolve
        internal static BindingDataResolver GetTemplateResolver(string originalValue, AutoResolveAttribute attr, INameResolver nameResolver, PropertyInfo propInfo, BindingDataContract contract, Validator validator)
        {
            string resolvedValue = nameResolver.ResolveWholeString(originalValue);
            var    template      = BindingTemplate.FromString(resolvedValue);

            if (!template.HasParameters)
            {
                // No { } tokens, bind eagerly up front.
                validator(resolvedValue);
            }

            IResolutionPolicy policy = GetPolicy(attr.ResolutionPolicyType, propInfo);

            template.ValidateContractCompatibility(contract);
            return((newAttr, bindingData) => TemplateBind(policy, propInfo, newAttr, template, bindingData, validator));
        }
        private ParameterDescriptor ToBlobDescr(BlobAttribute attr, ParameterInfo parameter, INameResolver nameResolver)
        {
            // Resolve the connection string to get an account name.
            var client = GetClient(attr);

            var accountName = client.AccountName;

            var resolved = nameResolver.ResolveWholeString(attr.BlobPath);

            string containerName = resolved;
            string blobName      = null;
            int    split         = resolved.IndexOf('/');

            if (split > 0)
            {
                containerName = resolved.Substring(0, split);
                blobName      = resolved.Substring(split + 1);
            }

            FileAccess access = FileAccess.ReadWrite;

            if (attr.Access.HasValue)
            {
                access = attr.Access.Value;
            }
            else
            {
                var type = parameter.ParameterType;
                if (type.IsByRef || type == typeof(TextWriter))
                {
                    access = FileAccess.Write;
                }
                if (type == typeof(TextReader) || type == typeof(string) || type == typeof(byte[]))
                {
                    access = FileAccess.Read;
                }
            }

            return(new BlobParameterDescriptor
            {
                Name = parameter.Name,
                AccountName = accountName,
                ContainerName = containerName,
                BlobName = blobName,
                Access = access
            });
        }
Exemplo n.º 30
0
        internal static TimerSchedule Create(TimerTriggerAttribute attribute, INameResolver nameResolver)
        {
            TimerSchedule schedule = null;

            if (!string.IsNullOrEmpty(attribute.ScheduleExpression))
            {
                string resolvedExpression = nameResolver.ResolveWholeString(attribute.ScheduleExpression);

                CronSchedule cronSchedule = null;
                TimeSpan     periodTimespan;
                if (CronSchedule.TryCreate(resolvedExpression, out cronSchedule))
                {
                    schedule = cronSchedule;

                    DateTime[] nextOccurrences = cronSchedule.InnerSchedule.GetNextOccurrences(DateTime.Now, DateTime.Now + TimeSpan.FromMinutes(1)).ToArray();
                    if (nextOccurrences.Length > 1)
                    {
                        // if there is more than one occurrence due in the next minute,
                        // assume that this is a sub-minute constant schedule and disable
                        // persistence
                        attribute.UseMonitor = false;
                    }
                }
                else if (TimeSpan.TryParse(resolvedExpression, out periodTimespan))
                {
                    schedule = new ConstantSchedule(periodTimespan);

                    if (periodTimespan.TotalMinutes < 1)
                    {
                        // for very frequent constant schedules, we want to disable persistence
                        attribute.UseMonitor = false;
                    }
                }
                else
                {
                    throw new ArgumentException("The schedule expression was not recognized as a valid cron expression or timespan string.");
                }
            }
            else
            {
                schedule = (TimerSchedule)Activator.CreateInstance(attribute.ScheduleType);
            }

            return(schedule);
        }
        internal static bool IsDisabledBySetting(string settingName, MethodInfo method, INameResolver nameResolver)
        {
            if (nameResolver != null)
            {
                settingName = nameResolver.ResolveWholeString(settingName);
            }

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

            // check the target setting and return false (disabled) if the value exists
            // and is "falsey"
            string value = ConfigurationUtility.GetSettingFromConfigOrEnvironment(settingName);
            if (!string.IsNullOrEmpty(value) &&
                (string.Compare(value, "1", StringComparison.OrdinalIgnoreCase) == 0 ||
                 string.Compare(value, "true", StringComparison.OrdinalIgnoreCase) == 0))
            {
                return true;
            }

            return false;
        }