Ejemplo n.º 1
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));
            }
            createdFiles.Clear();
            if (templateListView.SelectedItems.Count == 1)
            {
                if (!AllPropertiesHaveAValue)
                {
                    MessageService.ShowMessage("${res:Dialog.NewFile.FillOutFirstMessage}", "${res:Dialog.NewFile.FillOutFirstCaption}");
                    return;
                }
                TemplateItem item = (TemplateItem)templateListView.SelectedItems[0];

                PropertyService.Set("Dialogs.NewFileDialog.LastSelectedTemplate", item.Template.Name);

                string fileName;
                StringParserPropertyContainer.FileCreation["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.DefaultName);
                    }
                    fileName = Path.Combine(basePath, fileName);
                    fileName = FileUtility.NormalizePath(fileName);
                    IProject project = ProjectService.CurrentProject;
                    if (project != null)
                    {
                        StringParserPropertyContainer.FileCreation["StandardNamespace"] = CustomToolsService.GetDefaultNamespace(project, fileName);
                    }
                }

                FileTemplateOptions options = new FileTemplateOptions();
                options.ClassName  = GenerateValidClassOrNamespaceName(Path.GetFileNameWithoutExtension(fileName), false);
                options.FileName   = FileName.Create(fileName);
                options.IsUntitled = allowUntitledFiles;
                options.Namespace  = StringParserPropertyContainer.FileCreation["StandardNamespace"];

                StringParserPropertyContainer.FileCreation["FullName"] = fileName;
                StringParserPropertyContainer.FileCreation["FileName"] = Path.GetFileName(fileName);
                StringParserPropertyContainer.FileCreation["FileNameWithoutExtension"] = Path.GetFileNameWithoutExtension(fileName);
                StringParserPropertyContainer.FileCreation["Extension"] = Path.GetExtension(fileName);
                StringParserPropertyContainer.FileCreation["Path"]      = Path.GetDirectoryName(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):
                if (ProjectService.CurrentProject != null && !this.allowUntitledFiles)
                {
                    options.Project = ProjectService.CurrentProject;
                    // add required assembly references to the project
                    bool changes = false;
                    foreach (ReferenceProjectItem reference in item.Template.RequiredAssemblyReferences)
                    {
                        IEnumerable <ProjectItem> refs = ProjectService.CurrentProject.GetItemsOfType(ItemType.Reference);
                        if (!refs.Any(projItem => string.Equals(projItem.Include, reference.Include, StringComparison.OrdinalIgnoreCase)))
                        {
                            ReferenceProjectItem projItem = (ReferenceProjectItem)reference.CloneFor(ProjectService.CurrentProject);
                            ProjectService.AddProjectItem(ProjectService.CurrentProject, projItem);
                            changes = true;
                        }
                    }
                    if (changes)
                    {
                        ProjectService.CurrentProject.Save();
                    }
                }

                foreach (FileDescriptionTemplate newfile in item.Template.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;
                    }
                }
                ScriptRunner scriptRunner = new ScriptRunner();
                foreach (FileDescriptionTemplate newFile in item.Template.FileDescriptionTemplates)
                {
                    FileOperationResult result = FileUtility.ObservedSave(
                        () => {
                        if (!String.IsNullOrEmpty(newFile.BinaryFileName))
                        {
                            SaveFile(newFile, null, newFile.BinaryFileName);
                        }
                        else
                        {
                            SaveFile(newFile, scriptRunner.CompileScript(item.Template, newFile), null);
                        }
                    }, StringParser.Parse(newFile.Name)
                        );
                    if (result != FileOperationResult.OK)
                    {
                        return;
                    }
                }

                DialogResult = DialogResult.OK;

                // raise FileCreated event for the new files.
                foreach (KeyValuePair <string, FileDescriptionTemplate> entry in createdFiles)
                {
                    FileService.FireFileCreated(entry.Key, false);
                }
                item.Template.RunActions(options);
            }
        }
Ejemplo n.º 2
0
 public string GetDefaultCustomToolForFileName(FileProjectItem projectItem)
 {
     return(CustomToolsService.GetCompatibleCustomToolNames(projectItem).FirstOrDefault());
 }
Ejemplo n.º 3
0
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (context == null || context.PropertyDescriptor == null || context.Instance == null || provider == null)
            {
                return(value);
            }

            IComponent component = context.Instance as IComponent;

            if (component == null || component.Site == null)
            {
                LoggingService.Info("Editing of image properties on objects not implementing IComponent and components without Site is not supported by the ImageResourceEditor.");
                if (typeof(Icon).IsAssignableFrom(context.PropertyDescriptor.PropertyType))
                {
                    return(new IconEditor().EditValue(context, provider, value));
                }
                else
                {
                    return(new ImageEditor().EditValue(context, provider, value));
                }
            }

            var prs = provider.GetService(typeof(ProjectResourceService)) as ProjectResourceService;

            if (prs == null)
            {
                return(value);
            }

            var edsvc = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;

            if (edsvc == null)
            {
                throw new InvalidOperationException("The required IWindowsFormsEditorService is not available.");
            }

            var dictService = component.Site.GetService(typeof(IDictionaryService)) as IDictionaryService;

            if (dictService == null)
            {
                throw new InvalidOperationException("The required IDictionaryService is not available.");
            }

            var projectResource = dictService.GetValue(ProjectResourceService.ProjectResourceKey + context.PropertyDescriptor.Name) as ProjectResourceInfo;

            IProject project = prs.ProjectContent.Project as IProject;
            ImageResourceEditorDialog dialog;

            if (projectResource != null && Object.ReferenceEquals(projectResource.OriginalValue, value) && prs.DesignerSupportsProjectResources)
            {
                dialog = new ImageResourceEditorDialog(project, context.PropertyDescriptor.PropertyType, projectResource);
            }
            else
            {
                if (context.PropertyDescriptor.PropertyType == typeof(Image))
                {
                    dialog = new ImageResourceEditorDialog(project, value as Image, prs.DesignerSupportsProjectResources);
                }
                else if (context.PropertyDescriptor.PropertyType == typeof(Icon))
                {
                    dialog = new ImageResourceEditorDialog(project, value as Icon, prs.DesignerSupportsProjectResources);
                }
                else
                {
                    throw new InvalidOperationException("ImageResourceEditor called on unsupported property type: " + context.PropertyDescriptor.PropertyType.ToString());
                }
            }

            using (dialog) {
                if (edsvc.ShowDialog(dialog) == DialogResult.OK)
                {
                    projectResource = dialog.SelectedProjectResource;
                    if (projectResource != null)
                    {
                        dictService.SetValue(ProjectResourceService.ProjectResourceKey + context.PropertyDescriptor.Name, projectResource);

                        // Ensure the resource generator is turned on for the selected resource file.
                        if (project != null)
                        {
                            FileProjectItem fpi = project.FindFile(projectResource.ResourceFile);
                            if (fpi == null)
                            {
                                throw new InvalidOperationException("The selected resource file '" + projectResource.ResourceFile + "' was not found in the project.");
                            }
                            const string resourceGeneratorToolName       = "ResXFileCodeGenerator";
                            const string publicResourceGeneratorToolName = "PublicResXFileCodeGenerator";
                            if (!String.Equals(resourceGeneratorToolName, fpi.CustomTool, StringComparison.Ordinal) &&
                                !String.Equals(publicResourceGeneratorToolName, fpi.CustomTool, StringComparison.Ordinal))
                            {
                                fpi.CustomTool = resourceGeneratorToolName;
                            }
                            CustomToolsService.RunCustomTool(fpi, true);
                        }

                        return(projectResource.OriginalValue);
                    }
                    else
                    {
                        dictService.SetValue(ProjectResourceService.ProjectResourceKey + context.PropertyDescriptor.Name, null);
                        return(dialog.SelectedResourceValue);
                    }
                }
            }

            return(value);
        }
        void ProjectTreeScanningBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            if (this.project == null)
            {
                return;
            }

            ProjectResourceInfo selectedProjectResource = e.Argument as ProjectResourceInfo;

            IProjectContent projectContent = ParserService.GetProjectContent(this.project);

            TreeNode root           = new TreeNode(this.project.Name, 0, 0);
            TreeNode preSelection   = null;
            TreeNode lastFileNode   = null;
            int      fileNodesCount = 0;

            foreach (FileProjectItem item in this.project.GetItemsOfType(ItemType.EmbeddedResource).OfType <FileProjectItem>().OrderBy(fpi => Path.GetFileName(fpi.VirtualName)))
            {
                if (this.projectTreeScanningBackgroundWorker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                // Skip files where the generated class name
                // would conflict with an existing class.
                string namespaceName = item.GetEvaluatedMetadata("CustomToolNamespace");
                if (string.IsNullOrEmpty(namespaceName))
                {
                    namespaceName = CustomToolsService.GetDefaultNamespace(item.Project, item.FileName);
                }
                IClass existingClass = projectContent.GetClass(namespaceName + "." + StronglyTypedResourceBuilder.VerifyResourceName(Path.GetFileNameWithoutExtension(item.FileName), projectContent.Language.CodeDomProvider), 0);
                if (existingClass != null)
                {
                    if (!ProjectResourceService.IsGeneratedResourceClass(existingClass))
                    {
                        continue;
                    }
                }

                bool     selectedFile = (selectedProjectResource != null) && FileUtility.IsEqualFileName(selectedProjectResource.ResourceFile, item.FileName);
                TreeNode file         = null;

                try {
                    foreach (KeyValuePair <string, object> r in this.GetResources(item.FileName).OrderBy(pair => pair.Key))
                    {
                        if (this.projectTreeScanningBackgroundWorker.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }

                        if (file == null)
                        {
                            file = CreateAndAddFileNode(root, item);
                        }

                        TreeNode resNode = new TreeNode(r.Key, 3, 3);
                        resNode.Tag = r.Value;
                        file.Nodes.Add(resNode);

                        if (selectedFile)
                        {
                            if (String.Equals(r.Key, selectedProjectResource.ResourceKey, StringComparison.Ordinal))
                            {
                                preSelection = resNode;
                            }
                        }
                    }

                    if (file != null)
                    {
                        lastFileNode = file;
                        ++fileNodesCount;
                    }
                } catch (Exception ex) {
                    if (file == null)
                    {
                        file = CreateAndAddFileNode(root, item);
                    }
                    TreeNode error = new TreeNode(ex.Message, 4, 4);
                    file.Nodes.Add(error);
                }
            }

            if (e.Cancel)
            {
                DisposeNodeImages(root);
            }
            else
            {
                // Preselect the file node if there is only one
                if (preSelection == null && fileNodesCount == 1)
                {
                    preSelection = lastFileNode;
                }
                e.Result = new TreeScanResult(root, preSelection);
            }
        }
Ejemplo n.º 5
0
        void OpenEvent(object sender, EventArgs e)
        {
            if (((TreeView)ControlDictionary["categoryTreeView"]).SelectedNode != null)
            {
                PropertyService.Set("Dialogs.NewProjectDialog.LargeImages", ((RadioButton)ControlDictionary["largeIconsRadioButton"]).Checked);
                PropertyService.Set("Dialogs.NewFileDialog.LastSelectedCategory", ((TreeView)ControlDictionary["categoryTreeView"]).SelectedNode.Text);
            }
            createdFiles.Clear();
            if (((ListView)ControlDictionary["templateListView"]).SelectedItems.Count == 1)
            {
                if (!AllPropertiesHaveAValue)
                {
                    MessageService.ShowMessage("${res:Dialog.NewFile.FillOutFirstMessage}", "${res:Dialog.NewFile.FillOutFirstCaption}");
                    return;
                }
                TemplateItem item = (TemplateItem)((ListView)ControlDictionary["templateListView"]).SelectedItems[0];
                string       fileName;
                StringParser.Properties["StandardNamespace"] = "DefaultNamespace";
                if (allowUntitledFiles)
                {
                    fileName = GenerateCurrentFileName();
                }
                else
                {
                    fileName = ControlDictionary["fileNameTextBox"].Text.Trim();
                    if (!FileUtility.IsValidFileName(fileName) ||
                        fileName.IndexOf(Path.AltDirectorySeparatorChar) >= 0 ||
                        fileName.IndexOf(Path.DirectorySeparatorChar) >= 0)
                    {
                        MessageService.ShowError(StringParser.Parse("${res:ICSharpCode.SharpDevelop.Commands.SaveFile.InvalidFileNameError}", new string[, ] {
                            { "FileName", fileName }
                        }));
                        return;
                    }
                    if (Path.GetExtension(fileName).Length == 0)
                    {
                        fileName += Path.GetExtension(item.Template.DefaultName);
                    }
                    fileName = Path.Combine(basePath, fileName);
                    fileName = Path.GetFullPath(fileName);
                    IProject project = ProjectService.CurrentProject;
                    if (project != null)
                    {
                        StringParser.Properties["StandardNamespace"] = CustomToolsService.GetDefaultNamespace(project, fileName);
                    }
                }
                StringParser.Properties["FullName"] = fileName;
                StringParser.Properties["FileName"] = Path.GetFileName(fileName);
                StringParser.Properties["FileNameWithoutExtension"] = Path.GetFileNameWithoutExtension(fileName);
                StringParser.Properties["Extension"] = Path.GetExtension(fileName);
                StringParser.Properties["Path"]      = Path.GetDirectoryName(fileName);

                StringParser.Properties["ClassName"] = GenerateValidClassName(Path.GetFileNameWithoutExtension(fileName));


                if (item.Template.WizardPath != null)
                {
                    Properties customizer = new Properties();
                    customizer.Set("Template", item.Template);
                    customizer.Set("Creator", this);
                    WizardDialog wizard = new WizardDialog("File Wizard", customizer, item.Template.WizardPath);
                    if (wizard.ShowDialog(ICSharpCode.SharpDevelop.Gui.WorkbenchSingleton.MainForm) == DialogResult.OK)
                    {
                        DialogResult = DialogResult.OK;
                    }
                }
                else
                {
                    foreach (FileDescriptionTemplate newfile in item.Template.FileDescriptionTemplates)
                    {
                        if (!IsFilenameAvailable(StringParser.Parse(newfile.Name)))
                        {
                            MessageService.ShowError("Filename " + StringParser.Parse(newfile.Name) + " is in use.\nChoose another one");
                            return;
                        }
                    }
                    ScriptRunner scriptRunner = new ScriptRunner();

                    foreach (FileDescriptionTemplate newfile in item.Template.FileDescriptionTemplates)
                    {
                        if (newfile.ContentData != null)
                        {
                            SaveFile(newfile, null, newfile.ContentData);
                        }
                        else
                        {
                            SaveFile(newfile, scriptRunner.CompileScript(item.Template, newfile), null);
                        }
                    }
                    DialogResult = DialogResult.OK;

                    // raise FileCreated event for the new files
                    foreach (KeyValuePair <string, FileDescriptionTemplate> entry in createdFiles)
                    {
                        FileService.FireFileCreated(entry.Key);
                    }
                }
            }
        }