/// <summary>
        /// Given a predictor type returns a set of all permissible learners (with their sweeper params, if defined).
        /// </summary>
        /// <returns>Array of viable learners.</returns>
        public static SuggestedRecipe.SuggestedLearner[] AllowedLearners(IHostEnvironment env, MacroUtils.TrainerKinds trainerKind)
        {
            //not all learners advertised in the API are available in CORE.
            var catalog = ModuleCatalog.CreateInstance(env);
            var availableLearnersList = catalog.AllEntryPoints().Where(
                x => x.InputKinds?.FirstOrDefault(i => i == typeof(CommonInputs.ITrainerInput)) != null);

            var learners     = new List <SuggestedRecipe.SuggestedLearner>();
            var type         = typeof(CommonInputs.ITrainerInput);
            var trainerTypes = typeof(Experiment).Assembly.GetTypes()
                               .Where(p => type.IsAssignableFrom(p) &&
                                      MacroUtils.IsTrainerOfKind(p, trainerKind));

            foreach (var tt in trainerTypes)
            {
                var sweepParams = AutoMlUtils.GetSweepRanges(tt);
                var epInputObj  = (CommonInputs.ITrainerInput)tt.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] { });
                var sl          = new SuggestedRecipe.SuggestedLearner
                {
                    PipelineNode = new TrainerPipelineNode(epInputObj, sweepParams),
                    LearnerName  = tt.Name
                };

                if (sl.PipelineNode != null && availableLearnersList.FirstOrDefault(l => l.Name.Equals(sl.PipelineNode.GetEpName())) != null)
                {
                    learners.Add(sl);
                }
            }

            return(learners.ToArray());
        }
        public Legacy.Models.TrainTestEvaluator.Output AddAsTrainTest(Var <IDataView> trainData, Var <IDataView> testData,
                                                                      MacroUtils.TrainerKinds trainerKind, Experiment experiment = null, bool includeTrainingMetrics = false)
        {
            experiment = experiment ?? _env.CreateExperiment();
            var graphDef   = ToEntryPointGraph(experiment);
            var subGraph   = graphDef.Graph;
            var firstInput = new Var <IDataView> {
                VarName = graphDef.GetSubgraphFirstNodeDataVarName(_env)
            };
            var finalOutput = graphDef.ModelOutput;

            // TrainTestMacro
            var trainTestInput = new Legacy.Models.TrainTestEvaluator
            {
                Nodes          = subGraph,
                TransformModel = null,
                Inputs         =
                {
                    Data = firstInput
                },
                Outputs =
                {
                    PredictorModel = finalOutput
                },
                TrainingData           = trainData,
                TestingData            = testData,
                Kind                   = MacroUtils.TrainerKindApiValue <Legacy.Models.MacroUtilsTrainerKinds>(trainerKind),
                PipelineId             = UniqueId.ToString("N"),
                IncludeTrainingMetrics = includeTrainingMetrics
            };
            var trainTestOutput = experiment.Add(trainTestInput);

            return(trainTestOutput);
        }
        // REVIEW: We may want to allow for sweeping with CV in the future, so we will need to add new methods like this, or refactor these in that case.
        public Experiment CreateTrainTestExperiment(IDataView trainData, IDataView testData, MacroUtils.TrainerKinds trainerKind,
                                                    bool includeTrainingMetrics, out Legacy.Models.TrainTestEvaluator.Output resultsOutput)
        {
            var graphDef = ToEntryPointGraph();
            var subGraph = graphDef.Graph;
            var nodes    = graphDef.Graph.GetNodes();

            _env.CheckNonEmpty(nodes, nameof(nodes), "Empty Subgraph on TrainTest Experiment.");

            Var <IDataView> firstInput = new Var <IDataView> {
                VarName = graphDef.GetSubgraphFirstNodeDataVarName(_env)
            };
            var finalOutput = graphDef.ModelOutput;

            // TrainTestMacro
            var trainTestInput = new Legacy.Models.TrainTestEvaluator
            {
                TransformModel = null,
                Nodes          = subGraph,
                Inputs         =
                {
                    Data = firstInput
                },
                Outputs =
                {
                    PredictorModel = finalOutput
                },
                PipelineId             = UniqueId.ToString("N"),
                Kind                   = MacroUtils.TrainerKindApiValue <Legacy.Models.MacroUtilsTrainerKinds>(trainerKind),
                IncludeTrainingMetrics = includeTrainingMetrics
            };

            var experiment      = _env.CreateExperiment();
            var trainTestOutput = experiment.Add(trainTestInput);

            experiment.Compile();
            experiment.SetInput(trainTestInput.TrainingData, trainData);
            experiment.SetInput(trainTestInput.TestingData, testData);
            resultsOutput = trainTestOutput;
            return(experiment);
        }
Example #4
0
        /// <summary>
        /// Loads all custom textures from disk into texture objects. This is done on a separate thread so it is not done redundantly multiple times on each atlas thread
        /// </summary>
        /// <param name="CustomFolderPaths">The list of absolute paths containing custom contour icon images to be loaded</param>
        /// <param name="token">The cancellation token</param>
        /// <returns>The list of textures</returns>
        public static Task LoadCustomContourIconsAsync(List <string> CustomFolderPaths, CancellationToken token)
        {
            ParseCustomTexturesTask = Task.Run(() =>
            {
                Logging.Info(LogOptions.MethodName, "Custom contour icon images task starting");
                ParseStopwatch.Restart();

                //parse each folder list to create a list of all custom contour icons
                Logging.Debug(LogOptions.MethodName, "Custom contour icon images folder count: {0}", CustomFolderPaths.Count);
                List <string> customContourIconFilesList = new List <string>();
                foreach (string folder in CustomFolderPaths)
                {
                    string realFolder = MacroUtils.MacroReplace(folder, ReplacementTypes.FilePath);
                    Logging.Info(LogOptions.MethodName, "Checking for custom contour icon images in directory {0}", realFolder);
                    token.ThrowIfCancellationRequested();

                    if (!Directory.Exists(realFolder))
                    {
                        Logging.Warning(LogOptions.MethodName, "Directory {0} does not exist, skipping", realFolder);
                        continue;
                    }

                    customContourIconFilesList.AddRange(FileUtils.DirectorySearch(realFolder, SearchOption.TopDirectoryOnly, false, "*", 5, 3, false));
                }

                //filter the list to just image files
                //{ "*.jpg", "*.png", "*.bmp" }
                Logging.Debug(LogOptions.MethodName, "List created, filtering for only png,jpg,bmp image files", CustomFolderPaths.Count);
                customContourIconFilesList = customContourIconFilesList.Where(filepath =>
                {
                    if (Path.GetExtension(filepath).ToLower().Contains("png"))
                    {
                        return(true);
                    }
                    else if (Path.GetExtension(filepath).ToLower().Contains("jpg"))
                    {
                        return(true);
                    }
                    else if (Path.GetExtension(filepath).ToLower().Contains("bmp"))
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }).ToList();
                customContourIconFilesList = customContourIconFilesList.Distinct().ToList();
                if (customContourIconFilesList.Count == 0)
                {
                    Logging.Warning(LogOptions.MethodName, "Total of 0 custom contour icons found to parse (Is this the intent?)");
                    return;
                }

                //just in case, dispose of the old one
                DisposeParsedCustomTextures();
                CustomContourIconImages = new List <Texture>();
                Logging.Debug(LogOptions.MethodName, "Loading custom images into data lists for atlas creator", CustomFolderPaths.Count);
                foreach (string customContourIconFilePath in customContourIconFilesList)
                {
                    token.ThrowIfCancellationRequested();

                    //load the bitmap as well
                    Bitmap customContourIconImage = new Bitmap(customContourIconFilePath);

                    //don't care about the x an y for the custom textures
                    CustomContourIconImages.Add(new Texture()
                    {
                        Name       = Path.GetFileNameWithoutExtension(customContourIconFilePath),
                        Height     = customContourIconImage.Height,
                        Width      = customContourIconImage.Width,
                        X          = 0,
                        Y          = 0,
                        AtlasImage = customContourIconImage
                    });
                    customContourIconImage = null;
                }
                Logging.Info(LogOptions.MethodName, "Custom images parsing task completed in {0} msec", ParseStopwatch.ElapsedMilliseconds);
                ParseStopwatch.Stop();
            });
            return(ParseCustomTexturesTask);
        }
Example #5
0
        public static XmlDocument SavePatchToXmlDocument(List <Patch> PatchesList)
        {
            XmlDocument doc         = new XmlDocument();
            XmlElement  patchHolder = doc.CreateElement("patchs");

            doc.AppendChild(patchHolder);
            int counter = 0;

            foreach (Patch patch in PatchesList)
            {
                Logging.Patcher("[SavePatchToXmlDocument]: Saving patch {0} of {1}: {2}", LogLevel.Info, ++counter, PatchesList.Count, patch.ToString());
                Logging.Patcher("{0}", LogLevel.Info, patch.DumpPatchInfoForLog);
                XmlElement xmlPatch = doc.CreateElement("patch");
                patchHolder.AppendChild(xmlPatch);

                XmlElement version = doc.CreateElement("version");
                version.InnerText = patch.Version.ToString();
                xmlPatch.AppendChild(version);

                XmlElement type = doc.CreateElement("type");
                type.InnerText = patch.Type;
                xmlPatch.AppendChild(type);

                XmlElement mode = doc.CreateElement("mode");
                mode.InnerText = patch.Mode;
                xmlPatch.AppendChild(mode);

                XmlElement patchPath = doc.CreateElement("patchPath");
                patchPath.InnerText = patch.PatchPath;
                xmlPatch.AppendChild(patchPath);

                XmlElement followPath = doc.CreateElement("followPath");
                followPath.InnerText = patch.Version == 1 ? false.ToString() : patch.FollowPath.ToString();
                xmlPatch.AppendChild(followPath);

                XmlElement file = doc.CreateElement("file");
                file.InnerText = patch.File;
                xmlPatch.AppendChild(file);

                if (patch.Type.Equals("regex"))
                {
                    XmlElement line = doc.CreateElement("line");
                    line.InnerText = string.Join(",", patch.Lines);
                    xmlPatch.AppendChild(line);
                }
                else
                {
                    XmlElement line = doc.CreateElement("path");
                    line.InnerText = patch.Path;
                    xmlPatch.AppendChild(line);
                }

                XmlElement search = doc.CreateElement("search");
                search.InnerText = patch.Search;
                xmlPatch.AppendChild(search);

                XmlElement replace = doc.CreateElement("replace");
                replace.InnerText = MacroUtils.MacroReplace(patch.Replace, ReplacementTypes.TextEscape);
                xmlPatch.AppendChild(replace);
            }
            return(doc);
        }
        private void TestPatchButton_Click(object sender, RoutedEventArgs e)
        {
            //test from selection components
            if (PatchSettings.SwitchToLogWhenTestingPatch)
            {
                RightSideTabControl.SelectedItem = LogOutputTab;
            }
            Logging.Patcher("TestPatch() start", LogLevel.Info);
            Logging.Patcher("Checking UI elements for valid patch information...", LogLevel.Info);
            //make new patch element
            Patch patchToTest = new Patch();

            //check input from UI left panel side:
            //file location
            Logging.Patcher("File to Patch location mode: {0}", LogLevel.Info, FilePathTypeCombobox.SelectedItem ?? "(null)");
            if (FilePathTypeCombobox.SelectedItem == null)
            {
                Logging.Patcher("Invalid file path type", LogLevel.Info);
                return;
            }
            switch (FilePathTypeCombobox.SelectedItem.ToString())
            {
            case "Absolute":
                Logging.Patcher("Checking if absolute file path {0} exists...", LogLevel.Info, FileToPatchTextbox.Text);
                if (File.Exists(FileToPatchTextbox.Text))
                {
                    Logging.Patcher("File Exists!", LogLevel.Info);
                    patchToTest.File         = FileToPatchTextbox.Text;
                    patchToTest.CompletePath = FileToPatchTextbox.Text;
                }
                else
                {
                    Logging.Patcher("File does not exist, aborting", LogLevel.Info);
                    return;
                }
                break;

            case "Relative":
                Logging.Patcher("Using relative macro {0}", LogLevel.Info, PatchPathCombobox.SelectedItem ?? "(null)");
                string completePathForPatchFile;
                switch (PatchPathCombobox.SelectedItem.ToString())
                {
                case "app":
                    if (Directory.Exists(PatchSettings.AppMacro))
                    {
                        Logging.Patcher("app macro folder path exists...", LogLevel.Info);
                        if (FileToPatchTextbox.Text.Contains("versiondir") && string.IsNullOrWhiteSpace(PatchSettings.VersiondirMacro))
                        {
                            Logging.Patcher("versiondir macro found, but versiondir patch setting macro is blank, aborting", LogLevel.Info);
                            return;
                        }
                        completePathForPatchFile = PatchSettings.AppMacro + FileToPatchTextbox.Text;
                        completePathForPatchFile = MacroUtils.MacroReplace(completePathForPatchFile, ReplacementTypes.ZipFilePath);
                    }
                    else
                    {
                        Logging.Patcher("app macro folder path does not exist, aborting", LogLevel.Info);
                        return;
                    }
                    break;

                case "appData":
                    if (Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)))
                    {
                        Logging.Patcher("appData macro folder path exists...", LogLevel.Info);
                        completePathForPatchFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + FileToPatchTextbox.Text;
                    }
                    else
                    {
                        Logging.Patcher("appData macro folder path does not exist, aborting", LogLevel.Info);
                        return;
                    }
                    break;

                default:
                    Logging.Patcher("Invalid path macro", LogLevel.Info);
                    return;
                }
                Logging.Patcher("relative path built as {0}", LogLevel.Info, completePathForPatchFile);
                if (File.Exists(completePathForPatchFile))
                {
                    Logging.Patcher("File exists!", LogLevel.Info);
                    patchToTest.File         = FileToPatchTextbox.Text;
                    patchToTest.CompletePath = completePathForPatchFile;
                }
                else
                {
                    Logging.Patcher("File does not exist, aborting (did you forget to add \"\\\" to the beginning of the path?", LogLevel.Info);
                }
                break;

            default:
                Logging.Patcher("Invalid file path type, aborting", LogLevel.Info);
                return;
            }

            //check patch type
            if (PatchTypeCombobox.SelectedItem == null)
            {
                Logging.Patcher("Invalid Patch Type, aborting", LogLevel.Info);
                return;
            }
            patchToTest.Type = PatchTypeCombobox.SelectedItem as string;

            //check patch mode
            switch (patchToTest.Type.ToLower())
            {
            case "regex":
            case "regx":
                if (!string.IsNullOrWhiteSpace(PatchModeCombobox.SelectedItem as string))
                {
                    Logging.Patcher("Type=regex, invalid patch type: {0}", LogLevel.Error, PatchModeCombobox.SelectedItem as string);
                    Logging.Patcher("valid types are: (null)");
                    return;
                }
                //set the lines
                if (string.IsNullOrWhiteSpace(PatchLinesPathTextbox.Text))
                {
                    Logging.Patcher("Type=regex, Lines to patch is blank", LogLevel.Error);
                    return;
                }
                else
                {
                    patchToTest.Line = PatchLinesPathTextbox.Text;
                }
                break;

            case "xml":
                //check if path/lines is valid (has string values)
                if (string.IsNullOrWhiteSpace(PatchLinesPathTextbox.Text))
                {
                    Logging.Patcher("invalid xpath", LogLevel.Error);
                    return;
                }
                if (!validXmlModes.Contains((PatchModeCombobox.SelectedItem as string).ToLower()))
                {
                    Logging.Patcher("Type=xml, invalid patch type: {0}", LogLevel.Error, PatchModeCombobox.SelectedItem as string);
                    Logging.Patcher("valid types are: {0}", LogLevel.Error, string.Join(",", validXmlModes));
                    return;
                }
                patchToTest.Path = PatchLinesPathTextbox.Text;
                break;

            case "json":
                //check if path/lines is valid (has string values)
                if (string.IsNullOrWhiteSpace(PatchLinesPathTextbox.Text))
                {
                    Logging.Patcher("invalid jsonpath");
                    return;
                }
                if (!validJsonModes.Contains((PatchModeCombobox.SelectedItem as string).ToLower()))
                {
                    Logging.Patcher("Type=json, invalid patch type: {0}", LogLevel.Info, PatchModeCombobox.SelectedItem as string);
                    Logging.Patcher("valid types are: {0}", LogLevel.Info, string.Join(",", validJsonModes));
                    return;
                }
                patchToTest.Path = PatchLinesPathTextbox.Text;
                break;

            default:
                throw new BadMemeException("invalid patch type, but you should probably make this a enum not strings");
            }
            patchToTest.Mode = PatchModeCombobox.SelectedItem as string;
            //check followPath true ONLY for json
            if (!patchToTest.Type.Equals("json") && (bool)PatchFollowPathSetting.IsChecked)
            {
                Logging.Patcher("Types=json, followPathSetting must be false!");
                return;
            }

            //check search and replace
            if (string.IsNullOrWhiteSpace(PatchReplaceTextbox.Text) && string.IsNullOrWhiteSpace(PatchSearchTextbox.Text))
            {
                Logging.Patcher("patch replace and search are blank, invalid patch");
                return;
            }

            if (string.IsNullOrWhiteSpace(PatchSearchTextbox.Text))
            {
                Logging.Patcher("patch search is blank (is this the intent?)", LogLevel.Warning);
            }
            patchToTest.Search = PatchSearchTextbox.Text;

            if (string.IsNullOrWhiteSpace(PatchReplaceTextbox.Text))
            {
                Logging.Patcher("patch replace is blank (is this the intent?)", LogLevel.Info);
            }
            patchToTest.Replace = PatchReplaceTextbox.Text;

            //put patch into patch test methods
            Logging.Patcher("Running patch...", LogLevel.Info);
            switch (Patcher.RunPatchFromEditor(patchToTest))
            {
            case PatchExitCode.Error:
                Logging.Patcher("Patch failed with errors. Check the log for details.", LogLevel.Error);
                break;

            case PatchExitCode.Warning:
                Logging.Patcher("Patch completed with warnings. Check the log for details.", LogLevel.Warning);
                break;

            case PatchExitCode.Success:
                Logging.Patcher("Patch completed successfully!", LogLevel.Info);
                break;
            }
        }
        public async Task Test01_LoadModSelectionListTest()
        {
            PackageSelectionList selectionList = null;

            Logging.Info("Creating a ModSelectionList Window");

            //create the window and run it on its own thread and dispatcher
            //this can avoid problems with the unit test dispatcher not running the window the way it should
            //it's still an STA thread so WPF can use it as a UI thread
            //https://www.c-sharpcorner.com/uploadfile/suchit_84/creating-wpf-windows-on-dedicated-threads/
            Thread thread = new Thread(() =>
            {
                selectionList = new PackageSelectionList(modpackSettings, commandLineSettings, databaseManager)
                {
                    ApplyColorSettings = false, //not cross-thread safe
                    ApplyScaling       = false,
                    ApplyToolTips      = true,
                    AutoInstallMode    = false,
                    LocalizeWindow     = true,
                    OriginalHeight     = 720.0,
                    OriginalWidth      = 1280.0,

                    //WotClientVersionFromMainWindow is for UI display only
                    WotClientVersionFromMainWindow = "TESTING",

                    //WoTDirectoryFromMainWindow is for UI display only
                    WoTDirectoryFromMainWindow = "TESTING",

                    //DatabaseVersionFromMainWindow is for UI display and when saving a selection
                    DatabaseVersionFromMainWindow = "TESTING"
                };

                selectionList.Closed     += (sender, e) => selectionList.Dispatcher.BeginInvokeShutdown(DispatcherPriority.ApplicationIdle);
                selectionList.WindowState = WindowState.Normal;
                selectionList.Show();

                //start the windows message pump
                Dispatcher.Run();
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();

            //wait for selection list to finish loading
            while (selectionList == null)
            {
                await Task.Delay(100);
            }

            while (!selectionList.LoadingUI)
            {
                await Task.Delay(100);
            }

            while (selectionList.LoadingUI)
            {
                await Task.Delay(1000);
            }

            selectionList.OnSelectionListReturn += (sender, e) => args = e;

            Logging.Info("Selecting 100 components");
            selectionList.Dispatcher.Invoke(() =>
            {
                List <SelectablePackage> flatListRandomSelection = DatabaseUtils.GetFlatSelectablePackageList(selectionList.ParsedCategoryList);
                flatListRandomSelection = flatListRandomSelection.FindAll(package => package.Enabled);
                Random random           = new Random();
                for (int i = 0; i < 100; i++)
                {
                    int selectIndex           = random.Next(0, flatListRandomSelection.Count);
                    SelectablePackage package = flatListRandomSelection[selectIndex];
                    Logging.Info("Index {0} selects package {1}", selectIndex, package.PackageName);
                    package.Checked = true;
                }

                //click the continue button
                List <FrameworkElement> elements = UiUtils.GetAllWindowComponentsLogical(selectionList, false);
                FrameworkElement buttonElement   = elements.Find(element => element.Tag != null && element.Tag.Equals("ContinueButton"));
                Button clearSelectionsButton     = buttonElement as Button;
                clearSelectionsButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            });

            //run some base tests on the return args
            Assert.IsTrue(args.ContinueInstallation);
            Assert.IsTrue(args.GlobalDependencies.Count > 0);
            Assert.IsTrue(args.Dependencies.Count > 0);
            Assert.IsTrue(args.ParsedCategoryList.Count > 0);

            //below this message is copy-modify-paste from the MainWindow's install and OnBeginInstall methods. Some of this should be moved into some sort of re-usable implementation. TODO
            //setup for install
            string wotExeFilepath   = RegistryUtils.AutoFindWoTDirectoryFirst();
            string wotExeFolderpath = Path.GetDirectoryName(wotExeFilepath);

            //get version folders to install as
            string versionXml       = Path.Combine(wotExeFolderpath, ApplicationConstants.WoTVersionXml);
            string versionTemp      = XmlUtils.GetXmlStringFromXPath(versionXml, ApplicationConstants.WoTVersionXmlXpath);
            string WoTClientVersion = versionTemp.Split('#')[0].Trim().Substring(2).Trim();

            Logging.Info("Detected client version: {0}", WoTClientVersion);

            //build macro hash for install
            MacroUtils.BuildFilepathMacroList(WoTClientVersion, databaseManager.WoTOnlineFolderVersion, wotExeFolderpath);

            //perform dependency calculations
            List <DatabasePackage>   flatList              = DatabaseUtils.GetFlatList(null, null, selectionList.ParsedCategoryList);
            List <SelectablePackage> flatListSelect        = DatabaseUtils.GetFlatSelectablePackageList(selectionList.ParsedCategoryList);
            List <Dependency>        dependneciesToInstall = new List <Dependency>(DatabaseUtils.CalculateDependencies(selectionList.Dependencies, selectionList.ParsedCategoryList, false, false));

            //create install list
            List <DatabasePackage> packagesToInstall = new List <DatabasePackage>();

            packagesToInstall.AddRange(selectionList.GlobalDependencies.FindAll(globalDep => globalDep.Enabled && !string.IsNullOrWhiteSpace(globalDep.ZipFile)));
            packagesToInstall.AddRange(dependneciesToInstall.FindAll(dep => dep.Enabled && !string.IsNullOrWhiteSpace(dep.ZipFile)));
            List <SelectablePackage> selectablePackagesToInstall = flatListSelect.FindAll(fl => fl.Enabled && fl.Checked && !string.IsNullOrWhiteSpace(fl.ZipFile));

            packagesToInstall.AddRange(selectablePackagesToInstall);
            List <SelectablePackage> userModsToInstall = args.UserMods.FindAll(mod => mod.Checked);

            //while we're at it let's make a list of packages that need to be downloaded
            List <DatabasePackage> packagesToDownload = packagesToInstall.FindAll(pack => pack.DownloadFlag);

            //and check if we need to actually install anything
            if (selectablePackagesToInstall.Count == 0 && userModsToInstall.Count == 0)
            {
                Assert.Fail("No packages to install");
            }

            //perform list install order calculations
            List <DatabasePackage>[] orderedPackagesToInstall = DatabaseUtils.CreateOrderedInstallList(packagesToInstall);

            //first, if we have downloads to do, then start processing them
            CancellationToken nullToken;

            if (packagesToDownload.Count > 0)
            {
                DownloadManager downloadManager = new DownloadManager()
                {
                    CancellationToken    = nullToken,
                    RetryCount           = 3,
                    DownloadLocationBase = ApplicationConstants.RelhaxDownloadsFolderPath,
                    UrlBase = ApplicationConstants.DownloadMirrors[selectionList.ModpackSettings.DownloadMirror].Replace("{onlineFolder}", databaseManager.WoTOnlineFolderVersion)
                };

                Logging.Info("Download while install = false and packages to download, processing downloads with await");
                Progress <RelhaxDownloadProgress> downloadProgress = new Progress <RelhaxDownloadProgress>();
                downloadManager.Progress = downloadProgress;
                await downloadManager.DownloadPackagesAsync(packagesToDownload);

                downloadManager.Dispose();
            }
            else
            {
                Logging.Info("No packages to download, continue");
            }

            InstallEngine installEngine = new InstallEngine(selectionList.ModpackSettings, selectionList.CommandLineSettings)
            {
                FlatListSelectablePackages = flatListSelect,
                OrderedPackagesToInstall   = orderedPackagesToInstall,
                PackagesToInstall          = packagesToInstall,
                ParsedCategoryList         = args.ParsedCategoryList,
                Dependencies              = args.Dependencies,
                GlobalDependencies        = args.GlobalDependencies,
                UserPackagesToInstall     = userModsToInstall,
                CancellationToken         = nullToken,
                DownloadingPackages       = (packagesToDownload.Count > 0),
                DisableTriggersForInstall = true,
                DatabaseVersion           = "TESTING",
                WoTDirectory              = wotExeFolderpath,
                WoTClientVersion          = WoTClientVersion
            };

            Progress <RelhaxInstallerProgress> progress = new Progress <RelhaxInstallerProgress>();
            RelhaxInstallFinishedEventArgs     results  = await installEngine.RunInstallationAsync(progress);

            Logging.Debug("Installation has finished");
            Assert.IsTrue(results.ExitCode == InstallerExitCodes.Success);
            installEngine.Dispose();
            installEngine = null;
        }
Example #8
0
        /// <summary>
        /// Creates a shortcut on the user's desktop
        /// </summary>
        /// <param name="shortcut">The shortcut parameters</param>
        /// <param name="sb">The StringBuilder to log the path to the created file</param>
        public static void CreateShortcut(Shortcut shortcut, StringBuilder sb)
        {
            Logging.Info(shortcut.ToString());
            Logging.Info("Creating shortcut {0}", shortcut.Name);

            //build the full macro for path (target) and name (also filename)
            string target       = MacroUtils.MacroReplace(shortcut.Path, ReplacementTypes.FilePath).Replace(@"/", @"\");
            string filename     = string.Format("{0}.lnk", shortcut.Name);
            string shortcutPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            shortcutPath = Path.Combine(shortcutPath, filename);

            Logging.Info("Target={0}", target);
            Logging.Info("ShortcutPath={0}", shortcutPath);
            if (!File.Exists(target))
            {
                Logging.Warning("Target does not exist, skipping shortcut", target);
                return;
            }

            //target exists, but do we need to update the shortcut?
            if (File.Exists(shortcutPath))
            {
                Logging.Debug("Shortcut path exists, checking if update needed");

                //get the target path
                IShellLink link = (IShellLink) new ShellLink();
                (link as IPersistFile).Load(shortcutPath, (int)StgmConstants.STGM_READ);
                StringBuilder oldTargetSB = new StringBuilder((int)Win32Value.MAX_PATH);
                link.GetPath(oldTargetSB, oldTargetSB.Capacity, null, (int)SLGP.RAWPATH);
                string oldTarget = oldTargetSB.ToString();

                Logging.Debug("New target = {0}, old target = {1}", target, oldTarget);
                if (!target.Equals(oldTarget))
                {
                    //needs update
                    Logging.Debug("Updating target");
                    link.SetDescription("Created by Relhax Modpack");
                    link.SetPath(target);
                    link.SetWorkingDirectory(Path.GetDirectoryName(target));

                    //The arguments used when executing the target (none used for now)
                    link.SetArguments("");
                    (link as IPersistFile).Save(shortcutPath, false);
                }
                else
                {
                    //no update needed
                    Logging.Debug("No update needed");
                    return;
                }
            }
            else
            {
                Logging.Debug("Shortcut path does not exist, creating");
                IShellLink link = (IShellLink) new ShellLink();

                // setup shortcut information
                link.SetDescription("Created by Relhax Modpack");
                link.SetPath(target);
                link.SetIconLocation(target, 0);
                link.SetWorkingDirectory(Path.GetDirectoryName(target));

                //The arguments used when executing the exe (none used for now)
                link.SetArguments("");
                (link as IPersistFile).Save(shortcutPath, false);
            }

            //getting here means that the target is updated or created, so log it to the installer
            sb.AppendLine(shortcutPath);
        }