Esempio n. 1
0
        public ICodeGenerator Create(
            string defaultNamespace,
            string inputFileContents,
            string inputFilePath,
            SupportedLanguage language,
            SupportedCodeGenerator generator)
        {
            switch (generator)
            {
            case SupportedCodeGenerator.AutoRest:
                return(new AutoRestCSharpCodeGenerator(
                           inputFilePath,
                           defaultNamespace));

            case SupportedCodeGenerator.NSwag:
                return(new NSwagCSharpCodeGenerator(
                           inputFilePath,
                           defaultNamespace,
                           optionsFactory.Create <INSwagOptions, NSwagOptionsPage>()));

            case SupportedCodeGenerator.Swagger:
                return(new SwaggerCSharpCodeGenerator(
                           inputFilePath,
                           defaultNamespace,
                           optionsFactory.Create <IGeneralOptions, GeneralOptionPage>()));

            case SupportedCodeGenerator.OpenApi:
                return(new OpenApiCSharpCodeGenerator(
                           inputFilePath,
                           defaultNamespace,
                           optionsFactory.Create <IGeneralOptions, GeneralOptionPage>()));
            }

            throw new NotSupportedException();
        }
        public ICodeGenerator Create(
            string defaultNamespace,
            string inputFileContents,
            string inputFilePath,
            SupportedLanguage language,
            SupportedCodeGenerator generator)
        {
            remoteLogger.TrackFeatureUsage(generator.GetName());

            switch (generator)
            {
            case SupportedCodeGenerator.AutoRest:
                return(new AutoRestCSharpCodeGenerator(
                           inputFilePath,
                           defaultNamespace,
                           optionsFactory.Create <IAutoRestOptions, AutoRestOptionsPage>(),
                           processLauncher,
                           documentFactory,
                           dependencyInstaller));

            case SupportedCodeGenerator.NSwag:
                return(new NSwagCSharpCodeGenerator(
                           inputFilePath,
                           new OpenApiDocumentFactory(),
                           new NSwagCodeGeneratorSettingsFactory(
                               defaultNamespace,
                               optionsFactory.Create <INSwagOptions, NSwagOptionsPage>())));

            case SupportedCodeGenerator.Swagger:
                return(new SwaggerCSharpCodeGenerator(
                           inputFilePath,
                           defaultNamespace,
                           optionsFactory.Create <IGeneralOptions, GeneralOptionPage>(),
                           processLauncher,
                           dependencyInstaller));

            case SupportedCodeGenerator.OpenApi:
                return(new OpenApiCSharpCodeGenerator(
                           inputFilePath,
                           defaultNamespace,
                           optionsFactory.Create <IGeneralOptions, GeneralOptionPage>(),
                           optionsFactory.Create <IOpenApiGeneratorOptions, OpenApiGeneratorOptionsPage>(),
                           processLauncher,
                           dependencyInstaller));

            default:
                throw new NotSupportedException();
            }
        }
Esempio n. 3
0
        public TOptions GetMatchingOptions(string name)
        {
            foreach (var key in _globs.Keys)
            {
                var glob = _globs[key];
                if (glob.IsMatch(name))
                {
                    var targetOptions = _innerFactory.Create(key);
                    //  _targetOptionsMonitor.Get(key);
                    return(targetOptions);
                }
            }

            return(_innerFactory.Create(name));
        }
        private async Task ApplyContext(HostAssignmentContext assignmentContext)
        {
            _logger.LogInformation($"Applying {assignmentContext.Environment.Count} app setting(s)");
            assignmentContext.ApplyAppSettings(_environment);

            // We need to get the non-PlaceholderMode script Path so we can unzip to the correct location.
            // This asks the factory to skip the PlaceholderMode check when configuring options.
            var options = _optionsFactory.Create(ScriptApplicationHostOptionsSetup.SkipPlaceholder);
            RunFromPackageContext pkgContext = assignmentContext.GetRunFromPkgContext();

            if ((pkgContext.IsScmRunFromPackage() && await pkgContext.BlobExistsAsync(_logger)) ||
                (!pkgContext.IsScmRunFromPackage() && !string.IsNullOrEmpty(pkgContext.Url) && pkgContext.Url != "1"))
            {
                await ApplyBlobPackageContext(pkgContext, options.ScriptPath);
            }
            else if (!string.IsNullOrEmpty(assignmentContext.AzureFilesConnectionString))
            {
                await MountCifs(assignmentContext.AzureFilesConnectionString, assignmentContext.AzureFilesContentShare, "/home");
            }

            // Irrespective of deployment mechanism mount the share for user data files.
            if (assignmentContext.IsUserDataMountEnabled())
            {
                if (!string.IsNullOrEmpty(assignmentContext.AzureFilesConnectionString) &&
                    !string.IsNullOrEmpty(assignmentContext.AzureFilesContentShare))
                {
                    await MountUserData(assignmentContext);
                }
                else
                {
                    _logger.LogWarning(
                        $"{EnvironmentSettingNames.AzureFilesConnectionString} or {EnvironmentSettingNames.AzureFilesContentShare} is empty. User data share will not be mounted");
                }
            }
        }
        public PredictionEngine <TInput, TPrediction> GetPredictionEngine(string modelName)
        {
            if (_namedPools.ContainsKey(modelName))
            {
                return(_namedPools[modelName].PredictionEnginePool.Get());
            }

            if (string.IsNullOrEmpty(modelName))
            {
                if (_defaultPool == null)
                {
                    throw new ArgumentException("You need to configure a default, not named, model before you use this method.");
                }

                return(_defaultPool.PredictionEnginePool.Get());
            }

            var options = _optionsFactory.Create(modelName);

            var pool = new ModelPoolLoader <TInput, TPrediction>(options);

            _namedPools.Add(modelName, pool);

            return(pool.PredictionEnginePool.Get());
        }
Esempio n. 6
0
        /// <summary>
        /// Returns a configured <typeparamref name="TOptions"/> instance with the given <paramref name="name"/>.
        /// </summary>
        public virtual TOptions Get(string name)
        {
            name = name ?? Options.DefaultName;

            // Store the options in our instance cache
            return(_cache.GetOrAdd(name, () => _factory.Create(name)));
        }
        private async Task ApplyContext(HostAssignmentContext assignmentContext)
        {
            _logger.LogInformation($"Applying {assignmentContext.Environment.Count} app setting(s)");
            assignmentContext.ApplyAppSettings(_environment);

            // We need to get the non-PlaceholderMode script path so we can unzip to the correct location.
            // This asks the factory to skip the PlaceholderMode check when configuring options.
            var options = _optionsFactory.Create(ScriptApplicationHostOptionsSetup.SkipPlaceholder);

            var zipPath = assignmentContext.ZipUrl;

            if (!string.IsNullOrEmpty(zipPath))
            {
                // download zip and extract
                var zipUri   = new Uri(zipPath);
                var filePath = await DownloadAsync(zipUri);

                UnpackPackage(filePath, options.ScriptPath);

                string bundlePath = Path.Combine(options.ScriptPath, "worker-bundle");
                if (Directory.Exists(bundlePath))
                {
                    _logger.LogInformation($"Python worker bundle detected");
                }
            }
        }
        private TOptions CreateOptions(string name, TSettings settings)
        {
            var options = _factory.Create(name);

            SetOptions(options, settings);
            return(options);
        }
        /// <summary>
        /// Gets a PredictionEngine for a named model.
        /// </summary>
        /// <param name="modelName">
        /// The name of the model which allows for uniquely identifying the model when
        /// multiple models have the same <typeparamref name="TData"/> and
        /// <typeparamref name="TPrediction"/> types.
        /// </param>
        public PredictionEngine <TData, TPrediction> GetPredictionEngine(string modelName)
        {
            if (_namedPools.TryGetValue(modelName, out var existingPool))
            {
                return(existingPool.PredictionEnginePool.Get());
            }

            //This is the case where someone has used string.Empty to get the default model.
            //We can throw all the time, but it seems reasonable that we would just do what
            //they are expecting if they know that an empty string means default.
            if (string.IsNullOrEmpty(modelName))
            {
                if (_defaultEnginePool == null)
                {
                    throw new ArgumentException("You need to configure a default, not named, model before you use this method.");
                }

                return(_defaultEnginePool.PredictionEnginePool.Get());
            }

            //Here we are in the world of named models where the model hasn't been built yet.
            var options = _predictionEngineOptions.Create(modelName);
            var pool    = new PoolLoader <TData, TPrediction>(_serviceProvider, options);

            pool = _namedPools.GetOrAdd(modelName, pool);
            return(pool.PredictionEnginePool.Get());
        }
Esempio n. 10
0
        public virtual Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
        {
            this.context = context;
            options      = optionsCache.GetOrAdd(scheme.Name, () => optionsFactory.Create(scheme.Name));

            return(Task.CompletedTask);
        }
        private async Task ApplyContext(HostAssignmentContext assignmentContext)
        {
            _logger.LogInformation($"Applying {assignmentContext.Environment.Count} app setting(s)");
            assignmentContext.ApplyAppSettings(_environment);

            // We need to get the non-PlaceholderMode script Path so we can unzip to the correct location.
            // This asks the factory to skip the PlaceholderMode check when configuring options.
            var options = _optionsFactory.Create(ScriptApplicationHostOptionsSetup.SkipPlaceholder);
            RunFromPackageContext pkgContext = assignmentContext.GetRunFromPkgContext();

            if ((pkgContext.IsScmRunFromPackage() && await pkgContext.BlobExistsAsync(_logger)) ||
                (!pkgContext.IsScmRunFromPackage() && !string.IsNullOrEmpty(pkgContext.Url) && pkgContext.Url != "1"))
            {
                await ApplyBlobPackageContext(pkgContext, options.ScriptPath);
            }
            else if (!string.IsNullOrEmpty(assignmentContext.AzureFilesConnectionString))
            {
                await _meshInitServiceClient.MountCifs(assignmentContext.AzureFilesConnectionString, assignmentContext.AzureFilesContentShare, "/home");
            }

            // BYOS
            var storageVolumes = assignmentContext.GetBYOSEnvironmentVariables()
                                 .Select(AzureStorageInfoValue.FromEnvironmentVariable).ToList();

            var mountedVolumes =
                (await Task.WhenAll(storageVolumes.Where(v => v != null).Select(MountStorageAccount))).Where(
                    result => result).ToList();

            if (mountedVolumes.Count != storageVolumes.Count)
            {
                _logger.LogWarning(
                    $"Successfully mounted {mountedVolumes.Count} / {storageVolumes.Count} BYOS storage accounts");
            }
        }
Esempio n. 12
0
            public ApiExplorerOptions Create(string name)
            {
                var newOptions = factory.Create(name);

                newOptions.UseQualifiedNames = options.Value.UseQualifiedNames;
                return(newOptions);
            }
Esempio n. 13
0
        private async Task ApplyContext(HostAssignmentContext assignmentContext)
        {
            _logger.LogInformation($"Applying {assignmentContext.Environment.Count} app setting(s)");
            assignmentContext.ApplyAppSettings(_environment);

            // We need to get the non-PlaceholderMode script path so we can unzip to the correct location.
            // This asks the factory to skip the PlaceholderMode check when configuring options.
            var options = _optionsFactory.Create(ScriptApplicationHostOptionsSetup.SkipPlaceholder);

            var zipPath = assignmentContext.ZipUrl;

            if (!string.IsNullOrEmpty(zipPath))
            {
                // download zip and extract
                var zipUri   = new Uri(zipPath);
                var filePath = Path.GetTempFileName();
                await DownloadAsync(zipUri, filePath);

                using (_metricsLogger.LatencyEvent(MetricEventNames.LinuxContainerSpecializationZipExtract))
                {
                    _logger.LogInformation($"Extracting files to '{options.ScriptPath}'");
                    ZipFile.ExtractToDirectory(filePath, options.ScriptPath, overwriteFiles: true);
                    _logger.LogInformation($"Zip extraction complete");
                }

                string bundlePath = Path.Combine(options.ScriptPath, "worker-bundle");
                if (Directory.Exists(bundlePath))
                {
                    _logger.LogInformation($"Python worker bundle detected");
                }
            }
        }
Esempio n. 14
0
        public JwtBearerOptions Get(string name)
        {
            var tenant = _tenantProvider.GetCurrentTenant();

            Lazy <JwtBearerOptions> Create() => new Lazy <JwtBearerOptions>(() => _optionsFactory.Create(name));

            return(_cache.GetOrAdd((name, tenant), _ => Create()).Value);
        }
Esempio n. 15
0
        private PoolLoader <TData, TPrediction> AddPool(string modelName)
        {
            //Here we are in the world of named models where the model hasn't been built yet.
            var options = _predictionEngineOptions.Create(modelName);
            var pool    = new PoolLoader <TData, TPrediction>(_serviceProvider, options);

            pool = _namedPools.GetOrAdd(modelName, pool);
            return(pool);
        }
Esempio n. 16
0
        public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
        {
            this.context = context ?? throw new ArgumentNullException(nameof(context));

            options = optionsCache.GetOrAdd(scheme.Name, () => optionsFactory.Create(scheme.Name));

            emitSameSiteNone = options.Notifications.EmitSameSiteNone(context.Request.GetUserAgent());

            return(Task.CompletedTask);
        }
Esempio n. 17
0
        private FacebookOptions CreateOptions(string name, SiteContext tenant)
        {
            var options = _factory.Create(name);

            options.AppId     = "placeholder";
            options.AppSecret = "placeholder";
            ConfigureTenantOptions(tenant, options);

            return(options);
        }
Esempio n. 18
0
        private MicrosoftAccountOptions CreateOptions(string name, SiteContext tenant)
        {
            var options = _factory.Create(name);

            options.ClientId     = "placeholder";
            options.ClientSecret = "placeholder";
            ConfigureTenantOptions(tenant, options);

            return(options);
        }
Esempio n. 19
0
        private TwitterOptions CreateOptions(string name, SiteContext tenant)
        {
            var options = _factory.Create(name);

            options.ConsumerKey    = "placeholder";
            options.ConsumerSecret = "placeholder";

            ConfigureTenantOptions(tenant, options);

            return(options);
        }
Esempio n. 20
0
 private RestEaseOptionsPage GetOptionsFromOptionsPage()
 {
     try
     {
         return((RestEaseOptionsPage)_optionsFactory.Create <RestEaseOptionsPage>());
     }
     catch
     {
         Trace.WriteLine($"Error getting {nameof(RestEaseOptionsPage)} using default.");
         return(new RestEaseOptionsPage());
     }
 }
Esempio n. 21
0
        protected DapperDbContext(IOptionsFactory <DapperDbContextOptions> optionsAccessors)
        //protected DapperDbContext(IEnumerable<IOptions<DapperDbContextOptions>> optionsAccessors)
        {
            //SqlMapperExtensions.GetDatabaseType = DataSource.GetDatabaseType;
            SqlMapperExtensions.GetDatabaseType = conn => "MySqlConnection";
            SqlMapperExtensions.TableNameMapper = (name) => name.Name;
            _options = optionsAccessors.Create(DataSourceOptions.ToString());
            //_options = optionsAccessors.FirstOrDefault(p=>p.Configure).Value;
            _connection = CreateConnection(_options.Configuration);

            _connection.Open();
        }
        public TOptions CreateOptions(string schemeName)
        {
            ArgumentValidation.ValidateString(nameof(schemeName), schemeName);

            var options = _optionsFactory.Create(schemeName);

            _optionsMonitorCache.TryRemove(schemeName);
            _optionsMonitorCache.TryAdd(schemeName, options);

            PostConfigure(schemeName, options);

            return(options);
        }
Esempio n. 23
0
 public MempoolMonitoringService(
     IOptionsFactory <BatBotOptions> batBotOptionsFactory,
     MessagingService messagingService,
     BackoffService backoffService,
     TransactionProcessorService transactionProcessorService,
     EthereumService ethereumService)
 {
     _batBotOptions               = batBotOptionsFactory.Create(Options.DefaultName);
     _messagingService            = messagingService;
     _backoffService              = backoffService;
     _transactionProcessorService = transactionProcessorService;
     _ethereumService             = ethereumService;
 }
Esempio n. 24
0
        /// <summary>
        /// Returns a configured <typeparamref name="TOptions"/> instance with the given <paramref name="name"/>.
        /// </summary>
        public virtual TOptions Get(string?name)
        {
            name ??= Options.DefaultName;

            if (!_cache.TryGetValue(name, out TOptions? options))
            {
                // Store the options in our instance cache. Avoid closure on fast path by storing state into scoped locals.
                IOptionsFactory <TOptions> localFactory = _factory;
                string localName = name;
                options = _cache.GetOrAdd(name, () => localFactory.Create(localName));
            }

            return(options);
        }
        private CookieAuthenticationOptions CreateOptions(string name, SiteContext tenant, bool isAppCookie)
        {
            var options = _factory.Create(name);

            if (isAppCookie)
            {
                ConfigureApplicationCookie(tenant, options, name);
            }
            else
            {
                ConfigureOtherCookies(tenant, options, name);
            }

            return(options);
        }
        public PredictionEnginePool(IServiceProvider serviceProvider,
                                    IOptions <MLOptions> mlContextOptions,
                                    IOptionsFactory <PredictionEnginePoolOptions <TData, TPrediction> > predictionEngineOptions)
        {
            _mlContextOptions        = mlContextOptions.Value;
            _predictionEngineOptions = predictionEngineOptions;
            _serviceProvider         = serviceProvider;

            var defaultOptions = _predictionEngineOptions.Create(string.Empty);

            if (defaultOptions.ModelLoader != null)
            {
                _defaultEnginePool = new PoolLoader <TData, TPrediction>(_serviceProvider, defaultOptions);
            }

            _namedPools = new ConcurrentDictionary <string, PoolLoader <TData, TPrediction> >();
        }
        public ModelPredictionEngine(
            IOptionsFactory <ModelPredictionEngineOptions <TInput, TPrediction> > optionsFactory,
            IOptions <MLContextOptions> mlContextOptions)
        {
            _optionsFactory = optionsFactory ?? throw new ArgumentNullException(nameof(optionsFactory));

            MLContext = mlContextOptions.Value.MLContext ?? throw new ArgumentNullException(nameof(mlContextOptions));

            var defaultOptions = _optionsFactory.Create(string.Empty);

            if (defaultOptions.CreateModel != null)
            {
                _defaultPool = new ModelPoolLoader <TInput, TPrediction>(defaultOptions);
            }

            _namedPools = new Dictionary <string, ModelPoolLoader <TInput, TPrediction> >();
        }
        public JwtBearerOptions Get(string name)
        {
            // Console.WriteLine($"Before options factory");
            var tenant = _tenantProvider.GetCurrentTenant();

            Lazy <JwtBearerOptions> Create() => new Lazy <JwtBearerOptions>(() => _optionsFactory.Create(name));

            var result = _cache.GetOrAdd((name, tenant), _ => Create()).Value;

            // var result = _optionsFactory.Create(name);
            // Console.WriteLine($"result.ClaimsIssuer = {result.ClaimsIssuer}");
            // Console.WriteLine($"result.Authority = {result.Authority}");
            // result.Authority = tenant;
            Console.WriteLine($"factory name = {name}");
            Console.WriteLine($"factory result.Authority = {result.Authority}");
            Console.WriteLine($"factory result.Authority hash - {result.Authority.GetHashCode()}");
            return(result);
        }
Esempio n. 29
0
        private async Task ApplyContext(HostAssignmentContext assignmentContext)
        {
            _logger.LogInformation($"Applying {assignmentContext.Environment.Count} app setting(s)");
            assignmentContext.ApplyAppSettings(_environment);

            // We need to get the non-PlaceholderMode script Path so we can unzip to the correct location.
            // This asks the factory to skip the PlaceholderMode check when configuring options.
            var options = _optionsFactory.Create(ScriptApplicationHostOptionsSetup.SkipPlaceholder);
            RunFromPackageContext pkgContext = assignmentContext.GetRunFromPkgContext();

            if ((pkgContext.IsScmRunFromPackage() && await pkgContext.BlobExistsAsync(_logger)) ||
                (!pkgContext.IsScmRunFromPackage() && !string.IsNullOrEmpty(pkgContext.Url) && pkgContext.Url != "1"))
            {
                await ApplyBlobPackageContext(pkgContext, options.ScriptPath);
            }
            else if (!string.IsNullOrEmpty(assignmentContext.AzureFilesConnectionString))
            {
                ApplyAzureFilesContext(assignmentContext.AzureFilesConnectionString, assignmentContext.AzureFilesContentShare, "/home");
            }
        }
        private async Task AddTokenClaimsToPrincipal(string authenticationScheme, ClaimsPrincipal principal, string tokenName)
        {
            var jwtToken = await HttpContext.GetTokenAsync("External", tokenName);

            if (!string.IsNullOrWhiteSpace(jwtToken))
            {
                var token          = new JwtSecurityToken(jwtToken);
                var claimsIdentity = new ClaimsIdentity(token.Claims, tokenName);

                // die OpenIdConnectOptions zum authenticationScheme ermittteln
                var options = _optionsFactory.Create(authenticationScheme);

                // Alle Claimsctions ausführen, diese löschen z.b. nicht benötigte Claims für Cookies.
                foreach (var action in options.ClaimActions)
                {
                    action.Run(null, claimsIdentity, null);
                }

                principal.AddIdentity(claimsIdentity);
            }
        }