/// <summary>
        /// Shows the 'Browse for folder' dialog.
        /// </summary>
        /// <param name="description">A description shown inside the dialog.</param>
        /// <param name="startLocation">Start location, relative to the <see cref="BaseDirectory"/></param>
        /// <param name="textBoxEditMode">The TextBoxEditMode used for the text box containing the file name</param>
        /// <returns>Returns the location of the folder; or null if the dialog was cancelled.</returns>
        private string BrowseForFolder(string description, string startLocation, TextBoxEditMode textBoxEditMode)
        {
            string startAt = GetInitialDirectory(startLocation, textBoxEditMode, false);
            string path    = SD.FileService.BrowseForFolder(description, startAt);

            if (String.IsNullOrEmpty(path))
            {
                return(null);
            }
            else
            {
                if (!String.IsNullOrEmpty(startLocation))
                {
                    path = FileUtility.GetRelativePath(startLocation, path);
                }
                if (!path.EndsWith("\\", StringComparison.Ordinal) && !path.EndsWith("/", StringComparison.Ordinal))
                {
                    path += "\\";
                }
                if (textBoxEditMode == TextBoxEditMode.EditEvaluatedProperty)
                {
                    return(path);
                }
                else
                {
                    return(MSBuildInternals.Escape(path));
                }
            }
        }
Example #2
0
 void FindKeys(string directory)
 {
     directory = FileUtility.NormalizePath(directory);
     while (true)
     {
         try {
             foreach (string fileName in Directory.GetFiles(directory, "*.snk"))
             {
                 keyFile.Add(MSBuildInternals.Escape(FileUtility.GetRelativePath(base.BaseDirectory, fileName)));
             }
             foreach (string fileName in Directory.GetFiles(directory, "*.pfx"))
             {
                 keyFile.Add(MSBuildInternals.Escape(FileUtility.GetRelativePath(base.BaseDirectory, fileName)));
             }
             foreach (string fileName in Directory.GetFiles(directory, "*.key"))
             {
                 keyFile.Add(MSBuildInternals.Escape(FileUtility.GetRelativePath(base.BaseDirectory, fileName)));
             }
         } catch {
             // can happen for networked drives / network locations
             break;
         }
         int pos = directory.LastIndexOf(Path.DirectorySeparatorChar);
         if (pos < 0)
         {
             break;
         }
         directory = directory.Substring(0, pos);
     }
 }
Example #3
0
        /// <summary>
        /// Shows an 'Open File' dialog.
        /// </summary>
        /// <param name="filter">The filter string that determines which files are displayed.</param>
        /// <param name="startLocation">Start location, relative to the <see cref="BaseDirectory"/></param>
        /// <param name="textBoxEditMode">The TextBoxEditMode used for the text box containing the file name</param>
        /// <returns>Returns the location of the file; or null if the dialog was cancelled.</returns>
        protected string BrowseForFile(string filter, string startLocation, TextBoxEditMode textBoxEditMode)
        {
            var dialog = new OpenFileDialog();

            dialog.InitialDirectory = GetInitialDirectory(startLocation, textBoxEditMode, true);

            if (!String.IsNullOrEmpty(filter))
            {
                dialog.Filter = StringParser.Parse(filter);
            }

            if (dialog.ShowDialog() == true)
            {
                string fileName = dialog.FileName;
                if (!String.IsNullOrEmpty(this.BaseDirectory))
                {
                    fileName = FileUtility.GetRelativePath(this.BaseDirectory, fileName);
                }
                if (textBoxEditMode == TextBoxEditMode.EditEvaluatedProperty)
                {
                    return(fileName);
                }
                else
                {
                    return(MSBuildInternals.Escape(fileName));
                }
            }
            return(null);
        }
Example #4
0
 public void SetUpFixture()
 {
     wixNodeBuilder   = new WixProjectNodeBuilder();
     project          = new MSBuildBasedProject(MSBuildInternals.CreateEngine());
     project.IdGuid   = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF";
     project.FileName = @"C:\Projects\Test\test.csproj";
 }
Example #5
0
        /// <summary>
        /// Shows the 'Browse for folder' dialog.
        /// </summary>
        /// <param name="description">A description shown inside the dialog.</param>
        /// <param name="startLocation">Start location, relative to the <see cref="BaseDirectory"/></param>
        /// <param name="textBoxEditMode">The TextBoxEditMode used for the text box containing the file name</param>
        /// <returns>Returns the location of the folder; or null if the dialog was cancelled.</returns>
        protected string BrowseForFolder(string description, string startLocation, TextBoxEditMode textBoxEditMode)
        {
            string startAt = GetInitialDirectory(startLocation, textBoxEditMode, false);

            using (var fdiag = FileService.CreateFolderBrowserDialog(description, startAt))
            {
                if (fdiag.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string path = fdiag.SelectedPath;
                    if (!String.IsNullOrEmpty(startLocation))
                    {
                        path = FileUtility.GetRelativePath(startLocation, path);
                    }
                    if (!path.EndsWith("\\", StringComparison.Ordinal) && !path.EndsWith("/", StringComparison.Ordinal))
                    {
                        path += "\\";
                    }
                    if (textBoxEditMode == TextBoxEditMode.EditEvaluatedProperty)
                    {
                        return(path);
                    }
                    else
                    {
                        return(MSBuildInternals.Escape(path));
                    }
                }
            }
            return(null);
        }
 public void Event(object sender, EventArgs e)
 {
     using (OpenFileDialog fdiag = new OpenFileDialog()) {
         fdiag.Filter      = StringParser.Parse(filter);
         fdiag.Multiselect = false;
         try {
             string initialDir = System.IO.Path.GetDirectoryName(System.IO.Path.Combine(panel.baseDirectory, target.Text));
             if (FileUtility.IsValidPath(initialDir) && System.IO.Directory.Exists(initialDir))
             {
                 fdiag.InitialDirectory = initialDir;
             }
         } catch {}
         if (fdiag.ShowDialog() == DialogResult.OK)
         {
             string file = fdiag.FileName;
             if (panel.baseDirectory != null)
             {
                 file = FileUtility.GetRelativePath(panel.baseDirectory, file);
             }
             if (textBoxEditMode == TextBoxEditMode.EditEvaluatedProperty)
             {
                 target.Text = file;
             }
             else
             {
                 target.Text = MSBuildInternals.Escape(file);
             }
         }
     }
 }
            public void Event(object sender, EventArgs e)
            {
                string startLocation = panel.baseDirectory;

                if (startLocation != null)
                {
                    string text = panel.ControlDictionary[target].Text;
                    if (textBoxEditMode == TextBoxEditMode.EditRawProperty)
                    {
                        text = MSBuildInternals.Unescape(text);
                    }
                    startLocation = FileUtility.GetAbsolutePath(startLocation, text);
                }

                string path = SD.FileService.BrowseForFolder(description, startLocation);

                if (panel.baseDirectory != null)
                {
                    path = FileUtility.GetRelativePath(panel.baseDirectory, path);
                }
                if (!path.EndsWith("\\", StringComparison.Ordinal) && !path.EndsWith("/", StringComparison.Ordinal))
                {
                    path += "\\";
                }
                if (textBoxEditMode == TextBoxEditMode.EditEvaluatedProperty)
                {
                    panel.ControlDictionary[target].Text = path;
                }
                else
                {
                    panel.ControlDictionary[target].Text = MSBuildInternals.Escape(path);
                }
            }
Example #8
0
        private void CreateKeyFile()
        {
            if (File.Exists(StrongNameTool))
            {
                string title   = StringParser.Parse("${res:Dialog.ProjectOptions.Signing.CreateKey.Title}");
                string str     = StringParser.Parse("${res:Dialog.ProjectOptions.Signing.CreateKey.KeyName}");
                var    keyName = str.Remove(str.IndexOf("&"), 1);

                string key = MessageService.ShowInputBox(title, keyName, base.Project.Name);
                if (!String.IsNullOrEmpty(key))
                {
                    if (!key.EndsWith(".snk") && !key.EndsWith(".pfx"))
                    {
                        key += ".snk";
                    }
                    if (CreateKey(Path.Combine(base.Project.Directory, key)))
                    {
                        AssemblyOriginatorKeyFile.Value = MSBuildInternals.Escape(key);
                        keyFileComboBox.Text            = AssemblyOriginatorKeyFile.Value;
                    }
                }
            }
            else
            {
                MessageService.ShowMessage("${res:Dialog.ProjectOptions.Signing.SNnotFound}");
            }
        }
Example #9
0
        public void PartCoverSettingsFileName()
        {
            MSBuildBasedProject project = new MSBuildBasedProject(MSBuildInternals.CreateEngine());

            project.FileName = @"C:\temp\test.csproj";

            Assert.AreEqual(@"C:\temp\test.PartCover.Settings", PartCoverSettings.GetFileName(project));
        }
Example #10
0
 public override IEnumerable <ReferenceProjectItem> ResolveAssemblyReferences(CancellationToken cancellationToken)
 {
     ReferenceProjectItem[] additionalItems =
     {
         new ReferenceProjectItem(this, "mscorlib"),
         new ReferenceProjectItem(this, "Microsoft.VisualBasic"),
     };
     return(MSBuildInternals.ResolveAssemblyReferences(this, additionalItems));
 }
Example #11
0
        /// <summary>
        /// run this method with a .net 3.5 and .net 4.0 project to generate the table above.
        /// </summary>
        void CreateReferenceToFrameworkTable()
        {
            LoggingService.Warn("Running CreateReferenceToFrameworkTable()");

            MSBuildBasedProject project = selectDialog.ConfigureProject as MSBuildBasedProject;

            if (project == null)
            {
                return;
            }

            var redistNameToRequiredFramework = new Dictionary <string, string> {
                { "Framework", null },
                { "Microsoft-Windows-CLRCoreComp", null },
                { "Microsoft.VisualStudio.Primary.Interop.Assemblies.8.0", null },
                { "Microsoft-WinFX-Runtime", "3.0" },
                { "Microsoft-Windows-CLRCoreComp.3.0", "3.0" },
                { "Microsoft-Windows-CLRCoreComp-v3.5", "3.5" },
                { "Microsoft-Windows-CLRCoreComp.4.0", "4.0" },
            };

            using (StreamWriter w = new StreamWriter("c:\\temp\\references.txt")) {
                List <ReferenceProjectItem> referenceItems = new List <ReferenceProjectItem>();
                WorkbenchSingleton.SafeThreadCall(
                    delegate {
                    foreach (ListViewItem item in fullItemList)
                    {
                        referenceItems.Add(new ReferenceProjectItem(project, item.Tag.ToString()));
                    }
                });

                MSBuildInternals.ResolveAssemblyReferences(project, referenceItems.ToArray());
                foreach (ReferenceProjectItem rpi in referenceItems)
                {
                    if (string.IsNullOrEmpty(rpi.Redist))
                    {
                        continue;
                    }
                    if (!redistNameToRequiredFramework.ContainsKey(rpi.Redist))
                    {
                        LoggingService.Error("unknown redist: " + rpi.Redist);
                    }
                    else if (redistNameToRequiredFramework[rpi.Redist] != null)
                    {
                        w.Write("\t\t\t{ \"");
                        w.Write(rpi.Include);
                        w.Write("\", \"");
                        w.Write(redistNameToRequiredFramework[rpi.Redist]);
                        w.WriteLine("\" },");
                    }
                }
            }
        }
        protected void InitTargetFramework(string defaultTargets, string extendedTargets)
        {
            const string            TargetFrameworkProperty = "TargetFrameworkVersion";
            ConfigurationGuiBinding targetFrameworkBinding;

            targetFrameworkBinding = helper.BindStringEnum("targetFrameworkComboBox", TargetFrameworkProperty,
                                                           "",
                                                           new StringPair("", "Default (.NET 2.0)"),
                                                           // We do not support .NET 1.0 anymore - compiling would still work,
                                                           // but debugging, unit testing etc. are not supported.
                                                           //new StringPair("v1.0", ".NET Framework 1.0"),
                                                           new StringPair("v1.1", ".NET Framework 1.1"),
                                                           new StringPair("v2.0", ".NET Framework 2.0"),
                                                           new StringPair("CF 1.0", "Compact Framework 1.0"),
                                                           new StringPair("CF 2.0", "Compact Framework 2.0"),
                                                           new StringPair("Mono v1.1", "Mono 1.1"),
                                                           new StringPair("Mono v2.0", "Mono 2.0"));
            targetFrameworkBinding.CreateLocationButton("targetFrameworkLabel");
            helper.Saved += delegate {
                // Test if SharpDevelop-Build extensions are needed
                MSBuildBasedProject project = helper.Project;
                bool needExtensions         = false;
                foreach (MSBuild.BuildProperty p in project.GetAllProperties(TargetFrameworkProperty))
                {
                    if (p.IsImported == false && p.Value.Length > 0)
                    {
                        needExtensions = true;
                        break;
                    }
                }
                foreach (MSBuild.Import import in project.MSBuildProject.Imports)
                {
                    if (needExtensions)
                    {
                        if (defaultTargets.Equals(import.ProjectPath, StringComparison.InvariantCultureIgnoreCase))
                        {
                            //import.ProjectPath = extendedTargets;
                            MSBuildInternals.SetImportProjectPath(project, import, extendedTargets);
                            break;
                        }
                    }
                    else
                    {
                        if (extendedTargets.Equals(import.ProjectPath, StringComparison.InvariantCultureIgnoreCase))
                        {
                            //import.ProjectPath = defaultTargets;
                            MSBuildInternals.SetImportProjectPath(project, import, defaultTargets);
                            break;
                        }
                    }
                }
            };
        }
 private void XmlDocHelper()
 {
     if (DocumentFileIsChecked)
     {
         this.DocumentationFile.Value = MSBuildInternals.Escape(
             Path.ChangeExtension(ICSharpCode.Core.FileUtility.GetRelativePath(projectOptions.Project.Directory, projectOptions.
                                                                               Project.OutputAssemblyFullPath),
                                  ".xml"));
     }
     else
     {
         this.DocumentationFile.Value = string.Empty;
     }
 }
 /// <summary>
 /// Gets the MSBuild build property with the specified name from the WixProject.
 /// </summary>
 MSBuild.BuildProperty GetMSBuildProperty(string name)
 {
     MSBuild.Project msbuildProject = project.MSBuildProject;
     foreach (MSBuild.BuildPropertyGroup g in msbuildProject.PropertyGroups.Cast <MSBuild.BuildPropertyGroup>().ToList())
     {
         if (!g.IsImported)
         {
             MSBuild.BuildProperty property = MSBuildInternals.GetProperty(g, name);
             if (property != null)
             {
                 return(property);
             }
         }
     }
     return(null);
 }
Example #15
0
 void UpdateXmlEnabled(object sender, EventArgs e)
 {
     Get <TextBox>("xmlDocumentation").Enabled = Get <CheckBox>("xmlDocumentation").Checked;
     if (Get <CheckBox>("xmlDocumentation").Checked)
     {
         if (Get <TextBox>("xmlDocumentation").Text.Length == 0)
         {
             Get <TextBox>("xmlDocumentation").Text = MSBuildInternals.Escape(
                 Path.ChangeExtension(FileUtility.GetRelativePath(baseDirectory, project.OutputAssemblyFullPath),
                                      ".xml"));
         }
     }
     else
     {
         Get <TextBox>("xmlDocumentation").Text = "";
     }
 }
Example #16
0
        protected override void AddOrRemoveExtensions()
        {
            // Test if SharpDevelop-Build extensions are required
            bool needExtensions = false;

            foreach (var p in GetAllProperties("TargetFrameworkVersion"))
            {
                if (p.IsImported == false)
                {
                    if (p.Value.StartsWith("CF"))
                    {
                        needExtensions = true;
                    }
                }
            }

            foreach (Microsoft.Build.BuildEngine.Import import in MSBuildProject.Imports)
            {
                if (needExtensions)
                {
                    if (DefaultTargetsFile.Equals(import.ProjectPath, StringComparison.OrdinalIgnoreCase))
                    {
                        //import.ProjectPath = extendedTargets;
                        MSBuildInternals.SetImportProjectPath(this, import, ExtendedTargetsFile);
                        // Workaround for SD2-1490. It would be better if the project browser could refresh itself
                        // when necessary.
                        ProjectBrowserPad.Instance.ProjectBrowserControl.RefreshView();
                        break;
                    }
                }
                else
                {
                    if (ExtendedTargetsFile.Equals(import.ProjectPath, StringComparison.OrdinalIgnoreCase))
                    {
                        //import.ProjectPath = defaultTargets;
                        MSBuildInternals.SetImportProjectPath(this, import, DefaultTargetsFile);
                        // Workaround for SD2-1490. It would be better if the project browser could refresh itself
                        // when necessary.
                        ProjectBrowserPad.Instance.ProjectBrowserControl.RefreshView();
                        break;
                    }
                }
            }
        }
Example #17
0
 void CreateKeyFile()
 {
     if (File.Exists(CreateKeyForm.StrongNameTool))
     {
         using (CreateKeyForm createKey = new CreateKeyForm(baseDirectory)) {
             createKey.KeyFile = project.Name;
             if (createKey.ShowDialog(WorkbenchSingleton.MainForm) == DialogResult.OK)
             {
                 keyFile.Text = MSBuildInternals.Escape(createKey.KeyFile);
                 return;
             }
         }
     }
     else
     {
         MessageService.ShowMessage("${res:Dialog.ProjectOptions.Signing.SNnotFound}");
     }
     keyFile.Text = "";
 }
Example #18
0
 public override IEnumerable <ReferenceProjectItem> ResolveAssemblyReferences(CancellationToken cancellationToken)
 {
     ReferenceProjectItem[] additionalReferences =
     {
         new ReferenceProjectItem(this, "mscorlib"),
         new ReferenceProjectItem(this, "System")
     };
     ReferenceProjectItem[] booReferences =
     {
         new ReferenceProjectItem(this, "Boo.Lang")
         {
             FileName = typeof(Boo.Lang.Builtins).Assembly.Location
         },
         new ReferenceProjectItem(this, "Boo.Extensions")
         {
             FileName = typeof(Boo.Lang.Extensions.PropertyAttribute).Assembly.Location
         }
     };
     return(MSBuildInternals.ResolveAssemblyReferences(this, additionalReferences).Concat(booReferences));
 }
Example #19
0
        void ResolveVersionsWorker()
        {
            MSBuildBasedProject project = selectDialog.ConfigureProject as MSBuildBasedProject;

            if (project == null)
            {
                return;
            }

            List <ListViewItem>         itemsToResolveVersion = new List <ListViewItem>();
            List <ReferenceProjectItem> referenceItems        = new List <ReferenceProjectItem>();

            WorkbenchSingleton.SafeThreadCall(
                delegate {
                foreach (ListViewItem item in shortItemList)
                {
                    if (item.SubItems[1].Text.Contains("/"))
                    {
                        itemsToResolveVersion.Add(item);
                        referenceItems.Add(new ReferenceProjectItem(project, item.Text));
                    }
                }
            });

            MSBuildInternals.ResolveAssemblyReferences(project, referenceItems.ToArray());

            WorkbenchSingleton.SafeThreadAsyncCall(
                delegate {
                if (IsDisposed)
                {
                    return;
                }
                for (int i = 0; i < itemsToResolveVersion.Count; i++)
                {
                    if (referenceItems[i].Version != null)
                    {
                        itemsToResolveVersion[i].SubItems[1].Text = referenceItems[i].Version.ToString();
                    }
                }
            });
        }
Example #20
0
        string GetInitialDirectory(string relativeLocation, TextBoxEditMode textBoxEditMode, bool isFile)
        {
            if (textBoxEditMode == TextBoxEditMode.EditRawProperty)
            {
                relativeLocation = MSBuildInternals.Unescape(relativeLocation);
            }
            if (string.IsNullOrEmpty(relativeLocation))
            {
                return(this.BaseDirectory);
            }

            try {
                string path = FileUtility.GetAbsolutePath(this.BaseDirectory, relativeLocation);
                if (FileUtility.IsValidPath(path))
                {
                    return(isFile ? System.IO.Path.GetDirectoryName(path) : path);
                }
            } catch (ArgumentException) {
                // can happen in GetAbsolutePath if the path contains invalid characters
            }
            return(this.BaseDirectory);
        }
Example #21
0
        private string BrowseForFolder(string description, TextBoxEditMode textBoxEditMode)
        {
            string startLocation = base.BaseDirectory;

            if (startLocation != null)
            {
                string text = StartWorkingDirectory.Value;
                if (textBoxEditMode == TextBoxEditMode.EditRawProperty)
                {
                    text = MSBuildInternals.Unescape(text);
                }

                startLocation = FileUtility.GetAbsolutePath(startLocation, text);
            }

            using (FolderBrowserDialog fdiag = FileService.CreateFolderBrowserDialog(description, startLocation))
            {
                if (fdiag.ShowDialog() == DialogResult.OK)
                {
                    string path = fdiag.SelectedPath;
                    if (base.BaseDirectory != null)
                    {
                        path = FileUtility.GetRelativePath(base.BaseDirectory, path);
                    }
                    if (!path.EndsWith("\\") && !path.EndsWith("/"))
                    {
                        path += "\\";
                    }

//						if (textBoxEditMode == TextBoxEditMode.EditEvaluatedProperty) {
////							panel.ControlDictionary[target].Text = path;
//						} else {
//							panel.ControlDictionary[target].Text = MSBuildInternals.Escape(path);
////						}
                    return(path);
                }
            }
            return(startLocation);
        }
            public void Event(object sender, EventArgs e)
            {
                string startLocation = panel.baseDirectory;

                if (startLocation != null)
                {
                    string text = panel.ControlDictionary[target].Text;
                    if (textBoxEditMode == TextBoxEditMode.EditRawProperty)
                    {
                        text = MSBuildInternals.Unescape(text);
                    }
                    startLocation = FileUtility.GetAbsolutePath(startLocation, text);
                }

                using (FolderBrowserDialog fdiag = FileService.CreateFolderBrowserDialog(description, startLocation)) {
                    if (fdiag.ShowDialog() == DialogResult.OK)
                    {
                        string path = fdiag.SelectedPath;
                        if (panel.baseDirectory != null)
                        {
                            path = FileUtility.GetRelativePath(panel.baseDirectory, path);
                        }
                        if (!path.EndsWith("\\") && !path.EndsWith("/"))
                        {
                            path += "\\";
                        }
                        if (textBoxEditMode == TextBoxEditMode.EditEvaluatedProperty)
                        {
                            panel.ControlDictionary[target].Text = path;
                        }
                        else
                        {
                            panel.ControlDictionary[target].Text = MSBuildInternals.Escape(path);
                        }
                    }
                }
            }
 bool EnsureCorrectName(ref string newName)
 {
     newName = newName.Trim();
     if (editPlatforms && string.Equals(newName, "AnyCPU", StringComparison.OrdinalIgnoreCase))
     {
         newName = "Any CPU";
     }
     foreach (string item in listBox.Items)
     {
         if (string.Equals(item, newName, StringComparison.OrdinalIgnoreCase))
         {
             MessageService.ShowMessage("${res:Dialog.EditAvailableConfigurationsDialog.DuplicateName}");
             return(false);
         }
     }
     if (MSBuildInternals.Escape(newName) != newName ||
         !FileUtility.IsValidDirectoryEntryName(newName) ||
         newName.Contains("'"))
     {
         MessageService.ShowMessage("${res:Dialog.EditAvailableConfigurationsDialog.InvalidName}");
         return(false);
     }
     return(true);
 }
Example #24
0
 bool EnsureCorrectName(ref string newName)
 {
     newName = newName.Trim();
     if (editPlatforms && string.Equals(newName, "AnyCPU", StringComparison.InvariantCultureIgnoreCase))
     {
         newName = "Any CPU";
     }
     foreach (string item in listBox.Items)
     {
         if (string.Equals(item, newName, StringComparison.InvariantCultureIgnoreCase))
         {
             MessageService.ShowMessage("Duplicate name.");
             return(false);
         }
     }
     if (MSBuildInternals.Escape(newName) != newName ||
         !FileUtility.IsValidDirectoryName(newName) ||
         newName.Contains("'"))
     {
         MessageService.ShowMessage("The name was invalid.");
         return(false);
     }
     return(true);
 }
        public IProject CreateProject(ProjectCreateInformation projectCreateInformation, string defaultLanguage)
        {
            // remember old outerProjectBasePath
            string outerProjectBasePath = projectCreateInformation.ProjectBasePath;
            string outerProjectName     = projectCreateInformation.ProjectName;

            try
            {
                projectCreateInformation.ProjectBasePath = Path.Combine(projectCreateInformation.ProjectBasePath, this.relativePath);
                if (!Directory.Exists(projectCreateInformation.ProjectBasePath))
                {
                    Directory.CreateDirectory(projectCreateInformation.ProjectBasePath);
                }

                string language = string.IsNullOrEmpty(languageName) ? defaultLanguage : languageName;
                LanguageBindingDescriptor descriptor   = LanguageBindingService.GetCodonPerLanguageName(language);
                ILanguageBinding          languageinfo = (descriptor != null) ? descriptor.Binding : null;

                if (languageinfo == null)
                {
                    StringParser.Properties["type"] = language;
                    MessageService.ShowError("${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.CantCreateProjectWithTypeError}");
                    return(null);
                }

                string newProjectName = StringParser.Parse(name, new string[, ] {
                    { "ProjectName", projectCreateInformation.ProjectName }
                });
                string projectLocation = Path.GetFullPath(Path.Combine(projectCreateInformation.ProjectBasePath,
                                                                       newProjectName + LanguageBindingService.GetProjectFileExtension(language)));


                StringBuilder standardNamespace = new StringBuilder();
                // filter 'illegal' chars from standard namespace
                if (newProjectName != null && newProjectName.Length > 0)
                {
                    char ch = '.';
                    for (int i = 0; i < newProjectName.Length; ++i)
                    {
                        if (ch == '.')
                        {
                            // at beginning or after '.', only a letter or '_' is allowed
                            ch = newProjectName[i];
                            if (!Char.IsLetter(ch))
                            {
                                standardNamespace.Append('_');
                            }
                            else
                            {
                                standardNamespace.Append(ch);
                            }
                        }
                        else
                        {
                            ch = newProjectName[i];
                            // can only contain letters, digits or '_'
                            if (!Char.IsLetterOrDigit(ch) && ch != '.')
                            {
                                standardNamespace.Append('_');
                            }
                            else
                            {
                                standardNamespace.Append(ch);
                            }
                        }
                    }
                }

                projectCreateInformation.OutputProjectFileName = projectLocation;
                projectCreateInformation.RootNamespace         = standardNamespace.ToString();
                projectCreateInformation.ProjectName           = newProjectName;

                StringParser.Properties["StandardNamespace"] = projectCreateInformation.RootNamespace;

                IProject project;
                try {
                    project = languageinfo.CreateProject(projectCreateInformation);
                } catch (ProjectLoadException ex) {
                    MessageService.ShowError(ex.Message);
                    return(null);
                }

                // Add Project items
                foreach (ProjectItem projectItem in projectItems)
                {
                    ProjectItem newProjectItem = new UnknownProjectItem(
                        project,
                        StringParser.Parse(projectItem.ItemType.ItemName),
                        StringParser.Parse(projectItem.Include)
                        );
                    foreach (string metadataName in projectItem.MetadataNames)
                    {
                        string metadataValue = projectItem.GetMetadata(metadataName);
                        // if the input contains any special MSBuild sequences, don't escape the value
                        // we want to escape only when the special characters are introduced by the StringParser.Parse replacement
                        if (metadataValue.Contains("$(") || metadataValue.Contains("%"))
                        {
                            newProjectItem.SetMetadata(StringParser.Parse(metadataName), StringParser.Parse(metadataValue));
                        }
                        else
                        {
                            newProjectItem.SetEvaluatedMetadata(StringParser.Parse(metadataName), StringParser.Parse(metadataValue));
                        }
                    }
                    ((IProjectItemListProvider)project).AddProjectItem(newProjectItem);
                }

                // Add Imports
                if (clearExistingImports || projectImports.Count > 0)
                {
                    if (!(project is MSBuildBasedProject))
                    {
                        throw new Exception("<Imports> may be only used in project templates for MSBuildBasedProjects");
                    }

                    if (clearExistingImports)
                    {
                        MSBuildInternals.ClearImports(((MSBuildBasedProject)project).MSBuildProject);
                    }
                    try {
                        foreach (Import projectImport in projectImports)
                        {
                            ((MSBuildBasedProject)project).MSBuildProject.AddNewImport(projectImport.Key, projectImport.Value);
                        }
                        ((MSBuildBasedProject)project).CreateItemsListFromMSBuild();
                    } catch (MSBuild.InvalidProjectFileException ex) {
                        if (string.IsNullOrEmpty(importsFailureMessage))
                        {
                            MessageService.ShowError("Error creating project:\n" + ex.Message);
                        }
                        else
                        {
                            MessageService.ShowError(importsFailureMessage + "\n\n" + ex.Message);
                        }
                        return(null);
                    }
                }

                if (projectProperties.Count > 0)
                {
                    if (!(project is MSBuildBasedProject))
                    {
                        throw new Exception("<PropertyGroup> may be only used in project templates for MSBuildBasedProjects");
                    }

                    foreach (ProjectProperty p in projectProperties)
                    {
                        ((MSBuildBasedProject)project).SetProperty(
                            StringParser.Parse(p.Configuration),
                            StringParser.Parse(p.Platform),
                            StringParser.Parse(p.Name),
                            StringParser.Parse(p.Value),
                            p.Location,
                            p.ValueIsLiteral
                            );
                    }
                }

                // Add Files
                foreach (FileDescriptionTemplate file in files)
                {
                    string fileName = Path.Combine(projectCreateInformation.ProjectBasePath, StringParser.Parse(file.Name, new string[, ] {
                        { "ProjectName", projectCreateInformation.ProjectName }
                    }));
                    FileProjectItem projectFile = new FileProjectItem(project, project.GetDefaultItemType(fileName));

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

                    file.SetProjectItemProperties(projectFile);

                    ((IProjectItemListProvider)project).AddProjectItem(projectFile);

                    if (File.Exists(fileName))
                    {
                        StringParser.Properties["fileName"] = fileName;
                        if (!MessageService.AskQuestion("${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.OverwriteQuestion}", "${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.OverwriteQuestion.InfoName}"))
                        {
                            continue;
                        }
                    }

                    try {
                        if (!Directory.Exists(Path.GetDirectoryName(fileName)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                        }
                        if (file.ContentData != null)
                        {
                            // Binary content
                            File.WriteAllBytes(fileName, file.ContentData);
                        }
                        else
                        {
                            // Textual content
                            StreamWriter sr          = new StreamWriter(File.Create(fileName), ParserService.DefaultFileEncoding);
                            string       fileContent = StringParser.Parse(file.Content, new string[, ] {
                                { "ProjectName", projectCreateInformation.ProjectName }, { "FileName", fileName }
                            });
                            fileContent = StringParser.Parse(fileContent);
                            if (SharpDevelopTextEditorProperties.Instance.IndentationString != "\t")
                            {
                                fileContent = fileContent.Replace("\t", SharpDevelopTextEditorProperties.Instance.IndentationString);
                            }
                            sr.Write(fileContent);
                            sr.Close();
                        }
                    } catch (Exception ex) {
                        StringParser.Properties["fileName"] = fileName;
                        MessageService.ShowError(ex, "${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.FileCouldntBeWrittenError}");
                    }
                }

                RunCreateActions(project);

                // Save project
                if (File.Exists(projectLocation))
                {
                    StringParser.Properties["projectLocation"] = projectLocation;
                    if (MessageService.AskQuestion("${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.OverwriteProjectQuestion}", "${res:ICSharpCode.SharpDevelop.Internal.Templates.ProjectDescriptor.OverwriteQuestion.InfoName}"))
                    {
                        project.Save();
                    }
                }
                else
                {
                    project.Save();
                }

                projectCreateInformation.createdProjects.Add(project);
                ProjectService.OnProjectCreated(new ProjectEventArgs(project));
                return(project);
            }
            finally
            {
                // set back outerProjectBasePath
                projectCreateInformation.ProjectBasePath = outerProjectBasePath;
                projectCreateInformation.ProjectName     = outerProjectName;
            }
        }
Example #26
0
 public void SetEvaluatedMetadata(string name, string value)
 {
     item.SetMetadataValue(name, MSBuildInternals.Escape(value));
 }
        void AddButtonClick(object sender, EventArgs e)
        {
            IEnumerable <string> availableSourceItems;

            if (project != null)
            {
                if (editPlatforms)
                {
                    availableSourceItems = project.PlatformNames;
                }
                else
                {
                    availableSourceItems = project.ConfigurationNames;
                }
            }
            else
            {
                if (editPlatforms)
                {
                    availableSourceItems = solution.GetPlatformNames();
                }
                else
                {
                    availableSourceItems = solution.GetConfigurationNames();
                }
            }

            using (AddNewConfigurationDialog dlg = new AddNewConfigurationDialog
                                                       (project == null, editPlatforms,
                                                       availableSourceItems,
                                                       delegate(string name) { return(EnsureCorrectName(ref name)); }
                                                       ))
            {
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    string newName = dlg.NewName;
                    // fix up the new name
                    if (!EnsureCorrectName(ref newName))
                    {
                        return;
                    }

                    if (project != null)
                    {
                        IProjectAllowChangeConfigurations pacc = project as IProjectAllowChangeConfigurations;
                        if (pacc != null)
                        {
                            if (editPlatforms)
                            {
                                pacc.AddProjectPlatform(MSBuildInternals.FixPlatformNameForProject(newName), dlg.CopyFrom);
                            }
                            else
                            {
                                pacc.AddProjectConfiguration(newName, dlg.CopyFrom);
                            }
                        }
                    }
                    else
                    {
                        if (editPlatforms)
                        {
                            solution.AddSolutionPlatform(newName, dlg.CopyFrom, dlg.CreateInAllProjects);
                        }
                        else
                        {
                            solution.AddSolutionConfiguration(newName, dlg.CopyFrom, dlg.CreateInAllProjects);
                        }
                    }
                    InitList();
                }
            }
        }