public static Version GetVisualStudioVersion() { Process process = Process.GetCurrentProcess(); FileVersionInfo v = process.MainModule.FileVersionInfo; return(new Version(v.ProductMajorPart, v.ProductMinorPart, v.ProductBuildPart)); }
private void SetupProcess(WinProcess setupProcess) { var processRootDirectory = fusionCatalogue .GetActiveLocation(FusionId); metaInfo = LoadMetaInfo(processRootDirectory); var executableName = Path.Combine(processRootDirectory, metaInfo[FusionMetaEntry.ExecutableInfoKey]); setupProcess.StartInfo.Verb = "runas"; setupProcess.StartInfo.FileName = executableName; setupProcess.StartInfo.RedirectStandardOutput = false; setupProcess.StartInfo.RedirectStandardError = false; var parentId = WinProcess.GetCurrentProcess().Id; var parentPort = configStore.Value?.Rest?.Port; setupProcess.StartInfo.EnvironmentVariables.Add(ZappVariables.FusionIdEnvKey, FusionId); setupProcess.StartInfo.EnvironmentVariables.Add(ZappVariables.ParentProcessIdEnvKey, Convert.ToString(parentId)); setupProcess.StartInfo.EnvironmentVariables.Add(ZappVariables.ParentPortEnvKey, Convert.ToString(parentPort)); setupProcess.StartInfo.UseShellExecute = false; setupProcess.StartInfo.CreateNoWindow = true; setupProcess.EnableRaisingEvents = true; setupProcess.Exited += (s, e) => OnExited(); }
private async Task <int> Run(HostCommandContext context, string pipeName, long maxMemory, int affinityMask, int maxCpu) { var currentProcess = SDProcess.GetCurrentProcess(); var logger = context.ServiceProvider.GetService <ILoggerFactory>().CreateLogger <HostProcessImpl>(); logger.HostProcessStart(currentProcess.Id); string name = "pihost." + currentProcess.Id; var limits = new IsolationLimits(maxMemory, maxCpu, affinityMask); if (limits.IsAnyEnabled) { s_jobObject = new JobObject(name); s_jobObject.AddProcess(currentProcess); s_jobObject.Enable(limits, (l, v) => logger.ProcessLimitSet(l, v)); } var host = new IpcServiceHostBuilder(context.ServiceProvider) .AddNamedPipeEndpoint <IHostProcess>(name, pipeName, includeFailureDetailsInResponse: true) .Build(); logger.IpcServiceHostStarting(pipeName); context.SetStartComplete(); await host.RunAsync(context.Token).ConfigureAwait(false); return(0); }
void OnOpen(object sender, EventArgs e) { var fc = new FileChooserDialog("Choose the file to open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept); fc.SetPosition(WindowPosition.Center); if (fc.Run() == (int)ResponseType.Accept) { if (!AppController.Instance.Surface.IsEmpty()) { string fileName = Process.GetCurrentProcess().MainModule.FileName.Replace(".vshost", ""); ProcessStartInfo info = new ProcessStartInfo(fileName); info.UseShellExecute = false; info.Arguments = fc.Filename; Process processChild = Process.Start(info); } else { AppController.Instance.FileName = fc.Filename; var saved = ConfigManager.Read <PrimitivesSurface> (AppController.Instance.FileName); AppController.Instance.ResetSurface(); AppController.Instance.ReloadSurface(saved); _grid.Surface = AppController.Instance.Surface; _grid.Surface.QueueDraw(); } } //Don't forget to call Destroy() or the FileChooserDialog window won't get closed. fc.Destroy(); }
// ReSharper disable once UnusedParameter.Local /// <summary> /// Initializing the Guest class /// </summary> /// <param name="inContext">Should contain information about the environment</param> /// <param name="adapterId"><see cref="string" /> identification of the desired network adapter</param> /// <param name="injectionGuessAddress">Address of the injection assembly to be used for child processes</param> /// <param name="injectionDelay">Number of milliseconds after child process creation to try to inject the code</param> /// <param name="isInDebug">Indicates if injected code should create a log file and print activity information</param> // ReSharper disable once TooManyDependencies public Guest( RemoteHooking.IContext inContext, string adapterId, string injectionGuessAddress, int injectionDelay, bool isInDebug) { DebugMessage( nameof(Guest), "Initializing ..." ); InjectionGuessAddress = injectionGuessAddress; InjectionDelay = injectionDelay; AdapterId = adapterId; if (isInDebug) { try { var process = Process.GetCurrentProcess(); LogPath = Path.Combine(Path.GetTempPath(), "NetworkAdapterSelector-" + process.ProcessName + "[" + process.Id + "].log"); } catch { // ignored } } }
private void Initialize() { m_window = new MainWindow { Text = "Genetic Tanks PID " + Process.GetCurrentProcess().Id }; m_window.Show(); m_renderWindow = new RenderWindow(m_window.DrawingPanelHandle, new ContextSettings { AntialiasingLevel = 8 }); Globals.Initialize(m_renderWindow); //TankFactory.CreateControlledTestTank(Vector2.Zero, 0); // TankFactory.CreateTestTank(new Vector2(-200, -200), 90); // TankFactory.CreateTestTank(new Vector2(200, -200), 180); // TankFactory.CreateTestTank(new Vector2(0, 100), 90); // TankFactory.CreateTestTank(new Vector2(-100, 200), 0); // TankFactory.CreateTestTank(new Vector2(-100, -100), 135); // TankFactory.CreateTestTank(new Vector2(-200, 0), -90); if (Properties.Settings.Default.PauseOnStart) { Globals.EventManager.QueueEvent(new PauseGameEvent(true)); } var ga = new TankGeneticAlgorithmProcess(Globals.Arena, Globals.EventManager, Globals.PhysicsManager); Globals.ProcessManager.AddProcess(ga); }
/// <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)); }
internal void Restart(DTE dte, bool elevated) { var currentProcess = Process.GetCurrentProcess(); var parser = new ArgumentParser(dte.CommandLineArguments); if (currentProcess.MainModule == null) { return; } var builder = new RestartProcessBuilder() .WithDevenv(currentProcess.MainModule.FileName).WithArguments(parser.GetArguments()); var openedItem = GetOpenedItem(dte); if (openedItem != OpenedItem.None) { if (openedItem.IsSolution) { builder.WithSolution(openedItem.Name); } else { builder.WithProject(openedItem.Name); } } if (elevated) { builder.WithElevatedPermission(); } const string commandName = "File.Exit"; var closeCommand = dte.Commands.Item(commandName); CommandEvents closeCommandEvents = null; if (closeCommand != null) { closeCommandEvents = dte.Events.CommandEvents[closeCommand.Guid, closeCommand.ID]; } // Install the handler // ReSharper disable once UnusedVariable var handler = new VisualStudioEventHandler(dte.Events.DTEEvents, closeCommandEvents, builder.Build()); if (closeCommand != null && closeCommand.IsAvailable) { // if the Exit command is present, execute it with all graceful dialogs by VS dte.ExecuteCommand(commandName); } else { // Close brutally dte.Quit(); } }
void LaunchNewExecutable(string targetDirectory) { using (var currentProcess = WindowsProcess.GetCurrentProcess()) { var executableFile = Path.Combine( targetDirectory, $"{currentProcess.ProcessName}.exe"); processManager.LaunchFile(executableFile, $"cleanup {Environment.CurrentDirectory}"); } }
// -------------------------------------------------------------------------------------------- /// <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); }
private void OnBeforeQueryStatusGroup(object sender, EventArgs e) { // I don't need this next line since this is a lambda. // But I just wanted to show that sender is the OleMenuCommand. OleMenuCommand item = (OleMenuCommand)sender; if (ElevationChecker.CanCheckElevation) { item.Visible = !ElevationChecker.IsElevated(Process.GetCurrentProcess().Handle); } }
public static void Attach() { if (!_enabled) { return; } if (!_weAttached && System.Diagnostics.Debugger.IsAttached) { return; // there is already a debugger } if (_tests.Any()) { var stop = false; var stack = new StackTrace(); var frames = stack.GetFrames(); foreach (var frame in frames) { var methodName = frame.GetMethod().Name; if (_tests.Any(t => methodName.Contains(t))) { stop = true; break; } } if (!stop) { // there we test names and we did not match any return; } } if (!System.Diagnostics.Debugger.IsAttached) { // grab the automation object and attach to debugger DTE2 dte = (DTE2)Marshal.GetActiveObject($"VisualStudio.DTE.{_vsVersion}"); // attach to the current process var id = DiagnosticsProcess.GetCurrentProcess().Id; var processes = dte.Debugger.LocalProcesses; var proc = processes.Cast <Process2>().SingleOrDefault(p => p.ProcessID == id); proc.Attach2(); _weAttached = true; } // Break here. Use the Step Out (Shift + F11) to get into the test. System.Diagnostics.Debugger.Break(); }
private static Process FindVsOrVsTestConsoleExe() { var process = Process.GetCurrentProcess(); string executable = Path.GetFileName(process.MainModule.FileName).Trim().ToUpperInvariant(); while (executable != null && executable != "DEVENV.EXE" && executable != "VSTEST.CONSOLE.EXE") { process = ParentProcessUtils.GetParentProcess(process.Id); executable = process != null ? Path.GetFileName(process.MainModule.FileName).Trim().ToUpperInvariant() : null; } return(process); }
private static Process FindVsOrVsTestConsoleExe() { var process = Process.GetCurrentProcess(); string executable = Path.GetFileName(process.MainModule.FileName).Trim().ToLower(); while (executable != null && !ParentProcessRegex.IsMatch(executable)) { process = ParentProcessUtils.GetParentProcess(process.Id); executable = process != null ? Path.GetFileName(process.MainModule.FileName).Trim().ToLower() : null; } return(process); }
public bool ApplicationIsActivated() { var activatedHandle = GetForegroundWindow(); if (activatedHandle == IntPtr.Zero) { return(false); // No window is currently activated } var procId = Process.GetCurrentProcess().Id; int activeProcId; GetWindowThreadProcessId(activatedHandle, out activeProcId); return(activeProcId == procId); }
public static bool Attach(DTE dte) { string myprocesss = Process.GetCurrentProcess().ProcessName; var processes = dte.Debugger.LocalProcesses; foreach (var proc in processes.Cast <EnvDTE.Process>()) { if (proc.Name.Contains(myprocesss)) { proc.Attach(); return(true); } } return(false); }
public bool Execute() { try { var solutionPath = Path.GetFullPath(Environment.ExpandEnvironmentVariables("%HYDRASOLUTIONPATH%")); var projectPath = Path.Combine(solutionPath, @"ApplicationGenerator"); var appFilePath = Path.Combine(projectPath, @"app"); var directory = new DirectoryInfo(appFilePath); var parentProcess = Process.GetCurrentProcess().GetParent(); if (!parentProcess.ProcessName.IsOneOf("devenv", "msvsmon")) { return(true); } using (var package = ZipPackage.Open(Path.Combine(projectPath, "app.zip"), FileMode.Create)) { directory.GetDescendantsAndSelf(d => d.GetDirectories(), d => { foreach (var file in d.GetFiles()) { var path = d.FullName.RemoveStartIfMatches(appFilePath).ForwardSlashes(); var part = package.CreatePart(new Uri(path + "/" + file.Name, UriKind.Relative), ""); using (var stream = new MemoryStream(File.ReadAllBytes(file.FullName))) { part.GetStream().WriteAll(stream); } } }); } } catch (Exception ex) { var error = string.Format("Error zipping up Hydra applicaton files. \r\nError: {0}", ex.ToString()); var message = new BuildErrorEventArgs(string.Empty, string.Empty, string.Empty, 0, 0, 0, 0, error, "", "", DateTime.Now); this.BuildEngine.LogErrorEvent(message); Console.WriteLine(error); return(false); } return(true); }
/// <summary> /// The method opens up a window comparing two files /// </summary> /// <param name="compareFiles">The compare files view model</param> private static void CompareFiles(FileComparisonViewModel compareFiles) { var firstFileName = Path.GetTempFileName(); var secondFileName = Path.GetTempFileName(); compareFiles.FirstFile?.DownloadShelvedFile(firstFileName); compareFiles.SecondFile?.DownloadShelvedFile(secondFileName); var dte = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE80.DTE2; // lets try DTE if (dte != null) { dte.ExecuteCommand("Tools.DiffFiles", string.Format("\"{0}\" \"{1}\" \"{2}\" \"{3}\"", firstFileName, secondFileName, compareFiles.FirstFileDisplayName, compareFiles.SecondFileDisplayName)); return; } string diffToolCommandArguments; string diffToolCommand; GetExternalTool(Path.GetExtension(compareFiles.FirstFile.FileName), out diffToolCommand, out diffToolCommandArguments); if (string.IsNullOrWhiteSpace(diffToolCommand)) { var currentProcess = Process.GetCurrentProcess(); currentProcess.StartInfo.FileName = currentProcess.Modules[0].FileName; currentProcess.StartInfo.Arguments = string.Format(CultureInfo.CurrentCulture, @"/diff ""{0}"" ""{1}""", firstFileName, secondFileName); currentProcess.Start(); } else { // So there is a tool configured. Let's use it diffToolCommandArguments = diffToolCommandArguments.Replace("%1", firstFileName).Replace("%2", secondFileName); var startInfo = new ProcessStartInfo { Arguments = diffToolCommandArguments, FileName = diffToolCommand }; Process.Start(startInfo); } }
static void Main() { Log.InfoFmt("PID {0}", Process.GetCurrentProcess().Id); // ensure all unhandled exceptions are logged AppDomain.CurrentDomain.UnhandledException += (sender, args) => Log.Error(args.ExceptionObject); // farseer configuration Settings.AllowSleep = true; Settings.UseFPECollisionCategories = true; Settings.VelocityIterations = 10; Settings.PositionIterations = 8; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); new GeneticTanks().Run(); }
/// <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 (Exception ex) { if (ex is System.ComponentModel.Win32Exception || ex is NullReferenceException) { sb.Append($"{process.Id, 10} {process.ProcessName, -10} [Elevated process - cannot determine path]\n"); } else { Debug.WriteLine($"[PrintProcessStatus] {ex.ToString()}"); } } } console.Out.WriteLine(sb.ToString()); } catch (InvalidOperationException ex) { console.Out.WriteLine(ex.ToString()); } }
private void InitExt() { RefreshTimer = new Timer(1000); RefreshTimer.Elapsed += RefreshTimerElapsed; RefreshTimer.Enabled = true; IdeProcess = Process.GetCurrentProcess(); InfoControl = new InfoControl((long)(new ComputerInfo()).TotalPhysicalMemory); Injector = new StatusBarInjector(Application.Current.MainWindow); TotalCpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); TotalRamCounter = new PerformanceCounter("Memory", "Available Bytes"); //end of construct IdeProcess.InitCpuUsage(); Injector.InjectControl(InfoControl); OptionsPage = GetDialogPage(typeof(OptionsPage)) as OptionsPage; if (OptionsPage != null) { InfoControl.Format = OptionsPage.Format; //first trigger } }
private void InvokeVsixInstaller(string tempDir, string rootSuffix, bool installSystemWide) { var process = Process.GetCurrentProcess(); var dir = Path.GetDirectoryName(process.MainModule.FileName); var exe = Path.Combine(dir, "VSIXInstaller.exe"); var configuration = new SetupConfiguration() as ISetupConfiguration; var adminSwitch = installSystemWide ? "/admin" : string.Empty; ISetupInstance instance = configuration.GetInstanceForCurrentProcess(); IEnumerable <string> vsixFiles = Directory.EnumerateFiles(tempDir, "*.vsix").Select(f => Path.GetFileName(f)); var start = new ProcessStartInfo { FileName = exe, Arguments = $"{string.Join(" ", vsixFiles)} /instanceIds:{instance.GetInstanceId()} {adminSwitch}", WorkingDirectory = tempDir, UseShellExecute = false, }; if (!string.IsNullOrEmpty(rootSuffix)) { start.Arguments += $" /rootSuffix:{rootSuffix}"; } Process.Start(start); }
public static DotNetProcess GetRunningProcess() { var result = DotNetProcess.GetCurrentProcess(); return(result); }
void TraceCore(TraceEventCache eventCache, string source, TraceEventType eventType, int id, bool hasRelatedActivity, Guid relatedActivity, int level, bool wrapData, params object [] data) { Process p = eventCache != null? Process.GetProcessById(eventCache.ProcessId) : Process.GetCurrentProcess(); w.WriteStartElement("E2ETraceEvent", e2e_ns); // <System> w.WriteStartElement("System", sys_ns); w.WriteStartElement("EventID", sys_ns); w.WriteString(XmlConvert.ToString(id)); w.WriteEndElement(); // FIXME: find out what should be written w.WriteStartElement("Type", sys_ns); w.WriteString("3"); w.WriteEndElement(); w.WriteStartElement("SubType", sys_ns); // FIXME: it does not seem always to match eventType value ... w.WriteAttributeString("Name", eventType.ToString()); // FIXME: find out what should be written w.WriteString("0"); w.WriteEndElement(); // FIXME: find out what should be written w.WriteStartElement("Level", sys_ns); w.WriteString(level.ToString()); w.WriteEndElement(); w.WriteStartElement("TimeCreated", sys_ns); w.WriteAttributeString("SystemTime", XmlConvert.ToString(eventCache != null ? eventCache.DateTime : DateTime.Now)); w.WriteEndElement(); w.WriteStartElement("Source", sys_ns); w.WriteAttributeString("Name", source); w.WriteEndElement(); w.WriteStartElement("Correlation", sys_ns); w.WriteAttributeString("ActivityID", String.Concat("{", Guid.Empty, "}")); w.WriteEndElement(); w.WriteStartElement("Execution", sys_ns); // FIXME: which should I use here? //w.WriteAttributeString ("ProcessName", p.ProcessName); w.WriteAttributeString("ProcessName", p.MainModule.ModuleName); w.WriteAttributeString("ProcessID", p.Id.ToString()); w.WriteAttributeString("ThreadID", eventCache != null ? eventCache.ThreadId : Thread.CurrentThread.ManagedThreadId.ToString()); w.WriteEndElement(); w.WriteStartElement("Channel", sys_ns); // FIXME: find out what should be written. w.WriteEndElement(); w.WriteStartElement("Computer"); w.WriteString(p.MachineName); w.WriteEndElement(); w.WriteEndElement(); // <ApplicationData> w.WriteStartElement("ApplicationData", e2e_ns); w.WriteStartElement("TraceData", e2e_ns); foreach (object o in data) { if (wrapData) { w.WriteStartElement("DataItem", e2e_ns); } if (o is XPathNavigator) { // the output ignores xmlns difference between the parent (E2ETraceEvent and the content node). // To clone such behavior, I took this approach. w.WriteRaw(XPathNavigatorToString((XPathNavigator)o)); } else if (o != null) { w.WriteString(o.ToString()); } if (wrapData) { w.WriteEndElement(); } } w.WriteEndElement(); w.WriteEndElement(); w.WriteEndElement(); w.Flush(); // for XmlWriter Flush(); // for TextWriter }
void TraceCore(TraceEventCache eventCache, string source, TraceEventType eventType, int id, bool hasRelatedActivity, Guid relatedActivity, int level, bool wrapData, params object [] data) { Process p = eventCache != null? Process.GetProcessById(eventCache.ProcessId) : Process.GetCurrentProcess(); w.WriteStartElement("E2ETraceEvent", e2e_ns); // <System> w.WriteStartElement("System", sys_ns); w.WriteStartElement("EventID", sys_ns); w.WriteString(XmlConvert.ToString(id)); w.WriteEndElement(); // FIXME: find out what should be written w.WriteStartElement("Type", sys_ns); w.WriteString("3"); w.WriteEndElement(); w.WriteStartElement("SubType", sys_ns); // FIXME: it does not seem always to match eventType value ... w.WriteAttributeString("Name", eventType.ToString()); // FIXME: find out what should be written w.WriteString("0"); w.WriteEndElement(); // FIXME: find out what should be written w.WriteStartElement("Level", sys_ns); w.WriteString(level.ToString()); w.WriteEndElement(); w.WriteStartElement("TimeCreated", sys_ns); w.WriteAttributeString("SystemTime", XmlConvert.ToString(eventCache != null ? eventCache.DateTime : DateTime.Now)); w.WriteEndElement(); w.WriteStartElement("Source", sys_ns); w.WriteAttributeString("Name", source); w.WriteEndElement(); w.WriteStartElement("Correlation", sys_ns); w.WriteAttributeString("ActivityID", String.Concat("{", Guid.Empty, "}")); w.WriteEndElement(); w.WriteStartElement("Execution", sys_ns); // FIXME: which should I use here? //w.WriteAttributeString ("ProcessName", p.ProcessName); w.WriteAttributeString("ProcessName", p.MainModule.ModuleName); w.WriteAttributeString("ProcessID", p.Id.ToString()); w.WriteAttributeString("ThreadID", eventCache != null ? eventCache.ThreadId : Thread.CurrentThread.ManagedThreadId.ToString()); w.WriteEndElement(); w.WriteStartElement("Channel", sys_ns); // FIXME: find out what should be written. w.WriteEndElement(); w.WriteStartElement("Computer"); w.WriteString(p.MachineName); w.WriteEndElement(); w.WriteEndElement(); // <ApplicationData> w.WriteStartElement("ApplicationData", e2e_ns); foreach (object o in data) { if (wrapData) { w.WriteStartElement("TraceData", e2e_ns); } if (o != null) { w.WriteString(o.ToString()); } if (wrapData) { w.WriteEndElement(); } } w.WriteEndElement(); w.WriteEndElement(); }
/// <summary> /// Print the current list of available .NET core processes for diagnosis, their statuses and the command line arguments that are passed to them. /// </summary> public static void ProcessStatus(IConsole console) { int GetColumnWidth(IEnumerable <int> fieldWidths) { int consoleWidth = 0; if (Console.IsOutputRedirected) { consoleWidth = Int32.MaxValue; } else { consoleWidth = Console.WindowWidth; } int extra = (int)Math.Ceiling(consoleWidth * 0.05); int largeLength = consoleWidth / 2 - 16 - extra; return(Math.Min(fieldWidths.Max(), largeLength)); } void FormatTableRows(List <ProcessDetails> rows, StringBuilder tableText) { if (rows.Count == 0) { tableText.Append("No supported .NET processes were found"); return; } var processIDs = rows.Select(i => i.ProcessId.ToString().Length); var processNames = rows.Select(i => i.ProcessName.Length); var fileNames = rows.Select(i => i.FileName.Length); var commandLineArgs = rows.Select(i => i.CmdLineArgs.Length); int iDLength = GetColumnWidth(processIDs); int nameLength = GetColumnWidth(processNames); int fileLength = GetColumnWidth(fileNames); int cmdLength = GetColumnWidth(commandLineArgs); foreach (var info in rows) { MakeFixedWidth(info.ProcessId.ToString(), iDLength, tableText, true, true); MakeFixedWidth(info.ProcessName, nameLength, tableText, false, true); MakeFixedWidth(info.FileName, fileLength, tableText, false, true); MakeFixedWidth(info.CmdLineArgs, cmdLength, tableText, false, true); tableText.Append("\n"); } } 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; List <Microsoft.Internal.Common.Commands.ProcessStatusCommandHandler.ProcessDetails> printInfo = new (); foreach (var process in processes) { if (process.Id == currentPid) { continue; } try { String cmdLineArgs = GetArgs(process); cmdLineArgs = cmdLineArgs == process.MainModule?.FileName ? string.Empty : cmdLineArgs; string fileName = process.MainModule?.FileName ?? string.Empty; var commandInfo = new ProcessDetails() { ProcessId = process.Id, ProcessName = process.ProcessName, FileName = fileName, CmdLineArgs = cmdLineArgs }; printInfo.Add(commandInfo); } catch (Exception ex) { if (ex is Win32Exception || ex is InvalidOperationException) { var commandInfo = new ProcessDetails() { ProcessId = process.Id, ProcessName = process.ProcessName, FileName = "[Elevated process - cannot determine path]", CmdLineArgs = "" }; printInfo.Add(commandInfo); } else { Debug.WriteLine($"[PrintProcessStatus] {ex.ToString()}"); } } } FormatTableRows(printInfo, sb); console.Out.WriteLine(sb.ToString()); } catch (InvalidOperationException ex) { console.Out.WriteLine(ex.ToString()); } }
public bool Execute() { try { if (Keys.ControlKey.IsPressed()) { if (MessageBox.Show("Debug?", "Debug InstallTemplates", MessageBoxButtons.YesNo) == DialogResult.Yes) { Debugger.Launch(); } } var solutionPath = Path.GetFullPath(Environment.ExpandEnvironmentVariables("%HYDRASOLUTIONPATH%")); var itemTemplatesOutputPath = Path.Combine(solutionPath, @"ApplicationGenerator\ExportedItemTemplates"); var projectTemplatesOutputPath = Path.Combine(solutionPath, @"ApplicationGenerator\ExportedProjectTemplates"); var vsTemplatesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"Visual Studio 2019\Templates\ItemTemplates\Hydra"); var projectDirectory = Path.GetDirectoryName(this.BuildEngine.ProjectFileOfTaskNode); var localTemplatesPath = Path.Combine(projectDirectory, @"bin\" + this.Configuration + @"\Templates"); var directory = new DirectoryInfo(itemTemplatesOutputPath); var parentProcess = Process.GetCurrentProcess().GetParent(); if (!parentProcess.ProcessName.IsOneOf("devenv", "msvsmon")) { return(true); } if (!Directory.Exists(vsTemplatesPath)) { Directory.CreateDirectory(vsTemplatesPath); } // Visual Studio templates foreach (var folder in directory.GetDirectories()) { using (var package = ZipPackage.Open(Path.Combine(vsTemplatesPath, folder.Name + ".zip"), FileMode.Create)) { foreach (var file in folder.GetFiles()) { var part = package.CreatePart(new Uri("/" + file.Name, UriKind.Relative), ""); using (var stream = new MemoryStream(File.ReadAllBytes(file.FullName))) { part.GetStream().WriteAll(stream); } } } } // Locally distributed templates directory = new DirectoryInfo(projectTemplatesOutputPath); if (!Directory.Exists(localTemplatesPath)) { Directory.CreateDirectory(localTemplatesPath); } foreach (var folder in directory.GetDirectories()) { using (var package = ZipPackage.Open(Path.Combine(localTemplatesPath, folder.Name + ".zip"), FileMode.Create)) { var subFolders = folder.GetDirectories("*", SearchOption.AllDirectories); foreach (var file in folder.GetFiles()) { var part = package.CreatePart(new Uri("/" + file.Name, UriKind.Relative), ""); using (var stream = new MemoryStream(File.ReadAllBytes(file.FullName))) { part.GetStream().WriteAll(stream); } } foreach (var subFolder in subFolders) { foreach (var file in subFolder.GetFiles()) { var relativePath = file.FullName.RemoveStart(folder.FullName).ReverseSlashes(); var part = package.CreatePart(new Uri(relativePath, UriKind.Relative), ""); using (var stream = new MemoryStream(File.ReadAllBytes(file.FullName))) { part.GetStream().WriteAll(stream); } } } } } foreach (var file in directory.GetFiles()) { File.Copy(file.FullName, Path.Combine(localTemplatesPath, file.Name), true); } } catch (Exception ex) { var error = string.Format("Error installing Hydra Visual Studio templates. \r\nError: {0}", ex.ToString()); var message = new BuildErrorEventArgs(string.Empty, string.Empty, string.Empty, 0, 0, 0, 0, error, "", "", DateTime.Now); this.BuildEngine.LogErrorEvent(message); Console.WriteLine(error); return(false); } return(true); }
private void ProcessCommand(DataTarget dataTarget, ILogger logger) { logger.LogInformation($"Host PID: {Process.GetCurrentProcess().Id}"); var clrInfo = dataTarget.ClrVersions[0]; logger.LogInformation($"Flavor: {clrInfo.Flavor}"); logger.LogInformation($"Dac: {clrInfo.DacInfo.PlatformAgnosticFileName}"); logger.LogInformation($"Module: {clrInfo.ModuleInfo}"); logger.LogInformation($"TargetArchitecture: {clrInfo.DacInfo.TargetArchitecture}"); using var runtime = CreateRuntime(clrInfo); var runtimeContext = new RuntimeContext(runtime, string.Empty); var heap = runtime.Heap; logger.LogInformation($"Can Walk Heap: {heap.CanWalkHeap}"); // heap.LogTopMemObjects(logger, 10, 1, 1); if (_commandLineOptions.TaskCompletionSource) { LogExtensions.LogTaskCompletionSources(logger, runtimeContext); } if (_commandLineOptions.ServicePointManager) { var servicePointManagerAnalyzer = new ServicePointManagerAnalyzer(runtimeContext); servicePointManagerAnalyzer.Dump(logger); } if (_commandLineOptions.LongString) { LongStringAnalyzer longStringAnalyzer = new LongStringAnalyzer(runtimeContext); longStringAnalyzer.TraversingHeapMode = _commandLineOptions.TraversingHeapMode; longStringAnalyzer.Dump(logger); } if (_commandLineOptions.AsyncStateMachine) { var asyncStateMachineAnalyzer = new AsyncStateMachineAnalyzer(runtimeContext); asyncStateMachineAnalyzer.TraversingHeapMode = _commandLineOptions.TraversingHeapMode; asyncStateMachineAnalyzer.Dump(logger); } if (_commandLineOptions.Heap) { // LogExtensions.LogHeapSegments(runtimeContext.Heap, logger); // var modulesAnalyzer = new ModulesAnalyzer(runtimeContext); // modulesAnalyzer.Dump(logger); } if (_commandLineOptions.Task) { LogExtensions.LogTaskObjects( runtimeContext, logger, true, false); } // var dictionaryProxy = new DictionaryProxy(runtimeContext, 0x1dccd3aec28); // var dictionaryProxy = new DictionaryProxy(runtimeContext, 0x000001dccd176650); // var dictionaryProxy = new DictionaryProxy(runtimeContext, 0x000001dccd1aba48); // dictionaryProxy.Dump(logger); // var dictionaryProxy2 = new DictionaryProxy(runtimeContext, 0x000001dccd2dd198); // var dictionaryProxy2 = new DictionaryProxy(runtimeContext, 0x000001dccef138b8); // dictionaryProxy2.Dump<char, int>(logger); // foreach (var segment in runtime.Heap.Segments) // { // segment.EnumerateObjects() // } // // var q = from obj in runtime.Heap.EnumerateObjects() // where obj.Type != null // && obj.Type.Name == "System.Byte[]" // select obj; // // foreach (var o in q.Take(10)) // { // System.Console.WriteLine($"{o.Address:X} {o.Type}"); // } // // return; // ProcessByteArrays(runtime); ulong totalLohSegmentSize = 0; ulong totalLohObjSize = 0; ulong totalLohArraySize = 0; foreach (var segment in runtime.Heap.Segments) { if (!segment.IsLargeObjectSegment) { continue; } totalLohSegmentSize += segment.Length; var query = from obj in segment.EnumerateObjects() select obj; foreach (var obj in query) { if (!obj.IsFree) { totalLohObjSize += obj.Size; } var isArray = obj.Type?.Name == "System.Byte[]"; if (isArray) { totalLohArraySize += obj.Size; } } } System.Console.WriteLine($"LOH: segments {Size.ToString(totalLohSegmentSize)} all objects {Size.ToString(totalLohObjSize)} byte arrays {Size.ToString(totalLohArraySize)}"); var q = from obj in runtime.Heap.EnumerateObjects() where obj.Type?.Name == "System.Net.Http.HttpResponseMessage" select obj; var countByDiscoveryKey = new Dictionary <string, int>(); long totalRequestLoh = 0; var requestTotalByDiscoveryKey = new Dictionary <string, long>(); long totalResponseLoh = 0; var responseTotalByDiscoveryKey = new Dictionary <string, long>(); foreach (var responseObj in q) { var requestMessageObj = responseObj.ReadObjectField("requestMessage"); var uriProxy = new UriProxy(runtimeContext, requestMessageObj.ReadObjectField("requestUri")); var(requestLength, requestLOH) = GetRequestLength(responseObj, runtimeContext); var(responseLength, responseLOH) = GetResponseLength(responseObj, runtimeContext); // if (uriProxy.Value.Contains("c558fd4d8151489bbaf58896725d7540")) // { // System.Console.WriteLine( // $"{uriProxy.Value} {requestLength} {requestLOH} {responseLength} {responseLOH}"); // } var discoveryKey = GetDiscoveryKey(uriProxy); if (discoveryKey != null) { countByDiscoveryKey.IncrementValue(discoveryKey); } if (requestLOH ?? false) { totalRequestLoh += requestLength ?? 0; if (discoveryKey != null) { requestTotalByDiscoveryKey.IncrementValue(discoveryKey, requestLength ?? 0); } } if (responseLOH ?? false) { totalResponseLoh += responseLength ?? 0; if (discoveryKey != null) { responseTotalByDiscoveryKey.IncrementValue(discoveryKey, responseLength ?? 0); } } // var bufferObj = streamObject.ReadObjectField("_buffer"); } System.Console.WriteLine($"Total Request LOH: {Size.ToString(totalRequestLoh)} Total Response LOH: {Size.ToString(totalResponseLoh)}"); System.Console.WriteLine("Requests by service"); WriteTotals(requestTotalByDiscoveryKey, countByDiscoveryKey); System.Console.WriteLine("Responses by service"); WriteTotals(responseTotalByDiscoveryKey, countByDiscoveryKey); return; foreach (var segment in runtime.Heap.Segments) { if (!segment.IsLargeObjectSegment) { continue; } var query = from obj in segment.EnumerateObjects() where obj.Type?.Name == "System.Byte[]" select obj; foreach (var arrayObject in query.Take(10)) { System.Console.WriteLine(arrayObject.AsArray().Length); } // var query = from obj in segment.EnumerateObjects() // where obj.Type?.Name == "System.Net.HttpWebRequest" // && obj.Address == 0x1fd003e0a08 // select obj; // foreach (var requestObject in query) // { // var uriProxy = new UriProxy(runtimeContext, requestObject.ReadObjectField("_Uri")); // System.Console.WriteLine($"{requestObject} {uriProxy.Value}"); // // var responseObject = requestObject.ReadObjectField("_HttpResponse"); // var m_CoreResponseDataObject = responseObject.ReadObjectField("m_CoreResponseData"); // var m_ConnectStreamObject = m_CoreResponseDataObject.ReadObjectField("m_ConnectStream"); // // if (requestObject.IsNull) // { // System.Console.WriteLine("NO RESPONSE"); // } // else // { // var responseLength = responseObject.ReadField<long>("m_ContentLength"); // System.Console.WriteLine($"Response content length: {responseLength.ToMemorySizeString()}"); // // // Retention path of System.Net.ConnectStream // // // // 0x000001fc90e69720 System.Net.HttpWebRequest._HttpResponse -> // // 0x000001fc903248e0 System.Net.HttpWebResponse.m_CoreResponseData -> // // 0x000001fc903248a8 System.Net.CoreResponseData.m_ConnectStream -> // // 0x000001fc90324718 System.Net.ConnectStream // // // } // // // // if (clrObject.Address == 0x202eed90288) // // { // // System.Console.WriteLine($"{clrObject} {clrObject.Size}"); // // // // var bytes = new byte[clrObject.Size]; // // Span<byte> span = new Span<byte>(bytes); // // dataTarget.DataReader.Read(clrObject.Address, span); // // // // var str = Encoding.UTF8.GetString(span); // // System.Console.WriteLine(str); // // System.Console.WriteLine("-------------------"); // // } // } } }
private void WindowTitleCheckLoop() { while (true) { try { // Get the host process var currentProcess = Process.GetCurrentProcess(); // We do care only about the main window var mainWindowHandler = currentProcess.MainWindowHandle; if (mainWindowHandler != IntPtr.Zero && !string.IsNullOrEmpty(currentProcess.MainWindowTitle)) { if (ActiveWindow != mainWindowHandler) { if (ActiveWindow != IntPtr.Zero) { DebugMessage( nameof(WindowTitleCheckLoop), "Main window changed from #{0} to #{1}. Cleaning old window's title bar.", ActiveWindow, mainWindowHandler ); // In case main window changed, we need to clean the older one try { WindowTitle.CleanWindowsTitle(ActiveWindow); } catch { // ignored } } ActiveWindow = mainWindowHandler; } // Making sure that our special text is in the title bar WindowTitle.AppendWindowTitle(ActiveWindow, GenerateCaptionText()); } Thread.Sleep(300); } catch (Exception e) { // Ignoring the InvalidOperationException as it happens a lot when program don't have // a valid window if (!(e is InvalidOperationException)) { DebugMessage(nameof(WindowTitleCheckLoop), e.ToString()); } Thread.Sleep(1000); } } // ReSharper disable once FunctionNeverReturns }
public void RegisterPackage(string packageIdentifier, string packagePath) { var fileInfo = new FileInfo(packagePath); var outdated = false; var installedExtension = (IInstalledExtension)null; if (!fileInfo.Exists) { var openFileDialog = new OpenFileDialog(); var ext = Path.GetExtension(packagePath).Remove(0, 1); var window = new WindowWrapper(Process.GetCurrentProcess().MainWindowHandle); openFileDialog.CheckFileExists = true; openFileDialog.Filter = string.Format("Package files (*.{0})|*.{0}", ext); openFileDialog.DefaultExt = ext; openFileDialog.InitialDirectory = Environment.ExpandEnvironmentVariables("%HYDRASOLUTIONPATH%"); openFileDialog.Title = string.Format("Select file for '{0}'", packagePath); if (openFileDialog.ShowDialog(window) != DialogResult.OK) { var message = new BuildErrorEventArgs(string.Empty, string.Empty, string.Empty, 0, 0, 0, 0, string.Format("Error finding package '{0}' at '{1}'", packageIdentifier, packagePath) + ". Please select file from bin folder of Package Project or get latest from TFS.", "", "", DateTime.Now); this.BuildEngine.LogErrorEvent(message); return; } else { File.Copy(openFileDialog.FileName, packagePath); } } fileInfo = new FileInfo(packagePath); if (!fileInfo.Exists) { var message = new BuildErrorEventArgs(string.Empty, string.Empty, string.Empty, 0, 0, 0, 0, string.Format("Error finding package '{0}' at '{1}'", packageIdentifier, packagePath) + ". Please select file from bin folder of Package Project or get latest from TFS.", "", "", DateTime.Now); this.BuildEngine.LogErrorEvent(message); return; } if (fileInfo.Extension == ".dll") { // is a dll, use RegPkg var projectFile = new FileInfo(this.BuildEngine.ProjectFileOfTaskNode); var regPkgPath = Path.Combine(solutionPath, @"Binaries\SolutionLibraries\RegPkg.exe"); var process = new Process(); var startInfo = new ProcessStartInfo { UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true, CreateNoWindow = true, FileName = regPkgPath, Arguments = "/unregister" + " \"" + fileInfo.FullName + "\"" }; process.StartInfo = startInfo; process.Start(); var result = process.StandardOutput.ReadToEnd(); result += "\r\n" + process.StandardError.ReadToEnd(); process.WaitForExit(); if (process.ExitCode != 0) { var message = new BuildErrorEventArgs(string.Empty, string.Empty, string.Empty, 0, 0, 0, 0, string.Format("Error unregistering package '{0}'. ", packageIdentifier) + result + " Exit code = " + process.ExitCode.ToString() + ". You can try running Visual Studio as Administrator to uninstall this component.", "", "", DateTime.Now); this.BuildEngine.LogErrorEvent(message); } else { var message = new BuildMessageEventArgs(string.Format("'{0}' package unregistered successfully. ", packageIdentifier) + result, "", "", MessageImportance.High); this.BuildEngine.LogMessageEvent(message); } process = new Process(); startInfo = new ProcessStartInfo { UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true, CreateNoWindow = true, FileName = regPkgPath, Arguments = "/root:Software\\Microsoft\\VisualStudio\\10.0 \"" + packagePath + "\"" }; process.StartInfo = startInfo; process.Start(); result = process.StandardOutput.ReadToEnd(); result += "\r\n" + process.StandardError.ReadToEnd(); process.WaitForExit(); if (process.ExitCode != 0) { var message = new BuildErrorEventArgs(string.Empty, string.Empty, string.Empty, 0, 0, 0, 0, string.Format("Error registering package '{0}'. ", packageIdentifier) + result + " Exit code = " + process.ExitCode.ToString() + ". You can try running Visual Studio as Administrator to install this component.", "", "", DateTime.Now); this.BuildEngine.LogErrorEvent(message); return; } else { var message = new BuildMessageEventArgs(string.Format("'{0}' package registered successfully. ", packageIdentifier) + result, "", "", MessageImportance.High); this.BuildEngine.LogMessageEvent(message); } } else { // is vsx Action <DateTime, DirectoryInfo> checkOutdated = null; checkOutdated = new Action <DateTime, DirectoryInfo>((date, directory) => { foreach (var file in directory.GetFiles()) { if (file.Extension != ".vsix" && file.Extension != ".zip") { if (DateTime.Compare(file.LastWriteTime, date) > 0) { outdated = true; return; } } } foreach (var dir in directory.GetDirectories()) { checkOutdated(date, dir); } }); // lets do another workaround due to Microsoft stupidity //var extensionPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Microsoft\VisualStudio\10.0\Extensions\Cloud IDEaaS"); //var folder = new DirectoryInfo(extensionPath); //Action<DirectoryInfo> deleteDeleteMeFiles = null; //deleteDeleteMeFiles = new Action<DirectoryInfo>(directory => //{ // foreach (var file in directory.GetFiles("*.deleteme")) // { // try // { // file.Delete(); // } // catch (Exception ex) // { // try // { // RestartExplorer(); // file.Delete(); // } // catch // { // try // { // var hydraCopyPath = Path.Combine(solutionPath, @"Binaries\SolutionLibraries\HydraCopy.exe"); // var process = new Process(); // var startInfo = new ProcessStartInfo // { // UseShellExecute = false, // RedirectStandardError = true, // RedirectStandardOutput = true, // CreateNoWindow = true, // FileName = hydraCopyPath, // Arguments = "\"" + file.FullName + "\" /delete" // }; // process.StartInfo = startInfo; // process.Start(); // process.WaitForExit(); // if (process.ExitCode != 0) // { // throw new Exception(string.Format("HydraCopy.exe exited with error code = '{0}'", process.ExitCode)); // } // } // catch (Exception ex2) // { // var message2 = new BuildErrorEventArgs(string.Empty, string.Empty, string.Empty, 0, 0, 0, 0, string.Format("Error launching HydraCopy.exe to remove leftover files for package '{0}'. Error={1}. You can try rebuilding or restarting Visual Studio to remove these files.", packageIdentifier, ex2.ToString()), "", "", DateTime.Now); // this.BuildEngine.LogErrorEvent(message2); // } // var message = new BuildErrorEventArgs(string.Empty, string.Empty, string.Empty, 0, 0, 0, 0, string.Format("Error removing leftover files for package '{0}'. Error={1}. You can try rebuilding or restarting Visual Studio to remove these files.", packageIdentifier, ex.ToString()), "", "", DateTime.Now); // this.BuildEngine.LogErrorEvent(message); // } // } // } // foreach (var dir in directory.GetDirectories()) // { // deleteDeleteMeFiles(dir); // } //}); //if (folder.Exists) //{ // deleteDeleteMeFiles(folder); //} //if (Environment.Is64BitOperatingSystem) //{ // extensionPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Cloud IDEaaS"); //} //else //{ // extensionPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Cloud IDEaaS"); //} //folder = new DirectoryInfo(extensionPath); //if (folder.Exists) //{ // deleteDeleteMeFiles(folder); //} if (extensionManager.TryGetInstalledExtension(packageIdentifier, out installedExtension)) { checkOutdated(installedExtension.InstalledOn.DateTime, fileInfo.Directory); if (!outdated) { return; } } if (outdated) { // see if there are templates in folder the VSIX installer will balk fileInfo = new FileInfo(Path.Combine(fileInfo.DirectoryName, "extension.vsixmanifest")); if (fileInfo.Exists) { var stream = File.OpenRead(fileInfo.FullName); var installLocation = Path.Combine(Environment.ExpandEnvironmentVariables("%LocalAppData%"), @"Microsoft\VisualStudio\10.0\Extensions"); var _namespace = "vs"; stream.Seek(0, SeekOrigin.Begin); var xPathDocument = new XPathDocument(stream); stream.Close(); var nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace(_namespace, "http://schemas.microsoft.com/developer/vsx-schema/2010"); var navigator = xPathDocument.CreateNavigator(); var iter = navigator.Select(string.Format("{0}:Vsix/{0}:Identifier/{0}:Author", _namespace), nsmgr); iter.MoveNext(); var author = iter.Current.Value; iter = navigator.Select(string.Format("{0}:Vsix/{0}:Identifier/{0}:Name", _namespace), nsmgr); iter.MoveNext(); var name = iter.Current.Value; iter = navigator.Select(string.Format("{0}:Vsix/{0}:Identifier/{0}:Version", _namespace), nsmgr); iter.MoveNext(); var version = iter.Current.Value; installLocation = Path.Combine(installLocation, string.Format(@"{0}\{1}\{2}", author, name, version)); var dirInstall = new DirectoryInfo(installLocation); if (dirInstall.Exists) { try { dirInstall.Delete(true); } catch { try { RestartExplorer(); dirInstall.Delete(true); } catch (Exception ex) { } } } } try { if (extensionManager.IsInstalled(installedExtension)) { extensionManager.Uninstall(installedExtension); } var message = new BuildMessageEventArgs(string.Format("'{0}' package unregistered successfully. ", packageIdentifier), "", "", MessageImportance.High); this.BuildEngine.LogMessageEvent(message); } catch (Exception ex) { var message = new BuildErrorEventArgs(string.Empty, string.Empty, string.Empty, 0, 0, 0, 0, string.Format("Error unregistering package '{0}'. Error={1}", packageIdentifier, ex.ToString()), "", "", DateTime.Now); this.BuildEngine.LogErrorEvent(message); } } if (installedExtension == null || outdated) { try { var debug = false; if (debug) { var package = ZipPackage.Open(@"C:\Users\u164225\Documents\Visual Studio 2010\My Exported Templates\DummyProject.vsix"); var parts = package.GetParts(); package.Close(); package = ZipPackage.Open(packagePath); parts = package.GetParts(); package.Close(); var installExtension2 = extensionManager.CreateInstallableExtension(@"C:\Users\u164225\Documents\Visual Studio 2010\My Exported Templates\DummyProject.vsix"); var reason2 = extensionManager.Install(installExtension2, false); var message2 = new BuildMessageEventArgs(string.Format("'{0}' package registered successfully with restart reason={1}. ", "DummyProject.fc1c3820-6d48-428d-963d-1f4bfa392f6b", reason2), "", "", MessageImportance.High); Debugger.Break(); } var installExtension = extensionManager.CreateInstallableExtension(packagePath); var reason = extensionManager.Install(installExtension, false); var message = new BuildMessageEventArgs(string.Format("'{0}' package registered successfully with restart reason={1}. ", packageIdentifier, reason), "", "", MessageImportance.High); this.BuildEngine.LogMessageEvent(message); } catch (Exception ex2) { try { RestartExplorer(); var installExtension = extensionManager.CreateInstallableExtension(packagePath); var reason = extensionManager.Install(installExtension, false); var message = new BuildMessageEventArgs(string.Format("'{0}' package registered successfully with restart reason={1}. ", packageIdentifier, reason), "", "", MessageImportance.High); this.BuildEngine.LogMessageEvent(message); } catch (Exception ex) { var message = new BuildErrorEventArgs(string.Empty, string.Empty, string.Empty, 0, 0, 0, 0, string.Format("Error registering package '{0}'. Error={1}", packageIdentifier, ex.ToString()), "", "", DateTime.Now); this.BuildEngine.LogErrorEvent(message); } } } } }