コード例 #1
0
 public FileTemplateResult(FileTemplateOptions options)
 {
     if (options == null)
     {
         throw new ArgumentNullException("options");
     }
     this.options = options;
 }
コード例 #2
0
        /// <summary>
        /// Creates an OpenedFile for the new file, fills it with the file content, and saves it to disk.
        /// </summary>
        OpenedFile SaveFile(FileDescriptionTemplate newFile, string content, string binaryFileName, FileTemplateOptions options, out bool shouldOpen)
        {
            shouldOpen = false;
            string unresolvedFileName = StringParser.Parse(newFile.Name);
            // Parse twice so that tags used in included standard header are parsed
            string parsedContent = StringParser.Parse(StringParser.Parse(content));

            if (parsedContent != null)
            {
                if (SD.EditorControlService.GlobalOptions.IndentationString != "\t")
                {
                    parsedContent = parsedContent.Replace("\t", SD.EditorControlService.GlobalOptions.IndentationString);
                }
            }


            // when newFile.Name is "${Path}/${FileName}", there might be a useless '/' in front of the file name
            // if the file is created when no project is opened. So we remove single '/' or '\', but not double
            // '\\' (project is saved on network share).
            if (unresolvedFileName.StartsWith("/", StringComparison.Ordinal) && !unresolvedFileName.StartsWith("//", StringComparison.Ordinal) ||
                unresolvedFileName.StartsWith("\\", StringComparison.Ordinal) && !unresolvedFileName.StartsWith("\\\\", StringComparison.Ordinal))
            {
                unresolvedFileName = unresolvedFileName.Substring(1);
            }

            var project  = options.Project;
            var fileName = FileName.Create(unresolvedFileName);

            if (newFile.IsDependentFile && Path.IsPathRooted(fileName))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                if (!String.IsNullOrEmpty(binaryFileName))
                {
                    File.Copy(binaryFileName, fileName);
                }
                else
                {
                    File.WriteAllText(fileName, parsedContent, SD.FileService.DefaultFileEncoding);
                }
                if (project != null)
                {
                    AddTemplateFileToProject(project, newFile, fileName);
                }
                return(SD.FileService.GetOrCreateOpenedFile(fileName));
            }
            else
            {
                if (!String.IsNullOrEmpty(binaryFileName))
                {
                    LoggingService.Warn("binary file was skipped");
                    return(null);
                }
                var        data = SD.FileService.DefaultFileEncoding.GetBytesWithPreamble(parsedContent);
                OpenedFile file = null;
                try {
                    if (Path.IsPathRooted(fileName))
                    {
                        file = SD.FileService.GetOrCreateOpenedFile(fileName);
                        file.SetData(data);

                        Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                        file.SaveToDisk();

                        if (project != null)
                        {
                            AddTemplateFileToProject(project, newFile, fileName);
                        }
                    }
                    else
                    {
                        file = SD.FileService.CreateUntitledOpenedFile(Path.GetFileName(fileName), data);
                    }
                    shouldOpen = true;
                    OpenedFile retVal = file;
                    file = null;                     // don't close file when there was no exception and we're returning it
                    return(retVal);
                } finally {
                    if (file != null)
                    {
                        file.CloseIfAllViewsClosed();
                    }
                }
            }
        }
コード例 #3
0
		string SaveFile(FileDescriptionTemplate newFile, string content, string binaryFileName, FileTemplateOptions options)
		{
			string unresolvedFileName = StringParser.Parse(newFile.Name);
			// Parse twice so that tags used in included standard header are parsed
			string parsedContent = StringParser.Parse(StringParser.Parse(content));
			
			if (parsedContent != null) {
				if (SD.EditorControlService.GlobalOptions.IndentationString != "\t") {
					parsedContent = parsedContent.Replace("\t", SD.EditorControlService.GlobalOptions.IndentationString);
				}
			}
			
			
			// when newFile.Name is "${Path}/${FileName}", there might be a useless '/' in front of the file name
			// if the file is created when no project is opened. So we remove single '/' or '\', but not double
			// '\\' (project is saved on network share).
			if (unresolvedFileName.StartsWith("/") && !unresolvedFileName.StartsWith("//")
			    || unresolvedFileName.StartsWith("\\") && !unresolvedFileName.StartsWith("\\\\"))
			{
				unresolvedFileName = unresolvedFileName.Substring(1);
			}
			
			var project = options.Project;
			var fileName = FileName.Create(unresolvedFileName);
			
			if (newFile.IsDependentFile && Path.IsPathRooted(fileName)) {
				Directory.CreateDirectory(Path.GetDirectoryName(fileName));
				if (!String.IsNullOrEmpty(binaryFileName))
					File.Copy(binaryFileName, fileName);
				else
					File.WriteAllText(fileName, parsedContent, SD.FileService.DefaultFileEncoding);
				if (project != null)
					AddTemplateFileToProject(project, newFile, fileName);
			} else {
				if (!String.IsNullOrEmpty(binaryFileName)) {
					LoggingService.Warn("binary file was skipped");
					return null;
				}
				var data = SD.FileService.DefaultFileEncoding.GetBytesWithPreamble(parsedContent);
				OpenedFile file = null;
				try {
					if (Path.IsPathRooted(fileName)) {
						file = SD.FileService.GetOrCreateOpenedFile(fileName);
						file.SetData(data);
						
						Directory.CreateDirectory(Path.GetDirectoryName(fileName));
						file.SaveToDisk();
						
						if (project != null)
							AddTemplateFileToProject(project, newFile, fileName);
					} else {
						file = SD.FileService.CreateUntitledOpenedFile(Path.GetFileName(fileName), data);
					}
					
					SD.FileService.OpenFile(file.FileName);
				} finally {
					if (file != null)
						file.CloseIfAllViewsClosed();
				}
			}
			
			return fileName;
		}
コード例 #4
0
        public override FileTemplateResult Create(FileTemplateOptions options)
        {
            FileTemplateResult result = new FileTemplateResult(options);

            StandardHeader.SetHeaders();
            StringParserPropertyContainer.FileCreation["StandardNamespace"]        = options.Namespace;
            StringParserPropertyContainer.FileCreation["FullName"]                 = options.FileName;
            StringParserPropertyContainer.FileCreation["FileName"]                 = Path.GetFileName(options.FileName);
            StringParserPropertyContainer.FileCreation["FileNameWithoutExtension"] = Path.GetFileNameWithoutExtension(options.FileName);
            StringParserPropertyContainer.FileCreation["Extension"]                = Path.GetExtension(options.FileName);
            StringParserPropertyContainer.FileCreation["Path"] = Path.GetDirectoryName(options.FileName);

            StringParserPropertyContainer.FileCreation["ClassName"] = options.ClassName;

            // when adding a file to a project (but not when creating a standalone file while a project is open):
            var project = options.Project;

            if (project != null && !options.IsUntitled)
            {
                // add required assembly references to the project
                foreach (ReferenceProjectItem reference in RequiredAssemblyReferences)
                {
                    IEnumerable <ProjectItem> refs = project.GetItemsOfType(ItemType.Reference);
                    if (!refs.Any(projItem => string.Equals(projItem.Include, reference.Include, StringComparison.OrdinalIgnoreCase)))
                    {
                        ReferenceProjectItem projItem = (ReferenceProjectItem)reference.CloneFor(project);
                        ProjectService.AddProjectItem(project, projItem);
                        //ProjectBrowserPad.RefreshViewAsync();
                    }
                }
            }

            foreach (FileDescriptionTemplate newfile in FileDescriptionTemplates)
            {
                if (!IsFilenameAvailable(StringParser.Parse(newfile.Name)))
                {
                    MessageService.ShowError(string.Format("Filename {0} is in use.\nChoose another one", StringParser.Parse(newfile.Name)));                     // TODO : translate
                    return(null);
                }
            }
            try {
                var          filesToOpen  = new List <FileName>();
                ScriptRunner scriptRunner = new ScriptRunner();
                foreach (FileDescriptionTemplate newFile in FileDescriptionTemplates)
                {
                    FileOperationResult opresult = FileUtility.ObservedSave(
                        () => {
                        OpenedFile resultFile;
                        bool shouldOpen;
                        if (!String.IsNullOrEmpty(newFile.BinaryFileName))
                        {
                            resultFile = SaveFile(newFile, null, newFile.BinaryFileName, options, out shouldOpen);
                        }
                        else
                        {
                            resultFile = SaveFile(newFile, scriptRunner.CompileScript(this, newFile), null, options, out shouldOpen);
                        }
                        if (resultFile != null)
                        {
                            result.NewOpenedFiles.Add(resultFile);
                            result.NewFiles.Add(resultFile.FileName);
                            if (shouldOpen)
                            {
                                filesToOpen.Add(resultFile.FileName);
                            }
                        }
                    }, FileName.Create(StringParser.Parse(newFile.Name))
                        );
                    if (opresult != FileOperationResult.OK)
                    {
                        return(null);
                    }
                }

                // Run creation actions
                if (createActions != null)
                {
                    createActions(result);
                }

                foreach (var filename in filesToOpen.Intersect(result.NewFiles))
                {
                    SD.FileService.OpenFile(filename);
                }
            } finally {
                // Now that the view contents
                foreach (var file in result.NewOpenedFiles)
                {
                    file.CloseIfAllViewsClosed();
                }
                result.NewOpenedFiles.RemoveAll(f => f.RegisteredViewContents.Count == 0);
            }
            // raise FileCreated event for the new files.
            foreach (var fileName in result.NewFiles)
            {
                FileService.FireFileCreated(fileName, false);
            }

            if (project != null)
            {
                project.Save();
            }

            return(result);
        }
コード例 #5
0
		public override FileTemplateResult Create(FileTemplateOptions options)
		{
			FileTemplateResult result = new FileTemplateResult(options);
			
			StandardHeader.SetHeaders();
			StringParserPropertyContainer.FileCreation["StandardNamespace"] = options.Namespace;
			StringParserPropertyContainer.FileCreation["FullName"]                 = options.FileName;
			StringParserPropertyContainer.FileCreation["FileName"]                 = Path.GetFileName(options.FileName);
			StringParserPropertyContainer.FileCreation["FileNameWithoutExtension"] = Path.GetFileNameWithoutExtension(options.FileName);
			StringParserPropertyContainer.FileCreation["Extension"]                = Path.GetExtension(options.FileName);
			StringParserPropertyContainer.FileCreation["Path"]                     = Path.GetDirectoryName(options.FileName);
			
			StringParserPropertyContainer.FileCreation["ClassName"] = options.ClassName;
			
			// when adding a file to a project (but not when creating a standalone file while a project is open):
			var project = options.Project;
			if (project != null && !options.IsUntitled) {
				// add required assembly references to the project
				foreach (ReferenceProjectItem reference in RequiredAssemblyReferences) {
					IEnumerable<ProjectItem> refs = project.GetItemsOfType(ItemType.Reference);
					if (!refs.Any(projItem => string.Equals(projItem.Include, reference.Include, StringComparison.OrdinalIgnoreCase))) {
						ReferenceProjectItem projItem = (ReferenceProjectItem)reference.CloneFor(project);
						ProjectService.AddProjectItem(project, projItem);
						ProjectBrowserPad.RefreshViewAsync();
					}
				}
			}
			
			foreach (FileDescriptionTemplate newfile in FileDescriptionTemplates) {
				if (!IsFilenameAvailable(StringParser.Parse(newfile.Name))) {
					MessageService.ShowError(string.Format("Filename {0} is in use.\nChoose another one", StringParser.Parse(newfile.Name))); // TODO : translate
					return null;
				}
			}
			ScriptRunner scriptRunner = new ScriptRunner();
			foreach (FileDescriptionTemplate newFile in FileDescriptionTemplates) {
				FileOperationResult opresult = FileUtility.ObservedSave(
					() => {
						string resultFile;
						if (!String.IsNullOrEmpty(newFile.BinaryFileName)) {
							resultFile = SaveFile(newFile, null, newFile.BinaryFileName, options);
						} else {
							resultFile = SaveFile(newFile, scriptRunner.CompileScript(this, newFile), null, options);
						}
						if (resultFile != null) {
							result.NewFiles.Add(FileName.Create(resultFile));
						}
					}, FileName.Create(StringParser.Parse(newFile.Name))
				);
				if (opresult != FileOperationResult.OK)
					return null;
			}
			
			if (project != null) {
				project.Save();
			}
			
			// raise FileCreated event for the new files.
			foreach (var fileName in result.NewFiles) {
				FileService.FireFileCreated(fileName, false);
			}
			return result;
		}
コード例 #6
0
		public FileTemplateResult(FileTemplateOptions options)
		{
			if (options == null)
				throw new ArgumentNullException("options");
			this.options = options;
		}
コード例 #7
0
ファイル: FileTemplate.cs プロジェクト: ichengzi/SharpDevelop
 /// <summary>
 /// Instanciates the template, writes the new files to disk, and adds them to the project.
 /// </summary>
 public abstract FileTemplateResult Create(FileTemplateOptions options);
コード例 #8
0
		void OpenEvent(object sender, EventArgs e)
		{
			if (categoryTreeView.SelectedNode != null) {
				PropertyService.Set("Dialogs.NewProjectDialog.LargeImages", ((RadioButton)ControlDictionary["largeIconsRadioButton"]).Checked);
				PropertyService.Set("Dialogs.NewFileDialog.CategoryViewState", TreeViewHelper.GetViewStateString(categoryTreeView));
				PropertyService.Set("Dialogs.NewFileDialog.LastSelectedCategory", TreeViewHelper.GetPath(categoryTreeView.SelectedNode));
			}
			if (templateListView.SelectedItems.Count == 1) {
				TemplateItem item = (TemplateItem)templateListView.SelectedItems[0];
				
				PropertyService.Set("Dialogs.NewFileDialog.LastSelectedTemplate", item.Template.Name);
				
				string fileName;
				string standardNamespace = "DefaultNamespace";
				if (allowUntitledFiles) {
					fileName = GenerateCurrentFileName();
				} else {
					fileName = ControlDictionary["fileNameTextBox"].Text.Trim();
					if (!FileUtility.IsValidPath(fileName)
					    || fileName.IndexOf(Path.AltDirectorySeparatorChar) >= 0
					    || fileName.IndexOf(Path.DirectorySeparatorChar) >= 0)
					{
						MessageService.ShowError(StringParser.Parse("${res:ICSharpCode.SharpDevelop.Commands.SaveFile.InvalidFileNameError}", new StringTagPair("FileName", fileName)));
						return;
					}
					if (Path.GetExtension(fileName).Length == 0) {
						fileName += Path.GetExtension(item.Template.SuggestFileName(null));
					}
					fileName = Path.Combine(basePath, fileName);
					fileName = FileUtility.NormalizePath(fileName);
					if (project != null) {
						standardNamespace = CustomToolsService.GetDefaultNamespace(project, fileName);
					}
				}
				
				options = new FileTemplateOptions();
				options.ClassName = GenerateValidClassOrNamespaceName(Path.GetFileNameWithoutExtension(fileName), false);
				options.FileName = FileName.Create(fileName);
				options.IsUntitled = allowUntitledFiles;
				options.Namespace = standardNamespace;
				options.CustomizationObject = localizedTypeDescriptor;
				options.Project = project;
				
				result = SelectedTemplate.Create(options);
				DialogResult = DialogResult.OK;
				if (result != null)
					SelectedTemplate.RunActions(result);
			}
		}
コード例 #9
0
 /// <summary>
 /// Instanciates the template, writes the new files to disk, and adds them to the project.
 /// </summary>
 public abstract FileTemplateResult Create(FileTemplateOptions options);