Пример #1
0
        void TextAreaTextEntered(object sender, TextCompositionEventArgs e)
        {
            if (e.Text.Length > 0 && !e.Handled)
            {
                ILanguageBinding languageBinding = GetAdapterFromSender(sender).Language;
                if (languageBinding != null && languageBinding.FormattingStrategy != null)
                {
                    char c = e.Text[0];
                    // When entering a newline, AvalonEdit might use either "\r\n" or "\n", depending on
                    // what was passed to TextArea.PerformTextInput. We'll normalize this to '\n'
                    // so that formatting strategies don't have to handle both cases.
                    if (c == '\r')
                    {
                        c = '\n';
                    }
                    languageBinding.FormattingStrategy.FormatLine(GetAdapterFromSender(sender), c);

                    if (c == '\n')
                    {
                        // Immediately parse on enter.
                        // This ensures we have up-to-date CC info about the method boundary when a user
                        // types near the end of a method.
                        ParserService.BeginParse(this.FileName, this.DocumentAdapter.CreateSnapshot());
                    }
                }
            }
        }
Пример #2
0
        protected ILanguageBinding GetLanguageBinding(string language)
        {
            ILanguageBinding binding = LanguageBindingService.GetBindingPerLanguageName(language);

            if (binding == null)
            {
                throw new InvalidOperationException("Language '" + language + "' not found");
            }
            return(binding);
        }
Пример #3
0
        public static IProject LoadProject(IMSBuildEngineProvider provider, string location, string title, string projectTypeGuid)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            if (location == null)
            {
                throw new ArgumentNullException("location");
            }
            if (title == null)
            {
                throw new ArgumentNullException("title");
            }
            if (projectTypeGuid == null)
            {
                throw new ArgumentNullException("projectTypeGuid");
            }

            IProject newProject;

            if (!File.Exists(location))
            {
                newProject          = new MissingProject(location, title);
                newProject.TypeGuid = projectTypeGuid;
            }
            else
            {
                ILanguageBinding binding = LanguageBindingService.GetBindingPerProjectFile(location);
                if (binding != null)
                {
                    try {
                        location = Path.GetFullPath(location);
                    } catch (Exception) {}
                    try {
                        newProject = binding.LoadProject(provider, location, title);
                    } catch (XmlException ex) {
                        newProject          = new UnknownProject(location, title, ex.Message, true);
                        newProject.TypeGuid = projectTypeGuid;
                    } catch (Microsoft.Build.BuildEngine.InvalidProjectFileException ex) {
                        newProject          = new UnknownProject(location, title, ex.Message, true);
                        newProject.TypeGuid = projectTypeGuid;
                    } catch (UnauthorizedAccessException ex) {
                        newProject          = new UnknownProject(location, title, ex.Message, true);
                        newProject.TypeGuid = projectTypeGuid;
                    }
                }
                else
                {
                    newProject          = new UnknownProject(location, title);
                    newProject.TypeGuid = projectTypeGuid;
                }
            }
            return(newProject);
        }
Пример #4
0
        internal void FileNameChanged()
        {
            DetachExtensions();
            extensions = AddInTree.BuildItems <ITextEditorExtension>(extensionsPath, this, false);
            AttachExtensions();

            languageBinding = SD.LanguageService.GetLanguageByFileName(PrimaryView.FileName);

            // update properties set by languageBinding
            this.TextEditor.TextArea.IndentationStrategy = new OptionControlledIndentationStrategy(this, languageBinding.FormattingStrategy);
        }
Пример #5
0
		internal void FileNameChanged()
		{
			if (languageBinding != null)
				languageBinding.Detach();
			
			languageBinding = LanguageBindingService.CreateBinding(this); // never returns null
			languageBinding.Attach(this);
			
			// update properties set by languageBinding
			this.TextEditor.TextArea.IndentationStrategy = new OptionControlledIndentationStrategy(this, languageBinding.FormattingStrategy);
		}
Пример #6
0
		internal void FileNameChanged()
		{
			DetachExtensions();
			extensions = AddInTree.BuildItems<ITextEditorExtension>(extensionsPath, this, false);
			AttachExtensions();
			
			languageBinding = SD.LanguageService.GetLanguageByFileName(PrimaryView.FileName);
			
			// update properties set by languageBinding
			this.TextEditor.TextArea.IndentationStrategy = new OptionControlledIndentationStrategy(this, languageBinding.FormattingStrategy);
		}
        /// <summary>
        /// Creates an item with the specified sub items. And the current
        /// Condition status for this item.
        /// </summary>
        public override object BuildItem(object owner, ArrayList subItems, ConditionCollection conditions)
        {
            //			if (subItems == null || subItems.Count > 0) {
            //				throw new ApplicationException("Tried to buil a command with sub commands, please check the XML definition.");
            //			}
            Debug.Assert(Class != null && Class.Length > 0);

            languageBinding = (ILanguageBinding)AddIn.CreateObject(Class);

            return this;
        }
Пример #8
0
        internal void FileNameChanged()
        {
            if (languageBinding != null)
            {
                languageBinding.Detach();
            }

            languageBinding = LanguageBindingService.CreateBinding(this);             // never returns null
            languageBinding.Attach(this);

            // update properties set by languageBinding
            this.TextEditor.TextArea.IndentationStrategy = new OptionControlledIndentationStrategy(this, languageBinding.FormattingStrategy);
        }
        public void AddReference()
        {
            foreach (ListViewItem item in SelectedItems)
            {
                IProject         project = (IProject)item.Tag;
                ILanguageBinding binding = LanguageBindingService.GetBindingPerLanguageName(project.Language);

                selectDialog.AddReference(
                    project.Name, "Project", project.OutputAssemblyFullPath,
                    new ProjectReferenceProjectItem(selectDialog.ConfigureProject, project)
                    );
            }
        }
Пример #10
0
        public static Ambience GetAmbienceForLanguage(string languageName)
        {
            ILanguageBinding binding = LanguageBindingService.GetBindingPerLanguageName(languageName);

            if (binding != null)
            {
                return(GetAmbienceForFile(binding.GetFileName("a")));
            }
            else
            {
                return(defaultAmbience);
            }
        }
Пример #11
0
        public override void SetUp()
        {
            base.SetUp();
            project.Stub(p => p.Language).Return(null).WhenCalled(mi => mi.ReturnValue = projectLanguage);

            codeGenerator   = MockRepository.GenerateMock <CodeGenerator>();
            languageBinding = MockRepository.GenerateMock <ILanguageBinding>();
            languageBinding.Stub(binding => binding.CodeGenerator).Return(codeGenerator);
            project.Stub(p => p.LanguageBinding).Return(languageBinding);

            codeModelContext = new CodeModelContext {
                CurrentProject = project
            };
        }
Пример #12
0
        bool CheckName(string name, ILanguageBinding language)
        {
            if (string.IsNullOrEmpty(name))
            {
                return(false);
            }

            if ((language.CodeDomProvider == null) || !language.CodeDomProvider.IsValidIdentifier(name))
            {
                return(false);
            }

            return(true);
        }
Пример #13
0
        public override void SetUp()
        {
            base.SetUp();
            project.Stub(p => p.Language).Return(null).WhenCalled(mi => mi.ReturnValue = projectLanguage);

            codeGenerator = MockRepository.GenerateMock<CodeGenerator>();
            languageBinding = MockRepository.GenerateMock<ILanguageBinding>();
            languageBinding.Stub(binding => binding.CodeGenerator).Return(codeGenerator);
            project.Stub(p => p.LanguageBinding).Return(languageBinding);

            codeModelContext = new CodeModelContext {
                CurrentProject = project
            };
        }
Пример #14
0
        static bool CheckName(string name, ILanguageBinding language)
        {
            if (string.IsNullOrEmpty(name))
            {
                return(false);
            }

            if ((language.CodeDomProvider == null) || (!language.CodeDomProvider.IsValidIdentifier(name) &&
                                                       !language.CodeDomProvider.IsValidIdentifier(language.CodeGenerator.EscapeIdentifier(name))))
            {
                return(false);
            }

            return(true);
        }
Пример #15
0
        public Project CreateSingleFileProject(string file)
        {
            ILanguageBinding binding = LanguageBindingService.GetBindingPerFileName(file);

            if (binding != null)
            {
                ProjectCreateInformation info = new ProjectCreateInformation();
                info.ProjectName     = Path.GetFileNameWithoutExtension(file);
                info.SolutionPath    = Path.GetDirectoryName(file);
                info.ProjectBasePath = Path.GetDirectoryName(file);
                Project project = CreateProject(binding.Language, info, null);
                project.Files.Add(new ProjectFile(file));
                return(project);
            }
            return(null);
        }
Пример #16
0
        void TextAreaTextEntered(object sender, TextCompositionEventArgs e)
        {
            if (e.Text.Length > 0 && !e.Handled)
            {
                var adapter = GetAdapterFromSender(sender);
                ILanguageBinding languageBinding = adapter.Language;
                if (languageBinding != null && languageBinding.FormattingStrategy != null)
                {
                    char c = e.Text[0];
                    // When entering a newline, AvalonEdit might use either "\r\n" or "\n", depending on
                    // what was passed to TextArea.PerformTextInput. We'll normalize this to '\n'
                    // so that formatting strategies don't have to handle both cases.
                    if (c == '\r')
                    {
                        c = '\n';
                    }
                    languageBinding.FormattingStrategy.FormatLine(adapter, c);

                    if (c == '\n')
                    {
                        // Immediately parse on enter.
                        // This ensures we have up-to-date CC info about the method boundary when a user
                        // types near the end of a method.
                        SD.ParserService.ParseAsync(this.FileName, this.Document.CreateSnapshot()).FireAndForget();
                    }
                    else
                    {
                        if (e.Text.Length == 1)
                        {
                            // disable all code completion bindings when CC is disabled
                            if (!CodeCompletionOptions.EnableCodeCompletion)
                            {
                                return;
                            }

                            foreach (ICodeCompletionBinding cc in CodeCompletionBindings)
                            {
                                if (cc.HandleKeyPressed(adapter, c))
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #17
0
 void TextAreaTextEntered(object sender, TextCompositionEventArgs e)
 {
     if (e.Text.Length > 0 && !e.Handled)
     {
         ILanguageBinding languageBinding = _avalonEditTextEditorAdapter.Language;
         if (languageBinding != null && languageBinding.FormattingStrategy != null)
         {
             char c = e.Text[0];
             // When entering a newline, AvalonEdit might use either "\r\n" or "\n", depending on
             // what was passed to TextArea.PerformTextInput. We'll normalize this to '\n'
             // so that formatting strategies don't have to handle both cases.
             if (c == '\r')
             {
                 c = '\n';
             }
             languageBinding.FormattingStrategy.FormatLine(_avalonEditTextEditorAdapter, c);
         }
     }
 }
Пример #18
0
        // Returns the name of the file that this template generates.
        // All parameters are optional (can be null)
        public virtual string GetFileName(SolutionItem policyParent, Project project, string language, string baseDirectory, string entryName)
        {
            if (string.IsNullOrEmpty(entryName) && !string.IsNullOrEmpty(defaultName))
            {
                entryName = defaultName;
            }

            string fileName = entryName;

            //substitute tags
            if ((name != null) && (name.Length > 0))
            {
                Dictionary <string, string> tags = new Dictionary <string, string> ();
                ModifyTags(policyParent, project, language, entryName ?? name, null, ref tags);
                fileName = StringParserService.Parse(name, tags);
            }

            if (fileName == null)
            {
                throw new InvalidOperationException("File name not provided in template");
            }

            //give it an extension if it didn't get one (compatibility with pre-substition behaviour)
            if (Path.GetExtension(fileName).Length == 0)
            {
                if (!string.IsNullOrEmpty(defaultExtension))
                {
                    fileName = fileName + defaultExtension;
                }
                else if (!string.IsNullOrEmpty(language))
                {
                    ILanguageBinding languageBinding = GetLanguageBinding(language);
                    fileName = languageBinding.GetFileName(fileName);
                }
            }

            if (baseDirectory != null)
            {
                fileName = Path.Combine(baseDirectory, fileName);
            }

            return(fileName);
        }
        public void CommentCode()
        {
            TextMark curMark, endMark;
            TextIter start, end;
            string   commentTag;

            if (GetSelectionBounds(out start, out end))
            {
                //selection; can contain multiple lines
                // Don't comment lines where no chars are actually selected (fixes bug #81632)
                if (end.LineOffset == 0)
                {
                    end.BackwardLine();
                }
            }

            ILanguageBinding binding = Services.Languages.GetBindingPerFileName(IdeApp.Workbench.ActiveDocument.FileName);

            commentTag = "//";
            if (binding != null && binding.CommentTag != null)
            {
                commentTag = binding.CommentTag;
            }

            start.LineOffset = 0;

            endMark = CreateMark(null, end, false);
            using (new AtomicUndo(this)) {
                while (start.Line <= end.Line)
                {
                    curMark = CreateMark(null, start, true);
                    Insert(ref start, commentTag);
                    start = GetIterAtMark(curMark);
                    end   = GetIterAtMark(endMark);
                    start.ForwardLine();
                }
            }
        }
        public DotNetProject(string languageName, ProjectCreateInformation info, XmlElement projectOptions)
        {
            string binPath;
            if (info != null) {
                Name = info.ProjectName;
                binPath = info.BinPath;
            } else {
                binPath = ".";
            }

            language = languageName;
            languageBinding = FindLanguage (language);

            DotNetProjectConfiguration configuration = (DotNetProjectConfiguration) CreateConfiguration ("Debug");
            configuration.CompilationParameters = languageBinding.CreateCompilationParameters (projectOptions);
            Configurations.Add (configuration);

            configuration = (DotNetProjectConfiguration) CreateConfiguration ("Release");
            configuration.DebugMode = false;
            configuration.CompilationParameters = languageBinding.CreateCompilationParameters (projectOptions);
            Configurations.Add (configuration);

            foreach (DotNetProjectConfiguration parameter in Configurations) {
                parameter.OutputDirectory = Path.Combine (binPath, parameter.Name);
                parameter.OutputAssembly  = Name;

                if (projectOptions != null) {
                    if (projectOptions.Attributes["Target"] != null) {
                        parameter.CompileTarget = (CompileTarget)Enum.Parse(typeof(CompileTarget), projectOptions.Attributes["Target"].InnerText);
                    }
                    if (projectOptions.Attributes["PauseConsoleOutput"] != null) {
                        parameter.PauseConsoleOutput = Boolean.Parse(projectOptions.Attributes["PauseConsoleOutput"].InnerText);
                    }
                }
            }
        }
Пример #21
0
        // Can add tags for substitution based on project, language or filename.
        // If overriding but still want base implementation's tags, should invoke base method.
        // We supply defaults whenever it is possible, to avoid having unsubstituted tags. However,
        // do not substitute blanks when a sensible default cannot be guessed, because they result
        //in less obvious errors.
        public virtual void ModifyTags(SolutionItem policyParent, Project project, string language,
                                       string identifier, string fileName, ref Dictionary <string, string> tags)
        {
            DotNetProject    netProject        = project as DotNetProject;
            string           languageExtension = "";
            ILanguageBinding binding           = null;

            if (!string.IsNullOrEmpty(language))
            {
                binding = GetLanguageBinding(language);
                if (binding != null)
                {
                    languageExtension = Path.GetExtension(binding.GetFileName("Default")).Remove(0, 1);
                }
            }

            //need a default namespace or if there is no project, substitutions can get very messed up
            string ns;

            if (project is IDotNetFileContainer)
            {
                ns = ((IDotNetFileContainer)project).GetDefaultNamespace(fileName);
            }
            else
            {
                ns = "Application";
            }

            //need an 'identifier' for tag substitution, e.g. class name or page name
            //if not given an identifier, use fileName
            if ((identifier == null) && (fileName != null))
            {
                identifier = Path.GetFileName(fileName);
            }

            if (identifier != null)
            {
                //remove all extensions
                while (Path.GetExtension(identifier).Length > 0)
                {
                    identifier = Path.GetFileNameWithoutExtension(identifier);
                }
                identifier        = CreateIdentifierName(identifier);
                tags ["Name"]     = identifier;
                tags ["FullName"] = ns.Length > 0 ? ns + "." + identifier : identifier;

                //some .NET languages may be able to use keywords as identifiers if they're escaped
                IDotNetLanguageBinding dnb = binding as IDotNetLanguageBinding;
                if (dnb != null)
                {
                    System.CodeDom.Compiler.CodeDomProvider provider = dnb.GetCodeDomProvider();
                    if (provider != null)
                    {
                        tags ["EscapedIdentifier"] = provider.CreateEscapedIdentifier(identifier);
                    }
                }
            }

            tags ["Namespace"] = ns;
            if (policyParent != null)
            {
                tags ["SolutionName"] = policyParent.Name;
            }
            if (project != null)
            {
                tags ["ProjectName"]     = project.Name;
                tags ["SafeProjectName"] = CreateIdentifierName(project.Name);
                var info = project.AuthorInformation ?? AuthorInformation.Default;
                tags ["AuthorCopyright"] = info.Copyright;
                tags ["AuthorCompany"]   = info.Company;
                tags ["AuthorTrademark"] = info.Trademark;
                tags ["AuthorEmail"]     = info.Email;
                tags ["AuthorName"]      = info.Name;
            }
            if ((language != null) && (language.Length > 0))
            {
                tags ["Language"] = language;
            }
            if (languageExtension.Length > 0)
            {
                tags ["LanguageExtension"] = languageExtension;
            }

            if (fileName != FilePath.Null)
            {
                FilePath fileDirectory = Path.GetDirectoryName(fileName);
                if (project != null && project.BaseDirectory != FilePath.Null && fileDirectory.IsChildPathOf(project.BaseDirectory))
                {
                    tags ["ProjectRelativeDirectory"] = fileDirectory.ToRelative(project.BaseDirectory);
                }
                else
                {
                    tags ["ProjectRelativeDirectory"] = fileDirectory;
                }

                tags ["FileNameWithoutExtension"] = Path.GetFileNameWithoutExtension(fileName);
                tags ["Directory"] = fileDirectory;
                tags ["FileName"]  = fileName;
            }
        }
Пример #22
0
        public bool CanCreateSingleFileProject(string file)
        {
            ILanguageBinding binding = LanguageBindingService.GetBindingPerFileName(file);

            return(binding != null);
        }
Пример #23
0
        /// <summary>
        /// Load a single project as solution.
        /// </summary>
        public static void LoadProject(string fileName)
        {
            string solutionFile = Path.ChangeExtension(fileName, ".sln");

            if (File.Exists(solutionFile))
            {
                LoadSolution(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)
                    {
                        string[,] parseArgs = { { "SolutionName", Path.GetFileName(solutionFile) }, { "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();

            solution.Name = Path.GetFileNameWithoutExtension(fileName);
            ILanguageBinding binding = LanguageBindingService.GetBindingPerProjectFile(fileName);
            IProject         project;

            if (binding != null)
            {
                project = LanguageBindingService.LoadProject(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 string[, ] {
                    { "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);
            }
        }
 public void SetLanguageBinding(ILanguageBinding languageBinding)
 {
     this.languageBinding = languageBinding;
 }
Пример #25
0
        public static IProject LoadProject(IMSBuildEngineProvider provider, string location, string title, string projectTypeGuid, IProgressMonitor progressMonitor)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            if (location == null)
            {
                throw new ArgumentNullException("location");
            }
            if (title == null)
            {
                throw new ArgumentNullException("title");
            }
            if (projectTypeGuid == null)
            {
                throw new ArgumentNullException("projectTypeGuid");
            }

            if (progressMonitor != null)
            {
                progressMonitor.BeginTask("Loading " + title, 0, false);
            }

            IProject newProject;

            if (!File.Exists(location))
            {
                newProject          = new MissingProject(location, title);
                newProject.TypeGuid = projectTypeGuid;
            }
            else
            {
                ILanguageBinding binding = LanguageBindingService.GetBindingPerProjectFile(location);
                if (binding != null)
                {
                    location = FileUtility.NormalizePath(location);
                    try {
                        newProject = binding.LoadProject(provider, location, title);
                    } catch (ProjectLoadException ex) {
                        LoggingService.Warn("Project load error", ex);
                        if (progressMonitor != null)
                        {
                            progressMonitor.ShowingDialog = true;
                        }
                        newProject          = new UnknownProject(location, title, ex.Message, true);
                        newProject.TypeGuid = projectTypeGuid;
                        if (progressMonitor != null)
                        {
                            progressMonitor.ShowingDialog = false;
                        }
                    } catch (UnauthorizedAccessException ex) {
                        LoggingService.Warn("Project load error", ex);
                        if (progressMonitor != null)
                        {
                            progressMonitor.ShowingDialog = true;
                        }
                        newProject          = new UnknownProject(location, title, ex.Message, true);
                        newProject.TypeGuid = projectTypeGuid;
                        if (progressMonitor != null)
                        {
                            progressMonitor.ShowingDialog = false;
                        }
                    }
                }
                else
                {
                    string ext = Path.GetExtension(location);
                    if (".proj".Equals(ext, StringComparison.OrdinalIgnoreCase) ||
                        ".build".Equals(ext, StringComparison.OrdinalIgnoreCase))
                    {
                        newProject          = new MSBuildFileProject(location, title);
                        newProject.TypeGuid = projectTypeGuid;
                    }
                    else
                    {
                        newProject          = new UnknownProject(location, title);
                        newProject.TypeGuid = projectTypeGuid;
                    }
                }
            }
            return(newProject);
        }
        static bool CheckName(string name, ILanguageBinding language)
        {
            if (string.IsNullOrEmpty(name))
                return false;

            if ((language.CodeDomProvider == null) || (!language.CodeDomProvider.IsValidIdentifier(name) &&
                                                       !language.CodeDomProvider.IsValidIdentifier(language.CodeGenerator.EscapeIdentifier(name))))
                return false;

            return true;
        }
 internal DotNetProject(string languageName)
 {
     language = languageName;
     languageBinding = FindLanguage (language);
 }
 public override void Deserialize(ITypeSerializer handler, DataCollection data)
 {
     base.Deserialize (handler, data);
     languageBinding = FindLanguage (language);
 }
Пример #29
0
        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;
                LanguageBindingDescriptor descriptor   = LanguageBindingService.GetCodonPerLanguageName(language);
                ILanguageBinding          languageinfo = (descriptor != null) ? descriptor.Binding : null;

                if (languageinfo == null)
                {
                    StringParser.Properties["type"] = language;
                    MessageService.ShowError("${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.CantCreateProjectWithTypeError}");
                    return(null);
                }

                string newProjectName = StringParser.Parse(name, new string[, ] {
                    { "ProjectName", projectCreateInformation.ProjectName }
                });
                string projectLocation = Path.GetFullPath(Path.Combine(projectCreateInformation.ProjectBasePath,
                                                                       newProjectName + LanguageBindingService.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;

                StringParser.Properties["StandardNamespace"] = projectCreateInformation.RootNamespace;

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

                // Add Project items
                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)
                {
                    if (!(project is MSBuildBasedProject))
                    {
                        throw new Exception("<Imports> may be only used in project templates for MSBuildBasedProjects");
                    }

                    if (clearExistingImports)
                    {
                        MSBuildInternals.ClearImports(((MSBuildBasedProject)project).MSBuildProject);
                    }
                    try {
                        foreach (Import projectImport in projectImports)
                        {
                            ((MSBuildBasedProject)project).MSBuildProject.AddNewImport(projectImport.Key, projectImport.Value);
                        }
                        ((MSBuildBasedProject)project).CreateItemsListFromMSBuild();
                    } catch (MSBuild.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
                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);

                    if (File.Exists(fileName))
                    {
                        StringParser.Properties["fileName"] = fileName;
                        if (!MessageService.AskQuestion("${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.OverwriteQuestion}", "${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.OverwriteQuestion.InfoName}"))
                        {
                            continue;
                        }
                    }

                    try {
                        if (!Directory.Exists(Path.GetDirectoryName(fileName)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                        }
                        if (file.ContentData != null)
                        {
                            // Binary content
                            File.WriteAllBytes(fileName, file.ContentData);
                        }
                        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 (SharpDevelopTextEditorProperties.Instance.IndentationString != "\t")
                            {
                                fileContent = fileContent.Replace("\t", SharpDevelopTextEditorProperties.Instance.IndentationString);
                            }
                            sr.Write(fileContent);
                            sr.Close();
                        }
                    } catch (Exception ex) {
                        StringParser.Properties["fileName"] = fileName;
                        MessageService.ShowError(ex, "${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.FileCouldntBeWrittenError}");
                    }
                }

                RunCreateActions(project);

                // Save project
                if (File.Exists(projectLocation))
                {
                    StringParser.Properties["projectLocation"] = projectLocation;
                    if (MessageService.AskQuestion("${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.OverwriteProjectQuestion}", "${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.OverwriteQuestion.InfoName}"))
                    {
                        project.Save();
                    }
                }
                else
                {
                    project.Save();
                }

                projectCreateInformation.createdProjects.Add(project);
                ProjectService.OnProjectCreated(new ProjectEventArgs(project));
                return(project);
            }
            finally
            {
                // set back outerProjectBasePath
                projectCreateInformation.ProjectBasePath = outerProjectBasePath;
                projectCreateInformation.ProjectName     = outerProjectName;
            }
        }
Пример #30
0
		public void SetLanguageBinding(ILanguageBinding languageBinding)
		{
			this.languageBinding = languageBinding;
		}
        public static IRefactorer GetRefactorerForLanguage(string language)
        {
            ILanguageBinding binding = GetBindingPerLanguageName(language);

            return(binding != null ? binding.Refactorer : null);
        }
		bool CheckName(string name, ILanguageBinding language)
		{
			if (string.IsNullOrEmpty(name))
				return false;
			
			if ((language.CodeDomProvider == null) || !language.CodeDomProvider.IsValidIdentifier(name))
				return false;
			
			return true;
		}