public static bool TryGetPropertyByName(EnvDTE.Properties properties, string propertyName, out Property result) { result = null; if (properties != null) { var list = properties.OfType <Property>().ToList(); //var temp = list.Select(e => new { e.Name }).ToList(); foreach (Property item in list) { if (item != null && string.Equals(item.Name, propertyName, StringComparison.InvariantCultureIgnoreCase)) { result = item; return(true); } } } return(false); }
public static string GetCommandArgs() { EnvDTE.Properties props = IDEUtils.GetDtePropertiesFromHierarchy(); if (props == null) { return(DockableCLArgs.Resources.StartupMessage); } string commandArgs = string.Empty; switch (lang) { case ProjLang.CPP: commandArgs = IDEUtils.GetProperty(props, "CommandArguments") as string ?? string.Empty; break; case ProjLang.CS: commandArgs = IDEUtils.GetProperty(props, "StartArguments") as string ?? string.Empty; break; } return(commandArgs); }
private void UpdateProjectConfigurationsToUseRuleSetFile(EnvDTE.Project envDteProject, string fileName) { foreach (EnvDTE.Configuration config in envDteProject.ConfigurationManager) { EnvDTE.Properties properties = config.Properties; try { EnvDTE.Property codeAnalysisRuleSetFileProperty = properties?.Item("CodeAnalysisRuleSet"); if (codeAnalysisRuleSetFileProperty != null) { codeAnalysisRuleSetFileProperty.Value = fileName; } } catch (ArgumentException) { // Unfortunately the properties collection sometimes throws an ArgumentException // instead of returning null if the current configuration doesn't support CodeAnalysisRuleSet. // Ignore it and move on. } } }
private void AddKeyFileToProject(Project project) { // Save the key to a file. if (keyBuffer != null) { try { string destinationDirectory = Path.GetDirectoryName(project.FullName); string keySavePath = Path.Combine(destinationDirectory, KEY_FILENAME); File.WriteAllBytes(keySavePath, keyBuffer); project.ProjectItems.AddFromFile(keySavePath); // Add properties in the project to use the key for signing. EnvDTE.Properties projProps = project.Properties; projProps.Item("SignAssembly").Value = true; projProps.Item("AssemblyOriginatorKeyFile").Value = KEY_FILENAME; } catch (Exception e) { throw new Exception("Cannot add the strong name key to the project. " + e.Message, e); } } }
public static bool SetProperty(EnvDTE.Properties properties, string name, object value) { if (properties == null || string.IsNullOrEmpty(name)) { return(false); } try { EnvDTE.Property property = properties.Cast <EnvDTE.Property>().FirstOrDefault(p => p.Name == name); if (property == null) { return(false); } property.Value = value; return(true); } catch (InvalidCastException) { return(false); } }
public static object[] GetProperties(EnvDTE.Properties properties, params string[] names) { var values = new object[names.Length]; foreach (object p in properties) { try { if (p is Property property) { for (int i = 0; i < names.Length; i++) { if (names[i] == property.Name) { values[i] = property.Value; break; } } } } catch { continue; } } return(values); }
///////////////////////////////////////////////////////////////////////////// // Overriden Package Implementation #region Package Members /// <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 initilaization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString())); base.Initialize(); // Add our command handlers for menu (commands must exist in the .vsct file) OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (null != mcs) { // Create the command for the menu item. CommandID menuCommandID = new CommandID(GuidList.guidClangFormatCmdSet, (int)PkgCmdIDList.ClangFormatCommand); MenuCommand menuItem = new MenuCommand(MenuItemCallback, menuCommandID); mcs.AddCommand(menuItem); } DTE env = (DTE)GetService(typeof(DTE)); EnvDTE.Properties props = env.get_Properties("LLVM", "clang-format"); owp = CreatePane("clang-format"); cf = new ClangFormat(owp, props); }
/// <summary> /// Called when the Visual Studio IDE goes idle to give /// the component a chance to perform idle time tasks. /// </summary> /// <remarks> /// The component may periodically call FContinueIdle and, if it returns /// false, the component should terminate its idle time processing and return. /// If a component reaches a point where it has no idle tasks and does not need /// FDoIdle calls, it should remove its idle task registration via /// FUpdateComponentRegistration. If this method is called while the component /// is performing a tracking operation, the component should only perform idle time /// tasks that it deems appropriate to perform during tracking. /// </remarks> public void OnIdle() { if (Dte == null || _codeCache == null) { // Initialize is in progress. // return; } var tickCount = (uint)Environment.TickCount; if (tickCount < _lastTickCount) { // The tick count rolled over, so treat this as if the timeout has expired // to keep from waiting until the count gets up to the required value again. } else { // Check to see when the last occurrence was. Only search once per second. if ((tickCount - _lastTickCount) < _delayBetweenIdleProcessing) { return; } } try { if (_codeCache.CurrentFileManager != null) { CodeOutlineFileManager.OutlineFileManagerState state = _codeCache.CurrentFileManager.State; switch (state) { case CodeOutlineFileManager.OutlineFileManagerState.Failed: _control.ShowException(_codeCache.CurrentFileManager.ParseException); _control.Enabled = true; return; case CodeOutlineFileManager.OutlineFileManagerState.StartLoadingCodeModel: // Load completely anew. _control.ShowWaitWhileReadyMessage(); _codeCache.CurrentFileManager.Load(); return; case CodeOutlineFileManager.OutlineFileManagerState.LoadingCodeModel: // Continue loading after an interruption. _codeCache.CurrentFileManager.ContinueLoading(); return; case CodeOutlineFileManager.OutlineFileManagerState.DoneLoadingCodeModel: // Loading is complete. _codeCache.CurrentFileManager.FinishLoading(); _codeCache.CurrentFileManager.TreeView.Refresh(); _codeCache.CurrentFileManager.FilterView.Refresh(); _control.Enabled = _codeCache.CurrentFileManager.FileIsOutlined; if (_control.Enabled) { var selectedType = (CodeElementType)Enum.Parse(typeof(CodeElementType), _control.filterToolStripCombo.SelectedItem.ToString()); _codeCache.CurrentFileManager.ElementFilter = selectedType; } _control.HideWaitWhileReadyMessage(); _control.Reset(); _codeCache.CurrentFileManager.State = CodeOutlineFileManager.OutlineFileManagerState.WaitToStartOver; return; case CodeOutlineFileManager.OutlineFileManagerState.WaitToStartOver: break; } } // Get the current active TextPoint from the DTE. if (!_control.Enabled || Dte.ActiveDocument == null || _codeCache.CurrentFileManager == null || _codeCache.CurrentFileManager.TreeViewFocused) { return; } var sel = (TextSelection)Dte.ActiveDocument.Selection; if (sel == null) { return; } TextPoint tp = sel.ActivePoint; if ((tp.Line == _lineNum) && (tp.LineCharOffset == _colNum)) { if (!_codeElementSelectedOnIdle && ((tickCount - _lastTickCountBeforeUpdate) > _delayBetweenCodeElementSelection)) { _codeElementSelectedOnIdle = true; // Turn off pretty listing to fix the problem with line autocompletion // being invoked when the code element position is determined. EnvDTE.Properties properties = Dte.get_Properties("TextEditor", "Basic-Specific"); Property property = null; foreach (Property p in properties) { if (p.Name == "PrettyListing") { property = p; break; } } bool currentPrettyListing = true; if (property != null) { currentPrettyListing = (bool)property.Value; property.Value = false; } _codeCache.CurrentFileManager.SelectCodeElement(tp); // Set pretty listing back to its previous value. if (property != null) { property.Value = currentPrettyListing; } _lastTickCountBeforeUpdate = tickCount; } } else { _codeElementSelectedOnIdle = false; } _lineNum = tp.Line; _colNum = tp.LineCharOffset; } catch (Exception ex) { //exceptions from time to time occur in Nemerle parser if (_codeCache.CurrentFileManager != null) { _codeCache.CurrentFileManager.OnException(ex); } //Utils.DisplayMessage(Resources.ErrorPrefix, "FDoIdle exception: " + ex.ToString()); } _lastTickCount = tickCount; }
/// <summary> /// The event explorer user control constructor. /// </summary> public RdtEventControl() { InitializeComponent(); // Create a selection container for tracking selected RDT events. selectionContainer = new MsVsShell.SelectionContainer(); // Advise the RDT of this event sink. IOleServiceProvider sp = Package.GetGlobalService(typeof(IOleServiceProvider)) as IOleServiceProvider; if (sp == null) { return; } rdt = new RunningDocumentTable(new ServiceProvider(sp)); if (rdt == null) { return; } rdtCookie = rdt.Advise(this); // Obtain the single instance of the options via automation. try { DTE dte = (DTE)Package.GetGlobalService(typeof(DTE)); EnvDTE.Properties props = dte.get_Properties("RDT Event Explorer", "Explorer Options"); IOptions o = props.Item("ContainedOptions").Object as IOptions; options = (Options)o; } catch { IVsActivityLog log = Package.GetGlobalService( typeof(SVsActivityLog)) as IVsActivityLog; if (log != null) { log.LogEntry( (UInt32)__ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION, this.ToString(), string.Format(CultureInfo.CurrentCulture, "RdtEventExplorer could not obtain properties via automation: {0}", this.ToString()) ); } options = new Options(); } // Prepare the event grid. eventGrid.AutoGenerateColumns = false; eventGrid.AllowUserToAddRows = false; eventGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect; eventGrid.Columns.Add("Event", Resources.EventHeader); eventGrid.Columns.Add("Moniker", Resources.MonikerHeader); eventGrid.Columns["Event"].ReadOnly = true; eventGrid.Columns["Moniker"].ReadOnly = true; eventGrid.AllowUserToResizeRows = false; eventGrid.AllowUserToResizeColumns = true; eventGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; int x = Screen.PrimaryScreen.Bounds.Size.Width; int y = Screen.PrimaryScreen.Bounds.Size.Height; Size = new Size(x / 3, y / 3); }
public void TestAutomationOnProjectItem() { UIThreadInvoker.Invoke((ThreadInvoker) delegate() { //Get the global service provider and the dte IServiceProvider sp = VsIdeTestHostContext.ServiceProvider; DTE dte = (DTE)sp.GetService(typeof(DTE)); string destination = Path.Combine(TestContext.TestDir, TestContext.TestName); Utilities.CreateMyNestedProject(sp, dte, TestContext.TestName, destination, true); OAProject automation = Utilities.FindExtObject(sp, Utilities.NestedProjectGuid, TestContext.TestName) as OAProject; Assert.IsNotNull(automation, "Failed to create a project using automation"); ProjectNode project = automation.Project; // Get the AssemblyInfo.cs, try to open it and then ask using automation that it is opened. EnvDTE.ProjectItem item = automation.ProjectItems.Item("AssemblyInfo.cs"); Assert.IsNotNull(item, "Could not retrieve AssemblyInfo.cs"); EnvDTE.Window window = item.Open(VSConstants.LOGVIEWID_Primary.ToString()); Assert.IsNotNull(window, "Could not open the AssemblyInfo.cs"); window.Activate(); bool isOpen = item.get_IsOpen(VSConstants.LOGVIEWID_Primary.ToString()); Assert.IsTrue(isOpen, "The AssemblyInfo.cs file should have been opened"); // Now save it item.Save(""); Assert.IsTrue(item.Saved, "The renamed AssemblyInfo.cs has not been saved"); // Get the Document EnvDTE.Document document = item.Document; Assert.IsNotNull(document, "Could not retrieve the document object"); Assert.IsTrue(document.Name == "AssemblyInfo.cs", "The document for the file item is incorrect. It's name should be AssemblyInfo.cs"); // Try the properties on a nested item EnvDTE.ProjectItem nestedProject = automation.ProjectItems.Item("ANestedProject"); EnvDTE.ProjectItem nestedProjectItem = nestedProject.ProjectItems.Item("Program.cs"); EnvDTE.Properties nesteditemsProps = nestedProjectItem.Properties; EnvDTE.Property nestedItemProperty = nesteditemsProps.Item("BuildAction"); Assert.IsNotNull(nestedItemProperty, "Could not retrieve the BuildAction property from the nested project item"); nestedItemProperty.Value = BuildAction.Content; Assert.AreEqual((BuildAction)nestedItemProperty.Value, BuildAction.Content); // Now try the properties on the top project item EnvDTE.Properties props = item.Properties; Assert.IsNotNull(props, "Could not retrieve the BuildAction property from the nested project item"); EnvDTE.Property itemProperty = props.Item("BuildAction"); Assert.IsNotNull(itemProperty, "Could not retrieve the BuildAction property from the nested project item"); Assert.IsFalse(itemProperty is OANullProperty, "Could not retrieve the BuildAction property from the nested project item"); itemProperty.Value = BuildAction.Content; Assert.AreEqual(itemProperty.Value, BuildAction.Content); // Now save as Assert.IsTrue(item.SaveAs("AssemblyInfo1.cs"), "The file AssemblyInfo.cs could not be reanmed to AssemblyInfo1.cs"); Assert.IsTrue(item.Name == "AssemblyInfo1.cs", "File item has been renamed to AssemblyInfo1.cs but the Name property has not"); // Now try the Program.cs. That should not be opened EnvDTE.ProjectItem item1 = automation.ProjectItems.Item("Program.cs"); Assert.IsNotNull(item1, "Could not retrieve AssemblyInfo.cs"); isOpen = item1.get_IsOpen(VSConstants.LOGVIEWID_Primary.ToString()); Assert.IsFalse(isOpen, "The Program.cs should not have been opened"); // Now get the Reference folder as a project item and expand it. EnvDTE.ProjectItem references = automation.ProjectItems.Item("References"); references.ExpandView(); // Check that actually it was expanded. IVsUIHierarchyWindow uiHierarchy = VsShellUtilities.GetUIHierarchyWindow(project.Site, HierarchyNode.SolutionExplorer); System.Reflection.MethodInfo mi = typeof(ProjectNode).GetMethod("FindChild", BindingFlags.NonPublic | BindingFlags.Instance); ReferenceContainerNode containerNode = (ReferenceContainerNode)mi.Invoke(project, new object[] { "References" }); __VSHIERARCHYITEMSTATE state; uint stateAsInt; uiHierarchy.GetItemState(project, (uint)containerNode.ID, (uint)__VSHIERARCHYITEMSTATE.HIS_Expanded, out stateAsInt); state = (__VSHIERARCHYITEMSTATE)stateAsInt; Assert.IsTrue(state == __VSHIERARCHYITEMSTATE.HIS_Expanded, "The References folder has not been expanded"); }); }
public void TestInterfaceMethodsOnProperty() { UIThreadInvoker.Invoke((ThreadInvoker) delegate() { //Get the global service provider and the dte IServiceProvider sp = VsIdeTestHostContext.ServiceProvider; DTE dte = (DTE)sp.GetService(typeof(DTE)); string destination = Path.Combine(TestContext.TestDir, TestContext.TestName); Utilities.CreateMyNestedProject(sp, dte, TestContext.TestName, destination, true); OAProject automation = Utilities.FindExtObject(sp, Utilities.NestedProjectGuid, TestContext.TestName) as OAProject; Assert.IsNotNull(automation, "Failed to create a project using automation"); ProjectNode projectNode = automation.Project; // Get Project Property object EnvDTE.Property property = automation.Properties.Item("RootNamespace"); Assert.IsNotNull(property, "Could not retrieve valid RootNamespace property"); Assert.IsFalse(property is OANullProperty, "Could not retrieve valid RootNamespace property"); object retValue = property.Application; Assert.IsNull(retValue); Assert.IsTrue((string)property.Value == "Application", "Failed to retrieve the Value property."); property.Value = "Test1"; Assert.AreEqual(property.Value, "Test1"); // Get Collection object from property object EnvDTE.Properties properties = property.Collection; Assert.IsNotNull(properties, "Collection property failed to retrieve an object"); // Get the DTE retValue = property.DTE; Assert.IsNotNull(retValue); // Get the Indexed value retValue = property.get_IndexedValue(1, 2, 3, 4); Assert.IsNull(retValue); property.let_Value(1); Assert.AreEqual(property.Value, "1"); // Check the name. string name = property.Name; Assert.IsNotNull(name); Assert.IsTrue(name == "RootNamespace", "RootNamespace property was not set correctly"); short numIndeces = property.NumIndices; //Currently it gives back 0 //It must be Assertd when the method changes Assert.IsTrue(numIndeces == 0); // Assert the Object property retValue = property.Object; Assert.AreEqual(retValue, property.Value); property.Object = "test1"; retValue = property.Object; Assert.AreEqual(retValue, "test1"); // Test the parent property EnvDTE.Properties parent = property.Parent; Assert.IsTrue(parent is OAProperties, "Parent property failed to return the parent of a property"); //It does nothing currently. Cannot be Assertd. property.set_IndexedValue(1, 2, 3, 4, 5); // Try a non string value on the Value. ArrayList list = new ArrayList(); property.Value = list; retValue = property.Value; Assert.AreEqual(retValue, list.ToString()); // Test the iterators for enumeration. // We are interested to see that we advance with the iteration. bool[] found = new bool[2]; foreach (EnvDTE.Property aProperty in automation.Properties) { if (aProperty.Name == "RootNamespace") { found[0] = true; } else if (aProperty.Name == "AssemblyName") { found[1] = true; } } foreach (bool foundValue in found) { Assert.IsTrue(foundValue, "The iterator on property collection has not been implemented correctly"); } }); }
public static FontsAndColorsItems GetTextEditorFontAndColorsItems(DTE2 dte) { EnvDTE.Properties props = dte.get_Properties("FontsAndColors", "TextEditor"); return(props.Item("FontsAndColorsItems").Object as FontsAndColorsItems); }
public void ProjectFinishedGenerating(Project project) { if (_selectedTypes != null) { string _validationErrors = string.Empty; string _itemPath = null; string _fileExtension = null; EnvDTE80.Events2 _objEvents2; EnvDTE80.Solution2 _solution = project.DTE.Solution as EnvDTE80.Solution2; OutputWindowManager outPutWindowmng = new OutputWindowManager(); // Subscribe all the IDE events _envDTE = project.DTE; _objEvents2 = ((EnvDTE80.Events2)(_envDTE.Events)); // Write the post-build command to register the assembly. if (VSOptionsValidator.CanCreatePostBuildEvent(ref _validationErrors)) { // Add command-line parameters. string command = $"copy /Y \"$(TargetPath)\" \"{WebApiOptions.Instance.Path}\\$(ProjectName).dll\""; EnvDTE.Properties configmg = project.Properties; configmg.Item("PostBuildEvent").Value = command; outPutWindowmng.WriteMessage("The post-build command was added to the project.", OutputWindowMessagesType.Message); } else { outPutWindowmng.WriteMessage("The post-build event has not been configured because of the following validation issues:", OutputWindowMessagesType.Warning); outPutWindowmng.WriteMessage(_validationErrors, OutputWindowMessagesType.Message); outPutWindowmng.WriteMessage("Check this on Tools | Options | PRIMAVERA Extensibility.", OutputWindowMessagesType.Message); } if (project.Kind == PrjKind.prjKindCSharpProject) { _itemPath = _solution.GetProjectItemTemplate("PriWebApiControler.zip", "CSharp"); _fileExtension = ".cs"; } else { _itemPath = _solution.GetProjectItemTemplate("PriWebApiControler.zip", "VisualBasic"); _fileExtension = ".vb"; } // Add folder to keep all controllers. ProjectItem rootFolder = project.ProjectItems.AddFolder("Controllers"); // Add the class to the project. rootFolder.ProjectItems.AddFromTemplate(_itemPath, _controllerName + _fileExtension); // Add generic references //WizardHelper.AddApiBaseDependencies(project); WizardHelper.AddBaseReferences(project, "Bas", GeneralOptions.Instance.Path); WizardHelper.AddBaseReferences(project, "Api", WebApiOptions.Instance.Path); // Add references to the select modules foreach (TreeNode type in _selectedTypes) { if (!String.IsNullOrEmpty(_itemPath)) { // Add dependencies to the select modules. WizardHelper.AddDependenciesReference(project, type.Text); } } outPutWindowmng.WriteMessage("The project was created with success."); } }
private void SetDTEProperty(string category, string page, string item, object value) { EnvDTE.Properties props = appobj_.get_Properties(category, page); EnvDTE.Property prop = props.Item(item); prop.Value = value; }
/// <summary> /// Gets default namespace from properties (obtained from a Project or ProjectItem). /// </summary> /// <param name="properties">Properties from where to get the Default Namespace.</param> /// <returns></returns> public static string GetDefaultNamespaceFromProperties(EnvDTE.Properties properties) { return(properties.Item(Resources.Properties_DefaultNamespace).Value.ToString()); }
private bool HasProperties(EnvDTE.Properties properties, params string[] names) { return(properties.Count > 0 && names.Any(n => HasProperty(properties, n))); }
public void ProjectFinishedGenerating(Project project) { if (selectedTypes != null) { string validationErrors = string.Empty; string itemPath = null; string fileExtension = null; EnvDTE80.Events2 objEvents2; EnvDTE80.Solution2 solution = project.DTE.Solution as EnvDTE80.Solution2; OutputWindowManager outPutWindowmng = new OutputWindowManager(); // Subscribe all the IDE events envDTE = project.DTE; objEvents2 = ((EnvDTE80.Events2)(envDTE.Events)); // Subscribe the item added event projectItemsEvents = objEvents2.ProjectItemsEvents; projectItemsEvents.ItemAdded += ProjectItemsEvents_ItemAdded; // Write the post-build command to register the assembly. if (VSOptionsValidator.CanCreatePostBuildEvent(ref validationErrors)) { // Build the command to call. string erpPath = Path.Combine(GeneralOptions.Instance.Path, "RegisterExtension.exe"); if (File.Exists(erpPath)) { // Add command-line parameters. string command = $"Call {string.Format("\"{0}\"", erpPath)} " + $" {GeneralOptions.Instance.Company} {GeneralOptions.Instance.UserName}" + $" {GeneralOptions.Instance.Password} {GeneralOptions.Instance.ProductLine}" + $" $(TargetPath) {GeneralOptions.Instance.CommonExtension}"; EnvDTE.Properties configmg = project.Properties; configmg.Item("PostBuildEvent").Value = command; outPutWindowmng.WriteMessage("The post-build command was added to the project.", OutputWindowMessagesType.Message); // Set start external program string erpEpp = string.Format("Erp100L{0}.exe", GeneralOptions.Instance.ProductLine == 0 ? "E" : "P"); Configuration activeConfig = project.ConfigurationManager.ActiveConfiguration; activeConfig.Properties.Item("StartAction").Value = prjStartAction.prjStartActionProgram; activeConfig.Properties.Item("StartProgram").Value = Path.Combine(GeneralOptions.Instance.Path, erpEpp); outPutWindowmng.WriteMessage("The start external program was set.", OutputWindowMessagesType.Message); } else { StringBuilder msg = new StringBuilder(); msg.Append("The post-build command could not be registered. \n"); msg.Append("The command line utility does not exist on the folder."); msg.Append(GeneralOptions.Instance.Path); msg.Append("Download it from https://developers.primaverabss.com/v10/como-automatizar-registo-extensoes/ \n"); outPutWindowmng.WriteMessage(msg.ToString(), OutputWindowMessagesType.Error); } } else { outPutWindowmng.WriteMessage("The post-build event has not been configured because of the following validation issues:", OutputWindowMessagesType.Warning); outPutWindowmng.WriteMessage(validationErrors, OutputWindowMessagesType.Message); outPutWindowmng.WriteMessage("Check this on Tools | Options | PRIMAVERA Extensibility.", OutputWindowMessagesType.Message); } if (project.Kind == PrjKind.prjKindCSharpProject) { itemPath = solution.GetProjectItemTemplate("PriClass.zip", "CSharp"); fileExtension = ".cs"; } else { itemPath = solution.GetProjectItemTemplate("PriClass.zip", "VisualBasic"); fileExtension = ".vb"; } if (!String.IsNullOrEmpty(itemPath)) { // Add generic references WizardHelper.AddBaseReferences(project, "Bas", GeneralOptions.Instance.Path); WizardHelper.AddBaseReferences(project, "Ext", GeneralOptions.Instance.Path); foreach (MyTreeNode type in selectedTypes) { this.SelectedNode = type; ProjectItem rootFolder = project.ProjectItems.Cast <ProjectItem>() .FirstOrDefault(i => i.Name == type.Module) ?? project.ProjectItems.AddFolder(type.Module); // Add the module reference. WizardHelper.AddModuleReference(project, "Primavera.Extensibility." + type.Module); // Add dependencies to the select modules. WizardHelper.AddDependenciesReference(project, type.Module); switch (type.ModuleType) { case "Editors": rootFolder.ProjectItems.AddFromTemplate(itemPath, "Ui" + type.ClassName + fileExtension); break; case "Services": rootFolder.ProjectItems.AddFromTemplate(itemPath, "Api" + type.ClassName + fileExtension); break; } } } outPutWindowmng.WriteMessage("The project was created with success."); // UnSubscribing event. projectItemsEvents.ItemAdded -= ProjectItemsEvents_ItemAdded; } }
/// <summary> /// Generates the specified Source File in the received Project with the options /// provided and gets the Namespace ready to add code in it. /// </summary> /// <param name="targetProject">Project where the Source File is going to be placed.</param> /// <param name="targetProjectFolder">Project folder where the source file is going to be placed. /// Null indicates to place the source file as child of targetProject.</param> /// <param name="sourceFileName">Source File name to use.</param> /// <param name="sourceFileHeaderComment">Source File Header Comment (optional).</param> /// <param name="sourceNamespace">Namespace used in the Source File.</param> /// <param name="isServiceReady">Specifies if it is Service-Ready (serialization is going to be used).</param> /// <param name="sourceFileItem">(out parameter) Source File ProjectItem.</param> /// <returns></returns> public static CodeNamespace GenerateSourceAndGetNamespace(Project targetProject, ProjectItem targetProjectFolder, string sourceFileName, string sourceFileHeaderComment, string sourceNamespace, bool isServiceReady, out ProjectItem sourceFileItem) { // Validate source file name if (sourceFileName.EndsWith(Resources.CSharpFileExtension) == false) { sourceFileName += Resources.CSharpFileExtension; } // Validate source file header comment if (string.IsNullOrWhiteSpace(sourceFileHeaderComment) == false) { if (sourceFileHeaderComment.IndexOf("*/") >= 0) { throw new ApplicationException(Resources.Error_HeaderCommentInvalidChars); } } // ProjectItems collection where to place the source file ProjectItems projectItems = targetProject.ProjectItems; if (targetProjectFolder != null) { // Place inside received project folder projectItems = targetProjectFolder.ProjectItems; } // Properties collection of the target EnvDTE.Properties targetProperties = targetProject.Properties; if (targetProjectFolder != null) { targetProperties = targetProjectFolder.Properties; } // Source file sourceFileItem = null; #region If source file exists in the target, clear it and get the reference foreach (ProjectItem projItem in projectItems) { string projItemFileName = projItem.Properties.Item(Resources.ProjectItem_FileName).Value.ToString(); if (sourceFileName.ToLower() == projItemFileName.ToLower()) { // Source file already exists sourceFileItem = projItem; if (sourceFileItem.FileCodeModel.CodeElements != null && sourceFileItem.FileCodeModel.CodeElements.Count > 0) { // Clear source file CodeElement firstElement = sourceFileItem.FileCodeModel.CodeElements.Item(1); CodeElement lastElement = sourceFileItem.FileCodeModel.CodeElements.Item( sourceFileItem.FileCodeModel.CodeElements.Count); EditPoint startPoint = firstElement.StartPoint.CreateEditPoint(); EditPoint endPoint = lastElement.EndPoint.CreateEditPoint(); while (startPoint.AtStartOfDocument != true) { startPoint.LineUp(); } while (endPoint.AtEndOfDocument != true) { endPoint.LineDown(); } startPoint.Delete(endPoint); } break; } } #endregion #region If source file NOT exists in the target, create it and get the reference if (sourceFileItem == null) { // New source file, get target path string targetPath = targetProperties.Item(Resources.Properties_LocalPath).Value.ToString(); // Check if the new source file already exists in the file system (and it is not added to the solution) if (File.Exists(targetPath + sourceFileName)) { // Rename the existent source file string backupSourceFileName = (sourceFileName + Resources.BackupFileExtension); File.Move((targetPath + sourceFileName), (targetPath + backupSourceFileName)); // Add warning VisualStudioHelper.AddToErrorList(TaskErrorCategory.Warning, string.Format(Resources.Warning_SourceFileAlreadyExists, sourceFileName, backupSourceFileName), targetProject, sourceFileName, null, null); } // Add source file to target sourceFileItem = projectItems.AddFromTemplate(TemplateClass.FilePath, sourceFileName); } #endregion #region Generate imports var importList = new List <SourceCodeImport>(); importList.Add(new SourceCodeImport(Resources.NamespaceSystem)); importList.Add(new SourceCodeImport(Resources.NamespaceSystemCollectionsGeneric)); importList.Add(new SourceCodeImport(Resources.NamespaceSystemText)); if (isServiceReady) { importList.Add(new SourceCodeImport(Resources.NamespaceSystemRuntimeSerialization)); } importList = importList.OrderBy(d => d.ImportNamespace).ToList(); #endregion Generate imports // Add imports to the source code VisualStudioHelper.AddImportsToSourceCode(ref sourceFileItem, importList); // Get Source file code start EditPoint objEditPoint = sourceFileItem.FileCodeModel.CodeElements.Item(1).StartPoint.CreateEditPoint(); objEditPoint.StartOfDocument(); // Add header comment if (string.IsNullOrWhiteSpace(sourceFileHeaderComment) == false) { sourceFileHeaderComment = (Environment.NewLine + sourceFileHeaderComment + Environment.NewLine); objEditPoint.Insert( string.Format(Resources.CSharpCommentMultiline, sourceFileHeaderComment) + Environment.NewLine); } // Add EntitiesToDTOs signature string timestamp = DateTime.Now.ToString("yyyy/MM/dd - HH:mm:ss"); objEditPoint.Insert(string.Format(Resources.EntitiesToDTOsSignature, AssemblyHelper.Version, timestamp)); objEditPoint.Insert(Environment.NewLine); // Add blank line before source file namespace objEditPoint.EndOfDocument(); objEditPoint.Insert(Environment.NewLine); // Add namespace CodeNamespace objNamespace = sourceFileItem.FileCodeModel .AddNamespace(sourceNamespace, AppConstants.PLACE_AT_THE_END); return(objNamespace); }