public StartingContext(IContainer container, ProfileManager profileManager, ISplash splash)
        {
            _container      = container;
            _splash         = splash;
            _profileManager = profileManager;

            if (_profileManager.ProfileLoaded)
            {
                Pandora.Log.WriteEntry("Import startup initiated");
                LoadProfile(_profileManager.Profile.Name);
            }
            else
            {
                Pandora.Log.WriteEntry("Normal startup initiated");

                // Move on with normal startup
                Process proc = Pandora.ExistingInstance;
                if (proc != null) // Single instance check
                {
                    Pandora.Log.WriteError(null, "Double instance detected");
                    MessageBox.Show("You can't run two instances of Pandora's Box at the same time");
                    //  Issue 33:    Bring to front if already started - Tarion
                    ProcessExtension.BringToFront(proc);
                }
                else
                {
                    Pandora.Log.WriteEntry("Double instances check passed");
                    DoProfile();
                }
            }
        }
Exemple #2
0
        public static StatisticalResultCsv[] Run(string name, string method, int ke, int keep, IEnumerable <StatisticalResultCsv> selectedMembers)
        {
            string methodFolder = $"{Config.WorkingFolder}\\{name}";

            Directory.CreateDirectory(methodFolder);
            string candidatesFolder = $"{Config.WorkingFolder}\\{name}\\candidates\\";

            Directory.CreateDirectory(candidatesFolder);
            foreach (var member in selectedMembers)
            {
                File.Copy($"{Config.WorkingFolder}\\{member.Method}\\{member.Dataset}\\individuals\\{member.File}", $"{candidatesFolder}\\{member.File}", true);
            }
            Icas.Common.ProcessExtension.Run("RScript", $"job_ensemble.R {name} {method} {selectedMembers.First().Dataset} {selectedMembers.First().Degredome} {keep}");
            FeatureType dt = FeatureType.Reactivity;

            FeatureType.TryParse(selectedMembers.First().DataType, out dt);

            ProcessExtension.Run("Python", $"{Config.JobOnewayPy} {name} {selectedMembers.First().Dataset}");
            ProcessExtension.Run("RScript", $"{Config.JobPairwiseComparisonR} {name} {selectedMembers.First().Dataset}");
            AlgorithmCsv algorithm = new AlgorithmCsv();

            algorithm.Name    = name;
            algorithm.Feature = selectedMembers.First().DataType;
            DatasetCsv dataset = MiSettings.Datasets.First(c => c.Name == selectedMembers.First().Dataset);
            var        results = Icas.Clustering.Cluster.RunIndividual(algorithm, new[] { dataset }, false);

            Icas.Clustering.Cluster.Summarize(algorithm);
            return(results);
        }
Exemple #3
0
 public override void Run()
 {
     ProcessExtension.Start(LauncherFilename, new[] {
         "--run", AcsName
     }, new ProcessStartInfo {
         WorkingDirectory = AcRootDirectory.Instance.RequireValue
     });
 }
        private static void MainInner(string[] args)
        {
            if (AppUpdater.OnStartup(args))
            {
                return;
            }

            if (args.Length == 2 && args[0] == "--run")
            {
                Process.Start(args[1]);
                return;
            }

            var appGuid = ((GuidAttribute)Assembly.GetEntryAssembly().GetCustomAttributes(typeof(GuidAttribute), true).GetValue(0)).Value;
            var mutexId = $@"Global\{{{appGuid}}}";

            if (Array.IndexOf(args, WindowsHelper.RestartArg) != -1)
            {
                for (var i = 0; i < 999; i++)
                {
                    Thread.Sleep(200);

                    using (var mutex = new Mutex(false, mutexId)) {
                        if (mutex.WaitOne(0, false))
                        {
                            break;
                        }
                    }
                }

                ProcessExtension.Start(MainExecutingFile.Location, args.Where(x => x != WindowsHelper.RestartArg));
                return;
            }

            using (var mutex = new Mutex(false, mutexId)) {
                _secondInstanceMessage = User32.RegisterWindowMessage(mutexId);
                if (mutex.WaitOne(0, false))
                {
                    if (AppUpdater.OnUniqueStartup(args))
                    {
                        return;
                    }

                    _initialized = true;
                    App.CreateAndRun(false);

                    /*if (args.Length == 0) {
                     *  TryToRunAppSafely();
                     * } else {
                     *  App.CreateAndRun(false);
                     * }*/
                }
                else
                {
                    PassArgsToRunningInstance(args);
                }
            }
        }
Exemple #5
0
        private static void InstallAndRunNewVersion()
        {
            /* will be replaced this file */
            var originalFilename = MainExecutingFile.Location.ApartFromLast(UpdatePostfix, StringComparison.OrdinalIgnoreCase) + ExecutableExtension;

            /* if file already exists */
            if (File.Exists(originalFilename))
            {
                /* ten attempts, five seconds */
                for (var i = 0; i < 10; i++)
                {
                    try {
                        File.Delete(originalFilename);
                        break;
                    } catch (Exception) {
                        Thread.Sleep(500);
                    }
                }

                /* if we couldn’t delete file normally, let’s kill any process with this name */
                if (File.Exists(originalFilename))
                {
                    try {
                        foreach (var process in Process.GetProcessesByName(Path.GetFileName(originalFilename)))
                        {
                            process.Kill();
                        }
                    } catch (Exception) {
                        // ignored
                    }

                    /* four attempts, two seconds */
                    for (var i = 0; i < 4; i++)
                    {
                        try {
                            File.Delete(originalFilename);
                        } catch (Exception) {
                            Thread.Sleep(500);
                        }
                    }
                }

                if (File.Exists(originalFilename))
                {
                    MessageBox.Show(
                        string.Format(ToolsStrings.AppUpdater_CannotUpdate_HelpNeeded, Path.GetFileName(originalFilename),
                                      Path.GetFileName(MainExecutingFile.Location)),
                        ToolsStrings.AppUpdater_UpdateFailed, MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
            }

            File.Copy(MainExecutingFile.Location, originalFilename);
            ProcessExtension.Start(originalFilename, Environment.GetCommandLineArgs().Skip(1));
            Environment.Exit(0);
        }
Exemple #6
0
 private static void RunUpdateExeAndExitIfExists()
 {
     if (!File.Exists(UpdateLocation))
     {
         return;
     }
     Logging.Write($"Starting “{UpdateLocation}”…");
     ProcessExtension.Start(UpdateLocation, Environment.GetCommandLineArgs().Skip(1));
     Environment.Exit(0);
 }
Exemple #7
0
        public void OnProgress(Game.ProgressState progress)
        {
            switch (progress)
            {
            case Game.ProgressState.Preparing:
                Model.WaitingStatus = AppStrings.Race_Preparing;
                break;

            case Game.ProgressState.Launching:
                if (AcRootDirectory.CheckDirectory(MainExecutingFile.Directory) &&
                    MainExecutingFile.Name != "AssettoCorsa.exe" &&
                    new IniFile(AcPaths.GetCfgVideoFilename())["CAMERA"].GetNonEmpty("MODE") == "OCULUS" &&
                    MessageDialog.Show(
                        "Oculus Rift might not work properly with Content Manager is in AC root folder. It’s better to move it to avoid potential issues.",
                        "Important note", new MessageDialogButton {
                    [MessageBoxResult.Yes] = "Move it now",
                    [MessageBoxResult.No] = "Ignore"
                }, "oculusRiftWarningMessage") == MessageBoxResult.Yes)
                {
                    try {
                        var newLocation = FilesStorage.Instance.GetFilename(MainExecutingFile.Name);
                        File.Copy(MainExecutingFile.Location, newLocation, true);
                        WindowsHelper.ViewFile(newLocation);
                        ProcessExtension.Start(newLocation, new[] { @"--restart", @"--move-app=" + MainExecutingFile.Location });
                        Environment.Exit(0);
                    } catch (Exception e) {
                        NonfatalError.Notify("Failed to move Content Manager executable", "I’m afraid you’ll have to do it manually.", e);
                    }
                }

                if (SettingsHolder.Drive.SelectedStarterType == SettingsHolder.DriveSettings.DeveloperStarterType)
                {
                    Model.WaitingStatus = "Now, run AC…";
                }
                else
                {
                    Model.WaitingStatus = _mode == GameMode.Race ? AppStrings.Race_LaunchingGame :
                                          _mode == GameMode.Replay ? AppStrings.Race_LaunchingReplay : AppStrings.Race_LaunchingBenchmark;
                }
                break;

            case Game.ProgressState.Waiting:
                Model.WaitingStatus = _mode == GameMode.Race ? AppStrings.Race_Waiting :
                                      _mode == GameMode.Replay ? AppStrings.Race_WaitingReplay : AppStrings.Race_WaitingBenchmark;
                break;

            case Game.ProgressState.Finishing:
                RevertSizeFix().Ignore();
                Model.WaitingStatus = AppStrings.Race_CleaningUp;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(progress), progress, null);
            }
        }
Exemple #8
0
        private string Execute(string filename, string originalText)
        {
            using (var p = ProcessExtension.Start(
                       _executableName ?? filename,
                       _executableName == null ? null : _arguments.Append(filename),
                       new ProcessStartInfo {
                WorkingDirectory = _workingDirectory ?? ".",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                RedirectStandardInput = true,
                CreateNoWindow = true,
                StandardOutputEncoding = Encoding.UTF8,
                StandardErrorEncoding = Encoding.UTF8
            })) {
                p.Start();

                using (var writer = new StreamWriter(p.StandardInput.BaseStream, Encoding.UTF8)) {
                    writer.Write(originalText);
                    writer.Close();
                }

                p.WaitForExit();

                var output = p.StandardOutput.ReadToEnd().Trim();
                var error  = p.StandardError.ReadToEnd().Trim();

                if (p.ExitCode != 0)
                {
                    var sb = new StringBuilder();
                    sb.AppendLine("Exit code: " + p.ExitCode);

                    if (output.Length > 0)
                    {
                        sb.Append("\n\n");
                        sb.AppendLine(output);
                    }

                    if (error.Length > 0)
                    {
                        sb.Append("\n\n");
                        sb.AppendLine(error);
                    }

                    TypoLogging.Write(sb.ToString());
                    throw new ExternalInterpreterException(_executableName + " " + _arguments.Append(filename).JoinToString(" "),
                                                           p.ExitCode, output, error);
                }

                p.Close();
                return(output);
            }
        }
Exemple #9
0
        public static void MainInner(string[] args)
        {
            // if (AppUpdater.OnStartup(args)) return;

            if (args.Length == 2 && args[0] == "--run")
            {
                Process.Start(args[1]);
                return;
            }

            var mainAssembly = Assembly.GetEntryAssembly();

            if (mainAssembly == null)
            {
                return;
            }

            var appGuid = ((GuidAttribute)mainAssembly.GetCustomAttributes(typeof(GuidAttribute), true).GetValue(0)).Value;
            var mutexId = $@"Global\{{{appGuid}}}";

            if (args.Contains(WindowsHelper.RestartArg))
            {
                for (var i = 0; i < 999; i++)
                {
                    Thread.Sleep(200);

                    using (var mutex = new Mutex(false, mutexId)) {
                        if (mutex.WaitOne(0, false))
                        {
                            break;
                        }
                    }
                }

                ProcessExtension.Start(MainExecutingFile.Location, args.Where(x => x != WindowsHelper.RestartArg));
                return;
            }

            using (var mutex = new Mutex(false, mutexId)) {
                SecondInstanceMessage = User32.RegisterWindowMessage(mutexId);
                if (mutex.WaitOne(0, false))
                {
                    _initialized = true;
                    App.CreateAndRun();
                }
                else
                {
                    PassArgsToRunningInstance(args);
                }
            }
        }
Exemple #10
0
            private async Task RunProcessAsync(string filename, IEnumerable <string> args,
                                               IProgress <double?> progress, CancellationToken cancellationToken)
            {
                var process = ProcessExtension.Start(filename, args, new ProcessStartInfo {
                    UseShellExecute        = false,
                    RedirectStandardOutput = progress != null,
                    RedirectStandardError  = true,
                    CreateNoWindow         = true
                });

                try {
                    cancellationToken.ThrowIfCancellationRequested();
                    if (progress != null)
                    {
                        process.OutputDataReceived += (sender, eventArgs) => {
                            if (!string.IsNullOrWhiteSpace(eventArgs.Data))
                            {
                                progress.Report(FlexibleParser.ParseDouble(eventArgs.Data, 0d) / 100d);
                            }
                        };
                    }
                    process.ErrorDataReceived += (sender, eventArgs) => {
                        if (!string.IsNullOrWhiteSpace(eventArgs.Data))
                        {
                            AcToolsLogging.Write(eventArgs.Data);
                        }
                    };
                    if (progress != null)
                    {
                        process.BeginOutputReadLine();
                    }
                    process.BeginErrorReadLine();
                    await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);

                    if (process.ExitCode != 0)
                    {
                        throw new Exception("Failed to run process: " + process.ExitCode);
                    }
                } finally {
                    if (!process.HasExitedSafe())
                    {
                        process.Kill();
                    }
                    process.Dispose();
                }
            }
Exemple #11
0
            public static void Split(string filename, string directory)
            {
                var pro = new ProcessExtension();

                var durationArgs   = $"-i \"{filename}\"";
                var durationResult = pro.Execute(FFMpegExecute, durationArgs);

                if (Regex.IsMatch(durationResult, DurationExpression))
                {
                    var durationMatch  = Regex.Match(durationResult, DurationExpression);
                    var durationString = durationMatch.Groups[1].Value;
                    var duration       = TimeSpan.Parse(durationString);
                    var currentTime    = TimeSpan.Zero;

                    var index      = 1;
                    var splitSpanc = new TimeSpan(0, 3, 0);

                    while (currentTime < duration)
                    {
                        var time = duration.Subtract(currentTime);

                        if (time > splitSpanc)
                        {
                            var splitArgs = $"-ss {currentTime} -i \"{filename}\" -c copy -t {currentTime.Add(splitSpanc)} \"{directory}\\Video_{index++}.mkv\"";

                            pro.InvokeShell(FFMpegExecute, splitArgs);

                            currentTime = currentTime.Add(splitSpanc);
                        }
                        else
                        {
                            var splitArgs = $"-ss {currentTime} -i \"{filename}\" -c copy -t {time} \"{directory}\\Video{index++}.mkv\"";

                            pro.InvokeShell(FFMpegExecute, splitArgs);

                            currentTime = currentTime.Add(time);
                        }
                    }
                }
                else
                {
                    throw new Exception($"FileName:{filename} Read File Struct Error");
                }
            }
Exemple #12
0
        public static void RestartCurrentApplication()
        {
            try {
                ProcessExtension.Start(MainExecutingFile.Location,
                                       Environment.GetCommandLineArgs().Skip(1).ApartFrom(RestartArg)
                                       .Where(x => !x.StartsWith("acmanager:", StringComparison.OrdinalIgnoreCase)).Prepend(RestartArg));

                var app = Application.Current;
                if (app == null)
                {
                    Environment.Exit(0);
                }
                else
                {
                    app.Shutdown();
                }
            } catch (Exception e) {
                Logging.Warning(e);
            }
        }
Exemple #13
0
        private static async Task ResetService()
        {
            var secondResponse = ActionExtension.InvokeInMainThread(() => MessageDialog.Show(
                                                                        "Would you like to reset FTH system to make sure changes are applied? Otherwise, you would need to restart Windows.[br][br]It’ll need to run this command:[br][mono]Rundll32.exe fthsvc.dll,FthSysprepSpecialize[/mono][br][br]Or, Content Manager can simply prepare a .bat-file for you to inspect and run manually. [url=\"https://docs.microsoft.com/en-us/windows/win32/win7appqual/fault-tolerant-heap\"]Learn more[/url].",
                                                                        "One more thing",
                                                                        new MessageDialogButton(MessageBoxButton.YesNo, MessageBoxResult.Yes)
            {
                [MessageBoxResult.Yes] = "Reset automatically",
                [MessageBoxResult.No]  = "Prepare a .bat-file only"
            }));

            if (secondResponse == MessageBoxResult.Cancel)
            {
                return;
            }

            var filename = FilesStorage.Instance.GetTemporaryFilename("RunElevated", "FixFTH.bat");

            File.WriteAllText(filename, @"@echo off
:: More info: https://docs.microsoft.com/en-us/windows/win32/win7appqual/fault-tolerant-heap
echo Running rundll32.exe fthsvc.dll,FthSysprepSpecialize...
cd %windir%\system32
%windir%\system32\rundll32.exe fthsvc.dll,FthSysprepSpecialize
echo Done
pause");

            if (secondResponse == MessageBoxResult.Yes)
            {
                var procRunDll32 = ProcessExtension.Start("explorer.exe", new[] { filename }, new ProcessStartInfo {
                    Verb = "runas"
                });
                await procRunDll32.WaitForExitAsync().ConfigureAwait(false);

                Logging.Debug("Done: " + procRunDll32.ExitCode);
            }
            else if (secondResponse == MessageBoxResult.No)
            {
                WindowsHelper.ViewFile(filename);
            }
        }
Exemple #14
0
        public static StatisticalResultCsv[] RunIndividual(AlgorithmCsv algorithm, DatasetCsv dataset, int k, bool runScript)
        {
            List <StatisticalResultCsv> finalResults = new List <StatisticalResultCsv>();

            FeatureType dataType = FeatureTypeExtension.FromString(dataset.Feature);

            if (runScript)
            {
                //ProcessExtension.Run("python", $"\"{Config.WorkingFolder}{algorithm.Script}\" {dataset.Name} 10 100");
                ProcessExtension.RunScript($"{Config.WorkingFolder}{algorithm.Script}", $"{dataset.Name} 10 100 {k}");
                //onewan ANOVA
                ProcessExtension.Run("python", $"\"{Config.WorkingFolder}{Config.JobOnewayPy}\" {algorithm.Name} {dataset.Name}");
                //pairwise comparison
                ProcessExtension.Run("RScript", $"\"{Config.WorkingFolder}{Config.JobPairwiseComparisonR}\" {algorithm.Name} {dataset.Name}");
            }

            //compactness

            string folder = $"{Config.WorkingFolder}{algorithm.Name}\\{dataset.Name}\\";

            if (!Directory.Exists(folder))
            {
                throw new FileNotFoundException();
            }

            switch (dataType)
            {
            case FeatureType.Reactivity:
                finalResults.AddRange(CSCompactness.AttachCompactness(algorithm, dataset));
                break;

            case FeatureType.RnaDistance:
                finalResults.AddRange(CSCompactness.AttachCompactness(algorithm, dataset));
                break;
            }


            return(finalResults.ToArray());
        }
Exemple #15
0
        public List <TaskCommand> Generate(Dictionary <string, JToken> sectionData)
        {
            string sectionDataPath = StorageHelper.GetSectionFilePath("temp", $"secdat-{Guid.NewGuid()}.json");

            File.WriteAllText(sectionDataPath, JsonConvert.SerializeObject(sectionData));

            try
            {
                string raw = ProcessExtension.RunToolProcess("target", $"\"script\" \"{sectionDataPath}\"");
                return(JArray.Parse(raw)
                       .Select <JToken, TaskCommand>(x =>
                                                     (x[/* MAGIC */ "tar" + "get"].ToObject <string>(), x["args"].ToObject <string>(),
                                                      x["formatter"].ToObject <string>()))
                       .ToList());
            }
            finally
            {
                if (File.Exists(sectionDataPath))
                {
                    File.Delete(sectionDataPath);
                }
            }
        }
Exemple #16
0
 protected Process GetProcessByName(string processName)
 {
     return(ProcessExtension.GetProcessByName(processName));
 }
Exemple #17
0
            private async Task <string> PackIntoSingleAsync(string destination, IProgress <AsyncProgressEntry> progress, CancellationToken cancellation)
            {
                var list = await Server.PackServerData(IncludeExecutable, ServerPresetPackMode.Windows, true, cancellation);

                if (list == null || cancellation.IsCancellationRequested)
                {
                    return(null);
                }

                var temporary = FilesStorage.Instance.GetTemporaryFilename("EVB Package");

                Directory.CreateDirectory(temporary);

                try {
                    var executable = list.First(x => x.Key.EndsWith(@".exe"));

                    // Building XML with params
                    var doc = new XmlDocument();
                    doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-16", null));

                    var uniqueName = $@"__ROOT_TAG_UNIQUE_NAME_{StringExtension.RandomString(16)}";
                    var rootTag    = (XmlElement)doc.AppendChild(doc.CreateElement(uniqueName));

                    // <InputFile>, <OutputFile>
                    rootTag.AppendChild(doc.CreateElement("InputFile")).InnerText = executable.GetFilename(temporary) ??
                                                                                    throw new Exception("Main executable not in the list");
                    rootTag.AppendChild(doc.CreateElement("OutputFile")).InnerText = destination;

                    // <Files>
                    var filesTag = (XmlElement)rootTag.AppendChild(doc.CreateElement("Files"));
                    filesTag.AppendChild(doc.CreateElement("Enabled")).InnerText = "true";
                    filesTag.AppendChild(doc.CreateElement("DeleteExtractedOnExit")).InnerText = "true";
                    filesTag.AppendChild(doc.CreateElement("CompressFiles")).InnerText         = "true";

                    // A bit of mess for directories
                    XmlElement CreateDirectory(XmlElement parent, string name)
                    {
                        var element = (XmlElement)parent.AppendChild(doc.CreateElement("File"));

                        element.AppendChild(doc.CreateElement("Type")).InnerText                = "3";
                        element.AppendChild(doc.CreateElement("Name")).InnerText                = name;
                        element.AppendChild(doc.CreateElement("Action")).InnerText              = "0";
                        element.AppendChild(doc.CreateElement("OverwriteDateTime")).InnerText   = "false";
                        element.AppendChild(doc.CreateElement("OverwriteAttributes")).InnerText = "false";
                        return((XmlElement)element.AppendChild(doc.CreateElement("Files")));
                    }

                    void CreateFile(XmlElement parent, string name, string filename)
                    {
                        var element = (XmlElement)parent.AppendChild(doc.CreateElement("File"));

                        element.AppendChild(doc.CreateElement("Type")).InnerText                = "2";
                        element.AppendChild(doc.CreateElement("Name")).InnerText                = name;
                        element.AppendChild(doc.CreateElement("File")).InnerText                = filename;
                        element.AppendChild(doc.CreateElement("ActiveX")).InnerText             = "false";
                        element.AppendChild(doc.CreateElement("ActiveXInstall")).InnerText      = "false";
                        element.AppendChild(doc.CreateElement("Action")).InnerText              = "0";
                        element.AppendChild(doc.CreateElement("OverwriteDateTime")).InnerText   = "false";
                        element.AppendChild(doc.CreateElement("OverwriteAttributes")).InnerText = "false";
                        element.AppendChild(doc.CreateElement("PassCommandLine")).InnerText     = "false";
                    }

                    var directories     = new Dictionary <string, XmlElement>();
                    var directoriesRoot = (XmlElement)filesTag.AppendChild(doc.CreateElement("Files"));
                    directories[""] = CreateDirectory(directoriesRoot, "%DEFAULT FOLDER%");

                    XmlElement GetDirectoryOf(string name)
                    {
                        var directoryName = Path.GetDirectoryName(name) ?? "";

                        if (!directories.TryGetValue(directoryName, out XmlElement directory))
                        {
                            directory = CreateDirectory(GetDirectoryOf(directoryName), Path.GetFileName(directoryName));
                            directories[directoryName] = directory;
                        }

                        return(directory);
                    }

                    foreach (var entry in list.ApartFrom(executable))
                    {
                        CreateFile(GetDirectoryOf(entry.Key), Path.GetFileName(entry.Key), entry.GetFilename(temporary));
                    }

                    // <Registries>
                    var registriesTag = (XmlElement)rootTag.AppendChild(doc.CreateElement("Registries"));
                    registriesTag.AppendChild(doc.CreateElement("Enabled")).InnerText = "false";

                    // <Packaging>
                    var packagingTag = (XmlElement)rootTag.AppendChild(doc.CreateElement("Packaging"));
                    packagingTag.AppendChild(doc.CreateElement("Enabled")).InnerText = "false";

                    // <Options>
                    var optionsTag = (XmlElement)rootTag.AppendChild(doc.CreateElement("Options"));
                    optionsTag.AppendChild(doc.CreateElement("ShareVirtualSystem")).InnerText             = "true";
                    optionsTag.AppendChild(doc.CreateElement("MapExecutableWithTemporaryFile")).InnerText = "false";
                    optionsTag.AppendChild(doc.CreateElement("AllowRunningOfVirtualExeFiles")).InnerText  = "true";

                    // EVB-file
                    var manifest = FileUtils.GetTempFileName(temporary, ".evb");
                    await FileUtils.WriteAllBytesAsync(manifest, Encoding.Unicode.GetBytes(doc.OuterXml.Replace(uniqueName, "")));

                    // Processing
                    var evb = Shell32.FindExecutable(manifest);
                    if (Path.GetFileName(evb)?.Contains("enigma", StringComparison.OrdinalIgnoreCase) != true || !File.Exists(evb))
                    {
                        throw new InformativeException("Enigma Virtual Box not found",
                                                       "Please, make sure it’s installed and .EVB-files are associated with its “enigmavbconsole.exe” executable.");
                    }

                    var process = ProcessExtension.Start(evb, new[] { manifest }, new ProcessStartInfo {
                        CreateNoWindow         = true,
                        RedirectStandardError  = true,
                        RedirectStandardOutput = true,
                        UseShellExecute        = false
                    });

                    process.Start();

                    var error  = new StringBuilder();
                    var output = new StringBuilder();
                    process.ErrorDataReceived += (sender, args) => {
                        if (args.Data != null)
                        {
                            error.Append(args.Data);
                            error.Append('\n');
                        }
                    };
                    process.OutputDataReceived += (sender, args) => {
                        if (args.Data != null)
                        {
                            output.Append(args.Data);
                            error.Append('\n');
                        }
                    };
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();

                    await process.WaitForExitAsync(cancellation);

                    if (!process.HasExitedSafe())
                    {
                        process.Kill();
                    }

                    Logging.Debug("STDOUT: " + output);
                    Logging.Debug("STDERR: " + error);

                    if (process.ExitCode != 0 && !File.Exists(destination))
                    {
                        throw new Exception($@"Exit code={process.ExitCode}");
                    }

                    return(destination);
                } finally {
                    try {
                        //list.DisposeEverything();
                        //Directory.Delete(temporary, true);
                    } catch (Exception e) {
                        Logging.Warning(e);
                    }
                }
            }
Exemple #18
0
        public void Start(int port, [CanBeNull] string filename)
        {
#if DEBUG
            var log = this;
#else
            var log = new NullLog();
#endif
            _server = new WebServer($"http://+:{port}/", log, RoutingStrategy.Wildcard);

            // HTTP part: index webpage, static files nearby (if any)
            var pages = new PagesProvider(filename);

            _server.RegisterModule(new WebApiModule());
            _server.Module <WebApiModule>().RegisterController(() => new IndexPageController(pages));

            if (Directory.Exists(pages.StaticDirectory))
            {
                _server.RegisterModule(new StaticFilesModule(new Dictionary <string, string> {
                    [@"/"] = pages.StaticDirectory
                })
                {
                    UseRamCache = false,
                    UseGzip     = false
                });
            }

            // Websockets part
            var module = new WebSocketsModule();
            _server.RegisterModule(module);

            _sharedServer = new PublishDataSocketsServer(@"Current Race Shared Memory Server");
            module.RegisterWebSocketsServer(@"/api/ws/shared", _sharedServer);

            _statsServer = new PublishDataSocketsServer(@"Current Race Stats Server");
            module.RegisterWebSocketsServer(@"/api/ws/stats", _statsServer);

            // Starting
            try {
                _server.RunAsync();
            } catch (HttpListenerException e) when(e.ToString().Contains("0x80004005"))
            {
                NonfatalError.NotifyBackground("Can’t start web server",
                                               $"Don’t forget to allow port’s usage with something like “netsh http add urlacl url=\"http://+:{port}/\" user=everyone”.", e, new[] {
                    new NonfatalErrorSolution($"Use “netsh” to allow usage of port {port}", null, async token => {
                        try {
                            var command = $"netsh http add urlacl url=\"http://+:{port}/\" user=everyone";
                            var proc    = ProcessExtension.Start("cmd", new[] {
                                "/C", $"echo {command} & {command} & @pause"
                            }, new ProcessStartInfo {
                                Verb = "runas"
                            });
                            await proc.WaitForExitAsync(token).ConfigureAwait(false);
                            Logging.Debug("Done: " + proc.ExitCode);
                        } catch (Win32Exception ex) when(ex.ErrorCode != -1)
                        {
                            Logging.Debug(ex.ErrorCode);
                            throw new InformativeException("Access denied",
                                                           "Unfortunately, HTTP.sys driver doesn’t allow to assign ports without administrator privileges.");
                        }
                    })
                });
            } catch (Exception e) {
                Logging.Error(e);
            }
        }
 public void RunFirstPy()
 {
     ProcessExtension.Run("python", "C:\\JICWork\\first.py");
     Debug.Print("hi");
 }
Exemple #20
0
        public static string ScanForGamePath()
        {
            try
            {
                var uoFileName = ProcessExtension.GetFileNameFromProcessName("CoDUOMP");
                if (!string.IsNullOrEmpty(uoFileName))
                {
                    return(uoFileName);
                }

                var codFileName = ProcessExtension.GetFileNameFromProcessName("CoDMP");
                if (!string.IsNullOrEmpty(codFileName))
                {
                    return(codFileName);
                }

                var mohaaFileName = ProcessExtension.GetFileNameFromProcessName("mohaa");
                if (!string.IsNullOrEmpty(mohaaFileName))
                {
                    return(mohaaFileName);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Log.WriteLine(ex.ToString());
            }

            try
            {
                var procs = Process.GetProcesses();
                for (int i = 0; i < procs.Length; i++)
                {
                    var proc = procs[i];
                    if ((proc?.MainWindowTitle ?? string.Empty).IndexOf("CoD:United Offensive Multiplayer", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        var fileName = ProcessExtension.GetFileNameFromProcess(proc);
                        if (!string.IsNullOrEmpty(fileName))
                        {
                            return(fileName);
                        }
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Log.WriteLine(ex.ToString());
            }

            try
            {
                var filesInStartup = Directory.GetFiles(Application.StartupPath);
                if (filesInStartup?.Length > 0)
                {
                    for (int i = 0; i < filesInStartup.Length; i++)
                    {
                        var fileName = Path.GetFileName(filesInStartup[i]);
                        if (fileName.Equals("CoDUOMP.exe", StringComparison.OrdinalIgnoreCase) || fileName.Equals("CoDMP.exe", StringComparison.OrdinalIgnoreCase) || fileName.Equals("mohaa.exe", StringComparison.OrdinalIgnoreCase))
                        {
                            return(Application.StartupPath);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Log.WriteLine(ex.ToString());
            }

            var registryInstallPath = Registry.GetValue(RegistryPath, "InstallPath", string.Empty)?.ToString() ?? string.Empty;

            if (string.IsNullOrEmpty(registryInstallPath))
            {
                registryInstallPath = Registry.GetValue(RegistryPathVirtualStore, "InstallPath", string.Empty)?.ToString() ?? string.Empty;
            }

            if (!string.IsNullOrEmpty(registryInstallPath))
            {
                return(registryInstallPath);
            }

            var paths1 = GetPotentialPathsFromSubkey(@"Software\Classes\VirtualStore\MACHINE\SOFTWARE\NVIDIA Corporation\Global\NVTweak\NvCplAppNamesStored", Registry.CurrentUser);
            var paths2 = GetPotentialPathsFromSubkey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FeatureUsage\AppSwitched", Registry.CurrentUser);
            var paths3 = GetPotentialPathsFromSubkey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FeatureUsage\ShowJumpView", Registry.CurrentUser);
            var paths4 = GetPotentialPathsFromSubkey(@"Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Compatibility Assistant\Store", Registry.CurrentUser);
            var paths5 = GetPotentialPathsFromSubkey(@"System\GameConfigStore\Children", Registry.CurrentUser, true);

            var allPaths = Pool.GetList <string>();

            try
            {
                allPaths.AddRange(paths1);
                allPaths.AddRange(paths2);
                allPaths.AddRange(paths3);
                allPaths.AddRange(paths4);
                allPaths.AddRange(paths5);

                if (allPaths.Count < 1)
                {
                    var noRegPathStr = "allPaths was empty, so we were unable to grab any install info from registry.";
                    Console.WriteLine(noRegPathStr);
                    Log.WriteLine(noRegPathStr);
                    return(string.Empty);
                }
                else
                {
                    if (allPaths.Count == 1)
                    {
                        return(allPaths[0]);
                    }

                    var distinctPaths = allPaths.Distinct();
                    var allPathStr    = "distinctPaths contains: " + distinctPaths.Count().ToString("N0") + " paths: " + Environment.NewLine + string.Join(", ", distinctPaths);
                    Console.WriteLine(allPathStr);
                    Log.WriteLine(allPathStr);
                    return(distinctPaths.Count() == 1 ? distinctPaths.FirstOrDefault() : distinctPaths.OrderByDescending(p => File.GetLastAccessTimeUtc(p)).FirstOrDefault());
                }
            }
            finally { Pool.FreeList(ref allPaths); }
        }
Exemple #21
0
        private async Task RunWrapper(string serverExecutable, ICollection <string> log, IProgress <AsyncProgressEntry> progress, CancellationToken cancellation)
        {
            progress.Report(AsyncProgressEntry.FromStringIndetermitate("Loading wrapper…"));
            var wrapperFilename = await LoadWinWrapper(cancellation);

            if (cancellation.IsCancellationRequested)
            {
                return;
            }

            if (wrapperFilename == null)
            {
                throw new InformativeException("Can’t run server", "Can’t load server wrapper.");
            }

            try {
                using (var process = ProcessExtension.Start(wrapperFilename, new[] {
                    "-e", serverExecutable, $"presets/{Id}"
                }, new ProcessStartInfo {
                    UseShellExecute = false,
                    WorkingDirectory = Path.GetDirectoryName(serverExecutable) ?? "",
                    RedirectStandardOutput = true,
                    CreateNoWindow = true,
                    RedirectStandardError = true,
                    StandardOutputEncoding = Encoding.UTF8,
                    StandardErrorEncoding = Encoding.UTF8,
                })) {
                    process.Start();
                    SetRunning(process);
                    ChildProcessTracker.AddProcess(process);

                    progress?.Report(AsyncProgressEntry.Finished);
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();

                    process.OutputDataReceived += (sender, args) => {
                        if (!string.IsNullOrWhiteSpace(args.Data))
                        {
                            ActionExtension.InvokeInMainThread(() => log.Add(Regex.Replace(args.Data, @"\b(WARNING: .+)", @"[color=#ff8800]$1[/color]")));
                        }
                    };

                    process.ErrorDataReceived += (sender, args) => {
                        if (!string.IsNullOrWhiteSpace(args.Data))
                        {
                            ActionExtension.InvokeInMainThread(() => log.Add($@"[color=#ff0000]{args.Data}[/color]"));
                        }
                    };

                    await process.WaitForExitAsync(cancellation);

                    if (!process.HasExitedSafe())
                    {
                        process.Kill();
                    }

                    log.Add($@"[CM] Stopped: {process.ExitCode}");
                }
            } finally {
                SetRunning(null);
            }
        }
Exemple #22
0
 public static void ViewDirectory([NotNull] string directory)
 {
     ProcessExtension.Start(@"explorer", new [] { FileUtils.NormalizePath(directory) });
 }
Exemple #23
0
 public static void ViewDirectory([NotNull] string directory)
 {
     ProcessExtension.Start(@"explorer", new [] { directory });
 }