void InstallControl() { // Create an instance of the VS IDE, Type type = System.Type.GetTypeFromProgID("VisualStudio.DTE.10.0"); DTE dte = (DTE)System.Activator.CreateInstance(type, true); // create a temporary winform project; string tmpFile = Path.GetFileNameWithoutExtension(Path.GetTempFileName()); string tmpDir = string.Format("{0}{1}", Path.GetTempPath(), tmpFile); Solution2 solution = dte.Solution as Solution2; string templatePath = solution.GetProjectTemplate("WindowsApplication.zip", "CSharp"); Project proj = solution.AddFromTemplate(templatePath, tmpDir, "dummyproj", false); // add the control to the toolbox. EnvDTE.Window window = dte.Windows.Item(EnvDTE.Constants.vsWindowKindToolbox); EnvDTE.ToolBox toolbox = (EnvDTE.ToolBox)window.Object; EnvDTE.ToolBoxTab myTab = toolbox.ToolBoxTabs.Add("Saino"); myTab.Activate(); myTab.ToolBoxItems.Add("MyUserControl", ctrlPath, vsToolBoxItemFormat.vsToolBoxItemFormatDotNETComponent); dte.Solution.Close(false); Marshal.ReleaseComObject(dte); //Console.WriteLine("Control Installed!!!"); }
public static Project CreateAndAddUnitTestProject(Solution2 sol, string csProjectName, string csProjectPath, UnitTestCodeType codeType) { //System.Windows.Forms.MessageBox.Show("You must have at least 1 project in your current solution with a project name that ends with UnitTest"); Project proj = null; try { String csItemTemplatePath; switch (codeType) { case UnitTestCodeType.CSharp: csItemTemplatePath = sol.GetProjectTemplate(UTGHelper.CommonStrings.DEFAULT_PROJECT_TEMPLATE, UTGHelper.CommonStrings.DEFAULT_LANGUAGE); break; case UnitTestCodeType.VB: csItemTemplatePath = sol.GetProjectTemplate(UTGHelper.CommonStrings.DEFAULT_PROJECT_TEMPLATE, UTGHelper.CommonStrings.DEFAULT_VB_LANGUAGE); break; default: throw new Exception(string.Format(UTGHelper.CommonErrors.ERR_LANUAGE_TYPE_NOT_SUPPORTED, codeType.ToString())); } proj = sol.AddFromTemplate(csItemTemplatePath, csProjectPath, csProjectName, false); } catch (Exception ex) { Logger.LogException(ex); throw; } return proj; }
private static async Task <Project> CreateProjectFromTemplateAsync( Solution2 solution2, string solutionFolderName, string projectTemplateFilePath, string destPath, string projectName) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); if (string.IsNullOrEmpty(solutionFolderName)) { solution2.AddFromTemplate(projectTemplateFilePath, destPath, projectName, Exclusive: false); return(null); } else { var solutionFolderProject = await VSSolutionHelper.GetSolutionFolderProjectAsync(solution2, solutionFolderName); var solutionFolder = (SolutionFolder)solutionFolderProject.Object; solutionFolder.AddFromTemplate(projectTemplateFilePath, destPath, projectName); return(solutionFolderProject); } }
/// <summary> /// Creates a project of given template and adds a reference to it to the sourceProject /// </summary> /// <param name="sourceProject">can be null, otherwise a reference will be added</param> private static Project CreateProjectAndAddReferenceToIt(VSProject sourceProject, Solution2 solution, string newProjectTemplate, string newProjectName, string newProjectDirectory) { var bindingProjectDir = Path.Combine(Path.GetDirectoryName(sourceProject != null ? sourceProject.Project.FileName : solution.FileName), newProjectDirectory ?? "", newProjectName); if (Directory.Exists(bindingProjectDir)) { Directory.Delete(bindingProjectDir, true); } string csTemplatePath = solution.GetProjectTemplate(newProjectTemplate, "CSharp"); solution.AddFromTemplate(csTemplatePath, bindingProjectDir, newProjectName); //let's find our new project (AddFromTemplate returns null all the time) var newProject = solution.Projects.OfType <Project>().First(p => p.Name == newProjectName); newProject.Save(); //add reference for the target project if (sourceProject != null) { sourceProject.References.AddProject(newProject); } return(newProject); }
public static Project CreateAndAddUnitTestProject(Solution2 sol, string csProjectName, string csProjectPath, UnitTestCodeType codeType) { //System.Windows.Forms.MessageBox.Show("You must have at least 1 project in your current solution with a project name that ends with UnitTest"); Project proj = null; try { String csItemTemplatePath; switch (codeType) { case UnitTestCodeType.CSharp: csItemTemplatePath = sol.GetProjectTemplate(UTGHelper.CommonStrings.DEFAULT_PROJECT_TEMPLATE, UTGHelper.CommonStrings.DEFAULT_LANGUAGE); break; case UnitTestCodeType.VB: csItemTemplatePath = sol.GetProjectTemplate(UTGHelper.CommonStrings.DEFAULT_PROJECT_TEMPLATE, UTGHelper.CommonStrings.DEFAULT_VB_LANGUAGE); break; default: throw new Exception(string.Format(UTGHelper.CommonErrors.ERR_LANUAGE_TYPE_NOT_SUPPORTED, codeType.ToString())); } proj = sol.AddFromTemplate(csItemTemplatePath, csProjectPath, csProjectName, false); } catch (Exception ex) { Logger.LogException(ex); throw; } return(proj); }
public void CreateSolution() { // Create Target solution from PrismStarter Visual Studio project templates // (zip files in ..\Users\...\Documents\My Exported Templates). MessageService.WriteMessage(string.Empty); MessageService.WriteMessage("==================================================="); MessageService.WriteMessage(string.Format("Creating {0}", Connect.settingsObject.TargetSolutionPath)); MessageService.WriteMessage("==================================================="); sln2.Create(Utilities.RemoveEndBackSlash(Connect.settingsObject.TargetSolutionPath), Connect.settingsObject.TargetSolutionName); MessageService.WriteMessage(string.Format("{0} created", Connect.settingsObject.TargetSolutionName)); try { int numProjects = Connect.settingsObject.ProjectNames.Count; for (int i = 0; i < numProjects; i++) { templatePath = sln2.GetProjectTemplate(Connect.settingsObject.ZipFileNames[i], "CSharp"); projectPath = string.Format("{0}{1}", Connect.settingsObject.TargetSolutionPath, Utilities.RemoveEndBackSlash(Connect.settingsObject.ProjectPaths[i])); sln2.AddFromTemplate(templatePath, projectPath, Utilities.RemoveEndBackSlash(Connect.settingsObject.ProjectPaths[i]), false); MessageService.WriteMessage(string.Format("{0} created", Connect.settingsObject.ProjectNames[i])); } } catch (Exception x) { throw x; } sln2.SaveAs(string.Format("{0}{1}", Connect.settingsObject.TargetSolutionPath, Connect.settingsObject.TargetSolutionName)); CloseSolution(); MessageService.WriteMessage(string.Format("{0} created", Connect.settingsObject.TargetSolutionName)); }
public void AddProject(string projectName, string projectTemplate, string languageName) { var projectPath = Path.Combine(DirectoryName, projectName); var projectTemplatePath = GetProjectTemplatePath(projectTemplate, ConvertLanguageName(languageName)); _solution.AddFromTemplate(projectTemplatePath, projectPath, projectName, Exclusive: false); }
private void CreateUnitTestProject(DTE2 dte, string projectName) { // get the current solution Solution2 currentSolution = (Solution2)dte.Solution; string currentSolutionPath = string.Format("{0}\\{1}", GetSolutionPath(dte), projectName); string projTemplate = currentSolution.GetProjectTemplate("csClassLibrary.vstemplate|FrameworkVersion=4.6.1", "CSharp"); // create a new C# class library project using the template obtained above. currentSolution.AddFromTemplate(projTemplate, currentSolutionPath, projectName, false); currentSolution.SaveAs(currentSolution.FullName); }
private static void createProject(SolutionData solutionData, Solution2 solution, DTE dte) { switch (solutionData.projectType) { case ProjectType.CsConsole: solution.AddFromTemplate(solution.GetProjectTemplate("ConsoleApplication.zip", "CSharp"), solutionData.directoryPath + "\\" + solutionData.projectName, solutionData.projectName); break; case ProjectType.CsForms: solution.AddFromTemplate(solution.GetProjectTemplate("WindowsApplication.zip", "CSharp"), solutionData.directoryPath + "\\" + solutionData.projectName, solutionData.projectName); break; case ProjectType.CppEmpty: object[] contextParams = { "{66bb5dd8-bf70-4784-be56-2273124f2638}", solutionData.projectName, solutionData.directoryPath + "\\" }; dte.LaunchWizard(@"c:\Program Files (x86)\Microsoft Visual Studio " + dte.Version + @"\VC\vcprojects\emptyproj.vsz", contextParams); break; } }
private static void CreateProject(Solution2 solution, string projType, string projLanguage, string projPath) { try { string projectName = projPath.Substring(projPath.LastIndexOf('\\') + 1); string templatePath = solution.GetProjectTemplate(projType, projLanguage); solution.AddFromTemplate(templatePath, projPath, projectName); } catch (System.Exception ex) { MessageBox.Show("ERROR: " + ex.Message); } }
private void CreateProject(XElement projectElement) { const string language = "Language"; const string name = "ProjectName"; const string template = "ProjectTemplate"; var languageName = projectElement.Attribute(language)?.Value ?? throw new ArgumentException($"You must specify an attribute called '{language}' on a project element."); var projectName = projectElement.Attribute(name)?.Value ?? throw new ArgumentException($"You must specify an attribute called '{name}' on a project element."); var projectTemplate = projectElement.Attribute(template)?.Value ?? throw new ArgumentException($"You must specify an attribute called '{template}' on a project element."); var projectPath = Path.Combine(DirectoryName, projectName); var projectTemplatePath = GetProjectTemplatePath(projectTemplate, ConvertLanguageName(languageName)); _solution.AddFromTemplate(projectTemplatePath, projectPath, projectName, Exclusive: false); foreach (var documentElement in projectElement.Elements("Document")) { var fileName = documentElement.Attribute("FileName").Value; UpdateOrAddFile(projectName, fileName, contents: documentElement.Value); } }
public static Project AddProjectToSolution(string projectName, string projectTemplateFile, string projectTemplateLanguage, string[] filesToRemove, Solution2 currentSolution) { if (!currentSolution.IsOpen || projectName == string.Empty) { return(null); } string destinationPath = GetSolutionPath((Solution)currentSolution); destinationPath += "\\" + projectName; string csTemplatePath = currentSolution.GetProjectTemplate(projectTemplateFile, projectTemplateLanguage); Project newProject = currentSolution.AddFromTemplate(csTemplatePath, destinationPath, projectName, false); if (newProject == null) { if (projectTemplateLanguage == "Web" || projectTemplateLanguage == "Web\\CSharp") { projectName = destinationPath + "\\"; } foreach (Project p in currentSolution.Projects) { if (p.Name == projectName) { newProject = p; } } } if (newProject != null) { foreach (ProjectItem item in newProject.ProjectItems) { foreach (string filename in filesToRemove) { if (item.Name == filename) { item.Delete(); break; } } } } else { throw new Exception("Unable to locate project in solution after it was created (" + projectName + ")"); } return(newProject); }
/// <summary> /// 添加类库项目 /// </summary> /// <param name="dte">DTE宿体</param> /// <param name="projectName">项目名称</param> /// <param name="overWrite">是否覆盖现有项目</param> /// <returns>创建的项目类</returns> public static Project AddClassLibrary(this DTE dte, string projectName, bool overWrite = false) { try { Solution2 sln = dte.Solution as Solution2; Project prj = (sln as Solution).FindProject(projectName); if (null != prj) { if (overWrite == false) { return(prj); } else { prj.Delete(); } } string projectTemplate = sln.GetProjectTemplate("ClassLibrary.zip", "CSharp"); string path = Path.Combine(Path.GetDirectoryName(sln.FullName), projectName); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } prj = sln.AddFromTemplate(projectTemplate, path, projectName); if (null == prj) { prj = (sln as Solution).FindProject(projectName); } //移除Class1 ProjectItem prjItem = prj.ProjectItems.FindItem("Class1.cs"); if (null != prjItem) { prjItem.Delete(); } //更改Project目标平台为X86 prj.SetProjectConfig("PlatformTarget", "X86"); return(prj); } catch (Exception ex) { throw ex; } }
void showSPIInfoMenuItem_Click(object sender, MenuItemEventArgs e) { //here check if the web app is generated or not ISharePointProject project = (ISharePointProject)e.Owner; //only if there is no previous link added(fresh app) if (project.AppSettings.InstalledEventEndpoint == null && project.AppSettings.WebProjectPath == null) { string webProjectName = project.Name + "Web"; DTE dte = Package.GetGlobalService(typeof(EnvDTE.DTE)) as DTE; Solution2 solution = (Solution2)dte.Solution; string tmp = solution.GetProjectTemplate("RemoteProvisioningEventReceiver.zip", "CSharp"); //string tmp = solution.GetProjectTemplate("RemoteProvisioning.zip", "CSharp"); string solutionFolder = solution.FullName.Substring(0, solution.FullName.LastIndexOf("\\")); Project web = solution.AddFromTemplate(tmp, solutionFolder + "\\" + webProjectName, webProjectName, false); //beacuse web always return with null value !!! bool success = false; foreach (Project item in solution.Projects) { if (item.FullName == solutionFolder + "\\" + webProjectName + "\\" + webProjectName + ".csproj") { success = true; web = item; break; } } if (success) { project.AppSettings.LinkToWebProject(web.FullName, false, false); project.AppSettings.InstalledEventEndpoint = "~remoteAppUrl/Services/AppEventReceiver.svc"; project.AppSettings.UninstallingEventEndpoint = "~remoteAppUrl/Services/AppEventReceiver.svc"; //add app permission and remote webapplication node to xml XmlDocument appManifest = new XmlDocument(); appManifest.Load(project.AppSettings.AppManifest.FullPath); XmlNamespaceManager nsmgr = new XmlNamespaceManager(appManifest.NameTable); nsmgr.AddNamespace("appManifest", "http://schemas.microsoft.com/sharepoint/2012/app/manifest"); XmlNode appPrinciple = appManifest.ChildNodes[2].ChildNodes[1]; appPrinciple.InnerXml = " <RemoteWebApplication ClientId=\"*\"/>"; XmlNode app = appManifest.ChildNodes[2]; app.InnerXml += @"<AppPermissionRequests><AppPermissionRequest Scope=""http://sharepoint/content/sitecollection"" Right=""FullControl"" /></AppPermissionRequests>"; appManifest.Save(project.AppSettings.AppManifest.FullPath); } } }
protected Project CreateSolutionWithProject(string solutionName = "TestSolution", string projectName = "TestProject") { string solutionPath = Path.Combine(RootDir, solutionName); string projectPath = Path.Combine(solutionPath, projectName); if (Directory.Exists(solutionPath)) { Directory.Delete(solutionPath, true); } Solution2 solution = (Solution2)Dte.Solution; solution.Create(solutionPath, solutionName); var projectTemplate = solution.GetProjectTemplate("ConsoleApplication.zip", "CSharp"); solution.AddFromTemplate(projectTemplate, projectPath, projectName); return(solution.Projects.Item(1)); }
static void CreateProject(Solution2 solution2, string projectSubFolder, string projectName, string projectTemplateName, string language) { // Credits: https://www.mztools.com/articles/2013/MZ2013022.aspx string solutionFileFullName; string solutionFolderFullName; string projectTemplateFileFullName; string projectFolderFullName; try { // Get the full name of the solution file solutionFileFullName = solution2.FileName; // Get the full name of the solution folder solutionFolderFullName = System.IO.Path.GetDirectoryName(solutionFileFullName); // Compose the full name of the project folder projectFolderFullName = System.IO.Path.Combine(solutionFolderFullName, projectSubFolder); if (!(projectFolderFullName.EndsWith("\\"))) { projectFolderFullName += "\\"; } // Get the project template projectTemplateFileFullName = solution2.GetProjectTemplate(projectTemplateName, language); // Add the project solution2.AddFromTemplate(projectTemplateFileFullName, projectFolderFullName, projectName, false); // Log: AddLogEntryOnUIThread(string.Format(@"")); AddLogEntryOnUIThread(string.Format(@"===============================================")); AddLogEntryOnUIThread(string.Format(@"Created project ""{0}"".", projectName)); AddLogEntryOnUIThread(string.Format(@"===============================================")); AddLogEntryOnUIThread(string.Format(@"")); } catch (Exception ex) { DisplayMessageBoxOnUIThread(ex.ToString()); } }
/// <summary> /// Creates a new project based on the given full path to the project template. /// </summary> /// <param name="projectTemplate"></param> /// <param name="framework"></param> /// <param name="solnPath"></param> public void CreateProject(string projectTemplateFullPath, string projectTargetFramework, string projectName, string solnFullPath = null) { try { if (solnFullPath == null) { solnFullPath = Path.Combine(Environment.CurrentDirectory, "Solution" + DateTime.Now.Ticks.ToString()); } this.SolutionPath = solnFullPath; Solution2 soln = dteObject.Solution as Solution2; //setting the project location is required due to Nuget bug # 2917 : http://nuget.codeplex.com/workitem/2917 Properties prop = dteObject.Properties["Environment", "ProjectsAndSolution"]; prop.Item("ProjectsLocation").Value = Path.GetFullPath(Path.GetDirectoryName(solnFullPath)); soln.AddFromTemplate(projectTemplateFullPath + projectTargetFramework, solnFullPath, projectName); } catch (Exception e) { throw new Exception(string.Format("Unable to create project with template {0}. Make sure that the template is valid and the template file exists. Exception message : {1}", projectTemplateFullPath.ToString(), e.Message)); } }
public static Project AddProjectToSolution(string projectName, string projectTemplateFile, string projectTemplateLanguage, string[] filesToRemove, Solution2 currentSolution) { if (!currentSolution.IsOpen || projectName == string.Empty) return null; string destinationPath = GetSolutionPath((Solution)currentSolution); destinationPath += "\\" + projectName; string csTemplatePath = currentSolution.GetProjectTemplate(projectTemplateFile, projectTemplateLanguage); Project newProject = currentSolution.AddFromTemplate(csTemplatePath, destinationPath, projectName, false); if (newProject == null) { if (projectTemplateLanguage == "Web" || projectTemplateLanguage == "Web\\CSharp") { projectName = destinationPath + "\\"; } foreach (Project p in currentSolution.Projects) { if (p.Name == projectName) { newProject = p; } } } if (newProject != null) { foreach (ProjectItem item in newProject.ProjectItems) { foreach (string filename in filesToRemove) { if (item.Name == filename) { item.Delete(); break; } } } } else { throw new Exception("Unable to locate project in solution after it was created (" + projectName + ")"); } return newProject; }
public void Initialize() { Project currentProject = GetProjectByName(_projectName); if (currentProject != null) { try { _solution.Remove(currentProject); } catch (COMException e) { Debug.WriteLine(e.Message); } } string solutionPath = Path.GetDirectoryName(_solution.FullName); string projectPath = Path.Combine(solutionPath, _projectName); TryDeleteDirectory(projectPath); string classLibraryTemplatePath = _solution.GetProjectTemplate(_projectTemplateAndFrameworkVersion, PROJECT_LANGUAGE); _solution.AddFromTemplate(classLibraryTemplatePath, projectPath, _projectName); Project newProject = GetProjectByName(_projectName); DeleteDefaultClass(newProject); Project clientProject = GetProjectByName(_rosMessageTypeAttributeProjectName); if (null != clientProject) { VSProject newProjectVSProject = (VSProject)newProject.Object; newProjectVSProject.References.AddProject(clientProject); } else { throw new ProjectNotFoundException($"There is no such project: {_rosMessageTypeAttributeProjectName}"); } _project = newProject; }
private static Project GetTestingProject(Project p_referencedProject) { Project testingProject = null; string projectName = "UnitTesting"; DTE2 dte = (DTE2)Secure_TDDPackage.GetGlobalService(typeof(DTE)); Solution2 soln = (Solution2)dte.Solution; foreach (Project proj in soln.Projects) { if (proj.Name == projectName) { testingProject = proj; break; } } if (testingProject == null) { string unitTestProjectTemplatePath; unitTestProjectTemplatePath = soln.GetProjectTemplate("UnitTestProject", "CSharp"); string projectDestinationPath = soln.FullName.Remove(soln.FullName.LastIndexOf('\\')); projectDestinationPath += "\\" + projectName; soln.AddFromTemplate(unitTestProjectTemplatePath, projectDestinationPath, projectName); foreach (Project proj in soln.Projects) { if (proj.Name == projectName) { testingProject = proj; break; } } VSProject vsProj = testingProject.Object as VSProject; vsProj.References.AddProject(p_referencedProject); } return(testingProject); }
/// <summary> /// 添加服务项目 /// </summary> /// <param name="dte">DTE宿体</param> /// <param name="projectName">项目名称</param> /// <param name="overWrite">是否覆盖现有项目</param> /// <returns>创建的项目类</returns> public static Project AddWebService(this DTE dte, string projectName, bool overWrite = false) { try { Solution2 sln = dte.Solution as Solution2; Project prj = (sln as Solution).FindProject(projectName); if (null != prj) { if (overWrite == false) { return(prj); } else { prj.Delete(); } } string projectTemplate = sln.GetProjectTemplate("EmptyWebApplicationProject40.zip", "CSharp"); string path = Path.Combine(Path.GetDirectoryName(sln.FullName), projectName); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } prj = sln.AddFromTemplate(projectTemplate, path, projectName); if (null == prj) { prj = (sln as Solution).FindProject(projectName); } prj.SetProjectConfig("PlatformTarget", "X86"); return(prj); } catch (Exception ex) { throw ex; } }
private static void CreateProject(Solution2 solution, string projType, string projLanguage, string projPath) { try { string projectName = projPath.Substring(projPath.LastIndexOf('\\') + 1); string templatePath = solution.GetProjectTemplate(projType, projLanguage); solution.AddFromTemplate(templatePath, projPath, projectName); } catch (System.Exception ex) { MessageBox.Show("ERROR: " + ex.Message); } }
public void RunFinished() { Solution2 solution2 = (Solution2)this._dte2.Solution; string slClassLibProjectPath = this._slClassLibProject.FullName; string classLibName = this._replacementsDictionary["$safeprojectname$"]; // Determine whether the SL project was created in a Solution Folder. // If the user explicitly asked to Add Project under a Solution Folder, // it will be non-null. However if they ask to Create New Project under // a Solution Folder but change their mind to say "Add to Solution", // they will end up with the Silverlight project as a child of the SLN. ProjectItem projectItem = this._slClassLibProject.ParentProjectItem; ProjectItems projectItems = projectItem == null ? null : projectItem.Collection; Project parentProject = projectItems == null ? null : projectItems.Parent as Project; SolutionFolder slProjectParentSolutionFolder = (parentProject != null && parentProject.Kind == ProjectKinds.vsProjectKindSolutionFolder) ? parentProject.Object as SolutionFolder : null; // If the SL project was created in a Solution Folder, it wins because we cannot move it (see below). // However if the SL project was created as a child of the Solution, we have a choice. If a Solution Folder // was active when the user added the template, that is the one we will use. But if there was no active // Solution Folder, then we unconditionally create a new Solution Folder as a child of the Solution. SolutionFolder libFolder = slProjectParentSolutionFolder ?? this._activeSolutionFolder; if (libFolder == null) { try { // SL project was created directly under the Solution. Create a Solution Folder // to hold the pair of projects. libFolder = (SolutionFolder)((Project)solution2.AddSolutionFolder(classLibName)).Object; } catch (COMException) { libFolder = null; } } bool isVb = this._slClassLibProject.CodeModel.Language.Equals(CodeModelLanguageConstants.vsCMLanguageVB, StringComparison.OrdinalIgnoreCase); string language = isVb ? "VisualBasic" : "CSharp"; // CSDMain 228876 // Appending the FrameworkVersion to the file name when calling GetProjectTemplate is an undocumented way to request a specific $targetframeworkversion$ token // to become available to the child template. Without doing this, the default target framework value is used, which for VS 11 is 4.5. // Reference: http://www.visualstudiodev.com/visual-studio-extensibility/using-automation-to-create-templates-using-different-framework-versions-in-vs2008-23148.shtml string templateName = "ClassLibrary.zip|FrameworkVersion=" + this._replacementsDictionary["$targetframeworkversion$"]; string netClassLibProjectTemplate = solution2.GetProjectTemplate(templateName, language); string netClassLibProjectName = classLibName + ".Web"; string destination = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(slClassLibProjectPath)), netClassLibProjectName); // This code executes if we either created our own SolutionFolder or are using // the one the user chose. if (libFolder != null) { // Create the .NET class library in whichever SolutionFolder we decided to use above libFolder.AddFromTemplate(netClassLibProjectTemplate, destination, netClassLibProjectName); // If the SL project was created as a child of the Solution, we need to move it // into our new Solution Folder. However, if it was created in a Solution Folder, // we leave it as is. Dev10 bug 893488 disallows moving the SL project from one // Solution Folder to another, so this strategy avoids that issue. if (slProjectParentSolutionFolder == null) { // Move the Silverlight library under the folder solution2.Remove(this._slClassLibProject); this._slClassLibProject = libFolder.AddFromFile(slClassLibProjectPath); } } else { solution2.AddFromTemplate(netClassLibProjectTemplate, destination, netClassLibProjectName, false); } // Link the two class libraries together string extension = Path.GetExtension(slClassLibProjectPath); IVsSolution ivsSolution = (IVsSolution)Package.GetGlobalService(typeof(SVsSolution)); IVsHierarchy hierarchy; ivsSolution.GetProjectOfUniqueName(_slClassLibProject.UniqueName, out hierarchy); IVsBuildPropertyStorage buildPropertyStorage = (IVsBuildPropertyStorage)hierarchy; buildPropertyStorage.SetPropertyValue("LinkedOpenRiaServerProject", null, (uint)_PersistStorageType.PST_PROJECT_FILE, Path.Combine("..", Path.Combine(netClassLibProjectName, netClassLibProjectName + extension))); buildPropertyStorage.SetPropertyValue("DisableFastUpToDateCheck", null, (uint)_PersistStorageType.PST_PROJECT_FILE, "true"); }
public ShellProject AddFromTemplate(string FileName, string Destination, string ProjectName, bool Exclusive) { return(new ShellProject(_solution.AddFromTemplate(FileName, Destination, ProjectName, Exclusive))); }
/// <summary> /// Creates the designtime project and adds the appropriate files to the /// project. /// </summary> public void CreateProject(Solution2 mySolution) { // first, retrieve the visual studio installation folder RegistryKey regkey; // notice no try/catch, we want exceptions bubbling up as there's really nothing // we can do about them here. // retrieve the BizTalk Server installation folder string bizTalkInstallRegistryKey = @"SOFTWARE\Microsoft\BizTalk Server\3.0"; regkey = Registry.LocalMachine.OpenSubKey(bizTalkInstallRegistryKey); this._BizTalkInstallPath = regkey.GetValue("InstallPath").ToString(); // This is no longer present in the registry under the BizTalk Server key this._TargetVSVersion = "14.0"; // regkey.GetValue("TargetVSVersion").ToString(); regkey.Close(); // Visual studio installation folder string vsInstallFolderRegistryKey = string.Format(@"SOFTWARE\Microsoft\VisualStudio\{0}_Config", this._TargetVSVersion); regkey = Registry.CurrentUser.OpenSubKey(vsInstallFolderRegistryKey); // set the actual Visual Studio installation folder for later use this._VisualStudioInstallPath = regkey.GetValue("InstallDir").ToString(); regkey.Close(); string projectTemplate = null; string projectFileName = null; string classFileExtension = null; implementationLanguages language = (implementationLanguages)_WizardResults[WizardValues.ImplementationLanguage]; switch (language) { case implementationLanguages.CSharp: projectTemplate = (mySolution as Solution2).GetProjectTemplate("ClassLibrary.zip", "CSharp"); projectFileName = _ProjectName + ".csproj"; classFileExtension = ".cs"; break; case implementationLanguages.VBNet: projectTemplate = (mySolution as Solution2).GetProjectTemplate("ClassLibrary.zip", "VisualBasic"); projectFileName = _ProjectName + ".vbproj"; classFileExtension = ".vb"; break; default: MessageBox.Show(String.Format("Language \"{0}\" not supported", language)); return; } var startingProjects = (from Project p in this._Application.Solution.Projects select p).ToArray(); // add the specified project to the solution mySolution.AddFromTemplate(projectTemplate, _ProjectDirectory, _ProjectName, this._FExclusive); Project pipelineComponentProject = null; // Query for te added project pipelineComponentProject = (from Project p in this._Application.Solution.Projects where !startingProjects.Any(s => s.UniqueName == p.UniqueName) select p).First(); // delete the Class1.cs|vb|jsharp|... the template adds to the project pipelineComponentProject.ProjectItems.Item("Class1" + classFileExtension).Delete(); // adjust project properties pipelineComponentProject.Properties.Item("RootNameSpace").Value = (string)_WizardResults[WizardValues.Namespace]; pipelineComponentProject.Properties.Item("AssemblyName").Value = (string)_WizardResults[WizardValues.ClassName]; // Get a reference to the Visual Studio Project and // use it to add a reference to the framework assemblies VSProject PipelineComponentVSProject = (VSProject)pipelineComponentProject.Object; if (null != PipelineComponentVSProject.Project) { foreach (Property prop in PipelineComponentVSProject.Project.Properties) { switch (prop.Name) { case "TargetFrameworkMoniker": prop.Value = ".NETFramework,Version=v4.5"; break; case "TargetFramework": prop.Value = (0x040005).ToString(); break; } } } //PipelineComponentVSProject.Project.Properties.Item("TargetFrameworkMoniker").Value = ".NETFramework,Version=v4.5"; //PipelineComponentVSProject.Project.Properties.Item("TargetFramework").Value = (0x040005).ToString(); PipelineComponentVSProject.References.Add("System.dll"); PipelineComponentVSProject.References.Add("System.Xml.dll"); PipelineComponentVSProject.References.Add("System.Drawing.dll"); PipelineComponentVSProject.References.Add(Path.Combine(_BizTalkInstallPath, @"Microsoft.BizTalk.Pipeline.dll")); PipelineComponentVSProject.References.Add(Path.Combine(_BizTalkInstallPath, @"Microsoft.BizTalk.Messaging.dll")); PipelineComponentVSProject.References.Add(Path.Combine(_BizTalkInstallPath, @"Microsoft.BizTalk.Streaming.dll")); // add our resource bundle string resourceBundle = Path.Combine(_ProjectDirectory, ((string)_WizardResults[WizardValues.ClassName]) + ".resx"); ResXResourceWriter resx = new ResXResourceWriter(resourceBundle); resx.AddResource("COMPONENTNAME", _WizardResults[WizardValues.ComponentName] as string); resx.AddResource("COMPONENTDESCRIPTION", _WizardResults[WizardValues.ComponentDescription] as string); resx.AddResource("COMPONENTVERSION", _WizardResults[WizardValues.ComponentVersion] as string); resx.AddResource("COMPONENTICON", _WizardResults[WizardValues.ComponentIcon]); resx.Close(); pipelineComponentProject.ProjectItems.AddFromFile(resourceBundle); // get the enum value of our choosen component type componentTypes componentType = (componentTypes)Enum.Parse(typeof(componentTypes), _WizardResults[WizardValues.ComponentStage] as string); // create our actual class string pipelineComponentSourceFile = Path.Combine(_ProjectDirectory, ((string)_WizardResults[WizardValues.ClassName]) + classFileExtension); PipelineComponentCodeGenerator.generatePipelineComponent( pipelineComponentSourceFile, _WizardResults[WizardValues.Namespace] as string, _WizardResults[WizardValues.ClassName] as string, (bool)_WizardResults[WizardValues.ImplementIProbeMessage], _DesignerProperties, componentType, (implementationLanguages)_WizardResults[WizardValues.ImplementationLanguage]); pipelineComponentProject.ProjectItems.AddFromFile(pipelineComponentSourceFile); #region add the component utilities class, if needed if (DesignerVariableType.SchemaListUsed) { string BizTalkUtilitiesFileName = "Microsoft.BizTalk.Component.Utilities.dll"; Stream stream = this.GetType().Assembly.GetManifestResourceStream(_ProjectNamespace + "." + BizTalkUtilitiesFileName); using (BinaryReader br = new BinaryReader(stream)) { using (FileStream fs = new FileStream(Path.Combine(_ProjectDirectory, BizTalkUtilitiesFileName), FileMode.Create)) { // temporary storage byte[] b = null; // read the stream in blocks of ushort.MaxValue while ((b = br.ReadBytes(ushort.MaxValue)).Length > 0) { // write what we've read to the output file fs.Write(b, 0, b.Length); } } } PipelineComponentVSProject.References.Add(Path.Combine(_ProjectDirectory, BizTalkUtilitiesFileName)); } #endregion // save the project file PipelineComponentVSProject.Project.Save(Path.Combine(_ProjectDirectory, projectFileName)); // only do this if we're creating a new solution, otherwise the user // might get distracted from his/her current work #if RELEASE if (this._FExclusive) { #endif // retrieve the main code file from the added project ProjectItem item = PipelineComponentVSProject.Project.ProjectItems.Item(Path.GetFileName(pipelineComponentSourceFile)); // let's open up the main code file and show it so the user can start editing Window mainSourceFile = item.Open(Constants.vsViewKindPrimary); // set the editor to the newly created sourcecode mainSourceFile.Activate(); #if RELEASE } #endif }
private static void createProject(SolutionData solutionData, Solution2 solution, DTE dte) { switch (solutionData.projectType) { case ProjectType.CsConsole: solution.AddFromTemplate(solution.GetProjectTemplate("ConsoleApplication.zip", "CSharp"), solutionData.directoryPath + "\\" + solutionData.projectName, solutionData.projectName); break; case ProjectType.CsForms: solution.AddFromTemplate(solution.GetProjectTemplate("WindowsApplication.zip", "CSharp"), solutionData.directoryPath + "\\" + solutionData.projectName, solutionData.projectName); break; case ProjectType.CppEmpty: object[] contextParams = { "{66bb5dd8-bf70-4784-be56-2273124f2638}", solutionData.projectName, solutionData.directoryPath + "\\" }; dte.LaunchWizard(@"c:\Program Files (x86)\Microsoft Visual Studio " + dte.Version + @"\VC\vcprojects\emptyproj.vsz", contextParams); break; } }
/// <summary> /// Creates a project of given template and adds a reference to it to the sourceProject /// </summary> /// <param name="sourceProject">can be null, otherwise a reference will be added</param> private static Project CreateProjectAndAddReferenceToIt(VSProject sourceProject, Solution2 solution, string newProjectTemplate, string newProjectName, string newProjectDirectory) { var bindingProjectDir = Path.Combine(Path.GetDirectoryName(sourceProject != null ? sourceProject.Project.FileName : solution.FileName), newProjectDirectory ?? "", newProjectName); if (Directory.Exists(bindingProjectDir)) Directory.Delete(bindingProjectDir, true); string csTemplatePath = solution.GetProjectTemplate(newProjectTemplate, "CSharp"); solution.AddFromTemplate(csTemplatePath, bindingProjectDir, newProjectName); //let's find our new project (AddFromTemplate returns null all the time) var newProject = solution.Projects.OfType<Project>().First(p => p.Name == newProjectName); newProject.Save(); //add reference for the target project if (sourceProject != null) { sourceProject.References.AddProject(newProject); } return newProject; }
/// <summary> /// create solution and output proj in other thread /// solution name = project name /// </summary> private bool RunLongProcess(List <FileInfo> files, String projName, String folderOutputPath , string path_to_GUI_Testing_Automation_ref , string path_to_vstemplate_output_proj , string tempProjectFolder , List <string> runningTestFilesRelativePath , List <string> otherFilesRelativePath , string AUTPath) { EnvDTE80.DTE2 dte2 = null; string folderSolution = folderOutputPath; string folderOutputProj = folderOutputPath + "\\" + projName; string solutionName = projName + ".sln"; string outputProjName = projName; string pathTo_csproj = folderOutputProj + "\\" + outputProjName + ".csproj"; //string pathToSolution = folderSolution + "\\" + solutionName; //get solution2 as part of visual studio string versionDTE = "VisualStudio.DTE.15.0"; System.Type dteType = System.Type.GetTypeFromProgID(versionDTE, true); dte2 = (EnvDTE80.DTE2)System.Activator.CreateInstance(dteType, true); MessageFilter.Register(); Solution2 sol = (Solution2)dte2.Solution; //delete the old folder_solution if it exists. if (Directory.Exists(folderSolution)) { Directory.Delete(folderSolution, true); } //create a new folder_solution Directory.CreateDirectory(folderSolution); //create a solution that locates in the above solution sol.Create(folderSolution, solutionName); //create a new folder_output_project Directory.CreateDirectory(folderOutputProj); Project outputProj = sol.AddFromTemplate(path_to_vstemplate_output_proj , folderOutputProj, outputProjName, false); //save the solution sol.SaveAs(solutionName); // for kill process dte2.Quit(); MessageFilter.Revoke(); var t1 = DateTime.Now; while (dte2 != null && (DateTime.Now - t1).TotalSeconds < 5) { //dte2. try { dte2.Quit(); } catch (Exception) { } System.Threading.Thread.Sleep(1000); } ModifyProject(files, folderOutputProj, runningTestFilesRelativePath, otherFilesRelativePath, tempProjectFolder, pathTo_csproj, path_to_GUI_Testing_Automation_ref, projName, AUTPath); return(true); }