public override bool Execute ()
		{
			if (files == null || files.Length == 0)
				//nothing to do
				return true;

			assignedFiles = new ITaskItem [files.Length];
			for (int i = 0; i < files.Length; i ++) {
				string file = files [i].ItemSpec;
				string afile = null;
				//FIXME: Hack!
				string normalized_root = Path.GetFullPath (rootFolder);

				// cur dir should already be set to
				// the project dir
				file = Path.GetFullPath (file);

				if (file.StartsWith (normalized_root)) {
					afile = Path.GetFullPath (file).Substring (
							normalized_root.Length);
					// skip over "root/"
					if (afile [0] == '\\' ||
						afile [0] == '/')
						afile = afile.Substring (1);

				} else {
					afile = Path.GetFileName (file);
				}

				assignedFiles [i] = new TaskItem (files [i]);
				assignedFiles [i].SetMetadata ("TargetPath", afile);
			}

			return true;
		}
Example #2
0
 /// <summary>
 /// Helper function to parse the ParameterEntryElement
 /// </summary>
 /// <param name="element"></param>
 /// <param name="parentItem"></param>
 /// <returns></returns>
 private Utilities.TaskItem ReadParameterEntryElement(Xml.XmlElement element, Utilities.TaskItem parentItem)
 {
     Debug.Assert(element != null && parentItem != null);
     Utilities.TaskItem taskItem = null;
     if (string.Compare(element.Name, "parameterEntry", System.StringComparison.OrdinalIgnoreCase) == 0)
     {
         taskItem = new Microsoft.Build.Utilities.TaskItem(parentItem);
         taskItem.RemoveMetadata("OriginalItemSpec");
         foreach (Xml.XmlNode attribute in element.Attributes)
         {
             if (attribute != null && attribute.Name != null && attribute.Value != null)
             {
                 string value = DisableEscapeMSBuildVariable ? attribute.Value : Utility.EscapeTextForMSBuildVariable(attribute.Value);
                 taskItem.SetMetadata(attribute.Name, value);
             }
         }
     }
     else if (string.Compare(element.Name, "parameterValidation", System.StringComparison.OrdinalIgnoreCase) == 0)
     {
         taskItem = new Microsoft.Build.Utilities.TaskItem(parentItem);
         taskItem.RemoveMetadata("OriginalItemSpec");
         taskItem.SetMetadata("Element", "parameterValidation");
         foreach (Xml.XmlNode attribute in element.Attributes)
         {
             if (attribute != null && attribute.Name != null && attribute.Value != null)
             {
                 string value = DisableEscapeMSBuildVariable ? attribute.Value : Utility.EscapeTextForMSBuildVariable(attribute.Value);
                 taskItem.SetMetadata(attribute.Name, value);
             }
         }
     }
     return(taskItem);
 }
Example #3
0
    private static ITaskItem GetTaskItemFromJToken(
        this JToken token
        )
    {
        ITaskItem retVal;

        switch (token)
        {
        case JValue value:
            retVal = new TaskItem(value.Value?.ToString() ?? "");
            break;

        case JObject obj:
            retVal = new TaskItem(
                obj.Property(ITEM_SPEC).GetItemMetaData(),
                obj.Properties()
                .Where(p => !String.Equals(p.Name, ITEM_SPEC))
                .ToDictionary(p => p.Name, p => p.GetItemMetaData())
                );
            break;

        default:
            retVal = null;
            break;
        }

        return(retVal);
    }
 public override bool Execute()
 {
     if (string.IsNullOrEmpty(SourceDirectory))
     {
         Log.LogError("Argument SourceDirectory is missing.");
         return false;
     }
     if (string.IsNullOrEmpty(StartAppPath))
     {
         Log.LogError("Argument StartAppPath is missing.");
         return false;
     }
     if (string.IsNullOrEmpty(UniqueSourceDirectoryPath))
     {
         Log.LogError("Argument UniqueSourceDirectoryPath is missing.");
         return false;
     }
     var orderer = new AppOrderer();
     var list = orderer.GetAppBuildOrder(SourceDirectory, StartAppPath, UniqueSourceDirectoryPath, Log);
     var returnList = new List<ITaskItem>();
     foreach (string app in list)
     {
         ITaskItem item = new TaskItem(app);
         item.SetMetadata("AppPath", app);
         returnList.Add(item);
     }
     AppList = returnList.ToArray();
     return true;
 }
		private void SetMetaData(TaskItem item, string data, bool set)
		{
			if (set)
			{
				item.SetMetadata(TemplateFile.MetadataValueTag, data);
			}
		}
Example #6
0
		public override bool Execute ()
		{
			if (files == null || files.Length == 0)
				//nothing to do
				return true;

			List<ITaskItem> outFiles = new List<ITaskItem> ();

			for (int i = 0; i < files.Length; i ++) {
				string file = files [i].ItemSpec;
				string link = files [i].GetMetadata ("Link");
				string definingProjectPath = files [i].GetMetadata ("DefiningProjectFullPath");

				if (String.IsNullOrEmpty (link) && Path.IsPathRooted (file) && !string.IsNullOrEmpty (definingProjectPath)) {
					file = Path.GetFullPath (file);
					var projectDir = Path.GetFullPath (Path.GetDirectoryName (definingProjectPath));
					if (projectDir.Length == 0 || projectDir [projectDir.Length - 1] != Path.DirectorySeparatorChar)
						projectDir += Path.DirectorySeparatorChar;
					if (file.StartsWith (projectDir)) {
						// The file is in the same folder or a subfolder of the project that contains it.
						// Use the relative path wrt the containing project as link.
						var outFile = new TaskItem (files [i]);
						outFile.SetMetadata ("Link", file.Substring (projectDir.Length));
						outFiles.Add (outFile);
					}
				}
			}

			assignedFiles = outFiles.ToArray ();

			return true;
		}
Example #7
0
        public void BasicTestCreate()
        {
            var basicSampleTaskItem = new TaskItem("BasicSample");
            var cSharpTaskItem = new TaskItem("Microsoft.CSharp");
            var serviceTaskItem = new TaskItem(
                "Microsoft.Practices.ServiceLocation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");

            var task = new FindAssembliesInOutputDirTask(_fileSystem)
                           {
                               InputAssemblies = new ITaskItem[]
                                                     {
                                                         basicSampleTaskItem,
                                                         cSharpTaskItem,
                                                         serviceTaskItem
                                                     },
                               OutputDir = new[]
                                               {
                                                  @"C:\"
                                               }
                           };

            Assert.True(task.Execute());
            var outputs = task.AssembliesInOutputDir;
            Assert.Contains(basicSampleTaskItem, outputs);
            Assert.Contains(serviceTaskItem, outputs);
            Assert.DoesNotContain(cSharpTaskItem, outputs);
        }
Example #8
0
        public void NullITaskItem()
        {
            ITaskItem item = null;
            TaskItem taskItem = new TaskItem(item);

            // no NullReferenceException
        }
Example #9
0
        public override bool Execute()
        {
            var results = new List<ITaskItem> ();

            Log.LogTaskName ("PackLibraryResources");
            Log.LogTaskProperty ("BundleResourcesWithLogicalNames", BundleResourcesWithLogicalNames);
            Log.LogTaskProperty ("Prefix", Prefix);

            if (BundleResourcesWithLogicalNames != null) {
                foreach (var item in BundleResourcesWithLogicalNames) {
                    var logicalName = item.GetMetadata ("LogicalName");

                    if (string.IsNullOrEmpty (logicalName)) {
                        Log.LogError ("Items must have logical names computed.");
                        return false;
                    }

                    var embedded = new TaskItem (item);

                    embedded.SetMetadata ("LogicalName", "__" + Prefix + "_content_" + EscapeMangledResource (logicalName));

                    results.Add (embedded);
                }
            }

            EmbeddedResources = results.ToArray ();

            return !Log.HasLoggedErrors;
        }
 public static ITaskItem CreateFileItem(string sourcePath, string targetPath, string targetFramework)
 {
     TaskItem item = new TaskItem(sourcePath);
     item.SetMetadata("TargetPath", targetPath);
     item.SetMetadata("TargetFramework", targetFramework);
     return item;
 }
        public override bool Execute()
        {
            Log.LogMessage (MessageImportance.Low, "Task GetNugetPackageBasePath");
            Log.LogMessage (MessageImportance.Low, "\tPackageName : {0}", PackageName);
            Log.LogMessage (MessageImportance.Low, "\tPackageConfigFiles : ");
            foreach (ITaskItem file in PackageConfigFiles) {
                Log.LogMessage (MessageImportance.Low, "\t\t{0}", file.ItemSpec);
            }

            Version latest = null;
            foreach (string file in PackageConfigFiles.Select (x => Path.GetFullPath (x.ItemSpec)).Distinct ().OrderBy (x => x)) {
                if (!File.Exists (file)) {
                    Log.LogWarning ("\tPackages config file {0} not found", file);
                    continue;
                }

                Version tmp = GetPackageVersion (file);
                if (latest != null && latest >= tmp)
                    continue;
                latest = tmp;
            }

            if (latest == null)
                Log.LogError ("NuGet Package '{0}' not found", PackageName);
            else
                BasePath = new TaskItem (Path.Combine ("packages", $"{PackageName}.{latest}"));
            Log.LogMessage (MessageImportance.Low, $"BasePath == {BasePath}");
            return !Log.HasLoggedErrors;
        }
        private static ITaskItem[] GetSourceFolder(string folder)
        {
            var folderItem = new TaskItem(folder);
            folderItem.SetMetadata("Test-name", "Test-Content");

            return new ITaskItem[] { folderItem };
        }
Example #13
0
 private static ITaskItem CreateProjectCopyLocal(ProjectCopyLocal projectCopyLocal)
 {
     var copies = projectCopyLocal.CopyLocals;
     var result = new TaskItem(projectCopyLocal.Project);
     result.SetMetadata("CopyLocals", string.Join(Environment.NewLine, copies.ToArray()));    
     return result;
 }
        public void AppendItemWithMissingAttribute()
        {
            // Construct the task items.
            TaskItem i = new TaskItem();
            i.ItemSpec = "MySoundEffect.wav";
            i.SetMetadata("Name", "Kenny");
            i.SetMetadata("Access", "Private");

            TaskItem j = new TaskItem();
            j.ItemSpec = "MySplashScreen.bmp";
            j.SetMetadata("Name", "Cartman");
            j.SetMetadata("HintPath", @"c:\foo");
            j.SetMetadata("Access", "Public");

            CommandLineBuilderExtension c = new CommandLineBuilderExtension();

            c.AppendSwitchIfNotNull
            (
                "/myswitch:",
                new ITaskItem[] { i, j },
                new string[] { "Name", "HintPath", "Access" },
                null
            );
            Assert.Equal(@"/myswitch:MySoundEffect.wav,Kenny /myswitch:MySplashScreen.bmp,Cartman,c:\foo,Public", c.ToString());
        }
Example #15
0
        public override bool Execute()
        {
            EmbeddedResources = new ITaskItem[BundleResources.Length];

            Log.LogTaskName ("CreateEmbeddedResources");
            Log.LogTaskProperty ("BundleResources", BundleResources);
            Log.LogTaskProperty ("Prefix", Prefix);

            for (int i = 0; i < BundleResources.Length; i++) {
                var bundleResource = BundleResources[i];

                // clone the item
                var embeddedResource = new TaskItem (bundleResource.ItemSpec);
                bundleResource.CopyMetadataTo (embeddedResource);

                // mangle the resource name
                var logicalName = "__" + Prefix + "_content_" + EscapeMangledResource (bundleResource.GetMetadata ("LogicalName"));
                embeddedResource.SetMetadata ("LogicalName", logicalName);

                // add it to the output connection
                EmbeddedResources[i] = embeddedResource;
            }

            return true;
        }
        private static void ResolveSDKFromRefereneAssemblyLocation(string referenceName, string expectedPath)
        {
            // Create the engine.
            MockEngine engine = new MockEngine();
            TaskItem taskItem = new TaskItem(referenceName);
            taskItem.SetMetadata("SDKName", "FakeSDK, Version=1.0");

            TaskItem resolvedSDK = new TaskItem(@"C:\FakeSDK");
            resolvedSDK.SetMetadata("SDKName", "FakeSDK, Version=1.0");
            resolvedSDK.SetMetadata("TargetedSDKConfiguration", "Debug");
            resolvedSDK.SetMetadata("TargetedSDKArchitecture", "X86");

            TaskItem[] assemblies = new TaskItem[] { taskItem };

            // Now, pass feed resolved primary references into ResolveAssemblyReference.
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies = assemblies;
            t.ResolvedSDKReferences = new ITaskItem[] { resolvedSDK };
            t.SearchPaths = new String[] { @"C:\SomeOtherPlace" };
            bool succeeded = Execute(t);

            Assert.True(succeeded);
            Assert.Equal(1, t.ResolvedFiles.Length);
            Assert.Equal(0, engine.Errors);
            Assert.Equal(0, engine.Warnings);
            Assert.True(t.ResolvedFiles[0].ItemSpec.Equals(expectedPath, StringComparison.OrdinalIgnoreCase));
        }
Example #17
0
        protected ITaskItem ConvertPackageElement(ITaskItem project, PackageReference packageReference)
        {
            var id = packageReference.Id;
            var version = packageReference.Version;
            var targetFramework = packageReference.TargetFramework;
            var isDevelopmentDependency = packageReference.IsDevelopmentDependency;
            var requireReinstallation = packageReference.RequireReinstallation;
            var versionConstraint = packageReference.VersionConstraint;

            var item = new TaskItem(id);
            project.CopyMetadataTo(item);

            var packageDirectoryPath = GetPackageDirectoryPath(project.GetMetadata("FullPath"), id, version);
            item.SetMetadata("PackageDirectoryPath", packageDirectoryPath);
            item.SetMetadata("ProjectPath", project.GetMetadata("FullPath"));

            item.SetMetadata("IsDevelopmentDependency", isDevelopmentDependency.ToString());
            item.SetMetadata("RequireReinstallation", requireReinstallation.ToString());

            if (version != null)
                item.SetMetadata(Metadata.Version, version.ToString());

            if (targetFramework != null)
                item.SetMetadata(Metadata.TargetFramework, targetFramework.GetShortFrameworkName());

            if (versionConstraint != null)
                item.SetMetadata("VersionConstraint", versionConstraint.ToString());

            return item;
        }
 private static ITaskItem[] ExpandWildcards(ITaskItem[] expand)
 {
     if (expand == null)
     {
         return null;
     }
     ArrayList list = new ArrayList();
     foreach (ITaskItem item in expand)
     {
         if (Microsoft.Build.Shared.FileMatcher.HasWildcards(item.ItemSpec))
         {
             foreach (string str in Microsoft.Build.Shared.FileMatcher.GetFiles(null, item.ItemSpec))
             {
                 TaskItem item2 = new TaskItem(item) {
                     ItemSpec = str
                 };
                 Microsoft.Build.Shared.FileMatcher.Result result = Microsoft.Build.Shared.FileMatcher.FileMatch(item.ItemSpec, str);
                 if ((result.isLegalFileSpec && result.isMatch) && ((result.wildcardDirectoryPart != null) && (result.wildcardDirectoryPart.Length > 0)))
                 {
                     item2.SetMetadata("RecursiveDir", result.wildcardDirectoryPart);
                 }
                 list.Add(item2);
             }
         }
         else
         {
             list.Add(item);
         }
     }
     return (ITaskItem[]) list.ToArray(typeof(ITaskItem));
 }
Example #19
0
        public override bool Execute()
        {
            ArrayList list = new ArrayList();
            foreach (ITaskItem item in AssemblyFiles)
            {
                AssemblyName an;
                try
                {
                    an = AssemblyName.GetAssemblyName(item.ItemSpec);
                }
                catch (BadImageFormatException e)
                {
                    Log.LogErrorWithCodeFromResources("GetAssemblyIdentity.CouldNotGetAssemblyName", item.ItemSpec, e.Message);
                    continue;
                }
                catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e))
                {
                    Log.LogErrorWithCodeFromResources("GetAssemblyIdentity.CouldNotGetAssemblyName", item.ItemSpec, e.Message);
                    continue;
                }

                ITaskItem newItem = new TaskItem(an.FullName);
                newItem.SetMetadata("Name", an.Name);
                if (an.Version != null)
                    newItem.SetMetadata("Version", an.Version.ToString());
                if (an.GetPublicKeyToken() != null)
                    newItem.SetMetadata("PublicKeyToken", ByteArrayToHex(an.GetPublicKeyToken()));
                if (an.CultureInfo != null)
                    newItem.SetMetadata("Culture", an.CultureInfo.ToString());
                item.CopyMetadataTo(newItem);
                list.Add(newItem);
            }
            Assemblies = (ITaskItem[])list.ToArray(typeof(ITaskItem));
            return !Log.HasLoggedErrors;
        }
Example #20
0
        public override bool Execute()
        {
            Regex packageNameRegex = new Regex(PackageNameRegex);
            List<ITaskItem> packageNameItems = new List<ITaskItem>();

            foreach (string packageDrop in PackageDrops)
            {
                if (!Directory.Exists(packageDrop))
                {
                    Log.LogWarning("PackageDrop does not exist - '{0}'", packageDrop);
                    continue;
                }
                IEnumerable<ITaskItem> packages = Directory.GetFiles(packageDrop).Select(f => new TaskItem(Path.GetFileNameWithoutExtension(f)));


                foreach (ITaskItem package in packages)
                {
                    Match m = packageNameRegex.Match(package.ItemSpec);
                    if (m.Success)
                    {
                        TaskItem packageName = new TaskItem(m.Groups[0].Value);
                        packageName.SetMetadata("PackageName", m.Groups[1].Value);
                        packageName.SetMetadata("PackageVersion", m.Groups[2].Value);
                        packageName.SetMetadata("PrereleaseVersion", m.Groups[3].Value);
                        packageNameItems.Add(packageName);
                    }
                }
            }
            PackageNames = packageNameItems?.OrderBy(an => an.ItemSpec.ToString(), StringComparer.Ordinal)?.ToArray();
            return true;
        }
		public override bool Execute ()
		{
			if (string.IsNullOrEmpty (extensionDomain)) {
				Log.LogError ("ExtensionDomain item not found");
				return false;
			}
			if (addinReferences == null) {
				return true;
			}

			Application app = SetupService.GetExtensibleApplication (extensionDomain);
			if (app == null) {
				Log.LogError ("Extension domain '{0}' not found", extensionDomain);
				return false;
			}
			
			foreach (ITaskItem item in addinReferences) {
				string addinId = item.ItemSpec.Replace (':',',');
				Addin addin = app.Registry.GetAddin (addinId);
				if (addin == null) {
					Log.LogError ("Add-in '{0}' not found", addinId);
					return false;
				}
				if (addin.Description == null) {
					Log.LogError ("Add-in '{0}' could not be loaded", addinId);
					return false;
				}
				foreach (string asm in addin.Description.MainModule.Assemblies) {
					string file = Path.Combine (addin.Description.BasePath, asm);
					TaskItem ti = new TaskItem (file);
					references.Add (ti);
				}
			}
			return true;
		}
Example #22
0
        protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance)
        {
            if (singleLine.StartsWith("Successfully created package"))
            {
                var outputPackage = singleLine.Split('\'').Skip(1).First();
                var outputPackageItem = new TaskItem(outputPackage);
                if (outputPackage.EndsWith(".symbols.nupkg", StringComparison.OrdinalIgnoreCase))
                {
                    OutputSymbolsPackage = new[] { outputPackageItem };
                }
                else
                {
                    OutputPackage = new[] { outputPackageItem };
                }
            }

            if (messageImportance == MessageImportance.High)
            {
                Log.LogError(singleLine);
                return;
            }

            if (singleLine.StartsWith("Issue:") || singleLine.StartsWith("Description:") || singleLine.StartsWith("Solution:"))
            {
                Log.LogWarning(singleLine);
                return;
            }

            base.LogEventsFromTextOutput(singleLine, messageImportance);
        }
Example #23
0
		public override bool Execute ()
		{
			assemblies = new ITaskItem [assembly_files.Length];

			for (int i = 0; i < assemblies.Length; i++) {
				string file = assembly_files [i].ItemSpec;
				AssemblyName an = AssemblyName.GetAssemblyName (file);
				TaskItem item = new TaskItem (an.FullName);

				item.SetMetadata ("Version", an.Version.ToString ());

				byte[] pk = an.GetPublicKeyToken ();
				string pkStr = pk != null? ByteArrayToString (pk) : "null";
				item.SetMetadata ("PublicKeyToken", pkStr);

				CultureInfo culture = an.CultureInfo;
				if (culture != null) {
					string cn;
					if (culture.LCID == CultureInfo.InvariantCulture.LCID)
						cn = "neutral";
					else
						cn = culture.Name;
					item.SetMetadata ("Culture", cn);
				}

				assemblies[i] = item;
			}

			return true;
		}
        public override bool Execute()
        {
            // read the xml file and populate the JobsFound result

            if (File.Exists(ConfigFile)) {

                var doc = XDocument.Load(ConfigFile);
                var jobs = from wj in doc.Root.Elements("WebJob")
                           select new {
                               RelPath = wj.Attribute("RelativePath").Value,
                               Schedule = wj.Attribute("Schedule").Value
                           };

                var resultList = new List<ITaskItem>();

                foreach (var job in jobs) {

                    var item = new TaskItem(job.RelPath);
                    item.SetMetadata("Schedule", job.Schedule);

                    resultList.Add(item);
                }

                JobsFound = resultList.ToArray();
            }
            else {
                Log.LogMessage("web jobs config file not found at [{0}]", ConfigFile);
            }

            return !Log.HasLoggedErrors;
        }
Example #25
0
		protected internal override void AddCommandLineCommands (
						CommandLineBuilderExtension commandLine)
		{
			if (Sources.Length == 0)
				return;

			foreach (ITaskItem item in Sources)
				commandLine.AppendSwitchIfNotNull ("--complist=", item.ItemSpec);

			commandLine.AppendSwitchIfNotNull ("--target=", LicenseTarget);

			if (ReferencedAssemblies != null)
				foreach (ITaskItem reference in ReferencedAssemblies)
					commandLine.AppendSwitchIfNotNull ("--load=", reference.ItemSpec);

			string outdir;
			if (Bag ["OutputDirectory"] != null)
				outdir = OutputDirectory;
			else
				outdir = ".";

			commandLine.AppendSwitchIfNotNull ("--outdir=", outdir);

			if (Bag ["NoLogo"] != null && NoLogo)
				commandLine.AppendSwitch ("--nologo");

			OutputLicense = new TaskItem (Path.Combine (OutputDirectory, LicenseTarget.ItemSpec + ".licenses"));
		}
        public void Build()
        {
            RegexCompiler task = new RegexCompiler();
            task.BuildEngine = new MockBuild();
            task.OutputDirectory = TaskUtility.TestDirectory;
            task.AssemblyName = "MSBuild.Community.RegularExpressions.dll";
            task.AssemblyTitle = "MSBuild.Community.RegularExpressions";
            task.AssemblyDescription = "MSBuild Community Tasks Regular Expressions";
            task.AssemblyCompany = "MSBuildTasks";
            task.AssemblyProduct = "MSBuildTasks";
            task.AssemblyCopyright = "Copyright (c) MSBuildTasks 2008";
            task.AssemblyVersion = "1.0.0.0";
            task.AssemblyFileVersion = "1.0.0.0";
            task.AssemblyInformationalVersion = "1.0.0.0";
            task.AssemblyKeyFile = @"..\..\..\MSBuild.Community.Tasks\MSBuild.Community.Tasks.snk";

            List<ITaskItem> expressions = new List<ITaskItem>();

            TaskItem item1 = new TaskItem("TextRegex");
            item1.SetMetadata("Pattern", @"\G[^<]+");
            item1.SetMetadata("Options", "RegexOptions.Singleline | RegexOptions.Multiline");
            item1.SetMetadata("IsPublic", "true");

            TaskItem item2 = new TaskItem("CommentRegex");
            item2.SetMetadata("Pattern", @"\G<%--(([^-]*)-)*?-%>");
            item2.SetMetadata("Options", "RegexOptions.Singleline | RegexOptions.Multiline");
            item2.SetMetadata("IsPublic", "true");

            task.RegularExpressions = new ITaskItem[] {item1, item2};

            bool result = task.Execute();
            Assert.IsTrue(result);
        }
Example #27
0
		public override bool Execute() {
			var inputsGroupedByConfigFile = new Dictionary<string, List<WorkItem>>();
		
			OutputFiles = new ITaskItem[InputFiles.Length];
			for (int i = 0; i < InputFiles.Length; i++) {
				string infileLocal = InputFiles[i].ItemSpec;
				OutputFiles[i] = new TaskItem(Path.ChangeExtension(infileLocal, ExecutablesCommon.GeneratedFileExtension));
				string infile     = Path.GetFullPath(infileLocal);
				string outfile    = Path.ChangeExtension(infile, ExecutablesCommon.GeneratedFileExtension);
				string configFile = ExecutablesCommon.FindConfigFilePath(infile) ?? "";
				List<WorkItem> l;
				if (!inputsGroupedByConfigFile.TryGetValue(configFile, out l))
					inputsGroupedByConfigFile[configFile] = l = new List<WorkItem>();
				l.Add(new WorkItem() { InFile = infile, OutFile = outfile, Namespace = FindNamespace(InputFiles[i]) });
			}

			bool success = true;
			foreach (var kvp in inputsGroupedByConfigFile) {
                ExecutablesCommon.ProcessWorkItemsInSeparateAppDomain(kvp.Key, kvp.Value, (item, ex) => {
                    if (ex is TemplateErrorException) {
						Log.LogError(null, null, null, item.InFile, 0, 0, 0, 0, ex.Message);
						success = false;
					}
					else {
						Log.LogErrorFromException(ex, true, true, item.InFile);
						success = false;
					}
                    return true;
                });
			}
			return success;
		}
		public void Init()
		{
			mockCompiler = new MockPythonCompiler();
			compilerTask = new PythonCompilerTask(mockCompiler);
			sourceTaskItem = new TaskItem("test.py");
			compilerTask.Sources = new ITaskItem[] {sourceTaskItem};
		}
Example #29
0
        public override bool Execute()
        {
            var frameworks = new List<ITaskItem> ();

            Log.LogTaskName ("CollectFrameworks");
            Log.LogTaskProperty ("AppBundlePath", AppBundlePath);

            var fwDir = Path.Combine (AppBundlePath, "Frameworks");
            if (Directory.Exists (fwDir)) {
                foreach (var fw in Directory.GetDirectories (fwDir)) {
                    if (!fw.EndsWith (".framework")) {
                        Log.LogWarning ("Found a directory within the Frameworks directory which is not a framework: {0}", fw);
                        continue;
                    }
                    var fwName = Path.GetFileName (fw);
                    var stem = fwName.Substring (0, fwName.Length - ".framework".Length);
                    var fwBinary = Path.Combine (fw, stem);
                    if (!File.Exists (fwBinary)) {
                        Log.LogWarning ("The framework {0} does not contain a binary named {1}", Path.GetDirectoryName (fwBinary), Path.GetFileName (fwBinary));
                        continue;
                    }

                    var framework = new TaskItem (fwBinary);
                    frameworks.Add (framework);
                }
            } else {
                Log.LogMessage ("No Frameworks directory found.");
            }

            Frameworks = frameworks.ToArray ();

            return !Log.HasLoggedErrors;
        }
Example #30
0
 public void CheckForSpecificMetadataOnParent()
 {
     Reference reference = new Reference(isWinMDFile, fileExists, getRuntimeVersion);
     ITaskItem taskItem = new TaskItem("TestReference");
     taskItem.SetMetadata("SpecificVersion", "true");
     reference.MakePrimaryAssemblyReference(taskItem, true, ".dll");
     Assert.True(reference.CheckForSpecificVersionMetadataOnParentsReference(false));
 }
        private ITaskItem CreateScriptItem(FileInfo arg)
        {
            var item = new TaskItem(arg.FullName);

            item.SetMetadata("Schema", arg.Directory.Name);

            return item;
        }
Example #32
0
        public override bool Execute()
        {
            Log.LogTaskName ("PrepareNativeReferences");
            Log.LogTaskProperty ("IntermediateOutputPath", IntermediateOutputPath);
            Log.LogTaskProperty ("NativeReferences", NativeReferences);

            if (NativeReferences == null || NativeReferences.Length == 0)
                return !Log.HasLoggedErrors;

            var embeddedResources = new List<ITaskItem> ();
            var nativeFrameworks = new List<ITaskItem> ();
            var text = new StringBuilder ();

            for (int i = 0; i < NativeReferences.Length; i++) {
                NativeReferenceKind kind;
                string value;

                value = NativeReferences[i].GetMetadata ("Kind") ?? string.Empty;
                if (!Enum.TryParse (value, out kind)) {
                    Log.LogError (null, null, null, NativeReferences[i].ItemSpec, 0, 0, 0, 0, "Unknown native reference type: {0}", value);
                    continue;
                }

                var path = NativeReferences[i].ItemSpec;
                var logicalName = Path.GetFileName (path);

                var item = new TaskItem (path);

                if (kind == NativeReferenceKind.Framework) {
                    nativeFrameworks.Add (item);
                } else {
                    item.SetMetadata ("LogicalName", logicalName);
                    embeddedResources.Add (item);
                }

                text.AppendFormat ("[assembly: ObjCRuntime.LinkWith (\"{0}\"", logicalName);
                AppendLinkTargetProperty (text, NativeReferences[i]);
                AppendBooleanProperty (text, NativeReferences[i], "IsCxx");
                AppendBooleanProperty (text, NativeReferences[i], "NeedsGccExceptionHandling");
                AppendBooleanProperty (text, NativeReferences[i], "SmartLink", true);
                AppendBooleanProperty (text, NativeReferences[i], "ForceLoad");
                AppendStringProperty (text, NativeReferences[i], "Frameworks");
                AppendStringProperty (text, NativeReferences[i], "WeakFrameworks");
                AppendStringProperty (text, NativeReferences[i], "LinkerFlags");
                text.Append (")]");
                text.AppendLine ();
            }

            var linkWith = Path.Combine (IntermediateOutputPath, "LinkWithAttributes.cs");
            Directory.CreateDirectory (Path.GetDirectoryName (linkWith));
            File.WriteAllText (linkWith, text.ToString ());

            EmbeddedResources = embeddedResources.ToArray ();
            NativeFrameworks = nativeFrameworks.ToArray ();
            LinkWithAttributes = new TaskItem (linkWith);

            return !Log.HasLoggedErrors;
        }
Example #33
0
        /// <summary>
        /// Parse the Parameter element
        /// </summary>
        /// <param name="element"></param>
        private void ReadParameterElement(Xml.XmlElement element)
        {
            Debug.Assert(element != null);
            if (string.Compare(element.Name, "parameter", System.StringComparison.OrdinalIgnoreCase) == 0)
            {
                Xml.XmlAttribute nameAttribute = element.Attributes.GetNamedItem("name") as Xml.XmlAttribute;
                if (nameAttribute != null)
                {
                    Utilities.TaskItem taskItem = new Microsoft.Build.Utilities.TaskItem(nameAttribute.Value);
                    foreach (Xml.XmlNode attribute in element.Attributes)
                    {
                        string attributeName = attribute.Name.ToLower(System.Globalization.CultureInfo.InvariantCulture);
                        if (string.CompareOrdinal(attributeName, "xmlns") == 0 ||
                            attribute.Name.StartsWith("xmlns:", System.StringComparison.Ordinal) ||
                            string.CompareOrdinal(attributeName, "name") == 0
                            )
                        {
                            continue;
                        }
                        string value = DisableEscapeMSBuildVariable ? attribute.Value : Utility.EscapeTextForMSBuildVariable(attribute.Value);
                        taskItem.SetMetadata(attribute.Name, value);
                    }
                    // work around the MSDeploy.exe limition of the Parameter must have the ParameterEntry.
                    // m_parametersList.Add(taskItem);
                    bool fAddNoParameterEntryParameter = true;

                    foreach (Xml.XmlNode childNode in element.ChildNodes)
                    {
                        Xml.XmlElement childElement = childNode as Xml.XmlElement;
                        if (childElement != null)
                        {
                            Utilities.TaskItem childEntry = ReadParameterEntryElement(childElement, taskItem);
                            if (childEntry != null)
                            {
                                fAddNoParameterEntryParameter = false; // we have Parameter entry, supress adding the Parameter with no entry
                                m_parametersList.Add(childEntry);
                            }
                        }
                    }

                    if (fAddNoParameterEntryParameter)
                    {
                        // finally add a parameter without any entry
                        m_parametersList.Add(taskItem);
                    }
                }
            }
        }
Example #34
0
        private async Task PushBuildManifestAsync(
            BlobFeedAction blobFeedAction,
            IEnumerable <BlobArtifactModel> blobArtifacts,
            IEnumerable <PackageArtifactModel> packageArtifacts)
        {
            bool disabledByBlob = await blobFeedAction.feed.CheckIfBlobExists(
                $"{blobFeedAction.feed.RelativePath}{DisableManifestPushConfigurationBlob}");

            if (disabledByBlob)
            {
                Log.LogMessage(
                    MessageImportance.Normal,
                    $"Skipping manifest push: feed has '{DisableManifestPushConfigurationBlob}'.");
                return;
            }

            string blobPath = $"{AssetsVirtualDir}{ManifestAssetOutputDir}{ManifestName}.xml";

            string existingStr = await blobFeedAction.feed.DownloadBlobAsString(
                $"{blobFeedAction.feed.RelativePath}{blobPath}");

            BuildModel buildModel;

            if (existingStr != null)
            {
                buildModel = BuildModel.Parse(XElement.Parse(existingStr));
            }
            else
            {
                buildModel = new BuildModel(
                    new BuildIdentity(
                        ManifestName,
                        ManifestBuildId,
                        ManifestBranch,
                        ManifestCommit));
            }

            buildModel.Artifacts.Blobs.AddRange(blobArtifacts);
            buildModel.Artifacts.Packages.AddRange(packageArtifacts);

            string tempFile = null;

            try
            {
                tempFile = Path.GetTempFileName();

                File.WriteAllText(tempFile, buildModel.ToXml().ToString());

                var item = new MSBuild.TaskItem(tempFile, new Dictionary <string, string>
                {
                    ["RelativeBlobPath"] = blobPath
                });

                using (var clientThrottle = new SemaphoreSlim(MaxClients, MaxClients))
                {
                    await blobFeedAction.UploadAssets(
                        item,
                        clientThrottle,
                        UploadTimeoutInMinutes,
                        allowOverwrite : true);
                }
            }
            finally
            {
                if (tempFile != null)
                {
                    File.Delete(tempFile);
                }
            }
        }