/// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            this.GetLogger().LogInformation(this.GetPackageName(), "Initializing.");
            base.Initialize();

            try
            {
                var visualStudioProcess = Process.GetCurrentProcess();
                this.otherApplicationFocusedHandlerReference = this.HandleOtherApplicationFocused;
                this.currentInstanceFocusedHandlerReference  = this.HandleCurrentInstanceFocused;
                this.otherApplicationFocusedHookHandle       = WindowsEventHooker.SetWinEventHook(3, 3, IntPtr.Zero, this.otherApplicationFocusedHandlerReference, 0, 0, SetWinEventHookFlags.WINEVENT_OUTOFCONTEXT | SetWinEventHookFlags.WINEVENT_SKIPOWNPROCESS);
                this.currentInstanceFocusedHookHandle        = WindowsEventHooker.SetWinEventHook(3, 3, IntPtr.Zero, this.currentInstanceFocusedHandlerReference, (uint)visualStudioProcess.Id, 0, SetWinEventHookFlags.WINEVENT_OUTOFCONTEXT);

                var dte = (DTE)this.GetService(typeof(DTE));

                this.solutionEvents = dte.Events.SolutionEvents;
                this.solutionEvents.BeforeClosing += this.HandleBeforeClosingSolution;
                this.solutionEvents.Opened        += this.HandleSolutionOpened;

                this.GetLogger().LogInformation(this.GetPackageName(), "Initialized.");
            }
            catch (Exception exception)
            {
                this.GetLogger().LogError(this.GetPackageName(), "Exception during initialization", exception);
            }
        }
        /// <summary>
        /// Tries to attach the program to Visual Studio debugger.
        /// Returns true is the attaching was successful, false is debugger attaching failed.
        /// </summary>
        /// <param name="sln">Solution file containing code to be debugged.</param>
        public static bool attachDebugger(string sln)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                return(true);
            }
            log("Attaching to Visual Studio debugger...");
            var proc = VSAttacher.GetVisualStudioForSolutions(
                new List <string>()
            {
                Path.GetFileName(sln)
            });

            if (proc != null)
            {
                VSAttacher.AttachVSToProcess(
                    proc, Process.GetCurrentProcess());
            }
            else
            {
                try { System.Diagnostics.Debugger.Launch(); }
                catch (Exception e) { }
            }                     // try and attach the old fashioned way
            if (System.Diagnostics.Debugger.IsAttached)
            {
                log(@"The builder was attached successfully. Further messages will displayed in ""Debug"" output of ""Output"" window.");
                return(true);
            }
            log("Could not attach to visual studio instance.");
            return(false);
        }
예제 #3
0
파일: Login.cs 프로젝트: zneel/TheNoobBot
        private void InitializeProgram()
        {
            try
            {
                // File .exe.config
                Process tempsProcess = Process.GetCurrentProcess();
                bool    restartBot   = !Others.ExistFile(Application.StartupPath + "\\" + tempsProcess.ProcessName + ".exe.config");
                var     sw           = new StreamWriter(Application.StartupPath + "\\" + tempsProcess.ProcessName + ".exe.config");
                sw.WriteLine("<?xml version=\"1.0\"?>");
                sw.WriteLine("<configuration>");
                sw.WriteLine("  <startup>");
                sw.WriteLine("    <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.5\"/>");
                sw.WriteLine("  </startup>");
                sw.WriteLine("  <runtime>");
                sw.WriteLine("    <loadFromRemoteSources enabled=\"true\"/>");
                sw.WriteLine("    <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">");
                sw.WriteLine("    <probing privatePath=\"products\"/>");
                sw.WriteLine("  </assemblyBinding>");
                sw.WriteLine("  </runtime>");
                sw.WriteLine("</configuration>");
                sw.Close();
                if (restartBot)
                {
                    Process.Start(Application.StartupPath + "\\" + tempsProcess.ProcessName + ".exe");
                    tempsProcess.Kill();
                }

                LangSelection.DropDownStyle = ComboBoxStyle.DropDownList;
                Others.GetVisualStudioRedistribuable2013();
            }
            catch (Exception ex)
            {
                Logging.WriteError("Login > InitializeProgram(): " + ex);
            }
        }
예제 #4
0
        internal static void Connect(string login, string password)
        {
            try
            {
                if (HardwareKey == "")
                {
                    HardwareKey = Others.GetRandomString(20);
                }
                Application.DoEvents();
                if (login == "" || (password == "" && login.Length != 20))
                {
                    MessageBox.Show(Translate.Get(Translate.Id.User_name_or_Password_error) + ".",
                                    Translate.Get(Translate.Id.Error), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Process.GetCurrentProcess().Kill();
                    return;
                }
                Login    = login.ToLower();
                Password = password;

                Thread connectThreadLaunch = new Thread(ConnectThread)
                {
                    Name = "ConnectThread"
                };
                connectThreadLaunch.Start();
            }
            catch (Exception e)
            {
                Logging.WriteError("FDsojfOFDSiojfzeosqodifjksdfjsij: " + e);
            }
        }
        /// <summary>
        /// Check if Visual Studio is the foreground window
        /// </summary>
        /// <returns></returns>
        private bool IsVisualStudioForegroundWindow()
        {
            NativeWindowMethods.GetWindowThreadProcessId(NativeWindowMethods.GetForegroundWindow(), out uint foregroundProcessId);
            int visualStudioProcessId = Process.GetCurrentProcess().Id;

            return(visualStudioProcessId == foregroundProcessId);
        }
예제 #6
0
파일: Login.cs 프로젝트: zneel/TheNoobBot
        private void InitializeProgram()
        {
            try
            {
                // File .exe.config
                Process tempsProcess = Process.GetCurrentProcess();
                if (!Others.ExistFile(Application.StartupPath + "\\" + tempsProcess.ProcessName + ".exe.config"))
                {
                    var sw = new StreamWriter(Application.StartupPath + "\\" + tempsProcess.ProcessName + ".exe.config");
                    sw.WriteLine("<?xml version=\"1.0\"?>");
                    sw.WriteLine("<configuration>");
                    sw.WriteLine("<startup>");
                    sw.WriteLine("<supportedRuntime version=\"v4.0\"/>");
                    sw.WriteLine("</startup>");
                    sw.WriteLine("<runtime>");
                    sw.WriteLine("<loadFromRemoteSources enabled=\"true\"/>");
                    sw.WriteLine("</runtime>");
                    sw.WriteLine("</configuration>");
                    sw.Close();

                    Process.Start(Application.StartupPath + "\\" + tempsProcess.ProcessName + ".exe");
                    tempsProcess.Kill();
                }

                LangSelection.DropDownStyle = ComboBoxStyle.DropDownList;
                Others.GetVisualStudioRedistribuable2013();
            }
            catch (Exception ex)
            {
                Logging.WriteError("Login > InitializeProgram(): " + ex);
            }
        }
예제 #7
0
 private static double GetScaleFactor()
 {
     using (var mainWindowHandle = Graphics.FromHwnd(Process.GetCurrentProcess().MainWindowHandle))
     {
         return(mainWindowHandle.DpiX / 96); // 100% scale factor is 96 dpi
     }
 }
예제 #8
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            this.logger.Debug("Initializing...");

            var visualStudioProcess = Process.GetCurrentProcess();

            this.otherApplicationFocusedHandlerReference = this.HandleOtherApplicationFocused;
            this.currentInstanceFocusedHandlerReference  = this.HandleCurrentInstanceFocused;
            this.otherApplicationFocusedHookHandle       = WindowsEventHooker.SetWinEventHook(3, 3, IntPtr.Zero, this.otherApplicationFocusedHandlerReference, 0, 0, SetWinEventHookFlags.WINEVENT_OUTOFCONTEXT | SetWinEventHookFlags.WINEVENT_SKIPOWNPROCESS);
            this.currentInstanceFocusedHookHandle        = WindowsEventHooker.SetWinEventHook(3, 3, IntPtr.Zero, this.currentInstanceFocusedHandlerReference, (uint)visualStudioProcess.Id, 0, SetWinEventHookFlags.WINEVENT_OUTOFCONTEXT);

            try
            {
                var dte = (DTE)this.GetService(typeof(DTE));

                this.solutionEvents = dte.Events.SolutionEvents;
                this.solutionEvents.BeforeClosing += this.HandleBeforeClosingSolution;
            }
            catch (Exception e)
            {
                this.logger.Error(e, "Could not hook visual studio closing event.");
            }

            this.logger.Debug("Initialized...");
        }
예제 #9
0
        private static void Main(string[] args)
        {
            var duration = int.Parse(args[0]);
            var name     = args[1];
            var PID      = Process.GetCurrentProcess().Id;

            var           startTime = DateTime.Now;
            var           i         = 0;
            var           random    = new Random();
            Func <double> runTime   = () => (DateTime.Now - startTime).TotalSeconds;

            while (runTime() < duration)
            {
                var progress = GetProgress(runTime() / duration);
                Console.WriteLine("{2} [{0}-{3}]  line {1:d5} ", name, i, progress, PID);
                double interval;
                if ((i++ % 15) == 0)
                {
                    Console.WriteLine("Cmdline: {0}", Environment.GetCommandLineArgs().Skip(1).ToList().Join(" "));
                    interval = 2000;
                }
                else
                {
                    interval = Math.Round(Math.Exp(-10 * random.NextDouble()) * 1000);
                }
                interval = 10;
                Thread.Sleep((int)interval);
            }
        }
예제 #10
0
        public void Process_Current_Test()
        {
            var pi      = Process.Current;
            var process = DiagnosticsProcess.GetCurrentProcess();

            VerifyProcess(pi, process);
        }
        /// <summary>
        /// Returns an instance of ReloadedProcess from the current Process.
        /// </summary>
        /// <returns></returns>
        public static ReloadedProcess GetCurrentProcess()
        {
            // Get Current Process
            var currentProcess = SystemProcess.GetCurrentProcess();

            // Return Reloaded Process
            return(new ReloadedProcess(currentProcess));
        }
 void LaunchNewExecutable(string targetDirectory)
 {
     using (var currentProcess = WindowsProcess.GetCurrentProcess())
     {
         var executableFile = Path.Combine(targetDirectory, $"{currentProcess.ProcessName}.exe");
         processManager.LaunchFile(executableFile, $"cleanup {Environment.CurrentDirectory}");
     }
 }
예제 #13
0
        // --------------------------------------------------------------------------------------------
        /// <summary>
        /// Try to get the DTE object from the COM ROT.
        /// </summary>
        /// <remarks>Refer to http://books.google.com/books?id=kfRWvKSePmAC&pg=PA131&lpg=PA131&dq=COM+item+moniker&source=bl&ots=o6dVfcbIbq&sig=8PeV1ZW_8s4-Az036GBYoXxpIcU&hl=en&ei=YV2lScvmDobRkAXJuI28BQ&sa=X&oi=book_result&resnum=4&ct=result</remarks>
        // --------------------------------------------------------------------------------------------
        private static void TryToGetServiceProviderFromCurrentProcess(string vsMoniker)
        {
            // provides access to a bind context, which is an object
            // that stores information about a particular moniker binding operation.
            IBindCtx ctx;

            // manages access to the Running Object Table (ROT), a globally accessible look-up
            // table on each workstation. A workstation's ROT keeps track of those objects that
            // can be identified by a moniker and that are currently running on the workstation.
            // Like the idea of Running Document Table.
            IRunningObjectTable rot;

            // used to enumerate the components of a moniker or to enumerate the monikers
            // in a table of monikers.
            IEnumMoniker enumMoniker;

            // contains methods that allow you to use a moniker object, which contains
            // information that uniquely identifies a COM object.
            var moniker = new IMoniker[1];

            // ItemMoniker of the IDE, refer to http://msdn.microsoft.com/en-us/library/ms228755.aspx
            string ideMoniker = String.Format(vsMoniker, Process.GetCurrentProcess().Id);

            // Supplies a pointer to an implementation of IBindCtx (a bind context object).
            CreateBindCtx(0, out ctx);

            // Supplies a pointer to the IRunningObjectTable interface on the local Running Object Table (ROT).
            ctx.GetRunningObjectTable(out rot);

            // Creates and returns a pointer to an enumerator that can list the monikers of
            // all the objects currently registered in the Running Object Table (ROT).
            rot.EnumRunning(out enumMoniker);

            DTE2 dte = null;

            // Enum all the current monikers registered in COM ROT
            while (enumMoniker.Next(1, moniker, IntPtr.Zero) == 0)
            {
                string displayName;
                moniker[0].GetDisplayName(ctx, moniker[0], out displayName);
                if (displayName == ideMoniker)
                {
                    // --- Got the IDE Automation Object
                    Object oDTE;
                    rot.GetObject(moniker[0], out oDTE);
                    dte = oDTE as DTE2;
                    if (dte != null)
                    {
                        break;
                    }
                }
            }

            SuggestGlobalServiceProvider(dte);
        }
예제 #14
0
        internal static void Restart(this DTE dte)
        {
            Process currentProcess = Process.GetCurrentProcess();

            ArgumentParser parser = new ArgumentParser(dte.CommandLineArguments);

            RestartProcessBuilder builder = new RestartProcessBuilder()
                                            .WithDevenv(currentProcess.MainModule.FileName)
                                            .WithArguments(parser.GetArguments());

            OpenedItem openedItem = dte.GetOpenedItem();

            if (openedItem != OpenedItem.None)
            {
                if (openedItem.IsSolution)
                {
                    builder.WithSolution(openedItem.Name);
                }
                else
                {
                    builder.WithProject(openedItem.Name);
                }
            }

            builder.WithElevatedPermission();


            const string commandName = "File.Exit";

            EnvDTE.Command closeCommand = dte.Commands.Item(commandName);

            CommandEvents closeCommandEvents = null;

            if (closeCommand != null)
            {
                closeCommandEvents = dte.Events.CommandEvents[closeCommand.Guid, closeCommand.ID];
            }

            // Install the handler
            VisualStudioCommandInvoker handler = new VisualStudioCommandInvoker(dte.Events.DTEEvents, closeCommandEvents, builder.Build());

            if (closeCommand != null && closeCommand.IsAvailable)
            {
                // if the Exit commad is present, execute it with all gracefulls dialogs by VS
                dte.ExecuteCommand(commandName);
            }
            else
            {
                // Close brutally
                dte.Quit();
            }
        }
예제 #15
0
파일: Login.cs 프로젝트: zneel/TheNoobBot
 private void LangSelection_SelectedIndexChanged(object sender, EventArgs e)
 {
     try
     {
         Directory.CreateDirectory(Application.StartupPath + "\\Settings\\");
         Others.WriteFile(Application.StartupPath + "\\Settings\\lang.txt", LangSelection.Text + ".xml");
         Others.OpenWebBrowserOrApplication(Process.GetCurrentProcess().ProcessName + ".exe");
         Process.GetCurrentProcess().Kill();
     }
     catch (Exception ex)
     {
         Logging.WriteError("LangSelection_SelectedIndexChanged(object sender, EventArgs e): " + ex);
     }
 }
예제 #16
0
 private static void HookWowQ()
 {
     if (true)
     {
         try
         {
             Pulsator.Dispose(true);
         }
         catch
         {
         }
         HookInfoz.GetCurrentProcess().Kill();
     }
 }
예제 #17
0
        private static DTE GetDebuggerHostDte()
        {
            var currentProcessId = Process.GetCurrentProcess().Id;

            foreach (var process in Process.GetProcessesByName("devenv"))
            {
                var dte = IntegrationHelper.TryLocateDteForProcess(process);
                if (dte?.Debugger?.DebuggedProcesses?.OfType <EnvDTE.Process>().Any(p => p.ProcessID == currentProcessId) ?? false)
                {
                    return(dte);
                }
            }

            return(null);
        }
        /// <summary>
        /// Writes the given object (usually an exception) to disc so that it can be picked up by the CrashManager and send to Hockeyapp.
        /// </summary>
        /// <param name="exception">The object to write (usually an exception)</param>
        /// <param name="terminate">Flag that determines whether the process should be terminated after logging the exception</param>
        /// <remarks>This method controls exactly what is written to disc.  Its really a translation of the ExceptionHandler.saveException
        /// This method doesn't call any java if the exception object isn't a java class so it is safe to call when the mono runtime is no
        /// longer able to invoke JNI methods, for example in the case of a crash in the pure c# managed space.</remarks>
        public static void WriteTrace(object exception, bool terminate = true)
        {
            if (exception is Java.Lang.Exception)
            {
                ExceptionHandler.SaveNativeException(exception as Java.Lang.Exception, exception.ToString(), Java.Lang.Thread.CurrentThread(), _Listener);
            }
            else
            {
                ExceptionHandler.SaveManagedException(Java.Lang.Throwable.FromException(exception as Exception), Java.Lang.Thread.CurrentThread(), _Listener);
            }

            if (terminate)
            {
                Process.GetCurrentProcess().Kill();
                Environment.Exit(10);
            }
        }
        public static void PrintProcessStatus(IConsole console)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Process with Event Pipe available for Diagnostics");
            Console.ResetColor();

            // Ignore current process from the list
            int currentProcess = Process.GetCurrentProcess().Id;

            var processes = DiagnosticsClient.GetPublishedProcesses()
                            .Select(GetProcessById)
                            .Where(process => process != null && process.Id != currentProcess);

            foreach (var process in processes)
            {
                Console.WriteLine($"\t{process.Id} {process.ProcessName} {process.MainModule.FileName}");
            }
        }
예제 #20
0
        /// <summary>Determines whether this instance this instance can be started.</summary>
        /// <returns><c>true</c> if this instance can be started; otherwise <c>false</c>.</returns>
        private static bool CanStartThisInstance()
        {
            // check for the "newinstance" argument
            var forceNewInstance = false;

            foreach (var arg in Program.Arguments)
            {
                if (arg == ValidArgs.NewInstance)
                {
                    forceNewInstance = true;
                }
                else if (arg.StartsWith(ValidArgs.ParentProcId))
                {
                    var id = int.Parse(arg.Replace(ValidArgs.ParentProcId, "").Trim());
                    _parentProc  = Process.GetProcessById(id);
                    _isChildProc = true;
                }
            }

            if (forceNewInstance)
            {
                return(true);                  // force starting process
            }
            // check for a previous instance
            var appExeFile = new System.IO.FileInfo(AppPath).Name;

            appExeFile = appExeFile.Remove(appExeFile.LastIndexOf('.')); // remove the extension

            var procs    = Process.GetProcessesByName(appExeFile);
            var thisProc = Process.GetCurrentProcess();

            debuggerAttached = System.Diagnostics.Debugger.IsAttached;

            /*
             * Conditions for starting this instance:
             *  1. This is the only process
             *  2. More than one process and one of the existing processes is this one's parent
             *  3. A debugger is attached to this process
             */
            return((procs.Length == 1 && procs[0].Id == thisProc.Id) ||     // condition 1
                   (procs.Length > 1 && _parentProc != null &&
                    procs.Select(p => p.Id).Contains(_parentProc.Id)) ||    // condition 2
                   debuggerAttached);                                       // condition 3
        }
예제 #21
0
        /// <summary>
        /// Создать <see cref="LuaFixServer"/>.
        /// </summary>
        public LuaFixServer()
        {
            _sessionHolder = new LuaSession(new MillisecondIncrementalIdGenerator())
            {
                Path = SystemProcess.GetCurrentProcess().MainModule.FileName
            };

            var inProcessor  = new MessageProcessorPool(new MessageProcessor("Processor 'LuaServer' (In)", err => _logManager.Application.AddErrorLog(err)));
            var outProcessor = new MessageProcessorPool(new MessageProcessor("Processor 'LuaServer' (Out)", err => _logManager.Application.AddErrorLog(err)));

            _marketDataAdapter = new LuaMarketDataAdapter(_sessionHolder)
            {
                InMessageProcessor  = inProcessor,
                OutMessageProcessor = outProcessor
            };
            _transactionAdapter = new LuaTransactionAdapter(_sessionHolder)
            {
                InMessageProcessor  = inProcessor,
                OutMessageProcessor = outProcessor
            };

            _fixServer = new FixServerEx((l, p) =>
            {
                if (Login.IsEmpty() || (l.CompareIgnoreCase(Login) && p == Password))
                {
                    _prevLevel1.Clear();
                    return(Tuple.Create(TimeSpan.FromMilliseconds(100), FixClientRoles.Admin));
                }

                return(null);
            }, _transactionAdapter, _marketDataAdapter);

            _logManager.Application = new QuikNativeApp();

            _logManager.Sources.Add(_sessionHolder);
            _logManager.Sources.Add(_fixServer);

            LogFile = "StockSharp.QuikLua.log";

            var path        = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var logFileName = Path.Combine(path, LogFile);

            _logManager.Listeners.Add(new FileLogListener(logFileName));
        }
예제 #22
0
 private void DebugMessage(string p)
 {
     try
     {
         if (!_isDebug)
         {
             return;
         }
         var process = Process.GetCurrentProcess();
         File.AppendAllText(
             Path.Combine(Path.GetTempPath(),
                          "NetworkAdapterSelector-" + process.ProcessName + "[" + process.Id + "].log"),
             string.Format("{0}{1}{2}{1}", new string('-', 30), Environment.NewLine, p));
     }
     catch
     {
         // ignored
     }
 }
예제 #23
0
        /// <summary>
        /// Preparing IDE host enviorenment
        /// </summary>
        internal void Init(string startupPath)
        {
            Console.WriteLine("Init()");

            // get #D installation path from registry
            rootPath = (string)Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\SharpDevelop.exe").GetValue("");

            baseDir = Path.GetDirectoryName(Path.GetDirectoryName(rootPath).TrimEnd('\\'));

            dataDir  = baseDir + @"\data\";
            addInDir = baseDir + @"\AddIns\AddIns\";
            binDir   = baseDir + @"\bin\";

            workbenchIsRunning = false;

            comminicationService = new WCFCommunicationService();
            hostProcess          = Process.GetCurrentProcess().Parent();
            ConfigureEnviorenment();
        }
예제 #24
0
        private void btnMute_Click(object sender, EventArgs e)
        {
            var pid = Process.GetCurrentProcess().Id;

            bool muted = !(VolumeMixer.GetApplicationMute(pid) ?? false);

            VolumeMixer.SetApplicationMute(pid, muted);

            muted = VolumeMixer.GetApplicationMute(pid) ?? false;
            if (muted)
            {
                this.btnMute.BackgroundImage = Properties.Resources.Muted;
            }
            else
            {
                this.btnMute.BackgroundImage = Properties.Resources.Volume;
            }

            Settings.Application_Muted.Value = muted;
        }
        internal Elastic.CommonSchema.Process GetProcess()
        {
            if (_processName == null)
            {
                using var process = Process.GetCurrentProcess();
                _processId        = process.Id;
                _processName      = process.ProcessName;
            }

            var currentThread = Thread.CurrentThread;

            return(new Elastic.CommonSchema.Process
            {
                Name = _processName,
                Pid = _processId,
                Thread = new ProcessThread {
                    Name = currentThread.Name, Id = currentThread.ManagedThreadId
                }
            });
        }
예제 #26
0
        public IProcess GetCurrentProcess()
        {
            NativeProcess process;

            try
            {
                process = NativeProcess.GetCurrentProcess();
            }
            catch
            {
                return(null);
            }

            return(new Process
            {
                Id = process.Id,
                MainWindowTitle = process.MainWindowTitle,
                ProcessName = process.ProcessName
            });
        }
        private IEnumerable <Process> EnumerateVisualStudioProcesses()
        {
            var process = Process.GetCurrentProcess();

            if (process.ProcessName.ToLower().Contains(_visualStudioProcessName))
            {
                // We're being compiled directly by Visual Studio
                yield return(process);
            }

            // We're being compiled by other tool (e.g. MSBuild) called from a Visual Studio instance
            // therefore, some Visual Studio instance is our parent process.

            // Because of nodeReuse, we can't guarantee that the parent process of our current process is the "right" Visual Studio
            // so we just have to go through them all, and try to find our project in one of the Visual Studio's that are open

            foreach (var visualStudioProcess in Process.GetProcessesByName(_visualStudioProcessName))
            {
                yield return(visualStudioProcess);
            }
        }
예제 #28
0
        /// <summary>
        /// Print the current list of available .NET core processes for diagnosis and their statuses
        /// </summary>
        public static void PrintProcessStatus(IConsole console)
        {
            try
            {
                StringBuilder sb        = new StringBuilder();
                var           processes = DiagnosticsClient.GetPublishedProcesses()
                                          .Select(GetProcessById)
                                          .Where(process => process != null)
                                          .OrderBy(process => process.ProcessName)
                                          .ThenBy(process => process.Id);

                var currentPid = Process.GetCurrentProcess().Id;

                foreach (var process in processes)
                {
                    if (process.Id == currentPid)
                    {
                        continue;
                    }

                    try
                    {
                        sb.Append($"{process.Id, 10} {process.ProcessName, -10} {process.MainModule.FileName}\n");
                    }
                    catch (InvalidOperationException)
                    {
                        sb.Append($"{process.Id, 10} {process.ProcessName, -10} [Elevated process - cannot determine path]\n");
                    }
                    catch (NullReferenceException)
                    {
                        sb.Append($"{process.Id, 10} {process.ProcessName, -10} [Elevated process - cannot determine path]\n");
                    }
                }
                console.Out.WriteLine(sb.ToString());
            }
            catch (InvalidOperationException ex)
            {
                console.Out.WriteLine(ex.ToString());
            }
        }
예제 #29
0
        private void LaunchBrowser(IBrowserLauncher browserLauncher, IDirectoryAccessor directoryAccessor)
        {
            var processName = Process.GetCurrentProcess().ProcessName;

            var uri = processName == "dotnet" ||
                      processName == "dotnet.exe"
                          ? new Uri("http://localhost:4242")
                          : new Uri("http://localhost:5000");

            if (StartupOptions.Uri != null &&
                !StartupOptions.Uri.IsAbsoluteUri)
            {
                uri = new Uri(uri, StartupOptions.Uri);
            }
            else if (StartupOptions.Uri == null)
            {
                var readmeFile = FindReadmeFileAtRoot();
                if (readmeFile != null)
                {
                    uri = new Uri(uri, readmeFile.ToString());
                }
            }

            browserLauncher.LaunchBrowser(uri);

            RelativeFilePath FindReadmeFileAtRoot()
            {
                var files = directoryAccessor.GetAllFilesRecursively().Where(f => (StringComparer.InvariantCultureIgnoreCase.Compare(f.FileName, "readme.md") == 0) && IsRoot(f.Directory)).ToList();

                return(files.FirstOrDefault());
            }

            bool IsRoot(RelativeDirectoryPath path)
            {
                var isRoot = path == null || path == RelativeDirectoryPath.Root;

                return(isRoot);
            }
        }
예제 #30
0
        public override URIStartResult HandleURIStart(string[] args)
        {
            var myProcessId = Process.GetCurrentProcess().Id;

            //Process[] processes = Process.GetProcessesByName("AmongUsCapture");
            //foreach (Process p in processes)
            //{
            //if (p.Id != myProcessId)
            //    {
            //        p.Kill();
            //    }
            // }
            Console.WriteLine(Program.GetExecutablePath());

            mutex = new Mutex(true, appName, out var createdNew);
            var wasURIStart = args.Length > 0 && args[0].StartsWith(UriScheme + "://");
            var result      = URIStartResult.CONTINUE;

            if (!createdNew) // send it to already existing instance if applicable, then close
            {
                if (wasURIStart)
                {
                    SendToken(args[0]);
                }

                return(URIStartResult.CLOSE);
            }
            else if (wasURIStart) // URI start on new instance, continue as normal but also handle current argument
            {
                result = URIStartResult.PARSE;
            }

            RegisterProtocol();

            return(result);
        }