public static IWebHost SeedDatabase(this IWebHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var serviceProvider = scope.ServiceProvider;
                var env             = serviceProvider.GetRequiredService <IHostingEnvironment>();

                try
                {
                    var context = serviceProvider.GetRequiredService <ApplicationDbContext>();
                    Log.Information("Seeding the database with data...");
                    context.Database.Migrate();
                    ApplicationInitializer.Initialize(context);

                    ApplicationInitializer.SeedUsers(context, serviceProvider.GetRequiredService <UserManager <ApplicationUser> >());
                    scope.ServiceProvider.GetService <PersistedGrantDbContext>().Database.Migrate();
                    var configurationDbContext = scope.ServiceProvider.GetService <ConfigurationDbContext>();
                    configurationDbContext.Database.Migrate();
                    ApplicationInitializer.SeedConfiguration(configurationDbContext);
                    Log.Information("Seeding the database finished");
                }
                catch (Exception e)
                {
                    Log.Fatal(e, "An error occurred while seeding the database");
                }
            }

            return(host);
        }
Exemple #2
0
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            //Application Initializer

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    ApplicationInitializer      applicationInitializer      = services.GetRequiredService <ApplicationInitializer>();
                    ChatMessageSingletonService chatMessageSingletonService = services.GetRequiredService <ChatMessageSingletonService>();
                    IMapper mapper = services.GetRequiredService <IMapper>();
                    applicationInitializer.InitializeSingleton();
                    //Start TCP Server
                    General.InitServer(chatMessageSingletonService, mapper, services);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred while seeding the database.");
                }
            }


            host.Run();
        }
        private static void Main()
        {
            // In real life we will await this and close Splash screen after object will be ready
            var rootWindow = ApplicationInitializer.WarmupServices().Result;

            rootWindow.Show();
        }
 public TestPackageExecutor(ApplicationInitializer appInitializer)
 {
     ItemStarts          = new List <ProgressReport>();
     ProgressReports     = new List <ProgressReport>();
     ItemStops           = new List <ProgressReport>();
     this.appInitializer = appInitializer;
 }
Exemple #5
0
        private void StartFlowToolbox()
        {
            ApplicationInitializer applicationInitializer = new ApplicationInitializer();
            FlowToolboxWindow      flowToolboxWindow      = new FlowToolboxWindow();

            flowToolboxWindow.content.Content = new IntegrationTool.ProjectDesigner.FlowDesign.FlowToolbox(applicationInitializer.ModuleLoader.Modules.Where(t => t.Attributes.ModuleType == ModuleType.Step).ToList());
            flowToolboxWindow.ShowDialog();
        }
Exemple #6
0
        public static void Run(IConsumer consumer, IVocabularyRepository vocabularyRepository)
        {
            var random                     = new Random();
            var shuffleAlgorithm           = new FisherYatesShuffleAlgorithm(random);
            var practiseInitializerFactory = new PractiseInitializerFactory(consumer, shuffleAlgorithm);

            var applicationInitializer = new ApplicationInitializer(consumer, vocabularyRepository, practiseInitializerFactory);

            applicationInitializer.Start();
        }
        public static TestPackageExecutor ExecuteProjectPackage(string projectPath, string packageName)
        {
            ApplicationInitializer appInitializer = new ApplicationInitializer();
            Project project = ProjectLoader.LoadFromPath(projectPath, appInitializer);

            TestPackageExecutor testExecutor = new TestPackageExecutor(appInitializer);

            testExecutor.ExecutePackage(project.Packages.Where(t => t.DisplayName == packageName).First(), project.Connections);

            return(testExecutor);
        }
            public void EnsureDependencies()
            {
                EnsureConfigurationFilesAreAvailableDuringTest();

                AppManager = new ApplicationManager();
                AppInit    = new ApplicationInitializer();

                Dirs = DirHandler.Instance;
                Dirs.CurrentDirectory = Environment.CurrentDirectory;

                ProxisHome = ProxyHome.Instance;
                ProxisHome.StatisticsProxy = AppInit.InitializeStatisticsComponent(AppManager);
            }
Exemple #9
0
            public void EnsureDependencies()
            {
                EnsureConfigurationFilesAreAvailableDuringTest();

                AppManager = new ApplicationManager();
                AppInit    = new ApplicationInitializer();

                Dirs = DirHandler.Instance;
                Dirs.CurrentDirectory = Environment.CurrentDirectory;

                ProxisHome = ProxyHome.Instance;
                ProxisHome.StatisticsProxy = AppInit.InitializeStatisticsComponent(AppManager);
            }
Exemple #10
0
        /// <summary>
        /// A simple constructor that initializes the object with the given values.
        /// </summary>
        /// <param name="p_iniApplicationInitializer">The application initializer.</param>
        public ApplicationInitializationForm(ApplicationInitializer p_iniApplicationInitializer)
        {
            InitializeComponent();

            var pos = PointToScreen(lblVersion.Location);

            pos = pbxLogo.PointToClient(pos);
            lblVersion.Parent    = pbxLogo;
            lblVersion.Location  = pos;
            lblVersion.BackColor = Color.Transparent;

            ViewModel = p_iniApplicationInitializer;
        }
Exemple #11
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            GlobalConfiguration.Configuration.EnsureInitialized();

            //var appFac = new AppServiceFactory();
            //AppServiceGateway.SetCurrent(appFac);

            ApplicationInitializer.Load();
        }
Exemple #12
0
        public MainWindow(ApplicationInitializer applicationInitializer)
        {
            this.RecentFilesList = new RecentFilesList();

            InitializeComponent();

            this.applicationInitializer = applicationInitializer;

            this.CommandBindings.Add(new CommandBinding(ApplicationCommands.New, New_Executed, New_Enabled));
            this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, Open_Executed, Open_Enabled));
            this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, Save_Executed, Save_Enabled));
            this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, Close_Executed));
            RecentFilesChanged();
            this.RecentFilesList.RecentFiles.CollectionChanged += RecentFiles_CollectionChanged;
        }
Exemple #13
0
 public void Configure(IApplicationBuilder app, ApplicationInitializer initializer)
 {
     Api.Configuration.Configure(app, host =>
     {
         return(host
                .UseDefaultFiles()
                .UseStaticFiles()
                .UseSwagger()
                .UseSwaggerUI(c =>
         {
             c.SwaggerEndpoint("/swagger/v1/swagger.json", "Personas V1");
             c.RoutePrefix = "";
         }));
     }, initializer);
 }
Exemple #14
0
        public MainWindow(ApplicationInitializer applicationInitializer)
        {
            InitializeComponent();
            this.applicationInitializer = applicationInitializer;
            //this.mainWindowContent.Content = new InitializationScreens.InitialScreen();

            this.CommandBindings.Add(new CommandBinding(ApplicationCommands.New, New_Executed, New_Enabled));
            this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, Open_Executed, Open_Enabled));
            this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, Save_Executed, Save_Enabled));

            // OpenProject(@"C:\Temp\IntegrationToolTests\CrmTest\CrmTest.xml");
            // OpenProject(@"..\..\..\IntegrationTool.UnitTests.ApplicationCore\FlowTestProjects\ErrorContinuation\ComplexTests.xml");
            // OpenProject(@"..\..\..\IntegrationTool.UnitTests.ApplicationCore\FlowTestProjects\ErrorPath\SimpleErrorPathTests.xml");

            // this.mainWindowContent.Content = new FlowDesign.FlowDesigner(applicationInitializer.ModuleLoader.Modules);
        }
Exemple #15
0
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope()) {
                var services = scope.ServiceProvider;
                try {
                    ApplicationInitializer.Initialize(services);
                } catch (Exception ex) {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }
Exemple #16
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationContext context)
        {
            _logger.Info("Configure the HTTP request pipeline...");

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            loggerFactory.AddLog4Net();

            CultureInfo[] supportedCultures = new CultureInfo[]
            {
                new CultureInfo("en-US"),
                new CultureInfo("fr-FR")
            };
            RequestLocalizationOptions optionsLocalization = new RequestLocalizationOptions()
            {
                DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US"),
                SupportedCultures     = supportedCultures,
                SupportedUICultures   = supportedCultures
            };

            optionsLocalization.RequestCultureProviders.Insert(0, new CustomChainedCultureProvider());
            app.UseRequestLocalization(optionsLocalization);

            app.UseMvc();

            if (env.IsDevelopment())
            {
                // Create data tests by default
                ApplicationInitializer.Initialize(context);
                _logger.Info("[Configure] Create data test by default");

                app.UseDeveloperExceptionPage();
            }

            app.UseMvcWithDefaultRoute();

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("v1/swagger.json", "Business Core WebAPI");
            });
        }
        void _worker_Complete(object sender, EventArgs e)
        {
            if (_operation.Completed)
            {
                object[] result = (object[])((RunWorkerCompletedEventArgs)e).Result;
                ApplicationInitializer initializer = (ApplicationInitializer)result[0];

                MainWindow mw = new MainWindow(initializer);
                Close();
                mw.Show();
            }
            else
            {
                MessageBox.Show("Cannot initialise application:\n" + _operation.ErrorDescription,
                                "Fatal Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Close();
            }
        }
Exemple #18
0
        public static IApplicationBuilder Configure(
            IApplicationBuilder app,
            Func <IApplicationBuilder, IApplicationBuilder> configureHost, ApplicationInitializer initializer)
        {
            initializer.SeedUsers().Wait();

            return(configureHost(app)
                   .UseProblemDetails()
                   .UseRouting()
                   .UseAuthentication()
                   .UseAuthorization()
                   .UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            }));
        }
        public void GivenApplicationDescriptor_ThenSetTelemetryItem()
        {
            // Arrange

            var applicationDescriptor  = new ApplicationDescriptor("application-name", "20190110.03");
            var applicationInitializer = new ApplicationInitializer(applicationDescriptor);

            var telemetryItem = new TraceTelemetry();

            // Act

            applicationInitializer.Initialize(telemetryItem);

            // Assert

            Assert.Equal(applicationDescriptor.Name, telemetryItem.Context.Cloud.RoleName);
            Assert.Equal(applicationDescriptor.Instance, telemetryItem.Context.Cloud.RoleInstance);
            Assert.Equal(applicationDescriptor.Version, telemetryItem.Context.Component.Version);
        }
Exemple #20
0
        /// <summary>
        /// The long-running operation is performed here.
        /// </summary>
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                ApplicationInitializer applicationInitializer = new ApplicationInitializer();
                e.Result = new object[] { applicationInitializer };

                foreach (ModuleDescription moduleDescription in applicationInitializer.ModuleLoader.Modules)
                {
                }
                System.Threading.Thread.Sleep(1500);

                // long-running operation goes here.

                completed = true;
            }
            catch (Exception ex)
            {
                completed        = false;
                errorDescription = ex.Message + "\n" + ex.StackTrace;
            }
        }
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context     = services.GetRequiredService <ApplicationContext>();
                    var userManager = services.GetRequiredService <UserManager <User> >();
                    var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >();
                    await ApplicationInitializer.InitializeAsync(userManager, roleManager, context);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred while seeding the database.");
                }
            }
            host.Run();
        }
Exemple #22
0
        static void Main(string[] args)
        {
            CommandLineOptions commandLineOptions = ParseCommandLineOptions(args);

            ApplicationInitializer appInitializer = new ApplicationInitializer();

            Project project = ProjectLoader.LoadFromPath(commandLineOptions.ProjectPath, appInitializer);

            Type[] extraTypes = appInitializer.ModuleLoader.GetModuleTypeList();

            Console.WriteLine("Starting execution of project " + project.ProjectName + "\n");

            string[] packagesToRun = String.IsNullOrEmpty(commandLineOptions.Packages) ?
                                     project.Packages.Select(t => t.DisplayName).ToArray <string>() :
                                     packagesToRun = commandLineOptions.Packages.Split(',');

            List <Package> packagesToExecute = new List <Package>();

            foreach (string packageName in packagesToRun)
            {
                Package package = project.Packages.Where(t => t.DisplayName == packageName).FirstOrDefault();
                if (package == null)
                {
                    Console.WriteLine("Package " + packageName + " does not exist in project " + project.ProjectName);
                    Environment.Exit(1);
                }

                packagesToExecute.Add(package);
            }

            foreach (Package package in packagesToExecute)
            {
                Task.Run(() => RunPackage(package, project.Connections, appInitializer.ModuleLoader.Modules, extraTypes)).Wait();
            }

            Console.WriteLine("\nExecution finished");
        }
 /// <summary>
 /// A simple constructor that initializes the object with the given values.
 /// </summary>
 /// <param name="p_iniApplicationInitializer">The application initializer.</param>
 public ApplicationInitializationForm(ApplicationInitializer p_iniApplicationInitializer)
 {
     InitializeComponent();
     ViewModel = p_iniApplicationInitializer;
 }
        /// <summary>
        /// Runs the applications
        /// </summary>
        /// <remarks>
        /// This method makes sure the environment is sane. If so, it creates the required services
        /// and launches the main form.
        /// </remarks>
        /// <param name="args">The command line arguments passed to the application.</param>
        /// <returns><c>true</c> if the application started as expected;
        /// <c>false</c> otherwise.</returns>
        public bool RunMainForm(string[] args)
        {
            if (!SandboxCheck(_environmentInfo))
            {
                return(false);
            }

            SetCompressorPath(_environmentInfo);

            var deletedDll = CheckModScriptDLL();

            string requestedGameMode = null;

            Uri modToAdd = null;

            if (args.Length > 0 && !args[0].StartsWith("-"))
            {
                if (Uri.TryCreate(args[0], UriKind.Absolute, out modToAdd) && modToAdd.Scheme.Equals("nxm", StringComparison.OrdinalIgnoreCase))
                {
                    requestedGameMode = DetermineRequestedGameMode(modToAdd.Host);
                }
            }
            else
            {
                for (var i = 0; i < args.Length; i++)
                {
                    var strArg = args[i];

                    if (strArg == "-game")
                    {
                        requestedGameMode = args[i + 1];
                        Trace.Write("Game Specified On Command line: " + requestedGameMode + ") ");
                    }
                }
            }

            var changeDefaultGameMode = false;
            var supportedGames        = GetSupportedGameModes();

            do
            {
                var fontSetResolver = SetUpFonts();

                var installedGames = GetInstalledGameModes(supportedGames);

                if (installedGames == null)
                {
                    Trace.TraceInformation("No installed games.");
                    MessageBox.Show($"No games were detected! {_environmentInfo.Settings.ModManagerName} will now close.", "No Games", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }

                CheckIfDefaultGameModeIsInstalled(installedGames);

                var selector        = new GameModeSelector(supportedGames, installedGames, _environmentInfo);
                var gameModeFactory = selector.SelectGameMode(requestedGameMode, changeDefaultGameMode);

                if (selector.RescanRequested)
                {
                    _environmentInfo.Settings.InstalledGamesDetected = false;
                    _environmentInfo.Settings.Save();
                    changeDefaultGameMode = true;
                    continue;
                }

                if (gameModeFactory == null)
                {
                    return(false);
                }

                Trace.TraceInformation($"Game Mode Factory Selected: {gameModeFactory.GameModeDescriptor.Name} ({gameModeFactory.GameModeDescriptor.ModeId})");

                Mutex gameModeMutex = null;
                var   ownsMutex     = false;

                try
                {
                    for (var attemptCount = 0; attemptCount < 3; attemptCount++)
                    {
                        Trace.TraceInformation($"Creating Game Mode mutex (Attempt: {attemptCount})");
                        gameModeMutex = new Mutex(true, $"{_environmentInfo.Settings.ModManagerName}-{gameModeFactory.GameModeDescriptor.ModeId}-GameModeMutex", out ownsMutex);

                        //If the mutex is owned, you are the first instance of the mod manager for game mode, so break out of loop.
                        if (ownsMutex)
                        {
                            break;
                        }

                        try
                        {
                            //If the mutex isn't owned, attempt to talk across the messager.
                            using (var messager = MessagerClient.GetMessager(_environmentInfo, gameModeFactory.GameModeDescriptor))
                            {
                                if (messager != null)
                                {
                                    //Messenger was created OK, send download request, or bring to front.
                                    if (modToAdd != null)
                                    {
                                        Trace.TraceInformation($"Messaging to add: {modToAdd}");
                                        messager.AddMod(modToAdd.ToString());
                                    }
                                    else
                                    {
                                        Trace.TraceInformation("Messaging to bring to front.");
                                        messager.BringToFront();
                                    }

                                    return(true);
                                }
                            }

                            gameModeMutex.Close();
                            gameModeMutex = null;
                        }
                        catch (InvalidOperationException)
                        {
                            var stbPromptMessage = new StringBuilder();
                            stbPromptMessage.AppendLine($"{_environmentInfo.Settings.ModManagerName} was unable to start. It appears another instance of {_environmentInfo.Settings.ModManagerName} is already running.");
                            stbPromptMessage.AppendLine($"If you were trying to download multiple files, wait for {_environmentInfo.Settings.ModManagerName} to start before clicking on a new file download.");
                            MessageBox.Show(stbPromptMessage.ToString(), "Already running", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return(false);
                        }

                        //Messenger couldn't be created, so sleep for a few seconds to give time for opening
                        // the running copy of the mod manager to start up/shut down
                        Thread.Sleep(TimeSpan.FromSeconds(5.0d));
                    }

                    if (!ownsMutex)
                    {
                        var htlListener = (HeaderlessTextWriterTraceListener)Trace.Listeners["DefaultListener"];
                        htlListener.ChangeFilePath(Path.Combine(Path.GetDirectoryName(htlListener.FilePath), "Messager" + Path.GetFileName(htlListener.FilePath)));

                        Trace.TraceInformation("THIS IS A MESSAGER TRACE LOG.");

                        if (!htlListener.TraceIsForced)
                        {
                            htlListener.SaveToFile();
                        }

                        var stbPromptMessage = new StringBuilder();
                        stbPromptMessage.AppendLine($"{_environmentInfo.Settings.ModManagerName} was unable to start. It appears another instance of {_environmentInfo.Settings.ModManagerName} is already running.");
                        stbPromptMessage.AppendLine("A Trace Log file was created at:");
                        stbPromptMessage.AppendLine(htlListener.FilePath);
                        stbPromptMessage.AppendLine("Before reporting the issue, don't close this window and check for a fix here (you can close it afterwards):");
                        stbPromptMessage.AppendLine(NexusLinks.FAQs);
                        stbPromptMessage.AppendLine("If you can't find a solution, please make a bug report and attach the TraceLog file here:");
                        stbPromptMessage.AppendLine(NexusLinks.Issues);
                        MessageBox.Show(stbPromptMessage.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        return(false);
                    }

                    ApplicationInitializer appInitializer = null;

                    while ((appInitializer == null) || (appInitializer.Status == TaskStatus.Retrying))
                    {
                        appInitializer = new ApplicationInitializer(_environmentInfo, fontSetResolver, deletedDll);
                        var appInitializerForm = new ApplicationInitializationForm(appInitializer);
                        appInitializer.Initialize(gameModeFactory, SynchronizationContext.Current);
                        appInitializerForm.ShowDialog();
                    }

                    if (appInitializer.Status != TaskStatus.Complete)
                    {
                        if (appInitializer.Status == TaskStatus.Error)
                        {
                            return(false);
                        }

                        changeDefaultGameMode = true;
                        DisposeServices(appInitializer.Services);

                        continue;
                    }

                    var gameMode = appInitializer.GameMode;
                    var services = appInitializer.Services;

                    var mainFormViewModel = new MainFormVM(_environmentInfo, installedGames, gameMode, services.ModRepository, services.DownloadMonitor, services.ModActivationMonitor, services.ModManager, services.PluginManager);
                    var mainForm          = new MainForm(mainFormViewModel);

                    using (var msgMessager = MessagerServer.InitializeListener(_environmentInfo, gameMode, services.ModManager, mainForm))
                    {
                        if (modToAdd != null)
                        {
                            Trace.TraceInformation("Adding mod: " + modToAdd);
                            msgMessager.AddMod(modToAdd.ToString());
                            modToAdd = null;
                        }

                        Trace.TraceInformation("Running Application.");

                        try
                        {
                            Application.Run(mainForm);
                            services.ModInstallLog.Backup();
                            requestedGameMode     = mainFormViewModel.RequestedGameMode;
                            changeDefaultGameMode = mainFormViewModel.DefaultGameModeChangeRequested;
                        }
                        finally
                        {
                            DisposeServices(services);
                            gameMode.Dispose();
                        }
                    }
                }
                finally
                {
                    if (gameModeMutex != null)
                    {
                        if (ownsMutex)
                        {
                            gameModeMutex.ReleaseMutex();
                        }

                        gameModeMutex.Close();
                    }

                    FileUtil.ForceDelete(_environmentInfo.TemporaryPath);

                    //Clean up created font's.
                    FontManager.Dispose();
                }
            } while (!string.IsNullOrEmpty(requestedGameMode) || changeDefaultGameMode);

            return(true);
        }
 public IPractiseInitializer Create(ApplicationInitializer applicationInitializer)
 {
     return(new PractiseInitializer(applicationInitializer, _consumer, _shuffleAlgorithm));
 }
        /// <summary>
        /// Runs the applications
        /// </summary>
        /// <remarks>
        /// This method makes sure the environment is sane. If so, it creates the required services
        /// and launches the main form.
        /// </remarks>
        /// <param name="p_strArgs">The command line arguments passed to the application.</param>
        /// <returns><c>true</c> if the application started as expected;
        /// <c>false</c> otherwise.</returns>
        public bool RunMainForm(string[] p_strArgs)
        {
            if (!SandboxCheck(m_eifEnvironmentInfo))
                return false;
            SetCompressorPath(m_eifEnvironmentInfo);

            string strRequestedGameMode = null;
            string[] strArgs = p_strArgs;
            Uri uriModToAdd = null;
            if ((p_strArgs.Length > 0) && !p_strArgs[0].StartsWith("-"))
            {
                if (Uri.TryCreate(p_strArgs[0], UriKind.Absolute, out uriModToAdd) && uriModToAdd.Scheme.Equals("nxm", StringComparison.OrdinalIgnoreCase))
                    strRequestedGameMode = uriModToAdd.Host;
            }
            else
                for (Int32 i = 0; i < p_strArgs.Length; i++)
                {
                    string strArg = p_strArgs[i];
                    if (strArg.StartsWith("-"))
                    {
                        switch (strArg)
                        {
                            case "-game":
                                strRequestedGameMode = p_strArgs[i + 1];
                                Trace.Write("Game Specified On Command line: " + strRequestedGameMode + ") ");
                                break;
                        }
                    }
                }

            bool booChangeDefaultGameMode = false;
            GameModeRegistry gmrSupportedGames = GetSupportedGameModes();
            do
            {
                NexusFontSetResolver nfrResolver = SetUpFonts();

                GameModeRegistry gmrInstalledGames = GetInstalledGameModes(gmrSupportedGames);
                if (gmrInstalledGames == null)
                {
                    Trace.TraceInformation("No installed games.");
                    MessageBox.Show(String.Format("No games were detected! {0} will now close.", m_eifEnvironmentInfo.Settings.ModManagerName), "No Games", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }

                GameModeSelector gmsSelector = new GameModeSelector(gmrSupportedGames, gmrInstalledGames, m_eifEnvironmentInfo);
                IGameModeFactory gmfGameModeFactory = gmsSelector.SelectGameMode(strRequestedGameMode, booChangeDefaultGameMode);
                if (gmsSelector.RescanRequested)
                {
                    m_eifEnvironmentInfo.Settings.InstalledGamesDetected = false;
                    m_eifEnvironmentInfo.Settings.Save();
                    booChangeDefaultGameMode = true;
                    continue;
                }
                if (gmfGameModeFactory == null)
                    return false;

                Trace.TraceInformation(String.Format("Game Mode Factory Selected: {0} ({1})", gmfGameModeFactory.GameModeDescriptor.Name, gmfGameModeFactory.GameModeDescriptor.ModeId));

                Mutex mtxGameModeMutex = null;
                bool booOwnsMutex = false;
                try
                {
                    for (Int32 intAttemptCount = 0; intAttemptCount < 3; intAttemptCount++)
                    {
                        Trace.TraceInformation("Creating Game Mode mutex (Attempt: {0})", intAttemptCount);
                        mtxGameModeMutex = new Mutex(true, String.Format("{0}-{1}-GameModeMutex", m_eifEnvironmentInfo.Settings.ModManagerName, gmfGameModeFactory.GameModeDescriptor.ModeId), out booOwnsMutex);

                        //If the mutex is owned, you are the first instance of the mod manager for game mode, so break out of loop.
                        if (booOwnsMutex)
                            break;

                        try
                        {
                            //If the mutex isn't owned, attempt to talk across the messager.
                            using (IMessager msgMessager = MessagerClient.GetMessager(m_eifEnvironmentInfo, gmfGameModeFactory.GameModeDescriptor))
                            {
                                if (msgMessager != null)
                                {
                                    //Messenger was created OK, send download request, or bring to front.
                                    if (uriModToAdd != null)
                                    {
                                        Trace.TraceInformation(String.Format("Messaging to add: {0}", uriModToAdd));
                                        msgMessager.AddMod(uriModToAdd.ToString());
                                    }
                                    else
                                    {
                                        Trace.TraceInformation(String.Format("Messaging to bring to front."));
                                        msgMessager.BringToFront();
                                    }
                                    return true;
                                }
                            }
                            mtxGameModeMutex.Close();
                            mtxGameModeMutex = null;
                        }
                        catch (InvalidOperationException)
                        {
                            StringBuilder stbPromptMessage = new StringBuilder();
                            stbPromptMessage.AppendFormat("{0} was unable to start. It appears another instance of {0} is already running.", m_eifEnvironmentInfo.Settings.ModManagerName).AppendLine();
                            stbPromptMessage.AppendFormat("If you were trying to download multiple files, wait for {0} to start before clicking on a new file download.", m_eifEnvironmentInfo.Settings.ModManagerName).AppendLine();
                            MessageBox.Show(stbPromptMessage.ToString(), "Already running", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        //Messenger couldn't be created, so sleep for a few seconds to give time for opening
                        // the running copy of the mod manager to start up/shut down
                        Thread.Sleep(TimeSpan.FromSeconds(5.0d));
                    }
                    if (!booOwnsMutex)
                    {
                        HeaderlessTextWriterTraceListener htlListener = (HeaderlessTextWriterTraceListener)Trace.Listeners["DefaultListener"];
                        htlListener.ChangeFilePath(Path.Combine(Path.GetDirectoryName(htlListener.FilePath), "Messager" + Path.GetFileName(htlListener.FilePath)));
                        Trace.TraceInformation("THIS IS A MESSAGER TRACE LOG.");
                        if (!htlListener.TraceIsForced)
                            htlListener.SaveToFile();

                        StringBuilder stbPromptMessage = new StringBuilder();
                        stbPromptMessage.AppendFormat("{0} was unable to start. It appears another instance of {0} is already running.", m_eifEnvironmentInfo.Settings.ModManagerName).AppendLine();
                        stbPromptMessage.AppendLine("A Trace Log file was created at:");
                        stbPromptMessage.AppendLine(htlListener.FilePath);
                        stbPromptMessage.AppendLine("Before reporting the issue, don't close this window and check for a fix here (you can close it afterwards):");
                        stbPromptMessage.AppendLine(NexusLinks.FAQs);
                        stbPromptMessage.AppendLine("If you can't find a solution, please make a bug report and attach the TraceLog file here:");
                        stbPromptMessage.AppendLine(NexusLinks.Issues);
                        MessageBox.Show(stbPromptMessage.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }

                    //ApplicationInitializer ainInitializer = new ApplicationInitializer(m_eifEnvironmentInfo, nfrResolver);
                    //ApplicationInitializationForm frmAppInitilizer = new ApplicationInitializationForm(ainInitializer);
                    //ainInitializer.Initialize(gmfGameModeFactory, SynchronizationContext.Current);
                    //frmAppInitilizer.ShowDialog();
                    ApplicationInitializer ainInitializer = null;
                    ApplicationInitializationForm frmAppInitilizer = null;
                    while ((ainInitializer == null) || (ainInitializer.Status == TaskStatus.Retrying))
                    {
                        ainInitializer = new ApplicationInitializer(m_eifEnvironmentInfo, nfrResolver);
                        frmAppInitilizer = new ApplicationInitializationForm(ainInitializer);
                        ainInitializer.Initialize(gmfGameModeFactory, SynchronizationContext.Current);
                        frmAppInitilizer.ShowDialog();
                    }

                    if (ainInitializer.Status != TaskStatus.Complete)
                    {
                        if (ainInitializer.Status == TaskStatus.Error)
                            return false;
                        booChangeDefaultGameMode = true;
                        DisposeServices(ainInitializer.Services);
                        continue;
                    }

                    IGameMode gmdGameMode = ainInitializer.GameMode;
                    ServiceManager svmServices = ainInitializer.Services;

                    MainFormVM vmlMainForm = new MainFormVM(m_eifEnvironmentInfo, gmrInstalledGames, gmdGameMode, svmServices.ModRepository, svmServices.DownloadMonitor, svmServices.ActivateModsMonitor, svmServices.UpdateManager, svmServices.ModManager, svmServices.PluginManager);
                    MainForm frmMain = new MainForm(vmlMainForm);

                    using (IMessager msgMessager = MessagerServer.InitializeListener(m_eifEnvironmentInfo, gmdGameMode, svmServices.ModManager, frmMain))
                    {
                        if (uriModToAdd != null)
                        {
                            Trace.TraceInformation("Adding mod: " + uriModToAdd.ToString());
                            msgMessager.AddMod(uriModToAdd.ToString());
                            uriModToAdd = null;
                        }

                        Trace.TraceInformation("Running Application.");
                        try
                        {
                            Application.Run(frmMain);
                            svmServices.ModInstallLog.Backup();
                            strRequestedGameMode = vmlMainForm.RequestedGameMode;
                            booChangeDefaultGameMode = vmlMainForm.DefaultGameModeChangeRequested;
                        }
                        finally
                        {
                            DisposeServices(svmServices);
                            gmdGameMode.Dispose();
                        }
                    }
                }
                finally
                {
                    if (mtxGameModeMutex != null)
                    {
                        if (booOwnsMutex)
                            mtxGameModeMutex.ReleaseMutex();
                        mtxGameModeMutex.Close();
                    }
                    FileUtil.ForceDelete(m_eifEnvironmentInfo.TemporaryPath);

                    //Clean up created font's.
                    FontManager.Dispose();
                }
            } while (!String.IsNullOrEmpty(strRequestedGameMode) || booChangeDefaultGameMode);
            return true;
        }
 public static IDisposable Initialize(this WinApplication winApplication)
 => ApplicationInitializer.Create(winApplication);
Exemple #28
0
 public void Configure(IApplicationBuilder app, ApplicationInitializer initializer)
 {
     Configuration.Configure(app, host => host, initializer);
 }
 public MovieAdminModel(ApplicationInitializer context)
 {
     _context = context;
 }