public void CreateProjectInstanceWithItemsContainingProjects() { const string CapturedMetadataName = "DefiningProjectFullPath"; var pc = new ProjectCollection(); var projA = ProjectRootElement.Create(pc); var projB = ProjectRootElement.Create(pc); projA.FullPath = Path.Combine(Path.GetTempPath(), "a.proj"); projB.FullPath = Path.Combine(Path.GetTempPath(), "b.proj"); projB.AddImport("a.proj"); projA.AddItem("Compile", "aItem.cs"); projB.AddItem("Compile", "bItem.cs"); var projBEval = new Project(projB, null, null, pc); var projBInstance = projBEval.CreateProjectInstance(); var projBInstanceItem = projBInstance.GetItemsByItemTypeAndEvaluatedInclude("Compile", "bItem.cs").Single(); var projAInstanceItem = projBInstance.GetItemsByItemTypeAndEvaluatedInclude("Compile", "aItem.cs").Single(); Assert.AreEqual(ProjectCollection.Escape(projB.FullPath), projBInstanceItem.GetMetadataValue(CapturedMetadataName)); Assert.AreEqual(ProjectCollection.Escape(projA.FullPath), projAInstanceItem.GetMetadataValue(CapturedMetadataName)); // Although GetMetadataValue returns non-null, GetMetadata returns null... Assert.IsNull(projAInstanceItem.GetMetadata(CapturedMetadataName)); // .. Just like built-in metadata does: (this segment just demonstrates similar functionality -- it's not meant to test built-in metadata) Assert.IsNotNull(projAInstanceItem.GetMetadataValue("Identity")); Assert.IsNull(projAInstanceItem.GetMetadata("Identity")); Assert.IsTrue(projAInstanceItem.HasMetadata(CapturedMetadataName)); Assert.IsFalse(projAInstanceItem.Metadata.Any()); Assert.IsTrue(projAInstanceItem.MetadataNames.Contains(CapturedMetadataName, StringComparer.OrdinalIgnoreCase)); Assert.AreEqual(projAInstanceItem.MetadataCount, projAInstanceItem.MetadataNames.Count); }
public bool GenerateEFSQLScriptsInternal(bool isLoggingEnabled = true) { InitializeProperties(); EFSQLScripts = new ITaskItem[EFMigrations.Length]; int index = 0; foreach (ITaskItem dbContext in EFMigrations) { string outputFileFullPath = Path.Combine(EFPublishDirectory, EFSQLScriptsFolderName, dbContext.ItemSpec + ".sql"); bool isScriptGenerationSuccessful = GenerateSQLScript(outputFileFullPath, dbContext.ItemSpec, isLoggingEnabled); if (!isScriptGenerationSuccessful) { return(false); } ITaskItem sqlScriptItem = new TaskItem(outputFileFullPath); sqlScriptItem.SetMetadata("DBContext", dbContext.ItemSpec); string connectionStringEscaped = ProjectCollection.Escape(dbContext.GetMetadata("Value")); sqlScriptItem.SetMetadata("ConnectionString", connectionStringEscaped); EFSQLScripts[index] = sqlScriptItem; index++; } return(true); }
public void EscapeDoesWTF() { string value_xml = "What are 'ESCAPE' & \"EVALUATE\" ? $ # % ^"; string value = "What are 'ESCAPE' & \"EVALUATE\" ? $ # % ^"; string escaped = "What are %27ESCAPE%27 & \"EVALUATE\" %3f %24 # %25 ^"; string xml = string.Format(@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <Foo>{0}</Foo> <Baz>$(FOO)</Baz> </PropertyGroup> </Project>", value_xml); var path = "file://localhost/foo.xml"; var reader = XmlReader.Create(new StringReader(xml), null, path); var root = ProjectRootElement.Create(reader); var proj = new Project(root); var prop = proj.Properties.First(p => p.Name == "Foo"); Assert.AreEqual(value, prop.UnevaluatedValue, "#1"); Assert.AreEqual(value, prop.EvaluatedValue, "#2"); // eh? Assert.AreEqual(value, Project.GetPropertyValueEscaped(prop), "#3"); prop = proj.Properties.First(p => p.Name == "Baz"); Assert.AreEqual("$(FOO)", prop.UnevaluatedValue, "#4"); Assert.AreEqual(value, prop.EvaluatedValue, "#5"); // eh? Assert.AreEqual(value, Project.GetPropertyValueEscaped(prop), "#6"); // OK you are fine. Assert.AreEqual(escaped, ProjectCollection.Escape(value), "#7"); }
private void DoAdd(string itemType, string itemPath) { var added = this.itemProject.BuildProject.AddItem(itemType, ProjectCollection.Escape(itemPath)); Debug.Assert(added.Count == 1, "adding a file created more than 1 new item, should not be possible since we escape wildcard characters"); this.item = added[0]; }
public Task SetProjectGuidAsync(Guid value) { // Avoid searching for the <ProjectGuid/> if we've already checked previously in GetProjectGuidAsync. // This handles project open, avoids us needed to take another read-lock during setting of it. // // Technically a project could add a <ProjectGuid/> latter down the track by editing the project or // reloading from disk, however, both the solution, CPS and other components within Visual Studio // do not handle the GUID changing underneath them. if (_isPersistedInProject == false) { return(Task.CompletedTask); } return(_projectAccessor.OpenProjectXmlForUpgradeableReadAsync(_project, async(projectXml, cancellationToken) => { ProjectPropertyElement property = FindProjectGuidProperty(projectXml); if (property != null) { _isPersistedInProject = true; // Avoid touching the project file unless the actual GUID has changed, regardless of format if (!TryParseGuid(property, out Guid result) || value != result) { await _projectAccessor.OpenProjectXmlForWriteAsync(_project, (root) => { property.Value = ProjectCollection.Escape(value.ToString("B").ToUpperInvariant()); }).ConfigureAwait(true); } } else { _isPersistedInProject = false; } })); }
public void DefiningProjectItemBuiltInMetadataFromWildcards() { const string CapturedMetadataName = "DefiningProjectFullPath"; var pc = new ProjectCollection(); var projA = ProjectRootElement.Create(pc); var projB = ProjectRootElement.Create(pc); string tempDir = Path.GetTempFileName(); File.Delete(tempDir); Directory.CreateDirectory(tempDir); File.Create(Path.Combine(tempDir, "aItem.cs")).Dispose(); projA.FullPath = Path.Combine(tempDir, "a.proj"); projB.FullPath = Path.Combine(tempDir, "b.proj"); projB.AddImport("a.proj"); projA.AddItem("Compile", "*.cs"); projB.AddItem("CompileB", "@(Compile)"); var projBEval = new Project(projB, null, null, pc); var projBInstance = projBEval.CreateProjectInstance(); var projAInstanceItem = projBInstance.GetItemsByItemTypeAndEvaluatedInclude("Compile", "aItem.cs").Single(); var projBInstanceItem = projBInstance.GetItemsByItemTypeAndEvaluatedInclude("CompileB", "aItem.cs").Single(); Assert.AreEqual(ProjectCollection.Escape(projA.FullPath), projAInstanceItem.GetMetadataValue(CapturedMetadataName)); Assert.AreEqual(ProjectCollection.Escape(projB.FullPath), projBInstanceItem.GetMetadataValue(CapturedMetadataName)); Assert.IsTrue(projAInstanceItem.HasMetadata(CapturedMetadataName)); Assert.IsFalse(projAInstanceItem.Metadata.Any()); Assert.IsTrue(projAInstanceItem.MetadataNames.Contains(CapturedMetadataName, StringComparer.OrdinalIgnoreCase)); Assert.AreEqual(projAInstanceItem.MetadataCount, projAInstanceItem.MetadataNames.Count); }
public IDictionary CloneCustomMetadataEscaped() { var ret = new Hashtable(); foreach (DictionaryEntry e in metadata) { ret [e.Key] = ProjectCollection.Escape((string)e.Value); } return(ret); }
System.Collections.IDictionary ITaskItem2.CloneCustomMetadataEscaped() { var dic = ((ITaskItem)this).CloneCustomMetadata(); foreach (DictionaryEntry p in dic) { dic [p.Key] = ProjectCollection.Escape((string)p.Value); } return(dic); }
void GenerateCompileIncludes(ProjectItemGroupElement itemGroup) { foreach (var include in new[] { "Test.cs", "Test2.cs", "Test3.cs" }) { itemGroup.AddItem ("Compile", ProjectCollection.Escape (include), new[] { new KeyValuePair<string, string> ("SubType", "Code") }); } foreach (var resource in new[] { "Test.resx", "Test2.resx", "Test3.resx" }) { itemGroup.AddItem ("EmbeddedResource", ProjectCollection.Escape (resource), new[] { new KeyValuePair<string, string> ("LogicalName", "Name.Space.Test") }); } }
void GenerateReferences(ProjectItemGroupElement itemGroup) { foreach (var reference in new[] { "Test.dll", "Test2.dll", "Test3.dll" }) { var name = Path.GetFileNameWithoutExtension (reference); itemGroup.AddItem ("Reference", name, new[] { new KeyValuePair<string, string> ("Name", name), new KeyValuePair<string, string> ("HintPath", ProjectCollection.Escape (reference)) }); } foreach (var reference in new[] { "mscorlib", "System", "System.Xml" }) { itemGroup.AddItem ("Reference", reference); } }
public void Rename(string newPath) { string escapedPath = ProjectCollection.Escape(newPath); if (this.IsVirtual) { virtualProperties[ProjectFileConstants.Include] = escapedPath; return; } item.Rename(escapedPath); this.RefreshProperties(); }
internal Microsoft.Build.Evaluation.ProjectItem AddMsBuildItem(string itemType, string value) { string str = ProjectCollection.Escape(value); IList <Microsoft.Build.Evaluation.ProjectItem> projectItems = this.MsBuildProject.AddItem(itemType, str); if (projectItems.Count == 0) { return(null); } if (projectItems.Count > 1) { throw new InvalidOperationException(); } return(projectItems[0]); }
static ProjectRootElement CreateProject() { var monoDroidPath = XamarinAndroid.Path; var msBuildPath = Path.Combine(monoDroidPath, "lib", "xbuild", "Xamarin", "Android"); if (!msBuildPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.OrdinalIgnoreCase)) msBuildPath = msBuildPath + Path.DirectorySeparatorChar; var project = ProjectRootElement.Create(); project.AddProperty("Configuration", "Release"); project.AddProperty("Platform", "AnyCPU"); project.AddProperty("PlatformTarget", "AnyCPU"); project.AddProperty("OutputPath", "bin\\Release"); project.AddProperty("TargetFrameworkDirectory", string.Join(";", XamarinAndroid.TargetFrameworkDirectories)); project.AddImport(ProjectCollection.Escape(Path.Combine(msBuildPath, "Xamarin.Android.CSharp.targets"))); return project; }
void SetKnownProperties(ProjectPropertyGroupElement properties) { properties.AddProperty("AssemblyName", Path.GetFileNameWithoutExtension("ZigZag.exe")); properties.AddProperty("ProjectGuid", projectGuid.ToString("B")); properties.AddProperty("CheckForOverflowUnderflow", false.ToString()); properties.AddProperty("CodePage", String.Empty); properties.AddProperty("DebugSymbols", true.ToString()); properties.AddProperty("DebugType", "Full"); properties.AddProperty("Optimize", false.ToString()); properties.AddProperty("Platform", "AnyCPU"); properties.AddProperty("ProjectTypeGuids", projectTypeGuid.ToString("B")); properties.AddProperty("AllowUnsafeBlocks", false.ToString()); properties.AddProperty("WarningLevel", "4"); properties.AddProperty("OutputPath", ProjectCollection.Escape("bin\\Debug")); properties.AddProperty("OutputType", "winexe"); properties.AddProperty("DefineConstants", "DEBUG,TRACE"); properties.AddProperty("TreatWarningsAsErrors", true.ToString()); }
public void BuildSourceLinkUrl_BitbucketEnterprise_PersonalToken() { var engine = new MockEngine(); var task = new GetSourceLinkUrl() { BuildEngine = engine, SourceRoot = new MockItem("/src/", KVP("RepositoryUrl", ProjectCollection.Escape("https://user_name%40domain.com:[email protected]/scm/abc/project1.git")), KVP("SourceControl", "git"), KVP("RevisionId", "0123456789abcdefABCDEF000000000000000000")), Hosts = new[] { new MockItem("bitbucket.domain.tools", KVP("ContentUrl", "https://bitbucket.domain.tools")), } }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", engine.Log); AssertEx.AreEqual("https://bitbucket.domain.tools/projects/abc/repos/project1/raw/*?at=0123456789abcdefABCDEF000000000000000000", task.SourceLinkUrl); Assert.True(result); }
public void Execute() { if (DebugOutput == null) { DebugOutput = false; } var json = File.ReadAllText(SecretsJsonFilePath); var secrets = JObject.Parse(json); string replacement = string.Empty; string safeReplacement = string.Empty; foreach (var secret in secrets) { replacement += ProcessSecret(secret); safeReplacement += ProcessSecret(secret, true); } replacement = Regex.Replace(replacement, "\n\n$", ""); var secretsClass = GenerateClass(replacement); Log.LogMessage((bool)DebugOutput ? secretsClass : GenerateClass(Regex.Replace(safeReplacement, "\n\n$", ""))); var projectFile = Path.Combine(OutputPath, $"{SecretsClassName}.cs"); var intermediateFile = Path.Combine(IntermediateOutputPath, $"{SecretsClassName}.cs"); var outputFile = File.Exists(projectFile) ? projectFile : intermediateFile; Log.LogMessage($"Writing Secrets Class to: '{outputFile}'"); GeneratedFiles = new ITaskItem[] { new TaskItem(ProjectCollection.Escape(outputFile)) }; File.WriteAllText(outputFile, secretsClass); }
//===================================================================== /// <summary> /// This is used to HTML encode and escape an MSBuild property value /// </summary> /// <param name="unescapedValue">The unescaped value</param> /// <returns>The HTML encoded escaped value</returns> public static string Escape(string unescapedValue) { string escaped = HttpUtility.HtmlEncode(unescapedValue ?? String.Empty); return(ProjectCollection.Escape(escaped)); }
internal static void WriteProjectXml( IInterpreterRegistryService service, TextWriter writer, string projectPath, string sourcePath, string filters, string searchPaths, string startupFile, PythonInterpreterView selectedInterpreter, ProjectCustomization customization, bool detectVirtualEnv ) { var projectHome = PathUtils.GetRelativeDirectoryPath(Path.GetDirectoryName(projectPath), sourcePath); var project = ProjectRootElement.Create(); project.DefaultTargets = "Build"; project.ToolsVersion = "4.0"; var globals = project.AddPropertyGroup(); globals.AddProperty("Configuration", "Debug").Condition = " '$(Configuration)' == '' "; globals.AddProperty("SchemaVersion", "2.0"); globals.AddProperty("ProjectGuid", Guid.NewGuid().ToString("B")); globals.AddProperty("ProjectHome", projectHome); if (PathUtils.IsValidPath(startupFile)) { globals.AddProperty("StartupFile", startupFile); } else { globals.AddProperty("StartupFile", ""); } globals.AddProperty("SearchPath", searchPaths); globals.AddProperty("WorkingDirectory", "."); globals.AddProperty("OutputPath", "."); globals.AddProperty("ProjectTypeGuids", "{888888a0-9f3d-457c-b088-3a5042f75d52}"); globals.AddProperty("LaunchProvider", DefaultLauncherProvider.DefaultLauncherName); var interpreterId = globals.AddProperty(PythonConstants.InterpreterId, ""); if (selectedInterpreter != null && !String.IsNullOrWhiteSpace(selectedInterpreter.Id)) { interpreterId.Value = selectedInterpreter.Id; } // VS requires property groups with conditions for Debug // and Release configurations or many COMExceptions are // thrown. var debugGroup = project.AddPropertyGroup(); var releaseGroup = project.AddPropertyGroup(); debugGroup.Condition = "'$(Configuration)' == 'Debug'"; releaseGroup.Condition = "'$(Configuration)' == 'Release'"; var folders = new HashSet <string>(); var virtualEnvPaths = detectVirtualEnv ? new List <string>() : null; foreach (var unescapedFile in EnumerateAllFiles(sourcePath, filters, virtualEnvPaths)) { var file = ProjectCollection.Escape(unescapedFile); var ext = Path.GetExtension(file); var fileType = "Content"; if (PythonConstants.FileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase) || PythonConstants.WindowsFileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase)) { fileType = "Compile"; } folders.Add(Path.GetDirectoryName(file)); project.AddItem(fileType, file); } foreach (var folder in folders.Where(s => !string.IsNullOrWhiteSpace(s)).OrderBy(s => s)) { project.AddItem("Folder", folder); } if (selectedInterpreter != null && !String.IsNullOrWhiteSpace(selectedInterpreter.Id)) { project.AddItem( MSBuildConstants.InterpreterReferenceItem, selectedInterpreter.Id ); } if (virtualEnvPaths != null && virtualEnvPaths.Any() && service != null) { foreach (var path in virtualEnvPaths) { var shortId = PathUtils.GetFileOrDirectoryName(path); var longId = MSBuildProjectInterpreterFactoryProvider.GetInterpreterId("$(MSBuildProjectFullPath)", shortId); var config = VirtualEnv.FindInterpreterConfiguration(longId, path, service); if (config != null) { AddVirtualEnvironment(project, sourcePath, shortId, config); if (string.IsNullOrEmpty(interpreterId.Value)) { interpreterId.Value = longId; } } } } var imports = project.AddPropertyGroup(); imports.AddProperty("VisualStudioVersion", "10.0").Condition = " '$(VisualStudioVersion)' == '' "; (customization ?? DefaultProjectCustomization.Instance).Process( sourcePath, project, new Dictionary <string, ProjectPropertyGroupElement> { { "Globals", globals }, { "Imports", imports }, { "Debug", debugGroup }, { "Release", releaseGroup } } ); project.Save(writer); }
public string GetMetadataValueEscaped(string metadataName) { return(ProjectCollection.Escape((string)metadata [metadataName])); }
public static string GetMetadataValueEscaped(ProjectItemInstance item, string name) { var md = item.Metadata.FirstOrDefault(m => m.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); return(md != null?ProjectCollection.Escape(md.EvaluatedValue) : null); }
public static string GetMetadataValueEscaped(ProjectMetadataInstance metadatum) { return(ProjectCollection.Escape(metadatum.EvaluatedValue)); }
public static string GetEvaluatedItemIncludeEscaped(ProjectItemInstance item) { return(ProjectCollection.Escape(item.EvaluatedInclude)); }
string ITaskItem2.GetMetadataValueEscaped(string metadataName) { return(ProjectCollection.Escape(GetMetadataValue(metadataName))); }