Esempio n. 1
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);

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

            converterManager.AddConverter <JObject, SMSMessage>(CreateSmsMessage);

            BindingFactory   factory        = new BindingFactory(nameResolver, converterManager);
            IBindingProvider outputProvider = factory.BindToAsyncCollector <TwilioSmsAttribute, SMSMessage>((attr) =>
            {
                return(new TwilioSmsMessageAsyncCollector(CreateContext(attr)));
            });

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

            extensions.RegisterBindingRules <TwilioSmsAttribute>(ValidateBinding, nameResolver, outputProvider);
        }
Esempio n. 2
0
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (string.IsNullOrEmpty(_options.ConnectionString))
            {
                _options.ConnectionString = _nameResolver.Resolve(Constants.WebPubSubConnectionStringName);
                AddSettings(_options.ConnectionString);
            }

            if (string.IsNullOrEmpty(_options.Hub))
            {
                _options.Hub = _nameResolver.Resolve(Constants.HubNameStringName);
            }

            Exception webhookException = null;

            try
            {
#pragma warning disable CS0618 // Type or member is obsolete
                var url = context.GetWebhookHandler();
#pragma warning restore CS0618 // Type or member is obsolete
                _logger.LogInformation($"Registered Web PubSub negotiate Endpoint = {url?.GetLeftPart(UriPartial.Path)}");
            }
            catch (Exception ex)
            {
                // disable trigger.
                webhookException = ex;
            }

            // register JsonConverters
            RegisterJsonConverter();

            // bindings
            context
            .AddConverter <WebPubSubConnection, JObject>(JObject.FromObject)
            .AddConverter <JObject, WebPubSubOperation>(ConvertToWebPubSubOperation)
            .AddConverter <JArray, WebPubSubOperation[]>(ConvertToWebPubSubOperationArray);

            // Trigger binding
            context.AddBindingRule <WebPubSubTriggerAttribute>()
            .BindToTrigger(new WebPubSubTriggerBindingProvider(_dispatcher, _options, webhookException));

            var webpubsubConnectionAttributeRule = context.AddBindingRule <WebPubSubConnectionAttribute>();
            webpubsubConnectionAttributeRule.AddValidator(ValidateWebPubSubConnectionAttributeBinding);
            webpubsubConnectionAttributeRule.BindToInput(GetClientConnection);

            var webPubSubAttributeRule = context.AddBindingRule <WebPubSubAttribute>();
            webPubSubAttributeRule.AddValidator(ValidateWebPubSubAttributeBinding);
            webPubSubAttributeRule.BindToCollector(CreateCollector);

            _logger.LogInformation("Azure Web PubSub binding initialized");
        }
        public LifeCycleNotificationHelper(DurableTaskExtension config, ExtensionConfigContext extensionConfigContext)
        {
            this.config = config ?? throw new ArgumentNullException(nameof(config));
            this.extensionConfigContext = extensionConfigContext ?? throw new ArgumentNullException(nameof(extensionConfigContext));

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

            this.eventGridKeyValue = nameResolver.Resolve(config.EventGridKeySettingName);

            if (!string.IsNullOrEmpty(config.EventGridTopicEndpoint))
            {
                if (!string.IsNullOrEmpty(config.EventGridKeySettingName))
                {
                    this.useTrace = true;

                    // Currently, we support Event Grid Custom Topic for notify the lifecycle event of an orchestrator.
                    // For more detail about the Event Grid, please refer this document.
                    // Post to custom topic for Azure Event Grid
                    // https://docs.microsoft.com/en-us/azure/event-grid/post-to-custom-topic
                    httpClient = new HttpClient();
                    if (!string.IsNullOrEmpty(this.eventGridKeyValue))
                    {
                        httpClient.DefaultRequestHeaders.Add("aeg-sas-key", this.eventGridKeyValue);
                    }
                    else
                    {
                        throw new ArgumentException($"Failed to start lifecycle notification feature. Please check the configuration values for {config.EventGridKeySettingName} on AppSettings.");
                    }
                }
                else
                {
                    throw new ArgumentException($"Failed to start lifecycle notification feature. Please check the configuration values for {config.EventGridTopicEndpoint} and {config.EventGridKeySettingName}.");
                }
            }
        }
Esempio n. 4
0
        private string GetTriggerAttributeConnectionString(SQLTriggerAttribute triggerAttribute)
        {
            if (string.IsNullOrEmpty(triggerAttribute.ConnectionString))
            {
                var connectionString = _nameResolver.Resolve("SQLTrigger.ConnectionString");

                if (string.IsNullOrEmpty(connectionString))
                {
                    throw new InvalidOperationException("ConnectionString is mandatory");
                }

                return(connectionString);
            }

            return(triggerAttribute.ConnectionString);
        }
Esempio n. 5
0
        private string GetTriggerAttributeApiKey(WeatherTriggerAttribute triggerAttribute)
        {
            if (string.IsNullOrEmpty(triggerAttribute.ApiKey))
            {
                var apiKey = _nameResolver.Resolve("Weather.ApiKey");

                if (string.IsNullOrEmpty(apiKey))
                {
                    throw new InvalidOperationException("ApiKey is mandatory");
                }

                return(apiKey);
            }

            return(triggerAttribute.ApiKey);
        }
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

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

            if (string.IsNullOrEmpty(ConnectionString))
            {
                var resolvedConnectionStringSetting = nameResolver.Resolve(AzureWebJobsRedisConnectionStringSetting);
                ConnectionString = resolvedConnectionStringSetting;
            }

            var bindingRule = context.AddBindingRule <RedisAttribute>();

            bindingRule.AddValidator(ValidateConnection);
            bindingRule.BindToCollector <RedisMessageOpenType>(typeof(RedisOpenTypeConverter <>), this);
            bindingRule.BindToValueProvider <RedisMessageOpenType>((attr, t) => BindForItemAsync(attr, t));

            var triggerRule = context.AddBindingRule <RedisTriggerAttribute>();

            triggerRule.BindToTrigger <string>(new RedisTriggerAttributeBindingProvider(this));
            triggerRule.AddOpenConverter <string, RedisMessageOpenType>(typeof(RedisMessageOpenTypeBindingConverter <>));
        }
Esempio n. 7
0
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (string.IsNullOrEmpty(options.ConnectionString))
            {
                options.ConnectionString = nameResolver.Resolve(AzureSignalRConnectionStringName);
            }

            context.AddConverter <string, JObject>(JObject.FromObject);
            context.AddConverter <JObject, SignalRMessage>(input => input.ToObject <SignalRMessage>());
            context.AddConverter <SignalRConnectionInfo, JObject>(JObject.FromObject);

            var signalRConnectionInfoAttributeRule = context.AddBindingRule <SignalRConnectionInfoAttribute>();

            signalRConnectionInfoAttributeRule.AddValidator(ValidateSignalRConnectionInfoAttributeBinding);
            signalRConnectionInfoAttributeRule.BindToInput <SignalRConnectionInfo>(GetClientConnectionInfo);

            var signalRAttributeRule = context.AddBindingRule <SignalRAttribute>();

            signalRAttributeRule.AddValidator(ValidateSignalRAttributeBinding);
            signalRAttributeRule.BindToCollector <SignalRMessage>(CreateCollector);

            logger.LogInformation("SignalRService binding initialized");
        }
Esempio n. 8
0
 public void SetAppSettings(INameResolver appSettings)
 {
     if (TokenMapLocation == null)
     {
         TokenMapLocation = appSettings.Resolve(SubscriptionStoreLocationAppSettingName);
     }
 }
        internal string ResolveApiKey(string attributeApiKey)
        {
            // The behavior for ApiKey is unique, so we do not use the AutoResolve
            // functionality.
            // If an attribute sets the ApiKeySetting to an empty string,
            // that overwrites any default value and sets it to null.
            // If ApiKeySetting is null, it returns the default value.

            // First, if the key is an empty string, return null.
            if (attributeApiKey != null && attributeApiKey.Length == 0)
            {
                return(null);
            }

            // Second, if it is anything other than null, return the resolved value
            if (attributeApiKey != null)
            {
                return(_nameResolver.Resolve(attributeApiKey));
            }

            // Third, try the config's key
            if (!string.IsNullOrEmpty(ApiKey))
            {
                return(ApiKey);
            }

            // Finally, fall back to the default.
            return(_defaultApiKey);
        }
        private IClause ParseExact(MemberExpression expression)
        {
            var prop   = expression.Member as PropertyInfo;
            var column = _nameResolver.Resolve(prop);

            return(column.ToClause());
        }
            public override Collection <Attribute> GetAttributes()
            {
                Collection <Attribute> attributes = new Collection <Attribute>();

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

                if (!string.IsNullOrEmpty(connectionStringSetting))
                {
                    // Register each binding connection with the global config
                    string connectionStringValue = _nameResolver.Resolve(connectionStringSetting);
                    _apiHubConfig.AddConnection(connectionStringSetting, connectionStringValue);
                }

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

                if (Context.IsTrigger)
                {
                    FileWatcherType fileWatcherType       = Context.GetMetadataEnumValue <FileWatcherType>("fileWatcherType", FileWatcherType.Created);
                    int             pollIntervalInSeconds = Context.GetMetadataValue <int>("pollIntervalInSeconds");

                    attributes.Add(new ApiHubFileTriggerAttribute(connectionStringSetting, path, fileWatcherType, pollIntervalInSeconds));
                }
                else
                {
                    attributes.Add(new ApiHubFileAttribute(connectionStringSetting, path, Context.Access));
                }

                return(attributes);
            }
        /// <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>();

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

            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. 13
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. 14
0
        /// <inheritdoc />
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            INameResolver nameResolver = context.Config.NameResolver;

            _defaultApiKey = nameResolver.Resolve(AzureWebJobsSendGridApiKeyName);

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

            converterManager.AddConverter <string, Mail>(SendGridHelpers.CreateMessage);
            converterManager.AddConverter <JObject, Mail>(SendGridHelpers.CreateMessage);

            BindingFactory   factory        = new BindingFactory(nameResolver, converterManager);
            IBindingProvider outputProvider = factory.BindToAsyncCollector <SendGridAttribute, Mail>((attr) =>
            {
                string apiKey            = FirstOrDefault(attr.ApiKey, ApiKey, _defaultApiKey);
                ISendGridClient sendGrid = _sendGridClientCache.GetOrAdd(apiKey, a => ClientFactory.Create(a));
                return(new SendGridMailAsyncCollector(this, attr, sendGrid));
            });

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

            extensions.RegisterBindingRules <SendGridAttribute>(ValidateBinding, nameResolver, outputProvider);
        }
        /// <inheritdoc />
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var metadata = new ConfigMetadata();

            context.ApplyConfig(metadata, "sendgrid");
            this.ToAddress   = SendGridHelpers.Apply(this.ToAddress, metadata.To);
            this.FromAddress = SendGridHelpers.Apply(this.FromAddress, metadata.From);

            if (string.IsNullOrEmpty(this.ApiKey))
            {
                INameResolver nameResolver = context.Config.NameResolver;
                this.ApiKey = nameResolver.Resolve(AzureWebJobsSendGridApiKeyName);
            }

            context
            .AddConverter <string, SendGridMessage>(SendGridHelpers.CreateMessage)
            .AddConverter <JObject, SendGridMessage>(SendGridHelpers.CreateMessage)
            .AddBindingRule <SendGridAttribute>()
            .AddValidator(ValidateBinding)
            .BindToCollector <SendGridMessage>(CreateCollector);
        }
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

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


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

            rule.AddValidator(ValidateBinding);

            rule.BindToCollector(CreateContext);
        }
Esempio n. 17
0
        public MqttConfig Create(INameResolver nameResolver, ILogger logger)
        {
            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId(Guid.NewGuid().ToString())
                                             .WithTcpServer(nameResolver.Resolve("MqttServer"), 1883)
                                             .WithCredentials(nameResolver.Resolve("MqttUsername"), nameResolver.Resolve("MqttPassword"))
                                             .Build())
                          .Build();

            var topics = new TopicFilter[] {
                new TopicFilter("owntracks/kees/kees01", MqttQualityOfServiceLevel.ExactlyOnce)
            };

            return(new MqttConfigExample(options, topics));
        }
        /// <summary>
        /// Resolve all %% matches within a string.
        /// </summary>
        /// <param name="resolver">resolver to apply to each name</param>
        /// <param name="resolve">the input string. IE, "start%name1%...%name2%end"</param>
        /// <returns>The resolved string. IE, "startA...Bend" </returns>
        public static string ResolveWholeString(this INameResolver resolver, string resolve)
        {
            if (resolver == null)
            {
                throw new ArgumentNullException("resolver");
            }

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

            int           i  = 0;
            StringBuilder sb = new StringBuilder();

            while (i < resolve.Length)
            {
                int idxStart = resolve.IndexOf('%', i);
                if (idxStart >= 0)
                {
                    int idxEnd = resolve.IndexOf('%', idxStart + 1);
                    if (idxEnd < 0)
                    {
                        string msg = string.Format(CultureInfo.CurrentCulture, "The '%' at position {0} does not have a closing '%'", idxStart);
                        throw new InvalidOperationException(msg);
                    }
                    string name = resolve.Substring(idxStart + 1, idxEnd - idxStart - 1);

                    string value;
                    try
                    {
                        value = resolver.Resolve(name);
                    }
                    catch (Exception e)
                    {
                        string msg = string.Format(CultureInfo.CurrentCulture, "Threw an exception trying to resolve '%{0}%' ({1}:{2}).", name, e.GetType().Name, e.Message);
                        throw new InvalidOperationException(msg, e);
                    }
                    if (value == null)
                    {
                        string msg = string.Format(CultureInfo.CurrentCulture, "'%{0}%' does not resolve to a value.", name);
                        throw new InvalidOperationException(msg);
                    }
                    sb.Append(resolve.Substring(i, idxStart - i));
                    sb.Append(value);
                    i = idxEnd + 1;
                }
                else
                {
                    // no more '%' tokens
                    sb.Append(resolve.Substring(i));
                    break;
                }
            }

            return(sb.ToString());
        }
        public void SetAppSettings(INameResolver appSettings)
        {
            var settingsTokenMapLocation = appSettings.Resolve(SubscriptionStoreLocationAppSettingName);

            if (!string.IsNullOrEmpty(settingsTokenMapLocation) && TokenMapLocation == defaultTokenMapLocation)
            {
                TokenMapLocation = settingsTokenMapLocation;
            }
        }
        static string GetDefaultDaprAddress(INameResolver resolver)
        {
            if (!int.TryParse(resolver.Resolve("DAPR_HTTP_PORT"), out int daprPort))
            {
                daprPort = 3500;
            }

            return($"http://localhost:{daprPort}");
        }
        static string GetDefaultAppAddress(INameResolver resolver)
        {
            if (!int.TryParse(resolver.Resolve("DAPR_APP_PORT"), out int appPort))
            {
                appPort = 3001;
            }

            return($"http://127.0.0.1:{appPort}");
        }
        /// <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);

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

            rule.AddValidator(ValidateMobileAppUri);

            rule.BindToCollector <OpenType>(typeof(MobileTableCollectorBuilder <>), this);
            rule.BindToInput <IMobileServiceClient>(new MobileTableClientBuilder(this));

            // MobileType matching needs to know whether the attribute defines 'TableName', but
            // OpenTypes can't get access to the attribute. So use filters to split into 2 cases.
            rule.WhenIsNotNull(nameof(MobileTableAttribute.TableName)).
            BindToInput <IMobileServiceTableQuery <MobileTypeWithTableName> >(typeof(MobileTableQueryBuilder <>), this);
            rule.WhenIsNull(nameof(MobileTableAttribute.TableName)).
            BindToInput <IMobileServiceTableQuery <MobileTypeWithoutTableName> >(typeof(MobileTableQueryBuilder <>), this);

            rule.BindToInput <IMobileServiceTable>(new MobileTableJObjectTableBuilder(this));

            rule.WhenIsNotNull(nameof(MobileTableAttribute.TableName)).
            BindToInput <IMobileServiceTable <MobileTypeWithTableName> >(typeof(MobileTablePocoTableBuilder <>), this);
            rule.WhenIsNull(nameof(MobileTableAttribute.TableName)).
            BindToInput <IMobileServiceTable <MobileTypeWithoutTableName> >(typeof(MobileTablePocoTableBuilder <>), this);

            rule.WhenIsNotNull(nameof(MobileTableAttribute.TableName)).
            BindToValueProvider <MobileTypeWithTableName>(BindForItemAsync).AddValidator(HasId);
            rule.WhenIsNull(nameof(MobileTableAttribute.TableName)).
            BindToValueProvider <MobileTypeWithoutTableName>(BindForItemAsync).AddValidator(HasId);
        }
Esempio n. 23
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));
        }
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            _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 MsSqlDbExtensionConfigProvider(IOptions <MsSqlDbOptions> options,
                                       IMsSqlDbServiceFactory msSqlDbServiceFactory, IConfiguration configuration,
                                       INameResolver nameResolver, ILoggerFactory loggerFactory)
 {
     _options = options.Value;
     _msSqlDbServiceFactory   = msSqlDbServiceFactory;
     _configuration           = configuration;
     _nameResolver            = nameResolver;
     _loggerFactory           = loggerFactory;
     _defaultConnectionString = _nameResolver.Resolve(MsSqlDbConnectionStringName);
 }
Esempio n. 26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AttributeToConfigConverter"/> class.
        /// </summary>
        /// <param name="source">The trigger attribute.</param>
        /// <param name="nameResolver">The name resolver.</param>
        /// <param name="logger">The logger.</param>
        public AttributeToConfigConverter(MqttTriggerAttribute source, INameResolver nameResolver, ILogger logger)
        {
            _connectionString = new DbConnectionStringBuilder()
            {
                ConnectionString = nameResolver.Resolve(source.ConnectionString)
            };

            _mqttTriggerAttribute = source;
            _nameResolver         = nameResolver;
            _logger = logger;
        }
        /// <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.BindToCollector <MobileTableAttribute, OpenType>(typeof(MobileTableCollectorBuilder <>), this);

            IBindingProvider clientProvider = factory.BindToInput <MobileTableAttribute, IMobileServiceClient>(new MobileTableClientBuilder(this));

            IBindingProvider queryProvider = factory.BindToInput <MobileTableAttribute, IMobileServiceTableQuery <OpenType> >(typeof(MobileTableQueryBuilder <>), this);

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

            IBindingProvider jObjectTableProvider = factory.BindToInput <MobileTableAttribute, IMobileServiceTable>(new MobileTableJObjectTableBuilder(this));

            IBindingProvider tableProvider = factory.BindToInput <MobileTableAttribute, IMobileServiceTable <OpenType> >(typeof(MobileTablePocoTableBuilder <>), this);

            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);
        }
Esempio n. 28
0
        private MqttConfiguration GetConfigurationViaAttributeValues(MqttBaseAttribute mqttAttribute)
        {
            var name             = mqttAttribute.ConnectionString;
            var connectionString = _nameResolver.Resolve(mqttAttribute.ConnectionString);

            if (string.IsNullOrWhiteSpace(connectionString))
            {
                connectionString = _nameResolver.Resolve(DefaultAppsettingsKeyForConnectionString);
                name             = name ?? DefaultAppsettingsKeyForConnectionString;
            }
            var mqttConnectionString = new MqttConnectionString(connectionString, name);

            var mqttClientOptions = GetMqttClientOptions(mqttConnectionString);

            var managedMqttClientOptions = new ManagedMqttClientOptionsBuilder()
                                           .WithAutoReconnectDelay(_defaultReconnectTime)
                                           .WithClientOptions(mqttClientOptions)
                                           .Build();

            return(new MqttConfiguration(name, managedMqttClientOptions));
        }
        public LifeCycleNotificationHelper(
            DurableTaskOptions config,
            INameResolver nameResolver,
            EndToEndTraceHelper traceHelper)
        {
            this.config      = config ?? throw new ArgumentNullException(nameof(config));
            this.traceHelper = traceHelper ?? throw new ArgumentNullException(nameof(traceHelper));

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

            this.eventGridKeyValue      = nameResolver.Resolve(config.EventGridKeySettingName);
            this.eventGridTopicEndpoint = config.EventGridTopicEndpoint;
            if (nameResolver.TryResolveWholeString(config.EventGridTopicEndpoint, out var endpoint))
            {
                this.eventGridTopicEndpoint = endpoint;
            }

            if (!string.IsNullOrEmpty(this.eventGridTopicEndpoint))
            {
                if (!string.IsNullOrEmpty(config.EventGridKeySettingName))
                {
                    this.useTrace = true;

                    var retryStatusCode = config.EventGridPublishRetryHttpStatus?
                                          .Where(x => Enum.IsDefined(typeof(HttpStatusCode), x))
                                          .Select(x => (HttpStatusCode)x)
                                          .ToArray()
                                          ?? Array.Empty <HttpStatusCode>();

                    // Currently, we support Event Grid Custom Topic for notify the lifecycle event of an orchestrator.
                    // For more detail about the Event Grid, please refer this document.
                    // Post to custom topic for Azure Event Grid
                    // https://docs.microsoft.com/en-us/azure/event-grid/post-to-custom-topic
                    this.HttpMessageHandler = config.NotificationHandler ?? new HttpRetryMessageHandler(
                        new HttpClientHandler(),
                        config.EventGridPublishRetryCount,
                        config.EventGridPublishRetryInterval,
                        retryStatusCode);

                    if (string.IsNullOrEmpty(this.eventGridKeyValue))
                    {
                        throw new ArgumentException($"Failed to start lifecycle notification feature. Please check the configuration values for {config.EventGridKeySettingName} on AppSettings.");
                    }
                }
                else
                {
                    throw new ArgumentException($"Failed to start lifecycle notification feature. Please check the configuration values for {config.EventGridTopicEndpoint} and {config.EventGridKeySettingName}.");
                }
            }
        }
Esempio n. 30
0
        public async Task <PartnerServiceClient> ConvertAsync(PartnerServiceAttribute input, CancellationToken cancellationToken)
        {
            IVaultService vaultService;
            string        keyVaultEndpoint;

            try
            {
                keyVaultEndpoint = nameResolver.Resolve("KeyVaultEndpoint");
                vaultService     = new KeyVaultService(keyVaultEndpoint);


                return(new PartnerServiceClient(
                           new Uri(input.Endpoint),
                           new ServiceCredentials(
                               input.ApplicationId,
                               await vaultService.GetSecretAsync(input.SecretName).ConfigureAwait(false),
                               input.Resource,
                               input.ApplicationTenantId),
                           await GetPartnerHttpClientAsync(input.ApplicationTenantId).ConfigureAwait(false)));
            }
            finally
            {
                vaultService = null;
            }
        }
        private string GetResolvedConnectionString(PropertyInfo property, string configurationName)
        {
            string resolvedConnectionString;

            if (!string.IsNullOrWhiteSpace(configurationName))
            {
                resolvedConnectionString = _nameResolver.Resolve(configurationName);
            }
            else
            {
                var attribute = property.GetCustomAttribute <AppSettingAttribute>();
                if (attribute == null)
                {
                    throw new InvalidOperationException($"Unable to get AppSettingAttribute on property {property.Name}");
                }
                resolvedConnectionString = _nameResolver.Resolve(attribute.Default);
            }

            return(string.IsNullOrEmpty(resolvedConnectionString)
                ? _options.ConnectionString
                : resolvedConnectionString);
        }