public ProjectLoadInformation ReadProjectEntry(ISolution parentSolution)
        {
            if (currentLine == null)
            {
                return(null);
            }
            Match match = projectLinePattern.Match(currentLine);

            if (!match.Success)
            {
                return(null);
            }
            NextLine();
            string   title           = match.Groups["Title"].Value;
            string   location        = match.Groups["Location"].Value;
            FileName projectFileName = FileName.Create(Path.Combine(parentSolution.Directory, location));
            var      loadInformation = new ProjectLoadInformation(parentSolution, projectFileName, title);

            loadInformation.TypeGuid = ParseGuidDefaultEmpty(match.Groups["TypeGuid"].Value);
            loadInformation.IdGuid   = ParseGuidDefaultEmpty(match.Groups["IdGuid"].Value);
            SolutionSection section;

            while ((section = ReadSection(isGlobal: false)) != null)
            {
                loadInformation.ProjectSections.Add(section);
            }
            if (currentLine != "EndProject")
            {
                throw Error("Expected 'EndProject'");
            }
            NextLine();
            return(loadInformation);
        }
Exemple #2
0
		/// <summary>
		/// Create a new C++ project that loads the specified .vcproj file.
		/// </summary>
		public CppProject(ProjectLoadInformation info)
		{
			this.Name = info.ProjectName;
			this.FileName = info.FileName;
			this.TypeGuid = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";
			
			using (StreamReader r = new StreamReader(info.FileName, Encoding.Default)) {
				try {
					document.Load(r);
				} catch (Exception ex) {
					throw new ProjectLoadException(ex.Message, ex);
				}
			}
			if (document.DocumentElement.Name != "VisualStudioProject")
				throw new ProjectLoadException("The project is not a visual studio project.");
			XmlElement filesElement = document.DocumentElement["Files"];
			if (filesElement != null) {
				foreach (XmlElement filterElement in filesElement.ChildNodes.OfType<XmlElement>()) {
					if (filterElement.Name == "Filter") {
						FileGroup group = new FileGroup(this, filterElement);
						groups.Add(group);
						foreach (XmlElement fileElement in filterElement.ChildNodes.OfType<XmlElement>()) {
							if (fileElement.Name == "File" && fileElement.HasAttribute("RelativePath")) {
								items.Add(new FileItem(group, fileElement));
							}
						}
					}
				}
			}
		}
 //string warningText = "${res:ICSharpCode.SharpDevelop.Commands.ProjectBrowser.NoBackendForProjectType}";
 //        public void ShowWarningMessageBox()
 //        {
 //            warningDisplayedToUser = true;
 //            MessageService.ShowError("Error loading " + this.FileName + ":\n" + warningText);
 //        }
 public ErrorProject(ProjectLoadInformation information, Exception exception)
     : base(information)
 {
     if (exception == null)
         throw new ArgumentNullException("exception");
     this.exception = exception;
 }
		public CSharpProject(ProjectLoadInformation loadInformation)
			: base(loadInformation)
		{
			Init();
			if (loadInformation.InitializeTypeSystem)
				InitializeProjectContent(new CSharpProjectContent());
		}
Exemple #5
0
		public UnknownProject(ProjectLoadInformation information, string warningText, bool displayWarningToUser)
			: this(information)
		{
			this.warningText = warningText;
			if (displayWarningToUser) {
				ShowWarningMessageBox();
			}
		}
        //string warningText = "${res:ICSharpCode.SharpDevelop.Commands.ProjectBrowser.NoBackendForProjectType}";

//		public void ShowWarningMessageBox()
//		{
//			warningDisplayedToUser = true;
//			MessageService.ShowError("Error loading " + this.FileName + ":\n" + warningText);
//		}

        public ErrorProject(ProjectLoadInformation information, Exception exception)
            : base(information)
        {
            if (exception == null)
            {
                throw new ArgumentNullException("exception");
            }
            this.exception = exception;
        }
		Guid projectGuid; // GUID of next project to be loaded
		
		IProject LoadProject(ProjectLoadInformation info)
		{
			var project = MockRepository.GenerateStrictMock<IProject>();
			project.Stub(p => p.IdGuid).PropertyBehavior();
			project.IdGuid = projectGuid;
			project.Stub(p => p.FileName).Return(info.FileName);
			project.Stub(p => p.ParentSolution).Return(info.Solution);
			project.Stub(p => p.ParentFolder).PropertyBehavior();
			project.Stub(p => p.ProjectSections).Return(new SimpleModelCollection<SolutionSection>());
			project.Stub(p => p.ConfigurationMapping).Return(new ConfigurationMapping());
			project.Stub(p => p.IsStartable).Return(false);
			project.Stub(p => p.ProjectLoaded()).Do(new Action(delegate { }));
			return project;
		}
        Guid projectGuid;         // GUID of next project to be loaded

        IProject LoadProject(ProjectLoadInformation info)
        {
            var project = MockRepository.GenerateStrictMock <IProject>();

            project.Stub(p => p.IdGuid).PropertyBehavior();
            project.IdGuid = projectGuid;
            project.Stub(p => p.FileName).Return(info.FileName);
            project.Stub(p => p.ParentSolution).Return(info.Solution);
            project.Stub(p => p.ParentFolder).PropertyBehavior();
            project.Stub(p => p.ProjectSections).Return(new SimpleModelCollection <SolutionSection>());
            project.Stub(p => p.ConfigurationMapping).Return(new ConfigurationMapping());
            project.Stub(p => p.IsStartable).Return(false);
            project.Stub(p => p.ProjectLoaded()).Do(new Action(delegate { }));
            return(project);
        }
        public IProject LoadProject(ProjectLoadInformation info)
        {
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }
            info.ProgressMonitor.CancellationToken.ThrowIfCancellationRequested();
            ProjectBindingDescriptor descriptor = null;

            if (info.TypeGuid != Guid.Empty)
            {
                descriptor = projectBindings.FirstOrDefault(b => b.TypeGuid == info.TypeGuid);
            }
            if (descriptor == null)
            {
                string extension = info.FileName.GetExtension();
                if (extension.Equals(".proj", StringComparison.OrdinalIgnoreCase) || extension.Equals(".build", StringComparison.OrdinalIgnoreCase))
                {
                    return(new MSBuildFileProject(info));
                }
                descriptor = projectBindings.FirstOrDefault(b => extension.Equals(b.ProjectFileExtension, StringComparison.OrdinalIgnoreCase));
            }
            if (descriptor == null)
            {
                throw new ProjectLoadException(SD.ResourceService.GetString("ICSharpCode.SharpDevelop.Commands.ProjectBrowser.NoBackendForProjectType"));
            }

            // Set type GUID based on file extension
            info.TypeGuid = descriptor.TypeGuid;
            IProjectBinding binding = descriptor.Binding;

            if (binding == null)
            {
                throw new ProjectLoadException(SD.ResourceService.GetString("ICSharpCode.SharpDevelop.Commands.ProjectBrowser.NoBackendForProjectType"));
            }
            if (!binding.HandlingMissingProject && !SD.FileSystem.FileExists(info.FileName))
            {
                throw new FileNotFoundException("Project file not found", info.FileName);
            }
            var result = binding.LoadProject(info);

            if (result == null)
            {
                throw new InvalidOperationException("IProjectBinding.LoadProject() must not return null");
            }

            return(result);
        }
Exemple #10
0
        public VbpProject(ProjectLoadInformation info)
            : base(info)
        {
            _projectReader = new Vb6ProjectReader();
            _projectWriter = new Vb6ProjectWriter();

            FileInfo file = new FileInfo(info.FileName);
            using (Stream stream = file.OpenRead())
            {
                _vbProject = _projectReader.Read(file, stream);
            }

            AddGenericItems();
            AddReferences();

            _symbolCache = VbpProjectSymbolCache.FromProject(this);
        }
		public MSBuildFileProject(ProjectLoadInformation information) : base(information)
		{
			try {
				using (XmlReader r = XmlReader.Create(information.FileName, new XmlReaderSettings { IgnoreComments = true, XmlResolver = null })) {
					if (r.Read() && r.MoveToContent() == XmlNodeType.Element) {
						string toolsVersion = r.GetAttribute("ToolsVersion");
						Version v;
						if (Version.TryParse(toolsVersion, out v)) {
							if (v >= new Version(4, 0)) {
								minimumSolutionVersion = SolutionFormatVersion.VS2010; // use 4.0 Build Worker
							}
						}
					}
				}
			} catch (XmlException) {
			} catch (IOException) {
			}
		}
        static IProject LoadProjectWithErrorHandling(ProjectLoadInformation projectInfo)
        {
            Exception exception;

            try {
                return(SD.ProjectService.LoadProject(projectInfo));
            } catch (FileNotFoundException) {
                return(new MissingProject(projectInfo));
            } catch (ProjectLoadException ex) {
                exception = ex;
            } catch (IOException ex) {
                exception = ex;
            } catch (UnauthorizedAccessException ex) {
                exception = ex;
            }
            LoggingService.Warn("Project load error", exception);
            return(new ErrorProject(projectInfo, exception));
        }
        public IProject AddExistingProject(FileName fileName)
        {
            if (parentSolution.Projects.Any(p => p.FileName == fileName))
            {
                throw new ProjectLoadException("Project " + fileName + " is already part of this solution.");
            }
            ProjectLoadInformation loadInfo = new ProjectLoadInformation(parentSolution, fileName, fileName.GetFileNameWithoutExtension());
            IProject project = SD.ProjectService.LoadProject(loadInfo);

            if (parentSolution.GetItemByGuid(project.IdGuid) != null)
            {
                SD.Log.Warn("Added project has duplicate GUID; a new GUID will be generated.");
                project.IdGuid = Guid.NewGuid();
            }
            this.Items.Add(project);
            project.ProjectLoaded();
            ProjectBrowserPad.RefreshViewAsync();
            return(project);
        }
        SolutionFolder CreateSolutionFolder(Solution solution, ProjectLoadInformation information)
        {
            var folder = new SolutionFolder(solution, information.IdGuid);

            folder.Name = information.ProjectName;
            // Add solution items:
            var solutionItemsSection = information.ProjectSections.FirstOrDefault(s => s.SectionName == "SolutionItems");

            if (solutionItemsSection != null)
            {
                foreach (string location in solutionItemsSection.Values)
                {
                    var fileItem = new SolutionFileItem(solution);
                    fileItem.FileName = FileName.Create(Path.Combine(information.Solution.Directory, location));
                    folder.Items.Add(fileItem);
                }
            }
            return(folder);
        }
 public MSBuildFileProject(ProjectLoadInformation information) : base(information)
 {
     try {
         using (XmlReader r = XmlReader.Create(information.FileName, new XmlReaderSettings {
             IgnoreComments = true, XmlResolver = null
         })) {
             if (r.Read() && r.MoveToContent() == XmlNodeType.Element)
             {
                 string  toolsVersion = r.GetAttribute("ToolsVersion");
                 Version v;
                 if (Version.TryParse(toolsVersion, out v))
                 {
                     if (v >= new Version(4, 0))
                     {
                         minimumSolutionVersion = SolutionFormatVersion.VS2010;                                 // use 4.0 Build Worker
                     }
                 }
             }
         }
     } catch (XmlException ex) {
         throw new ProjectLoadException(ex.Message, ex);
     }             // IOException can also occur, but doesn't need to be converted to ProjectLoadException
 }
		public IProject LoadProject(ProjectLoadInformation loadInformation)
		{
			return new CSharpProject(loadInformation);
		}
Exemple #17
0
		public UnknownProject(ProjectLoadInformation information, string warningText)
			: this(information)
		{
			this.warningText = warningText;
		}
		bool UpgradeToolsVersion(ProjectLoadInformation loadInformation)
		{
			if (loadInformation.upgradeToolsVersion != null)
				return false;
			if (!CanUpgradeToolsVersion())
				return false;
			loadInformation.ProgressMonitor.ShowingDialog = true;
			StringTagPair[] tags = {
				new StringTagPair("ProjectName", loadInformation.ProjectName),
				new StringTagPair("OldToolsVersion", projectFile.ToolsVersion),
				new StringTagPair("NewToolsVersion", autoUpgradeNewToolsVersion)
			};
			string message = StringParser.Parse("${res:ICSharpCode.SharpDevelop.Project.UpgradeView.UpdateOnLoadDueToMissingMSBuild}", tags);
			string upgradeButton = StringParser.Parse("${res:ICSharpCode.SharpDevelop.Project.UpgradeView.UpdateToMSBuildButton}", tags);
			int result = MessageService.ShowCustomDialog(
				"${res:ICSharpCode.SharpDevelop.Project.UpgradeView.Title}",
				message,
				0, 1, upgradeButton, "${res:Global.CancelButtonText}");
			loadInformation.ProgressMonitor.ShowingDialog = false;
			if (result == 0) {
				loadInformation.upgradeToolsVersion = true;
				LoadProjectInternal(loadInformation);
				return true;
			} else {
				loadInformation.upgradeToolsVersion = false;
				return false;
			}
		}
Exemple #19
0
		public WixProject(ProjectLoadInformation info)
			: base(info)
		{
		}
Exemple #20
0
		public CSharpProject(ProjectLoadInformation loadInformation)
			: base(loadInformation)
		{
			Init();
		}
 public UnknownProject(ProjectLoadInformation information)
     : base(information)
 {
 }
Exemple #22
0
		public BooProject(ProjectLoadInformation info)
			: base(info)
		{
			Init();
		}
		public IProject LoadProject(ProjectLoadInformation loadInformation)
		{
			return new SnippetCompilerProject(loadInformation);
		}
		public IProject LoadProject(ProjectLoadInformation info)
		{
			return new CppProject(info);
		}
		public IProject LoadProject(ProjectLoadInformation loadInformation)
		{
			return new PythonProject(loadInformation);
		}
Exemple #26
0
 protected CompilableProject(ProjectLoadInformation information)
     : base(information)
 {
 }
 public MissingProject(ProjectLoadInformation information) : base(information)
 {
 }
Exemple #28
0
		public LSharpProject(ProjectLoadInformation info)
			: base(info)
		{
			Init();
		}
		public IProject LoadProject(ProjectLoadInformation loadInformation)
		{
			return new RubyProject(loadInformation);
		}
Exemple #30
0
		public ProjectLoadInformation ReadProjectEntry(ISolution parentSolution)
		{
			if (currentLine == null)
				return null;
			Match match = projectLinePattern.Match(currentLine);
			if (!match.Success)
				return null;
			NextLine();
			string title = match.Groups["Title"].Value;
			string location = match.Groups["Location"].Value;
			FileName projectFileName = FileName.Create(Path.Combine(parentSolution.Directory, location));
			var loadInformation = new ProjectLoadInformation(parentSolution, projectFileName, title);
			loadInformation.TypeGuid = ParseGuidDefaultEmpty(match.Groups["TypeGuid"].Value);
			loadInformation.IdGuid = ParseGuidDefaultEmpty(match.Groups["IdGuid"].Value);
			SolutionSection section;
			while ((section = ReadSection(isGlobal: false)) != null) {
				loadInformation.ProjectSections.Add(section);
			}
			if (currentLine != "EndProject")
				throw Error("Expected 'EndProject'");
			NextLine();
			return loadInformation;
		}
Exemple #31
0
		public PythonProject(ProjectLoadInformation info)
			: base(info)
		{
		}
Exemple #32
0
		SolutionFolder CreateSolutionFolder(Solution solution, ProjectLoadInformation information)
		{
			var folder = new SolutionFolder(solution, information.IdGuid);
			folder.Name = information.ProjectName;
			// Add solution items:
			var solutionItemsSection = information.ProjectSections.FirstOrDefault(s => s.SectionName == "SolutionItems");
			if (solutionItemsSection != null) {
				foreach (string location in solutionItemsSection.Values) {
					var fileItem = new SolutionFileItem(solution);
					fileItem.FileName = FileName.Create(Path.Combine(information.Solution.Directory, location));
					folder.Items.Add(fileItem);
				}
			}
			return folder;
		}
 public UnknownProject(ProjectLoadInformation information, string warningText)
     : this(information)
 {
     this.warningText = warningText;
 }
Exemple #34
0
		static ProjectSection SetupSolutionLoadSolutionProjects(Solution newSolution, StreamReader sr, IProgressMonitor progressMonitor)
		{
			if (progressMonitor == null)
				throw new ArgumentNullException("progressMonitor");
			
			string solutionDirectory = Path.GetDirectoryName(newSolution.FileName);
			
			ProjectSection nestedProjectsSection = null;
			IList<ProjectLoadInformation> projectsToLoad = new List<ProjectLoadInformation>();
			IList<IList<ProjectSection>> readProjectSections = new List<IList<ProjectSection>>();
			
			// process the solution file contents
			while (true) {
				string line = sr.ReadLine();
				
				if (line == null) {
					break;
				}
				Match match = projectLinePattern.Match(line);
				if (match.Success) {
					string projectGuid  = match.Result("${ProjectGuid}");
					string title        = match.Result("${Title}");
					string location     = match.Result("${Location}");
					string guid         = match.Result("${Guid}");
					
					if (!FileUtility.IsUrl(location)) {
						location = FileUtility.NormalizePath(Path.Combine(solutionDirectory, location));
					}
					
					if (projectGuid == FolderGuid) {
						SolutionFolder newFolder = SolutionFolder.ReadFolder(sr, title, location, guid);
						newSolution.AddFolder(newFolder);
					} else {
						ProjectLoadInformation loadInfo = new ProjectLoadInformation(newSolution, location, title);
						loadInfo.TypeGuid = projectGuid;
						loadInfo.Guid = guid;
						projectsToLoad.Add(loadInfo);
						IList<ProjectSection> currentProjectSections = new List<ProjectSection>();
						ReadProjectSections(sr, currentProjectSections);
						readProjectSections.Add(currentProjectSections);
					}
					match = match.NextMatch();
				} else {
					match = globalSectionPattern.Match(line);
					if (match.Success) {
						ProjectSection newSection = ProjectSection.ReadGlobalSection(sr, match.Result("${Name}"), match.Result("${Type}"));
						// Don't put the NestedProjects section into the global sections list
						// because it's transformed to a tree representation and the tree representation
						// is transformed back to the NestedProjects section during save.
						if (newSection.Name == "NestedProjects") {
							nestedProjectsSection = newSection;
						} else {
							newSolution.Sections.Add(newSection);
						}
					}
				}
			}
			// load projects
			for(int i=0; i<projectsToLoad.Count; i++) {
				ProjectLoadInformation loadInfo = projectsToLoad[i];
				IList<ProjectSection> projectSections = readProjectSections[i];
				loadInfo.ProjectSections = projectSections;
				
				// set the target platform
				SolutionItem projectConfig = newSolution.GetProjectConfiguration(loadInfo.Guid);
				loadInfo.Platform = AbstractProject.GetPlatformNameFromKey(projectConfig.Location);
				
				loadInfo.ProgressMonitor = progressMonitor;
				progressMonitor.Progress = (double)i / projectsToLoad.Count;
				progressMonitor.TaskName = "Loading " + loadInfo.ProjectName;
				
				using (IProgressMonitor nestedProgressMonitor = progressMonitor.CreateSubTask(1.0 / projectsToLoad.Count)) {
					loadInfo.ProgressMonitor = nestedProgressMonitor;
					IProject newProject = ProjectBindingService.LoadProject(loadInfo);
					newProject.IdGuid = loadInfo.Guid;
					newProject.ProjectSections.AddRange(projectSections);
					newSolution.AddFolder(newProject);
				}
			}
			return nestedProjectsSection;
		}
		public MSBuildBasedProject(ProjectLoadInformation loadInformation)
		{
			if (loadInformation == null)
				throw new ArgumentNullException("loadInformation");
			this.Name = loadInformation.ProjectName;
			isLoading = true;
			try {
				try {
					LoadProjectInternal(loadInformation);
				} catch (InvalidProjectFileException ex) {
					if (!(ex.ErrorCode == "MSB4132" && UpgradeToolsVersion(loadInformation))) {
						throw;
					}
				}
			} catch (InvalidProjectFileException ex) {
				LoggingService.Warn(ex);
				LoggingService.Warn("ErrorCode = " + ex.ErrorCode);
				Dispose();
				throw new ProjectLoadException(ex.Message, ex);
			} finally {
				isLoading = false;
			}
		}
Exemple #36
0
		protected CompilableProject(ProjectLoadInformation information)
			: base(information)
		{
		}
		void LoadProjectInternal(ProjectLoadInformation loadInformation)
		{
			this.projectCollection = loadInformation.ParentSolution.MSBuildProjectCollection;
			this.FileName = loadInformation.FileName;
			this.ActivePlatform = loadInformation.Platform;
			
			projectFile = ProjectRootElement.Open(loadInformation.FileName, projectCollection);
			if (loadInformation.upgradeToolsVersion == true && CanUpgradeToolsVersion()) {
				projectFile.ToolsVersion = autoUpgradeNewToolsVersion;
			}
			
			string userFileName = loadInformation.FileName + ".user";
			if (File.Exists(userFileName)) {
				try {
					userProjectFile = ProjectRootElement.Open(userFileName, projectCollection);
				} catch (InvalidProjectFileException ex) {
					throw new ProjectLoadException("Error loading user part " + userFileName + ":\n" + ex.Message, ex);
				}
			} else {
				userProjectFile = ProjectRootElement.Create(userFileName, projectCollection);
			}
			
			this.ActiveConfiguration = GetEvaluatedProperty("Configuration") ?? this.ActiveConfiguration;
			this.ActivePlatform = GetEvaluatedProperty("Platform") ?? this.ActivePlatform;
			
			CreateItemsListFromMSBuild();
			LoadConfigurationPlatformNamesFromMSBuild();
			
			base.IdGuid = GetEvaluatedProperty(ProjectGuidPropertyName);
		}
		//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();
			}
		}
Exemple #39
0
		public UnknownProject(ProjectLoadInformation information)
			: base(information)
		{
		}
Exemple #40
0
		public VBNetProject(ProjectLoadInformation info)
			: base(info)
		{
			InitVB();
		}
		public void NotMSBuildBasedProject()
		{
			ProjectLoadInformation info = new ProjectLoadInformation(MockSolution.Create(), FileName.Create(@"C:\Projects\Test.proj"), "Test");
			
			MissingProject project = new MissingProject(info);
			ITestProject testProject = new NUnitTestProject(project);
			NUnitConsoleApplication app = new NUnitConsoleApplication(new[] { testProject });
			
			Assert.AreEqual(project.GetType().BaseType, typeof(AbstractProject), "MissingProject should be derived from AbstractProject.");
			Assert.AreEqual(@"D:\SharpDevelop\bin\Tools\NUnit\nunit-console.exe", app.FileName);
		}
Exemple #42
0
		static IProject LoadProjectWithErrorHandling(ProjectLoadInformation projectInfo)
		{
			Exception exception;
			try {
				return SD.ProjectService.LoadProject(projectInfo);
			} catch (FileNotFoundException) {
				return new MissingProject(projectInfo);
			} catch (ProjectLoadException ex) {
				exception = ex;
			} catch (IOException ex) {
				exception = ex;
			} catch (UnauthorizedAccessException ex) {
				exception = ex;
			}
			LoggingService.Warn("Project load error", exception);
			return new UnknownProject(projectInfo, exception.Message);
		}