public RemoteBuildEngine (Process proc, IBuildEngine engine) { this.proc = proc; this.engine = engine; Interlocked.Increment (ref count); }
private static bool CheckForError(IBuildEngine engine, string error, bool exists) { var buildEngine = engine as BuildEngineStub; if (buildEngine == null) { Assert.Fail("Not a BuildEngineStub, cannot test with this"); } if (buildEngine.Errors != null && buildEngine.Errors.Count > 0) { foreach (var anError in buildEngine.Errors) { if (anError.StartsWith(error)) { return exists; } } } if (!exists) { return true; } var sb = new StringBuilder(); sb.AppendLine(error + " not found. Actual errors: "); foreach (var anError in buildEngine.Errors) { sb.AppendLine(anError); } Assert.Fail(sb.ToString()); // ReSharper disable HeuristicUnreachableCode return !exists; // ReSharper restore HeuristicUnreachableCode }
/// <summary> /// Public constructor which can be used by task factories to assist them in logging messages. /// </summary> /// <param name="taskInstance">task containing an instance of this class</param> public TaskLoggingHelper(IBuildEngine buildEngine, string taskName) { ErrorUtilities.VerifyThrowArgumentNull(buildEngine, "buildEngine"); ErrorUtilities.VerifyThrowArgumentLength(taskName, "taskName"); _taskName = taskName; _buildEngine = buildEngine; }
public void Setup() { _mocks = new MockRepository(); _task = _mocks.DynamicMock<ITask>(); _engine = _mocks.DynamicMock<IBuildEngine>(); _logger = new MsBuildLogger(new TaskLoggingHelper(_task)); }
internal TlbReference(TaskLoggingHelper taskLoggingHelper, IComReferenceResolver resolverCallback, IEnumerable<string> referenceFiles, ComReferenceInfo referenceInfo, string itemName, string outputDirectory, bool hasTemporaryWrapper, bool delaySign, string keyFile, string keyContainer, bool noClassMembers, string targetProcessorArchitecture, bool includeTypeLibVersionInName, bool executeAsTool, string sdkToolsPath, IBuildEngine buildEngine, string[] environmentVariables) : base(taskLoggingHelper, resolverCallback, referenceInfo, itemName, outputDirectory, delaySign, keyFile, keyContainer, includeTypeLibVersionInName, executeAsTool, sdkToolsPath, buildEngine, environmentVariables) { this.hasTemporaryWrapper = hasTemporaryWrapper; this.noClassMembers = noClassMembers; this.targetProcessorArchitecture = targetProcessorArchitecture; this.referenceFiles = referenceFiles; }
public bool Initialize(string taskName, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) { var projectFileDirectory = Path.GetDirectoryName(taskFactoryLoggingHost.ProjectFileOfTaskNode); var thisAssemblyDirectory = Path.GetDirectoryName(this.GetType().Assembly.Location); _assemblyResolver.BeginResolving(thisAssemblyDirectory, projectFileDirectory); try { var engine = Ruby.CreateEngine(); _taskScriptScope = engine.CreateScope(); _taskScriptScope.ExecuteEmbeddedScript(RubyTaskScript); var rubyTaskBody = TaskBodyParser.Parse(taskBody); var scriptFile = projectFileDirectory.CombinePath(rubyTaskBody.Script).ToFullPath(); var scriptContents = _fileSystem.GetFileContent(scriptFile); _taskScriptScope.Execute(scriptContents); _taskClass = engine.Runtime.Globals.GetVariable(taskName); } catch(Exception) { _assemblyResolver.Dispose(); throw; } return true; }
public static void deleteTestDirectory(IBuildEngine buildEngine) { RemoveDir removeDirTask = new RemoveDir(); removeDirTask.BuildEngine = buildEngine; removeDirTask.Directories = StringArrayToItemArray(new string[] { TestDirectory }); removeDirTask.Execute(); }
public void Setup() { ccu = new CodeCompileUnit(); mocks = new MockRepository(); engine = Engine.GlobalEngine; engine.BinPath = @"C:\Program Files (x86)\MSBuild"; project = new Project(); buildEngine = mocks.DynamicMock<MockBuildEngine>(project); logger = new NullLogger(); parserService = mocks.DynamicMock<ISiteTreeGeneratorService>(); naming = mocks.DynamicMock<INamingService>(); sourceStorage = mocks.DynamicMock<IParsedSourceStorageService>(); source = mocks.DynamicMock<ISourceGenerator>(); typeResolver = mocks.DynamicMock<ITypeResolver>(); treeService = mocks.DynamicMock<ITreeCreationService>(); viewSourceMapper = mocks.DynamicMock<IViewSourceMapper>(); generator = mocks.DynamicMock<IGenerator>(); task = new GenerateMonoRailSiteTreeTask(logger, parserService, naming, source, sourceStorage, typeResolver, treeService, viewSourceMapper, generator); item = mocks.DynamicMock<ITaskItem>(); parsedSource = mocks.DynamicMock<IParser>(); }
public void Setup() { task = MockRepository.GenerateStub<ITask>(); engine = MockRepository.GenerateMock<IBuildEngine>(); logger = new MsBuildLogger(new TaskLoggingHelper(task)); task.Expect(t => t.BuildEngine).Return(engine).Repeat.Any(); }
public void Setup() { engine = Engine.GlobalEngine; engine.BinPath = Directory.Exists(@"C:\Program Files (x86)\MSBuild") ? @"C:\Program Files (x86)\MSBuild" : @"C:\Program Files\MSBuild"; project = new Project(); buildEngine = MockRepository.GenerateMock<MockBuildEngine>(project); task = new GenerateMonoRailSiteTreeTask(); }
/// <summary> /// Initialize the factory. /// </summary> public bool Initialize(string taskName, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) { if (!String.Equals(taskName, TaskType.Name, StringComparison.OrdinalIgnoreCase)) { ErrorUtilities.ThrowInternalError("Unexpected task name {0}. Expected {1}", taskName, TaskType.Name); } return true; }
protected void CheckoutProject(IBuildEngine engine, string path) { SvnCheckout task = new SvnCheckout(); task.RepositoryPath = path; task.RepositoryUrl = RepositoryURL; task.BuildEngine = engine; task.Execute(); }
public void Initialize() { _buildEngine = new BuildEngineMock(); Console.WriteLine("Blah blah blah " + Assembly.GetExecutingAssembly().Location); _taskItems = new TaskItemMock[1]; _taskItems[0] = new TaskItemMock(@"EricLemes.MSBuildTasks.Tests.DummyAssembly.dll").AddMetadata("FullPath", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\\EricLemes.MSBuildTasks.Tests.DummyAssembly.dll"); }
private SpyLogger(IBuildEngine buildEngine, string taskName) : base(buildEngine, taskName) { buildEngine.WhenAny(e => e.LogMessageEvent(null)) .Do<BuildMessageEventArgs>(Log); buildEngine.WhenAny(e => e.LogWarningEvent(null)) .Do<BuildWarningEventArgs>(Log); buildEngine.WhenAny(e => e.LogErrorEvent(null)) .Do<BuildErrorEventArgs>(Log); }
public MSBuildLogger(ConfigurationPropertyHolder configuration) { var task = configuration as ITask; if (task != null) { build_engine = task.BuildEngine; } calling_task = configuration; }
private void AssertFilesSubmitted(IBuildEngine engine) { string path = string.Format(RepositoryPathTemplate, DateTime.Now.Ticks); CheckoutProject(engine, path); string filePath = Path.Combine(path, "trunk\\DocumentA.txt"); string contents = File.ReadAllText(filePath); Assert.That(contents, Is.EqualTo(ModifyString)); }
/// <summary> /// Construct. /// </summary> public AssemblyFoldersFromConfigResolver(string searchPathElement, GetAssemblyName getAssemblyName, FileExists fileExists, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVesion, ProcessorArchitecture targetProcessorArchitecture, bool compareProcessorArchitecture, IBuildEngine buildEngine, TaskLoggingHelper log) : base( searchPathElement, getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVesion, targetProcessorArchitecture, compareProcessorArchitecture) { _buildEngine = buildEngine as IBuildEngine4; _taskLogger = log; }
private SpyLogger(IBuildEngine buildEngine, string taskName, bool includeSourceInformation) : base(buildEngine, taskName) { this.includeSourceInformation = includeSourceInformation; buildEngine.WhenAny(e => e.LogMessageEvent(null)) .Do<BuildMessageEventArgs>(Log); buildEngine.WhenAny(e => e.LogWarningEvent(null)) .Do<BuildWarningEventArgs>(Log); buildEngine.WhenAny(e => e.LogErrorEvent(null)) .Do<BuildErrorEventArgs>(Log); }
internal AxTlbBaseReference(TaskLoggingHelper taskLoggingHelper, IComReferenceResolver resolverCallback, ComReferenceInfo referenceInfo, string itemName, string outputDirectory, bool delaySign, string keyFile, string keyContainer, bool includeTypeLibVersionInName, bool executeAsTool, string toolPath, IBuildEngine buildEngine, string[] environmentVariables) : base(taskLoggingHelper, referenceInfo, itemName) { this.resolverCallback = resolverCallback; this.outputDirectory = outputDirectory; this.includeTypeLibVersionInName = includeTypeLibVersionInName; this.BuildEngine = buildEngine; this.EnvironmentVariables = environmentVariables; this.DelaySign = delaySign; this.ExecuteAsTool = executeAsTool; this.KeyFile = keyFile; this.KeyContainer = keyContainer; this.ToolPath = toolPath; }
/// <summary> /// Initializes a new instance of the <see cref="DlrTask"/> class. /// </summary> /// <param name="factory">The Factory</param> /// <param name="xmlElement">The XElement</param> /// <param name="taskFactoryLoggingHost">The taskFactoryLoggingHost</param> internal DlrTask(DlrTaskFactory factory, XElement xmlElement, IBuildEngine taskFactoryLoggingHost) { this.xelement = xmlElement; this.language = GetLanguage(xmlElement); var srs = new ScriptRuntimeSetup(); srs.LanguageSetups.Add(IronRuby.Ruby.CreateRubySetup()); srs.LanguageSetups.Add(IronPython.Hosting.Python.CreateLanguageSetup(null)); var runtime = new ScriptRuntime(srs); this.engine = runtime.GetEngineByFileExtension(this.language); this.scope = this.engine.CreateScope(); this.scope.log = this.Log; }
/// <summary> /// Create an instance of the ITask /// </summary> public ITask CreateTask(IBuildEngine taskFactoryLoggingHost) { // The assembly will have been compiled during class factory initialization, create an instance of it if (this.compiledAssembly != null) { // In order to use the resource strings from the tasks assembly we need to register the resources with the task logging helper. TaskLoggingHelper log = new TaskLoggingHelper(taskFactoryLoggingHost, nameOfTask); log.TaskResources = AssemblyResources.PrimaryResources; log.HelpKeywordPrefix = "MSBuild."; Type[] exportedTypes = this.compiledAssembly.GetExportedTypes(); Type fullNameMatch = null; Type partialNameMatch = null; foreach (Type exportedType in exportedTypes) { string exportedTypeName = exportedType.FullName; if (exportedTypeName.Equals(nameOfTask, StringComparison.OrdinalIgnoreCase)) { fullNameMatch = exportedType; break; } else if (partialNameMatch == null && exportedTypeName.EndsWith(nameOfTask, StringComparison.OrdinalIgnoreCase)) { partialNameMatch = exportedType; } } if (fullNameMatch == null && partialNameMatch == null) { log.LogErrorWithCodeFromResources("CodeTaskFactory.CouldNotFindTaskInAssembly", nameOfTask); return null; } this.taskInstance = this.compiledAssembly.CreateInstance(fullNameMatch != null ? fullNameMatch.FullName : partialNameMatch.FullName, true) as ITask; if (this.taskInstance == null) { log.LogErrorWithCodeFromResources("CodeTaskFactory.NeedsITaskInterface", nameOfTask); return null; } return this.taskInstance; } else { return null; } }
/// <summary> /// Creates an instance of the task. /// </summary> public ITask CreateTask(IBuildEngine taskFactoryLoggingHost) { if (TaskType == typeof(MSBuild)) { return new MSBuild(); } else if (TaskType == typeof(CallTarget)) { return new CallTarget(); } ErrorUtilities.ThrowInternalError("Unexpected intrinsic task type {0}", TaskType); return null; }
public virtual bool Initialize( string taskName, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) { Contract.Requires(!string.IsNullOrEmpty(taskName)); Contract.Requires(parameterGroup != null); Contract.Requires(taskBody != null); Contract.Requires(taskFactoryLoggingHost != null); this.TaskXmlBody = taskBody; this.ParameterGroup = parameterGroup; return true; }
public void Setup() { _mocks = new MockRepository(); _engine = Engine.GlobalEngine; if (Directory.Exists(@"C:\Program Files (x86)\MSBuild")) { _engine.BinPath = @"C:\Program Files (x86)\MSBuild"; } else { _engine.BinPath = @"C:\Program Files\MSBuild"; } _project = new Project(); _buildEngine = _mocks.DynamicMock<MockBuildEngine>(_project); _task = new GenerateMonoRailSiteTreeTask(); }
private static ProjectInstance GetProjectInstance(IBuildEngine buildEngine) { var buildEngineType = buildEngine.GetType(); var targetBuilderCallbackField = buildEngineType.GetField("targetBuilderCallback", SearchBindingFlags); if (targetBuilderCallbackField == null) { throw new InvalidProjectFileException("Could not extract targetBuilderCallback from " + buildEngineType.FullName); } var targetBuilderCallback = targetBuilderCallbackField.GetValue(buildEngine); var targetCallbackType = targetBuilderCallback.GetType(); var projectInstanceField = targetCallbackType.GetField("projectInstance", SearchBindingFlags); if (projectInstanceField == null) { throw new InvalidProjectFileException("Could not extract projectInstance from " + targetCallbackType.FullName); } return (ProjectInstance)projectInstanceField.GetValue(targetBuilderCallback); }
/// <summary> /// Initializes a new instance of the <see cref="DlrTask"/> class. /// </summary> internal DlrTask(DlrTaskFactory factory, XElement xElement, IBuildEngine taskFactoryLoggingHost) { Contract.Requires(factory != null); Contract.Requires(xElement != null); Contract.Requires(taskFactoryLoggingHost != null); this.taskFactory = factory; this.xElement = xElement; this.language = GetLanguage(xElement); this.taskFactoryLoggingHost = taskFactoryLoggingHost; var srs = new ScriptRuntimeSetup(); srs.LanguageSetups.Add(IronRuby.Ruby.CreateRubySetup()); srs.LanguageSetups.Add(IronPython.Hosting.Python.CreateLanguageSetup(null)); var runtime = new ScriptRuntime(srs); engine = runtime.GetEngineByFileExtension(language); scope = engine.CreateScope(); scope.log = this.Log; }
public void Initialize() { _buildEngine = new BuildEngineMock(); _taskItems = new TaskItemMock[3]; _taskItems[0] = new TaskItemMock(@"..\src\EricLemes.MSBuildTasks.sln"). AddMetadata("FullPath", @"C:\SandBox\EricLemes.MSBuildTasks\src\EricLemes.MSBuildTasks.sln"). AddMetadata("RootDir", @"C:\"). AddMetadata("Filename", @"EricLemes.MSBuildTasks"). AddMetadata("Extension", @".sln"). AddMetadata("RelativeDir", @"..\src\"). AddMetadata("Directory", @"SandBox\EricLemes.MSBuildTasks\src\"). AddMetadata("RecursiveDir", ""). AddMetadata("Identity", @"..\src\EricLemes.MSBuildTasks.sln"). AddMetadata("ModifiedTime", "2013-04-13 20:36:44.6254104"). AddMetadata("CreatedTime", "2013-04-13 20:24:44.4392181"). AddMetadata("AccessedTime", "2013-04-13 20:24:44.4392181"); _taskItems[1] = new TaskItemMock(@"..\src\EricLemes.MSBuildTasks.suo"). AddMetadata("FullPath", @"C:\SandBox\EricLemes.MSBuildTasks\src\EricLemes.MSBuildTasks.suo"). AddMetadata("RootDir", @"C:\"). AddMetadata("Filename", @"EricLemes.MSBuildTasks"). AddMetadata("Extension", ".suo"). AddMetadata("RelativeDir", @"..\src\"). AddMetadata("Directory", @"SandBox\EricLemes.MSBuildTasks\src\"). AddMetadata("RecursiveDir", ""). AddMetadata("Identity", @"..\src\EricLemes.MSBuildTasks.suo"). AddMetadata("ModifiedTime", "2013-04-13 20:36:44.7510000"). AddMetadata("CreatedTime", "2013-04-13 20:24:44.4452185"). AddMetadata("AccessedTime", "2013-04-13 20:24:44.4452185"); _taskItems[2] = new TaskItemMock(@"..\src\EricLemes.MSBuildTasks2.sln"). AddMetadata("FullPath", @"C:\SandBox\EricLemes.MSBuildTasks\src\EricLemes.MSBuildTasks2.sln"). AddMetadata("RootDir", @"C:\"). AddMetadata("Filename", @"EricLemes.MSBuildTasks"). AddMetadata("Extension", @".sln"). AddMetadata("RelativeDir", @"..\src\"). AddMetadata("Directory", @"SandBox\EricLemes.MSBuildTasks\src\"). AddMetadata("RecursiveDir", ""). AddMetadata("Identity", @"..\src\EricLemes.MSBuildTasks.sln"). AddMetadata("ModifiedTime", "2013-04-13 20:36:44.6254104"). AddMetadata("CreatedTime", "2013-04-13 20:24:44.4392181"). AddMetadata("AccessedTime", "2013-04-13 20:24:44.4392181"); }
public Test(string include, string[] excludeReferences) { var taskItem = MockRepository.GenerateStub<ITaskItem>(); taskItem.ItemSpec = Path.Combine(TaskUtility.GetProjectRootDirectory(true), RootDir + include); taskItem.Stub(ti => ti.GetMetadata("FullPath")).Return(taskItem.ItemSpec); _taskItems = new[] { taskItem }; _excludeRefereces = (excludeReferences ?? new string[0]) .Select(filter => { var item = MockRepository.GenerateStub<ITaskItem>(); item.ItemSpec = filter; return item; }) .ToArray(); _outputFile = Path.GetTempFileName(); _buildEngineStub = MockRepository.GenerateStub<IBuildEngine>(); }
public static bool LogMessage(IBuildEngine buildEngine, BuildMessageEventArgs args) { bool success = true; if (args.Importance == MessageImportance.High) { int index = 0; using (TextReader reader = new StringReader(args.Message)) { for (string line = reader.ReadLine(); line != null; line = reader.ReadLine()) { Match match = tsLintRegex.Match(line); if (match.Success) { int lineNumber = int.Parse(match.Groups["LineNumber"].Value); int columnNumber = int.Parse(match.Groups["ColumnNumber"].Value); BuildErrorEventArgs errorArgs = new BuildErrorEventArgs( string.Empty, string.Empty, match.Groups["FileName"].Value, lineNumber, columnNumber, 0, 0, match.Groups["End"].Value, string.Empty, string.Empty); buildEngine.LogErrorEvent(errorArgs); success = false; index++; if (index == 100) { break; } } } } } buildEngine.LogMessageEvent(args); return success; }
internal FilteredBuildEngine(IBuildEngine realEngine, string excludeMessagePattern, string excludeWarningPattern, string excludeErrorPattern) { if (realEngine == null) throw new ArgumentNullException(nameof(realEngine)); this.RealEngine = realEngine; if (!String.IsNullOrEmpty(excludeMessagePattern)) { this.ExcludeMessageRegex = new Regex(excludeMessagePattern); } if (!String.IsNullOrEmpty(excludeWarningPattern)) { this.ExcludeWarningRegex = new Regex(excludeWarningPattern); } if (!String.IsNullOrEmpty(excludeErrorPattern)) { this.ExcludeErrorRegex = new Regex(excludeErrorPattern); } }
public override ITask CreateTask(IBuildEngine taskFactoryLoggingHost) { return(new ResolveEnvironment(Properties["ProjectPath"], taskFactoryLoggingHost)); }
public MockTask(IBuildEngine e) { _e = e; }
public MsBuildLoggerGateway(IBuildEngine buildEngine) { _buildEngine = buildEngine ?? throw new ArgumentNullException(nameof(buildEngine)); InfoImportance = MessageImportance.Normal; }
internal RunPythonCommand(string projectPath, IBuildEngine buildEngine) : base(projectPath, buildEngine) { }
public BuildTaskDatabase(IBuildEngine engine, ProjectInstance projectInstance) { this.engine = engine; LoadUsingTasks(projectInstance, projectInstance.UsingTasks); }
public bool Initialize(string taskName, IDictionary <string, TaskPropertyInfo> taskParameters, string taskElementContents, IBuildEngine taskFactoryLoggingHost) { return(Initialize(taskName, null, taskParameters, taskElementContents, taskFactoryLoggingHost)); }
internal PythonCommandTask(string projectPath, IBuildEngine buildEngine) { BuildEngine = buildEngine; ProjectPath = projectPath; }
/// <summary> /// Creates the task. /// </summary> /// <param name="taskFactoryLoggingHost">The task factory logging host.</param> /// <returns></returns> public ITask CreateTask(IBuildEngine taskFactoryLoggingHost) { return(new MyTask(this)); }
/// <summary> /// Initializes the factory for creating a task with the given script. /// </summary> /// <param name="taskName">Name of the task.</param> /// <param name="parameterGroup">The parameter group.</param> /// <param name="taskBody">The task body.</param> /// <param name="taskFactoryLoggingHost">The task factory logging host.</param> /// <returns></returns> public bool Initialize(string taskName, IDictionary <string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) { Contract.Requires(!string.IsNullOrEmpty(taskName)); Contract.Requires(parameterGroup != null); Contract.Requires(taskBody != null); Contract.Requires(taskFactoryLoggingHost != null); this.parameterGroup = parameterGroup; this.taskBody = taskBody; this.Script = taskBody; // Add our intrinsic task properties this.parameterGroup["Important"] = new TaskPropertyInfo("Important", typeof(bool), false, false); return(true); }
/// <summary> /// Do the work of actually instantiating and running the task. /// </summary> private OutOfProcTaskHostTaskResult InstantiateAndExecuteTask ( IBuildEngine oopTaskHostNode, LoadedType taskType, string taskName, string taskLocation, string taskFile, int taskLine, int taskColumn, #if FEATURE_APPDOMAIN AppDomainSetup appDomainSetup, #endif IDictionary <string, TaskParameter> taskParams ) { #if FEATURE_APPDOMAIN _taskAppDomain = null; #endif wrappedTask = null; try { wrappedTask = TaskLoader.CreateTask(taskType, taskName, taskFile, taskLine, taskColumn, new TaskLoader.LogError(LogErrorDelegate), #if FEATURE_APPDOMAIN appDomainSetup, #endif true /* always out of proc */ #if FEATURE_APPDOMAIN , out _taskAppDomain #endif ); wrappedTask.BuildEngine = oopTaskHostNode; } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } Exception exceptionToReturn = e; // If it's a TargetInvocationException, we only care about the contents of the inner exception, // so just save that instead. if (e is TargetInvocationException) { exceptionToReturn = e.InnerException; } return(new OutOfProcTaskHostTaskResult ( TaskCompleteType.CrashedDuringInitialization, exceptionToReturn, "TaskInstantiationFailureError", new string[] { taskName, taskLocation, String.Empty } )); } foreach (KeyValuePair <string, TaskParameter> param in taskParams) { try { PropertyInfo paramInfo = wrappedTask.GetType().GetProperty(param.Key, BindingFlags.Instance | BindingFlags.Public); paramInfo.SetValue(wrappedTask, param.Value?.WrappedParameter, null); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } Exception exceptionToReturn = e; // If it's a TargetInvocationException, we only care about the contents of the inner exception, // so just save that instead. if (e is TargetInvocationException) { exceptionToReturn = e.InnerException; } return(new OutOfProcTaskHostTaskResult ( TaskCompleteType.CrashedDuringInitialization, exceptionToReturn, "InvalidTaskAttributeError", new string[] { param.Key, param.Value.ToString(), taskName } )); } } bool success = false; try { if (CancelPending) { return(new OutOfProcTaskHostTaskResult(TaskCompleteType.Failure)); } // If it didn't crash and return before now, we're clear to go ahead and execute here. success = wrappedTask.Execute(); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } return(new OutOfProcTaskHostTaskResult(TaskCompleteType.CrashedDuringExecution, e)); } PropertyInfo[] finalPropertyValues = wrappedTask.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); IDictionary <string, Object> finalParameterValues = new Dictionary <string, Object>(StringComparer.OrdinalIgnoreCase); foreach (PropertyInfo value in finalPropertyValues) { // only record outputs if (value.GetCustomAttributes(typeof(OutputAttribute), true).Count() > 0) { try { finalParameterValues[value.Name] = value.GetValue(wrappedTask, null); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } // If it's not a critical exception, we assume there's some sort of problem in the parameter getter -- // so save the exception, and we'll re-throw once we're back on the main node side of the // communications pipe. finalParameterValues[value.Name] = e; } } } return(new OutOfProcTaskHostTaskResult(success ? TaskCompleteType.Success : TaskCompleteType.Failure, finalParameterValues)); }
static bool?CompileCore(IBuildEngine engine, CecilTypeSystem typeSystem) { var asm = typeSystem.TargetAssemblyDefinition; var embrsc = new EmbeddedResources(asm); if (embrsc.Resources.Count(CheckXamlName) == 0) { // Nothing to do return(null); } var xamlLanguage = new XamlLanguageTypeMappings(typeSystem) { XmlnsAttributes = { typeSystem.GetType("Avalonia.Metadata.XmlnsDefinitionAttribute"), }, ContentAttributes = { typeSystem.GetType("Robust.Client.UserInterface.XAML.ContentAttribute") }, UsableDuringInitializationAttributes = { typeSystem.GetType("Robust.Client.UserInterface.XAML.UsableDuringInitializationAttribute") }, DeferredContentPropertyAttributes = { typeSystem.GetType("Robust.Client.UserInterface.XAML.DeferredContentAttribute") }, RootObjectProvider = typeSystem.GetType("Robust.Client.UserInterface.XAML.ITestRootObjectProvider"), UriContextProvider = typeSystem.GetType("Robust.Client.UserInterface.XAML.ITestUriContext"), ProvideValueTarget = typeSystem.GetType("Robust.Client.UserInterface.XAML.ITestProvideValueTarget"), }; var emitConfig = new XamlLanguageEmitMappings <IXamlILEmitter, XamlILNodeEmitResult> { ContextTypeBuilderCallback = (b, c) => EmitNameScopeField(xamlLanguage, typeSystem, b, c) }; var transformerconfig = new TransformerConfiguration( typeSystem, typeSystem.TargetAssembly, xamlLanguage, XamlXmlnsMappings.Resolve(typeSystem, xamlLanguage), CustomValueConverter); var contextDef = new TypeDefinition("CompiledRobustXaml", "XamlIlContext", TypeAttributes.Class, asm.MainModule.TypeSystem.Object); asm.MainModule.Types.Add(contextDef); var contextClass = XamlILContextDefinition.GenerateContextClass(typeSystem.CreateTypeBuilder(contextDef), typeSystem, xamlLanguage, emitConfig); var compiler = new RobustXamlILCompiler(transformerconfig, emitConfig, true); var loaderDispatcherDef = new TypeDefinition("CompiledRobustXaml", "!XamlLoader", TypeAttributes.Class, asm.MainModule.TypeSystem.Object); var loaderDispatcherMethod = new MethodDefinition("TryLoad", MethodAttributes.Static | MethodAttributes.Public, asm.MainModule.TypeSystem.Object) { Parameters = { new ParameterDefinition(asm.MainModule.TypeSystem.String) } }; loaderDispatcherDef.Methods.Add(loaderDispatcherMethod); asm.MainModule.Types.Add(loaderDispatcherDef); var stringEquals = asm.MainModule.ImportReference(asm.MainModule.TypeSystem.String.Resolve().Methods.First( m => m.IsStatic && m.Name == "Equals" && m.Parameters.Count == 2 && m.ReturnType.FullName == "System.Boolean" && m.Parameters[0].ParameterType.FullName == "System.String" && m.Parameters[1].ParameterType.FullName == "System.String")); bool CompileGroup(IResourceGroup group) { var typeDef = new TypeDefinition("CompiledRobustXaml", "!" + group.Name, TypeAttributes.Class, asm.MainModule.TypeSystem.Object); //typeDef.CustomAttributes.Add(new CustomAttribute(ed)); asm.MainModule.Types.Add(typeDef); var builder = typeSystem.CreateTypeBuilder(typeDef); foreach (var res in group.Resources.Where(CheckXamlName)) { try { engine.LogMessage($"XAMLIL: {res.Name} -> {res.Uri}", MessageImportance.Low); var xaml = new StreamReader(new MemoryStream(res.FileContents)).ReadToEnd(); var parsed = XDocumentXamlParser.Parse(xaml); var initialRoot = (XamlAstObjectNode)parsed.Root; var classDirective = initialRoot.Children.OfType <XamlAstXmlDirective>() .FirstOrDefault(d => d.Namespace == XamlNamespaces.Xaml2006 && d.Name == "Class"); string classname; if (classDirective != null && classDirective.Values[0] is XamlAstTextNode tn) { classname = tn.Text; } else { classname = res.Name.Replace(".xaml", ""); } var classType = typeSystem.TargetAssembly.FindType(classname); if (classType == null) { throw new Exception($"Unable to find type '{classname}'"); } compiler.Transform(parsed); var populateName = $"Populate:{res.Name}"; var buildName = $"Build:{res.Name}"; var classTypeDefinition = typeSystem.GetTypeReference(classType).Resolve(); var populateBuilder = typeSystem.CreateTypeBuilder(classTypeDefinition); compiler.Compile(parsed, contextClass, compiler.DefinePopulateMethod(populateBuilder, parsed, populateName, classTypeDefinition == null), compiler.DefineBuildMethod(builder, parsed, buildName, true), null, (closureName, closureBaseType) => populateBuilder.DefineSubType(closureBaseType, closureName, false), res.Uri, res ); //add compiled populate method var compiledPopulateMethod = typeSystem.GetTypeReference(populateBuilder).Resolve().Methods .First(m => m.Name == populateName); const string TrampolineName = "!XamlIlPopulateTrampoline"; var trampoline = new MethodDefinition(TrampolineName, MethodAttributes.Static | MethodAttributes.Private, asm.MainModule.TypeSystem.Void); trampoline.Parameters.Add(new ParameterDefinition(classTypeDefinition)); classTypeDefinition.Methods.Add(trampoline); trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ldnull)); trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Call, compiledPopulateMethod)); trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); var foundXamlLoader = false; // Find RobustXamlLoader.Load(this) and replace it with !XamlIlPopulateTrampoline(this) foreach (var method in classTypeDefinition.Methods .Where(m => !m.Attributes.HasFlag(MethodAttributes.Static))) { var i = method.Body.Instructions; for (var c = 1; c < i.Count; c++) { if (i[c].OpCode == OpCodes.Call) { var op = i[c].Operand as MethodReference; if (op != null && op.Name == TrampolineName) { foundXamlLoader = true; break; } if (op != null && op.Name == "Load" && op.Parameters.Count == 1 && op.Parameters[0].ParameterType.FullName == "System.Object" && op.DeclaringType.FullName == "Robust.Client.UserInterface.XAML.RobustXamlLoader") { if (MatchThisCall(i, c - 1)) { i[c].Operand = trampoline; foundXamlLoader = true; } } } } } if (!foundXamlLoader) { var ctors = classTypeDefinition.GetConstructors() .Where(c => !c.IsStatic).ToList(); // We can inject xaml loader into default constructor if (ctors.Count == 1 && ctors[0].Body.Instructions.Count(o => o.OpCode != OpCodes.Nop) == 3) { var i = ctors[0].Body.Instructions; var retIdx = i.IndexOf(i.Last(x => x.OpCode == OpCodes.Ret)); i.Insert(retIdx, Instruction.Create(OpCodes.Call, trampoline)); i.Insert(retIdx, Instruction.Create(OpCodes.Ldarg_0)); } else { throw new InvalidProgramException( $"No call to RobustXamlLoader.Load(this) call found anywhere in the type {classType.FullName} and type seems to have custom constructors."); } } //add compiled build method var compiledBuildMethod = typeSystem.GetTypeReference(builder).Resolve().Methods .First(m => m.Name == buildName); var parameterlessCtor = classTypeDefinition.GetConstructors() .FirstOrDefault(c => c.IsPublic && !c.IsStatic && !c.HasParameters); if (compiledBuildMethod != null && parameterlessCtor != null) { var i = loaderDispatcherMethod.Body.Instructions; var nop = Instruction.Create(OpCodes.Nop); i.Add(Instruction.Create(OpCodes.Ldarg_0)); i.Add(Instruction.Create(OpCodes.Ldstr, res.Uri)); i.Add(Instruction.Create(OpCodes.Call, stringEquals)); i.Add(Instruction.Create(OpCodes.Brfalse, nop)); if (parameterlessCtor != null) { i.Add(Instruction.Create(OpCodes.Newobj, parameterlessCtor)); } else { i.Add(Instruction.Create(OpCodes.Call, compiledBuildMethod)); } i.Add(Instruction.Create(OpCodes.Ret)); i.Add(nop); } } catch (Exception e) { engine.LogWarningEvent(new BuildWarningEventArgs("XAMLIL", "", res.Uri, 0, 0, 0, 0, e.ToString(), "", "CompileRobustXaml")); } } return(true); } if (embrsc.Resources.Count(CheckXamlName) != 0) { if (!CompileGroup(embrsc)) { return(false); } } loaderDispatcherMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldnull)); loaderDispatcherMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); return(true); }
/// <summary> /// Execute a task on the STA thread. /// </summary> /// <comment> /// STA thread launching code lifted from XMakeBuildEngine\BackEnd\Components\RequestBuilder\TaskBuilder.cs, ExecuteTaskInSTAThread method. /// Any bug fixes made to this code, please ensure that you also fix that code. /// </comment> private OutOfProcTaskHostTaskResult InstantiateAndExecuteTaskInSTAThread ( IBuildEngine oopTaskHostNode, LoadedType taskType, string taskName, string taskLocation, string taskFile, int taskLine, int taskColumn, #if FEATURE_APPDOMAIN AppDomainSetup appDomainSetup, #endif IDictionary <string, TaskParameter> taskParams ) { ManualResetEvent taskRunnerFinished = new ManualResetEvent(false); OutOfProcTaskHostTaskResult taskResult = null; Exception exceptionFromExecution = null; try { ThreadStart taskRunnerDelegate = delegate() { try { taskResult = InstantiateAndExecuteTask ( oopTaskHostNode, taskType, taskName, taskLocation, taskFile, taskLine, taskColumn, #if FEATURE_APPDOMAIN appDomainSetup, #endif taskParams ); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } exceptionFromExecution = e; } finally { taskRunnerFinished.Set(); } }; Thread staThread = new Thread(taskRunnerDelegate); staThread.SetApartmentState(ApartmentState.STA); staThread.Name = "MSBuild STA task runner thread"; staThread.CurrentCulture = Thread.CurrentThread.CurrentCulture; staThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture; staThread.Start(); // TODO: Why not just Join on the thread??? taskRunnerFinished.WaitOne(); } finally { #if CLR2COMPATIBILITY taskRunnerFinished.Close(); #else taskRunnerFinished.Dispose(); #endif taskRunnerFinished = null; } if (exceptionFromExecution != null) { // Unfortunately this will reset the callstack throw exceptionFromExecution; } return(taskResult); }
/// <summary> /// This is responsible for invoking Execute on the Task /// Any method calling ExecuteTask must remember to call CleanupTask /// </summary> /// <remarks> /// We also allow the Task to have a reference to the BuildEngine by design /// at ITask.BuildEngine /// </remarks> /// <param name="oopTaskHostNode">The OutOfProcTaskHostNode as the BuildEngine</param> /// <param name="taskName">The name of the task to be executed</param> /// <param name="taskLocation">The path of the task binary</param> /// <param name="taskFile">The path to the project file in which the task invocation is located.</param> /// <param name="taskLine">The line in the project file where the task invocation is located.</param> /// <param name="taskColumn">The column in the project file where the task invocation is located.</param> /// <param name="appDomainSetup">The AppDomainSetup that we want to use to launch our AppDomainIsolated tasks</param> /// <param name="taskParams">Parameters that will be passed to the task when created</param> /// <returns>Task completion result showing success, failure or if there was a crash</returns> internal OutOfProcTaskHostTaskResult ExecuteTask ( IBuildEngine oopTaskHostNode, string taskName, string taskLocation, string taskFile, int taskLine, int taskColumn, #if FEATURE_APPDOMAIN AppDomainSetup appDomainSetup, #endif IDictionary <string, TaskParameter> taskParams ) { buildEngine = oopTaskHostNode; this.taskName = taskName; #if FEATURE_APPDOMAIN _taskAppDomain = null; #endif wrappedTask = null; LoadedType taskType = null; try { TypeLoader typeLoader = new TypeLoader(TaskLoader.IsTaskClass); taskType = typeLoader.Load(taskName, AssemblyLoadInfo.Create(null, taskLocation)); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } Exception exceptionToReturn = e; // If it's a TargetInvocationException, we only care about the contents of the inner exception, // so just save that instead. if (e is TargetInvocationException) { exceptionToReturn = e.InnerException; } return(new OutOfProcTaskHostTaskResult ( TaskCompleteType.CrashedDuringInitialization, exceptionToReturn, "TaskInstantiationFailureError", new string[] { taskName, taskLocation, String.Empty } )); } OutOfProcTaskHostTaskResult taskResult; if (taskType.HasSTAThreadAttribute()) { #if FEATURE_APARTMENT_STATE taskResult = InstantiateAndExecuteTaskInSTAThread(oopTaskHostNode, taskType, taskName, taskLocation, taskFile, taskLine, taskColumn, #if FEATURE_APPDOMAIN appDomainSetup, #endif taskParams); #else return(new OutOfProcTaskHostTaskResult ( TaskCompleteType.CrashedDuringInitialization, null, "TaskInstantiationFailureNotSupported", new string[] { taskName, taskLocation, typeof(RunInSTAAttribute).FullName } )); #endif } else { taskResult = InstantiateAndExecuteTask(oopTaskHostNode, taskType, taskName, taskLocation, taskFile, taskLine, taskColumn, #if FEATURE_APPDOMAIN appDomainSetup, #endif taskParams); } return(taskResult); }
internal ResolveEnvironment(string projectPath, IBuildEngine buildEngine) { BuildEngine = buildEngine; _projectPath = projectPath; _log = new TaskLoggingHelper(this); }
public bool Sign(IBuildEngine buildEngine, int round, IEnumerable <FileSignInfo> files) { return(LocalStrongNameSign(buildEngine, round, files) && AuthenticodeSign(buildEngine, round, files)); }
/// <summary> /// Initialze the task factory /// </summary> public bool Initialize(string taskName, IDictionary <string, TaskPropertyInfo> taskParameters, string taskElementContents, IBuildEngine taskFactoryLoggingHost) { _nameOfTask = taskName; _log = new TaskLoggingHelper(taskFactoryLoggingHost, taskName) { TaskResources = AssemblyResources.PrimaryResources, HelpKeywordPrefix = "MSBuild." }; XmlNode taskContent = ExtractTaskContent(taskElementContents); if (taskContent == null) { // Just return false because we have already logged the error in ExtractTaskContents return(false); } bool validatedTaskNode = ValidateTaskNode(); if (!validatedTaskNode) { return(false); } if (taskContent.Attributes["Type"] != null) { _type = taskContent.Attributes["Type"].Value; if (_type.Length == 0) { _log.LogErrorWithCodeFromResources("CodeTaskFactory.AttributeEmpty", "Type"); return(false); } } if (taskContent.Attributes["Language"] != null) { _language = taskContent.Attributes["Language"].Value; if (_language.Length == 0) { _log.LogErrorWithCodeFromResources("CodeTaskFactory.AttributeEmpty", "Language"); return(false); } } if (taskContent.Attributes["Source"] != null) { _sourcePath = taskContent.Attributes["Source"].Value; if (_sourcePath.Length == 0) { _log.LogErrorWithCodeFromResources("CodeTaskFactory.AttributeEmpty", "Source"); return(false); } if (_type == null) { _type = "Class"; } } _referencedAssemblies = ExtractReferencedAssemblies(); if (_log.HasLoggedErrors) { return(false); } _usingNamespaces = ExtractUsingNamespaces(); if (_log.HasLoggedErrors) { return(false); } _sourceCode = taskContent.InnerText; if (_type == null) { _type = "Fragment"; } if (_language == null) { _language = "cs"; } if (String.Equals(_type, "Fragment", StringComparison.OrdinalIgnoreCase)) { _typeIsFragment = true; _typeIsMethod = false; } else if (String.Equals(_type, "Method", StringComparison.OrdinalIgnoreCase)) { _typeIsFragment = false; _typeIsMethod = true; } _taskParameterTypeInfo = taskParameters; _compiledAssembly = CompileInMemoryAssembly(); // If it wasn't compiled, it logged why. // If it was, continue. if (_compiledAssembly != null) { // Now go find the type int he compiled assembly. Type[] exportedTypes = _compiledAssembly.GetExportedTypes(); Type fullNameMatch = null; Type partialNameMatch = null; foreach (Type exportedType in exportedTypes) { string exportedTypeName = exportedType.FullName; if (exportedTypeName.Equals(_nameOfTask, StringComparison.OrdinalIgnoreCase)) { fullNameMatch = exportedType; break; } else if (partialNameMatch == null && exportedTypeName.EndsWith(_nameOfTask, StringComparison.OrdinalIgnoreCase)) { partialNameMatch = exportedType; } } TaskType = fullNameMatch ?? partialNameMatch; if (TaskType == null) { _log.LogErrorWithCodeFromResources("CodeTaskFactory.CouldNotFindTaskInAssembly", _nameOfTask); } } return(!_log.HasLoggedErrors); }
/// <summary> /// Compile search paths into an array of resolvers. /// </summary> /// <param name="buildEngine"></param> /// <param name="searchPaths"></param> /// <param name="candidateAssemblyFiles">Paths to assembly files mentioned in the project.</param> /// <param name="targetProcessorArchitecture">Like x86 or IA64\AMD64, the processor architecture being targetted.</param> /// <param name="frameworkPaths">Paths to FX folders.</param> /// <param name="fileExists"></param> /// <param name="getAssemblyName"></param> /// <param name="getRegistrySubKeyNames"></param> /// <param name="getRegistrySubKeyDefaultValue"></param> /// <param name="openBaseKey"></param> /// <param name="installedAssemblies"></param> /// <param name="getRuntimeVersion"></param> /// <param name="targetedRuntimeVersion"></param> /// <param name="getAssemblyPathInGac"></param> /// <param name="log"></param> /// <returns></returns> public static Resolver[] CompileSearchPaths ( IBuildEngine buildEngine, string[] searchPaths, string[] candidateAssemblyFiles, System.Reflection.ProcessorArchitecture targetProcessorArchitecture, string[] frameworkPaths, FileExists fileExists, GetAssemblyName getAssemblyName, #if FEATURE_WIN32_REGISTRY GetRegistrySubKeyNames getRegistrySubKeyNames, GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, OpenBaseKey openBaseKey, #endif InstalledAssemblies installedAssemblies, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVersion, GetAssemblyPathInGac getAssemblyPathInGac, TaskLoggingHelper log ) { var resolvers = new Resolver[searchPaths.Length]; for (int p = 0; p < searchPaths.Length; ++p) { string basePath = searchPaths[p]; // Was {HintPathFromItem} specified? If so, take the Item's // HintPath property. if (0 == String.Compare(basePath, AssemblyResolutionConstants.hintPathSentinel, StringComparison.OrdinalIgnoreCase)) { resolvers[p] = new HintPathResolver(searchPaths[p], getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVersion); } else if (0 == String.Compare(basePath, AssemblyResolutionConstants.frameworkPathSentinel, StringComparison.OrdinalIgnoreCase)) { resolvers[p] = new FrameworkPathResolver(frameworkPaths, installedAssemblies, searchPaths[p], getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVersion); } else if (0 == String.Compare(basePath, AssemblyResolutionConstants.rawFileNameSentinel, StringComparison.OrdinalIgnoreCase)) { resolvers[p] = new RawFilenameResolver(searchPaths[p], getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVersion); } else if (0 == String.Compare(basePath, AssemblyResolutionConstants.candidateAssemblyFilesSentinel, StringComparison.OrdinalIgnoreCase)) { resolvers[p] = new CandidateAssemblyFilesResolver(candidateAssemblyFiles, searchPaths[p], getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVersion); } #if FEATURE_GAC else if (0 == String.Compare(basePath, AssemblyResolutionConstants.gacSentinel, StringComparison.OrdinalIgnoreCase)) { resolvers[p] = new GacResolver(targetProcessorArchitecture, searchPaths[p], getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVersion, getAssemblyPathInGac); } #endif else if (0 == String.Compare(basePath, AssemblyResolutionConstants.assemblyFoldersSentinel, StringComparison.OrdinalIgnoreCase)) { resolvers[p] = new AssemblyFoldersResolver(searchPaths[p], getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVersion); } #if FEATURE_WIN32_REGISTRY // Check for AssemblyFoldersEx sentinel. else if (0 == String.Compare(basePath, 0, AssemblyResolutionConstants.assemblyFoldersExSentinel, 0, AssemblyResolutionConstants.assemblyFoldersExSentinel.Length, StringComparison.OrdinalIgnoreCase)) { resolvers[p] = new AssemblyFoldersExResolver(searchPaths[p], getAssemblyName, fileExists, getRegistrySubKeyNames, getRegistrySubKeyDefaultValue, getRuntimeVersion, openBaseKey, targetedRuntimeVersion, targetProcessorArchitecture, true, buildEngine); } #endif else if (0 == String.Compare(basePath, 0, AssemblyResolutionConstants.assemblyFoldersFromConfigSentinel, 0, AssemblyResolutionConstants.assemblyFoldersFromConfigSentinel.Length, StringComparison.OrdinalIgnoreCase)) { resolvers[p] = new AssemblyFoldersFromConfigResolver(searchPaths[p], getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVersion, targetProcessorArchitecture, true, buildEngine, log); } else { resolvers[p] = new DirectoryResolver(searchPaths[p], getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVersion); } } return(resolvers); }
public MSBuildHostService(IBuildEngine buildEngine) { _buildEngine = buildEngine; _serverCompleted = new TaskCompletionSource <bool>(); }
public ITask CreateTask(IBuildEngine loggingHost) { return(CreateTask(loggingHost, null)); }
public virtual ITask CreateTask(IBuildEngine taskFactoryLoggingHost) { return(new BatchFileTask(this.TaskXmlBody)); }
public override ITask CreateTask(IBuildEngine taskFactoryLoggingHost) { return(new RunPythonCommand(Properties["ProjectPath"], taskFactoryLoggingHost)); }
public static bool DoesNotContainError(IBuildEngine engine, string error) { return(CheckForError(engine, error, false)); }
internal CreatePythonCommandItem(string projectPath, IBuildEngine buildEngine) : base(projectPath, buildEngine) { }
public static bool ContainsError(IBuildEngine engine, string error) { return(CheckForError(engine, error, true)); }
internal ConcurrentBag <SdkProjectMetaData> GetMetaData(List <string> projectList, ConcurrentBag <SdkProjectMetaData> supportedProjectBag) { SdkProjctType pType = SdkProjctType.Sdk; var projList = from p in projectList select new TaskItem(p); IBuildEngine buildEng = this.BuildEngine; //Object obj = new object(); //ThreadingTsk.Parallel.ForEach<ITaskItem>(projList, (proj) => foreach (ITaskItem proj in projList) { //lock (obj) //{ try { Project loadedProj = new Project(proj.ItemSpec); string targetFxList = loadedProj.GetPropertyValue("TargetFrameworks"); if (string.IsNullOrEmpty(targetFxList)) { targetFxList = loadedProj.GetPropertyValue("TargetFramework"); } ICollection <ProjectItem> pkgs = loadedProj.GetItemsIgnoringCondition("PackageReference"); if (pkgs.Any <ProjectItem>()) { var testReference = pkgs.Where <ProjectItem>((p) => p.EvaluatedInclude.Equals("xunit", StringComparison.OrdinalIgnoreCase)); if (testReference.Any <ProjectItem>()) { pType = SdkProjctType.Test; } else { pType = SdkProjctType.Sdk; } } var fxNames = targetFxList?.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)?.ToList <string>(); foreach (string fx in fxNames) { bool isFxSupported = IsTargetFxSupported(fx, out TargetFrameworkMoniker tfxMoniker); SdkProjectMetaData sp = new SdkProjectMetaData(project: proj, fxMoniker: tfxMoniker, fullProjectPath: proj.ItemSpec, isTargetFxSupported: isFxSupported, projectType: pType); supportedProjectBag.Add(sp); } } catch (Exception ex) { if (buildEng != null) { Log.LogWarningFromException(ex); } else { Debug.WriteLine(ex.Message); } } //} //loadedProj = null; } //); return(supportedProjectBag); }
bool Initialize(string taskName, IDictionary <string, string> factoryIdentityParameters, IDictionary <string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) { task_name = taskName; if (parameterGroup != null) { parameter_group = new Dictionary <string, TaskPropertyInfo> (parameterGroup); } List <string> references = new List <string> (); List <string> namespace_uses = new List <string> (); namespace_uses.Add("Microsoft.Build.Framework"); string type = null, language = null, code = null; var xml = XmlReader.Create(new StringReader(taskBody), new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment }); for (xml.MoveToContent(); !xml.EOF; xml.MoveToContent()) { switch (xml.NodeType) { case XmlNodeType.Element: switch (xml.LocalName) { case "Reference": references.Add(xml.GetAttribute("Include")); xml.Skip(); break; case "Using": namespace_uses.Add(xml.GetAttribute("Namespace")); xml.Skip(); break; case "Code": // MSB3757: Multiple Code elements have been found, this is not allowed. if (code != null) { throw new InvalidProjectFileException(null, "Multiple Code elements are not allowed", "MSB", "3757", null); } type = xml.GetAttribute("Type"); language = xml.GetAttribute("Language"); code = xml.ReadElementContentAsString(); break; } break; default: xml.Skip(); break; } } if (language != "cs" && language != "vb") { throw new InvalidProjectFileException(null, string.Format("{0} is not supported language for inline task", language), "MSB", "4175", null); } CodeCompileUnit ccu; if (type == "Class") // 'code' contains the whole class that implements the task { ccu = new CodeSnippetCompileUnit(code); } else // 'code' contains parts of the class that implements the task { ccu = new CodeCompileUnit(); var nsp = new CodeNamespace(); nsp.Imports.AddRange(namespace_uses.Select(x => new CodeNamespaceImport(x)).ToArray()); ccu.Namespaces.Add(nsp); var taskClass = new CodeTypeDeclaration { IsClass = true, Name = taskName, TypeAttributes = TypeAttributes.Public }; var parameters = new List <CodeMemberProperty> (); var parametersBackingFields = new List <CodeMemberField> (); // add a public property + backing field for each parameter foreach (var param in parameter_group) { var prop = new CodeMemberProperty { Attributes = MemberAttributes.Public | MemberAttributes.Final, Name = param.Value.Name, Type = new CodeTypeReference(param.Value.PropertyType) }; var propBf = new CodeMemberField { Attributes = MemberAttributes.Private, Name = "_" + prop.Name, Type = prop.Type }; // add getter and setter to the property prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), propBf.Name))); prop.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), propBf.Name), new CodePropertySetValueReferenceExpression())); parameters.Add(prop); parametersBackingFields.Add(propBf); } taskClass.Members.AddRange(parameters.ToArray()); taskClass.Members.AddRange(parametersBackingFields.ToArray()); taskClass.BaseTypes.Add("Microsoft.Build.Utilities.Task"); // The documentation says "ITask", but the very first example shows "Log" which is not in ITask! It is likely that the generated code uses Task or TaskExtension. if (type == "Method") // 'code' contains the 'Execute' method directly { taskClass.Members.Add(new CodeSnippetTypeMember(code)); } else if (type == "Fragment") // 'code' contains the body of the 'Execute' method { var method = new CodeMemberMethod { Attributes = MemberAttributes.Public | MemberAttributes.Override, Name = "Execute", ReturnType = new CodeTypeReference(typeof(bool)) }; // add the code and a 'return true' at the end of the method method.Statements.Add(new CodeSnippetStatement(code)); method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(true))); taskClass.Members.Add(method); } else { throw new ArgumentException("Invalid type: " + type); } nsp.Types.Add(taskClass); } var cscParams = new CompilerParameters(); cscParams.ReferencedAssemblies.Add("Microsoft.Build.Framework.dll"); cscParams.ReferencedAssemblies.Add("Microsoft.Build.Utilities.v4.0.dll"); // since we use Task, it depends on this dll. cscParams.ReferencedAssemblies.AddRange(GetReferences(references, taskFactoryLoggingHost)); cscParams.GenerateInMemory = true; var results = CodeDomProvider.CreateProvider(language).CompileAssemblyFromDom(cscParams, ccu); var errors = new CompilerError [results.Errors.Count]; results.Errors.CopyTo(errors, 0); if (errors.Any(e => !e.IsWarning)) { string msg = string.Format("Invalid '{0}' source code of '{1}' type: {2}", language, type, string.Join(" ", errors.Where(e => !e.IsWarning).Select(e => e.ToString()))); throw new InvalidProjectFileException(null, msg, "MSB", "3758", null); } assembly = results.CompiledAssembly; return(true); }
public bool Initialize(string taskName, IDictionary <string, TaskPropertyInfo> taskParameters, string taskElementContents, IBuildEngine taskFactoryLoggingHost) { this.nameOfTask = taskName; this.log = new TaskLoggingHelper(taskFactoryLoggingHost, taskName); this.log.TaskResources = Microsoft.Build.Shared.AssemblyResources.PrimaryResources; this.log.HelpKeywordPrefix = "MSBuild."; XmlNode node = this.ExtractTaskContent(taskElementContents); if (node == null) { return(false); } if (!this.ValidateTaskNode()) { return(false); } if (node.Attributes["Type"] != null) { this.type = node.Attributes["Type"].Value; if (this.type.Length == 0) { this.log.LogErrorWithCodeFromResources("CodeTaskFactory.AttributeEmpty", new object[] { "Type" }); return(false); } } if (node.Attributes["Language"] != null) { this.language = node.Attributes["Language"].Value; if (this.language.Length == 0) { this.log.LogErrorWithCodeFromResources("CodeTaskFactory.AttributeEmpty", new object[] { "Language" }); return(false); } } if (node.Attributes["Source"] != null) { this.sourcePath = node.Attributes["Source"].Value; if (this.sourcePath.Length == 0) { this.log.LogErrorWithCodeFromResources("CodeTaskFactory.AttributeEmpty", new object[] { "Source" }); return(false); } if (this.type == null) { this.type = "Class"; } } this.referencedAssemblies = this.ExtractReferencedAssemblies(); if (this.log.HasLoggedErrors) { return(false); } this.usingNamespaces = this.ExtractUsingNamespaces(); if (this.log.HasLoggedErrors) { return(false); } this.sourceCode = node.InnerText; if (this.log.HasLoggedErrors) { return(false); } if (this.type == null) { this.type = "Fragment"; } if (this.language == null) { this.language = "cs"; } if (string.Equals(this.type, "Fragment", StringComparison.OrdinalIgnoreCase)) { this.typeIsFragment = true; this.typeIsMethod = false; } else if (string.Equals(this.type, "Method", StringComparison.OrdinalIgnoreCase)) { this.typeIsFragment = false; this.typeIsMethod = true; } this.taskParameterTypeInfo = taskParameters; this.compiledAssembly = this.CompileInMemoryAssembly(); Type[] exportedTypes = this.compiledAssembly.GetExportedTypes(); Type type = null; Type type2 = null; foreach (Type type3 in exportedTypes) { string fullName = type3.FullName; if (fullName.Equals(this.nameOfTask, StringComparison.OrdinalIgnoreCase)) { type = type3; break; } if ((type2 == null) && fullName.EndsWith(this.nameOfTask, StringComparison.OrdinalIgnoreCase)) { type2 = type3; } } this.TaskType = type ?? type2; if (this.TaskType == null) { this.log.LogErrorWithCodeFromResources("CodeTaskFactory.CouldNotFindTaskInAssembly", new object[] { this.nameOfTask }); } return(!this.log.HasLoggedErrors); }
public abstract bool RunMSBuild(IBuildEngine buildEngine, string projectFilePath, string binLogPath);
/// <summary> /// Initialize the factory. /// </summary> public bool Initialize(string taskName, IDictionary <string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) { if (!String.Equals(taskName, TaskType.Name, StringComparison.OrdinalIgnoreCase)) { ErrorUtilities.ThrowInternalError("Unexpected task name {0}. Expected {1}", taskName, TaskType.Name); } return(true); }
protected WixToolTask(IBuildEngine engine, string wixToolsetPath) { BuildEngine = engine ?? throw new ArgumentNullException(nameof(engine)); Utils.CheckNullOrEmpty(nameof(wixToolsetPath), wixToolsetPath); ToolPath = wixToolsetPath; }