Пример #1
0
        public static void set_environment_variables(ChocolateyConfiguration config)
        {
            reset_environment_variables(config);

            Environment.SetEnvironmentVariable(ApplicationParameters.ChocolateyInstallEnvironmentVariableName, ApplicationParameters.InstallLocation);
            Environment.SetEnvironmentVariable("CHOCOLATEY_VERSION", config.Information.ChocolateyVersion);
            Environment.SetEnvironmentVariable("CHOCOLATEY_VERSION_PRODUCT", config.Information.ChocolateyProductVersion);
            Environment.SetEnvironmentVariable("OS_PLATFORM", config.Information.PlatformType.get_description_or_value());
            Environment.SetEnvironmentVariable("OS_VERSION", config.Information.PlatformVersion.to_string());
            Environment.SetEnvironmentVariable("OS_NAME", config.Information.PlatformName.to_string());
            // experimental until we know if this value returns correctly based on the OS and not the current process.
            Environment.SetEnvironmentVariable("OS_IS64BIT", config.Information.Is64BitOperatingSystem ? "true" : "false");
            Environment.SetEnvironmentVariable("PROCESS_IS64BIT", config.Information.Is64BitProcess ? "true" : "false");
            Environment.SetEnvironmentVariable("USER_NAME", config.Information.UserName);
            Environment.SetEnvironmentVariable("USER_DOMAIN", config.Information.UserDomainName);
            Environment.SetEnvironmentVariable("IS_ADMIN", config.Information.IsUserAdministrator ? "true" : "false");
            Environment.SetEnvironmentVariable("IS_SYSTEM", config.Information.IsUserSystemAccount ? "true" : "false");
            Environment.SetEnvironmentVariable("IS_REMOTEDESKTOP", config.Information.IsUserRemoteDesktop ? "true" : "false");
            Environment.SetEnvironmentVariable("IS_REMOTE", config.Information.IsUserRemote ? "true" : "false");
            Environment.SetEnvironmentVariable("IS_PROCESSELEVATED", config.Information.IsProcessElevated ? "true" : "false");
            Environment.SetEnvironmentVariable("TEMP", config.CacheLocation);
            Environment.SetEnvironmentVariable("TMP", config.CacheLocation);

            if (config.Debug)
            {
                Environment.SetEnvironmentVariable("ChocolateyEnvironmentDebug", "true");
            }
            if (config.Verbose)
            {
                Environment.SetEnvironmentVariable("ChocolateyEnvironmentVerbose", "true");
            }
            if (!config.Features.ChecksumFiles)
            {
                Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyIgnoreChecksums, "true");
            }
            if (config.Features.AllowEmptyChecksums)
            {
                Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyAllowEmptyChecksums, "true");
            }
            if (config.Features.AllowEmptyChecksumsSecure)
            {
                Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyAllowEmptyChecksumsSecure, "true");
            }

            Environment.SetEnvironmentVariable("chocolateyRequestTimeout", config.WebRequestTimeoutSeconds.to_string() + "000");

            if (config.CommandExecutionTimeoutSeconds != 0)
            {
                Environment.SetEnvironmentVariable("chocolateyResponseTimeout", config.CommandExecutionTimeoutSeconds.to_string() + "000");
            }

            if (!string.IsNullOrWhiteSpace(config.Proxy.Location))
            {
                var proxyCreds = string.Empty;
                if (!string.IsNullOrWhiteSpace(config.Proxy.User) &&
                    !string.IsNullOrWhiteSpace(config.Proxy.EncryptedPassword)
                    )
                {
                    proxyCreds = "{0}:{1}@".format_with(config.Proxy.User, NugetEncryptionUtility.DecryptString(config.Proxy.EncryptedPassword));

                    Environment.SetEnvironmentVariable("chocolateyProxyUser", config.Proxy.User);
                    Environment.SetEnvironmentVariable("chocolateyProxyPassword", NugetEncryptionUtility.DecryptString(config.Proxy.EncryptedPassword));
                }

                Environment.SetEnvironmentVariable("http_proxy", "{0}{1}".format_with(proxyCreds, config.Proxy.Location));
                Environment.SetEnvironmentVariable("https_proxy", "{0}{1}".format_with(proxyCreds, config.Proxy.Location));
                Environment.SetEnvironmentVariable("chocolateyProxyLocation", config.Proxy.Location);

                if (!string.IsNullOrWhiteSpace(config.Proxy.BypassList))
                {
                    Environment.SetEnvironmentVariable("chocolateyProxyBypassList", config.Proxy.BypassList);
                    Environment.SetEnvironmentVariable("no_proxy", config.Proxy.BypassList);
                }

                if (config.Proxy.BypassOnLocal)
                {
                    Environment.SetEnvironmentVariable("chocolateyProxyBypassOnLocal", "true");
                }
            }

            if (config.Features.UsePowerShellHost)
            {
                Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPowerShellHost, "true");
            }
            if (config.Force)
            {
                Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyForce, "true");
            }
            if (config.Features.ExitOnRebootDetected)
            {
                Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyExitOnRebootDetected, "true");
            }
            set_licensed_environment(config);
        }
Пример #2
0
        public void source_add(ChocolateyConfiguration configuration)
        {
            var source = configFileSettings.Sources.FirstOrDefault(p => p.Id.is_equal_to(configuration.SourceCommand.Name));

            if (source == null)
            {
                source = new ConfigFileSourceSetting
                {
                    Id                  = configuration.SourceCommand.Name,
                    Value               = configuration.Sources,
                    UserName            = configuration.SourceCommand.Username,
                    Password            = NugetEncryptionUtility.EncryptString(configuration.SourceCommand.Password),
                    Certificate         = configuration.SourceCommand.Certificate,
                    CertificatePassword = NugetEncryptionUtility.EncryptString(configuration.SourceCommand.CertificatePassword),
                    Priority            = configuration.SourceCommand.Priority,
                    BypassProxy         = configuration.SourceCommand.BypassProxy,
                };
                configFileSettings.Sources.Add(source);

                _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation);
                if (!configuration.QuietOutput)
                {
                    this.Log().Warn(() => "Added {0} - {1} (Priority {2})".format_with(source.Id, source.Value, source.Priority));
                }
            }
            else
            {
                var currentPassword            = string.IsNullOrWhiteSpace(source.Password) ? null : NugetEncryptionUtility.DecryptString(source.Password);
                var currentCertificatePassword = string.IsNullOrWhiteSpace(source.CertificatePassword) ? null : NugetEncryptionUtility.DecryptString(source.CertificatePassword);
                if (configuration.Sources.is_equal_to(source.Value) &&
                    configuration.SourceCommand.Priority == source.Priority &&
                    configuration.SourceCommand.Username.is_equal_to(source.UserName) &&
                    configuration.SourceCommand.Password.is_equal_to(currentPassword) &&
                    configuration.SourceCommand.CertificatePassword.is_equal_to(currentCertificatePassword) &&
                    configuration.SourceCommand.Certificate.is_equal_to(source.Certificate) &&
                    configuration.SourceCommand.BypassProxy == source.BypassProxy
                    )
                {
                    if (!configuration.QuietOutput)
                    {
                        this.Log().Warn(NO_CHANGE_MESSAGE);
                    }
                }
                else
                {
                    source.Value               = configuration.Sources;
                    source.Priority            = configuration.SourceCommand.Priority;
                    source.UserName            = configuration.SourceCommand.Username;
                    source.Password            = NugetEncryptionUtility.EncryptString(configuration.SourceCommand.Password);
                    source.CertificatePassword = NugetEncryptionUtility.EncryptString(configuration.SourceCommand.CertificatePassword);
                    source.Certificate         = configuration.SourceCommand.Certificate;
                    source.BypassProxy         = configuration.SourceCommand.BypassProxy;

                    _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation);
                    if (!configuration.QuietOutput)
                    {
                        this.Log().Warn(() => "Updated {0} - {1} (Priority {2})".format_with(source.Id, source.Value, source.Priority));
                    }
                }
            }
        }
Пример #3
0
        private static void set_global_options(IList <string> args, ChocolateyConfiguration config, Container container)
        {
            ConfigurationOptions.parse_arguments_and_update_configuration(
                args,
                config,
                (option_set) =>
            {
                option_set
                .Add("d|debug",
                     "Debug - Show debug messaging.",
                     option => config.Debug = option != null)
                .Add("v|verbose",
                     "Verbose - Show verbose messaging. Very verbose messaging, avoid using under normal circumstances.",
                     option => config.Verbose = option != null)
                .Add("trace",
                     "Trace - Show trace messaging. Very, very verbose trace messaging. Avoid except when needing super low-level .NET Framework debugging. Available in 0.10.4+.",
                     option => config.Trace = option != null)
                .Add("acceptlicense|accept-license",
                     "AcceptLicense - Accept license dialogs automatically. Reserved for future use.",
                     option => config.AcceptLicense = option != null)
                .Add("y|yes|confirm",
                     "Confirm all prompts - Chooses affirmative answer instead of prompting. Implies --accept-license",
                     option =>
                {
                    config.PromptForConfirmation = option == null;
                    config.AcceptLicense         = option != null;
                })
                .Add("f|force",
                     "Force - force the behavior. Do not use force during normal operation - it subverts some of the smart behavior for commands.",
                     option => config.Force = option != null)
                .Add("noop|whatif|what-if",
                     "NoOp / WhatIf - Don't actually do anything.",
                     option => config.Noop = option != null)
                .Add("r|limitoutput|limit-output",
                     "LimitOutput - Limit the output to essential information",
                     option => config.RegularOutput = option == null)
                .Add("timeout=|execution-timeout=",
                     "CommandExecutionTimeout (in seconds) - The time to allow a command to finish before timing out. Overrides the default execution timeout in the configuration of {0} seconds. '0' for infinite starting in 0.10.4.".format_with(config.CommandExecutionTimeoutSeconds.to_string()),
                     option =>
                {
                    int timeout = 0;
                    int.TryParse(option.remove_surrounding_quotes(), out timeout);
                    if (timeout > 0)
                    {
                        config.CommandExecutionTimeoutSeconds = timeout;
                    }
                })
                .Add("c=|cache=|cachelocation=|cache-location=",
                     "CacheLocation - Location for download cache, defaults to %TEMP% or value in chocolatey.config file.",
                     option => config.CacheLocation = option.remove_surrounding_quotes())
                .Add("allowunofficial|allow-unofficial|allowunofficialbuild|allow-unofficial-build",
                     "AllowUnofficialBuild - When not using the official build you must set this flag for choco to continue.",
                     option => config.AllowUnofficialBuild = option != null)
                .Add("failstderr|failonstderr|fail-on-stderr|fail-on-standard-error|fail-on-error-output",
                     "FailOnStandardError - Fail on standard error output (stderr), typically received when running external commands during install providers. This overrides the feature failOnStandardError.",
                     option => config.Features.FailOnStandardError = option != null)
                .Add("use-system-powershell",
                     "UseSystemPowerShell - Execute PowerShell using an external process instead of the built-in PowerShell host. Should only be used when internal host is failing. Available in 0.9.10+.",
                     option => config.Features.UsePowerShellHost = option == null)
                .Add("no-progress",
                     "Do Not Show Progress - Do not show download progress percentages. Available in 0.10.4+.",
                     option => config.Features.ShowDownloadProgress = option == null)
                .Add("proxy=",
                     "Proxy Location - Explicit proxy location. Overrides the default proxy location of '{0}'. Available for config settings in 0.9.9.9+, this CLI option available in 0.10.4+.".format_with(config.Proxy.Location),
                     option => config.Proxy.Location = option.remove_surrounding_quotes())
                .Add("proxy-user="******"Proxy User Name - Explicit proxy user (optional). Requires explicity proxy (`--proxy` or config setting). Overrides the default proxy user of '{0}'. Available for config settings in 0.9.9.9+, this CLI option available in 0.10.4+.".format_with(config.Proxy.User),
                     option => config.Proxy.User = option.remove_surrounding_quotes())
                .Add("proxy-password="******"Proxy Password - Explicit proxy password (optional) to be used with username. Requires explicity proxy (`--proxy` or config setting) and user name.  Overrides the default proxy password (encrypted in settings if set). Available for config settings in 0.9.9.9+, this CLI option available in 0.10.4+.",
                     option => config.Proxy.EncryptedPassword = NugetEncryptionUtility.EncryptString(option.remove_surrounding_quotes()))
                .Add("proxy-bypass-list=",
                     "ProxyBypassList - Comma separated list of regex locations to bypass on proxy. Requires explicity proxy (`--proxy` or config setting). Overrides the default proxy bypass list of '{0}'. Available in 0.10.4+.".format_with(config.Proxy.BypassList),
                     option => config.Proxy.BypassList = option.remove_surrounding_quotes())
                .Add("proxy-bypass-on-local",
                     "Proxy Bypass On Local - Bypass proxy for local connections. Requires explicity proxy (`--proxy` or config setting). Overrides the default proxy bypass on local setting of '{0}'. Available in 0.10.4+.".format_with(config.Proxy.BypassOnLocal),
                     option => config.Proxy.BypassOnLocal = option != null)
                ;
            },
                (unparsedArgs) =>
            {
                if (!string.IsNullOrWhiteSpace(config.CommandName))
                {
                    // save help for next menu
                    config.HelpRequested       = false;
                    config.UnsuccessfulParsing = false;
                }
            },
                () => { },
                () =>
            {
                var commandsLog = new StringBuilder();
                IEnumerable <ICommand> commands = container.GetAllInstances <ICommand>();
                foreach (var command in commands.or_empty_list_if_null())
                {
                    var attributes = command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast <CommandForAttribute>();
                    foreach (var attribute in attributes.or_empty_list_if_null())
                    {
                        commandsLog.AppendFormat(" * {0} - {1}\n", attribute.CommandName, attribute.Description);
                    }
                }

                "chocolatey".Log().Info(@"This is a listing of all of the different things you can pass to choco.
");
                "chocolatey".Log().Info(ChocolateyLoggers.Important, "Commands");
                "chocolatey".Log().Info(@"
{0}

Please run chocolatey with `choco command -help` for specific help on
 each command.
".format_with(commandsLog.ToString()));
                "chocolatey".Log().Info(ChocolateyLoggers.Important, @"How To Pass Options / Switches");
                "chocolatey".Log().Info(@"
You can pass options and switches in the following ways:

 * Unless stated otherwise, an option/switch should only be passed one
   time. Otherwise you may find weird/non-supported behavior.
 * `-`, `/`, or `--` (one character switches should not use `--`)
 * **Option Bundling / Bundled Options**: One character switches can be
   bundled. e.g. `-d` (debug), `-f` (force), `-v` (verbose), and `-y`
   (confirm yes) can be bundled as `-dfvy`.
 * NOTE: If `debug` or `verbose` are bundled with local options
   (not the global ones above), some logging may not show up until after
   the local options are parsed.
 * **Use Equals**: You can also include or not include an equals sign
   `=` between options and values.
 * **Quote Values**: When you need to quote an entire argument, such as
   when using spaces, please use a combination of double quotes and
   apostrophes (`""'value'""`). In cmd.exe you can just use double quotes
   (`""value""`) but in powershell.exe you should use backticks
   (`` `""value`"" ``) or apostrophes (`'value'`). Using the combination
   allows for both shells to work without issue, except for when the next
   section applies.
 * **Periods in PowerShell**: If you need to pass a period as part of a 
   value or a path, PowerShell doesn't always handle it well. Please 
   quote those values using ""Quote Values"" section above.
 * **Pass quotes in arguments**: When you need to pass quoted values to
   to something like a native installer, you are in for a world of fun. In
   cmd.exe you must pass it like this: `-ia ""/yo=""""Spaces spaces""""""`. In
   PowerShell.exe, you must pass it like this: `-ia '/yo=""""Spaces spaces""""'`.
   No other combination will work. In PowerShell.exe if you are on version
   v3+, you can try `--%` before `-ia` to just pass the args through as is,
   which means it should not require any special workarounds.
 * Options and switches apply to all items passed, so if you are
   installing multiple packages, and you use `--version=1.0.0`, choco
   is going to look for and try to install version 1.0.0 of every
   package passed. So please split out multiple package calls when
   wanting to pass specific options.
");
                "chocolatey".Log().Info(ChocolateyLoggers.Important, "Default Options and Switches");
            });
        }
Пример #4
0
        private static void add_or_remove_licensed_source(ChocolateyLicense license, ConfigFileSettings configFileSettings)
        {
            // do not enable or disable the source, in case the user has disabled it
            var addOrUpdate = license.IsValid;
            var sources     = configFileSettings.Sources.or_empty_list_if_null().ToList();

            var configSource = new ConfigFileSourceSetting
            {
                Id               = ApplicationParameters.ChocolateyLicensedFeedSourceName,
                Value            = ApplicationParameters.ChocolateyLicensedFeedSource,
                UserName         = "******",
                Password         = NugetEncryptionUtility.EncryptString(license.Id),
                Priority         = 10,
                BypassProxy      = false,
                AllowSelfService = false,
            };

            if (addOrUpdate && !sources.Any(s =>
                                            s.Id.is_equal_to(ApplicationParameters.ChocolateyLicensedFeedSourceName) &&
                                            NugetEncryptionUtility.DecryptString(s.Password).is_equal_to(license.Id)
                                            )
                )
            {
                configFileSettings.Sources.Add(configSource);
            }

            if (!addOrUpdate)
            {
                configFileSettings.Sources.RemoveWhere(s => s.Id.is_equal_to(configSource.Id));
            }

            // ensure only one licensed source - helpful when moving between licenses
            configFileSettings.Sources.RemoveWhere(s => s.Id.is_equal_to(configSource.Id) && !NugetEncryptionUtility.DecryptString(s.Password).is_equal_to(license.Id));
        }
Пример #5
0
 private static void set_global_options(IList <string> args, ChocolateyConfiguration config, Container container)
 {
     ConfigurationOptions.parse_arguments_and_update_configuration(
         args,
         config,
         (option_set) =>
     {
         option_set
         .Add("d|debug",
              "Debug - Show debug messaging.",
              option => config.Debug = option != null)
         .Add("v|verbose",
              "Verbose - Show verbose messaging. Very verbose messaging, avoid using under normal circumstances.",
              option => config.Verbose = option != null)
         .Add("trace",
              "Trace - Show trace messaging. Very, very verbose trace messaging. Avoid except when needing super low-level .NET Framework debugging. Available in 0.10.4+.",
              option => config.Trace = option != null)
         .Add("nocolor|no-color",
              "No Color - Do not show colorization in logging output. This overrides the feature '{0}', set to '{1}'. Available in 0.10.9+.".format_with(ApplicationParameters.Features.LogWithoutColor, config.Features.LogWithoutColor),
              option => config.Features.LogWithoutColor = option != null)
         .Add("acceptlicense|accept-license",
              "AcceptLicense - Accept license dialogs automatically. Reserved for future use.",
              option => config.AcceptLicense = option != null)
         .Add("y|yes|confirm",
              "Confirm all prompts - Chooses affirmative answer instead of prompting. Implies --accept-license",
              option =>
         {
             config.PromptForConfirmation = option == null;
             config.AcceptLicense         = option != null;
         })
         .Add("f|force",
              "Force - force the behavior. Do not use force during normal operation - it subverts some of the smart behavior for commands.",
              option => config.Force = option != null)
         .Add("noop|whatif|what-if",
              "NoOp / WhatIf - Don't actually do anything.",
              option => config.Noop = option != null)
         .Add("r|limitoutput|limit-output",
              "LimitOutput - Limit the output to essential information",
              option => config.RegularOutput = option == null)
         .Add("timeout=|execution-timeout=",
              "CommandExecutionTimeout (in seconds) - The time to allow a command to finish before timing out. Overrides the default execution timeout in the configuration of {0} seconds. '0' for infinite starting in 0.10.4.".format_with(config.CommandExecutionTimeoutSeconds.to_string()),
              option =>
         {
             int timeout       = 0;
             var timeoutString = option.remove_surrounding_quotes();
             int.TryParse(timeoutString, out timeout);
             if (timeout > 0 || timeoutString.is_equal_to("0"))
             {
                 config.CommandExecutionTimeoutSeconds = timeout;
             }
         })
         .Add("c=|cache=|cachelocation=|cache-location=",
              "CacheLocation - Location for download cache, defaults to %TEMP% or value in chocolatey.config file.",
              option => config.CacheLocation = option.remove_surrounding_quotes())
         .Add("dl=|downloadlocation=|download-location=",
              "Download Location - Downloads specified packages to this dir, defaults to {0}".format_with(ApplicationParameters.PackagesDownloadLocation),
              option => config.PackagesDownloadLocation = option.remove_surrounding_quotes())
         .Add("allowunofficial|allow-unofficial|allowunofficialbuild|allow-unofficial-build",
              "AllowUnofficialBuild - When not using the official build you must set this flag for choco to continue.",
              option => config.AllowUnofficialBuild = option != null)
         .Add("failstderr|failonstderr|fail-on-stderr|fail-on-standard-error|fail-on-error-output",
              "FailOnStandardError - Fail on standard error output (stderr), typically received when running external commands during install providers. This overrides the feature failOnStandardError.",
              option => config.Features.FailOnStandardError = option != null)
         .Add("use-system-powershell",
              "UseSystemPowerShell - Execute PowerShell using an external process instead of the built-in PowerShell host. Should only be used when internal host is failing. Available in 0.9.10+.",
              option => config.Features.UsePowerShellHost = option == null)
         .Add("no-progress",
              "Do Not Show Progress - Do not show download progress percentages. Available in 0.10.4+.",
              option => config.Features.ShowDownloadProgress = option == null)
         .Add("proxy=",
              "Proxy Location - Explicit proxy location. Overrides the default proxy location of '{0}'. Available for config settings in 0.9.9.9+, this CLI option available in 0.10.4+.".format_with(config.Proxy.Location),
              option => config.Proxy.Location = option.remove_surrounding_quotes())
         .Add("proxy-user="******"Proxy User Name - Explicit proxy user (optional). Requires explicit proxy (`--proxy` or config setting). Overrides the default proxy user of '{0}'. Available for config settings in 0.9.9.9+, this CLI option available in 0.10.4+.".format_with(config.Proxy.User),
              option => config.Proxy.User = option.remove_surrounding_quotes())
         .Add("proxy-password="******"Proxy Password - Explicit proxy password (optional) to be used with username. Requires explicit proxy (`--proxy` or config setting) and user name.  Overrides the default proxy password (encrypted in settings if set). Available for config settings in 0.9.9.9+, this CLI option available in 0.10.4+.",
              option => config.Proxy.EncryptedPassword = NugetEncryptionUtility.EncryptString(option.remove_surrounding_quotes()))
         .Add("proxy-bypass-list=",
              "ProxyBypassList - Comma separated list of regex locations to bypass on proxy. Requires explicit proxy (`--proxy` or config setting). Overrides the default proxy bypass list of '{0}'. Available in 0.10.4+.".format_with(config.Proxy.BypassList),
              option => config.Proxy.BypassList = option.remove_surrounding_quotes())
         .Add("proxy-bypass-on-local",
              "Proxy Bypass On Local - Bypass proxy for local connections. Requires explicit proxy (`--proxy` or config setting). Overrides the default proxy bypass on local setting of '{0}'. Available in 0.10.4+.".format_with(config.Proxy.BypassOnLocal),
              option => config.Proxy.BypassOnLocal = option != null)
         .Add("log-file=",
              "Log File to output to in addition to regular loggers. Available in 0.10.8+.",
              option => config.AdditionalLogFileLocation = option.remove_surrounding_quotes())
         ;
     },
         (unparsedArgs) =>
     {
         if (!string.IsNullOrWhiteSpace(config.CommandName))
         {
             // save help for next menu
             config.HelpRequested       = false;
             config.UnsuccessfulParsing = false;
         }
     },
         () => { },
         () =>
     {
         ChocolateyHelpCommand.display_help_message(container);
     });
 }
Пример #6
0
        protected override void Load(ContainerBuilder builder)
        {
            var viewModelAssembly = typeof(ShellViewModel).Assembly;
            var viewAssembly      = typeof(ShellView).Assembly;

            // Register Providers
            builder.RegisterType <VersionNumberProvider>().As <IVersionNumberProvider>().SingleInstance();
            builder.RegisterType <Elevation>().SingleInstance();
            builder.RegisterType <ChocolateyConfigurationProvider>().As <IChocolateyConfigurationProvider>().SingleInstance();
            builder.RegisterType <ChocolateyService>().As <IChocolateyService>().SingleInstance();
            builder.RegisterType <DotNetFileSystem>().As <chocolatey.infrastructure.filesystem.IFileSystem>().SingleInstance();

            // Register ViewModels
            builder.RegisterAssemblyTypes(viewModelAssembly)
            .Where(type => type.Name.EndsWith("ViewModel", StringComparison.Ordinal))
            .Where(type => type.GetInterface(typeof(INotifyPropertyChanged).Name) != null)
            .AsSelf()
            .InstancePerDependency();

            builder.RegisterType <PackageViewModel>().As <IPackageViewModel>();

            var choco = Lets.GetChocolatey();

            builder.RegisterInstance(choco.Container().GetInstance <IChocolateyConfigSettingsService>())
            .As <IChocolateyConfigSettingsService>().SingleInstance();
            builder.RegisterInstance(choco.Container().GetInstance <IXmlService>())
            .As <IXmlService>().SingleInstance();

            // Register Views
            builder.RegisterAssemblyTypes(viewAssembly)
            .Where(type => type.Name.EndsWith("View", StringComparison.Ordinal))
            .AsSelf()
            .InstancePerDependency();

            // Register the single window manager for this container
            builder.Register <IWindowManager>(c => new WindowManager()).InstancePerLifetimeScope();

            // Register the single event aggregator for this container
            builder.Register <IEventAggregator>(c => new EventAggregator()).InstancePerLifetimeScope();

            // Register Services
            builder.RegisterType <DialogService>().As <IDialogService>().SingleInstance();
            builder.RegisterType <ProgressService>().As <IProgressService>().SingleInstance();
            builder.RegisterType <PersistenceService>().As <IPersistenceService>().SingleInstance();
            builder.RegisterType <LiteDBFileStorageService>().As <IFileStorageService>().SingleInstance();
            builder.RegisterType <ChocolateyGuiCacheService>().As <IChocolateyGuiCacheService>().SingleInstance();
            builder.RegisterType <AllowedCommandsService>().As <IAllowedCommandsService>().SingleInstance();

            // Register Mapper
            var mapperConfiguration = new MapperConfiguration(config =>
            {
                config.CreateMap <IPackageViewModel, IPackageViewModel>()
                .ForMember(vm => vm.IsInstalled, options => options.Ignore());

                config.CreateMap <DataServicePackage, Package>()
                .ForMember(dest => dest.Authors, opt => opt.MapFrom(src => src.Authors.Split(new[] { ',' })))
                .ForMember(dest => dest.Owners, opt => opt.MapFrom(src => src.Owners.Split(new[] { ',' })));
                config.CreateMap <IPackage, Package>();

                config.CreateMap <ConfigFileFeatureSetting, ChocolateyFeature>();
                config.CreateMap <ConfigFileConfigSetting, ChocolateySetting>();
                config.CreateMap <ConfigFileSourceSetting, Common.Models.ChocolateySource>()
                .ForMember(dest => dest.Password, opt => opt.MapFrom(src => NugetEncryptionUtility.DecryptString(src.Password)))
                .ForMember(dest => dest.CertificatePassword, opt => opt.MapFrom(src => NugetEncryptionUtility.DecryptString(src.CertificatePassword)));

                config.CreateMap <ChocolateySource, Common.Models.ChocolateySource>()
                .ForMember(dest => dest.VisibleToAdminsOnly, opt => opt.MapFrom(src => src.VisibleToAdminOnly));
            });

            builder.RegisterType <BundledThemeService>().As <IBundledThemeService>().SingleInstance();
            builder.RegisterInstance(mapperConfiguration.CreateMapper()).As <IMapper>();

            try
            {
                var userDatabase = new LiteDatabase($"filename={Path.Combine(Bootstrapper.LocalAppDataPath, "data.db")};upgrade=true");

                LiteDatabase globalDatabase;
                if (Hacks.IsElevated)
                {
                    string dir = Path.Combine(Bootstrapper.AppDataPath, "Config");
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }

                    globalDatabase = new LiteDatabase($"filename={Path.Combine(dir, "data.db")};upgrade=true");
                }
                else
                {
                    if (!File.Exists(Path.Combine(Bootstrapper.AppDataPath, "Config", "data.db")))
                    {
                        // Since the global configuration database file doesn't exist, we must be running in a state where an administrator user
                        // has never run Chocolatey GUI. In this case, use null, which will mean attempts to use the global database will be ignored.
                        globalDatabase = null;
                    }
                    else
                    {
                        // Since this is a non-administrator user, they should only have read permissions to this database
                        globalDatabase = new LiteDatabase($"filename={Path.Combine(Bootstrapper.AppDataPath, "Config", "data.db")};readonly=true");
                    }
                }

                if (globalDatabase != null)
                {
                    builder.RegisterInstance(globalDatabase).As <LiteDatabase>().SingleInstance().Named <LiteDatabase>(Bootstrapper.GlobalConfigurationDatabaseName);
                }

                var configService = new ConfigService(globalDatabase, userDatabase);
                configService.SetEffectiveConfiguration();

                var iconService = new PackageIconService(userDatabase);

                builder.RegisterInstance(iconService).As <IPackageIconService>().SingleInstance();
                builder.RegisterInstance(configService).As <IConfigService>().SingleInstance();
                builder.RegisterInstance(new LiteDBFileStorageService(userDatabase)).As <IFileStorageService>().SingleInstance();

                // Since there are two instances of LiteDB, they are added as named instances, so that they can be retrieved when required
                builder.RegisterInstance(userDatabase).As <LiteDatabase>().SingleInstance().Named <LiteDatabase>(Bootstrapper.UserConfigurationDatabaseName);
            }
            catch (IOException ex)
            {
                Bootstrapper.Logger.Error(ex, Resources.Error_DatabaseAccessGui);
                throw;
            }

            builder.RegisterType <ImageService>().As <IImageService>().SingleInstance();
            builder.RegisterType <VersionService>().As <IVersionService>().SingleInstance();
            builder.RegisterType <SplashScreenService>().As <ISplashScreenService>().SingleInstance();
        }