Example #1
0
        public static ImmutableArray <(object, string)> GetConfigurationValues(this Scope scope)
        {
            ImmutableArray <Type> configurationValueTypes = Assemblies.FilteredAssemblies().SelectMany(assembly => TypeExtensions.GetLoadableTypes(assembly))
                                                            .Where(t => t.IsPublicConcreteTypeImplementing <IConfigurationValues>())
                                                            .ToImmutableArray();

            var logItems = new List <(object, string)>();

            foreach (Type configurationValueType in configurationValueTypes)
            {
                if (ResolutionExtensions.TryResolve(scope.Lifetime, configurationValueType, out object instance))
                {
                    string toString = instance.ToString();

                    string typeFullName = configurationValueType.FullName;

                    if (toString.Equals(typeFullName, StringComparison.OrdinalIgnoreCase))
                    {
                        string asJson = JsonConvert.SerializeObject(instance);

                        logItems.Add((instance, asJson));
                    }
                    else
                    {
                        logItems.Add((instance, toString));
                    }
                }
            }

            return(logItems.ToImmutableArray());
        }
        protected override void Load(ContainerBuilder builder)
        {
            Assembly[] assemblies = Assemblies.FilteredAssemblies().ToArray();

            builder.RegisterAssemblyTypes(assemblies)
            .Where(type => type.IsConcreteTypeImplementing <IHostedService>())
            .AsImplementedInterfaces()
            .SingleInstance();
        }
        protected override void Load(ContainerBuilder builder)
        {
            Assembly[] scanAssemblies = Assemblies.FilteredAssemblies().ToArray();

            builder.RegisterAssemblyTypes(scanAssemblies)
            .Where(type => type.IsConcreteTypeImplementing <IDataSeeder>())
            .AsImplementedInterfaces()
            .OnRegistered(OnRegistered);
        }
        public void ItShouldFindAllKnownAssemblies()
        {
            ImmutableArray <Assembly> assemblies = Assemblies.FilteredAssemblies(useCache: false)
                                                   .Where(assembly => !assembly.GetName().Name.EndsWith(".Views", StringComparison.OrdinalIgnoreCase))
                                                   .ToImmutableArray();

            _output.WriteLine(string.Join(
                                  Environment.NewLine,
                                  assemblies.Select(assembly => $"{assembly.FullName} {assembly.Location}")));

            Assert.Equal(4, assemblies.Length);

            Assert.Contains(assemblies, assembly => assembly == typeof(DeployController).Assembly);
            Assert.Contains(assemblies, assembly => assembly == typeof(VcsTestPathHelper).Assembly);
            Assert.Contains(assemblies, assembly => assembly == typeof(Assemblies).Assembly);
            Assert.Contains(assemblies, assembly => assembly == typeof(MartenConfiguration).Assembly);
        }
Example #5
0
        public async Task <SettingsViewModel> Handle(SettingsViewRequest request, CancellationToken cancellationToken)
        {
            ImmutableArray <ControllerRouteInfo> routesWithController =
                RouteList.GetRoutesWithController(Assemblies.FilteredAssemblies());

            var info = new ConfigurationInfo(_configuration.SourceChain,
                                             _configuration.AllKeys
                                             .OrderBy(item => item)
                                             .Select(item =>
                                                     new ConfigurationKeyInfo(item,
                                                                              _configuration[item],
                                                                              _configuration.ConfiguratorFor(item).GetType().Name))
                                             .ToImmutableArray());

            ImmutableArray <ContainerRegistrationInfo> registrations = _scope.Deepest().Lifetime.ComponentRegistry
                                                                       .Registrations.SelectMany(reg => reg.Services.Select(service =>
                                                                                                                            new ContainerRegistrationInfo(service.Description, reg.Lifetime.ToString()))).ToImmutableArray();

            IEnumerable <KeyValuePair <string, string> > aspNetConfigurationValues = _aspNetConfiguration
                                                                                     .AsEnumerable()
                                                                                     .Where(pair => !string.IsNullOrWhiteSpace(pair.Value))
                                                                                     .Select(pair =>
                                                                                             new KeyValuePair <string, string>(pair.Key,
                                                                                                                               pair.Value.MakeAnonymous(pair.Key, StringExtensions.DefaultAnonymousKeyWords.ToArray())));

            AppVersionInfo appVersionInfo = VersionHelper.GetAppVersion();

            ImmutableArray <(object, string)> configurationValues = _scope.GetConfigurationValues();

            IKeyValueConfiguration applicationMetadata = await GetApplicationMetadataAsync(cancellationToken);

            var settingsViewModel = new SettingsViewModel(
                _deploymentTargetReadService.GetType().Name,
                routesWithController,
                info,
                registrations,
                aspNetConfigurationValues,
                _loggingLevelSwitch.MinimumLevel,
                appVersionInfo,
                configurationValues,
                applicationMetadata);

            return(settingsViewModel);
        }
Example #6
0
        private static async Task <App> BuildAppAsync(
            CancellationTokenSource cancellationTokenSource,
            Action <LoggerConfiguration> loggerConfigurationAction,
            string[] args)
        {
            ImmutableArray <Assembly> scanAssemblies = Assemblies.FilteredAssemblies();

            string basePathFromArg = args.ParseParameter(ConfigurationConstants.ApplicationBasePath);

            string contentBasePathFromArg = args.ParseParameter(ConfigurationConstants.ContentBasePath);

            bool IsRunningAsService()
            {
                bool hasRunAsServiceArgument = args.Any(arg =>
                                                        arg.Equals(ApplicationConstants.RunAsService, StringComparison.OrdinalIgnoreCase));

                if (hasRunAsServiceArgument)
                {
                    return(true);
                }

                FileInfo processFileInfo;

                using (Process currentProcess = Process.GetCurrentProcess())
                {
                    processFileInfo = new FileInfo(currentProcess.MainModule.FileName);
                }

                if (processFileInfo.Name.Equals("Milou.Deployer.Web.WindowsService.exe", StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                return(false);
            }

            string currentDomainBaseDirectory = AppDomain.CurrentDomain.BaseDirectory;

            if (IsRunningAsService())
            {
                Console.WriteLine($"Switching current directory from {Directory.GetCurrentDirectory()} to {currentDomainBaseDirectory}");
                Directory.SetCurrentDirectory(currentDomainBaseDirectory);
            }

            string basePath        = basePathFromArg ?? currentDomainBaseDirectory;
            string contentBasePath = contentBasePathFromArg ?? Directory.GetCurrentDirectory();

            ILogger startupLogger =
                SerilogApiInitialization.InitializeStartupLogging(file => GetBaseDirectoryFile(basePath, file));

            startupLogger.Information("Using application root directory {Directory}", basePath);

            MultiSourceKeyValueConfiguration configuration =
                ConfigurationInitialization.InitializeConfiguration(args,
                                                                    file => GetBaseDirectoryFile(basePath, file),
                                                                    startupLogger, scanAssemblies, contentBasePath);

            string tempDirectory = configuration[ApplicationConstants.ApplicationTempDirectory];

            if (!string.IsNullOrWhiteSpace(tempDirectory))
            {
                if (tempDirectory.TryEnsureDirectoryExists(out DirectoryInfo tempDirectoryInfo))
                {
                    Environment.SetEnvironmentVariable(TempConstants.Tmp, tempDirectoryInfo.FullName);
                    Environment.SetEnvironmentVariable(TempConstants.Temp, tempDirectoryInfo.FullName);

                    startupLogger.Debug("Using specified temp directory {TempDirectory} {AppName}", tempDirectory, ApplicationConstants.ApplicationName);
                }
                else
                {
                    startupLogger.Warning("Could not use specified temp directory {TempDirectory}, {AppName}", tempDirectory, ApplicationConstants.ApplicationName);
                }
            }

            var loggingLevelSwitch = new LoggingLevelSwitch(LogEventLevel.Debug);

            ILogger appLogger =
                SerilogApiInitialization.InitializeAppLogging(configuration, startupLogger, loggerConfigurationAction, loggingLevelSwitch);

            if (args.Length > 0)
            {
                appLogger.Debug("Application started with command line args, {Args}, {AppName}", args, ApplicationConstants.ApplicationName);
            }
            else if (appLogger.IsEnabled(LogEventLevel.Verbose))
            {
                appLogger.Verbose("Application started with no command line args, {AppName}", ApplicationConstants.ApplicationName);
            }

            IReadOnlyList <IModule> modules =
                GetConfigurationModules(configuration, cancellationTokenSource, appLogger, scanAssemblies);

            Type[] excludedModuleTypes = { typeof(AppServiceModule) };

            var environmentConfiguration = new EnvironmentConfiguration
            {
                ApplicationBasePath = basePath,
                ContentBasePath     = contentBasePath
            };

            var singletons = new object[] { loggingLevelSwitch, environmentConfiguration };

            Scope rootScope = Bootstrapper.Start(configuration,
                                                 modules, appLogger, scanAssemblies, excludedModuleTypes, singletons);

            DeploymentTargetIds deploymentTargetIds = await GetDeploymentWorkerIdsAsync(rootScope.Deepest().Lifetime, appLogger, cancellationTokenSource.Token);

            ILifetimeScope webHostScope =
                rootScope.Deepest().Lifetime.BeginLifetimeScope(builder =>
            {
                builder.RegisterInstance(deploymentTargetIds).AsSelf().SingleInstance();
                builder.RegisterType <Startup>().AsSelf();
            });

            var webHostScopeWrapper = new Scope(Scope.WebHostScope, webHostScope);

            rootScope.Deepest().SubScope = webHostScopeWrapper;

            EnvironmentConfigurator.ConfigureEnvironment(rootScope.Deepest().Lifetime);

            IWebHostBuilder webHostBuilder =
                CustomWebHostBuilder.GetWebHostBuilder(configuration, rootScope, webHostScopeWrapper, appLogger, rootScope.Top());

            var app = new App(webHostBuilder, cancellationTokenSource, appLogger, configuration)
            {
                AppRootScope = rootScope.SubScope
            };

            return(app);
        }
Example #7
0
 protected override void Load(ContainerBuilder builder)
 {
     builder.RegisterAssemblyTypes(Assemblies.FilteredAssemblies().ToArray())
     .Where(type => type.IsPublicConcreteTypeImplementing <IConfigureEnvironment>())
     .As <IConfigureEnvironment>();
 }