public static ITriggerBindingProvider Create(INameResolver nameResolver,
            IStorageAccountProvider storageAccountProvider,
            IExtensionTypeLocator extensionTypeLocator,
            IHostIdProvider hostIdProvider,
            IQueueConfiguration queueConfiguration,
            IBackgroundExceptionDispatcher backgroundExceptionDispatcher,
            IContextSetter<IMessageEnqueuedWatcher> messageEnqueuedWatcherSetter,
            IContextSetter<IBlobWrittenWatcher> blobWrittenWatcherSetter,
            ISharedContextProvider sharedContextProvider,
            IExtensionRegistry extensions,
            TextWriter log)
        {
            List<ITriggerBindingProvider> innerProviders = new List<ITriggerBindingProvider>();
            innerProviders.Add(new QueueTriggerAttributeBindingProvider(nameResolver, storageAccountProvider,
                queueConfiguration, backgroundExceptionDispatcher, messageEnqueuedWatcherSetter,
                sharedContextProvider, log));
            innerProviders.Add(new BlobTriggerAttributeBindingProvider(nameResolver, storageAccountProvider,
                extensionTypeLocator, hostIdProvider, queueConfiguration, backgroundExceptionDispatcher,
                blobWrittenWatcherSetter, messageEnqueuedWatcherSetter, sharedContextProvider, log));

            // add any registered extension binding providers
            foreach (ITriggerBindingProvider provider in extensions.GetExtensions(typeof(ITriggerBindingProvider)))
            {
                innerProviders.Add(provider);
            }

            return new CompositeTriggerBindingProvider(innerProviders);
        }
Esempio n. 2
0
        public WorkItemManagerMock(string keyField, INameResolver resolver = null)
        {
            _keyField = keyField;
            _resolver = resolver ?? new NameResolverMock();

            WorkItemsCache = new SortedList<string, int>();
        }
        public static IBindingProvider Create(INameResolver nameResolver,
            IStorageAccountProvider storageAccountProvider,
            IExtensionTypeLocator extensionTypeLocator,
            IContextGetter<IMessageEnqueuedWatcher> messageEnqueuedWatcherGetter,
            IContextGetter<IBlobWrittenWatcher> blobWrittenWatcherGetter,
            IExtensionRegistry extensions)
        {
            List<IBindingProvider> innerProviders = new List<IBindingProvider>();
            innerProviders.Add(new QueueAttributeBindingProvider(nameResolver, storageAccountProvider, messageEnqueuedWatcherGetter));
            innerProviders.Add(new BlobAttributeBindingProvider(nameResolver, storageAccountProvider, extensionTypeLocator, blobWrittenWatcherGetter));
            innerProviders.Add(new TableAttributeBindingProvider(nameResolver, storageAccountProvider, extensions));

            // add any registered extension binding providers
            foreach (IBindingProvider provider in extensions.GetExtensions(typeof(IBindingProvider)))
            {
                innerProviders.Add(provider);
            }

            innerProviders.Add(new CloudStorageAccountBindingProvider(storageAccountProvider));
            innerProviders.Add(new CancellationTokenBindingProvider());

            // The console output binder below will handle all remaining TextWriter parameters. It must come after the
            // Blob binding provider; otherwise bindings like Do([Blob("a/b")] TextWriter blob) wouldn't work.
            innerProviders.Add(new ConsoleOutputBindingProvider());

            ContextAccessor<IBindingProvider> bindingProviderAccessor = new ContextAccessor<IBindingProvider>();
            innerProviders.Add(new RuntimeBindingProvider(bindingProviderAccessor));
            innerProviders.Add(new DataBindingProvider());

            IBindingProvider bindingProvider = new CompositeBindingProvider(innerProviders);
            bindingProviderAccessor.SetValue(bindingProvider);
            return bindingProvider;
        }
        public static FunctionIndexer Create(CloudStorageAccount account = null, INameResolver nameResolver = null, IExtensionRegistry extensionRegistry = null)
        {
            IStorageAccount storageAccount = account != null ? new StorageAccount(account) : null;
            IStorageAccountProvider storageAccountProvider = new SimpleStorageAccountProvider
            {
                StorageAccount = account
            };
            IExtensionTypeLocator extensionTypeLocator = new NullExtensionTypeLocator();
            ContextAccessor<IMessageEnqueuedWatcher> messageEnqueuedWatcherAccessor =
                new ContextAccessor<IMessageEnqueuedWatcher>();
            ContextAccessor<IBlobWrittenWatcher> blobWrittenWatcherAccessor =
                new ContextAccessor<IBlobWrittenWatcher>();
            ISharedContextProvider sharedContextProvider = new SharedContextProvider();
            ITriggerBindingProvider triggerBindingProvider = DefaultTriggerBindingProvider.Create(nameResolver,
                storageAccountProvider, extensionTypeLocator,
                new FixedHostIdProvider("test"), new SimpleQueueConfiguration(maxDequeueCount: 5),
                BackgroundExceptionDispatcher.Instance, messageEnqueuedWatcherAccessor, blobWrittenWatcherAccessor,
                sharedContextProvider, new DefaultExtensionRegistry(), TextWriter.Null);
            IBindingProvider bindingProvider = DefaultBindingProvider.Create(nameResolver, storageAccountProvider,
                extensionTypeLocator, messageEnqueuedWatcherAccessor,
                blobWrittenWatcherAccessor, new DefaultExtensionRegistry());

            IFunctionOutputLoggerProvider outputLoggerProvider = new NullFunctionOutputLoggerProvider();
            var task = outputLoggerProvider.GetAsync(CancellationToken.None);
            task.Wait();
            IFunctionOutputLogger outputLogger = task.Result;
            IFunctionExecutor executor = new FunctionExecutor(new NullFunctionInstanceLogger(), outputLogger, BackgroundExceptionDispatcher.Instance);

            if (extensionRegistry == null)
            {
                extensionRegistry = new DefaultExtensionRegistry();
            }

            return new FunctionIndexer(triggerBindingProvider, bindingProvider, DefaultJobActivator.Instance, executor, extensionRegistry);
        }
        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 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);
            }
        }
        public TableAttributeBindingProvider(INameResolver nameResolver, IStorageAccountProvider accountProvider, IExtensionRegistry extensions)
        {
            if (accountProvider == null)
            {
                throw new ArgumentNullException("accountProvider");
            }

            if (extensions == null)
            {
                throw new ArgumentNullException("extensions");
            }

            _nameResolver = nameResolver;
            _accountProvider = accountProvider;

            _tableProvider = new CompositeArgumentBindingProvider(
                new StorageTableArgumentBindingProvider(),
                new CloudTableArgumentBindingProvider(),
                new QueryableArgumentBindingProvider(),
                new CollectorArgumentBindingProvider(),
                new AsyncCollectorArgumentBindingProvider(),
                new TableArgumentBindingExtensionProvider(extensions));

            _entityProvider =
                new CompositeEntityArgumentBindingProvider(
                new TableEntityArgumentBindingProvider(),
                new PocoEntityArgumentBindingProvider()); // Supports all types; must come after other providers
        }
        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);
            }
        }
        internal static bool IsDisabled(MethodInfo method, INameResolver nameResolver, IJobActivator activator)
        {
            ParameterInfo triggerParameter = method.GetParameters().FirstOrDefault();
            if (triggerParameter != null)
            {
                // look for the first DisableAttribute up the hierarchy
                DisableAttribute disableAttribute = TypeUtility.GetHierarchicalAttributeOrNull<DisableAttribute>(triggerParameter);
                if (disableAttribute != null)
                {
                    if (!string.IsNullOrEmpty(disableAttribute.SettingName))
                    {
                        return IsDisabledBySetting(disableAttribute.SettingName, method, nameResolver);
                    }
                    else if (disableAttribute.ProviderType != null)
                    {
                        // a custom provider Type has been specified
                        return IsDisabledByProvider(disableAttribute.ProviderType, method, activator);
                    }
                    else
                    {
                        // the default constructor was used
                        return true;
                    }
                }
            }

            return false;
        }
Esempio n. 10
0
		public CreateBuilderSkeleton(ITypeContainer typeContainer, 
			INameResolver resolver, IErrorReport errorReport)
		{
			this.typeContainer = typeContainer;
			this.resolver = resolver;
			this.errorReport = errorReport;
		}
Esempio n. 11
0
 /// <summary>
 /// Connects to specified target host/port.
 /// </summary>
 /// <param name="route">The route.</param>
 /// <param name="targetHost">The target host.</param>
 /// <param name="targetPort">The target port.</param>
 /// <param name="nameResolver">The name resolver.</param>
 /// <returns></returns>
 public static Socket Connect(this Route route, string targetHost, int targetPort, INameResolver nameResolver)
 {
     var targetAddress = nameResolver.Resolve(targetHost, route);
     if (targetAddress == null)
         throw new ProxyRouteException(targetHost);
     return route.Connect(targetAddress, targetPort);
 }
Esempio n. 12
0
 public SingletonManager(IStorageAccountProvider accountProvider, IBackgroundExceptionDispatcher backgroundExceptionDispatcher, SingletonConfiguration config, TraceWriter trace, INameResolver nameResolver = null)
 {
     _accountProvider = accountProvider;
     _nameResolver = nameResolver;
     _backgroundExceptionDispatcher = backgroundExceptionDispatcher;
     _config = config;
     _trace = trace;
 }
 public HostListenerFactory(IEnumerable<IFunctionDefinition> functionDefinitions, SingletonManager singletonManager, IJobActivator activator, INameResolver nameResolver, TraceWriter trace)
 {
     _functionDefinitions = functionDefinitions;
     _singletonManager = singletonManager;
     _activator = activator;
     _nameResolver = nameResolver;
     _trace = trace;
 }
Esempio n. 14
0
		public TypeBuilderSkeletonStep(ModuleBuilder modBuilder, ITypeContainer container, 
			INameResolver resolver, IErrorReport errorReport)
		{
			this.modBuilder = modBuilder;
			this.container = container;
			this.resolver = resolver;
			this.errorReport = errorReport;
		}
 public EventHubTriggerAttributeBindingProvider(
     INameResolver nameResolver,
     IConverterManager converterManager,
     IEventHubProvider eventHubConfig)
 {
     this._nameResolver = nameResolver;
     this._converterManager = converterManager;
     this._eventHubConfig = eventHubConfig;
 }
        public ServiceBusAttributeBindingProvider(INameResolver nameResolver, ServiceBusConfiguration config)
        {
            if (nameResolver == null)
            {
                throw new ArgumentNullException("nameResolver");
            }
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            _nameResolver = nameResolver;
            _config = config;
        }
        public FileAttributeBindingProvider(FilesConfiguration config, INameResolver nameResolver)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            if (nameResolver == null)
            {
                throw new ArgumentNullException("nameResolver");
            }

            _config = config;
            _nameResolver = nameResolver;
        }
Esempio n. 18
0
 /// <summary>
 /// Connects the specified route.
 /// </summary>
 /// <param name="route">The route.</param>
 /// <param name="uri">The URI.</param>
 /// <param name="nameResolver">The name resolver.</param>
 /// <returns></returns>
 public static Stream Connect(this Route route, Uri uri, INameResolver nameResolver)
 {
     Stream stream = Connect(route, uri.Host, uri.Port, nameResolver).ToNetworkStream();
     try
     {
         if (stream != null && string.Equals(uri.Scheme, Uri.UriSchemeHttps, StringComparison.InvariantCultureIgnoreCase))
             stream = stream.AsSsl(uri.Host);
     }
     catch (IOException)
     {
         throw new ProxyRouteException(uri.Host);
     }
     return stream;
 }
        public QueueAttributeBindingProvider(INameResolver nameResolver, IStorageAccountProvider accountProvider,
            IContextGetter<IMessageEnqueuedWatcher> messageEnqueuedWatcherGetter)
        {
            if (accountProvider == null)
            {
                throw new ArgumentNullException("accountProvider");
            }

            if (messageEnqueuedWatcherGetter == null)
            {
                throw new ArgumentNullException("messageEnqueuedWatcherGetter");
            }

            _nameResolver = nameResolver;
            _accountProvider = accountProvider;
            _innerProvider = CreateInnerProvider(messageEnqueuedWatcherGetter);
        }
        public QueueTriggerAttributeBindingProvider(INameResolver nameResolver,
            IStorageAccountProvider accountProvider,
            IQueueConfiguration queueConfiguration,
            IBackgroundExceptionDispatcher backgroundExceptionDispatcher,
            IContextSetter<IMessageEnqueuedWatcher> messageEnqueuedWatcherSetter,
            ISharedContextProvider sharedContextProvider,
            TextWriter log)
        {
            if (accountProvider == null)
            {
                throw new ArgumentNullException("accountProvider");
            }

            if (queueConfiguration == null)
            {
                throw new ArgumentNullException("queueConfiguration");
            }

            if (backgroundExceptionDispatcher == null)
            {
                throw new ArgumentNullException("backgroundExceptionDispatcher");
            }

            if (messageEnqueuedWatcherSetter == null)
            {
                throw new ArgumentNullException("messageEnqueuedWatcherSetter");
            }

            if (sharedContextProvider == null)
            {
                throw new ArgumentNullException("sharedContextProvider");
            }

            if (log == null)
            {
                throw new ArgumentNullException("log");
            }

            _nameResolver = nameResolver;
            _accountProvider = accountProvider;
            _queueConfiguration = queueConfiguration;
            _backgroundExceptionDispatcher = backgroundExceptionDispatcher;
            _messageEnqueuedWatcherSetter = messageEnqueuedWatcherSetter;
            _sharedContextProvider = sharedContextProvider;
            _log = log;
        }
Esempio n. 21
0
 public SpecialValueResolver(IIncomingEmailMessage message, INameResolver resolver)
 {
     _resolver = resolver;
     _valueResolutionMap = new Dictionary<string, string>();
     _valueResolutionMap[SubjectKeyword] = GetValidSubject(message);
     _valueResolutionMap[SenderKeyword] = GetSender(message);
     _valueResolutionMap[MessageBodyKeyword] = TextUtils.FixLineBreaks(message.PlainTextBody);
     _valueResolutionMap[MessageBodyWithSenderKeyword] =
         String.Format("{0}\n\nCreated by: {1} ({2})", 
         _valueResolutionMap[MessageBodyKeyword], 
         message.SenderName, 
         message.SenderAddress);
     _valueResolutionMap[RawMessageBodyKeyword] = TextUtils.FixLineBreaks(message.RawBody);
     _valueResolutionMap[NowKeyword] = DateTime.Now.ToString("g");
     _valueResolutionMap[TodayKeyword] = DateTime.Now.ToString("d");
     _valueResolutionMap[LocationKeyword] = message.Location;
     _valueResolutionMap[StartTimeKeyword] = GetValidTimeString(message.StartTime);
     _valueResolutionMap[EndTimeKeyword] = GetValidTimeString(message.EndTime);
 }
Esempio n. 22
0
        /// <inheritdoc />
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            _nameResolver = context.Config.GetService <INameResolver>();
            IConverterManager converterManager = context.Config.GetService <IConverterManager>();

            // Set defaults, to be used if no other values are found:
            _defaultApiKey = _nameResolver.Resolve(AzureWebJobsMobileAppApiKeyName);

            string uriString = _nameResolver.Resolve(AzureWebJobsMobileAppUriName);

            Uri.TryCreate(uriString, UriKind.Absolute, out _defaultMobileAppUri);

            BindingFactory factory = new BindingFactory(_nameResolver, converterManager);

            IBindingProvider outputProvider = factory.BindToGenericAsyncCollector <MobileTableAttribute>(BindForOutput, ThrowIfInvalidOutputItemType);

            IBindingProvider clientProvider = factory.BindToExactType <MobileTableAttribute, IMobileServiceClient>(BindForClient);

            IBindingProvider queryProvider = factory.BindToGenericItem <MobileTableAttribute>(BindForQueryAsync);

            queryProvider = factory.AddFilter <MobileTableAttribute>(IsQueryType, queryProvider);

            IBindingProvider jObjectTableProvider = factory.BindToExactType <MobileTableAttribute, IMobileServiceTable>(BindForTable);

            IBindingProvider tableProvider = factory.BindToGenericItem <MobileTableAttribute>(BindForTableAsync);

            tableProvider = factory.AddFilter <MobileTableAttribute>(IsTableType, tableProvider);

            IBindingProvider itemProvider = factory.BindToGenericValueProvider <MobileTableAttribute>(BindForItemAsync);

            itemProvider = factory.AddFilter <MobileTableAttribute>(IsItemType, itemProvider);

            IExtensionRegistry extensions = context.Config.GetService <IExtensionRegistry>();

            extensions.RegisterBindingRules <MobileTableAttribute>(ValidateMobileAppUri, _nameResolver, outputProvider, clientProvider, jObjectTableProvider, queryProvider, tableProvider, itemProvider);
        }
        public void Initialize(ExtensionConfigContext context)
        {
            _accountProvider = context.Config.GetService <IStorageAccountProvider>();

            _blobWrittenWatcherGetter = context.PerHostServices.GetService <ContextAccessor <IBlobWrittenWatcher> >();
            _nameResolver             = context.Config.NameResolver;
            _converterManager         = context.Config.ConverterManager;

            var rule = context.AddBindingRule <BlobAttribute>();

            // Bind to multiple blobs (either via a container; a blob directory, an IEnumerable<T>)
            rule.BindToInput <CloudBlobDirectory>(this);

            rule.BindToInput <CloudBlobContainer>(this);

            rule.BindToInput <MultiBlobContext>(this); // Intermediate private context to capture state
            rule.AddOpenConverter <MultiBlobContext, IEnumerable <BlobCollectionType> >(typeof(BlobCollectionConverter <>), this);

            // BindToStream will also handle the custom Stream-->T converters.
            rule.SetPostResolveHook(ToBlobDescr).
            BindToStream(CreateStreamAsync, FileAccess.ReadWrite);     // Precedence, must beat CloudBlobStream

            // Normal blob
            // These are not converters because Blob/Page/Append affects how we *create* the blob.
            rule.SetPostResolveHook(ToBlobDescr).
            BindToInput <CloudBlockBlob>((attr, cts) => CreateBlobReference <CloudBlockBlob>(attr, cts));

            rule.SetPostResolveHook(ToBlobDescr).
            BindToInput <CloudPageBlob>((attr, cts) => CreateBlobReference <CloudPageBlob>(attr, cts));

            rule.SetPostResolveHook(ToBlobDescr).
            BindToInput <CloudAppendBlob>((attr, cts) => CreateBlobReference <CloudAppendBlob>(attr, cts));

            rule.SetPostResolveHook(ToBlobDescr).
            BindToInput <ICloudBlob>((attr, cts) => CreateBlobReference <ICloudBlob>(attr, cts));

            // CloudBlobStream's derived functionality is only relevant to writing.
            rule.When("Access", FileAccess.Write).
            SetPostResolveHook(ToBlobDescr).
            BindToInput <CloudBlobStream>(ConvertToCloudBlobStreamAsync);
        }
Esempio n. 24
0
 public KafkaAttributeBinding(
     string parameterName,
     KafkaAttribute attribute,
     IKafkaProducerFactory kafkaProducerFactory,
     IArgumentBinding <KafkaProducerEntity> argumentBinding,
     Type keyType,
     Type valueType,
     string avroSchema,
     IConfiguration config,
     INameResolver nameResolver)
 {
     this.parameterName        = parameterName;
     this.attribute            = attribute ?? throw new ArgumentNullException(nameof(attribute));
     this.kafkaProducerFactory = kafkaProducerFactory ?? throw new ArgumentNullException(nameof(kafkaProducerFactory));
     this.argumentBinding      = argumentBinding ?? throw new ArgumentNullException(nameof(argumentBinding));
     this.keyType      = keyType;
     this.valueType    = valueType ?? throw new ArgumentNullException(nameof(valueType));
     this.avroSchema   = avroSchema;
     this.config       = config;
     this.nameResolver = nameResolver;
 }
 public BlobsExtensionConfigProvider(
     BlobServiceClientProvider blobServiceClientProvider,
     BlobTriggerAttributeBindingProvider triggerBinder,
     IContextGetter <IBlobWrittenWatcher> contextAccessor,
     INameResolver nameResolver,
     IConverterManager converterManager,
     BlobTriggerQueueWriterFactory blobTriggerQueueWriterFactory,
     HttpRequestProcessor httpRequestProcessor,
     IFunctionDataCache functionDataCache,
     ILoggerFactory loggerFactory)
 {
     _blobServiceClientProvider = blobServiceClientProvider;
     _triggerBinder             = triggerBinder;
     _blobWrittenWatcherGetter  = contextAccessor;
     _nameResolver     = nameResolver;
     _converterManager = converterManager;
     _blobTriggerQueueWriterFactory = blobTriggerQueueWriterFactory;
     _httpRequestProcessor          = httpRequestProcessor;
     _functionDataCache             = functionDataCache;
     _logger = loggerFactory.CreateLogger <BlobsExtensionConfigProvider>();
 }
Esempio n. 26
0
        /// <inheritdoc />
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // get the services we need to construct our binding providers
            INameResolver      nameResolver = context.Config.GetService <INameResolver>();
            IExtensionRegistry extensions   = context.Config.GetService <IExtensionRegistry>();

            // register our trigger binding provider
            ServiceBusTriggerAttributeBindingProvider triggerBindingProvider = new ServiceBusTriggerAttributeBindingProvider(nameResolver, _serviceBusConfig);

            extensions.RegisterExtension <ITriggerBindingProvider>(triggerBindingProvider);

            // register our binding provider
            ServiceBusAttributeBindingProvider bindingProvider = new ServiceBusAttributeBindingProvider(nameResolver, _serviceBusConfig);

            extensions.RegisterExtension <IBindingProvider>(bindingProvider);
        }
        public FtpAttributeBindingProvider(FtpConfiguration config, INameResolver nameResolver, TraceWriter trace)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

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

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

            _config       = config;
            _nameResolver = nameResolver;
            _trace        = trace;
        }
Esempio n. 28
0
        /// <inheritdoc />
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            INameResolver nameResolver = context.Config.GetService <INameResolver>();

            // Use this if there is no other connection string set.
            _defaultConnectionString = nameResolver.Resolve(AzureWebJobsCosmosDBConnectionStringName);

            // Apply ValidateConnection to all on this rule.
            var rule = context.AddBindingRule <CosmosDBAttribute>();

            rule.AddValidator(ValidateConnection);
            rule.BindToCollector <DocumentOpenType>(typeof(CosmosDBCollectorBuilder <>), this);

            rule.BindToInput <DocumentClient>(new CosmosDBClientBuilder(this));

            // Enumerable inputs
            rule.WhenIsNull(nameof(CosmosDBAttribute.Id))
            .BindToInput <JArray>(typeof(CosmosDBJArrayBuilder), this);

            rule.WhenIsNull(nameof(CosmosDBAttribute.Id))
            .BindToInput <IEnumerable <DocumentOpenType> >(typeof(CosmosDBEnumerableBuilder <>), this);

            // Single input
            rule.WhenIsNotNull(nameof(CosmosDBAttribute.Id))
            .WhenIsNull(nameof(CosmosDBAttribute.SqlQuery))
            .BindToValueProvider <DocumentOpenType>((attr, t) => BindForItemAsync(attr, t));

            // Trigger
            var rule2 = context.AddBindingRule <CosmosDBTriggerAttribute>();

            rule2.BindToTrigger <IReadOnlyList <Document> >(new CosmosDBTriggerAttributeBindingProvider(nameResolver, this, LeaseOptions));
            rule2.AddConverter <string, IReadOnlyList <Document> >(str => JsonConvert.DeserializeObject <IReadOnlyList <Document> >(str));
            rule2.AddConverter <IReadOnlyList <Document>, JArray>(docList => JArray.FromObject(docList));
            rule2.AddConverter <IReadOnlyList <Document>, string>(docList => JArray.FromObject(docList).ToString());
        }
        public static TestJobHost <TProgram> Create <TProgram>(CloudStorageAccount storageAccount, int maxDequeueCount)
        {
            IStorageAccountProvider storageAccountProvider = new SimpleStorageAccountProvider
            {
                StorageAccount = storageAccount,
                // use null logging string since unit tests don't need logs.
                DashboardAccount = null
            };
            IServiceBusAccountProvider serviceBusAccountProvider = new NullServiceBusAccountProvider();
            IExtensionTypeLocator      extensionTypeLocator      = new NullExtensionTypeLocator();
            IHostIdProvider            hostIdProvider            = new FixedHostIdProvider("test");
            INameResolver       nameResolver       = null;
            IQueueConfiguration queueConfiguration = new SimpleQueueConfiguration(maxDequeueCount);
            ContextAccessor <IMessageEnqueuedWatcher> messageEnqueuedWatcherAccessor =
                new ContextAccessor <IMessageEnqueuedWatcher>();
            ContextAccessor <IBlobWrittenWatcher> blobWrittenWatcherAccessor =
                new ContextAccessor <IBlobWrittenWatcher>();
            ISharedContextProvider sharedContextProvider = new SharedContextProvider();

            IJobHostContextFactory contextFactory = new TestJobHostContextFactory
            {
                FunctionIndexProvider = new FunctionIndexProvider(new FakeTypeLocator(typeof(TProgram)),
                                                                  DefaultTriggerBindingProvider.Create(nameResolver, storageAccountProvider,
                                                                                                       serviceBusAccountProvider, extensionTypeLocator, hostIdProvider, queueConfiguration,
                                                                                                       BackgroundExceptionDispatcher.Instance, messageEnqueuedWatcherAccessor,
                                                                                                       blobWrittenWatcherAccessor, sharedContextProvider, TextWriter.Null),
                                                                  DefaultBindingProvider.Create(nameResolver, storageAccountProvider, serviceBusAccountProvider,
                                                                                                extensionTypeLocator, messageEnqueuedWatcherAccessor, blobWrittenWatcherAccessor),
                                                                  DefaultJobActivator.Instance),
                StorageAccountProvider = storageAccountProvider,
                Queues = queueConfiguration
            };

            IServiceProvider serviceProvider = new TestJobHostConfiguration
            {
                ContextFactory = contextFactory
            };

            return(new TestJobHost <TProgram>(serviceProvider));
        }
        public static FunctionIndexer Create(CloudStorageAccount account = null, INameResolver nameResolver = null, IExtensionRegistry extensionRegistry = null)
        {
            Mock <IServiceProvider> services      = new Mock <IServiceProvider>(MockBehavior.Strict);
            StorageClientFactory    clientFactory = new StorageClientFactory();

            services.Setup(p => p.GetService(typeof(StorageClientFactory))).Returns(clientFactory);
            IStorageAccount         storageAccount         = account != null ? new StorageAccount(account, services.Object) : null;
            IStorageAccountProvider storageAccountProvider = new SimpleStorageAccountProvider(services.Object)
            {
                StorageAccount = account
            };
            IExtensionTypeLocator extensionTypeLocator = new NullExtensionTypeLocator();
            ContextAccessor <IMessageEnqueuedWatcher> messageEnqueuedWatcherAccessor =
                new ContextAccessor <IMessageEnqueuedWatcher>();
            ContextAccessor <IBlobWrittenWatcher> blobWrittenWatcherAccessor =
                new ContextAccessor <IBlobWrittenWatcher>();
            ISharedContextProvider  sharedContextProvider = new SharedContextProvider();
            TestTraceWriter         logger                 = new TestTraceWriter(TraceLevel.Verbose);
            SingletonManager        singletonManager       = new SingletonManager();
            ITriggerBindingProvider triggerBindingProvider = DefaultTriggerBindingProvider.Create(nameResolver,
                                                                                                  storageAccountProvider, extensionTypeLocator,
                                                                                                  new FixedHostIdProvider("test"), new SimpleQueueConfiguration(maxDequeueCount: 5),
                                                                                                  BackgroundExceptionDispatcher.Instance, messageEnqueuedWatcherAccessor, blobWrittenWatcherAccessor,
                                                                                                  sharedContextProvider, new DefaultExtensionRegistry(), singletonManager, logger);
            IBindingProvider bindingProvider = DefaultBindingProvider.Create(nameResolver, storageAccountProvider,
                                                                             extensionTypeLocator, messageEnqueuedWatcherAccessor,
                                                                             blobWrittenWatcherAccessor, new DefaultExtensionRegistry());

            TraceWriter trace = new TestTraceWriter(TraceLevel.Verbose);
            IFunctionOutputLoggerProvider outputLoggerProvider = new NullFunctionOutputLoggerProvider();
            IFunctionOutputLogger         outputLogger         = outputLoggerProvider.GetAsync(CancellationToken.None).Result;
            IFunctionExecutor             executor             = new FunctionExecutor(new NullFunctionInstanceLogger(), outputLogger, BackgroundExceptionDispatcher.Instance, trace, null);

            if (extensionRegistry == null)
            {
                extensionRegistry = new DefaultExtensionRegistry();
            }

            return(new FunctionIndexer(triggerBindingProvider, bindingProvider, DefaultJobActivator.Instance, executor, extensionRegistry, new SingletonManager(), trace));
        }
Esempio n. 31
0
        internal static TimerSchedule Create(TimerTriggerAttribute attribute, INameResolver nameResolver, ILogger logger)
        {
            TimerSchedule schedule = null;

            if (!string.IsNullOrEmpty(attribute.ScheduleExpression))
            {
                string resolvedExpression = nameResolver.ResolveWholeString(attribute.ScheduleExpression);
                if (CronSchedule.TryCreate(resolvedExpression, out CronSchedule cronSchedule))
                {
                    schedule = cronSchedule;
                    if (attribute.UseMonitor && ShouldDisableScheduleMonitor(cronSchedule, DateTime.Now))
                    {
                        logger.LogDebug("UseMonitor changed to false based on schedule frequency.");
                        attribute.UseMonitor = false;
                    }
                }
                else if (TimeSpan.TryParse(resolvedExpression, out TimeSpan periodTimespan))
                {
                    schedule = new ConstantSchedule(periodTimespan);

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

            return(schedule);
        }
        internal void Validate(INameResolver environmentVariableResolver, EndToEndTraceHelper traceHelper)
        {
            if (string.IsNullOrEmpty(this.HubName))
            {
                throw new InvalidOperationException($"A non-empty {nameof(this.HubName)} configuration is required.");
            }

            if (IsInNonProductionSlot() && this.IsDefaultHubName())
            {
                throw new InvalidOperationException($"Task Hub name must be specified in host.json when using slots. Specified name must not equal the default HubName ({this.defaultHubName})." +
                                                    "See documentation on Task Hubs for information on how to set this: https://docs.microsoft.com/azure/azure-functions/durable/durable-functions-task-hubs");
            }

            string runtimeLanguage = environmentVariableResolver.Resolve("FUNCTIONS_WORKER_RUNTIME");

            if (this.ExtendedSessionsEnabled &&
                runtimeLanguage != null && // If we don't know from the environment variable, don't assume customer isn't .NET
                !string.Equals(runtimeLanguage, "dotnet", StringComparison.OrdinalIgnoreCase))
            {
                traceHelper.ExtensionWarningEvent(
                    hubName: this.HubName,
                    functionName: string.Empty,
                    instanceId: string.Empty,
                    message: "Durable Functions does not work with extendedSessions = true for non-.NET languages. This value is being set to false instead. See https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-perf-and-scale#extended-sessions for more details.");
                this.ExtendedSessionsEnabled = false;
            }

            this.Notifications.Validate();

            if (this.MaxConcurrentActivityFunctions <= 0)
            {
                throw new InvalidOperationException($"{nameof(this.MaxConcurrentActivityFunctions)} must be a non-negative integer value.");
            }

            if (this.MaxConcurrentOrchestratorFunctions <= 0)
            {
                throw new InvalidOperationException($"{nameof(this.MaxConcurrentOrchestratorFunctions)} must be a non-negative integer value.");
            }
        }
Esempio n. 33
0
        /// <inheritdoc />
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            INameResolver     nameResolver     = context.Config.GetService <INameResolver>();
            IConverterManager converterManager = context.Config.GetService <IConverterManager>();

            BindingFactory factory = new BindingFactory(nameResolver, converterManager);

            IBindingProvider outputProvider = factory.BindToGenericAsyncCollector <DocumentDBAttribute>((attr, t) => BindForOutput(attr, t, context.Trace));

            IBindingProvider clientProvider = factory.BindToExactType <DocumentDBAttribute, DocumentClient>(BindForClient);

            IBindingProvider itemProvider = factory.BindToGenericValueProvider <DocumentDBAttribute>((attr, t) => BindForItemAsync(attr, t, context.Trace));

            IExtensionRegistry extensions = context.Config.GetService <IExtensionRegistry>();

            extensions.RegisterBindingRules <DocumentDBAttribute>(ValidateConnection, nameResolver, outputProvider, clientProvider, itemProvider);
        }
Esempio n. 34
0
        public BlobAttributeBindingProvider(INameResolver nameResolver, IStorageAccountProvider accountProvider,
                                            IExtensionTypeLocator extensionTypeLocator, IContextGetter <IBlobWrittenWatcher> blobWrittenWatcherGetter)
        {
            if (accountProvider == null)
            {
                throw new ArgumentNullException("accountProvider");
            }

            if (extensionTypeLocator == null)
            {
                throw new ArgumentNullException("extensionTypeLocator");
            }

            if (blobWrittenWatcherGetter == null)
            {
                throw new ArgumentNullException("blobWrittenWatcherGetter");
            }

            _nameResolver    = nameResolver;
            _accountProvider = accountProvider;
            _provider        = CreateProvider(extensionTypeLocator.GetCloudBlobStreamBinderTypes(), blobWrittenWatcherGetter);
        }
Esempio n. 35
0
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            INameResolver nameResolver = context.Config.GetService <INameResolver>();

            _defaultAccountSid = nameResolver.Resolve(AzureWebJobsTwilioAccountSidKeyName);
            _defaultAuthToken  = nameResolver.Resolve(AzureWebJobsTwilioAccountAuthTokenName);

            context.AddConverter <JObject, CreateMessageOptions>(CreateMessageOptions);

            var rule = context.AddBindingRule <TwilioSmsAttribute>();

            rule.AddValidator(ValidateBinding);
            rule.BindToCollector <CreateMessageOptions>((attr) =>
            {
                return(new TwilioSmsMessageAsyncCollector(CreateContext(attr)));
            });
        }
 public JobHostContextFactory(
     IDashboardLoggingSetup dashboardLoggingSetup,
     IFunctionExecutor functionExecutor,
     IFunctionIndexProvider functionIndexProvider,
     ITriggerBindingProvider triggerBindingProvider,
     SingletonManager singletonManager,
     IJobActivator activator,
     IHostIdProvider hostIdProvider,
     INameResolver nameResolver,
     IExtensionRegistry extensions,
     ILoggerFactory loggerFactory,
     IWebJobsExceptionHandler exceptionHandler,
     SharedQueueHandler sharedQueueHandler,
     IOptions <JobHostOptions> jobHostOptions,
     IHostInstanceLogger hostInstanceLogger,
     IFunctionInstanceLogger functionInstanceLogger,
     IFunctionOutputLogger functionOutputLogger,
     IConverterManager converterManager,
     IAsyncCollector <FunctionInstanceLogEntry> eventCollector)
 {
     _dashboardLoggingSetup  = dashboardLoggingSetup;
     _functionExecutor       = functionExecutor;
     _functionIndexProvider  = functionIndexProvider;
     _triggerBindingProvider = triggerBindingProvider;
     _singletonManager       = singletonManager;
     _activator              = activator;
     _hostIdProvider         = hostIdProvider;
     _nameResolver           = nameResolver;
     _extensions             = extensions;
     _loggerFactory          = loggerFactory;
     _exceptionHandler       = exceptionHandler;
     _sharedQueueHandler     = sharedQueueHandler;
     _jobHostOptions         = jobHostOptions;
     _hostInstanceLogger     = hostInstanceLogger;
     _functionInstanceLogger = functionInstanceLogger;
     _functionOutputLogger   = functionOutputLogger;
     _converterManager       = converterManager;
     _eventCollector         = eventCollector;
 }
        public static FunctionIndexer Create(CloudStorageAccount account = null, INameResolver nameResolver = null, IExtensionRegistry extensionRegistry = null)
        {
            Mock<IServiceProvider> services = new Mock<IServiceProvider>(MockBehavior.Strict);
            StorageClientFactory clientFactory = new StorageClientFactory();
            services.Setup(p => p.GetService(typeof(StorageClientFactory))).Returns(clientFactory);
            IStorageAccount storageAccount = account != null ? new StorageAccount(account, services.Object) : null;
            IStorageAccountProvider storageAccountProvider = new SimpleStorageAccountProvider(services.Object)
            {
                StorageAccount = account
            };
            IExtensionTypeLocator extensionTypeLocator = new NullExtensionTypeLocator();
            ContextAccessor<IMessageEnqueuedWatcher> messageEnqueuedWatcherAccessor =
                new ContextAccessor<IMessageEnqueuedWatcher>();
            ContextAccessor<IBlobWrittenWatcher> blobWrittenWatcherAccessor =
                new ContextAccessor<IBlobWrittenWatcher>();
            ISharedContextProvider sharedContextProvider = new SharedContextProvider();
            TestTraceWriter logger = new TestTraceWriter(TraceLevel.Verbose);
            SingletonManager singletonManager = new SingletonManager();
            ITriggerBindingProvider triggerBindingProvider = DefaultTriggerBindingProvider.Create(nameResolver,
                storageAccountProvider, extensionTypeLocator,
                new FixedHostIdProvider("test"), new SimpleQueueConfiguration(maxDequeueCount: 5),
                BackgroundExceptionDispatcher.Instance, messageEnqueuedWatcherAccessor, blobWrittenWatcherAccessor,
                sharedContextProvider, new DefaultExtensionRegistry(), singletonManager, logger);
            IBindingProvider bindingProvider = DefaultBindingProvider.Create(nameResolver, storageAccountProvider,
                extensionTypeLocator, messageEnqueuedWatcherAccessor,
                blobWrittenWatcherAccessor, new DefaultExtensionRegistry());

            TraceWriter trace = new TestTraceWriter(TraceLevel.Verbose);
            IFunctionOutputLoggerProvider outputLoggerProvider = new NullFunctionOutputLoggerProvider();
            IFunctionOutputLogger outputLogger = outputLoggerProvider.GetAsync(CancellationToken.None).Result;
            IFunctionExecutor executor = new FunctionExecutor(new NullFunctionInstanceLogger(), outputLogger, BackgroundExceptionDispatcher.Instance, trace, null);

            if (extensionRegistry == null)
            {
                extensionRegistry = new DefaultExtensionRegistry();
            }

            return new FunctionIndexer(triggerBindingProvider, bindingProvider, DefaultJobActivator.Instance, executor, extensionRegistry, new SingletonManager(), trace);
        }
Esempio n. 38
0
        /// <summary>
        /// Execute the transfer asynchronously.
        /// </summary>
        /// <param name="scheduler">Transfer scheduler</param>
        /// <param name="cancellationToken">Token that can be used to cancel the transfer.</param>
        /// <returns>A task representing the transfer operation.</returns>
        public override async Task ExecuteAsync(TransferScheduler scheduler, CancellationToken cancellationToken)
        {
            try
            {
                this.Destination.Validate();
            }
            catch (StorageException se)
            {
                throw new TransferException(TransferErrorCode.FailToVadlidateDestination,
                                            Resources.FailedToValidateDestinationException,
                                            se);
            }
            catch (Exception ex)
            {
                throw new TransferException(TransferErrorCode.FailToVadlidateDestination,
                                            Resources.FailedToValidateDestinationException,
                                            ex);
            }

            this.nameResolver = GetNameResolver(this.Source, this.Destination, this.Delimiter);
            await this.ExecuteInternalAsync(scheduler, cancellationToken);
        }
        internal static bool IsDisabled(MethodInfo method, INameResolver nameResolver, IJobActivator activator)
        {
            // First try to resolve disabled state by setting
            string settingName = string.Format(CultureInfo.InvariantCulture, "AzureWebJobs.{0}.Disabled", Utility.GetFunctionName(method));

            if (ConfigurationUtility.IsSettingEnabled(settingName))
            {
                return(true);
            }
            else
            {
                // Second try to resolve disabled state by attribute
                ParameterInfo triggerParameter = method.GetParameters().FirstOrDefault();
                if (triggerParameter != null)
                {
                    // look for the first DisableAttribute up the hierarchy
                    DisableAttribute disableAttribute = TypeUtility.GetHierarchicalAttributeOrNull <DisableAttribute>(triggerParameter);
                    if (disableAttribute != null)
                    {
                        if (!string.IsNullOrEmpty(disableAttribute.SettingName))
                        {
                            return(IsDisabledBySetting(disableAttribute.SettingName, method, nameResolver));
                        }
                        else if (disableAttribute.ProviderType != null)
                        {
                            // a custom provider Type has been specified
                            return(IsDisabledByProvider(disableAttribute.ProviderType, method, activator));
                        }
                        else
                        {
                            // the default constructor was used
                            return(true);
                        }
                    }
                }

                return(false);
            }
        }
Esempio n. 40
0
        // TODO: Benchmark whether it would be beneficial to pass the unchanging parameters to the private methods
        //       in a readonly struct. We pass a lot of parameters and the call trees run quite deep.

        /// <summary>
        /// Compiles the given expression syntax tree and verifies its type.
        /// Returns the local index if successful, returns -1 and logs diagnostics if the compilation fails.
        /// </summary>
        /// <param name="syntax">The root of the expression syntax tree.</param>
        /// <param name="expectedType">The expected type of the evaluated expression. If null, the type is not checked.</param>
        /// <param name="method">The method to store and get local values from.</param>
        /// <param name="builder">Intermediate representation builder.</param>
        /// <param name="nameResolver">The resolver for variable and method names.</param>
        /// <param name="diagnostics">Receiver for possible diagnostics.</param>
        public static int TryCompileExpression(
            ExpressionSyntax syntax,
            TypeDefinition?expectedType,
            CompiledMethod method,
            BasicBlockBuilder builder,
            INameResolver nameResolver,
            IDiagnosticSink diagnostics)
        {
            // Compile the expression
            if (!InternalTryCompileExpression(syntax, method, builder, nameResolver, diagnostics, out var value))
            {
                return(-1);
            }

            // Verify the type
            // TODO: Once multiple integer types exist, there must be some notion of conversions
            if (expectedType != null && !value.Type.Equals(expectedType))
            {
                diagnostics.Add(DiagnosticCode.TypeMismatch, syntax.Position,
                                value.Type.TypeName, expectedType.TypeName);
                return(-1);
            }

            // Also, if the expression is constant, verify that it is representable
            if (!value.LocalIndex.HasValue && value.Type.Equals(SimpleType.Int32))
            {
                if (value.ConstantValue.AsSignedInteger < int.MinValue ||
                    value.ConstantValue.AsSignedInteger > int.MaxValue)
                {
                    diagnostics.Add(DiagnosticCode.IntegerConstantOutOfBounds, syntax.Position,
                                    value.ConstantValue.ToString(), SimpleType.Int32.TypeName);
                    return(-1);
                }
            }

            // Store the value in a local
            return(EnsureValueIsStored(value, method, builder));
        }
        // Expose internally for testing purposes
        internal static FunctionDescriptor FromMethod(
            MethodInfo method,
            IJobActivator jobActivator      = null,
            INameResolver nameResolver      = null,
            TimeoutAttribute defaultTimeout = null)
        {
            var disabled = HostListenerFactory.IsDisabled(method, nameResolver, jobActivator);

            bool hasCancellationToken = method.GetParameters().Any(p => p.ParameterType == typeof(CancellationToken));

            string logName   = method.Name;
            string shortName = method.GetShortName();
            FunctionNameAttribute nameAttribute = method.GetCustomAttribute <FunctionNameAttribute>();

            if (nameAttribute != null)
            {
                logName   = nameAttribute.Name;
                shortName = logName;
                if (!FunctionNameAttribute.FunctionNameValidationRegex.IsMatch(logName))
                {
                    throw new InvalidOperationException(string.Format("'{0}' is not a valid function name.", logName));
                }
            }

            return(new FunctionDescriptor
            {
                Id = method.GetFullName(),
                LogName = logName,
                FullName = method.GetFullName(),
                ShortName = shortName,
                IsDisabled = disabled,
                HasCancellationToken = hasCancellationToken,
                TimeoutAttribute = TypeUtility.GetHierarchicalAttributeOrNull <TimeoutAttribute>(method) ?? defaultTimeout,
                SingletonAttributes = method.GetCustomAttributes <SingletonAttribute>(),
                MethodLevelFilters = method.GetCustomAttributes().OfType <IFunctionFilter>(),
                ClassLevelFilters = method.DeclaringType.GetCustomAttributes().OfType <IFunctionFilter>()
            });
        }
        public static JobHost CreateJobHost(
            IOptions <DurableTaskOptions> options,
            ILoggerProvider loggerProvider,
            INameResolver nameResolver)
        {
            var config = new JobHostConfiguration {
                HostId = "durable-task-host"
            };

            config.TypeLocator = TestHelpers.GetTypeLocator();

            var connectionResolver = new WebJobsConnectionStringProvider();

            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(loggerProvider);

            var extension = new DurableTaskExtension(options, loggerFactory, nameResolver, connectionResolver);

            config.UseDurableTask(extension);

            // Mock INameResolver for not setting EnvironmentVariables.
            if (nameResolver != null)
            {
                config.AddService(nameResolver);
            }

            // Performance is *significantly* worse when dashboard logging is enabled, at least
            // when running in the storage emulator. Disabling to keep tests running quickly.
            config.DashboardConnectionString = null;

            // Add test logger
            config.LoggerFactory = loggerFactory;

            var host = new JobHost(config);

            return(host);
        }
Esempio n. 43
0
        /// <inheritdoc />
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            _trace = context.Trace;

            INameResolver nameResolver = context.Config.GetService <INameResolver>();

            IConverterManager converterManager = context.Config.GetService <IConverterManager>();

            // Use this if there is no other connection string set.
            _defaultConnectionString = nameResolver.Resolve(AzureWebJobsDocumentDBConnectionStringName);

            BindingFactory factory = new BindingFactory(nameResolver, converterManager);

            IBindingProvider outputProvider = factory.BindToCollector <DocumentDBAttribute, OpenType>(typeof(DocumentDBCollectorBuilder <>), this);

            IBindingProvider clientProvider = factory.BindToInput <DocumentDBAttribute, DocumentClient>(new DocumentDBClientBuilder(this));

            IBindingProvider jArrayProvider = factory.BindToInput <DocumentDBAttribute, JArray>(typeof(DocumentDBJArrayBuilder), this);

            IBindingProvider enumerableProvider = factory.BindToInput <DocumentDBAttribute, IEnumerable <OpenType> >(typeof(DocumentDBEnumerableBuilder <>), this);

            enumerableProvider = factory.AddValidator <DocumentDBAttribute>(ValidateInputBinding, enumerableProvider);

            IBindingProvider inputProvider = factory.BindToGenericValueProvider <DocumentDBAttribute>((attr, t) => BindForItemAsync(attr, t));

            inputProvider = factory.AddValidator <DocumentDBAttribute>(ValidateInputBinding, inputProvider);

            IExtensionRegistry extensions = context.Config.GetService <IExtensionRegistry>();

            extensions.RegisterBindingRules <DocumentDBAttribute>(ValidateConnection, nameResolver, outputProvider, clientProvider, jArrayProvider, enumerableProvider, inputProvider);

            context.Config.RegisterBindingExtensions(new CosmosDBTriggerAttributeBindingProvider(nameResolver, LeaseOptions));
        }
        // transforms binding data to appropriate resolver (appsetting, autoresolve, or originalValue)
        private BindingDataResolver GetResolver(PropertyInfo propInfo, INameResolver nameResolver, BindingDataContract contract)
        {
            // Do the attribute lookups once upfront, and then cache them (via func closures) for subsequent runtime usage.
            object originalValue = propInfo.GetValue(_source);
            AppSettingAttribute  appSettingAttr  = propInfo.GetCustomAttribute <AppSettingAttribute>();
            AutoResolveAttribute autoResolveAttr = propInfo.GetCustomAttribute <AutoResolveAttribute>();
            Validator            validator       = GetValidatorFunc(propInfo, appSettingAttr != null);

            if (appSettingAttr == null && autoResolveAttr == null)
            {
                validator(originalValue);

                // No special attributes, treat as literal.
                return((newAttr, bindingData) => originalValue);
            }

            if (appSettingAttr != null && autoResolveAttr != null)
            {
                throw new InvalidOperationException($"Property '{propInfo.Name}' cannot be annotated with both AppSetting and AutoResolve.");
            }

            // attributes only work on string properties.
            if (propInfo.PropertyType != typeof(string))
            {
                throw new InvalidOperationException($"AutoResolve or AppSetting property '{propInfo.Name}' must be of type string.");
            }
            var str = (string)originalValue;

            // first try to resolve with app setting
            if (appSettingAttr != null)
            {
                return(GetAppSettingResolver(str, appSettingAttr, nameResolver, propInfo, validator));
            }

            // Must have an [AutoResolve]
            // try to resolve with auto resolve ({...}, %...%)
            return(GetAutoResolveResolver(str, autoResolveAttr, nameResolver, propInfo, contract, validator));
        }
        public static IBindingProvider Create(
            INameResolver nameResolver,
            ILoggerFactory loggerFactory,
            IStorageAccountProvider storageAccountProvider,
            IExtensionTypeLocator extensionTypeLocator,
            IContextGetter <IBlobWrittenWatcher> blobWrittenWatcherGetter,
            IExtensionRegistry extensions)
        {
            List <IBindingProvider> innerProviders = new List <IBindingProvider>();

            innerProviders.Add(new BlobAttributeBindingProvider(nameResolver, storageAccountProvider, extensionTypeLocator, blobWrittenWatcherGetter));

            // add any registered extension binding providers
            // Queue and Table bindings were added as an extension, so those rules get included here.
            foreach (IBindingProvider provider in extensions.GetExtensions(typeof(IBindingProvider)))
            {
                innerProviders.Add(provider);
            }

            innerProviders.Add(new CloudStorageAccountBindingProvider(storageAccountProvider));
            innerProviders.Add(new CancellationTokenBindingProvider());

            // The TraceWriter binder handles all remaining TraceWriter/TextWriter parameters. It must come after the
            // Blob binding provider; otherwise bindings like Do([Blob("a/b")] TextWriter blob) wouldn't work.
            innerProviders.Add(new TraceWriterBindingProvider(loggerFactory));

            innerProviders.Add(new LoggerBindingProvider(loggerFactory));

            ContextAccessor <IBindingProvider> bindingProviderAccessor = new ContextAccessor <IBindingProvider>();

            innerProviders.Add(new RuntimeBindingProvider(bindingProviderAccessor));
            innerProviders.Add(new DataBindingProvider());

            IBindingProvider bindingProvider = new CompositeBindingProvider(innerProviders);

            bindingProviderAccessor.SetValue(bindingProvider);
            return(bindingProvider);
        }
Esempio n. 46
0
 public FunctionIndexer(
     ITriggerBindingProvider triggerBindingProvider,
     IBindingProvider bindingProvider,
     IJobActivator activator,
     IFunctionExecutor executor,
     SingletonManager singletonManager,
     ILoggerFactory loggerFactory,
     INameResolver nameResolver      = null,
     SharedQueueHandler sharedQueue  = null,
     TimeoutAttribute defaultTimeout = null,
     bool allowPartialHostStartup    = false)
 {
     _triggerBindingProvider = triggerBindingProvider ?? throw new ArgumentNullException(nameof(triggerBindingProvider));
     _bindingProvider        = bindingProvider ?? throw new ArgumentNullException(nameof(bindingProvider));
     _activator               = activator ?? throw new ArgumentNullException(nameof(activator));
     _executor                = executor ?? throw new ArgumentNullException(nameof(executor));
     _singletonManager        = singletonManager ?? throw new ArgumentNullException(nameof(singletonManager));
     _nameResolver            = nameResolver;
     _logger                  = loggerFactory?.CreateLogger(LogCategories.Startup);
     _sharedQueue             = sharedQueue;
     _defaultTimeout          = defaultTimeout;
     _allowPartialHostStartup = allowPartialHostStartup;
 }
        // Helper to do the indexing.
        private static Tuple<FunctionDescriptor, IFunctionDefinition> IndexMethod(string methodName, INameResolver nameResolver = null)
        {
            MethodInfo method = typeof(FunctionIndexerIntegrationTests).GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
            Assert.NotNull(method);

            FunctionIndexer indexer = FunctionIndexerFactory.Create(CloudStorageAccount.DevelopmentStorageAccount,
                nameResolver);

            Tuple<FunctionDescriptor, IFunctionDefinition> indexEntry = null;
            Mock<IFunctionIndexCollector> indexMock = new Mock<IFunctionIndexCollector>(MockBehavior.Strict);
            indexMock
                .Setup((i) => i.Add(
                    It.IsAny<IFunctionDefinition>(),
                    It.IsAny<FunctionDescriptor>(),
                    It.IsAny<MethodInfo>()))
                .Callback<IFunctionDefinition, FunctionDescriptor, MethodInfo>(
                    (ifd, fd, i) => indexEntry = Tuple.Create(fd, ifd));
            IFunctionIndexCollector index = indexMock.Object;

            indexer.IndexMethodAsync(method, index, CancellationToken.None).GetAwaiter().GetResult();

            return indexEntry;
        }
Esempio n. 48
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DurableTaskExtension"/>.
        /// </summary>
        /// <param name="options">The configuration options for this extension.</param>
        /// <param name="loggerFactory">The logger factory used for extension-specific logging and orchestration tracking.</param>
        /// <param name="nameResolver">The name resolver to use for looking up application settings.</param>
        /// <param name="connectionStringResolver">The resolver to use for looking up connection strings.</param>
        public DurableTaskExtension(
            IOptions <DurableTaskOptions> options,
            ILoggerFactory loggerFactory,
            INameResolver nameResolver,
            IConnectionStringResolver connectionStringResolver)
        {
            // Options will be null in Functions v1 runtime - populated later.
            this.Options                  = options?.Value ?? new DurableTaskOptions();
            this.nameResolver             = nameResolver ?? throw new ArgumentNullException(nameof(nameResolver));
            this.connectionStringResolver = connectionStringResolver ?? throw new ArgumentNullException(nameof(connectionStringResolver));

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

            ILogger logger = loggerFactory.CreateLogger(LoggerCategoryName);

            this.TraceHelper    = new EndToEndTraceHelper(logger, this.Options.LogReplayEvents);
            this.HttpApiHandler = new HttpApiHandler(this, logger);
            this.LifeCycleNotificationHelper = this.CreateLifeCycleNotificationHelper();
            this.isOptionsConfigured         = true;
        }
Esempio n. 49
0
 public virtual void SetAppSettings(INameResolver appSettings)
 {
     if (HostName == null)
     {
         HostName = appSettings.Resolve(Constants.WebsiteHostname);
     }
     if (ClientId == null)
     {
         ClientId = appSettings.Resolve(Constants.ClientIdName);
     }
     if (ClientSecret == null)
     {
         ClientSecret = appSettings.Resolve(Constants.ClientSecretName);
     }
     if (TenantUrl == null)
     {
         TenantUrl = appSettings.Resolve(Constants.WebsiteAuthOpenIdIssuer);
     }
     if (SigningKey == null)
     {
         SigningKey = appSettings.Resolve(Constants.WebsiteAuthSigningKey);
     }
 }
        public static JobHost CreateJobHost(
            IOptions <DurableTaskOptions> options,
            string storageProvider,
            ILoggerProvider loggerProvider,
            INameResolver nameResolver,
            IDurableHttpMessageHandlerFactory durableHttpMessageHandler,
            ILifeCycleNotificationHelper lifeCycleNotificationHelper)
        {
            IHost host = new HostBuilder()
                         .ConfigureLogging(
                loggingBuilder =>
            {
                loggingBuilder.AddProvider(loggerProvider);
            })
                         .ConfigureWebJobs(
                webJobsBuilder =>
            {
                webJobsBuilder.AddDurableTask(options, storageProvider);
                webJobsBuilder.AddAzureStorage();
            })
                         .ConfigureServices(
                serviceCollection =>
            {
                ITypeLocator typeLocator = TestHelpers.GetTypeLocator();
                serviceCollection.AddSingleton(typeLocator);
                serviceCollection.AddSingleton(nameResolver);
                serviceCollection.AddSingleton(durableHttpMessageHandler);

                if (lifeCycleNotificationHelper != null)
                {
                    serviceCollection.AddSingleton(lifeCycleNotificationHelper);
                }
            })
                         .Build();

            return((JobHost)host.Services.GetService <IJobHost>());
        }
Esempio n. 51
0
        private static FunctionMetadata ParseFunctionMetadata(string functionName, INameResolver nameResolver, JObject configMetadata)
        {
            FunctionMetadata functionMetadata = new FunctionMetadata
            {
                Name = functionName
            };

            JValue triggerDisabledValue = null;
            JArray bindingArray         = (JArray)configMetadata["bindings"];

            if (bindingArray == null || bindingArray.Count == 0)
            {
                throw new FormatException("At least one binding must be declared.");
            }

            if (bindingArray != null)
            {
                foreach (JObject binding in bindingArray)
                {
                    BindingMetadata bindingMetadata = ParseBindingMetadata(binding, nameResolver);
                    functionMetadata.Bindings.Add(bindingMetadata);
                    if (bindingMetadata.IsTrigger)
                    {
                        triggerDisabledValue = (JValue)binding["disabled"];
                    }
                }
            }

            // A function can be disabled at the trigger or function level
            if (IsDisabled(functionName, triggerDisabledValue) ||
                IsDisabled(functionName, (JValue)configMetadata["disabled"]))
            {
                functionMetadata.IsDisabled = true;
            }

            return(functionMetadata);
        }
        public static FunctionIndexer Create(CloudStorageAccount account = null, INameResolver nameResolver = null, IExtensionRegistry extensionRegistry = null)
        {
            IStorageAccount         storageAccount         = account != null ? new StorageAccount(account) : null;
            IStorageAccountProvider storageAccountProvider = new SimpleStorageAccountProvider
            {
                StorageAccount = account
            };
            IExtensionTypeLocator extensionTypeLocator = new NullExtensionTypeLocator();
            ContextAccessor <IMessageEnqueuedWatcher> messageEnqueuedWatcherAccessor =
                new ContextAccessor <IMessageEnqueuedWatcher>();
            ContextAccessor <IBlobWrittenWatcher> blobWrittenWatcherAccessor =
                new ContextAccessor <IBlobWrittenWatcher>();
            ISharedContextProvider  sharedContextProvider = new SharedContextProvider();
            TestTraceWriter         logger = new TestTraceWriter(TraceLevel.Verbose);
            ITriggerBindingProvider triggerBindingProvider = DefaultTriggerBindingProvider.Create(nameResolver,
                                                                                                  storageAccountProvider, extensionTypeLocator,
                                                                                                  new FixedHostIdProvider("test"), new SimpleQueueConfiguration(maxDequeueCount: 5),
                                                                                                  BackgroundExceptionDispatcher.Instance, messageEnqueuedWatcherAccessor, blobWrittenWatcherAccessor,
                                                                                                  sharedContextProvider, new DefaultExtensionRegistry(), logger);
            IBindingProvider bindingProvider = DefaultBindingProvider.Create(nameResolver, storageAccountProvider,
                                                                             extensionTypeLocator, messageEnqueuedWatcherAccessor,
                                                                             blobWrittenWatcherAccessor, new DefaultExtensionRegistry());

            IFunctionOutputLoggerProvider outputLoggerProvider = new NullFunctionOutputLoggerProvider();
            var task = outputLoggerProvider.GetAsync(CancellationToken.None);

            task.Wait();
            IFunctionOutputLogger outputLogger = task.Result;
            IFunctionExecutor     executor     = new FunctionExecutor(new NullFunctionInstanceLogger(), outputLogger, BackgroundExceptionDispatcher.Instance, new TestTraceWriter(TraceLevel.Verbose));

            if (extensionRegistry == null)
            {
                extensionRegistry = new DefaultExtensionRegistry();
            }

            return(new FunctionIndexer(triggerBindingProvider, bindingProvider, DefaultJobActivator.Instance, executor, extensionRegistry, new SingletonManager()));
        }
        public ServiceBusAttributeBindingProvider(INameResolver nameResolver, ServiceBusOptions options, IConfiguration configuration, MessagingProvider messagingProvider)
        {
            if (nameResolver == null)
            {
                throw new ArgumentNullException(nameof(nameResolver));
            }
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (messagingProvider == null)
            {
                throw new ArgumentNullException(nameof(messagingProvider));
            }

            _nameResolver      = nameResolver;
            _options           = options;
            _configuration     = configuration;
            _messagingProvider = messagingProvider;
        }
        public static async Task<JobHostContext> CreateAndLogHostStartedAsync(
            JobHost host,
            IStorageAccountProvider storageAccountProvider,
            IQueueConfiguration queueConfiguration,
            ITypeLocator typeLocator,
            IJobActivator activator,
            INameResolver nameResolver,
            IConsoleProvider consoleProvider,
            JobHostConfiguration config,
            CancellationToken shutdownToken,
            CancellationToken cancellationToken,
            IHostIdProvider hostIdProvider = null,
            FunctionExecutor functionExecutor = null,
            IFunctionIndexProvider functionIndexProvider = null,
            IBindingProvider bindingProvider = null,
            IHostInstanceLoggerProvider hostInstanceLogerProvider = null,
            IFunctionInstanceLoggerProvider functionInstanceLoggerProvider = null,
            IFunctionOutputLoggerProvider functionOutputLoggerProvider = null,
            IBackgroundExceptionDispatcher backgroundExceptionDispatcher = null,
            SingletonManager singletonManager = null)
        {
            if (hostIdProvider == null)
            {
                hostIdProvider = new DynamicHostIdProvider(storageAccountProvider, () => functionIndexProvider);
            }

            IExtensionTypeLocator extensionTypeLocator = new ExtensionTypeLocator(typeLocator);
            if (backgroundExceptionDispatcher == null)
            {
                backgroundExceptionDispatcher = BackgroundExceptionDispatcher.Instance;
            }
            ContextAccessor<IMessageEnqueuedWatcher> messageEnqueuedWatcherAccessor = new ContextAccessor<IMessageEnqueuedWatcher>();
            ContextAccessor<IBlobWrittenWatcher> blobWrittenWatcherAccessor = new ContextAccessor<IBlobWrittenWatcher>();
            ISharedContextProvider sharedContextProvider = new SharedContextProvider();

            // Create a wrapper TraceWriter that delegates to both the user 
            // TraceWriter specified on Config (if present), as well as to Console
            TraceWriter trace = new ConsoleTraceWriter(config.Tracing, consoleProvider.Out);

            // Register system services with the service container
            config.AddService<INameResolver>(nameResolver);

            ExtensionConfigContext context = new ExtensionConfigContext
            {
                Config = config,
                Trace = trace,
                Host = host
            };
            InvokeExtensionConfigProviders(context);

            IExtensionRegistry extensions = config.GetExtensions();
            ITriggerBindingProvider triggerBindingProvider = DefaultTriggerBindingProvider.Create(nameResolver,
                storageAccountProvider, extensionTypeLocator, hostIdProvider, queueConfiguration, backgroundExceptionDispatcher,
                messageEnqueuedWatcherAccessor, blobWrittenWatcherAccessor, sharedContextProvider, extensions, trace);

            if (bindingProvider == null)
            {
                bindingProvider = DefaultBindingProvider.Create(nameResolver, storageAccountProvider, extensionTypeLocator, messageEnqueuedWatcherAccessor, blobWrittenWatcherAccessor, extensions);
            }

            DefaultLoggerProvider loggerProvider = new DefaultLoggerProvider(storageAccountProvider, trace);

            if (singletonManager == null)
            {
                singletonManager = new SingletonManager(storageAccountProvider, backgroundExceptionDispatcher, config.Singleton, trace, config.NameResolver);
            }
            
            using (CancellationTokenSource combinedCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, shutdownToken))
            {
                CancellationToken combinedCancellationToken = combinedCancellationSource.Token;

                await WriteSiteExtensionManifestAsync(combinedCancellationToken);

                IStorageAccount dashboardAccount = await storageAccountProvider.GetDashboardAccountAsync(combinedCancellationToken);

                IHostInstanceLogger hostInstanceLogger = null;
                if (hostInstanceLogerProvider != null)
                {
                    hostInstanceLogger = await hostInstanceLogerProvider.GetAsync(combinedCancellationToken);
                }
                else
                {
                    hostInstanceLogger = await((IHostInstanceLoggerProvider)loggerProvider).GetAsync(combinedCancellationToken);
                }

                IFunctionInstanceLogger functionInstanceLogger = null;
                if (functionInstanceLoggerProvider != null)
                {
                    functionInstanceLogger = await functionInstanceLoggerProvider.GetAsync(combinedCancellationToken);
                }
                else
                {
                    functionInstanceLogger = (IFunctionInstanceLogger)(await((IFunctionInstanceLoggerProvider)loggerProvider).GetAsync(combinedCancellationToken));
                }

                IFunctionOutputLogger functionOutputLogger = null;
                if (functionOutputLoggerProvider != null)
                {
                    functionOutputLogger = await functionOutputLoggerProvider.GetAsync(combinedCancellationToken);
                }
                else
                {
                    functionOutputLogger = (IFunctionOutputLogger)(await((IFunctionOutputLoggerProvider)loggerProvider).GetAsync(combinedCancellationToken));
                }

                if (functionExecutor == null)
                {
                    functionExecutor = new FunctionExecutor(functionInstanceLogger, functionOutputLogger, backgroundExceptionDispatcher, trace);
                }

                if (functionIndexProvider == null)
                {
                    functionIndexProvider = new FunctionIndexProvider(typeLocator, triggerBindingProvider, bindingProvider, activator, functionExecutor, extensions, singletonManager);
                }

                IFunctionIndex functions = await functionIndexProvider.GetAsync(combinedCancellationToken);
                IListenerFactory functionsListenerFactory = new HostListenerFactory(functions.ReadAll(), singletonManager, activator, nameResolver, trace);

                IFunctionExecutor hostCallExecutor;
                IListener listener;
                HostOutputMessage hostOutputMessage;

                if (dashboardAccount != null)
                {
                    string hostId = await hostIdProvider.GetHostIdAsync(cancellationToken);

                    string sharedQueueName = HostQueueNames.GetHostQueueName(hostId);
                    IStorageQueueClient dashboardQueueClient = dashboardAccount.CreateQueueClient();
                    IStorageQueue sharedQueue = dashboardQueueClient.GetQueueReference(sharedQueueName);
                    IListenerFactory sharedQueueListenerFactory = new HostMessageListenerFactory(sharedQueue,
                        queueConfiguration, backgroundExceptionDispatcher, trace, functions,
                        functionInstanceLogger, functionExecutor);

                    Guid hostInstanceId = Guid.NewGuid();
                    string instanceQueueName = HostQueueNames.GetHostQueueName(hostInstanceId.ToString("N"));
                    IStorageQueue instanceQueue = dashboardQueueClient.GetQueueReference(instanceQueueName);
                    IListenerFactory instanceQueueListenerFactory = new HostMessageListenerFactory(instanceQueue,
                        queueConfiguration, backgroundExceptionDispatcher, trace, functions,
                        functionInstanceLogger, functionExecutor);

                    HeartbeatDescriptor heartbeatDescriptor = new HeartbeatDescriptor
                    {
                        SharedContainerName = HostContainerNames.Hosts,
                        SharedDirectoryName = HostDirectoryNames.Heartbeats + "/" + hostId,
                        InstanceBlobName = hostInstanceId.ToString("N"),
                        ExpirationInSeconds = (int)HeartbeatIntervals.ExpirationInterval.TotalSeconds
                    };

                    IStorageBlockBlob blob = dashboardAccount.CreateBlobClient()
                        .GetContainerReference(heartbeatDescriptor.SharedContainerName)
                        .GetBlockBlobReference(heartbeatDescriptor.SharedDirectoryName + "/" + heartbeatDescriptor.InstanceBlobName);
                    IRecurrentCommand heartbeatCommand = new UpdateHostHeartbeatCommand(new HeartbeatCommand(blob));

                    IEnumerable<MethodInfo> indexedMethods = functions.ReadAllMethods();
                    Assembly hostAssembly = GetHostAssembly(indexedMethods);
                    string displayName = hostAssembly != null ? hostAssembly.GetName().Name : "Unknown";

                    hostOutputMessage = new DataOnlyHostOutputMessage
                    {
                        HostInstanceId = hostInstanceId,
                        HostDisplayName = displayName,
                        SharedQueueName = sharedQueueName,
                        InstanceQueueName = instanceQueueName,
                        Heartbeat = heartbeatDescriptor,
                        WebJobRunIdentifier = WebJobRunIdentifier.Current
                    };

                    hostCallExecutor = CreateHostCallExecutor(instanceQueueListenerFactory, heartbeatCommand,
                        backgroundExceptionDispatcher, shutdownToken, functionExecutor);
                    IListenerFactory hostListenerFactory = new CompositeListenerFactory(functionsListenerFactory,
                        sharedQueueListenerFactory, instanceQueueListenerFactory);
                    listener = CreateHostListener(hostListenerFactory, heartbeatCommand, backgroundExceptionDispatcher, shutdownToken);

                    // Publish this to Azure logging account so that a web dashboard can see it. 
                    await LogHostStartedAsync(functions, hostOutputMessage, hostInstanceLogger, combinedCancellationToken);
                }
                else
                {
                    hostCallExecutor = new ShutdownFunctionExecutor(shutdownToken, functionExecutor);

                    IListener factoryListener = new ListenerFactoryListener(functionsListenerFactory);
                    IListener shutdownListener = new ShutdownListener(shutdownToken, factoryListener);
                    listener = shutdownListener;

                    hostOutputMessage = new DataOnlyHostOutputMessage();
                }

                functionExecutor.HostOutputMessage = hostOutputMessage;

                IEnumerable<FunctionDescriptor> descriptors = functions.ReadAllDescriptors();
                int descriptorsCount = descriptors.Count();

                if (descriptorsCount == 0)
                {
                    trace.Warning("No functions found. Try making job classes and methods public.", TraceSource.Indexing);
                }
                else
                {
                    StringBuilder functionsTrace = new StringBuilder();
                    functionsTrace.AppendLine("Found the following functions:");
                    
                    foreach (FunctionDescriptor descriptor in descriptors)
                    {
                        functionsTrace.AppendLine(descriptor.FullName);
                    }

                    trace.Info(functionsTrace.ToString(), TraceSource.Indexing);
                }

                return new JobHostContext(functions, hostCallExecutor, listener, trace);
            }
        }
Esempio n. 55
0
 /// <summary>
 /// Initializes a new instance of the SQLCommandBuilder class.
 /// </summary>
 /// <param name="nameResolver">
 /// The table/column name resolver.
 /// </param>
 public SqlCommandBuilder(INameResolver nameResolver)
 {
     Check.NotNull(nameResolver, "nameResolver");
     this.nameResolver = nameResolver;
 }
 public SendGridAttributeBindingProvider(SendGridConfiguration config, INameResolver nameResolver)
 {
     _config = config;
     _nameResolver = nameResolver;
 }
        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;
        }
        private static FunctionMetadata ParseFunctionMetadata(string functionName, INameResolver nameResolver, JObject configMetadata)
        {
            FunctionMetadata functionMetadata = new FunctionMetadata
            {
                Name = functionName
            };

            JValue triggerDisabledValue = null;
            JArray bindingArray = (JArray)configMetadata["bindings"];
            if (bindingArray == null || bindingArray.Count == 0)
            {
                throw new FormatException("At least one binding must be declared.");
            }

            if (bindingArray != null)
            {
                foreach (JObject binding in bindingArray)
                {
                    BindingMetadata bindingMetadata = ParseBindingMetadata(binding, nameResolver);
                    functionMetadata.Bindings.Add(bindingMetadata);
                    if (bindingMetadata.IsTrigger)
                    {
                        triggerDisabledValue = (JValue)binding["disabled"];
                    }
                }
            }

            // A function can be disabled at the trigger or function level
            if (IsDisabled(functionName, triggerDisabledValue) ||
                IsDisabled(functionName, (JValue)configMetadata["disabled"]))
            {
                functionMetadata.IsDisabled = true;
            }

            return functionMetadata;
        }
        private static BindingMetadata ParseBindingMetadata(JObject binding, INameResolver nameResolver)
        {
            BindingMetadata bindingMetadata = null;
            string bindingTypeValue = (string)binding["type"];
            string bindingDirectionValue = (string)binding["direction"];
            string connection = (string)binding["connection"];
            BindingType bindingType = default(BindingType);
            BindingDirection bindingDirection = default(BindingDirection);

            if (!string.IsNullOrEmpty(bindingDirectionValue) &&
                !Enum.TryParse<BindingDirection>(bindingDirectionValue, true, out bindingDirection))
            {
                throw new FormatException(string.Format(CultureInfo.InvariantCulture, "'{0}' is not a valid binding direction.", bindingDirectionValue));
            }

            if (!string.IsNullOrEmpty(bindingTypeValue) &&
                !Enum.TryParse<BindingType>(bindingTypeValue, true, out bindingType))
            {
                throw new FormatException(string.Format("'{0}' is not a valid binding type.", bindingTypeValue));
            }

            if (!string.IsNullOrEmpty(connection) && 
                string.IsNullOrEmpty(Utility.GetAppSettingOrEnvironmentValue(connection)))
            {
                throw new FormatException("Invalid Connection value specified.");
            }

            switch (bindingType)
            {
                case BindingType.EventHubTrigger:
                case BindingType.EventHub:
                    bindingMetadata = binding.ToObject<EventHubBindingMetadata>();
                    break;
                case BindingType.QueueTrigger:
                case BindingType.Queue:
                    bindingMetadata = binding.ToObject<QueueBindingMetadata>();
                    break;
                case BindingType.BlobTrigger:
                case BindingType.Blob:
                    bindingMetadata = binding.ToObject<BlobBindingMetadata>();
                    break;
                case BindingType.ServiceBusTrigger:
                case BindingType.ServiceBus:
                    bindingMetadata = binding.ToObject<ServiceBusBindingMetadata>();
                    break;
                case BindingType.HttpTrigger:
                    bindingMetadata = binding.ToObject<HttpTriggerBindingMetadata>();
                    break;
                case BindingType.Http:
                    bindingMetadata = binding.ToObject<HttpBindingMetadata>();
                    break;
                case BindingType.Table:
                    bindingMetadata = binding.ToObject<TableBindingMetadata>();
                    break;
                case BindingType.ManualTrigger:
                    bindingMetadata = binding.ToObject<BindingMetadata>();
                    break;
                case BindingType.TimerTrigger:
                    bindingMetadata = binding.ToObject<TimerBindingMetadata>();
                    break;
                case BindingType.EasyTable:
                    bindingMetadata = binding.ToObject<EasyTableBindingMetadata>();
                    break;
                case BindingType.DocumentDB:
                    bindingMetadata = binding.ToObject<DocumentDBBindingMetadata>();
                    break;
                case BindingType.NotificationHub:
                    bindingMetadata = binding.ToObject<NotificationHubBindingMetadata>();
                    break;
                case BindingType.ApiHub:
                case BindingType.ApiHubTrigger:
                    bindingMetadata = binding.ToObject<ApiHubBindingMetadata>();
                    break;
            }

            bindingMetadata.Type = bindingType;
            bindingMetadata.Direction = bindingDirection;
            bindingMetadata.Connection = connection;

            nameResolver.ResolveAllProperties(bindingMetadata);

            return bindingMetadata;
        }
 public SlackAttributeBindingProvider(SlackConfiguration config, INameResolver nameResolver)
 {
     _config = config;
     _nameResolver = nameResolver;
 }