public void CleanSolution() { DTE dte = (DTE)_serviceProvider.GetService(typeof(DTE)); SolutionBuild solutionBuild = dte.Solution.SolutionBuild; solutionBuild.Clean(true); }
public static bool HasInstrumentation(DTE dte) { SolutionBuild solutionBuild = dte.Solution.SolutionBuild; if ((solutionBuild == null) || (solutionBuild.StartupProjects == null)) { return(false); } foreach (String projectName in (Array)solutionBuild.StartupProjects) { Project project = dte.Solution.Projects.Item(projectName); if (project == null) { return(false); } if (project.ProjectItems.Item(STACK_INSTRUMENT_FILENAME) == null) { return(false); } } return(true); }
/// <summary> /// Determines whether [is loaded share point project selected] [the specified DTE]. /// </summary> /// <param name="dte">The DTE.</param> /// <param name="requireFarm">if set to <c>true</c> [require farm].</param> /// <returns> /// <c>true</c> if [is loaded share point project selected] [the specified DTE]; otherwise, <c>false</c>. /// </returns> public static bool IsLoadedSharePointProjectSelected(EnvDTE.DTE dte, bool requireFarm) { // We must loop to check a project is not only selecetd but loaded. foreach (SelectedItem item in dte.SelectedItems) { // If selected item is a project, and it is loaded, and it is a SharePoint project, then at least one project is selected. if ((item.Project != null) && (item.Project.ConfigurationManager != null) && IsSharePointProject(item.Project, requireFarm)) { return(true); } } // no SP project selected, check startup projects SolutionBuild solutionBuild = dte.Solution.SolutionBuild; if (solutionBuild != null) { Array startupProj = solutionBuild.StartupProjects as Array; if (startupProj != null) { foreach (String projectName in startupProj) { EnvDTE.Project project = DTEManager.GetProjectByName(projectName); if ((project != null) && (project.ConfigurationManager != null) && IsSharePointProject(project, requireFarm)) { return(true); } } } } return(false); }
public static bool TryGetActiveSolutionConfiguration( IServiceProvider serviceProvider, out SolutionBuild solutionBuild, out SolutionConfiguration2 activeConfiguration) { Contract.Requires(serviceProvider != null); Contract.Ensures(Contract.ValueAtReturn(out solutionBuild) != null || !Contract.Result <bool>()); Contract.Ensures(Contract.ValueAtReturn(out activeConfiguration) != null || !Contract.Result <bool>()); solutionBuild = null; activeConfiguration = null; DTE dte = VsServiceProviderHelper.GetService <DTE>(serviceProvider); if (dte == null) { return(false); } var solution = dte.Solution; if (solution == null) { return(false); } solutionBuild = solution.SolutionBuild; Contract.Assume(solutionBuild != null); activeConfiguration = solutionBuild.ActiveConfiguration as SolutionConfiguration2; return(solutionBuild != null && activeConfiguration != null); }
void CreateSolutionBuild() { solutionHelper = new SolutionHelper(); solution = solutionHelper.Solution; projectBuilder = solutionHelper.FakeProjectService.FakeProjectBuilder; solutionBuild = (SolutionBuild)solution.SolutionBuild; }
void CreateSolutionBuild(string solutionFileName = @"d:\projects\MyProject\MySolution.sln") { solutionHelper = new SolutionHelper(solutionFileName); solution = solutionHelper.Solution; projectBuilder = solutionHelper.FakeProjectService.FakeProjectBuilder; solutionBuild = (SolutionBuild)solution.SolutionBuild; }
private void PublishItemCallback(object sender, EventArgs e) { if (_dte.SelectedItems.Count != 1) { return; } SelectedItem item = _dte.SelectedItems.Item(1); ProjectItem projectItem = item.ProjectItem; if (projectItem.IsDirty) { MessageBoxResult result = MessageBox.Show("Save item and publish?", "Unsaved Item", MessageBoxButton.YesNo); if (result != MessageBoxResult.Yes) { return; } projectItem.Save(); } //Build TypeScript project if (projectItem.Name.ToUpper().EndsWith("TS")) { SolutionBuild solutionBuild = _dte.Solution.SolutionBuild; solutionBuild.BuildProject(_dte.Solution.SolutionBuild.ActiveConfiguration.Name, projectItem.ContainingProject.UniqueName, true); } CrmConn selectedConnection = (CrmConn)SharedGlobals.GetGlobal("SelectedConnection", _dte); if (selectedConnection == null) { return; } Guid webResourceId = GetMapping(projectItem, selectedConnection); if (webResourceId == Guid.Empty) { return; } CrmServiceClient connection = new CrmServiceClient(selectedConnection.ConnectionString); //CrmConnection connection = CrmConnection.Parse(selectedConnection.ConnectionString); //Check if < CRM 2011 UR12 (ExecuteMutliple) Version version = Version.Parse(selectedConnection.Version); if (version.Major == 5 && version.Revision < 3200) { UpdateAndPublishSingle(connection, projectItem, webResourceId); } else { UpdateAndPublishMultiple(connection, projectItem, webResourceId); } }
/// <summary> /// Get weather solution is on building or not. /// </summary> /// <param name="dte"></param> /// <returns></returns> public static bool OnBuilding(this DTE dte) { Solution solution = dte.Solution; SolutionBuild solutionBuild = solution.SolutionBuild; vsBuildState buildState = solutionBuild.BuildState; return(buildState == vsBuildState.vsBuildStateInProgress); }
private string SetVariables(string str, string cmdsDir) { if (str == null) { return(str); } var dte = (DTE)_serviceProvider.GetService(typeof(DTE)); Solution sln = dte.Solution; IList <Project> projs = GetProjects(dte); SolutionBuild build = sln.SolutionBuild; var slnCfg = (SolutionConfiguration2)build.ActiveConfiguration; Project proj = projs.Cast <Project>().FirstOrDefault(x => x.FileName.Contains(cmdsDir) && !x.FullName.EndsWith("vcxproj")); ApplyVariable("$(ConfigurationName)", slnCfg.Name, ref str); ApplyVariable("$(DevEnvDir)", Path.GetDirectoryName(dte.FileName), ref str); ApplyVariable("$(PlatformName)", slnCfg.PlatformName, ref str); ApplyVariable("$(SolutionDir)", Path.GetDirectoryName(sln.FileName), ref str); ApplyVariable("$(SolutionExt)", Path.GetExtension(sln.FileName), ref str); ApplyVariable("$(SolutionFileName)", Path.GetFileName(sln.FileName), ref str); ApplyVariable("$(SolutionName)", Path.GetFileNameWithoutExtension(sln.FileName), ref str); ApplyVariable("$(SolutionPath)", sln.FileName, ref str); if (proj != null && proj.ConfigurationManager != null) // some types of projects (TwinCat) can have null ConfigurationManager { Configuration projCfg = proj.ConfigurationManager.ActiveConfiguration; if (projCfg.Properties != null) // website folder projects (File -> Add -> Existing Web Site) have null properties { string outDir = (string)projCfg.Properties.Item("OutputPath").Value; string projectDir = Path.GetDirectoryName(proj.FileName); string targetFilename = (string)proj.Properties.Item("OutputFileName").Value; string targetPath = Path.Combine(projectDir, outDir, targetFilename); string targetDir = Path.Combine(projectDir, outDir); ApplyVariable("$(OutDir)", outDir, ref str); ApplyVariable("$(ProjectDir)", projectDir, ref str); ApplyVariable("$(ProjectExt)", Path.GetExtension(proj.FileName), ref str); ApplyVariable("$(ProjectFileName)", Path.GetFileName(proj.FileName), ref str); ApplyVariable("$(ProjectName)", proj.Name, ref str); ApplyVariable("$(ProjectPath)", proj.FileName, ref str); ApplyVariable("$(TargetDir)", targetDir, ref str); ApplyVariable("$(TargetExt)", Path.GetExtension(targetFilename), ref str); ApplyVariable("$(TargetFileName)", targetFilename, ref str); ApplyVariable("$(TargetName)", proj.Name, ref str); ApplyVariable("$(TargetPath)", targetPath, ref str); } } return(str); }
private bool IsRelease() { ThreadHelper.ThrowIfNotOnUIThread(); DTE2 dte = Package.GetGlobalService(typeof(DTE)) as DTE2;//await this.package.GetServiceAsync(typeof(DTE)) as DTE; Assumes.Present(dte); SolutionBuild builder = dte.Application.Solution.SolutionBuild; SolutionConfiguration2 config = (SolutionConfiguration2)builder.ActiveConfiguration; return(config.SolutionContexts.Item(1).ConfigurationName == "Release"); }
/// <summary> /// Sets the build dependencies in the Visual Studio solution /// The <paramref name="dependsOnProject"/> is excluded from the <paramref name="applicableProjects"/> automatically /// </summary> /// <param name="solutionBuild">Visual Studio build wrapper for current solution</param> /// <param name="applicableProjects">Projects to set the dependency </param> /// <param name="dependsOnProject">Required project the <paramref name="applicableProjects"/> depends on</param> private void SetBuildDependency(SolutionBuild solutionBuild, IEnumerable <Project> applicableProjects, Project dependsOnProject) { ThreadHelper.ThrowIfNotOnUIThread(); foreach (var applicableProject in applicableProjects) { if (applicableProject.UniqueName == dependsOnProject.UniqueName) { continue; } solutionBuild.BuildDependencies.Item(applicableProject.UniqueName).AddProject(dependsOnProject.UniqueName); Package.Output($" Added dependency {applicableProject.UniqueName} depends on {dependsOnProject.UniqueName}"); } }
public static bool BuildProject(Project project) { if (!(Package.GetGlobalService(typeof(DTE)) is DTE dte)) { return(false); } SolutionBuild solutionBuild = dte.Solution.SolutionBuild; solutionBuild.BuildProject(dte.Solution.SolutionBuild.ActiveConfiguration.Name, project.UniqueName, true); //0 = no errors return(solutionBuild.LastBuildInfo <= 0); }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private static Project GetStartupSolutionProject(IServiceProvider serviceProvider, IDictionary <string, string> projectProperties) { LoggingUtils.PrintFunction(); DTE dteService = serviceProvider.GetService(typeof(SDTE)) as DTE; Solution solution = dteService.Solution; SolutionBuild solutionBuild = solution.SolutionBuild; object [] startupProjects = (object [])solutionBuild.StartupProjects; Project startupProject = null; string startupProjectName = string.Empty; if (projectProperties.TryGetValue("ProjectName", out startupProjectName)) { // // Construct a listing of all the sub-projects in this solution. // List <Project> solutionProjects = new List <Project> (); foreach (Project project in solution.Projects) { solutionProjects.Add(project); GetProjectSubprojects(project, ref solutionProjects); } foreach (Project project in solutionProjects) { if (project.Name.Equals(startupProjectName)) { startupProject = project; break; } } } else if (startupProjects.Length > 0) { startupProject = startupProjects [0] as Project; startupProjectName = startupProject.Name; } return(startupProject); }
/// <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> /// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param> /// <param name="progress">A provider for progress updates.</param> /// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns> protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { _dte = (DTE)GetService(typeof(DTE)); sb = _dte.Solution.SolutionBuild; sc = sb.ActiveConfiguration; // When initialized asynchronously, the current thread may be a background thread at this point. // Do any initialization that requires the UI thread after switching to the UI thread. await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); await Command.InitializeAsync(this); AdviseSolutionEvents(); }
public async Task <bool> BuildSolution() { DTE dte = (DTE)_serviceProvider.GetService(typeof(DTE)); SolutionBuild solutionBuild = dte.Solution.SolutionBuild; string solutionConfiguration = solutionBuild.ActiveConfiguration.Name; await TRD.Tasks.Task.Factory.StartNew(() => solutionBuild.Build(true), TaskCreationOptions.LongRunning); bool compiledOK = (solutionBuild.LastBuildInfo == 0); return(compiledOK); }
private static string GetStartupProjectName(DTE myDTE) { string startupProjectName = string.Empty; SolutionBuild solutionBuild = myDTE.Solution.SolutionBuild; if ((solutionBuild == null) || (solutionBuild.StartupProjects == null)) { return(startupProjectName); } foreach (string el in (Array)solutionBuild.StartupProjects) { startupProjectName += el; } return(startupProjectName); }
public static bool AddInstrumentation(DTE dte) { SolutionBuild solutionBuild = dte.Solution.SolutionBuild; if ((solutionBuild == null) || (solutionBuild.StartupProjects == null)) { return(false); } foreach (String projectName in (Array)solutionBuild.StartupProjects) { Project project = dte.Solution.Projects.Item(projectName); if (project == null) { return(false); } try { string instrumentFileLocation = Path.Combine(Path.GetTempPath(), STACK_INSTRUMENT_FILENAME); StreamWriter instrumentCode = new StreamWriter(instrumentFileLocation); instrumentCode.Write(StackChecker.Resources.InstrumentationCode); instrumentCode.Close(); ProjectItem existingInstrumentCode = project.ProjectItems.Item(STACK_INSTRUMENT_FILENAME); if ((existingInstrumentCode != null) && (existingInstrumentCode.Document != null)) { existingInstrumentCode.Document.Close(); } existingInstrumentCode = project.ProjectItems.AddFromFileCopy(instrumentFileLocation); existingInstrumentCode.Open(Constants.vsViewKindCode).Visible = true; return(true); } catch { } return(false); } return(false); }
/// <summary> /// Build the current Visual Studio solution. /// </summary> /// <returns>true if built the solution successfully, false otherwise</returns> public bool BuildSolution() { bool result; try { DTE2 dte2 = (DTE2)Package.GetGlobalService(typeof(SDTE)); //dte2.ExecuteCommand("Build.BuildSolution"); SolutionBuild sb = dte2.Solution.SolutionBuild; sb.Build(true); result = (sb.LastBuildInfo == 0); } catch (Exception e) { WriteToOutput("Error building the solution. " + e.Message); result = false; } return(result); }
public override bool Build() { try { // _applicationObject.ExecuteCommand("Build.BuildSelection", ""); Project = (Project)((Array)Dte.ActiveSolutionProjects).GetValue(0); VsProject = ((VSProject2)(Project.Object)); if (!ExecuteBeforeBuild()) { return(false); } Solution = (Solution2)Dte.Solution; SolutionBuild = (SolutionBuild2)Solution.SolutionBuild; //sb2.BuildProject(sb2.ActiveConfiguration.Name, prj.UniqueName, true); SolutionBuild.Build(true); //_dte.ExecuteCommand("Build.RebuildSolution"); if (SolutionBuild.LastBuildInfo != 0) { return(false); } if (!BuildManifest()) { return(false); } ExecuteAfterRelease(); return(true); } catch (Exception ex) { OutputMessage(ex.Message); Logger.WriteExceptionLog(ex.Message + Environment.NewLine + ex.StackTrace); MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace, Common.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } }
public /*async*/ Task <bool> BuildProject(ProjectInfo project) { DTE dte = (DTE)_serviceProvider.GetService(typeof(DTE)); SolutionBuild solutionBuild = dte.Solution.SolutionBuild; string solutionConfiguration = solutionBuild.ActiveConfiguration.Name; GeneralUtils.ReportStatus($"Build: {project.Name}"); // TODO: 2017-01 Bnaya, Use the async version solutionBuild.BuildProject(solutionConfiguration, project.FullName, true); //await TRD.Tasks.Task.Factory.StartNew(() => // solutionBuild.BuildProject(solutionConfiguration, project.FullName, true), // TaskCreationOptions.LongRunning); bool compiledOK = (solutionBuild.LastBuildInfo == 0); if (!compiledOK && System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Debugger.Break(); } return(TRD.Tasks.Task.FromResult(compiledOK)); }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void MenuItemCallback(object sender, EventArgs e) { string message = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName); string title = "LaunchDebugger"; // Show a message box to prove we were here //VsShellUtilities.ShowMessageBox( // this.ServiceProvider, // message, // title, // OLEMSGICON.OLEMSGICON_INFO, // OLEMSGBUTTON.OLEMSGBUTTON_OK, // OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); FASTBuildPackage fbPackage = (FASTBuildPackage)this.package; if (null == fbPackage.m_dte.Solution) { return; } Solution sln = fbPackage.m_dte.Solution; SolutionBuild sb = sln.SolutionBuild; SolutionConfiguration2 sc = sb.ActiveConfiguration as SolutionConfiguration2; string startupProject = ""; foreach (String item in (Array)sb.StartupProjects) { startupProject += item; } var proj = sln.Item(startupProject).Object as VCProject; fbPackage.m_dte.ToolWindows.SolutionExplorer.GetItem("ConsoleApplication1\\ConsoleApplication1").Select(vsUISelectionType.vsUISelectionTypeSelect); fbPackage.m_dte.ExecuteCommand("ClassViewContextMenus.ClassViewProject.Debug.Startnewinstance"); }
private List <string> GetCurrentDir() { var list = new List <string>(); IVsSolution solution = (IVsSolution)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(IVsSolution)); SolutionBuild sb = StatusInfoPackage.GlobalDte.Solution.SolutionBuild; var sc = sb.StartupProjects as object[]; var startupname = (sc == null || sc.Length == 0) ? null : sc.Select(p => p.ToString()).ToList(); if (startupname == null) { foreach (Project project in MyTool.GetProjects(solution)) { list.Add(Directory.GetParent(project.FullName).FullName); break; } } else { foreach (Project project in MyTool.GetProjects(solution)) { foreach (var item in startupname) { if (project.FullName.EndsWith(item)) { list.Add(Directory.GetParent(project.FullName).FullName); } } } } return(list); }
private void UpdateProjectList() { Project selectedProject = null; if (projectList.SelectedItem != null) { selectedProject = projectList.SelectedItem as Project; } projectList.Items.Clear(); foreach (Project p in mDTE.Solution.Projects) { if (File.Exists(p.FullName)) { projectList.Items.Add(p); } } if (selectedProject == null) { SolutionBuild solutionBuild = mDTE.Solution.SolutionBuild; if ((solutionBuild != null) && (solutionBuild.StartupProjects != null)) { selectedProject = solutionBuild.StartupProjects as Project; } } try { projectList.SelectedItem = mDTE.Solution.Projects.Item(selectedProject); } catch { } ReloadProjectSymbols(); }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void MenuItemCallback(object sender, EventArgs e) { FASTBuildPackage fbPackage = (FASTBuildPackage)this.package; if (null == fbPackage.m_dte.Solution) { return; } MenuCommand eventSender = sender as MenuCommand; fbPackage.m_outputPane.Activate(); fbPackage.m_outputPane.Clear(); if (eventSender == null) { fbPackage.m_outputPane.OutputString("VSIX failed to cast sender to OleMenuCommand.\r"); return; } if (fbPackage.m_dte.Debugger.CurrentMode != dbgDebugMode.dbgDesignMode) { fbPackage.m_outputPane.OutputString("Build not launched due to active debugger.\r"); return; } if (!IsFBuildFindable(fbPackage.OptionFBPath)) { fbPackage.m_outputPane.OutputString(string.Format("Could not find fbuild at the provided path: {0}, please verify in the msfastbuild options.\r", fbPackage.OptionFBPath)); return; } fbPackage.m_dte.ExecuteCommand("File.SaveAll"); string fbCommandLine = ""; string fbWorkingDirectory = ""; Solution sln = fbPackage.m_dte.Solution; SolutionBuild sb = sln.SolutionBuild; SolutionConfiguration2 sc = sb.ActiveConfiguration as SolutionConfiguration2; VCProject proj = null; if (eventSender.CommandID.ID != SlnCommandId && eventSender.CommandID.ID != SlnContextCommandId) { if (fbPackage.m_dte.SelectedItems.Count > 0) { Project envProj = (fbPackage.m_dte.SelectedItems.Item(1).Project as EnvDTE.Project); if (envProj != null) { proj = envProj.Object as VCProject; } } if (proj == null) { string startupProject = ""; foreach (String item in (Array)sb.StartupProjects) { startupProject += item; } proj = sln.Item(startupProject).Object as VCProject; } if (proj == null) { fbPackage.m_outputPane.OutputString("No valid vcproj selected for building or set as the startup project.\r"); return; } fbPackage.m_outputPane.OutputString("Building " + Path.GetFileName(proj.ProjectFile) + " " + sc.Name + " " + sc.PlatformName + "\r"); fbCommandLine = string.Format("-p \"{0}\" -c {1} -f {2} -s \"{3}\" -a\"{4}\" -e \"{5}\"", Path.GetFileName(proj.ProjectFile), sc.Name, sc.PlatformName, sln.FileName, fbPackage.OptionFBArgs, fbPackage.OptionFBPath); fbWorkingDirectory = Path.GetDirectoryName(proj.ProjectFile); } else { fbCommandLine = string.Format("-s \"{0}\" -c {1} -f {2} -a\"{3}\" -e \"{4}\"", sln.FileName, sc.Name, sc.PlatformName, fbPackage.OptionFBArgs, fbPackage.OptionFBPath); fbWorkingDirectory = Path.GetDirectoryName(sln.FileName); } if (fbPackage.OptionBrokerage.Length > 0) { fbCommandLine += " -b " + fbPackage.OptionBrokerage; } if (fbPackage.OptionFBUnity) { fbCommandLine += " -u true"; } string msfastbuildPath = Assembly.GetAssembly(typeof(msfastbuild.msfastbuild)).Location; try { fbPackage.m_outputPane.OutputString("Launching msfastbuild with command line: " + fbCommandLine + "\r"); System.Diagnostics.Process FBProcess = new System.Diagnostics.Process(); FBProcess.StartInfo.FileName = msfastbuildPath; FBProcess.StartInfo.Arguments = fbCommandLine; FBProcess.StartInfo.WorkingDirectory = fbWorkingDirectory; FBProcess.StartInfo.RedirectStandardOutput = true; FBProcess.StartInfo.UseShellExecute = false; FBProcess.StartInfo.CreateNoWindow = true; var SystemEncoding = System.Globalization.CultureInfo.GetCultureInfo(GetSystemDefaultLCID()).TextInfo.OEMCodePage; FBProcess.StartInfo.StandardOutputEncoding = System.Text.Encoding.GetEncoding(SystemEncoding); System.Diagnostics.DataReceivedEventHandler OutputEventHandler = (Sender, Args) => { if (Args.Data != null) { fbPackage.m_outputPane.OutputString(Args.Data + "\r"); } }; FBProcess.OutputDataReceived += OutputEventHandler; FBProcess.Start(); FBProcess.BeginOutputReadLine(); //FBProcess.WaitForExit(); } catch (Exception ex) { fbPackage.m_outputPane.OutputString("VSIX exception launching msfastbuild. Could be a broken VSIX? Exception: " + ex.Message + "\r"); } }
public static void NRL() { try { // Current AutoCAD Document, Database and Editor. Autodesk.AutoCAD.ApplicationServices.Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; // Get running Visual Studio instances (using helper class). IDictionary <string, _DTE> vsInstances = RunningObjectTable.GetRunningVSIDETable(); // Check for no Visual Studio instances. if (vsInstances.Count == 0) { ed.WriteMessage("\nNo running Visual Studio instances were found. *Cancel*"); return; } // Create list of solution names. List <string> solNames = new List <string>(); foreach (KeyValuePair <string, _DTE> item in vsInstances) { solNames.Add(Path.GetFileNameWithoutExtension(item.Value.Solution.FullName)); } // Check if all solution names equal "". // i.e. no solutions loaded in any of the Visual Studio instances. bool allSolNamesEmpty = true; foreach (string name in solNames) { if (name != "") { allSolNamesEmpty = false; break; } } if (allSolNamesEmpty == true) { ed.WriteMessage("\nNo active Visual Studio solutions were found. *Cancel*"); return; } // Prompt user to select solution. PromptKeywordOptions pko = new PromptKeywordOptions("\nSelect Visual Studio instance to increment:"); pko.AllowNone = false; foreach (string name in solNames) { if (name != "") { pko.Keywords.Add(name); } } if (defaultKeyword == "" || solNames.Contains(defaultKeyword) == false) { int index = 0; while (solNames[index] == "") { index++; } pko.Keywords.Default = solNames[index]; } else { pko.Keywords.Default = defaultKeyword; } PromptResult pr = ed.GetKeywords(pko); if (pr.Status != PromptStatus.OK) { return; } defaultKeyword = pr.StringResult; // Use prompt result to set Visual Studio instance variable. _DTE dte = vsInstances.ElementAt(solNames.IndexOf(pr.StringResult)).Value; // Use custom WaitCursor class for long operation. using (WaitCursor wc = new WaitCursor()) { // Active Visual Studio Document. EnvDTE.Document vsDoc = dte.ActiveDocument; if (vsDoc == null) { ed.WriteMessage(String.Format("\nNo active document found for the '{0}' solution. *Cancel*", pr.StringResult)); return; } // Active Visual Studio Project. Project prj = vsDoc.ProjectItem.ContainingProject; // Debug directory - i.e. \bin\Debug. string debugDir = prj.FullName; debugDir = Path.GetDirectoryName(debugDir); debugDir = Path.Combine(debugDir, @"bin\Debug"); // NetReload directory - i.e. \bin\Debug\NetReload. string netReloadDir = Path.Combine(debugDir, "NetReload"); // Create NetReload directory if it doens't exist. if (Directory.Exists(netReloadDir) == false) { Directory.CreateDirectory(netReloadDir); } // Temporary random assembly file name (check it doesn't already exist). string tempAssemblyName; do { tempAssemblyName = Path.GetRandomFileName(); } while (File.Exists(Path.Combine(netReloadDir, tempAssemblyName + ".dll"))); // Project's initial "AssemblyName" property setting. string initAssemblyName = prj.Properties.Item("AssemblyName").Value as string; // Set project's "AssemblyName" property to temp value. prj.Properties.Item("AssemblyName").Value = tempAssemblyName; // Build solution. SolutionBuild solBuild = dte.Solution.SolutionBuild; solBuild.Build(true); // Re-set project's "AssemblyName" property back to initial value. prj.Properties.Item("AssemblyName").Value = initAssemblyName; // Check if build was successful. // # Note: LastBuildInfo property reports number of projects in the solution that failed to build. if (solBuild.LastBuildInfo != 0) { ed.WriteMessage(String.Format("\nBuild failed for the '{0}' solution. *Cancel*", pr.StringResult)); return; } // Move new assembly (.dll) from Debug directory to NetReload directory. File.Move( Path.Combine(debugDir, tempAssemblyName + ".dll"), Path.Combine(netReloadDir, tempAssemblyName + ".dll") ); // Move new .pdb file from Debug directory to NetReload directory. File.Move( Path.Combine(debugDir, tempAssemblyName + ".pdb"), Path.Combine(netReloadDir, tempAssemblyName + ".pdb") ); // NETLOAD new assembly file. System.Reflection.Assembly.LoadFrom(Path.Combine(netReloadDir, tempAssemblyName + ".dll")); // Output summary. ed.WriteMessage("\nNETRELOAD complete for {0}.dll.", initAssemblyName); } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { // Catch AutoCAD exception. Application.ShowAlertDialog(String.Format("ERROR" + "\nMessage: {0}\nErrorStatus: {1}", ex.Message, ex.ErrorStatus)); } catch (System.Exception ex) { // Catch Windows exception. Application.ShowAlertDialog(String.Format("ERROR" + "\nMessage: {0}", ex.Message)); } }
/// <summary> /// Gets the share point projects. /// </summary> /// <param name="isSolutionContext">if set to <c>true</c> [is solution context].</param> /// <param name="requireFarm">if set to <c>true</c> [require farm].</param> /// <returns></returns> public static ISharePointProject[] GetSharePointProjects(bool isSolutionContext, bool requireFarm) { List <EnvDTE.Project> candidateProjects = new List <EnvDTE.Project>(); if (isSolutionContext) { foreach (EnvDTE.Project project in DTEManager.DTE.Solution.Projects) { candidateProjects.Add(project); } } else { foreach (SelectedItem item in DTEManager.DTE.SelectedItems) { if (item.Project != null) { candidateProjects.Add(item.Project); } } } List <ISharePointProject> spProjects = new List <ISharePointProject>(); foreach (EnvDTE.Project project in candidateProjects) { ISharePointProject spProject = DTEManager.ProjectService.Convert <EnvDTE.Project, ISharePointProject>(project); if (spProject != null) { if ((!spProject.IsSandboxedSolution) || (!requireFarm)) { spProjects.Add(spProject); } } } // no SP project selected, check startup projects if (spProjects.Count == 0) { SolutionBuild solutionBuild = DTEManager.DTE.Solution.SolutionBuild; if (solutionBuild != null) { Array startupProj = solutionBuild.StartupProjects as Array; if (startupProj != null) { foreach (String projectName in startupProj) { EnvDTE.Project project = DTEManager.GetProjectByName(projectName); if (project != null) { ISharePointProject spProject = DTEManager.ProjectService.Convert <EnvDTE.Project, ISharePointProject>(project); if (spProject != null) { if ((!spProject.IsSandboxedSolution) || (!requireFarm)) { spProjects.Add(spProject); } } } } } } } return(spProjects.ToArray()); }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void MenuItemCallback(object sender, EventArgs e) { FASTBuildPackage fbPackage = (FASTBuildPackage)this.package; if (null == fbPackage.m_dte.Solution) return; MenuCommand eventSender = sender as MenuCommand; fbPackage.m_outputPane.Activate(); fbPackage.m_outputPane.Clear(); if (eventSender == null) { fbPackage.m_outputPane.OutputString("VSIX failed to cast sender to OleMenuCommand.\r"); return; } if (fbPackage.m_dte.Debugger.CurrentMode != dbgDebugMode.dbgDesignMode) { fbPackage.m_outputPane.OutputString("Build not launched due to active debugger.\r"); return; } if (!IsFBuildFindable(fbPackage.OptionFBPath)) { fbPackage.m_outputPane.OutputString(string.Format("Could not find fbuild at the provided path: {0}, please verify in the msfastbuild options.\r", fbPackage.OptionFBPath)); return; } fbPackage.m_dte.ExecuteCommand("File.SaveAll"); string fbCommandLine = ""; string fbWorkingDirectory = ""; Solution sln = fbPackage.m_dte.Solution; SolutionBuild sb = sln.SolutionBuild; SolutionConfiguration2 sc = sb.ActiveConfiguration as SolutionConfiguration2; VCProject proj = null; if (eventSender.CommandID.ID == ContextCommandId) { if (fbPackage.m_dte.SelectedItems.Count > 0) { Project envProj = (fbPackage.m_dte.SelectedItems.Item(1).Project as EnvDTE.Project); if (envProj != null) { proj = envProj.Object as VCProject; } } if (proj == null) { string startupProject = ""; foreach (String item in (Array)sb.StartupProjects) { startupProject += item; } proj = sln.Item(startupProject).Object as VCProject; } if (proj == null) { fbPackage.m_outputPane.OutputString("No valid vcproj selected for building or set as the startup project.\r"); return; } fbPackage.m_outputPane.OutputString("Building " + Path.GetFileName(proj.ProjectFile) + " " + sc.Name + " " + sc.PlatformName + "\r"); fbCommandLine = string.Format("-p \"{0}\" -c {1} -f {2} -s \"{3}\" -a\"{4}\" -b \"{5}\"", Path.GetFileName(proj.ProjectFile), sc.Name, sc.PlatformName, sln.FileName, fbPackage.OptionFBArgs, fbPackage.OptionFBPath); fbWorkingDirectory = Path.GetDirectoryName(proj.ProjectFile); } else if (eventSender.CommandID.ID == CommandId) { if (fbPackage.m_dte.ActiveDocument == null || fbPackage.m_dte.ActiveDocument.ProjectItem == null || fbPackage.m_dte.ActiveDocument.ProjectItem.ContainingProject == null) { fbPackage.m_outputPane.OutputString("No valid vcproj selected for building.\r"); return; } Project envProj = fbPackage.m_dte.ActiveDocument.ProjectItem.ContainingProject; if (envProj != null) { proj = envProj.Object as VCProject; } if (proj == null) { fbPackage.m_outputPane.OutputString("No valid vcproj selected for building or set as the startup project.\r"); return; } fbPackage.m_outputPane.OutputString("Building " + Path.GetFileName(proj.ProjectFile) + " " + sc.Name + " " + sc.PlatformName + "\r"); fbCommandLine = string.Format("-p \"{0}\" -c {1} -f {2} -s \"{3}\" -a\"{4}\" -b \"{5}\"", Path.GetFileName(proj.ProjectFile), sc.Name, sc.PlatformName, sln.FileName, fbPackage.OptionFBArgs, fbPackage.OptionFBPath); fbWorkingDirectory = Path.GetDirectoryName(proj.ProjectFile); } else if (eventSender.CommandID.ID == SlnCleanCommandId || eventSender.CommandID.ID == SlnContextCleanCommandId) { fbCommandLine = string.Format("-s \"{0}\" -c {1} -f {2} -a\"{3} -clean\" -b \"{4}\"", sln.FileName, sc.Name, sc.PlatformName, fbPackage.OptionFBArgs, fbPackage.OptionFBPath); fbWorkingDirectory = Path.GetDirectoryName(sln.FileName); fbPackage.m_dte.Solution.SolutionBuild.Clean(true); fbPackage.m_outputPane.Activate(); } else if (eventSender.CommandID.ID == SlnCleanBffCommandId) { fbWorkingDirectory = Path.GetDirectoryName(sln.FileName); var files = Directory.EnumerateFiles(fbWorkingDirectory, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".fdb") || s.EndsWith(".bff")); foreach (string file in files) { File.Delete(file); } fbPackage.m_outputPane.OutputString("bff file deleted.\r"); fbPackage.m_outputPane.OutputString("========== 정리: 성공 ==========\r"); Window output_window = fbPackage.m_dte.Windows.Item(EnvDTE.Constants.vsWindowKindOutput); output_window.Activate(); return; } else if (eventSender.CommandID.ID == SlnStopCommandId) { if (FBProcess == null) { return; } if (FBProcess.HasExited) { return; } FBProcess.CancelOutputRead(); FBProcess.Kill(); fbPackage.m_outputPane.OutputString("빌드가 취소되었습니다.\r"); Window output_window = fbPackage.m_dte.Windows.Item(EnvDTE.Constants.vsWindowKindOutput); output_window.Activate(); return; } else { fbCommandLine = string.Format("-s \"{0}\" -c {1} -f {2} -a\"{3}\" -b \"{4}\"", sln.FileName, sc.Name, sc.PlatformName, fbPackage.OptionFBArgs, fbPackage.OptionFBPath); fbWorkingDirectory = Path.GetDirectoryName(sln.FileName); } if (fbPackage.OptionFBUnity) { fbCommandLine += " -u true"; } if (fbPackage.OptionFBUseRelative) { fbCommandLine += " -t true"; } if (fbPackage.OptionFBUseLightCache) { fbCommandLine += " -l true"; } string msfastbuildPath = Assembly.GetAssembly(typeof(msfastbuild.msfastbuild)).Location; try { fbPackage.m_outputPane.OutputString("Launching msfastbuild with command line: " + fbCommandLine + "\r"); FBProcess = new System.Diagnostics.Process(); FBProcess.StartInfo.FileName = msfastbuildPath; FBProcess.StartInfo.Arguments = fbCommandLine; FBProcess.StartInfo.WorkingDirectory = fbWorkingDirectory; FBProcess.StartInfo.RedirectStandardOutput = true; FBProcess.StartInfo.UseShellExecute = false; FBProcess.StartInfo.CreateNoWindow = true; var SystemEncoding = System.Globalization.CultureInfo.GetCultureInfo(GetSystemDefaultLCID()).TextInfo.OEMCodePage; FBProcess.StartInfo.StandardOutputEncoding = System.Text.Encoding.GetEncoding(SystemEncoding); System.Diagnostics.DataReceivedEventHandler OutputEventHandler = (Sender, Args) => { if (Args.Data != null) fbPackage.m_outputPane.OutputString(Args.Data + "\r"); }; FBProcess.OutputDataReceived += OutputEventHandler; FBProcess.Start(); FBProcess.BeginOutputReadLine(); //FBProcess.WaitForExit(); } catch (Exception ex) { fbPackage.m_outputPane.OutputString("VSIX exception launching msfastbuild. Could be a broken VSIX? Exception: " + ex.Message + "\r"); } Window window = fbPackage.m_dte.Windows.Item(EnvDTE.Constants.vsWindowKindOutput); window.Activate(); }
public void Setup() { timerFake = new TimerFake(); solutionBuild = new SolutionBuild(timerFake, new Solution()); }
public static bool TryGetActiveSolutionConfiguration( IServiceProvider serviceProvider, out SolutionBuild solutionBuild, out SolutionConfiguration2 activeConfiguration) { Contract.Requires(serviceProvider != null); Contract.Ensures(Contract.ValueAtReturn(out solutionBuild) != null || !Contract.Result<bool>()); Contract.Ensures(Contract.ValueAtReturn(out activeConfiguration) != null || !Contract.Result<bool>()); solutionBuild = null; activeConfiguration = null; DTE dte = VsServiceProviderHelper.GetService<DTE>(serviceProvider); if (dte == null) return false; var solution = dte.Solution; if (solution == null) return false; solutionBuild = solution.SolutionBuild; Contract.Assume(solutionBuild != null); activeConfiguration = solutionBuild.ActiveConfiguration as SolutionConfiguration2; return solutionBuild != null && activeConfiguration != null; }
private void UpdateAndPublishSingle(CrmServiceClient client, Project project) { try { _dte.StatusBar.Text = "Deploying assembly..."; _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy); string outputFileName = project.Properties.Item("OutputFileName").Value.ToString(); string path = GetOutputPath(project) + outputFileName; //Build the project SolutionBuild solutionBuild = _dte.Solution.SolutionBuild; solutionBuild.BuildProject(_dte.Solution.SolutionBuild.ActiveConfiguration.Name, project.UniqueName, true); if (solutionBuild.LastBuildInfo > 0) { return; } //Make sure Major and Minor versions match Version assemblyVersion = Version.Parse(project.Properties.Item("AssemblyVersion").Value.ToString()); if (SelectedAssemblyItem.Item.Version.Major != assemblyVersion.Major || SelectedAssemblyItem.Item.Version.Minor != assemblyVersion.Minor) { _logger.WriteToOutputWindow("Error Updating Assembly In CRM: Changes To Major & Minor Versions Require Redeployment", Logger.MessageType.Error); return; } //Make sure assembly names match string assemblyName = project.Properties.Item("AssemblyName").Value.ToString(); if (assemblyName.ToUpper() != SelectedAssemblyItem.Item.Name.ToUpper()) { _logger.WriteToOutputWindow("Error Updating Assembly In CRM: Changes To Assembly Name Require Redeployment", Logger.MessageType.Error); return; } //Update CRM Entity crmAssembly = new Entity("pluginassembly") { Id = SelectedAssemblyItem.Item.AssemblyId }; crmAssembly["content"] = Convert.ToBase64String(File.ReadAllBytes(path)); client.OrganizationServiceProxy.Update(crmAssembly); //Update assembly name and version numbers SelectedAssemblyItem.Item.Version = assemblyVersion; SelectedAssemblyItem.Item.Name = project.Properties.Item("AssemblyName").Value.ToString(); SelectedAssemblyItem.Item.DisplayName = SelectedAssemblyItem.Item.Name + " (" + assemblyVersion + ")"; SelectedAssemblyItem.Item.DisplayName += (SelectedAssemblyItem.Item.IsWorkflowActivity) ? " [Workflow]" : " [Plug-in]"; } catch (FaultException <OrganizationServiceFault> crmEx) { _logger.WriteToOutputWindow("Error Deploying Report To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error); } catch (Exception ex) { _logger.WriteToOutputWindow("Error Deploying Report To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error); } _dte.StatusBar.Clear(); _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); }
private bool UpdateCrmAssembly(AssemblyItem assemblyItem, CrmServiceClient connection) { _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy); try { string outputFileName = ConnPane.SelectedProject.Properties.Item("OutputFileName").Value.ToString(); string path = GetOutputPath() + outputFileName; //Build the project SolutionBuild solutionBuild = _dte.Solution.SolutionBuild; solutionBuild.BuildProject(_dte.Solution.SolutionBuild.ActiveConfiguration.Name, ConnPane.SelectedProject.UniqueName, true); if (solutionBuild.LastBuildInfo > 0) { return(false); } //Make sure Major and Minor versions match Version assemblyVersion = Version.Parse(ConnPane.SelectedProject.Properties.Item("AssemblyVersion").Value.ToString()); if (assemblyItem.Version.Major != assemblyVersion.Major || assemblyItem.Version.Minor != assemblyVersion.Minor) { _logger.WriteToOutputWindow("Error Updating Assembly In CRM: Changes To Major & Minor Versions Require Redeployment", Logger.MessageType.Error); return(false); } //Make sure assembly names match string assemblyName = ConnPane.SelectedProject.Properties.Item("AssemblyName").Value.ToString(); if (assemblyName.ToUpper() != assemblyItem.Name.ToUpper()) { _logger.WriteToOutputWindow("Error Updating Assembly In CRM: Changes To Assembly Name Require Redeployment", Logger.MessageType.Error); return(false); } //Update CRM using (OrganizationService orgService = new OrganizationService(connection)) { Entity crmAssembly = new Entity("pluginassembly") { Id = assemblyItem.AssemblyId }; crmAssembly["content"] = Convert.ToBase64String(File.ReadAllBytes(path)); orgService.Update(crmAssembly); } //Update assembly name and version numbers assemblyItem.Version = assemblyVersion; assemblyItem.Name = ConnPane.SelectedProject.Properties.Item("AssemblyName").Value.ToString(); assemblyItem.DisplayName = assemblyItem.Name + " (" + assemblyVersion + ")"; assemblyItem.DisplayName += (assemblyItem.IsWorkflowActivity) ? " [Workflow]" : " [Plug-in]"; return(true); } catch (FaultException <OrganizationServiceFault> crmEx) { _logger.WriteToOutputWindow("Error Updating Assembly In CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error); return(false); } catch (Exception ex) { _logger.WriteToOutputWindow("Error Updating Assembly In CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error); return(false); } finally { _dte.StatusBar.Clear(); _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); } }