public void SetUpFixture()
        {
            RubyMSBuildEngineHelper.InitMSBuildEngine();

            List <ProjectBindingDescriptor> bindings = new List <ProjectBindingDescriptor>();

            using (TextReader reader = RubyBindingAddInFile.ReadAddInFile()) {
                AddIn addin = AddIn.Load(reader, String.Empty);
                bindings.Add(new ProjectBindingDescriptor(AddInHelper.GetCodon(addin, "/SharpDevelop/Workbench/ProjectBindings", "Ruby")));
            }
            ProjectBindingService.SetBindings(bindings);

            convertProjectCommand           = new DerivedConvertProjectToRubyProjectCommand();
            parseInfo                       = new ParseInformation(new DefaultCompilationUnit(new DefaultProjectContent()));
            convertProjectCommand.ParseInfo = parseInfo;
            convertProjectCommand.FileServiceDefaultEncoding = Encoding.Unicode;

            sourceProject           = new MockProject();
            sourceProject.Directory = @"d:\projects\test";
            source        = new FileProjectItem(sourceProject, ItemType.Compile, @"src\Program.cs");
            targetProject = (RubyProject)convertProjectCommand.CallCreateProject(@"d:\projects\test\converted", sourceProject);
            target        = new FileProjectItem(targetProject, source.ItemType, source.Include);
            source.CopyMetadataTo(target);

            textFileSource = new FileProjectItem(sourceProject, ItemType.None, @"src\readme.txt");
            textFileTarget = new FileProjectItem(targetProject, textFileSource.ItemType, textFileSource.Include);
            textFileSource.CopyMetadataTo(textFileTarget);

            convertProjectCommand.AddParseableFileContent(source.FileName, sourceCode);

            convertProjectCommand.CallConvertFile(source, target);
            convertProjectCommand.CallConvertFile(textFileSource, textFileTarget);
        }
Пример #2
0
        public static void AddProject(ISolutionFolderNode solutionFolderNode, string fileName)
        {
            if (solutionFolderNode == null)
            {
                throw new ArgumentNullException("solutionFolderNode");
            }
            ProjectLoadInformation loadInfo = new ProjectLoadInformation(solutionFolderNode.Solution, fileName, Path.GetFileNameWithoutExtension(fileName));

            AddProject(solutionFolderNode, ProjectBindingService.LoadProject(loadInfo));
        }
Пример #3
0
        MethodExtractorBase GetCurrentExtractor(ITextEditor editor)
        {
            switch (ProjectBindingService.GetCodonPerCodeFileName(editor.FileName).Language)
            {
            case "C#":
                return(new CSharpMethodExtractor(editor));

            default:
                MessageService.ShowError(string.Format(StringParser.Parse("${res:AddIns.SharpRefactoring.ExtractMethodNotSupported}"), ProjectBindingService.GetCodonPerCodeFileName(editor.FileName).Language));
                return(null);
            }
        }
        public void SetUpFixture()
        {
            PythonMSBuildEngineHelper.InitMSBuildEngine();

            List <ProjectBindingDescriptor> bindings = new List <ProjectBindingDescriptor>();

            using (TextReader reader = PythonBindingAddInFile.ReadAddInFile()) {
                AddIn addin = AddIn.Load(reader, String.Empty);
                bindings.Add(new ProjectBindingDescriptor(AddInHelper.GetCodon(addin, "/SharpDevelop/Workbench/ProjectBindings", "Python")));
            }
            ProjectBindingService.SetBindings(bindings);

            // Set up IProjectContent so the ConvertProjectToPythonProjectCommand can
            // locate the startup object and determine it's filename.

            mockProjectContent = new ICSharpCode.Scripting.Tests.Utils.MockProjectContent();
            MockClass mainClass = new MockClass(mockProjectContent, startupObject);

            mainClass.CompilationUnit.FileName = @"d:\projects\test\src\Main2.cs";
            mockProjectContent.SetClassToReturnFromGetClass(startupObject, mainClass);

            convertProjectCommand = new DerivedConvertProjectToPythonProjectCommand();
            convertProjectCommand.ProjectContent             = mockProjectContent;
            convertProjectCommand.FileServiceDefaultEncoding = Encoding.Unicode;

            Solution solution = new Solution(new MockProjectChangeWatcher());

            sourceProject = new MSBuildBasedProject(
                new ProjectCreateInformation()
            {
                Solution = solution,
                OutputProjectFileName = @"d:\projects\test\source.csproj",
                ProjectName           = "source"
            });
            sourceProject.Parent = solution;
            sourceProject.SetProperty(null, null, "StartupObject", startupObject, PropertyStorageLocations.Base, true);
            mainFile      = new FileProjectItem(sourceProject, ItemType.Compile, @"src\Main.cs");
            targetProject = (PythonProject)convertProjectCommand.CallCreateProject(@"d:\projects\test\converted", sourceProject);
            convertProjectCommand.CallCopyProperties(sourceProject, targetProject);
            targetMainFile = new FileProjectItem(targetProject, mainFile.ItemType, mainFile.Include);
            mainFile.CopyMetadataTo(targetMainFile);

            main2File       = new FileProjectItem(sourceProject, ItemType.Compile, @"src\Main2.cs");
            targetMain2File = new FileProjectItem(targetProject, main2File.ItemType, main2File.Include);
            main2File.CopyMetadataTo(targetMain2File);

            convertProjectCommand.AddParseableFileContent(mainFile.FileName, mainSource);
            convertProjectCommand.AddParseableFileContent(main2File.FileName, main2Source);

            convertProjectCommand.CallConvertFile(mainFile, targetMainFile);
            convertProjectCommand.CallConvertFile(main2File, targetMain2File);
        }
Пример #5
0
        public void AddReference()
        {
            foreach (ListViewItem item in SelectedItems)
            {
                IProject        project = (IProject)item.Tag;
                IProjectBinding binding = ProjectBindingService.GetBindingPerLanguageName(project.Language);

                selectDialog.AddReference(
                    project.Name, "Project", project.OutputAssemblyFullPath,
                    new ProjectReferenceProjectItem(selectDialog.ConfigureProject, project)
                    );
            }
        }
Пример #6
0
        string GetProxyFileNameExtension(string language)
        {
            ProjectBindingDescriptor binding = ProjectBindingService.GetCodonPerLanguageName(language);

            if (binding != null)
            {
                string[] extensions = binding.CodeFileExtensions;
                if (extensions.Length > 0)
                {
                    return(extensions[0]);
                }
            }
            throw new NotSupportedException("Unsupported language: " + language);
        }
Пример #7
0
        protected virtual IProject CreateProject(string targetProjectDirectory, IProject sourceProject)
        {
            ProjectCreateInformation info = new ProjectCreateInformation();

            info.Solution        = sourceProject.ParentSolution;
            info.ProjectBasePath = targetProjectDirectory;
            info.ProjectName     = sourceProject.Name + ".Converted";
            info.RootNamespace   = sourceProject.RootNamespace;

            ProjectBindingDescriptor descriptor = ProjectBindingService.GetCodonPerLanguageName(TargetLanguageName);

            if (descriptor == null || descriptor.Binding == null)
            {
                throw new InvalidOperationException("Cannot get Language Binding for " + TargetLanguageName);
            }

            info.OutputProjectFileName = FileUtility.NormalizePath(Path.Combine(targetProjectDirectory, info.ProjectName + descriptor.ProjectFileExtension));

            return(descriptor.Binding.CreateProject(info));
        }
        public static void InitializeProjectBindings()
        {
            Properties prop = new Properties();

            prop["id"] = "C#";
            prop["supportedextensions"]  = ".cs";
            prop["projectfileextension"] = ".csproj";
            Codon codon1 = new Codon(null, "ProjectBinding", prop, new Condition[0]);

            prop       = new Properties();
            prop["id"] = "VBNet";
            prop["supportedextensions"]  = ".vb";
            prop["projectfileextension"] = ".vbproj";
            Codon codon2 = new Codon(null, "ProjectBinding", prop, new Condition[0]);

            ProjectBindingService.SetBindings(new ProjectBindingDescriptor[] {
                new ProjectBindingDescriptor(codon1),
                new ProjectBindingDescriptor(codon2)
            });
        }
Пример #9
0
        public void SetUpFixture()
        {
            PythonMSBuildEngineHelper.InitMSBuildEngine();

            List <ProjectBindingDescriptor> bindings = new List <ProjectBindingDescriptor>();

            using (TextReader reader = PythonBindingAddInFile.ReadAddInFile()) {
                AddIn addin = AddIn.Load(reader, String.Empty);
                bindings.Add(new ProjectBindingDescriptor(AddInHelper.GetCodon(addin, "/SharpDevelop/Workbench/ProjectBindings", "Python")));
            }
            ProjectBindingService.SetBindings(bindings);

            convertProjectCommand = new DerivedConvertProjectToPythonProjectCommand();
            convertProjectCommand.FileServiceDefaultEncoding = Encoding.Unicode;

            sourceProject           = new MockProject();
            sourceProject.Directory = @"d:\projects\test";
            source        = new FileProjectItem(sourceProject, ItemType.Compile, @"src\Program.cs");
            targetProject = (PythonProject)convertProjectCommand.CallCreateProject(@"d:\projects\test\converted", sourceProject);
            target        = new FileProjectItem(targetProject, source.ItemType, source.Include);
            source.CopyMetadataTo(target);

            textFileSource = new FileProjectItem(sourceProject, ItemType.None, @"src\readme.txt");
            textFileTarget = new FileProjectItem(targetProject, textFileSource.ItemType, textFileSource.Include);
            textFileSource.CopyMetadataTo(textFileTarget);

            foreach (ProjectItem item in targetProject.Items)
            {
                ReferenceProjectItem reference = item as ReferenceProjectItem;
                if ((reference != null) && (reference.Name == "IronPython"))
                {
                    ironPythonReference = reference;
                    break;
                }
            }

            convertProjectCommand.AddParseableFileContent(source.FileName, sourceCode);

            convertProjectCommand.CallConvertFile(source, target);
            convertProjectCommand.CallConvertFile(textFileSource, textFileTarget);
        }
Пример #10
0
 int GetFileFilterIndex(IProject project, IList <FileFilterDescriptor> fileFilters)
 {
     if (project != null)
     {
         ProjectBindingDescriptor projectCodon = ProjectBindingService.GetCodonPerLanguageName(project.Language);
         if (projectCodon != null)
         {
             for (int i = 0; i < fileFilters.Count; ++i)
             {
                 for (int j = 0; j < projectCodon.CodeFileExtensions.Length; ++j)
                 {
                     if (fileFilters[i].ContainsExtension(projectCodon.CodeFileExtensions[j]))
                     {
                         return(i + 1);
                     }
                 }
             }
         }
     }
     return(0);
 }
Пример #11
0
        //Show prompt, create files from template, create project, execute command, save project
        public IProject CreateProject(ProjectCreateInformation projectCreateInformation, string defaultLanguage)
        {
            // remember old outerProjectBasePath
            string outerProjectBasePath = projectCreateInformation.ProjectBasePath;
            string outerProjectName     = projectCreateInformation.ProjectName;

            try
            {
                projectCreateInformation.ProjectBasePath = Path.Combine(projectCreateInformation.ProjectBasePath, this.relativePath);
                if (!Directory.Exists(projectCreateInformation.ProjectBasePath))
                {
                    Directory.CreateDirectory(projectCreateInformation.ProjectBasePath);
                }

                string language = string.IsNullOrEmpty(languageName) ? defaultLanguage : languageName;
                ProjectBindingDescriptor descriptor   = ProjectBindingService.GetCodonPerLanguageName(language);
                IProjectBinding          languageinfo = (descriptor != null) ? descriptor.Binding : null;

                if (languageinfo == null)
                {
                    MessageService.ShowError(
                        StringParser.Parse("${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.CantCreateProjectWithTypeError}",
                                           new StringTagPair("type", language)));
                    return(null);
                }

                string newProjectName  = StringParser.Parse(name, new StringTagPair("ProjectName", projectCreateInformation.ProjectName));
                string projectLocation = Path.GetFullPath(Path.Combine(projectCreateInformation.ProjectBasePath,
                                                                       newProjectName + ProjectBindingService.GetProjectFileExtension(language)));


                StringBuilder standardNamespace = new StringBuilder();
                // filter 'illegal' chars from standard namespace
                if (newProjectName != null && newProjectName.Length > 0)
                {
                    char ch = '.';
                    for (int i = 0; i < newProjectName.Length; ++i)
                    {
                        if (ch == '.')
                        {
                            // at beginning or after '.', only a letter or '_' is allowed
                            ch = newProjectName[i];
                            if (!Char.IsLetter(ch))
                            {
                                standardNamespace.Append('_');
                            }
                            else
                            {
                                standardNamespace.Append(ch);
                            }
                        }
                        else
                        {
                            ch = newProjectName[i];
                            // can only contain letters, digits or '_'
                            if (!Char.IsLetterOrDigit(ch) && ch != '.')
                            {
                                standardNamespace.Append('_');
                            }
                            else
                            {
                                standardNamespace.Append(ch);
                            }
                        }
                    }
                }

                projectCreateInformation.OutputProjectFileName = projectLocation;
                projectCreateInformation.RootNamespace         = standardNamespace.ToString();
                projectCreateInformation.ProjectName           = newProjectName;

                StringParserPropertyContainer.FileCreation["StandardNamespace"] = projectCreateInformation.RootNamespace;

                if (File.Exists(projectLocation))
                {
                    if (!MessageService.AskQuestion(
                            StringParser.Parse("${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.OverwriteProjectQuestion}",
                                               new StringTagPair("projectLocation", projectLocation)),
                            "${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.OverwriteQuestion.InfoName}"))
                    {
                        return(null);                        //The user doesnt want to overwrite the project...
                    }
                }

                //Show prompt if any of the files exist
                StringBuilder existingFileNames = new StringBuilder();
                foreach (FileDescriptionTemplate file in files)
                {
                    string fileName = Path.Combine(projectCreateInformation.ProjectBasePath, StringParser.Parse(file.Name, new string[, ] {
                        { "ProjectName", projectCreateInformation.ProjectName }
                    }));

                    if (File.Exists(fileName))
                    {
                        if (existingFileNames.Length > 0)
                        {
                            existingFileNames.Append(", ");
                        }
                        existingFileNames.Append(Path.GetFileName(fileName));
                    }
                }

                bool overwriteFiles = true;
                if (existingFileNames.Length > 0)
                {
                    if (!MessageService.AskQuestion(
                            StringParser.Parse("${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.OverwriteQuestion}",
                                               new StringTagPair("fileNames", existingFileNames.ToString())),
                            "${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.OverwriteQuestion.InfoName}"))
                    {
                        overwriteFiles = false;
                    }
                }



                #region Copy files to target directory
                foreach (FileDescriptionTemplate file in files)
                {
                    string fileName = Path.Combine(projectCreateInformation.ProjectBasePath, StringParser.Parse(file.Name, new string[, ] {
                        { "ProjectName", projectCreateInformation.ProjectName }
                    }));
                    if (File.Exists(fileName) && !overwriteFiles)
                    {
                        continue;
                    }

                    try
                    {
                        if (!Directory.Exists(Path.GetDirectoryName(fileName)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                        }
                        if (!String.IsNullOrEmpty(file.BinaryFileName))
                        {
                            // Binary content
                            File.Copy(file.BinaryFileName, fileName);
                        }
                        else
                        {
                            // Textual content
                            StreamWriter sr          = new StreamWriter(File.Create(fileName), ParserService.DefaultFileEncoding);
                            string       fileContent = StringParser.Parse(file.Content, new string[, ] {
                                { "ProjectName", projectCreateInformation.ProjectName }, { "FileName", fileName }
                            });
                            fileContent = StringParser.Parse(fileContent);
                            if (EditorControlService.GlobalOptions.IndentationString != "\t")
                            {
                                fileContent = fileContent.Replace("\t", EditorControlService.GlobalOptions.IndentationString);
                            }
                            sr.Write(fileContent);
                            sr.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageService.ShowException(ex, "Exception writing " + fileName);
                    }
                }
                #endregion

                #region Create Project
                IProject project;
                try {
                    project = languageinfo.CreateProject(projectCreateInformation);
                } catch (ProjectLoadException ex) {
                    MessageService.ShowError(ex.Message);
                    return(null);
                }
                #endregion

                #region Create Project Items, Imports and Files
                // Add Project items
                if (project is IProjectItemListProvider)
                {
                    foreach (ProjectItem projectItem in projectItems)
                    {
                        ProjectItem newProjectItem = new UnknownProjectItem(
                            project,
                            StringParser.Parse(projectItem.ItemType.ItemName),
                            StringParser.Parse(projectItem.Include)
                            );
                        foreach (string metadataName in projectItem.MetadataNames)
                        {
                            string metadataValue = projectItem.GetMetadata(metadataName);
                            // if the input contains any special MSBuild sequences, don't escape the value
                            // we want to escape only when the special characters are introduced by the StringParser.Parse replacement
                            if (metadataValue.Contains("$(") || metadataValue.Contains("%"))
                            {
                                newProjectItem.SetMetadata(StringParser.Parse(metadataName), StringParser.Parse(metadataValue));
                            }
                            else
                            {
                                newProjectItem.SetEvaluatedMetadata(StringParser.Parse(metadataName), StringParser.Parse(metadataValue));
                            }
                        }
                        ((IProjectItemListProvider)project).AddProjectItem(newProjectItem);
                    }
                }

                // Add Imports
                if (clearExistingImports || projectImports.Count > 0)
                {
                    MSBuildBasedProject msbuildProject = project as MSBuildBasedProject;
                    if (msbuildProject == null)
                    {
                        throw new Exception("<Imports> may be only used in project templates for MSBuildBasedProjects");
                    }
                    try {
                        msbuildProject.PerformUpdateOnProjectFile(
                            delegate {
                            var projectFile = msbuildProject.MSBuildProjectFile;
                            if (clearExistingImports)
                            {
                                foreach (var import in projectFile.Imports.ToArray())
                                {
                                    projectFile.RemoveChild(import);
                                }
                            }
                            foreach (Import projectImport in projectImports)
                            {
                                projectFile.AddImport(projectImport.Key).Condition = projectImport.Value;
                            }
                        });
                    } catch (InvalidProjectFileException ex) {
                        if (string.IsNullOrEmpty(importsFailureMessage))
                        {
                            MessageService.ShowError("Error creating project:\n" + ex.Message);
                        }
                        else
                        {
                            MessageService.ShowError(importsFailureMessage + "\n\n" + ex.Message);
                        }
                        return(null);
                    }
                }

                if (projectProperties.Count > 0)
                {
                    if (!(project is MSBuildBasedProject))
                    {
                        throw new Exception("<PropertyGroup> may be only used in project templates for MSBuildBasedProjects");
                    }

                    foreach (ProjectProperty p in projectProperties)
                    {
                        ((MSBuildBasedProject)project).SetProperty(
                            StringParser.Parse(p.Configuration),
                            StringParser.Parse(p.Platform),
                            StringParser.Parse(p.Name),
                            StringParser.Parse(p.Value),
                            p.Location,
                            p.ValueIsLiteral
                            );
                    }
                }

                // Add Files
                if (project is IProjectItemListProvider)
                {
                    foreach (FileDescriptionTemplate file in files)
                    {
                        string fileName = Path.Combine(projectCreateInformation.ProjectBasePath, StringParser.Parse(file.Name, new string[, ] {
                            { "ProjectName", projectCreateInformation.ProjectName }
                        }));
                        FileProjectItem projectFile = new FileProjectItem(project, project.GetDefaultItemType(fileName));

                        projectFile.Include = FileUtility.GetRelativePath(project.Directory, fileName);

                        file.SetProjectItemProperties(projectFile);

                        ((IProjectItemListProvider)project).AddProjectItem(projectFile);
                    }
                }

                #endregion

                RunCreateActions(project);

                project.ProjectCreationComplete();

                // Save project
                project.Save();


                projectCreateInformation.createdProjects.Add(project);
                ProjectService.OnProjectCreated(new ProjectEventArgs(project));
                return(project);
            }
            finally
            {
                // set back outerProjectBasePath
                projectCreateInformation.ProjectBasePath = outerProjectBasePath;
                projectCreateInformation.ProjectName     = outerProjectName;
            }
        }
Пример #12
0
        static void LoadProjectInternal(string fileName)
        {
            if (!Path.IsPathRooted(fileName))
            {
                throw new ArgumentException("Path must be rooted!");
            }
            string solutionFile = Path.ChangeExtension(fileName, ".sln");

            if (File.Exists(solutionFile))
            {
                LoadSolutionInternal(solutionFile);

                if (openSolution != null)
                {
                    bool found = false;
                    foreach (IProject p in openSolution.Projects)
                    {
                        if (FileUtility.IsEqualFileName(fileName, p.FileName))
                        {
                            found = true;
                            break;
                        }
                    }
                    if (found == false)
                    {
                        var parseArgs = new[] { new StringTagPair("SolutionName", Path.GetFileName(solutionFile)), new StringTagPair("ProjectName", Path.GetFileName(fileName)) };
                        int res       = MessageService.ShowCustomDialog(MessageService.ProductName,
                                                                        StringParser.Parse("${res:ICSharpCode.SharpDevelop.Commands.OpenCombine.SolutionDoesNotContainProject}", parseArgs),
                                                                        0, 2,
                                                                        StringParser.Parse("${res:ICSharpCode.SharpDevelop.Commands.OpenCombine.SolutionDoesNotContainProject.AddProjectToSolution}", parseArgs),
                                                                        StringParser.Parse("${res:ICSharpCode.SharpDevelop.Commands.OpenCombine.SolutionDoesNotContainProject.CreateNewSolution}", parseArgs),
                                                                        "${res:Global.IgnoreButtonText}");
                        if (res == 0)
                        {
                            // Add project to solution
                            Commands.AddExitingProjectToSolution.AddProject((ISolutionFolderNode)ProjectBrowserPad.Instance.SolutionNode, fileName);
                            SaveSolution();
                            return;
                        }
                        else if (res == 1)
                        {
                            CloseSolution();
                            try {
                                File.Copy(solutionFile, Path.ChangeExtension(solutionFile, ".old.sln"), true);
                            } catch (IOException) {}
                        }
                        else
                        {
                            // ignore, just open the solution
                            return;
                        }
                    }
                    else
                    {
                        // opened solution instead and correctly found the project
                        return;
                    }
                }
                else
                {
                    // some problem during opening, abort
                    return;
                }
            }
            Solution solution = new Solution(new ProjectChangeWatcher(solutionFile));

            solution.Name = Path.GetFileNameWithoutExtension(fileName);
            IProjectBinding binding = ProjectBindingService.GetBindingPerProjectFile(fileName);
            IProject        project;

            if (binding != null)
            {
                project = ProjectBindingService.LoadProject(new ProjectLoadInformation(solution, fileName, solution.Name));
                if (project is UnknownProject)
                {
                    if (((UnknownProject)project).WarningDisplayedToUser == false)
                    {
                        ((UnknownProject)project).ShowWarningMessageBox();
                    }
                    return;
                }
            }
            else
            {
                MessageService.ShowError(StringParser.Parse("${res:ICSharpCode.SharpDevelop.Commands.OpenCombine.InvalidProjectOrCombine}", new StringTagPair("FileName", fileName)));
                return;
            }
            solution.AddFolder(project);
            ProjectSection configSection = solution.GetSolutionConfigurationsSection();

            foreach (string configuration in project.ConfigurationNames)
            {
                foreach (string platform in project.PlatformNames)
                {
                    string key;
                    if (platform == "AnyCPU")                       // Fix for SD2-786
                    {
                        key = configuration + "|Any CPU";
                    }
                    else
                    {
                        key = configuration + "|" + platform;
                    }
                    configSection.Items.Add(new SolutionItem(key, key));
                }
            }
            solution.FixSolutionConfiguration(new IProject[] { project });

            if (FileUtility.ObservedSave((NamedFileOperationDelegate)solution.Save, solutionFile) == FileOperationResult.OK)
            {
                // only load when saved succesfully
                LoadSolution(solutionFile);
            }
        }