Ejemplo n.º 1
0
        void CreateManifest()
        {
            string manifestFile = Path.Combine(base.BaseDirectory, "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", EditorControlService.GlobalOptions.IndentationString);
                File.WriteAllText(manifestFile, defaultManifest, System.Text.Encoding.UTF8);
                FileService.FireFileCreated(manifestFile, false);
            }

            if (!base.Project.IsFileInProject(manifestFile))
            {
                FileProjectItem newItem = new FileProjectItem(base.Project, ItemType.None);
                newItem.Include = "app.manifest";
                ProjectService.AddProjectItem(base.Project, newItem);
                ProjectBrowserPad.RefreshViewAsync();
            }

            FileService.OpenFile(manifestFile);

            if (!manifestItems.Contains("app.manifest"))
            {
                manifestItems.Insert(newManifestInsertPosition, "app.manifest");
            }
            this.applicationManifestComboBox.SelectedIndex = manifestItems.IndexOf("app.manifest");
        }
Ejemplo n.º 2
0
        /// <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);
        }
Ejemplo n.º 3
0
        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);
            var                 formattingOptions = CSharpFormattingPolicies.Instance.GetProjectOptions(compilation.GetProject());
            CSharpOutputVisitor visitor           = new CSharpOutputVisitor(new StringWriter(newCode), formattingOptions.OptionsContainer.GetEffectiveOptions());

            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();
            }
        }
        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;
            }
        }
Ejemplo n.º 5
0
        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);
        }
Ejemplo n.º 6
0
        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;
            }
        }
Ejemplo n.º 7
0
        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);
        }