public void InstallService()
        {
            SetResutlText($"\n===== Installing service started =====", true);
            try
            {
                CopyAndUnzipFile();
                SetResutlText("Service installation begin");

                string installer = GetInstaller();
                if (string.IsNullOrEmpty(installer))
                {
                    SetResutlText("No application found to install");
                    SetResutlText($"\n===== Installing service ended with error =====", true);
                    return;
                }

                string cmd = GetInstallationCmd(installer);
                SetResutlText(ProcessHelpers.RunCmd(cmd, true));
            }
            catch (Exception ex)
            {
                SetResutlText($"{ex}");
            }
            SetResutlText($"\n===== Installing service ended =====", true);

            SetResutlText($"\n===== Starting service started =====", true);
            string startCmd = $"/k net start {setting.Settings.ServiceName}";

            SetResutlText(ProcessHelpers.RunCmd(startCmd, true));
            SetResutlText($"\n===== Starting service ended =====", true);
        }
示例#2
0
        /// <summary>
        /// Gets an "application name" for the executing application by looking at
        /// the hosted app name (.NET Framework on IIS only), assembly name, and process name.
        /// </summary>
        /// <returns>The default service name.</returns>
        private static string GetApplicationName()
        {
            try
            {
                try
                {
                    if (TryLoadAspNetSiteName(out var siteName))
                    {
                        return(siteName);
                    }
                }
                catch (Exception ex)
                {
                    // Unable to call into System.Web.dll
                    Log.SafeLogError(ex, "Unable to get application name through ASP.NET settings");
                }

                return(Assembly.GetEntryAssembly()?.GetName().Name ??
                       ProcessHelpers.GetCurrentProcessName());
            }
            catch (Exception ex)
            {
                Log.SafeLogError(ex, "Error creating default service name.");
                return(null);
            }
        }
示例#3
0
    protected void AddEnvironmentVariablesToProcess(ProcessStartInfo startInfo, IDictionary <string, string> environmentVariables)
    {
        var environment = startInfo.Environment;

        ProcessHelpers.SetEnvironmentVariable(environment, "ASPNETCORE_ENVIRONMENT", DeploymentParameters.EnvironmentName, Logger);
        ProcessHelpers.AddEnvironmentVariablesToProcess(startInfo, environmentVariables, Logger);
    }
        public void ServiceCheckStatus()
        {
            SetResutlText($"\n===== Getting service status started =====", true);
            string cmd = $"/k sc query {setting.Settings.ServiceName}";

            SetResutlText(ProcessHelpers.RunCmd(cmd, true));
            SetResutlText($"\n===== Getting service status ended =====", true);
        }
        public void UnInstallService()
        {
            SetResutlText($"\n===== Uninstalling service started =====", true);
            string cmd = $"/k sc delete {setting.Settings.ServiceName}";

            SetResutlText(ProcessHelpers.RunCmd(cmd, true));
            SetResutlText($"\n===== Uninstalling service ended =====", true);
        }
示例#6
0
        public void StopService()
        {
            SetResutlText($"\n===== Stopping service started =====", true);
            string cmd = $"/k net stop {setting.Settings.ServiceName}";

            SetResutlText(ProcessHelpers.RunCmd(cmd, true));
            SetResutlText($"\n===== Stopping service ended =====", true);
        }
示例#7
0
        private void OpenHyperlink(object parameter)
        {
            if (parameter is not string s)
            {
                return;
            }

            ProcessHelpers.ShellExecute(s);
        }
        public async Task <IEnumerable <WorkRoot> > GetWorkRootsAsync(
            CancellationToken cancellationToken)
        {
            IUserSettingsManager settingsManager = _app.GetRequiredService <IUserSettingsManager>();

            UserSettings?settings = await settingsManager.GetAsync(cancellationToken);

            if (settings.WorkRoots.Count() == 0)
            {
                _console.WriteLine("No work roots configured!");
                _console.WriteLine("You can configure you work roots in the UI or directly in:");
                _console.WriteLine($"{SettingsStore.UserSettingsFilePath}.");

                var options = new List <string>
                {
                    "Open UI",
                    "Open User settings in code",
                    $"Add {Directory.GetCurrentDirectory()} as work root",
                    "Cancel"
                };

                var index = _console.ChooseFromList(options);

                switch (index)
                {
                case 0:
                    IWebServer?webServer = _app.GetRequiredService <IWebServer>();
                    var        url       = await webServer.StartAsync(3003);

                    ProcessHelpers.OpenBrowser(url + "/settings");
                    break;

                case 1:
                    //first ensure file exists
                    if (!File.Exists(SettingsStore.UserSettingsFilePath))
                    {
                        await AddCurrentWorkroot(settingsManager, cancellationToken);
                    }
                    IWorkspaceService workspaceService = _app.GetRequiredService <IWorkspaceService>();
                    await workspaceService.OpenFileInCode(SettingsStore.UserSettingsFilePath);

                    break;

                case 2:
                    await AddCurrentWorkroot(settingsManager, cancellationToken);

                    break;

                default:
                    break;
                }
            }

            return(settings.WorkRoots);
        }
示例#9
0
        public async Task OnExecute(IConsole console)
        {
            console.WriteLine("Starting local proxy");
            var port = NetworkExtensions.GetAvailablePort(Port);

            if (port != Port)
            {
                console.WriteLine($"Port {Port} is allready in use.", ConsoleColor.Yellow);
                var useOther = Prompt.GetYesNo($"Start proxy on port: {port}", true);

                if (useOther)
                {
                    Port = port;
                }
                else
                {
                    return;
                }
            }
            var options = new LocalProxyOptions
            {
                Port = Port,
                DestinationAddress = DestinationAddress
            };

            string url = await _proxyServer.StartAsync(
                options,
                CommandAborded);

            ProcessHelpers.OpenBrowser(url);

            var stopMessage = "Press 'q' or 'esc' to stop";

            console.WriteLine(stopMessage);

            while (true)
            {
                ConsoleKeyInfo key = Console.ReadKey();
                if (key.KeyChar == 'q' || key.Key == ConsoleKey.Escape)
                {
                    break;
                }
                else
                {
                    console.ClearLine();
                    console.WriteLine("Unknown command", ConsoleColor.Red);
                    Console.WriteLine(stopMessage);
                }
            }

            console.WriteLine("Stopping proxy....");
            await _proxyServer.StopAsync();

            _proxyServer.Dispose();
        }
        public PerformanceCountersListener(IDogStatsd statsd)
        {
            _statsd = statsd;

            ProcessHelpers.GetCurrentProcessInformation(out _processName, out _, out _processId);

            // To prevent a potential deadlock when hosted in a service, performance counter initialization must be asynchronous
            // That's because performance counters may rely on wmiApSrv being started,
            // and the windows service manager only allows one service at a time to be starting: https://docs.microsoft.com/en-us/windows/win32/services/service-startup
            _initializationTask = Task.Run(InitializePerformanceCounters);
        }
示例#11
0
        public void AfterStartMining()
        {
            int pid = _miningProcess?.Id ?? -1;

            // TODO C# can have this shorter
            if (_affinityMask != 0 && pid != -1)
            {
                var okMsg = ProcessHelpers.AdjustAffinity(pid, _affinityMask);
                Logger.Info(_logGroup, $"Adjust Affinity returned: {okMsg.Item2}");
            }
        }
        /// <summary>
        /// Performs the entry point pre-checks; custom as well as 'RequiresElevatedPrivileges'.
        /// </summary>
        public void PerformEntryPointPreChecks()
        {
            if (this.RequiresElevatedPrivileges)
            {
                if (!ProcessHelpers.IsCurrentlyRunningAsAdmin())
                {
                    throw new NotSupportedException("This application requires elevated privileges, please run as administrator.");
                }
            }

            this.CustomPerformEntryPointPreChecks();
        }
示例#13
0
        /// <summary>
        /// Initializes a new instance of <see cref="RemoteMemory"/> for a specified <see cref="Process"/>.
        /// </summary>
        /// <param name="proc"><see cref="Process"/> to open.</param>
        public RemoteMemory(Process proc)
        {
            if (!ProcessHelpers.ProcessExists(proc))
            {
                throw new ArgumentException("Process not valid");
            }

            NativeProcess = proc;
            ProcessHandle = ProcessHelpers.OpenProcess(ProcessAccessFlags.AllAccess, NativeProcess.Id);
            Is64          = ProcessHelpers.Is64Bit(NativeProcess);
            Both64        = Is64 && Self64;
        }
示例#14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EventLogConfig"/> class.
 /// </summary>
 /// <param name="logInclusionKindToOriginsMap">The log-item origins to log for.</param>
 /// <param name="source">Optional event log source; DEFAULT is running process' name.</param>
 /// <param name="shouldCreateSourceIfMissing">Value indicating whether or not to create the source if missing.</param>
 /// <param name="logName">Optional log name; DEFAULT is <see cref="DefaultLogName" />.</param>
 /// <param name="machineName">Optional machine name; DEFAULT is <see cref="DefaultMachineName" />.</param>
 /// <param name="logItemPropertiesToIncludeInLogMessage"> The properties/aspects of a <see cref="LogItem"/> to include when building a log message.</param>
 public EventLogConfig(
     IReadOnlyDictionary <LogItemKind, IReadOnlyCollection <string> > logInclusionKindToOriginsMap,
     string source      = null,
     string logName     = DefaultLogName,
     string machineName = DefaultMachineName,
     bool shouldCreateSourceIfMissing = false,
     LogItemPropertiesToIncludeInLogMessage logItemPropertiesToIncludeInLogMessage = LogItemPropertiesToIncludeInLogMessage.Default)
     : base(logInclusionKindToOriginsMap, logItemPropertiesToIncludeInLogMessage)
 {
     this.Source = string.IsNullOrWhiteSpace(source) ? ProcessHelpers.GetRunningProcess().GetName() : source;
     this.ShouldCreateSourceIfMissing = shouldCreateSourceIfMissing;
     this.LogName     = string.IsNullOrWhiteSpace(logName) ? DefaultLogName : logName;
     this.MachineName = string.IsNullOrWhiteSpace(machineName) ? DefaultMachineName : machineName;
 }
示例#15
0
        private void StartEmbeddedExe(string exeName, IEnumerable <string> commandLineArguments)
        {
            var args = new List <string>
            {
                $@"-p ""{ApplicationNameTextBox.Text}""",
                $"-i {CommandDelayUpDown.Value}"
            };

            args.AddRange(commandLineArguments);

            ProcessHelpers.StartEmbeddedExe(exeName,
                                            args.ToArray(),
                                            MinimizeCheckBox.Checked);
        }
示例#16
0
        /// <summary>
        ///     Starts Word
        /// </summary>
        private void StartWord()
        {
            if (IsWordRunning)
            {
                Logger.WriteToLog($"Word is already running on PID {_wordProcess.Id}... skipped");
                return;
            }

            Logger.WriteToLog("Starting Word");

            _word = new WordInterop.ApplicationClass
            {
                ScreenUpdating = false,
                DisplayAlerts  = WordInterop.WdAlertLevel.wdAlertsNone,
                DisplayDocumentInformationPanel = false,
                DisplayRecentFiles = false,
                DisplayScrollBars  = false,
                AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable,
                Visible            = false
            };

            _word.Options.UpdateLinksAtOpen    = false;
            _word.Options.ConfirmConversions   = false;
            _word.Options.SaveInterval         = 0;
            _word.Options.SaveNormalPrompt     = false;
            _word.Options.SavePropertiesPrompt = false;
            _word.Options.AllowReadingMode     = false;
            _word.Options.WarnBeforeSavingPrintingSendingMarkup = false;
            _word.Options.UpdateFieldsAtPrint   = false;
            _word.Options.UpdateLinksAtOpen     = false;
            _word.Options.UpdateLinksAtPrint    = false;
            _word.Options.DoNotPromptForConvert = true;
            _word.Options.LocalNetworkFile      = false;
            _word.Options.ConfirmConversions    = false;

            var captionGuid = Guid.NewGuid().ToString();

            _word.Caption = captionGuid;

            var processId = ProcessHelpers.GetProcessIdByWindowTitle(captionGuid);

            if (!processId.HasValue)
            {
                throw new OCConfiguration("Could not determine Word process by title");
            }

            _wordProcess = Process.GetProcessById(processId.Value);

            Logger.WriteToLog($"Word started with process id {_wordProcess.Id}");
        }
        public PerformanceCountersListener(IDogStatsd statsd)
        {
            _statsd = statsd;

            ProcessHelpers.GetCurrentProcessInformation(out _processName, out _, out _processId);

            _memoryCategory = new PerformanceCounterCategory(MemoryCategoryName);

            var instanceName = GetInstanceName();

            _fullInstanceName = instanceName.Item2;
            _instanceName     = instanceName.Item1;

            InitializePerformanceCounters(_instanceName);
        }
示例#18
0
        public void AfterStartMining()
        {
            int pid = -1;

            if (_miningProcess != null && _miningProcess.Handle != null)
            {
                pid = _miningProcess.Handle.Id;
            }
            // TODO C# can have this shorter
            if (_affinityMask != 0 && pid != -1)
            {
                var(ok, msg) = ProcessHelpers.AdjustAffinity(pid, _affinityMask);
                // TODO log what is going on is it ok or not
            }
        }
示例#19
0
 private static void TrySetProcess()
 {
     try
     {
         if (!_processDataUnavailable && !_initialized)
         {
             _initialized = true;
             ProcessHelpers.GetCurrentProcessInformation(out _currentProcessName, out _currentProcessMachineName, out _currentProcessId);
         }
     }
     catch
     {
         _processDataUnavailable = true;
     }
 }
示例#20
0
        private static void ReplayDynamicXml(string standardInputData)
        {
            var assemblyDirLocation = new Uri(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase) ?? string.Empty).AbsolutePath;
            var exitCode            = ProcessHelpers.ExecuteFileAndReadOutput(new ProcessExecutionSettings
            {
                ProcessExePath    = Path.Combine(assemblyDirLocation, QpDbUpdateToolPath),
                Arguments         = $@"-s -vvv --disableDataIntegrity -t={(int)DBType} -m=""xml"" ""{ConnectionString}""",
                StandardInputData = standardInputData
            }, out var _, out var errorOutput);

            if (exitCode != 0)
            {
                throw new Exception($"Exit code was: {exitCode}, but should be 0. Error output from db update utility: {errorOutput}");
            }
        }
示例#21
0
        private void WebView_OnNavigationStarting(object sender, WebViewControlNavigationStartingEventArgs e)
        {
            if (e.Uri != null && e.Uri.AbsoluteUri == "about:blank")
            {
                e.Cancel = true;
                return;
            }

            if (string.IsNullOrWhiteSpace(e.Uri?.OriginalString))
            {
                return;
            }

            e.Cancel = true;
            ProcessHelpers.OpenUrlInExternalBrowser(e.Uri?.OriginalString);
        }
示例#22
0
        private int GetDotnetMajorVersion()
        {
            var result = ProcessHelpers.RunProcess("dotnet", "--version", Path.GetDirectoryName(_dte.Solution.FileName));

            if (result.exitCode != 0)
            {
                throw new InvalidOperationException($"Unable to detect current dotnet version (\"dotnet --version\" exited with code {result.exitCode})");
            }

            if (result.output.Contains("."))
            {
                if (int.TryParse(result.output.Substring(0, result.output.IndexOf('.')), out int majorVersion))
                {
                    return(majorVersion);
                }
            }

            throw new InvalidOperationException($"Unable to detect current dotnet version (\"dotnet --version\" returned \"{result.output}\")");
        }
示例#23
0
        private void OpenInExplorer(object sender, RoutedEventArgs e)
        {
            string tempPath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "PixiEditor",
                "crash_logs",
                "to-copy");

            DirectoryInfo info = Directory.CreateDirectory(tempPath);

            foreach (var file in info.EnumerateFiles())
            {
                file.Delete();
            }

            File.Copy(report.FilePath, Path.Combine(tempPath, Path.GetFileName(report.FilePath)), true);

            ProcessHelpers.ShellExecute(tempPath);
        }
示例#24
0
        private void OpenHyperlink(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            var tag    = button.Tag as string;

            string body = HttpUtility.UrlEncode($"** IMPORTANT: Drop the \"{Path.GetFileName(report.FilePath)}\" file in here **");

            var result = tag switch
            {
                "github" => GetGitHubLink(),
                "discord" => DiscordInviteLink,
                "email" => GetMailtoLink(),
                _ => throw new NotImplementedException()
            };

            OpenInExplorer(null, null);
            ProcessHelpers.ShellExecute(result);

            string GetGitHubLink()
            {
                StringBuilder builder = new();

                builder.Append("https://github.com/PixiEditor/PixiEditor/issues/new?title=");
                builder.Append(HttpUtility.UrlEncode($"Crash Report"));
                builder.Append("&body=");
                builder.Append(body);

                return(builder.ToString());
            }

            string GetMailtoLink()
            {
                StringBuilder builder = new();

                builder.Append("mailto:[email protected]?subject=");
                builder.Append(HttpUtility.UrlEncode($"Crash Report"));
                builder.Append("&body=");
                builder.Append(body);

                return(builder.ToString());
            }
        }
    }
示例#25
0
        public async Task ShowQuickActions(string path)
        {
            IWorkspaceService workspaceService = _app.GetRequiredService <IWorkspaceService>();
            var dir = new DirectoryInfo(path);

            QuickAction[] quickActions =
                workspaceService.GetQuickActions(path).ToArray();

            Console.WriteLine($"Quick actions: {dir.Name}");
            Console.WriteLine($"------------------------------------");

            var actionIndex = _console.ChooseFromList(
                quickActions.Select(x => x.ToString()));

            QuickAction?action = quickActions[actionIndex];

            switch (action.Type)
            {
            case QuickActionTypes.OpenVisualStudioSolution:
                ProcessHelpers.Open(action.Value);
                break;

            case QuickActionTypes.OpenDirectoryInExplorer:
                await workspaceService.OpenInExplorer(action.Value);

                break;

            case QuickActionTypes.OpenDirectoryInCode:
                await workspaceService.OpenInCode(action.Value);

                break;

            case QuickActionTypes.OpenDirectoryInTerminal:
                await workspaceService.OpenInTerminal(action.Value);

                break;

            case QuickActionTypes.RunSuperBoost:
                await workspaceService.RunSuperBoostAsync(action.Title, path);

                break;
            }
        }
示例#26
0
    internal static ProcessStartInfo GetInjectStartInfo(int processId, string optionalArgs = "")
    {
        // get Detourium injectclr location
        var installLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Detourium");

        // get x86 or x64 inject path
        var injectFilename = Path.Combine(installLocation, ProcessHelpers.GetPlatform(processId), "inject.exe");
        var spyFilename    = Path.Combine(installLocation, "Detourium.dll");

        // build args
        var args = string.Format("-m {0} -i \"{1}\" -l {2} -a \"{3}\" -n {4}", "EntryPoint", spyFilename, "Detourium.Runtime.DetouriumRuntime", optionalArgs, processId);

        // create and return the process info
        return(new ProcessStartInfo {
            CreateNoWindow = true,
            UseShellExecute = false,
            FileName = injectFilename,
            Arguments = args
        });
    }
        static LibLogScopeEventSubscriber()
        {
#if NETFRAMEWORK
            // Check if IIS automatic instrumentation has set the AppDomain property to indicate the PreStartInit state
            // If the property is not set, we must rely on a different method of determining the state
            object state = AppDomain.CurrentDomain.GetData(NamedSlotName);
            if (state is bool boolState)
            {
                _performAppDomainFlagChecks = true;
                _executingIISPreStartInit   = boolState;
            }
            else
            {
                _performAppDomainFlagChecks = false;
                _executingIISPreStartInit   = true;

                try
                {
                    string processName = ProcessHelpers.GetCurrentProcessName();

                    if (!processName.Equals("w3wp", StringComparison.OrdinalIgnoreCase) &&
                        !processName.Equals("iisexpress", StringComparison.OrdinalIgnoreCase))
                    {
                        // IIS is not running so we do not anticipate issues with IIS PreStartInit code execution
                        _executingIISPreStartInit = false;
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Error obtaining the process name for quickly validating IIS PreStartInit condition.");
                }
            }

            if (_executingIISPreStartInit)
            {
                Log.Warning("Automatic logs injection detected that IIS is still initializating. The {Source} will be checked at the start of each trace to only enable automatic logs injection when IIS is finished initializing.", _performAppDomainFlagChecks ? "AppDomain" : "System.Diagnostics.StackTrace");
            }
#endif

            InitResolvers();
        }
示例#28
0
        private void WebView_OnNavigationStarting(object sender, CoreWebView2NavigationStartingEventArgs e)
        {
            if (!e.IsUserInitiated)
            {
                return;
            }

            if (e.Uri != null && e.Uri.Contains("about:blank"))
            {
                e.Cancel = true;
                return;
            }

            if (string.IsNullOrWhiteSpace(e.Uri))
            {
                return;
            }

            e.Cancel = true;
            ProcessHelpers.OpenUrlInExternalBrowser(e.Uri);
        }
示例#29
0
        public static bool LocateFileInExplorer(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return(false);
            }

            // Clean up file path so it can be navigated OK
            filePath = Path.GetFullPath(filePath);
            try
            {
                ProcessHelpers.StartProcessAsync("explorer.exe", string.Format("/select,\"{0}\"", filePath));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return(false);
            }

            return(true);
        }
示例#30
0
        /// <summary>
        ///     Starts PowerPoint
        /// </summary>
        private void StartPowerPoint()
        {
            if (IsPowerPointRunning)
            {
                Logger.WriteToLog($"Powerpoint is already running on PID {_powerPointProcess.Id}... skipped");
                return;
            }

            Logger.WriteToLog("Starting PowerPoint");

            _powerPoint = new PowerPointInterop.ApplicationClass
            {
                DisplayAlerts = PowerPointInterop.PpAlertLevel.ppAlertsNone,
                DisplayDocumentInformationPanel = false,
                AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable
            };

            ProcessHelpers.GetWindowThreadProcessId(_powerPoint.HWND, out var processId);
            _powerPointProcess = Process.GetProcessById(processId);

            Logger.WriteToLog($"PowerPoint started with process id {_powerPointProcess.Id}");
        }