/// <summary> /// 将一个已经存在的文件加入项目 /// </summary> /// <param name="projectItems">某个项目下面的ProjectItems</param> /// <param name="path">要加入的文件的路径</param> public void CreateDocumentFromCopy(ProjectItems projectItems, string path) { if (VSSolution.CurrentSolution2 != null) { if (!File.Exists(path)) { throw new NullReferenceException("要加载的文件不存在"); } string givingName = path.Substring(path.LastIndexOf('\\') + 1, path.LastIndexOf('.') - path.LastIndexOf('\\') - 1); //检测是否已经存在该文件 List <ProjectItem> allFileProjectItem = GetAllFileProjectItem(projectItems); ProjectItem projectItem = allFileProjectItem.Find(i => i.Name == givingName); if (projectItem != null) { MessageBox.Show("已经存在给定的文件"); } else { try { projectItems.AddFromFileCopy(path); } catch (COMException e) { MessageBox.Show(e.Message); } } } }
/// <summary> /// Generates early-bound object wrapper /// </summary> /// <param name="sender"> </param> /// <param name="e"> </param> private void OnGenerateWrapper(object sender, EventArgs e) { try { //Get current Project: Project[] projects = VSUtils.GetProjects(GetNodeSite()); if (projects == null || projects.Length == 0) { return; } //This is an assumtion that's working so far. //TODO: verify if this is the right way to determine the startup project //in the solution: Project curProject = projects[0]; string curProjSuffix = VSUtils.MapProjectGuidToSuffix(new Guid(curProject.Kind)); if (curProjSuffix == string.Empty) { //neither a VB nor a CS project throw new Exception(WMISys.GetString("WMISE_Invalid_Project_Type_For_CodeGen")); } ProjectItems projItems = curProject.ProjectItems; if (projItems == null) { throw new Exception(WMISys.GetString("WMISE_Could_Not_Add_File_to_Project")); } Guid curProjectType = new Guid(curProject.Kind); string wrapperFileName = className + "." + curProjSuffix; if (!mgmtObj.GetStronglyTypedClassCode(VSUtils.MapProjectGuidToCodeLanguage(curProjectType), Path.GetTempPath() + "\\" + wrapperFileName)) { throw new Exception(WMISys.GetString("WMISE_Code_Generation_Failed")); } ProjectItem newItem = projItems.AddFromFileCopy(Path.GetTempPath() + "\\" + wrapperFileName); if (newItem == null) { throw new Exception(WMISys.GetString("WMISE_Could_Not_Add_File_to_Project")); } File.Delete(Path.GetTempPath() + "\\" + wrapperFileName); } catch (Exception exc) { MessageBox.Show(WMISys.GetString("WMISE_Exception", exc.Message, exc.StackTrace)); } }
public void AddFromFileCopy_AddFileNameOutsideProjectFolder_FileIsIncludedInProjectInProjectFolder() { CreateProjectItems(); msbuildProject.FileName = @"d:\projects\myproject\myproject\myproject.csproj"; string fileName = @"d:\projects\myproject\packages\tools\test.cs"; projectItems.AddFromFileCopy(fileName); var fileItem = msbuildProject.Items[0] as FileProjectItem; Assert.AreEqual("test.cs", fileItem.Include); }
/// <summary> /// Adds the item. /// </summary> /// <param name="project">The project.</param> /// <param name="projectItems">The project items.</param> private void AddItem(Project project, ProjectItems projectItems) { if (!overwriteItemIfExists) { outputProjectItem = DteHelper.FindItemByName(projectItems, Path.GetFileName(sourceFilePath), false); if (outputProjectItem == null) { outputProjectItem = projectItems.AddFromFileCopy(sourceFilePath); } } else { File.Copy(sourceFilePath, Path.Combine(projectItem.Properties.Item("FullPath").Value.ToString(), Path.GetFileName(sourceFilePath)), true); } }
///// <summary> ///// Ensuures that a project of a given name exists in the solution ///// </summary> ///// <param name="store">Model from which to look for</param> ///// <param name="relativePath">Relative path where to create the new project if necessary (ending in the project name with .csproj)</param> ///// <param name="sourcePath">Source path of the template of the project</param> ///// <param name="updateAssemblyNameAndNamespace">Should we update the assembly name and namespace of the new project.</param> ///// <remarks> ///// Suppose you want to create add a new project named "MyProject.csproj" from a template (vs vsTemplate located in a sub folder of the location of the extension, ///// and you want to have similar namespaces: ///// <code> ///// StoreHostingProject.EnsureNamedProjectExistsInDslSolution(dsl.Store, "MyProject.csproj" ///// , Path.Combine(Path.GetDirectoryName(typeof(ATypeInMyExtension).Assembly.Location), @"Templates\MyProject\MyTemplate.vstemplate") ///// , true ///// ); ///// </code> ///// </remarks> //public static void EnsureNamedProjectExistsInDslSolution(Store store, string relativePath, string sourcePath, bool updateAssemblyNameAndNamespace) //{ // // Verify that the relative path ends with csproj // if (Path.GetExtension(relativePath) != ".csproj") // { // throw new ArgumentException("relativePath should be relative path of the .csproj file to create with respect to the solution, hence ending in .csproj", "relativePath"); // } // Project project = Store2DTE.GetProjectForStore(store); // Solution solution = project.DTE.Solution; // Project newProject = solution.Projects.OfType<Project>().FirstOrDefault(p => p.UniqueName == relativePath); // if (newProject != null) // { // return; // } // string projectDirectory = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(project.FullName)), Path.GetFileNameWithoutExtension(relativePath)); // string projectPath = Path.Combine(projectDirectory, Path.GetFileName(relativePath)); // string projectSimpleName = Path.GetFileNameWithoutExtension(relativePath); // // The project exist but is not in the solution: let's just add it. // if (File.Exists(projectPath)) // { // solution.AddFromFile(projectPath, false); // } // // The project does not exist: create it from a template // else // { // newProject = project.DTE.Solution.AddFromTemplate(sourcePath, projectDirectory, Path.GetFileName(relativePath), false); // // Well known workaround for C# and VB projects, AddFromTemplate returns null // newProject = solution.Projects.OfType<Project>().FirstOrDefault(p => p.Name == projectSimpleName); // // Update the assembly name and namespace if necessary // if (updateAssemblyNameAndNamespace) // { // newProject.Properties.Item("AssemblyName").Value = project.Properties.Item("AssemblyName").Value.ToString().Replace("." + project.Name, "." + projectSimpleName); // newProject.Properties.Item("DefaultNamespace").Value = project.Properties.Item("DefaultNamespace").Value.ToString() + "." + projectSimpleName; // } // } //} #endregion #region Adding a file or a link to a file /// <summary> /// Ensures that a file is present in the project /// </summary> /// <param name="store">Store containing a model</param> /// <param name="relativePath">relative path where the file should be located</param> /// <param name="sourcePath">Path of the file to copy if not already present in the solution</param> /// <example> /// if you have a file Adapter.tt, added to the VSIX, of type Content, and copied if newer, in a folder Temmplates of the extension project, you can add /// it to the GeneratedCode folder of the DSL by the following code: /// <code> /// StoreHostingProject.EnsureFileInProject(dsl.Store, @"GeneratedCode\Adapter.tt", /// Path.Combine(Path.GetDirectoryName(typeof(MyExtensionAuthoring).Assembly.Location), @"Templates\Adapter.tt")); /// </code> /// </example> public static void EnsureFileCopiedInDslProject(Store store, string relativePath, string sourcePath) { Contract.Requires(store != null); Contract.Requires(relativePath != null); Contract.Requires(sourcePath != null); Project project = Store2DTE.GetProjectForStore(store); string[] pathSegments = relativePath.Split('\\'); ProjectItems parent = project.ProjectItems; // Find the folder (or create it if necessary) for (int i = 0; i < pathSegments.Length - 1; ++i) { ProjectItem folder = parent.OfType <ProjectItem>().FirstOrDefault(projectItem => projectItem.Name == pathSegments[i]); if (folder == null) { folder = parent.AddFolder(pathSegments[i]); } parent = folder.ProjectItems; } // Find the file and create it if necessary ProjectItem file = parent.OfType <ProjectItem>().FirstOrDefault(projectItem => projectItem.Name == pathSegments[pathSegments.Length - 1]); if (file == null) { string fileDirectory = Path.Combine(Path.GetDirectoryName(project.FullName), Path.GetDirectoryName(relativePath)); string filePath = Path.Combine(fileDirectory, Path.GetFileName(relativePath)); // Case where the file is already there, but not added to the project if (File.Exists(filePath)) { parent.AddFromFile(filePath); } else { parent.AddFromFileCopy(sourcePath); } } }
protected virtual void AddFileToProject(string path) { if (ExcludeFile(path)) { return; } // Get the project items for the folder path string folderPath = Path.GetDirectoryName(path); string fullPath = GetFullPath(path); ThreadHelper.Generic.Invoke(() => { ProjectItems container = Project.GetProjectItems(folderPath, createIfNotExists: true); // Add the file to the project container.AddFromFileCopy(fullPath); }); Logger.Log(MessageLevel.Debug, VsResources.Debug_AddedFileToProject, path, ProjectName); }
/// <summary> /// The method that creates a new item from the intput string. /// </summary> public override void Execute() { List <ProjectItem> items = new List <ProjectItem>(); ProjectItems tempProjectItems = null; if (projectItem != null) { tempProjectItems = projectItem.ProjectItems; } else { tempProjectItems = targetProject.ProjectItems; } foreach (string fileName in Directory.GetFiles(sourceFilePath, searchPattern)) { ProjectItem outputProjectItem; if (this.copy) { outputProjectItem = tempProjectItems.AddFromFileCopy(fileName); } else { outputProjectItem = tempProjectItems.AddFromFile(fileName); } items.Add(outputProjectItem); if (open && outputProjectItem != null) { Window wnd = outputProjectItem.Open(Constants.vsViewKindPrimary); wnd.Visible = true; wnd.Activate(); } } projectItems = items.ToArray(); }
protected virtual void AddFileToContainer(string fullPath, ProjectItems container) { container.AddFromFileCopy(fullPath); }
/// <summary> /// Adds the files and folders. /// </summary> /// <param name="source">The source.</param> /// <param name="target">The target.</param> /// <param name="targetProjectType">Type of the target project.</param> /// <param name="levels">The number of levels to walk down the chain. If <c>-1</c>, it will handle all levels.</param> /// <param name="fileFilter">An enumerable of files that should be handled with care, can be <c>null</c>.</param> /// <exception cref="ArgumentNullException">The <paramref name="source" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="target" /> is <c>null</c>.</exception> private void AddFilesAndFolders(ProjectItems source, ProjectItems target, ProjectType targetProjectType, int levels, IEnumerable<string> fileFilter) { Argument.IsNotNull("source", source); Argument.IsNotNull("target", target); string targetParentName = target.Parent.GetObjectName(); Log.Debug("Adding files and folders to target '{0}'", targetParentName); if (levels == 0) { return; } levels--; foreach (ProjectItem sourceItem in source) { var sourceItemName = sourceItem.Name; if (sourceItem.IsLinkedFile()) { Log.Debug("Skipping item '{0}' because it is a linked file (so has another root project)", sourceItem.GetObjectName()); continue; } if (ShouldSkipAddingOfItem(sourceItem, targetProjectType)) { Log.Debug("Skipping item '{0}' because it is ignored by a rule for target project {1}", sourceItem.GetObjectName(), targetProjectType); continue; } ProjectItem existingTargetItem = null; foreach (ProjectItem targetItem in target) { if (string.Equals(targetItem.Name, sourceItemName)) { existingTargetItem = targetItem; break; } } bool isFolder = sourceItem.IsFolder(); bool containsSubItems = isFolder || sourceItem.ContainsChildItems(); if (existingTargetItem == null) { if (!isFolder) { if (sourceItem.IsXamlFile() && ((targetProjectType == ProjectType.NET40) || (targetProjectType == ProjectType.NET45))) { Log.Debug("File '{0}' is a xaml file and the target project is NET40 or NET45. There is a bug in Visual Studio that does not allow to link xaml files in NET40, so a copy is created.", sourceItem.FileNames[0]); // string targetFile = sourceItem.GetTargetFileName(target); // File.Copy(sourceItem.FileNames[0], targetFile); existingTargetItem = target.AddFromFileCopy(sourceItem.FileNames[0]); } else { Log.Debug("Adding link to file '{0}'", sourceItem.FileNames[0]); try { // Linked file existingTargetItem = target.AddFromFile(sourceItem.FileNames[0]); } catch (Exception ex) { var messageService = ServiceLocator.Default.ResolveType<IMessageService>(); messageService.ShowError(ex); } } } else { Log.Debug("Adding folder '{0}'", sourceItem.FileNames[0]); string targetDirectory = sourceItem.GetTargetFileName(target.ContainingProject); existingTargetItem = Directory.Exists(targetDirectory) ? target.AddFromDirectory(targetDirectory) : target.AddFolder(sourceItem.Name); } if (existingTargetItem != null) { Log.Debug("Added item '{0}'", existingTargetItem.Name); } } bool isResourceFile = sourceItem.IsResourceFile(); if (isResourceFile) { SynchronizeResourceFileProperties(sourceItem, existingTargetItem, targetProjectType); } if (containsSubItems && !isResourceFile) { AddFilesAndFolders(sourceItem.ProjectItems, existingTargetItem.ProjectItems, targetProjectType, levels, fileFilter); } } Log.Debug("Added files and folders to target '{0}'", targetParentName); }
private void generateDataset(string datasetFilename, string datasetClassName) { if (datasetFilename == null || datasetFilename == "") { throw new Exception("No schema filename specified"); } if (this.checkedListBoxAdapters.CheckedItems.Count == 0) { throw new Exception("No data adapter items selected."); } int extensionStart = datasetFilename.LastIndexOf('.'); if (extensionStart == -1) { throw new Exception("Invalid data set filename " + extensionStart); } string datasetName = datasetFilename.Substring(0, extensionStart); VirtuosoDataAdapter adapter; DataSet targetDataSet = new DataSet(); DataSet sourceDataSet; for (int index = 0; index < checkedListBoxAdapters.CheckedItems.Count; index++) { adapter = null; foreach (IComponent c in _host.Container.Components) { if (c is VirtuosoDataAdapter && c.ToString() == this.checkedListBoxAdapters.CheckedItems[index].ToString()) { adapter = (VirtuosoDataAdapter)c; break; } } if (adapter == null) { throw new Exception("Inconsistency, failed to locate data adapter"); } sourceDataSet = new DataSet(); try { adapter.MissingSchemaAction = MissingSchemaAction.Add; if (adapter.MissingMappingAction == MissingMappingAction.Error) { adapter.MissingMappingAction = MissingMappingAction.Ignore; } DataTable [] tables = adapter.FillSchema(sourceDataSet, SchemaType.Mapped); // // Set all string columns to length -1 so that the xml schema file // generates correctly // foreach (DataTable table in tables) { foreach (DataColumn column in table.Columns) { if (column.DataType == typeof(string)) { column.MaxLength = -1; } } } // // Merge data table into main data set // foreach (DataTable table in tables) { if (!targetDataSet.Tables.Contains(table.TableName)) { targetDataSet.Merge(table); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } // // Locate project items collection where .xsd file should be added // if (_projectItem == null || _projectItem.Collection == null) { throw new ApplicationException("No project information available. Unable to generate data set file."); } object parent = _projectItem.Collection.Parent; ProjectItems projectItems = null; while (parent != null) { if ((parent as Project) != null) { // // The parent was the project node! // projectItems = ((Project)parent).ProjectItems; break; } if ((parent as ProjectItem) == null) { // // Parent node was not a project and not a project item... // break; } if (string.Compare(((ProjectItem)parent).Kind, EnvDTE.Constants.vsProjectItemKindPhysicalFolder, true, System.Globalization.CultureInfo.InvariantCulture) != 0) { // // Add .xsd file to folder // projectItems = ((ProjectItem)parent).ProjectItems; break; } parent = ((ProjectItem)parent).Collection.Parent; } Type xsdType = null; if (datasetClassName != null) { xsdType = _host.GetType(datasetClassName); } // // Now merge the existing data set into the target // if (datasetClassName != null && xsdType != null) { ConstructorInfo constructor = xsdType.GetConstructor(new Type[] {}); if (constructor != null) { sourceDataSet = (DataSet)constructor.Invoke(null); if (sourceDataSet != null) { foreach (DataTable table in sourceDataSet.Tables) { if (!targetDataSet.Tables.Contains(table.TableName)) { targetDataSet.Merge(table); } } } } } // // Calculate filename for dataset XML schema file // if (_projectItem.Properties == null) { throw new ApplicationException("Unable to locate project item properties."); } if (_projectItem.Properties.Item("FullPath") == null) { throw new ApplicationException("Unable to resolve full path of the dataset file."); } string xsdFilename = Path.Combine(Path.GetDirectoryName( (string)_projectItem.Properties.Item("FullPath").Value), datasetFilename); ProjectItem xsdItem = projectItems.DTE.Solution.FindProjectItem(xsdFilename); if (datasetClassName == null) { if (xsdItem != null || File.Exists(xsdFilename)) { if (MessageBox.Show(this, "File " + xsdFilename + " already exists. Overwrite?", "Overwrite Schema File", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) { DialogResult = DialogResult.None; return; } } } targetDataSet.Namespace = "http://www.tempuri.org/" + datasetName + ".xsd"; targetDataSet.DataSetName = datasetName; targetDataSet.WriteXmlSchema(xsdFilename); // // Add the .xsd file to the project, unless it already existed // if (xsdItem == null) { xsdItem = projectItems.AddFromFileCopy(xsdFilename); } // // Set the CustomTool property to "MSDataSetGenerator" // if (xsdItem != null && xsdItem.Properties != null) { Property custToolsProp = xsdItem.Properties.Item("CustomTool"); if (custToolsProp != null) { if (custToolsProp.Value.Equals(string.Empty)) { custToolsProp.Value = "MSDataSetGenerator"; } } else { VSProjectItem vsProjectItem = (VSProjectItem)xsdItem.Object; vsProjectItem.RunCustomTool(); } } // // Add a component to the designer if none exists // foreach (IComponent c in _host.Container.Components) { if (c is DataSet) { if (String.Compare(((DataSet)c).DataSetName, datasetName, true) == 0) { // // Found one, done! // return; } } } if (xsdType == null) { // // Figure out the fully qualified namespace name // Property namespaceProp = null; if ((parent as Project) != null) { namespaceProp = ((Project)parent).Properties.Item("RootNamespace"); } else if ((parent as ProjectItem) != null) { namespaceProp = ((ProjectItem)parent).Properties.Item("DefaultNamespace"); } if (namespaceProp != null) { xsdType = _host.GetType(namespaceProp.Value + "." + datasetName); } } // // Add the component to the designer // if (xsdType != null) { if (_host.Container.Components[datasetName] == null) { _host.CreateComponent(xsdType, datasetName); } else { _host.CreateComponent(xsdType); } } }
///------------------------------------------------------------------------------------------------------------- /// <summary> /// Gets a VshierarchyItem for the designer file if possible. /// Will create new file if specified and not existing. /// </summary> ///------------------------------------------------------------------------------------------------------------- protected virtual VsHierarchyItem GetDesignerItem(VsHierarchyItem itemCode, bool create) { VsHierarchyItem itemDesigner = null; if (itemCode != null) { // Calculate codebehind and designer file paths string codeBehindFile = itemCode.FullPath(); string designerFile = null; if (_isPartialClassDisabled) { designerFile = codeBehindFile; } else if (!string.IsNullOrEmpty(codeBehindFile)) { designerFile = codeBehindFile.Insert(codeBehindFile.LastIndexOf("."), ".designer"); } // Try to locate existing designer file if (!string.IsNullOrEmpty(designerFile)) { itemDesigner = VsHierarchyItem.CreateFromMoniker(designerFile, _hierarchy); if (itemDesigner != null) { return itemDesigner; } } // Create empty designer file if requested if (create && !string.IsNullOrEmpty(designerFile)) { ProjectItem projectItemCode = itemCode.ProjectItem(); if (projectItemCode != null) { ProjectItems projectItems = projectItemCode.Collection; if (projectItems != null) { try { using (StreamWriter sw = File.CreateText(designerFile)) { sw.WriteLine(" "); } projectItems.AddFromFileCopy(designerFile); } catch { } itemDesigner = VsHierarchyItem.CreateFromMoniker(designerFile, _hierarchy); if (itemDesigner != null) { return itemDesigner; } } } } } return itemDesigner; }
private static void AddFromItemFilePath(Project project, ProjectItems items, NewItemDynamicParameters p) { items.AddFromFileCopy(p.ItemFilePath); }
/// <summary> /// Add the file to the ProjectItems. /// </summary> /// <param name="items"> The item under which to add the file. </param> /// <param name="fileName"> The source file name. </param> /// <param name="fileToAdd"> The target file name. </param> /// <returns> /// Returns the newly added project item. /// </returns> protected virtual ProjectItem AddFromFileCopy(ProjectItems items, string fileName, string fileToAdd) { return(items.AddFromFileCopy(fileName)); }
/// <summary> /// Adds the item. /// </summary> /// <param name="project">The project.</param> /// <param name="projectItems">The project items.</param> private void AddItem(Project project, ProjectItems projectItems) { if(!overwriteItemIfExists) { outputProjectItem = DteHelper.FindItemByName(projectItems, Path.GetFileName(sourceFilePath), false); if (outputProjectItem == null) { outputProjectItem = projectItems.AddFromFileCopy(sourceFilePath); } } else { File.Copy(sourceFilePath, Path.Combine(projectItem.Properties.Item("FullPath").Value.ToString(), Path.GetFileName(sourceFilePath)), true); } }
/// <summary> /// 将一个已经存在的文件加入项目 /// </summary> /// <param name="projectItems">某个项目下面的ProjectItems</param> /// <param name="path">要加入的文件的路径</param> public void CreateDocumentFromCopy(ProjectItems projectItems, string path) { if (VSSolution.CurrentSolution2 != null) { if (!File.Exists(path)) { throw new NullReferenceException("要加载的文件不存在"); } string givingName = path.Substring(path.LastIndexOf('\\') + 1, path.LastIndexOf('.') - path.LastIndexOf('\\') - 1); //检测是否已经存在该文件 List<ProjectItem> allFileProjectItem = GetAllFileProjectItem(projectItems); ProjectItem projectItem = allFileProjectItem.Find(i => i.Name == givingName); if (projectItem != null) { MessageBox.Show("已经存在给定的文件"); } else { try { projectItems.AddFromFileCopy(path); } catch (COMException e) { MessageBox.Show(e.Message); } } } }
/// <summary> /// This will generate an early-bound wrapper for WMI class, /// add it as a source file to the current project; instantiate /// the newly-generated type and return it as a drag component. /// </summary> /// <param name="designerHost"> </param> public override IComponent[] CreateDragComponents(IDesignerHost designerHost) { try { Project[] projects = VSUtils.GetProjects(GetNodeSite()); if (projects == null) { return(null); } //This is an assumtion that's working so far. //TODO: verify this is the right way to determine the startup project //in the solution: Project curProject = projects[0]; ProjectItems projItems = curProject.ProjectItems; if (projItems == null) { return(null); } string curProjSuffix = VSUtils.MapProjectGuidToSuffix(new Guid(curProject.Kind)); if (curProjSuffix == string.Empty) { //neither a VB nor a CS project throw new Exception(WMISys.GetString("WMISE_Invalid_Project_Type_For_CodeGen")); } Guid curProjectType = new Guid(curProject.Kind); string wrapperFileName = className + "." + curProjSuffix; CodeTypeDeclaration newType = null; if (!mgmtClassObj.GetStronglyTypedClassCode(true, true, out newType)) { throw new Exception(WMISys.GetString("WMISE_Code_Generation_Failed")); } ICodeGenerator cg = VSUtils.MapProjectGuidToCodeGenerator(curProjectType); //construct generated code Namespace name (in the form "System.Management.root.cimv2") string[] nsParts = nsName.ToLower().Split(new Char[] { '\\' }); string codeNSName = "System.Management"; for (int i = 0; i < nsParts.Length; i++) { codeNSName += nsParts[i] + "."; } codeNSName = codeNSName.Substring(0, codeNSName.Length - 1); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(codeNSName); // Add imports to the code cn.Imports.Add(new CodeNamespaceImport("System")); cn.Imports.Add(new CodeNamespaceImport("System.ComponentModel")); cn.Imports.Add(new CodeNamespaceImport("System.Management")); cn.Imports.Add(new CodeNamespaceImport("System.Collections")); // Add class to the namespace cn.Types.Add(newType); //Now create the output file TextWriter tw = new StreamWriter(new FileStream(Path.GetTempPath() + "\\" + wrapperFileName, FileMode.Create)); // And write it to the file cg.GenerateCodeFromNamespace(cn, tw, new CodeGeneratorOptions()); ProjectItem newItem = projItems.AddFromFileCopy(Path.GetTempPath() + "\\" + wrapperFileName); if (newItem == null) { throw new Exception(WMISys.GetString("WMISE_Could_Not_Add_File_to_Project")); } File.Delete(Path.GetTempPath() + "\\" + wrapperFileName); Object comp = Activator.CreateInstance(designerHost.GetType(codeNSName + "." + newType.Name)); if (comp == null) { throw new Exception(WMISys.GetString("WMISE_Could_Not_Instantiate_Management_Class")); } return(new IComponent[] { (IComponent)comp }); //The commented-out block below implements the solution with VS custom code generator: /* * //create a new file containing the path to the instance object * string tempFileName = Path.GetTempPath() + this.className + ".wmi"; * StreamWriter sw = File.AppendText(tempFileName); * if (sw == null) * { * return null; * } * * sw.WriteLine(WmiHelper.MakeClassPath(this.serverName, * this.nsName, * this.className)); * * sw.Flush(); * sw.Close(); * ProjectItem newItem = projItems.AddFromFileCopy(tempFileName); * if (newItem == null) * { * return null; * } * File.Delete(tempFileName); * VSUtils.SetGenerator(newItem, "WMICodeGenerator"); * return null; //is this OK??? */ } catch (Exception exc) { MessageBox.Show(WMISys.GetString("WMISE_Exception", exc.Message, exc.StackTrace)); return(null); } }