void CreateManifest() { string manifestFile = Path.Combine(base.Project.Directory, "app.manifest"); if (!File.Exists(manifestFile)) { string defaultManifest; using (Stream stream = typeof(ApplicationSettings).Assembly.GetManifestResourceStream("Resources.DefaultManifest.manifest")) { if (stream == null) { throw new ResourceNotFoundException("DefaultManifest.manifest"); } using (StreamReader r = new StreamReader(stream)) { defaultManifest = r.ReadToEnd(); } } defaultManifest = defaultManifest.Replace("\t", SD.EditorControlService.GlobalOptions.IndentationString); File.WriteAllText(manifestFile, defaultManifest, System.Text.Encoding.UTF8); FileService.FireFileCreated(manifestFile, false); } if (!base.Project.IsFileInProject(FileName.Create(manifestFile))) { FileProjectItem newItem = new FileProjectItem(base.Project, ItemType.None); newItem.Include = "app.manifest"; ProjectService.AddProjectItem(base.Project, newItem); ProjectBrowserPad.RefreshViewAsync(); } FileService.OpenFile(manifestFile); this.applicationManifestComboBox.Items.Insert(0, "app.manifest"); this.applicationManifestComboBox.SelectedIndex = 0; }
public override void UpgradeProject(CompilerVersion newVersion, TargetFramework newFramework) { PortableTargetFramework newFx = newFramework as PortableTargetFramework; if (newFx != null) { // Convert to portable library Core.AnalyticsMonitorService.TrackFeature(GetType(), "ConvertToPortableLibrary"); var project = (CompilableProject)Project; lock (project.SyncRoot) { if (newVersion != null && GetAvailableCompilerVersions().Contains(newVersion)) { project.SetToolsVersion(newVersion.MSBuildVersion.Major + "." + newVersion.MSBuildVersion.Minor); } project.SetProperty(null, null, "TargetFrameworkProfile", newFx.TargetFrameworkProfile, PropertyStorageLocations.Base, true); project.SetProperty(null, null, "TargetFrameworkVersion", newFx.TargetFrameworkVersion, PropertyStorageLocations.Base, true); // Convert <Imports> project.PerformUpdateOnProjectFile( delegate { foreach (var import in project.MSBuildProjectFile.Imports) { if (import.Project.EndsWith(PortableLibraryProjectBehavior.NormalCSharpTargets, StringComparison.OrdinalIgnoreCase)) { import.Project = PortableLibraryProjectBehavior.PortableTargetsPath + PortableLibraryProjectBehavior.PortableCSharpTargets; break; } else if (import.Project.EndsWith(PortableLibraryProjectBehavior.NormalVBTargets, StringComparison.OrdinalIgnoreCase)) { import.Project = PortableLibraryProjectBehavior.PortableTargetsPath + PortableLibraryProjectBehavior.PortableVBTargets; break; } } }); // Remove references foreach (var referenceItem in project.GetItemsOfType(ItemType.Reference).ToArray()) { // get short assembly name: string assemblyName = referenceItem.Include; if (assemblyName.IndexOf(',') >= 0) { assemblyName = assemblyName.Substring(0, assemblyName.IndexOf(',')); } assemblyName += ","; if (KnownFrameworkAssemblies.FullAssemblyNames.Any(fullName => fullName.StartsWith(assemblyName, StringComparison.OrdinalIgnoreCase))) { // If it's a framework assembly, remove the reference // (portable libraries automatically reference all available framework assemblies) ProjectService.RemoveProjectItem(project, referenceItem); } } project.AddProjectType(ProjectTypeGuids.PortableLibrary); project.Save(); ProjectBrowserPad.RefreshViewAsync(); } } else { base.UpgradeProject(newVersion, newFramework); } }
public override async void Execute(EditorRefactoringContext context) { SyntaxTree st = await context.GetSyntaxTreeAsync().ConfigureAwait(false); ICompilation compilation = await context.GetCompilationAsync().ConfigureAwait(false); CSharpFullParseInformation info = await context.GetParseInformationAsync().ConfigureAwait(false) as CSharpFullParseInformation; EntityDeclaration node = (EntityDeclaration)st.GetNodeAt(context.CaretLocation, n => n is TypeDeclaration || n is DelegateDeclaration); IDocument document = context.Editor.Document; FileName newFileName = FileName.Create(Path.Combine(Path.GetDirectoryName(context.FileName), MakeValidFileName(node.Name))); string header = CopyFileHeader(document, info); string footer = CopyFileEnd(document, info); AstNode newNode = node.Clone(); foreach (var ns in node.Ancestors.OfType <NamespaceDeclaration>()) { var newNS = new NamespaceDeclaration(ns.Name); newNS.Members.AddRange(ns.Children.Where(ch => ch is UsingDeclaration || ch is UsingAliasDeclaration || ch is ExternAliasDeclaration).Select(usingDecl => usingDecl.Clone())); newNS.AddMember(newNode); newNode = newNS; } var topLevelUsings = st.Children.Where(ch => ch is UsingDeclaration || ch is UsingAliasDeclaration || ch is ExternAliasDeclaration); StringBuilder newCode = new StringBuilder(header); CSharpOutputVisitor visitor = new CSharpOutputVisitor(new StringWriter(newCode), FormattingOptionsFactory.CreateSharpDevelop()); foreach (var topLevelUsing in topLevelUsings) { topLevelUsing.AcceptVisitor(visitor); } newNode.AcceptVisitor(visitor); newCode.AppendLine(footer); IViewContent viewContent = FileService.NewFile(newFileName, newCode.ToString()); viewContent.PrimaryFile.SaveToDisk(newFileName); // now that the code is saved in the other file, remove it from the original document RemoveExtractedNode(context, node); IProject project = (IProject)compilation.GetProject(); if (project != null) { FileProjectItem projectItem = new FileProjectItem(project, ItemType.Compile); projectItem.FileName = newFileName; ProjectService.AddProjectItem(project, projectItem); FileService.FireFileCreated(newFileName, false); project.Save(); ProjectBrowserPad.RefreshViewAsync(); } }
void SaveAndOpenNewClassDiagram(IProject p, string filename, XmlDocument xmlDocument) { xmlDocument.Save(filename); FileProjectItem fpi = new FileProjectItem(p, ItemType.Content); fpi.FileName = filename; ProjectService.AddProjectItem(p, fpi); ProjectBrowserPad.RefreshViewAsync(); p.Save(); FileService.OpenFile(filename); }
public override void UpgradeProject(CompilerVersion newVersion, TargetFramework newFramework) { var project = (CompilableProject)Project; var newFx = newFramework as PortableTargetFramework; if (newFramework != null && newFx == null) { // convert to normal .NET project (not portable) SD.AnalyticsMonitor.TrackFeature(GetType(), "DowngradePortableLibrary"); project.PerformUpdateOnProjectFile( delegate { foreach (var import in project.MSBuildProjectFile.Imports) { if (import.Project.EndsWith(PortableCSharpTargets, StringComparison.OrdinalIgnoreCase)) { import.Project = NormalTargetsPath + NormalCSharpTargets; break; } else if (import.Project.EndsWith(PortableVBTargets, StringComparison.OrdinalIgnoreCase)) { import.Project = NormalTargetsPath + NormalVBTargets; break; } } }); project.RemoveProjectType(ProjectTypeGuids.PortableLibrary); AddReferenceIfNotExists("System"); AddReferenceIfNotExists("System.Xml"); if (newFramework.Version >= Versions.V3_5) { AddReferenceIfNotExists("System.Core"); } base.UpgradeProject(newVersion, newFramework); return; } lock (project.SyncRoot) { if (newVersion != null && GetAvailableCompilerVersions().Contains(newVersion)) { project.ToolsVersion = newVersion.MSBuildVersion.Major + "." + newVersion.MSBuildVersion.Minor; } if (newFx != null) { project.SetProperty(null, null, "TargetFrameworkProfile", newFx.TargetFrameworkProfile, PropertyStorageLocations.Base, true); project.SetProperty(null, null, "TargetFrameworkVersion", newFx.TargetFrameworkVersion, PropertyStorageLocations.Base, true); } project.Save(); ProjectBrowserPad.RefreshViewAsync(); } }
/// <summary> /// Add files to the current project at the project node. /// </summary> /// <param name="fileNames">list of files that have to be added.</param> internal static void AddFiles(string [] fileNames) { IProject project = ProjectService.CurrentProject; Debug.Assert(project != null); foreach (var file in fileNames) { string relFileName = FileUtility.GetRelativePath(project.Directory, file); FileProjectItem fileProjectItem = new FileProjectItem(project, project.GetDefaultItemType(file), relFileName); FileNode fileNode = new FileNode(file, FileNodeStatus.InProject); fileNode.ProjectItem = fileProjectItem; ProjectService.AddProjectItem(project, fileProjectItem); } project.Save(); ProjectBrowserPad.RefreshViewAsync(); }
void ClearStatusCacheAndEnqueueFile(string fileName) { OverlayIconManager.ClearStatusCache(); ProjectBrowserPad pad = ProjectBrowserPad.Instance; if (pad == null) { return; } FileNode node = pad.ProjectBrowserControl.FindFileNode(fileName); if (node == null) { return; } OverlayIconManager.Enqueue(node); }
public static void AddSessionToProject(this IProject project, string path) { Action updater = () => { if (!File.Exists(path)) { return; } FileService.OpenFile(path); if (!project.IsReadOnly) { FileProjectItem file = new FileProjectItem(project, ItemType.Content, "ProfilingSessions\\" + Path.GetFileName(path)); ProjectService.AddProjectItem(project, file); ProjectBrowserPad.RefreshViewAsync(); project.Save(); } }; SD.MainThread.InvokeIfRequired(updater); }
public static async void UpdateStatusCacheAndEnqueueFile(string fileName) { var item = GetTfsItem(fileName); if (item != null) { await UpdatePendingChanges(item.Workspace); } ProjectBrowserPad pad = ProjectBrowserPad.Instance; if (pad == null) { return; } FileNode node = pad.ProjectBrowserControl.FindFileNode(fileName); if (node == null) { return; } OverlayIconManager.EnqueueParents(node); }
public static void MoveClassToFile(IClass c, string newFileName) { LanguageProperties language = c.ProjectContent.Language; string existingCode = ParserService.GetParseableFileContent(c.CompilationUnit.FileName).Text; DomRegion fullRegion = language.RefactoringProvider.GetFullCodeRangeForType(existingCode, c); if (fullRegion.IsEmpty) { return; } Action removeExtractedCodeAction; string newCode = ExtractCode(c, fullRegion, c.BodyRegion.BeginLine, out removeExtractedCodeAction); newCode = language.RefactoringProvider.CreateNewFileLikeExisting(existingCode, newCode); if (newCode == null) { return; } IViewContent viewContent = FileService.NewFile(newFileName, newCode); viewContent.PrimaryFile.SaveToDisk(newFileName); // now that the code is saved in the other file, remove it from the original document removeExtractedCodeAction(); IProject project = (IProject)c.ProjectContent.Project; if (project != null) { FileProjectItem projectItem = new FileProjectItem(project, ItemType.Compile); projectItem.FileName = newFileName; ProjectService.AddProjectItem(project, projectItem); FileService.FireFileCreated(newFileName, false); project.Save(); ProjectBrowserPad.RefreshViewAsync(); } }
/// <summary> /// Add files to the current project at the project node. /// </summary> /// <param name="fileNames">list of files that have to be added.</param> internal static IEnumerable <FileProjectItem> AddFiles(string[] fileNames, ItemType itemType) { IProject project = ProjectService.CurrentProject; Debug.Assert(project != null); List <FileProjectItem> resultItems = new List <FileProjectItem>(); foreach (string file in fileNames) { FileProjectItem item = project.FindFile(FileName.Create(file)); if (item != null) { continue; // file already belongs to the project } string relFileName = FileUtility.GetRelativePath(project.Directory, file); item = new FileProjectItem(project, itemType, relFileName); ProjectService.AddProjectItem(project, item); resultItems.Add(item); } project.Save(); ProjectBrowserPad.RefreshViewAsync(); return(resultItems); }
public static void ExtractInterface(IClass c) { ExtractInterfaceOptions extractInterface = new ExtractInterfaceOptions(c); using (ExtractInterfaceDialog eid = new ExtractInterfaceDialog()) { extractInterface = eid.ShowDialog(extractInterface); if (extractInterface.IsCancelled) { return; } // do rename /* * MessageService.ShowMessageFormatted("Extracting interface", * @"Extracting {0} [{1}] from {2} into {3}", * extractInterface.NewInterfaceName, * extractInterface.FullyQualifiedName, * extractInterface.ClassEntity.Name, * extractInterface.NewFileName * ); * ` */ } string newInterfaceFileName = Path.Combine(Path.GetDirectoryName(c.CompilationUnit.FileName), extractInterface.NewFileName); if (File.Exists(newInterfaceFileName)) { int confirmReplace = MessageService.ShowCustomDialog("Extract Interface", newInterfaceFileName + " already exists!", 0, 1, "${res:Global.ReplaceButtonText}", "${res:Global.AbortButtonText}"); if (confirmReplace != 0) { return; } } LanguageProperties language = c.ProjectContent.Language; string classFileName = c.CompilationUnit.FileName; string existingClassCode = ParserService.GetParseableFileContent(classFileName).Text; // build the new interface... string newInterfaceCode = language.RefactoringProvider.GenerateInterfaceForClass(extractInterface.NewInterfaceName, existingClassCode, extractInterface.ChosenMembers, c, extractInterface.IncludeComments); if (newInterfaceCode == null) { return; } // ...dump it to a file... IViewContent viewContent = FileService.GetOpenFile(newInterfaceFileName); ITextEditorProvider editable = viewContent as ITextEditorProvider; if (viewContent != null && editable != null) { // simply update it editable.TextEditor.Document.Text = newInterfaceCode; viewContent.PrimaryFile.SaveToDisk(); } else { // create it viewContent = FileService.NewFile(newInterfaceFileName, newInterfaceCode); viewContent.PrimaryFile.SaveToDisk(newInterfaceFileName); // ... and add it to the project IProject project = (IProject)c.ProjectContent.Project; if (project != null) { FileProjectItem projectItem = new FileProjectItem(project, ItemType.Compile); projectItem.FileName = newInterfaceFileName; ProjectService.AddProjectItem(project, projectItem); FileService.FireFileCreated(newInterfaceFileName, false); project.Save(); ProjectBrowserPad.RefreshViewAsync(); } } ICompilationUnit newCompilationUnit = ParserService.ParseFile(newInterfaceFileName).CompilationUnit; IClass newInterfaceDef = newCompilationUnit.Classes[0]; // finally, add the interface to the base types of the class that we're extracting from if (extractInterface.AddInterfaceToClass) { string modifiedClassCode = language.RefactoringProvider.AddBaseTypeToClass(existingClassCode, c, newInterfaceDef); if (modifiedClassCode == null) { return; } // TODO: replacing the whole text is not an option, we would loose all breakpoints/bookmarks. viewContent = FileService.OpenFile(classFileName); editable = viewContent as ITextEditorProvider; if (editable == null) { return; } editable.TextEditor.Document.Text = modifiedClassCode; } }
public override FileTemplateResult Create(FileTemplateOptions options) { FileTemplateResult result = new FileTemplateResult(options); StandardHeader.SetHeaders(); StringParserPropertyContainer.FileCreation["StandardNamespace"] = options.Namespace; StringParserPropertyContainer.FileCreation["FullName"] = options.FileName; StringParserPropertyContainer.FileCreation["FileName"] = Path.GetFileName(options.FileName); StringParserPropertyContainer.FileCreation["FileNameWithoutExtension"] = Path.GetFileNameWithoutExtension(options.FileName); StringParserPropertyContainer.FileCreation["Extension"] = Path.GetExtension(options.FileName); StringParserPropertyContainer.FileCreation["Path"] = Path.GetDirectoryName(options.FileName); StringParserPropertyContainer.FileCreation["ClassName"] = options.ClassName; // when adding a file to a project (but not when creating a standalone file while a project is open): var project = options.Project; if (project != null && !options.IsUntitled) { // add required assembly references to the project foreach (ReferenceProjectItem reference in RequiredAssemblyReferences) { IEnumerable <ProjectItem> refs = project.GetItemsOfType(ItemType.Reference); if (!refs.Any(projItem => string.Equals(projItem.Include, reference.Include, StringComparison.OrdinalIgnoreCase))) { ReferenceProjectItem projItem = (ReferenceProjectItem)reference.CloneFor(project); ProjectService.AddProjectItem(project, projItem); ProjectBrowserPad.RefreshViewAsync(); } } } foreach (FileDescriptionTemplate newfile in FileDescriptionTemplates) { if (!IsFilenameAvailable(StringParser.Parse(newfile.Name))) { MessageService.ShowError(string.Format("Filename {0} is in use.\nChoose another one", StringParser.Parse(newfile.Name))); // TODO : translate return(null); } } ScriptRunner scriptRunner = new ScriptRunner(); foreach (FileDescriptionTemplate newFile in FileDescriptionTemplates) { FileOperationResult opresult = FileUtility.ObservedSave( () => { string resultFile; if (!String.IsNullOrEmpty(newFile.BinaryFileName)) { resultFile = SaveFile(newFile, null, newFile.BinaryFileName, options); } else { resultFile = SaveFile(newFile, scriptRunner.CompileScript(this, newFile), null, options); } if (resultFile != null) { result.NewFiles.Add(FileName.Create(resultFile)); } }, FileName.Create(StringParser.Parse(newFile.Name)) ); if (opresult != FileOperationResult.OK) { return(null); } } if (project != null) { project.Save(); } // raise FileCreated event for the new files. foreach (var fileName in result.NewFiles) { FileService.FireFileCreated(fileName, false); } return(result); }
void CreateProject() { if (categoryTreeView.SelectedNode != null) { ICSharpCode.Core.PropertyService.Set("Dialogs.NewProjectDialog.LastSelectedCategory", TreeViewHelper.GetPath(categoryTreeView.SelectedNode)); ICSharpCode.Core.PropertyService.Set("Dialogs.NewProjectDialog.CategoryTreeState", TreeViewHelper.GetViewStateString(categoryTreeView)); ICSharpCode.Core.PropertyService.Set("Dialogs.NewProjectDialog.LargeImages", largeIconsRadioButton.Checked); } string solution = solutionNameTextBox.Text.Trim(); string name = nameTextBox.Text.Trim(); string location = locationTextBox.Text.Trim(); string projectNameError = CheckProjectName(solution, name, location); if (projectNameError != null) { MessageService.ShowError(projectNameError); return; } if (templateListView.SelectedItems.Count == 1 && locationTextBox.Text.Length > 0 && solutionNameTextBox.Text.Length > 0) { TemplateItem item = (TemplateItem)templateListView.SelectedItems[0]; try { System.IO.Directory.CreateDirectory(NewProjectDirectory); } catch (Exception) { MessageService.ShowError("${res:ICSharpCode.SharpDevelop.Gui.Dialogs.NewProjectDialog.CantCreateDirectoryError}"); return; } ProjectTemplateOptions cinfo = new ProjectTemplateOptions(); if (item.Template.SupportedTargetFrameworks.Any()) { cinfo.TargetFramework = (TargetFramework)targetFrameworkComboBox.SelectedItem; ICSharpCode.Core.PropertyService.Set("Dialogs.NewProjectDialog.TargetFramework", cinfo.TargetFramework.TargetFrameworkVersion); } cinfo.ProjectBasePath = DirectoryName.Create(NewProjectDirectory); cinfo.ProjectName = name; if (createNewSolution) { if (!SD.ProjectService.CloseSolution()) { return; } result = item.Template.CreateAndOpenSolution(cinfo, NewSolutionDirectory, solution); } else { cinfo.Solution = SolutionFolder.ParentSolution; cinfo.SolutionFolder = SolutionFolder; result = item.Template.CreateProjects(cinfo); cinfo.Solution.Save(); } if (result != null) { item.Template.RunOpenActions(result); } ProjectBrowserPad.RefreshViewAsync(); DialogResult = DialogResult.OK; } }
bool CreateProject() { if (SelectedCategory != null) { ICSharpCode.Core.PropertyService.Set("Dialogs.NewProjectDialog.LastSelectedCategory", SelectedCategory.Text); ICSharpCode.Core.PropertyService.Set("Dialogs.NewProjectDialog.LargeImages", SelectedIconSizeIndex); } string solution = SolutionName.Trim(); string name = ProjectName.Trim(); string location = ProjectLocationDirectory.Trim(); string projectNameError = CheckProjectName(solution, name, location); if (projectNameError != null) { MessageService.ShowError(projectNameError); return(false); } if (SelectedTemplate != null && ProjectLocationDirectory.Length > 0 && SolutionName.Length > 0) { TemplateItem item = SelectedTemplate; try { System.IO.Directory.CreateDirectory(NewProjectDirectory); } catch (Exception) { MessageService.ShowError("${res:ICSharpCode.SharpDevelop.Gui.Dialogs.NewProjectDialog.CantCreateDirectoryError}"); return(false); } ProjectTemplateOptions cinfo = new ProjectTemplateOptions(); if (item.Template.SupportedTargetFrameworks.Any()) { cinfo.TargetFramework = SelectedTargetFramework; ICSharpCode.Core.PropertyService.Set("Dialogs.NewProjectDialog.TargetFramework", cinfo.TargetFramework.TargetFrameworkVersion); } cinfo.ProjectBasePath = DirectoryName.Create(NewProjectDirectory); cinfo.ProjectName = name; if (CreateNewSolution) { if (!SD.ProjectService.CloseSolution()) { return(false); } _result = item.Template.CreateAndOpenSolution(cinfo, NewSolutionDirectory, solution); } else { cinfo.Solution = SolutionFolder.ParentSolution; cinfo.SolutionFolder = SolutionFolder; _result = item.Template.CreateProjects(cinfo); cinfo.Solution.Save(); } if (_result != null) { item.Template.RunOpenActions(_result); } ProjectBrowserPad.RefreshViewAsync(); return(true); } return(false); }