internal ServiceBusConnectionStringBuilder(KeyValueConfigurationManager keyValueManager) : this()
 {
     if (keyValueManager != null)
     {
         this.InitializeFromKeyValueManager(keyValueManager);
     }
 }
示例#2
0
        public void LoadAssemblySettings()
        {
            var multiSourceKeyValueConfiguration = KeyValueConfigurationManager
                                                   .Add(NoConfiguration.Empty).AddReflectionSettings(AppDomain.CurrentDomain.GetAssemblies())
                                                   .Build();

            multiSourceKeyValueConfiguration.ShouldNotBeNull();
        }
示例#3
0
        public NotificationHubManager(string connectionString, string notificationHubPath)
        {
            this.notificationHubPath = notificationHubPath;
            KeyValueConfigurationManager keyValueConfigurationManager = new KeyValueConfigurationManager(connectionString);

            this.namespaceManager = keyValueConfigurationManager.CreateNamespaceManager();
            this.GetTokenProvider(keyValueConfigurationManager);
            this.GetBaseUri(keyValueConfigurationManager);
        }
示例#4
0
        public void MultiSourceAllValues()
        {
            IKeyValueConfiguration configuration = KeyValueConfigurationManager.Add(NoConfiguration.Empty).Build();

            if (configuration is IDisposable disposable)
            {
                disposable.Dispose();
            }

            Assert.Throws <ObjectDisposedException>(() => configuration.AllValues.ToString());
        }
示例#5
0
        public static void Execute()
        {
            var collection = new NameValueCollection
            {
                { string.Empty, string.Empty },
                { null, null },
                { null, string.Empty },
                { string.Empty, null },
                { "\t", "\t" },
                { "urn:test:key", "a-test-value" },
                { "urn:test:KEY", "second-test-value" },
                { "urn:another-key", "another-test-value" }
            };

            IKeyValueConfiguration appSettingsKeyValueConfiguration = new InMemoryKeyValueConfiguration(collection);

            KeyValueConfigurationManager.Add(appSettingsKeyValueConfiguration).Build();

            var goodKeys = new List <string>
            {
                "a-non-existing-key",
                "urn:test:key",
                "urn:TEST:key",
                "urn:test:KEY",
                "urn:another-key"
            };

            var keys = Specials.Special.ToList();

            keys.AddRange(goodKeys.Select(goodKey => new KeyValuePair <string, string?>(goodKey, goodKey)));

            var builder = new StringBuilder();

            foreach (var pair in keys)
            {
                builder.Append("Key: ").AppendLine(pair.Key);

                string?value = appSettingsKeyValueConfiguration.ValueOrDefault(pair.Value !);

                string displayValue = Specials.GetDisplayValue(value !);

                builder.Append("\t Instance: ").AppendLine(displayValue);

                string staticValue = StaticKeyValueConfigurationManager.AppSettings[pair.Value];

                string staticDisplayValue = Specials.GetDisplayValue(staticValue);

                builder.Append("\t Static: ").AppendLine(staticDisplayValue);
            }

            Console.WriteLine(builder.ToString());
        }
示例#6
0
        private void GetBaseUri(KeyValueConfigurationManager manager)
        {
            string item = manager.connectionProperties["Endpoint"];
            string str  = manager.connectionProperties["ManagementPort"];

            using (IEnumerator <Uri> enumerator = KeyValueConfigurationManager.GetEndpointAddresses(item, str).GetEnumerator())
            {
                if (enumerator.MoveNext())
                {
                    this.baseUri = enumerator.Current;
                }
            }
        }
        public static MultiSourceKeyValueConfiguration InitializeStartupConfiguration(IReadOnlyList <string> args,
                                                                                      IReadOnlyDictionary <string, string> environmentVariables,
                                                                                      IReadOnlyCollection <Assembly> assemblies)
        {
            var tempSource = KeyValueConfigurationManager.Add(NoConfiguration.Empty)
                             .AddEnvironmentVariables(environmentVariables)
                             .AddCommandLineArgsSettings(args).Build();

            var multiSourceKeyValueConfiguration = KeyValueConfigurationManager.Add(NoConfiguration.Empty)
                                                   .AddReflectionSettings(assemblies, tempSource).AddEnvironmentVariables(environmentVariables)
                                                   .AddCommandLineArgsSettings(args).DecorateWith(new ExpandKeyValueConfigurationDecorator()).Build();

            return(multiSourceKeyValueConfiguration);
        }
示例#8
0
        public void MultiSourceShouldDisposeNested()
        {
            IKeyValueConfiguration inMemoryKeyValueConfiguration =
                new Core.InMemoryKeyValueConfiguration(new NameValueCollection());
            IKeyValueConfiguration configuration =
                KeyValueConfigurationManager.Add(inMemoryKeyValueConfiguration).Build();

            if (configuration is IDisposable disposable)
            {
                disposable.Dispose();
            }

            Assert.Throws <ObjectDisposedException>(() => inMemoryKeyValueConfiguration.AllKeys.ToString());
        }
示例#9
0
        public void ItShouldUseValuesDefined()
        {
            IConfigurationRoot configurationRoot = new ConfigurationBuilder()
                                                   .AddInMemoryCollection(new Dictionary <string, string> {
                ["a:b:c"] = "123"
            }).Build();

            MultiSourceKeyValueConfiguration multiSourceKeyValueConfiguration = KeyValueConfigurationManager
                                                                                .Add(new KeyValueConfigurationAdapter(configurationRoot)).Build();

            string actual = multiSourceKeyValueConfiguration["a:b:c"];

            Assert.Equal("123", actual);
        }
        public static void Execute()
        {
            var collection = new NameValueCollection
            {
                { "urn:test:key", "a" }, { "urn:another-key", "b" }, { "urn:yet-another-key", "c" }
            };

            IKeyValueConfiguration appSettingsKeyValueConfiguration = new InMemoryKeyValueConfiguration(collection);

            KeyValueConfigurationManager.Add(appSettingsKeyValueConfiguration).Build();

            bool succeeded = true;

            Parallel.For(
                1,
                1001,
                index =>
            {
                Console.WriteLine("Loop index {0} on thread {1}", index, Thread.CurrentThread.ManagedThreadId);

                string a = StaticKeyValueConfigurationManager.AppSettings["urn:test:key"];

                if (a != "a")
                {
                    Console.WriteLine("WRONG a in index {0}, value {1}", index, a);
                    succeeded = false;
                }

                string b = StaticKeyValueConfigurationManager.AppSettings["urn:another-key"];

                if (b != "b")
                {
                    Console.WriteLine("WRONG b in index {0}, value {1}", index, b);
                    succeeded = false;
                }

                string c = StaticKeyValueConfigurationManager.AppSettings["urn:yet-another-key"];

                if (c != "c")
                {
                    Console.WriteLine("WRONG c in index {0}, value {1}", index, c);
                    succeeded = false;
                }
            });

            Console.WriteLine(succeeded
                ? "OK"
                : "Failed");
        }
        public void ItShouldExpandEnvironmentVariables()
        {
            string tempPath = Path.GetTempPath();

            const string pattern = "%temp%\\";

            string valueWithPattern = $"{pattern} hello";

            var values = new NameValueCollection {
                ["Test"] = valueWithPattern
            };

            var multiSourceKeyValueConfiguration = KeyValueConfigurationManager
                                                   .Add(new Core.InMemoryKeyValueConfiguration(values))
                                                   .DecorateWith(new ExpandKeyValueConfigurationDecorator())
                                                   .Build();
示例#12
0
        public void ItShouldResolveSingleInstanceFromUrn()
        {
            IConfigurationRoot configurationRoot = new ConfigurationBuilder()
                                                   .AddInMemoryCollection(new Dictionary <string, string>
            {
                ["urn:test:simple:instance:name"] = "John", ["urn:test:simple:instance:age"] = "42"
            }).Build();

            MultiSourceKeyValueConfiguration multiSourceKeyValueConfiguration = KeyValueConfigurationManager
                                                                                .Add(new KeyValueConfigurationAdapter(configurationRoot)).Build();

            SimpleCtorType actual = multiSourceKeyValueConfiguration.GetInstance <SimpleCtorType>() ?? throw new InvalidOperationException(
                                              $"Could not get {nameof(SimpleCtorType)}");

            Assert.Equal(new SimpleCtorType("John", 42), actual, SimpleCtorType.NameAgeComparer);
        }
示例#13
0
        public static void Execute()
        {
            KeyValueConfigurationManager
            .Add(new ReflectionKeyValueConfiguration(typeof(SampleConfigurationConstants).Assembly)).Build();

            ImmutableArray <ConfigurationMetadata> metadataFromAssemblyTypes =
                typeof(SampleConfigurationConstants).Assembly.GetMetadataFromAssemblyTypes();

            Console.WriteLine(JsonConvert.SerializeObject(metadataFromAssemblyTypes, Formatting.Indented));

            Console.WriteLine("Contains {0} keys", StaticKeyValueConfigurationManager.AppSettings.AllKeys.Length);

            foreach (StringPair stringPair in StaticKeyValueConfigurationManager.AppSettings.AllValues)
            {
                Console.WriteLine(stringPair);
            }
        }
        public void ItShouldExpandCustomEnvironmentVariables()
        {
            Environment.SetEnvironmentVariable("abcvalue", "123");


            var values = new NameValueCollection {
                ["Test"] = "%abcvalue%"
            };

            var multiSourceKeyValueConfiguration = KeyValueConfigurationManager
                                                   .Add(new Core.InMemoryKeyValueConfiguration(values))
                                                   .DecorateWith(new ExpandKeyValueConfigurationDecorator())
                                                   .Build();

            string expanded = multiSourceKeyValueConfiguration["test"];

            Assert.Equal("123", expanded);
        }
        public static MultiSourceKeyValueConfiguration InitializeConfiguration(
            [NotNull] Func <string, string> basePath,
            ILogger logger)
        {
            if (basePath == null)
            {
                throw new ArgumentNullException(nameof(basePath));
            }

            string environmentBasedSettingsPath =
                Environment.GetEnvironmentVariable(Configuration.ConfigurationConstants.JsonSettingsFile);

            string environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";

            AppSettingsBuilder appSettingsBuilder = KeyValueConfigurationManager
                                                    .Add(new ReflectionKeyValueConfiguration(typeof(ConfigurationInitialization).Assembly))
                                                    .Add(new JsonKeyValueConfiguration(basePath("settings.json"), false))
                                                    .Add(new JsonKeyValueConfiguration(basePath($"settings.{environmentName}.json"), false))
                                                    .Add(new JsonKeyValueConfiguration(basePath($"settings.{Environment.MachineName}.json"), false));

            if (environmentBasedSettingsPath.HasValue() && File.Exists(environmentBasedSettingsPath))
            {
                appSettingsBuilder =
                    appSettingsBuilder.Add(new JsonKeyValueConfiguration(environmentBasedSettingsPath,
                                                                         true));

                logger.Information("Added environment based configuration from key '{Key}', file '{File}'", Configuration.ConfigurationConstants.JsonSettingsFile, environmentBasedSettingsPath);
            }

            MultiSourceKeyValueConfiguration multiSourceKeyValueConfiguration = appSettingsBuilder
                                                                                .Add(new EnvironmentVariableKeyValueConfigurationSource())
                                                                                .Add(new UserConfiguration())
                                                                                .DecorateWith(new ExpandKeyValueConfigurationDecorator())
                                                                                .Build();

            logger.Information("Configuration done using chain {Chain}",
                               multiSourceKeyValueConfiguration.SourceChain);

            return(multiSourceKeyValueConfiguration);
        }
示例#16
0
        private void GetTokenProvider(KeyValueConfigurationManager manager)
        {
            IEnumerable <Uri> endpointAddresses = KeyValueConfigurationManager.GetEndpointAddresses(manager.connectionProperties["StsEndpoint"], null);
            string            item  = manager.connectionProperties["SharedSecretIssuer"];
            string            str   = manager.connectionProperties["SharedSecretValue"];
            string            item1 = manager.connectionProperties["SharedAccessKeyName"];
            string            str1  = manager.connectionProperties["SharedAccessKey"];

            if (string.IsNullOrEmpty(str))
            {
                if (string.IsNullOrEmpty(item1))
                {
                    throw new ArgumentException("connectionString");
                }
                this.tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(item1, str1);
                return;
            }
            if (endpointAddresses == null || !endpointAddresses.Any <Uri>())
            {
                this.tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(item, str);
                return;
            }
            this.tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(item, str, endpointAddresses.First <Uri>());
        }
        public static MultiSourceKeyValueConfiguration InitializeConfiguration(
            IReadOnlyList <string> args,
            [NotNull] Func <string, string> basePath,
            ILogger logger,
            IReadOnlyCollection <Assembly> scanAssemblies,
            string contentBasePath)
        {
            if (basePath == null)
            {
                throw new ArgumentNullException(nameof(basePath));
            }

            string environmentBasedSettingsPath =
                Environment.GetEnvironmentVariable(ConfigurationConstants.JsonSettingsFile);

            string environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";

            AppSettingsBuilder appSettingsBuilder = KeyValueConfigurationManager
                                                    .Add(new InMemoryKeyValueConfiguration(new NameValueCollection()));

            foreach (Assembly currentAssembly in scanAssemblies.OrderBy(assembly => assembly.FullName))
            {
                appSettingsBuilder =
                    appSettingsBuilder.Add(
                        new ReflectionKeyValueConfiguration(currentAssembly));
            }

            var loggingSettings = new NameValueCollection
            {
                { "Logging:LogLevel:Default", "Warning" },
                { "Logging:LogLevel:System.Net.Http.HttpClient", "Warning" },
                { "LogLevel:System.Net.Http.HttpClient", "Warning" }
            };

            FileInfo MachineSpecificConfig(DirectoryInfo directoryInfo)
            {
                return(directoryInfo.GetFiles($"settings.{Environment.MachineName}.json").SingleOrDefault());
            }

            string MachineSpecificFile()
            {
                var baseDirectory = new DirectoryInfo(basePath(null));

                FileInfo machineSpecificConfig = null;

                DirectoryInfo currentDirectory = baseDirectory;

                while (machineSpecificConfig is null && currentDirectory != null)
                {
                    try
                    {
                        machineSpecificConfig = MachineSpecificConfig(currentDirectory);

                        currentDirectory = currentDirectory.Parent;
                    }
                    catch (Exception ex) when(!ex.IsFatal())
                    {
                        logger.Warning(ex, "Could not find machine specific config file in any parent directory starting with base directory {BaseDirectory}", baseDirectory.FullName);
                        return(null);
                    }
                }

                return(machineSpecificConfig?.FullName);
            }

            appSettingsBuilder = appSettingsBuilder
                                 .Add(new InMemoryKeyValueConfiguration(loggingSettings))
                                 .Add(new JsonKeyValueConfiguration(basePath("settings.json"), false))
                                 .Add(new JsonKeyValueConfiguration(basePath($"settings.{environmentName}.json"), false));

            string machineSpecificFile = MachineSpecificFile();

            if (!string.IsNullOrWhiteSpace(machineSpecificFile))
            {
                appSettingsBuilder = appSettingsBuilder.Add(new JsonKeyValueConfiguration(machineSpecificFile));
            }

            if (environmentBasedSettingsPath.HasValue() && File.Exists(environmentBasedSettingsPath))
            {
                appSettingsBuilder =
                    appSettingsBuilder.Add(new JsonKeyValueConfiguration(environmentBasedSettingsPath,
                                                                         true));

                logger.Information("Added environment based configuration from key '{Key}', file '{File}'",
                                   ConfigurationConstants.JsonSettingsFile,
                                   environmentBasedSettingsPath);
            }

            var nameValueCollection = new NameValueCollection(StringComparer.OrdinalIgnoreCase);

            const char variableAssignmentCharacter = '=';

            foreach (string arg in args.Where(a => a.Count(c => c == variableAssignmentCharacter) == 1 && a.Length >= 3))
            {
                string[] parts = arg.Split(variableAssignmentCharacter, StringSplitOptions.RemoveEmptyEntries);

                if (parts.Length != 2)
                {
                    Console.WriteLine($"arg {arg} has length {parts.Length}");
                    continue;
                }

                string key   = parts[0];
                string value = parts[1];

                nameValueCollection.Add(key, value);
            }

            var inMemoryKeyValueConfiguration = new InMemoryKeyValueConfiguration(nameValueCollection);

            MultiSourceKeyValueConfiguration multiSourceKeyValueConfiguration = appSettingsBuilder
                                                                                .Add(new JsonKeyValueConfiguration(Path.Combine(contentBasePath, "config.user"), throwWhenNotExists: false))
                                                                                .Add(new EnvironmentVariableKeyValueConfigurationSource())
                                                                                .Add(inMemoryKeyValueConfiguration)
                                                                                .DecorateWith(new ExpandKeyValueConfigurationDecorator())
                                                                                .Build();

            logger.Information("Configuration done using chain {Chain}",
                               multiSourceKeyValueConfiguration.SourceChain);

            return(multiSourceKeyValueConfiguration);
        }
        public static VolatileTopicClient CreateFromConnectionString(string connectionString, string path, string clientId, Microsoft.ServiceBus.Messaging.Filter filter)
        {
            KeyValueConfigurationManager keyValueConfigurationManager = new KeyValueConfigurationManager(connectionString);

            return(keyValueConfigurationManager.CreateMessagingFactory().CreateVolatileTopicClient(path, clientId, filter));
        }
示例#19
0
        public static async Task <DeployerApp> BuildAppAsync([NotNull] string[] inputArgs,
                                                             ILogger?logger = null,
                                                             CancellationToken cancellationToken = default)
        {
            if (inputArgs is null)
            {
                throw new ArgumentNullException(nameof(inputArgs));
            }

            var args = inputArgs.ToImmutableArray();

            bool hasDefinedLogger = logger is {};

            string outputTemplate = GetOutputTemplate(args);

            var levelSwitch = new LoggingLevelSwitch();

            logger ??= new LoggerConfiguration()
            .WriteTo.Console(outputTemplate: outputTemplate, standardErrorFromLevel: LogEventLevel.Error)
            .MinimumLevel.ControlledBy(levelSwitch)
            .CreateLogger();

            logger.Verbose("Using output template {Template}", outputTemplate);

            try
            {
                string?machineSettings =
                    GetMachineSettingsFile(new DirectoryInfo(Path.Combine(
                                                                 Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "tools", "Milou.Deployer")));

                AppSettingsBuilder appSettingsBuilder;

                try
                {
                    appSettingsBuilder = KeyValueConfigurationManager
                                         .Add(new ReflectionKeyValueConfiguration(typeof(AppBuilder).Assembly))
                                         .Add(new ReflectionKeyValueConfiguration(typeof(ConfigurationKeys).Assembly));
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    logger.Error(ex, "Could note create settings");
                    throw;
                }

                if (!string.IsNullOrWhiteSpace(machineSettings))
                {
                    logger.Information("Using machine specific configuration file '{Settings}'", machineSettings);
                    appSettingsBuilder =
                        appSettingsBuilder.Add(new JsonKeyValueConfiguration(machineSettings, false));
                }

                string?configurationFile =
                    Environment.GetEnvironmentVariable(ConfigurationKeys.KeyValueConfigurationFile);

                if (!string.IsNullOrWhiteSpace(configurationFile) && File.Exists(configurationFile))
                {
                    logger.Information("Using configuration values from file '{ConfigurationFile}'", configurationFile);
                    appSettingsBuilder =
                        appSettingsBuilder.Add(new JsonKeyValueConfiguration(configurationFile, false));
                }

                var argsAsParameters = args
                                       .Where(arg => arg.StartsWith("-", StringComparison.OrdinalIgnoreCase))
                                       .Select(arg => arg.TrimStart('-'))
                                       .ToImmutableArray();

                MultiSourceKeyValueConfiguration configuration = appSettingsBuilder
                                                                 .Add(new EnvironmentVariableKeyValueConfigurationSource())
                                                                 .AddCommandLineArgsSettings(argsAsParameters)
                                                                 .Add(new UserJsonConfiguration())
                                                                 .Build();

                logger.Debug("Using configuration: {Configuration}", configuration.SourceChain);

                string logPath = configuration[ConsoleConfigurationKeys.LoggingFilePath];

                string environmentLogLevel =
                    configuration[ConfigurationKeys.LogLevelEnvironmentVariable];

                string configurationLogLevel = configuration[ConfigurationKeys.LogLevel];

                var logLevel =
                    Arbor.App.Extensions.Logging.LogEventLevelExtensions.ParseOrDefault(
                        environmentLogLevel.WithDefault(configurationLogLevel));

                levelSwitch.MinimumLevel = logLevel;

                LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
                                                          .WriteTo.Console(outputTemplate: outputTemplate);

                if (!string.IsNullOrWhiteSpace(logPath))
                {
                    loggerConfiguration = loggerConfiguration.WriteTo.File(logPath);
                }

                if (!hasDefinedLogger)
                {
                    if (logger is IDisposable disposable)
                    {
                        disposable.Dispose();
                    }

                    logger = loggerConfiguration
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .CreateLogger();
                }

                if (!string.IsNullOrWhiteSpace(machineSettings))
                {
                    logger.Information("Using machine specific configuration file '{Settings}'", machineSettings);
                }

                string?nugetSource = args.GetArgumentValueOrDefault("nuget-source");
                string?nugetConfig = args.GetArgumentValueOrDefault("nuget-config");

                var webDeployConfig = new WebDeployConfig(new WebDeployRulesConfig(
                                                              true,
                                                              true,
                                                              false,
                                                              true,
                                                              true));

                bool allowPreReleaseEnabled =
                    configuration[ConfigurationKeys.AllowPreReleaseEnvironmentVariable]
                    .ParseAsBooleanOrDefault() ||
                    (Debugger.IsAttached &&
                     configuration[ConfigurationKeys.ForceAllowPreRelease]
                     .ParseAsBooleanOrDefault());

                string?nuGetExePath = configuration[ConfigurationKeys.NuGetExePath];

                if (string.IsNullOrWhiteSpace(nuGetExePath))
                {
                    logger.Debug("nuget.exe is not specified, downloading with {Tool}", nameof(NuGetDownloadClient));

                    using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
                    {
                        var nuGetDownloadClient = new NuGetDownloadClient();
                        NuGetDownloadResult nuGetDownloadResult;

                        using (var httpClient = new HttpClient())
                        {
                            nuGetDownloadResult = await nuGetDownloadClient
                                                  .DownloadNuGetAsync(NuGetDownloadSettings.Default, logger, httpClient, cts.Token)
                                                  .ConfigureAwait(false);
                        }

                        if (!nuGetDownloadResult.Succeeded)
                        {
                            throw new InvalidOperationException(
                                      Resources.NuGetExeCouldNotBeDownloaded);
                        }

                        nuGetExePath = nuGetDownloadResult.NuGetExePath;
                    }

                    logger.Debug("Successfully downloaded nuget.exe to '{DownloadedPath}'", nuGetExePath);
                }

                var deployerConfiguration = new DeployerConfiguration(webDeployConfig)
                {
                    NuGetExePath               = nuGetExePath,
                    NuGetConfig                = nugetConfig.WithDefault(configuration[ConfigurationKeys.NuGetConfig]),
                    NuGetSource                = nugetSource.WithDefault(configuration[ConfigurationKeys.NuGetSource]),
                    AllowPreReleaseEnabled     = allowPreReleaseEnabled,
                    StopStartIisWebSiteEnabled = configuration[ConfigurationKeys.StopStartIisWebSiteEnabled]
                                                 .ParseAsBooleanOrDefault(true)
                };

                var nuGetCliSettings = new NuGetCliSettings(
                    deployerConfiguration.NuGetSource,
                    nuGetExePath: deployerConfiguration.NuGetExePath,
                    nugetConfigFile: deployerConfiguration.NuGetConfig);

                var nuGetPackageInstaller =
                    new NuGetPackageInstaller(logger: logger, nugetCliSettings: nuGetCliSettings);

                var deploymentService = new DeploymentService(
                    deployerConfiguration,
                    logger,
                    configuration,
                    new WebDeployHelper(logger),
                    deploymentExecutionDefinition =>
                    IisManager.Create(deployerConfiguration, logger, deploymentExecutionDefinition),
                    nuGetPackageInstaller,
                    new FtpHandlerFactory());

                string temp = configuration[ConfigurationKeys.TempDirectory];

                const string tempEnvironmentVariableName = "temp";

                if (!string.IsNullOrWhiteSpace(temp) && Directory.Exists(temp))
                {
                    Environment.SetEnvironmentVariable(tempEnvironmentVariableName, temp);
                    Environment.SetEnvironmentVariable("tmp", temp);
                }

                var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                return(new DeployerApp(logger, deploymentService, configuration, levelSwitch, cancellationTokenSource));
            }
            catch (Exception ex) when(!ex.IsFatal())
            {
                logger.Error("Could not build application");
                throw;
            }
        }
        private void InitializeFromKeyValueManager(KeyValueConfigurationManager manager)
        {
            int      num;
            int      num1;
            TimeSpan timeSpan;

            try
            {
                manager.Validate();
                foreach (Uri endpointAddress in KeyValueConfigurationManager.GetEndpointAddresses(manager.connectionProperties["Endpoint"], string.Empty))
                {
                    this.Endpoints.Add(endpointAddress);
                }
                foreach (Uri uri in KeyValueConfigurationManager.GetEndpointAddresses(manager.connectionProperties["StsEndpoint"], string.Empty))
                {
                    this.StsEndpoints.Add(uri);
                }
                if (int.TryParse(manager.connectionProperties["RuntimePort"], out num))
                {
                    this.RuntimePort = num;
                }
                if (int.TryParse(manager.connectionProperties["ManagementPort"], out num1))
                {
                    this.ManagementPort = num1;
                }
                string item = manager.connectionProperties["OperationTimeout"];
                if (!string.IsNullOrWhiteSpace(item) && TimeSpan.TryParse(item, CultureInfo.CurrentCulture, out timeSpan) && !timeSpan.Equals(this.OperationTimeout))
                {
                    this.OperationTimeout = timeSpan;
                }
                string str = manager.connectionProperties["SharedSecretIssuer"];
                if (!string.IsNullOrWhiteSpace(str))
                {
                    this.SharedSecretIssuerName = str;
                }
                string item1 = manager.connectionProperties["SharedSecretValue"];
                if (!string.IsNullOrWhiteSpace(item1))
                {
                    this.SharedSecretIssuerSecret = item1;
                }
                string str1 = manager.connectionProperties["SharedAccessKeyName"];
                if (!string.IsNullOrWhiteSpace(str1))
                {
                    this.SharedAccessKeyName = str1;
                }
                string item2 = manager.connectionProperties["SharedAccessKey"];
                if (!string.IsNullOrWhiteSpace(item2))
                {
                    this.SharedAccessKey = item2;
                }
                string str2 = manager.connectionProperties["WindowsDomain"];
                if (!string.IsNullOrWhiteSpace(str2))
                {
                    this.WindowsCredentialDomain = str2;
                }
                string item3 = manager.connectionProperties["WindowsUsername"];
                if (!string.IsNullOrWhiteSpace(item3))
                {
                    this.WindowsCredentialUsername = item3;
                }
                this.WindowsCredentialPassword = manager.GetWindowsPassword();
                string str3 = manager.connectionProperties["OAuthDomain"];
                if (!string.IsNullOrWhiteSpace(str3))
                {
                    this.OAuthDomain = str3;
                }
                string item4 = manager.connectionProperties["OAuthUsername"];
                if (!string.IsNullOrWhiteSpace(item4))
                {
                    this.OAuthUsername = item4;
                }
                this.OAuthPassword = manager.GetOAuthPassword();
                string str4 = manager.connectionProperties["TransportType"];
                if (!string.IsNullOrWhiteSpace(str4))
                {
                    this.TransportType = (Microsoft.ServiceBus.Messaging.TransportType)Enum.Parse(typeof(Microsoft.ServiceBus.Messaging.TransportType), str4);
                }
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                throw new ArgumentException(exception.Message, "connectionString", exception);
            }
        }
示例#21
0
        public static EventHubClient CreateFromConnectionString(string connectionString, string path)
        {
            KeyValueConfigurationManager keyValueConfigurationManager = new KeyValueConfigurationManager(connectionString, new TransportType?(TransportType.Amqp));

            return(keyValueConfigurationManager.CreateMessagingFactory().CreateEventHubClient(path));
        }
示例#22
0
        public async Task <ExitCode> RunAsync(string[] args)
        {
            MultiSourceKeyValueConfiguration multiSourceKeyValueConfiguration = KeyValueConfigurationManager.Add(new UserConfiguration())
                                                                                .Add(new AppSettingsKeyValueConfiguration())
                                                                                .Build();

            StaticKeyValueConfigurationManager.Initialize(multiSourceKeyValueConfiguration);

            bool simulateDebug =
                bool.TryParse(Environment.GetEnvironmentVariable("SimulateDebug"), out bool parsed) && parsed;

            bool debugLoggerEnabled = false;

            if (Debugger.IsAttached || simulateDebug)
            {
                if (simulateDebug)
                {
                    _logger.Write("Simulating debug");
                }

                await StartWithDebuggerAsync(args).ConfigureAwait(false);

                if (debugLoggerEnabled)
                {
                    _logger = new DebugLogger(_logger);
                }
            }

            _container = await BuildBootstrapper.StartAsync();

            _logger.Write($"Using logger '{_logger.GetType()}' with log level {_logger.LogLevel}");
            _cancellationToken = CancellationToken.None;
            ExitCode exitCode;
            var      stopwatch = new Stopwatch();

            stopwatch.Start();
            try
            {
                ExitCode systemToolsResult = await RunSystemToolsAsync();

                if (!systemToolsResult.IsSuccess)
                {
                    const string ToolsMessage = "All system tools did not succeed";
                    _logger.WriteError(ToolsMessage);

                    exitCode = systemToolsResult;
                }
                else
                {
                    exitCode = ExitCode.Success;
                    _logger.Write("All tools succeeded");
                }
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.ToString());
                exitCode = ExitCode.Failure;
            }

            stopwatch.Stop();

            _logger.Write($"Arbor.X.Build total elapsed time in seconds: {stopwatch.Elapsed.TotalSeconds:F}");

            ParseResult <int> exitDelayInMilliseconds =
                Environment.GetEnvironmentVariable(WellKnownVariables.BuildApplicationExitDelayInMilliseconds)
                .TryParseInt32(0);

            if (exitDelayInMilliseconds > 0)
            {
                _logger.Write(
                    $"Delaying build application exit with {exitDelayInMilliseconds} milliseconds specified in '{WellKnownVariables.BuildApplicationExitDelayInMilliseconds}'");
                await Task.Delay(TimeSpan.FromMilliseconds(exitDelayInMilliseconds), _cancellationToken);
            }

            if (Debugger.IsAttached)
            {
                WriteDebug($"Exiting build application with exit code {exitCode}");

                if (!debugLoggerEnabled)
                {
                    Debugger.Break();
                }
            }

            return(exitCode);
        }