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;
			
			LanguageBindingDescriptor descriptor = LanguageBindingService.GetCodonPerLanguageName(TargetLanguageName);
			if (descriptor == null || descriptor.Binding == null)
				throw new InvalidOperationException("Cannot get Language Binding for " + TargetLanguageName);
			
			info.OutputProjectFileName = Path.GetFullPath(Path.Combine(targetProjectDirectory, info.ProjectName + descriptor.ProjectFileExtension));
			
			return descriptor.Binding.CreateProject(info);
		}
Esempio n. 2
0
        protected override void Create(ICSharpCode.SharpDevelop.Internal.Templates.ProjectCreateInformation information)
        {
            base.Create(information);

            this.MSBuildProject.DefaultTargets = "Build";

            this.OutputType    = OutputType.Exe;
            this.RootNamespace = information.RootNamespace;
            this.AssemblyName  = information.ProjectName;

            if (!string.IsNullOrEmpty(information.TargetFramework))
            {
                this.TargetFrameworkVersion = information.TargetFramework;
                AddOrRemoveExtensions();
            }

            SetProperty("Debug", null, "OutputPath", @"bin\Debug\",
                        PropertyStorageLocations.ConfigurationSpecific, true);
            SetProperty("Release", null, "OutputPath", @"bin\Release\",
                        PropertyStorageLocations.ConfigurationSpecific, true);
            InvalidateConfigurationPlatformNames();

            SetProperty("Debug", null, "DebugSymbols", "True",
                        PropertyStorageLocations.ConfigurationSpecific, true);
            SetProperty("Release", null, "DebugSymbols", "False",
                        PropertyStorageLocations.ConfigurationSpecific, true);

            SetProperty("Debug", null, "DebugType", "Full",
                        PropertyStorageLocations.ConfigurationSpecific, true);
            SetProperty("Release", null, "DebugType", "None",
                        PropertyStorageLocations.ConfigurationSpecific, true);

            SetProperty("Debug", null, "Optimize", "False",
                        PropertyStorageLocations.ConfigurationSpecific, true);
            SetProperty("Release", null, "Optimize", "True",
                        PropertyStorageLocations.ConfigurationSpecific, true);
        }
		void OpenEvent(object sender, EventArgs e)
		{
			
			if (((TreeView)ControlDictionary["categoryTreeView"]).SelectedNode != null) {
				PropertyService.Set("Dialogs.NewProjectDialog.LastSelectedCategory", ((TreeView)ControlDictionary["categoryTreeView"]).SelectedNode.Text);
				PropertyService.Set("Dialogs.NewProjectDialog.LargeImages", ((RadioButton)ControlDictionary["largeIconsRadioButton"]).Checked);
			}
			
			
			string solution = ((TextBox)ControlDictionary["solutionNameTextBox"]).Text.Trim();
			string name     = ((TextBox)ControlDictionary["nameTextBox"]).Text.Trim();
			string location = ((TextBox)ControlDictionary["locationTextBox"]).Text.Trim();
			if (!FileUtility.IsValidFileName(solution)
			    || solution.IndexOf(Path.DirectorySeparatorChar) >= 0
			    || solution.IndexOf(Path.AltDirectorySeparatorChar) >= 0
			    || !FileUtility.IsValidFileName(name)
			    || name.IndexOf(Path.AltDirectorySeparatorChar) >= 0
			    || name.IndexOf(Path.DirectorySeparatorChar) >= 0
			    || !FileUtility.IsValidFileName(location))
			{
				MessageService.ShowError("${res:ICSharpCode.SharpDevelop.Gui.Dialogs.NewProjectDialog.IllegalProjectNameError}");
				return;
			}
			if (!char.IsLetter(name[0]) && name[0] != '_') {
				MessageService.ShowError("${res:ICSharpCode.SharpDevelop.Gui.Dialogs.NewProjectDialog.ProjectNameMustStartWithLetter}");
				return;
			}
			if (name.EndsWith(".")) {
				MessageService.ShowError("${res:ICSharpCode.SharpDevelop.Gui.Dialogs.NewProjectDialog.ProjectNameMustNotEndWithDot}");
				return;
			}
			
			PropertyService.Set("ICSharpCode.SharpDevelop.Gui.NewProjectDialog.AutoCreateProjectSubdir", ((CheckBox)ControlDictionary["autoCreateSubDirCheckBox"]).Checked);
			if (((ListView)ControlDictionary["templateListView"]).SelectedItems.Count == 1 && ((TextBox)ControlDictionary["locationTextBox"]).Text.Length > 0 && ((TextBox)ControlDictionary["solutionNameTextBox"]).Text.Length > 0) {
				TemplateItem item = (TemplateItem)((ListView)ControlDictionary["templateListView"]).SelectedItems[0];
				try {
					System.IO.Directory.CreateDirectory(ProjectSolution);
				} catch (Exception) {
					
					MessageService.ShowError("${res:ICSharpCode.SharpDevelop.Gui.Dialogs.NewProjectDialog.CantCreateDirectoryError}");
					return;
				}
				
				ProjectCreateInformation cinfo = new ProjectCreateInformation();
				if (!createNewSolution) {
					cinfo.Solution = ProjectService.OpenSolution;
				}
				
				cinfo.SolutionPath     = ProjectLocation;
				cinfo.ProjectBasePath = ProjectSolution;
				
				cinfo.ProjectName     = name;
				
				NewCombineLocation = item.Template.CreateProject(cinfo);
				if (NewCombineLocation == null || NewCombineLocation.Length == 0) {
					return;
				}
				if (createNewSolution) {
					ProjectService.LoadSolutionOrProject(NewCombineLocation);
					item.Template.RunOpenActions(cinfo);
				}
				
				NewProjectLocation = cinfo.CreatedProjects.Count > 0 ? cinfo.CreatedProjects[0] : "";
				DialogResult = DialogResult.OK;
			}
		}
		void OpenEvent(object sender, EventArgs e)
		{
			
			if (categoryTreeView.SelectedNode != null) {
				PropertyService.Set("Dialogs.NewProjectDialog.LastSelectedCategory", TreeViewHelper.GetPath(categoryTreeView.SelectedNode));
				PropertyService.Set("Dialogs.NewProjectDialog.CategoryTreeState", TreeViewHelper.GetViewStateString(categoryTreeView));
				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;
				}
				
				ProjectCreateInformation cinfo = new ProjectCreateInformation();
				if (!createNewSolution) {
					cinfo.Solution = ProjectService.OpenSolution;
					cinfo.SolutionPath = Path.GetDirectoryName(cinfo.Solution.FileName);
					cinfo.SolutionName = cinfo.Solution.Name;
				} else {
					cinfo.SolutionPath = NewSolutionDirectory;
				}
				
				if (item.Template.HasSupportedTargetFrameworks) {
					cinfo.TargetFramework = (TargetFramework)targetFrameworkComboBox.SelectedItem;
					PropertyService.Set("Dialogs.NewProjectDialog.TargetFramework", cinfo.TargetFramework.Name);
				}
				
				cinfo.ProjectBasePath = NewProjectDirectory;
				
				cinfo.SolutionName    = solution;
				cinfo.ProjectName     = name;
				
				NewSolutionLocation = item.Template.CreateProject(cinfo);
				if (NewSolutionLocation == null || NewSolutionLocation.Length == 0) {
					return;
				}
				if (createNewSolution) {
					ProjectService.LoadSolution(NewSolutionLocation);
				}
				item.Template.RunOpenActions(cinfo);
				
				NewProjectLocation = cinfo.createdProjects.Count > 0 ? cinfo.createdProjects[0].FileName : "";
				DialogResult = DialogResult.OK;
			}
		}
Esempio n. 5
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 StringTagPair("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 StringTagPair("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, true);
                        }
                        else
                        {
                            // Textual content
                            StreamWriter sr          = new StreamWriter(File.Create(fileName), ParserService.DefaultFileEncoding);
                            string       fileContent = StringParser.Parse(file.Content, new StringTagPair("ProjectName", projectCreateInformation.ProjectName), new StringTagPair("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 StringTagPair("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;
            }
        }