public override void RunOpenActions(ProjectTemplateResult result)
 {
     foreach (var action in openActions)
     {
         action(result);
     }
 }
		void RunCommandWithProjectCreateInfoAsOwner(List<TestableProject> projects)
		{
			var createInfo = new ProjectTemplateResult(new ProjectTemplateOptions());
			createInfo.NewProjects.AddRange(projects);
			
			command.FakeProjectService.ProjectCollections.Add(new ImmutableModelCollection<IProject>(projects));
			
			RunCommandWithProjectCreateInfoAsOwner(createInfo);
		}
			internal bool AddContents(ISolutionFolder parentFolder, ProjectTemplateResult templateResult, string defaultLanguage)
			{
				// Create sub projects
				foreach (SolutionFolderDescriptor folderDescriptor in solutionFoldersDescriptors) {
					ISolutionFolder folder = parentFolder.CreateFolder(folderDescriptor.name);
					if (!folderDescriptor.AddContents(folder, templateResult, defaultLanguage))
						return false;
				}
				foreach (ProjectDescriptor projectDescriptor in projectDescriptors) {
					IProject newProject = projectDescriptor.CreateProject(templateResult, defaultLanguage);
					if (newProject == null)
						return false;
					parentFolder.Items.Add(newProject);
				}
				return true;
			}
 internal bool AddContents(ISolutionFolder parentFolder, ProjectTemplateResult templateResult, string defaultLanguage)
 {
     // Create sub projects
     foreach (SolutionFolderDescriptor folderDescriptor in solutionFoldersDescriptors)
     {
         ISolutionFolder folder = parentFolder.CreateFolder(folderDescriptor.name);
         if (!folderDescriptor.AddContents(folder, templateResult, defaultLanguage))
         {
             return(false);
         }
     }
     foreach (ProjectDescriptor projectDescriptor in projectDescriptors)
     {
         bool success = projectDescriptor.CreateProject(templateResult, defaultLanguage, parentFolder);
         if (!success)
         {
             return(false);
         }
     }
     return(true);
 }
        public override ProjectTemplateResult CreateProjects(ProjectTemplateOptions options)
        {
            var result = new ProjectTemplateResult(options);

            StandardHeader.SetHeaders();
            if (solutionDescriptor != null)
            {
                if (!solutionDescriptor.AddContents(options.SolutionFolder, result, languagename))
                {
                    return(null);
                }
            }
            if (projectDescriptor != null)
            {
                bool success = projectDescriptor.CreateProject(result, languagename, options.SolutionFolder);
                if (!success)
                {
                    return(null);
                }
            }
            return(result);
        }
		public override void RunOpenActions(ProjectTemplateResult result)
		{
			foreach (var action in openActions) {
				action(result);
			}
		}
		public override ProjectTemplateResult CreateProjects(ProjectTemplateOptions options)
		{
			var result = new ProjectTemplateResult(options);
			StandardHeader.SetHeaders();
			if (solutionDescriptor != null) {
				if (!solutionDescriptor.AddContents(options.SolutionFolder, result, languagename))
					return null;
			}
			if (projectDescriptor != null) {
				IProject project = projectDescriptor.CreateProject(result, languagename);
				if (project != null) {
					options.SolutionFolder.Items.Add(project);
				} else {
					return null;
				}
			}
			return result;
		}
        void CreateProject()
        {
            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;
                }

                ProjectTemplateOptions cinfo = new ProjectTemplateOptions();

                if (item.Template.SupportedTargetFrameworks.Any()) {
                    cinfo.TargetFramework = (TargetFramework)targetFrameworkComboBox.SelectedItem;
                    PropertyService.Set("Dialogs.NewProjectDialog.TargetFramework", cinfo.TargetFramework.TargetFrameworkVersion);
                }

                cinfo.ProjectBasePath = DirectoryName.Create(NewProjectDirectory);
                cinfo.ProjectName     = name;

                if (createNewSolution) {
                    if (!SD.ProjectService.CloseSolution())
                        return;
                    result = item.Template.CreateAndOpenSolution(cinfo, NewSolutionDirectory, solution);
                } else {
                    cinfo.Solution = SolutionFolder.ParentSolution;
                    cinfo.SolutionFolder = SolutionFolder;
                    result = item.Template.CreateProjects(cinfo);
                    cinfo.Solution.Save();
                }

                if (result != null)
                    item.Template.RunOpenActions(result);

                ProjectBrowserPad.RefreshViewAsync();
                DialogResult = DialogResult.OK;
            }
        }
		/// <summary>
		/// Runs the actions after the newly created solution is opened in the IDE.
		/// </summary>
		public virtual void RunOpenActions(ProjectTemplateResult result)
		{
		}
Beispiel #10
0
        //Show prompt, create files from template, create project, execute command, save project
        public bool CreateProject(ProjectTemplateResult templateResults, string defaultLanguage, ISolutionFolder target)
        {
            var      projectCreateOptions = templateResults.Options;
            var      parentSolution       = templateResults.Options.Solution;
            IProject project = null;
            bool     success = false;

            try
            {
                string language = string.IsNullOrEmpty(languageName) ? defaultLanguage : languageName;
                ProjectBindingDescriptor descriptor   = SD.ProjectService.ProjectBindings.FirstOrDefault(b => b.Language == 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(false);
                }

                DirectoryName projectBasePath = GetProjectBasePath(projectCreateOptions);
                string        newProjectName  = StringParser.Parse(name, new StringTagPair("ProjectName", projectCreateOptions.ProjectName));
                Directory.CreateDirectory(projectBasePath);
                FileName projectLocation      = projectBasePath.CombineFile(newProjectName + descriptor.ProjectFileExtension);
                ProjectCreateInformation info = new ProjectCreateInformation(parentSolution, projectLocation);
                info.TargetFramework = projectCreateOptions.TargetFramework;

                StringBuilder standardNamespace = new StringBuilder();
                // filter 'illegal' chars from standard namespace
                if (!string.IsNullOrEmpty(newProjectName))
                {
                    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);
                            }
                        }
                    }
                }

                info.TypeGuid      = descriptor.TypeGuid;
                info.RootNamespace = standardNamespace.ToString();
                info.ProjectName   = newProjectName;
                if (!string.IsNullOrEmpty(defaultPlatform))
                {
                    info.ActiveProjectConfiguration = new ConfigurationAndPlatform("Debug", defaultPlatform);
                }

                RunPreCreateActions(info);

                StringParserPropertyContainer.FileCreation["StandardNamespace"] = info.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(false);                        //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(projectBasePath, StringParser.Parse(file.Name, new StringTagPair("ProjectName", info.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(projectBasePath, StringParser.Parse(file.Name, new StringTagPair("ProjectName", info.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), SD.FileService.DefaultFileEncoding);
                            string       fileContent = StringParser.Parse(file.Content,
                                                                          new StringTagPair("ProjectName", projectCreateOptions.ProjectName),
                                                                          new StringTagPair("SolutionName", projectCreateOptions.SolutionName),
                                                                          new StringTagPair("FileName", fileName));
                            fileContent = StringParser.Parse(fileContent);
                            if (SD.EditorControlService.GlobalOptions.IndentationString != "\t")
                            {
                                fileContent = fileContent.Replace("\t", SD.EditorControlService.GlobalOptions.IndentationString);
                            }
                            sr.Write(fileContent);
                            sr.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageService.ShowException(ex, "Exception writing " + fileName);
                    }
                }
                #endregion

                #region Create Project
                try {
                    info.InitializeTypeSystem = false;
                    project = languageinfo.CreateProject(info);
                } catch (ProjectLoadException ex) {
                    MessageService.ShowError(ex.Message);
                    return(false);
                }
                #endregion

                #region Create Project Items, Imports and Files
                // Add Project items
                if (!project.Items.IsReadOnly)
                {
                    foreach (ProjectItem projectItem in projectItems)
                    {
                        ProjectItem newProjectItem = new UnknownProjectItem(
                            project,
                            StringParser.Parse(projectItem.ItemType.ItemName),
                            StringParser.Parse(projectItem.Include,
                                               new StringTagPair("ProjectName", projectCreateOptions.ProjectName),
                                               new StringTagPair("SolutionName", projectCreateOptions.SolutionName))
                            );
                        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));
                            }
                        }
                        project.Items.Add(newProjectItem);
                    }
                }

                // Add properties from <PropertyGroup>
                // This must be done before adding <Imports>, because the import path can refer to properties.
                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 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) {
                        string message;
                        if (string.IsNullOrEmpty(importsFailureMessage))
                        {
                            message = "Error creating project:\n" + ex.Message;
                        }
                        else
                        {
                            message = importsFailureMessage + "\n\n" + ex.Message;
                        }
                        throw new ProjectLoadException(message, ex);
                    }
                }

                // Add Files
                if (!project.Items.IsReadOnly)
                {
                    foreach (FileDescriptionTemplate file in files)
                    {
                        string          fileName    = Path.Combine(projectBasePath, StringParser.Parse(file.Name, new StringTagPair("ProjectName", projectCreateOptions.ProjectName)));
                        FileProjectItem projectFile = new FileProjectItem(project, project.GetDefaultItemType(fileName));

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

                        file.SetProjectItemProperties(projectFile);

                        project.Items.Add(projectFile);
                    }
                }

                #endregion

                RunCreateActions(project);

                project.ProjectCreationComplete();

                // Save project
                project.Save();

                // HACK : close and reload
                var fn = project.FileName;
                project.Dispose();
                ProjectLoadInformation loadInfo = new ProjectLoadInformation(parentSolution, fn, fn.GetFileNameWithoutExtension());
                project = SD.ProjectService.LoadProject(loadInfo);
                target.Items.Add(project);
                project.ProjectLoaded();

                SD.GetRequiredService <IProjectServiceRaiseEvents>().RaiseProjectCreated(new ProjectEventArgs(project));
                templateResults.NewProjects.Add(project);
                success = true;
                return(true);
            } finally {
                if (project != null && !success)
                {
                    project.Dispose();
                }
            }
        }
		public override ProjectTemplateResult CreateProjects(ProjectTemplateOptions options)
		{
			var result = new ProjectTemplateResult(options);
			StandardHeader.SetHeaders();
			if (solutionDescriptor != null) {
				if (!solutionDescriptor.AddContents(options.SolutionFolder, result, languagename))
					return null;
			}
			if (projectDescriptor != null) {
				bool success = projectDescriptor.CreateProject(result, languagename, options.SolutionFolder);
				if (!success) {
					return null;
				}
			}
			return result;
		}
		//Show prompt, create files from template, create project, execute command, save project
		public bool CreateProject(ProjectTemplateResult templateResults, string defaultLanguage, ISolutionFolder target)
		{
			var projectCreateOptions = templateResults.Options;
			var parentSolution = templateResults.Options.Solution;
			IProject project = null;
			bool success = false;
			try
			{
				string language = string.IsNullOrEmpty(languageName) ? defaultLanguage : languageName;
				ProjectBindingDescriptor descriptor = SD.ProjectService.ProjectBindings.FirstOrDefault(b => b.Language == 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 false;
				}
				
				DirectoryName projectBasePath = projectCreateOptions.ProjectBasePath;
				string newProjectName = StringParser.Parse(name, new StringTagPair("ProjectName", projectCreateOptions.ProjectName));
				Directory.CreateDirectory(projectBasePath);
				FileName projectLocation = projectBasePath.CombineFile(newProjectName + descriptor.ProjectFileExtension);
				ProjectCreateInformation info = new ProjectCreateInformation(parentSolution, projectLocation);
				info.TargetFramework = projectCreateOptions.TargetFramework;
				
				StringBuilder standardNamespace = new StringBuilder();
				// filter 'illegal' chars from standard namespace
				if (!string.IsNullOrEmpty(newProjectName)) {
					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);
							}
						}
					}
				}
				
				info.TypeGuid = descriptor.TypeGuid;
				info.RootNamespace = standardNamespace.ToString();
				info.ProjectName = newProjectName;
				if (!string.IsNullOrEmpty(defaultPlatform))
					info.ActiveProjectConfiguration = new ConfigurationAndPlatform("Debug", defaultPlatform);
				
				RunPreCreateActions(info);
				
				StringParserPropertyContainer.FileCreation["StandardNamespace"] = info.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 false; //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(projectBasePath, StringParser.Parse(file.Name, new StringTagPair("ProjectName", info.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(projectBasePath, StringParser.Parse(file.Name, new StringTagPair("ProjectName", info.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), SD.FileService.DefaultFileEncoding);
							string fileContent = StringParser.Parse(file.Content,
							                                        new StringTagPair("ProjectName", projectCreateOptions.ProjectName),
							                                        new StringTagPair("SolutionName", projectCreateOptions.SolutionName),
							                                        new StringTagPair("FileName", fileName));
							fileContent = StringParser.Parse(fileContent);
							if (SD.EditorControlService.GlobalOptions.IndentationString != "\t") {
								fileContent = fileContent.Replace("\t", SD.EditorControlService.GlobalOptions.IndentationString);
							}
							sr.Write(fileContent);
							sr.Close();
						}
					}
					catch (Exception ex)
					{
						MessageService.ShowException(ex, "Exception writing " + fileName);
					}
				}
				#endregion
				
				#region Create Project
				try {
					info.InitializeTypeSystem = false;
					project = languageinfo.CreateProject(info);
				} catch (ProjectLoadException ex) {
					MessageService.ShowError(ex.Message);
					return false;
				}
				#endregion
				
				#region Create Project Items, Imports and Files
				// Add Project items
				if (!project.Items.IsReadOnly)
				{
					foreach (ProjectItem projectItem in projectItems) {
						ProjectItem newProjectItem = new UnknownProjectItem(
							project,
							StringParser.Parse(projectItem.ItemType.ItemName),
							StringParser.Parse(projectItem.Include,
							                   new StringTagPair("ProjectName", projectCreateOptions.ProjectName),
							                   new StringTagPair("SolutionName", projectCreateOptions.SolutionName))
						);
						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));
						}
						project.Items.Add(newProjectItem);
					}
				}
				
				// Add properties from <PropertyGroup>
				// This must be done before adding <Imports>, because the import path can refer to properties.
				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 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) {
						string message;
						if (string.IsNullOrEmpty(importsFailureMessage)) {
							message = "Error creating project:\n" + ex.Message;
						} else {
							message = importsFailureMessage + "\n\n" + ex.Message;
						}
						throw new ProjectLoadException(message, ex);
					}
				}
				
				// Add Files
				if (!project.Items.IsReadOnly) {
					
					foreach (FileDescriptionTemplate file in files) {
						string fileName = Path.Combine(projectBasePath, StringParser.Parse(file.Name, new StringTagPair("ProjectName", projectCreateOptions.ProjectName)));
						FileProjectItem projectFile = new FileProjectItem(project, project.GetDefaultItemType(fileName));
						
						projectFile.Include = FileUtility.GetRelativePath(project.Directory, fileName);
						
						file.SetProjectItemProperties(projectFile);
						
						project.Items.Add(projectFile);
					}
				}
				
				#endregion
				
				RunCreateActions(project);
				
				project.ProjectCreationComplete();
				
				// Save project
				project.Save();
				
				// HACK : close and reload
				var fn = project.FileName;
				project.Dispose();
				ProjectLoadInformation loadInfo = new ProjectLoadInformation(parentSolution, fn, fn.GetFileNameWithoutExtension());
				project = SD.ProjectService.LoadProject(loadInfo);
				target.Items.Add(project);
				project.ProjectLoaded();
				
				SD.GetRequiredService<IProjectServiceRaiseEvents>().RaiseProjectCreated(new ProjectEventArgs(project));
				templateResults.NewProjects.Add(project);
				success = true;
				return true;
			} finally {
				if (project != null && !success)
					project.Dispose();
			}
		}
 internal bool AddContents(ISolutionFolder parentFolder, ProjectTemplateResult templateResult, string defaultLanguage)
 {
     return mainFolder.AddContents(parentFolder, templateResult, defaultLanguage);
 }
 /// <summary>
 /// Runs the actions after the newly created solution is opened in the IDE.
 /// </summary>
 public virtual void RunOpenActions(ProjectTemplateResult result)
 {
 }
 void RunCommandWithProjectCreateInfoAsOwner(ProjectTemplateResult createInfo)
 {
     ((ICommand)command).Execute(createInfo);
 }
 internal bool AddContents(ISolutionFolder parentFolder, ProjectTemplateResult templateResult, string defaultLanguage)
 {
     return(mainFolder.AddContents(parentFolder, templateResult, defaultLanguage));
 }