public void VerifyGetTaskParameters()
        {
            TaskPropertyInfo[] propertyInfos  = _taskFactory.GetTaskParameters();
            LoadedType         comparisonType = new LoadedType(typeof(TaskToTestFactories), _loadInfo);

            PropertyInfo[] comparisonInfo = comparisonType.Type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            Assert.Equal(comparisonInfo.Length, propertyInfos.Length);

            bool foundExpectedParameter    = false;
            bool foundNotExpectedParameter = false;

            for (int i = 0; i < propertyInfos.Length; i++)
            {
                if (propertyInfos[i].Name.Equals("ExpectedParameter", StringComparison.OrdinalIgnoreCase))
                {
                    foundExpectedParameter = true;
                }

                if (propertyInfos[i].Name.Equals("NotExpectedParameter", StringComparison.OrdinalIgnoreCase))
                {
                    foundNotExpectedParameter = true;
                }
            }

            Assert.True(foundExpectedParameter);
            Assert.False(foundNotExpectedParameter);
        }
 /// <summary>
 /// Abstract out the creation of the new AssemblyTaskFactory with default task, and
 /// with some basic validation.
 /// </summary>
 private void SetupTaskFactory(IDictionary <string, string> factoryParameters, bool explicitlyLaunchTaskHost)
 {
     _taskFactory = new AssemblyTaskFactory();
     _loadInfo    = AssemblyLoadInfo.Create(null, Assembly.GetAssembly(typeof(TaskToTestFactories)).Location);
     _loadedType  = _taskFactory.InitializeFactory(_loadInfo, "TaskToTestFactories", new Dictionary <string, TaskPropertyInfo>(), string.Empty, factoryParameters, explicitlyLaunchTaskHost, null, ElementLocation.Create("NONE"), String.Empty);
     Assert.True(_loadedType.Assembly.Equals(_loadInfo)); // "Expected the AssemblyLoadInfo to be equal"
 }
Beispiel #3
0
        public TaskHostTask(IElementLocation taskLocation, TaskLoggingContext taskLoggingContext, IBuildComponentHost buildComponentHost, IDictionary <string, string> taskHostParameters, LoadedType taskType
#if FEATURE_APPDOMAIN
                            , AppDomainSetup appDomainSetup
#endif
                            )
        {
            ErrorUtilities.VerifyThrowInternalNull(taskType, nameof(taskType));

            _taskLocation       = taskLocation;
            _taskLoggingContext = taskLoggingContext;
            _buildComponentHost = buildComponentHost;
            _taskType           = taskType;
#if FEATURE_APPDOMAIN
            _appDomainSetup = appDomainSetup;
#endif
            _taskHostParameters = taskHostParameters;

            _packetFactory = new NodePacketFactory();

            (this as INodePacketFactory).RegisterPacketHandler(NodePacketType.LogMessage, LogMessagePacket.FactoryForDeserialization, this);
            (this as INodePacketFactory).RegisterPacketHandler(NodePacketType.TaskHostTaskComplete, TaskHostTaskComplete.FactoryForDeserialization, this);
            (this as INodePacketFactory).RegisterPacketHandler(NodePacketType.NodeShutdown, NodeShutdown.FactoryForDeserialization, this);

            _packetReceivedEvent = new AutoResetEvent(false);
            _receivedPackets     = new ConcurrentQueue <INodePacket>();
            _taskHostLock        = new Object();

            _setParameters = new Dictionary <string, object>();
        }
Beispiel #4
0
        public void SetUp()
        {
            // Whole bunch of setup code.
            XmlElement taskNode  = new XmlDocument().CreateElement("MockTask");
            LoadedType taskClass = new LoadedType(typeof(MockTask), new AssemblyLoadInfo(typeof(MockTask).Assembly.FullName, null));
            Engine     engine    = new Engine(@"c:\");

            loggingHelper          = new EngineLoggingServicesHelper();
            engine.LoggingServices = loggingHelper;
            Project project = new Project(engine);

            taskExecutionModule = new MockTaskExecutionModule(new EngineCallback(engine));
            // Set up some "fake data" which will be passed to the Task Execution State object
            Hashtable[] fakeArray = new Hashtable[1];
            fakeArray[0] = new Hashtable();
            projectLevelProprtiesForInference  = new BuildPropertyGroup();
            projectLevelPropertiesForExecution = new BuildPropertyGroup();
            inferenceBucketItemsByName         = fakeArray;
            inferenceBucketMetaData            = fakeArray;
            projectLevelItemsForInference      = new Hashtable();
            executionBucketItemsByName         = fakeArray;
            executionBucketMetaData            = fakeArray;
            projectLevelItemsForExecution      = new Hashtable();
            hostObject                = null;
            projectFileOfTaskNode     = "In Memory";
            parentProjectFullFileName = project.FullFileName;
            nodeProxyId               = engine.EngineCallback.CreateTaskContext(project, null, null, taskNode, EngineCallback.inProcNode, new BuildEventContext(BuildEventContext.InvalidNodeId, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTaskId));
            executionDirectory        = Directory.GetCurrentDirectory();
            projectId = project.Id;
        }
Beispiel #5
0
        public void SetUp()
        {
            // Whole bunch of setup code.
            XmlElement taskNode  = new XmlDocument().CreateElement("MockTask");
            LoadedType taskClass = new LoadedType(typeof(MockTask), new AssemblyLoadInfo(typeof(MockTask).Assembly.FullName, null));

            engine = new Engine(@"c:\");
            Project        project        = new Project(engine);
            EngineCallback engineCallback = new EngineCallback(engine);

            taskExecutionModule = new MockTaskExecutionModule(engineCallback);
            int        handleId   = engineCallback.CreateTaskContext(project, null, null, taskNode, EngineCallback.inProcNode, new BuildEventContext(BuildEventContext.InvalidNodeId, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTaskId));
            TaskEngine taskEngine = new TaskEngine
                                    (
                taskNode,
                null,                     /* host object */
                "In Memory",
                project.FullFileName,
                engine.LoggingServices,
                handleId,
                taskExecutionModule,
                null
                                    );

            taskEngine.TaskClass = taskClass;

            engineProxy          = new EngineProxy(taskExecutionModule, handleId, project.FullFileName, project.FullFileName, engine.LoggingServices, null);
            taskExecutionModule2 = new MockTaskExecutionModule(engineCallback, TaskExecutionModule.TaskExecutionModuleMode.MultiProcFullNodeMode);
            engineProxy2         = new EngineProxy(taskExecutionModule2, handleId, project.FullFileName, project.FullFileName, engine.LoggingServices, null);
        }
Beispiel #6
0
        public void NoTypeNamePicksFirstType()
        {
            Type   forwardingLoggerType                      = typeof(net.r_eg.IeXod.Logging.ConfigurableForwardingLogger);
            string forwardingLoggerAssemblyLocation          = forwardingLoggerType.Assembly.Location;
            Func <Type, object, bool> forwardingLoggerfilter = IsForwardingLoggerClass;
            Type firstPublicType = FirstPublicDesiredType(forwardingLoggerfilter, forwardingLoggerAssemblyLocation);

            TypeLoader loader     = new TypeLoader(forwardingLoggerfilter);
            LoadedType loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, forwardingLoggerAssemblyLocation));

            Assert.NotNull(loadedType);
            Assert.Equal(forwardingLoggerAssemblyLocation, loadedType.Assembly.AssemblyLocation);
            Assert.Equal(firstPublicType, loadedType.Type);


            Type   fileLoggerType                      = typeof(net.r_eg.IeXod.Logging.FileLogger);
            string fileLoggerAssemblyLocation          = forwardingLoggerType.Assembly.Location;
            Func <Type, object, bool> fileLoggerfilter = IsLoggerClass;

            firstPublicType = FirstPublicDesiredType(fileLoggerfilter, fileLoggerAssemblyLocation);

            loader     = new TypeLoader(fileLoggerfilter);
            loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, fileLoggerAssemblyLocation));
            Assert.NotNull(loadedType);
            Assert.Equal(fileLoggerAssemblyLocation, loadedType.Assembly.AssemblyLocation);
            Assert.Equal(firstPublicType, loadedType.Type);
        }
Beispiel #7
0
        public void NoTypeNamePicksFirstType()
        {
            Type   forwardingLoggerType                      = typeof(Microsoft.Build.Logging.ConfigurableForwardingLogger);
            string forwardingLoggerAssemblyLocation          = forwardingLoggerType.Assembly.Location;
            Func <Type, object, bool> forwardingLoggerfilter = IsForwardingLoggerClass;
            Type firstPublicType = FirstPublicDesiredType(forwardingLoggerfilter, forwardingLoggerAssemblyLocation);

            TypeLoader loader     = new TypeLoader(forwardingLoggerfilter);
            LoadedType loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, forwardingLoggerAssemblyLocation));

            Assert.NotNull(loadedType);
            Assert.True(loadedType.Assembly.AssemblyLocation.Equals(forwardingLoggerAssemblyLocation, StringComparison.OrdinalIgnoreCase));
            Assert.True(loadedType.Type.Equals(firstPublicType));


            Type   fileLoggerType                      = typeof(Microsoft.Build.Logging.FileLogger);
            string fileLoggerAssemblyLocation          = forwardingLoggerType.Assembly.Location;
            Func <Type, object, bool> fileLoggerfilter = IsLoggerClass;

            firstPublicType = FirstPublicDesiredType(fileLoggerfilter, fileLoggerAssemblyLocation);

            loader     = new TypeLoader(fileLoggerfilter);
            loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, fileLoggerAssemblyLocation));
            Assert.NotNull(loadedType);
            Assert.True(loadedType.Assembly.AssemblyLocation.Equals(fileLoggerAssemblyLocation, StringComparison.OrdinalIgnoreCase));
            Assert.True(loadedType.Type.Equals(firstPublicType));
        }
Beispiel #8
0
        /// <summary>
        /// Is the given task name able to be created by the task factory. In the case of an assembly task factory
        /// this question is answered by checking the assembly wrapped by the task factory to see if it exists.
        /// </summary>
        internal bool TaskNameCreatableByFactory(string taskName, IDictionary <string, string> taskIdentityParameters, string taskProjectFile, TargetLoggingContext targetLoggingContext, ElementLocation elementLocation)
        {
            if (!TaskIdentityParametersMatchFactory(_factoryIdentityParameters, taskIdentityParameters))
            {
                return(false);
            }

            // Parameters match, so now we check to see if the task exists.
            LoadedType taskClass = null;

            try
            {
                ErrorUtilities.VerifyThrowArgumentLength(taskName, "TaskName");
                taskClass = _typeLoader.ReflectionOnlyLoad(taskName, _loadedType.Assembly);
                if (taskClass != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (TargetInvocationException e)
            {
                // Exception thrown by the called code itself
                // Log the stack, so the task vendor can fix their code
                ProjectErrorUtilities.ThrowInvalidProject(elementLocation, "TaskLoadFailure", taskName, _loadedType.Assembly.AssemblyLocation, Environment.NewLine + e.InnerException.ToString());
            }
            catch (ReflectionTypeLoadException e)
            {
                // ReflectionTypeLoadException.LoaderExceptions may contain nulls
                foreach (Exception exception in e.LoaderExceptions)
                {
                    if (exception != null)
                    {
                        targetLoggingContext.LogError(new BuildEventFileInfo(taskProjectFile), "TaskLoadFailure", taskName, _loadedType.Assembly.AssemblyLocation, exception.Message);
                    }
                }

                ProjectErrorUtilities.ThrowInvalidProject(elementLocation, "TaskLoadFailure", taskName, _loadedType.Assembly.AssemblyLocation, e.Message);
            }
            catch (ArgumentNullException e)
            {
                // taskName may be null
                ProjectErrorUtilities.ThrowInvalidProject(elementLocation, "TaskLoadFailure", taskName, _loadedType.Assembly.AssemblyLocation, e.Message);
            }
            catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception.
            {
                if (ExceptionHandling.NotExpectedReflectionException(e))
                {
                    throw;
                }

                ProjectErrorUtilities.ThrowInvalidProject(elementLocation, "TaskLoadFailure", taskName, _loadedType.Assembly.AssemblyLocation, e.Message);
            }

            return(false);
        }
        /// <summary>
        /// We just need the loaded type information because the task factory which is not instance specific should 
        /// already have loaded the assembly and got the information.
        /// </summary>
        public AssemblyTaskFactoryInstance(string taskName, LoadedType loadedType)
        {
            ErrorUtilities.VerifyThrowArgumentLength(taskName, "taskName");
            ErrorUtilities.VerifyThrowArgumentNull(loadedType, "loadedType");

            this.taskName = taskName;
            this.loadedType = loadedType;
        }
Beispiel #10
0
        /// <summary>
        /// Loads a logger from its assembly, instantiates it, and handles errors.
        /// </summary>
        /// <returns>Instantiated logger.</returns>
        private ILogger CreateLogger(bool forwardingLogger)
        {
            ILogger logger = null;

            try
            {
                if (forwardingLogger)
                {
                    // load the logger from its assembly
                    LoadedType loggerClass = (new TypeLoader(s_forwardingLoggerClassFilter)).Load(_loggerClassName, _loggerAssembly);

                    if (loggerClass != null)
                    {
                        // instantiate the logger
                        logger = (IForwardingLogger)Activator.CreateInstance(loggerClass.Type);
                    }
                }
                else
                {
                    // load the logger from its assembly
                    LoadedType loggerClass = (new TypeLoader(s_loggerClassFilter)).Load(_loggerClassName, _loggerAssembly);

                    if (loggerClass != null)
                    {
                        // instantiate the logger
                        logger = (ILogger)Activator.CreateInstance(loggerClass.Type);
                    }
                }
            }
            catch (InvalidCastException e)
            {
                // The logger when trying to load has hit an invalid case, this is usually due to the framework assembly being a different version
                string message = ResourceUtilities.FormatResourceString("LoggerInstantiationFailureErrorInvalidCast", _loggerClassName, _loggerAssembly.AssemblyLocation, e.Message);
                throw new LoggerException(message, e.InnerException);
            }
            catch (TargetInvocationException e)
            {
                // At this point, the interesting stack is the internal exception;
                // the outer exception is System.Reflection stuff that says nothing
                // about the nature of the logger failure.
                Exception innerException = e.InnerException;

                if (innerException is LoggerException)
                {
                    // Logger failed politely during construction. In order to preserve
                    // the stack trace at which the error occured we wrap the original
                    // exception instead of throwing.
                    LoggerException l = ((LoggerException)innerException);
                    throw new LoggerException(l.Message, innerException, l.ErrorCode, l.HelpKeyword);
                }
                else
                {
                    throw;
                }
            }

            return(logger);
        }
Beispiel #11
0
 /// <summary>
 /// Creates an instance of this class for the given type.
 /// </summary>
 internal TaskFactoryWrapper(ITaskFactory taskFactory, LoadedType taskFactoryLoadInfo, string taskName, IDictionary <string, string> factoryIdentityParameters)
 {
     ErrorUtilities.VerifyThrowArgumentNull(taskFactory, "taskFactory");
     ErrorUtilities.VerifyThrowArgumentLength(taskName, "taskName");
     _taskFactory               = taskFactory;
     _taskName                  = taskName;
     TaskFactoryLoadedType      = taskFactoryLoadInfo;
     _factoryIdentityParameters = factoryIdentityParameters;
 }
Beispiel #12
0
        /// <summary>
        /// Given a task name and a list of assemblies, this helper method checks if the task exists in any of the assemblies.
        /// </summary>
        /// <remarks>
        /// If the task name is fully qualified, then a match (if any) is unambiguous; otherwise, if there are multiple tasks with
        /// the same name in different namespaces/assemblies, the first task found will be returned.
        /// </remarks>
        /// <param name="taskName"></param>
        /// <param name="taskAssemblies"></param>
        /// <param name="taskProjectFile"></param>
        /// <param name="taskNode"></param>
        /// <param name="loggingServices"></param>
        /// <param name="buildEventContext"></param>
        /// <param name="taskClass"></param>
        /// <returns>true, if task is successfully loaded</returns>
        private bool GetTaskFromAssembly
        (
            string taskName,
            ArrayList taskAssemblies,
            string taskProjectFile,
            XmlNode taskNode,
            EngineLoggingServices loggingServices,
            BuildEventContext buildEventContext,
            out LoadedType taskClass
        )
        {
            taskClass = null;

            foreach (AssemblyLoadInfo assembly in taskAssemblies)
            {
                try
                {
                    taskClass = typeLoader.Load(taskName, assembly);
                }
                catch (TargetInvocationException e)
                {
                    // Exception thrown by the called code itself
                    // Log the stack, so the task vendor can fix their code
                    ProjectErrorUtilities.VerifyThrowInvalidProject(false, taskNode, "TaskLoadFailure", taskName, assembly.ToString(), Environment.NewLine + e.InnerException.ToString());
                }
                catch (ReflectionTypeLoadException e)
                {
                    // ReflectionTypeLoadException.LoaderExceptions may contain nulls
                    foreach (Exception exception in e.LoaderExceptions)
                    {
                        if (exception != null)
                        {
                            loggingServices.LogError(buildEventContext, new BuildEventFileInfo(taskProjectFile), "TaskLoadFailure", taskName, assembly.ToString(), exception.Message);
                        }
                    }

                    ProjectErrorUtilities.VerifyThrowInvalidProject(false, taskNode, "TaskLoadFailure", taskName, assembly.ToString(), e.Message);
                }
                catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception.
                {
                    if (ExceptionHandling.NotExpectedReflectionException(e))
                    {
                        throw;
                    }

                    ProjectErrorUtilities.VerifyThrowInvalidProject(false, taskNode, "TaskLoadFailure", taskName, assembly.ToString(), e.Message);
                }

                if (taskClass != null)
                {
                    return(true);
                }
            }

            return(false);
        }
        public static TaskPropertyInfo[] GetTaskParameters(LoadedType loadedType)
        {
            PropertyInfo[] infos         = loadedType.Type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            var            propertyInfos = new TaskPropertyInfo[infos.Length];

            for (int i = 0; i < infos.Length; i++)
            {
                propertyInfos[i] = new ReflectableTaskPropertyInfo(infos[i]);
            }

            return(propertyInfos);
        }
Beispiel #14
0
        /// <summary>
        /// Loads a logger from its assembly, instantiates it, and handles errors.
        /// </summary>
        /// <returns>Instantiated logger.</returns>
        private ILogger CreateLogger(bool forwardingLogger)
        {
            ILogger logger = null;

            try
            {
                if (forwardingLogger)
                {
                    // load the logger from its assembly
                    LoadedType loggerClass = (new TypeLoader(forwardingLoggerClassFilter)).Load(loggerClassName, loggerAssembly);

                    if (loggerClass != null)
                    {
                        // instantiate the logger
                        logger = (IForwardingLogger)Activator.CreateInstance(loggerClass.Type);
                    }
                }
                else
                {
                    // load the logger from its assembly
                    LoadedType loggerClass = (new TypeLoader(loggerClassFilter)).Load(loggerClassName, loggerAssembly);

                    if (loggerClass != null)
                    {
                        // instantiate the logger
                        logger = (ILogger)Activator.CreateInstance(loggerClass.Type);
                    }
                }
            }
            catch (TargetInvocationException e)
            {
                // At this point, the interesting stack is the internal exception;
                // the outer exception is System.Reflection stuff that says nothing
                // about the nature of the logger failure.
                Exception innerException = e.InnerException;

                if (innerException is LoggerException)
                {
                    // Logger failed politely during construction. In order to preserve
                    // the stack trace at which the error occurred we wrap the original
                    // exception instead of throwing.
                    LoggerException l = ((LoggerException)innerException);
                    throw new LoggerException(l.Message, innerException, l.ErrorCode, l.HelpKeyword);
                }
                else
                {
                    throw;
                }
            }

            return(logger);
        }
Beispiel #15
0
        public IElement EnterArray(IElement index)
        {
            if (!IsIndexable)
            {
                throw new NotSupportedException("This element does not support indexing.");
            }

            var arrayElement = (BaseElement)this[index];

            arrayElement.previous = this;
            next = arrayElement;
            arrayElement.LoadedType = LoadedType.GetElementType();
            return(next);
        }
Beispiel #16
0
        public void Regress640476PartialName()
        {
            string     forwardingLoggerLocation = typeof(net.r_eg.IeXod.Logging.ConfigurableForwardingLogger).Assembly.Location;
            TypeLoader loader     = new TypeLoader(IsForwardingLoggerClass);
            LoadedType loadedType = loader.Load("ConfigurableForwardingLogger", AssemblyLoadInfo.Create(null, forwardingLoggerLocation));

            Assert.NotNull(loadedType);
            Assert.Equal(forwardingLoggerLocation, loadedType.Assembly.AssemblyLocation);

            string fileLoggerLocation = typeof(net.r_eg.IeXod.Logging.FileLogger).Assembly.Location;

            loader     = new TypeLoader(IsLoggerClass);
            loadedType = loader.Load("FileLogger", AssemblyLoadInfo.Create(null, fileLoggerLocation));
            Assert.NotNull(loadedType);
            Assert.Equal(fileLoggerLocation, loadedType.Assembly.AssemblyLocation);
        }
Beispiel #17
0
        public void Regress640476PartialName()
        {
            string     forwardingLoggerLocation = typeof(Microsoft.Build.Logging.ConfigurableForwardingLogger).Assembly.Location;
            TypeLoader loader     = new TypeLoader(IsForwardingLoggerClass);
            LoadedType loadedType = loader.Load("ConfigurableForwardingLogger", AssemblyLoadInfo.Create(null, forwardingLoggerLocation));

            Assert.NotNull(loadedType);
            Assert.True(loadedType.Assembly.AssemblyLocation.Equals(forwardingLoggerLocation, StringComparison.OrdinalIgnoreCase));

            string fileLoggerLocation = typeof(Microsoft.Build.Logging.FileLogger).Assembly.Location;

            loader     = new TypeLoader(IsLoggerClass);
            loadedType = loader.Load("FileLogger", AssemblyLoadInfo.Create(null, fileLoggerLocation));
            Assert.NotNull(loadedType);
            Assert.True(loadedType.Assembly.AssemblyLocation.Equals(fileLoggerLocation, StringComparison.OrdinalIgnoreCase));
        }
Beispiel #18
0
        public void Regress640476FullyQualifiedName()
        {
            Type       forwardingLoggerType     = typeof(Microsoft.Build.Logging.ConfigurableForwardingLogger);
            string     forwardingLoggerLocation = forwardingLoggerType.Assembly.Location;
            TypeLoader loader     = new TypeLoader(IsForwardingLoggerClass);
            LoadedType loadedType = loader.Load(forwardingLoggerType.FullName, AssemblyLoadInfo.Create(null, forwardingLoggerLocation));

            Assert.NotNull(loadedType);
            Assert.Equal(forwardingLoggerLocation, loadedType.Assembly.AssemblyLocation);

            Type   fileLoggerType     = typeof(Microsoft.Build.Logging.FileLogger);
            string fileLoggerLocation = fileLoggerType.Assembly.Location;

            loader     = new TypeLoader(IsLoggerClass);
            loadedType = loader.Load(fileLoggerType.FullName, AssemblyLoadInfo.Create(null, fileLoggerLocation));
            Assert.NotNull(loadedType);
            Assert.Equal(fileLoggerLocation, loadedType.Assembly.AssemblyLocation);
        }
Beispiel #19
0
        public virtual void Load(Emit g, TypeOfContent content)
        {
            if (Index != null)
            {
                InternalLoad(g, TypeOfContent.Value);

                if (LoadedType.IsByRef)
                {
                    g.LoadIndirect(LoadedType.GetElementType());
                }

                Index.Load(g, TypeOfContent.Value);

                if (content == TypeOfContent.Value)
                {
                    g.LoadElement(LoadedType);
                }
                else
                {
                    g.LoadElementAddress(LoadedType);
                }
            }
            else
            {
                if (LoadedType.IsByRef)
                {
                    InternalLoad(g, TypeOfContent.Value);
                    if (content == TypeOfContent.Value)
                    {
                        g.LoadIndirect(LoadedType.GetElementType());
                    }
                }
                else
                {
                    InternalLoad(g, content);
                }
            }
        }
Beispiel #20
0
 public override string ToString()
 {
     return($"{GetType().ToString()}; Load: {LoadedType.ToString()};");
 }
Beispiel #21
0
        /// <summary>
        /// Initialize the factory from the task registry
        /// </summary>
        internal LoadedType InitializeFactory
        (
            AssemblyLoadInfo loadInfo,
            string taskName,
            IDictionary <string, TaskPropertyInfo> taskParameters,
            string taskElementContents,
            IDictionary <string, string> taskFactoryIdentityParameters,
            bool taskHostFactoryExplicitlyRequested,
            TargetLoggingContext targetLoggingContext,
            ElementLocation elementLocation,
            string taskProjectFile
        )
        {
            ErrorUtilities.VerifyThrowArgumentNull(loadInfo, "loadInfo");
            VerifyThrowIdentityParametersValid(taskFactoryIdentityParameters, elementLocation, taskName, "Runtime", "Architecture");

            if (taskFactoryIdentityParameters != null)
            {
                _factoryIdentityParameters = new Dictionary <string, string>(taskFactoryIdentityParameters, StringComparer.OrdinalIgnoreCase);
            }

            _taskHostFactoryExplicitlyRequested = taskHostFactoryExplicitlyRequested;

            try
            {
                ErrorUtilities.VerifyThrowArgumentLength(taskName, "taskName");
                _taskName   = taskName;
                _loadedType = _typeLoader.Load(taskName, loadInfo);
                ProjectErrorUtilities.VerifyThrowInvalidProject(_loadedType != null, elementLocation, "TaskLoadFailure", taskName, loadInfo.AssemblyLocation, String.Empty);
            }
            catch (TargetInvocationException e)
            {
                // Exception thrown by the called code itself
                // Log the stack, so the task vendor can fix their code
                ProjectErrorUtilities.VerifyThrowInvalidProject(false, elementLocation, "TaskLoadFailure", taskName, loadInfo.AssemblyLocation, Environment.NewLine + e.InnerException.ToString());
            }
            catch (ReflectionTypeLoadException e)
            {
                // ReflectionTypeLoadException.LoaderExceptions may contain nulls
                foreach (Exception exception in e.LoaderExceptions)
                {
                    if (exception != null)
                    {
                        targetLoggingContext.LogError(new BuildEventFileInfo(taskProjectFile), "TaskLoadFailure", taskName, loadInfo.AssemblyLocation, exception.Message);
                    }
                }

                ProjectErrorUtilities.VerifyThrowInvalidProject(false, elementLocation, "TaskLoadFailure", taskName, loadInfo.AssemblyLocation, e.Message);
            }
            catch (ArgumentNullException e)
            {
                // taskName may be null
                ProjectErrorUtilities.VerifyThrowInvalidProject(false, elementLocation, "TaskLoadFailure", taskName, loadInfo.AssemblyLocation, e.Message);
            }
            catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception.
            {
                if (ExceptionHandling.NotExpectedReflectionException(e))
                {
                    throw;
                }

                ProjectErrorUtilities.VerifyThrowInvalidProject(false, elementLocation, "TaskLoadFailure", taskName, loadInfo.AssemblyLocation, e.Message);
            }

            return(_loadedType);
        }
Beispiel #22
0
        private List <TaskExecutionStateHelper> InitializeTaskState()
        {
            BuildPropertyGroup projectLevelProprtiesForInference;
            BuildPropertyGroup projectLevelPropertiesForExecution;

            Hashtable[] inferenceBucketItemsByName;
            Hashtable[] inferenceBucketMetaData;
            Hashtable   projectLevelItemsForInference;

            Hashtable[] executionBucketItemsByName;
            Hashtable[] executionBucketMetaData;
            Hashtable   projectLevelItemsForExecution;
            ITaskHost   hostObject;
            EngineLoggingServicesHelper loggingHelper;
            string projectFileOfTaskNode;
            string parentProjectFullFileName;
            int    nodeProxyId;
            int    projectId;
            string executionDirectory;

            XmlElement taskNode  = new XmlDocument().CreateElement("MockTask");
            LoadedType taskClass = new LoadedType(typeof(MockTask), new AssemblyLoadInfo(typeof(MockTask).Assembly.FullName, null));

            loggingHelper          = new EngineLoggingServicesHelper();
            engine.LoggingServices = loggingHelper;
            Project project = new Project(engine);

            nodeProxyId = engine.EngineCallback.CreateTaskContext(project, null, null, taskNode, EngineCallback.inProcNode, new BuildEventContext(BuildEventContext.InvalidNodeId, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTaskId));
            // Set up some "fake data" which will be passed to the Task Execution State object
            Hashtable[] fakeArray = new Hashtable[1];
            fakeArray[0] = new Hashtable();
            projectLevelProprtiesForInference  = new BuildPropertyGroup();
            projectLevelPropertiesForExecution = new BuildPropertyGroup();
            inferenceBucketItemsByName         = fakeArray;
            inferenceBucketMetaData            = fakeArray;
            projectLevelItemsForInference      = new Hashtable();
            executionBucketItemsByName         = fakeArray;
            executionBucketMetaData            = fakeArray;
            projectLevelItemsForExecution      = new Hashtable();
            hostObject                = null;
            projectFileOfTaskNode     = "In Memory";
            parentProjectFullFileName = project.FullFileName;

            executionDirectory = Directory.GetCurrentDirectory();
            projectId          = project.Id;


            MockTaskExecutionModule taskExecutionModule = taskExecutionModule = new MockTaskExecutionModule(new EngineCallback(engine));
            TaskExecutionMode       howToExecuteTask    = TaskExecutionMode.InferOutputsOnly;

            List <TaskExecutionStateHelper> executionStates = new List <TaskExecutionStateHelper>();

            TaskExecutionStateHelper executionStateNormal1 = new TaskExecutionStateHelper(
                howToExecuteTask,
                LookupHelpers.CreateLookup(projectLevelProprtiesForInference, projectLevelItemsForInference),
                LookupHelpers.CreateLookup(projectLevelPropertiesForExecution, projectLevelItemsForExecution),
                taskNode,
                hostObject,
                projectFileOfTaskNode,
                parentProjectFullFileName,
                executionDirectory,
                nodeProxyId);

            executionStateNormal1.LoggingService            = loggingHelper;
            executionStateNormal1.TargetInferenceSuccessful = true;
            executionStateNormal1.ParentModule = taskExecutionModule;

            executionStates.Add(executionStateNormal1);


            TaskExecutionStateHelper executionStateCallBack = new TaskExecutionStateHelper(
                howToExecuteTask,
                LookupHelpers.CreateLookup(projectLevelProprtiesForInference, projectLevelItemsForInference),
                LookupHelpers.CreateLookup(projectLevelPropertiesForExecution, projectLevelItemsForExecution),
                taskNode,
                hostObject,
                projectFileOfTaskNode,
                parentProjectFullFileName,
                executionDirectory,
                nodeProxyId);

            executionStateCallBack.LoggingService            = loggingHelper;
            executionStateCallBack.TargetInferenceSuccessful = true;

            executionStates.Add(executionStateCallBack);


            TaskExecutionStateHelper executionStateNormal2 = new TaskExecutionStateHelper(
                howToExecuteTask,
                LookupHelpers.CreateLookup(projectLevelProprtiesForInference, projectLevelItemsForInference),
                LookupHelpers.CreateLookup(projectLevelPropertiesForExecution, projectLevelItemsForExecution),
                taskNode,
                hostObject,
                projectFileOfTaskNode,
                parentProjectFullFileName,
                executionDirectory,
                nodeProxyId);

            executionStateNormal2.LoggingService            = loggingHelper;
            executionStateNormal2.TargetInferenceSuccessful = true;
            executionStateNormal2.ParentModule = taskExecutionModule;
            executionStates.Add(executionStateNormal2);

            TaskExecutionStateHelper executionStateNormal3 = new TaskExecutionStateHelper(
                howToExecuteTask,
                LookupHelpers.CreateLookup(projectLevelProprtiesForInference, projectLevelItemsForInference),
                LookupHelpers.CreateLookup(projectLevelPropertiesForExecution, projectLevelItemsForExecution),
                taskNode,
                hostObject,
                projectFileOfTaskNode,
                parentProjectFullFileName,
                executionDirectory,
                nodeProxyId);

            executionStateNormal3.LoggingService            = loggingHelper;
            executionStateNormal3.TargetInferenceSuccessful = true;
            executionStateNormal3.ParentModule = taskExecutionModule;
            executionStates.Add(executionStateNormal3);

            return(executionStates);
        }
        /// <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);
        }
Beispiel #24
0
        /// <summary>
        /// Given a task name, this method retrieves the task class. If the task has been requested before, it will be found in
        /// the class cache; otherwise, &lt;UsingTask&gt; declarations will be used to search the appropriate assemblies.
        /// </summary>
        /// <param name="taskName"></param>
        /// <param name="taskProjectFile"></param>
        /// <param name="taskNode"></param>
        /// <param name="exactMatchRequired"></param>
        /// <param name="loggingServices"></param>
        /// <param name="buildEventContext"></param>
        /// <param name="taskClass"></param>
        /// <returns>true, if task is found</returns>
        public bool GetRegisteredTask
        (
            string taskName,
            string taskProjectFile,
            XmlNode taskNode,
            bool exactMatchRequired,
            EngineLoggingServices loggingServices,
            BuildEventContext buildEventContext,
            out LoadedType taskClass
        )
        {
            taskClass = null;

            // If there are no using tags in the project don't bother caching or looking for tasks
            if (registeredTasks == null)
            {
                return(false);
            }

            Hashtable cachedTaskClasses = exactMatchRequired ? this.cachedTaskClassesWithExactMatch : this.cachedTaskClassesWithFuzzyMatch;

            if (cachedTaskClasses.Contains(taskName))
            {
                // Caller has asked us before for this same task name, and for the same value of "bool exactMatchRequired".
                // Return whatever the previous result was, even if it was null.   Why would the result be different than
                // it was before?  NOTE:  Hash tables CAN have "null" as their value, and this still returns "true" for Contains(...).
                taskClass = (LoadedType)cachedTaskClasses[taskName];
            }
            else
            {
                Hashtable registeredTasksFound;

                // look for the given task name in the registry; if not found, gather all registered task names that partially
                // match the given name
                if (FindRegisteredTasks(taskName, exactMatchRequired, out registeredTasksFound))
                {
                    foreach (DictionaryEntry registeredTaskFound in registeredTasksFound)
                    {
                        string mostSpecificTaskName = (string)registeredTaskFound.Key;

                        // if the given task name is longer than the registered task name
                        if (taskName.Length > ((string)registeredTaskFound.Key).Length)
                        {
                            // we will use the longer name to help disambiguate between multiple matches
                            mostSpecificTaskName = taskName;
                        }

                        if (GetTaskFromAssembly(mostSpecificTaskName, (ArrayList)registeredTaskFound.Value, taskProjectFile, taskNode, loggingServices, buildEventContext, out taskClass))
                        {
                            // Whilst we are within the processing of the task, we haven't actually started executing it, so
                            // our using task message needs to be in the context of the target. However any errors should be reported
                            // at the point where the task appears in the project.
                            BuildEventContext usingTaskContext = new BuildEventContext(buildEventContext.NodeId, buildEventContext.TargetId, buildEventContext.ProjectContextId, BuildEventContext.InvalidTaskId);
                            loggingServices.LogComment(usingTaskContext, "TaskFound", taskName, taskClass.Assembly.ToString());
                            break;
                        }
                    }
                }

                // Cache the result, even if it is null.  We should never again do the work we just did, for this task name.
                cachedTaskClasses[taskName] = taskClass;
            }

            return(taskClass != null);
        }
Beispiel #25
0
 public void TearDownAttribute()
 {
     _taskFactory = null;
     _loadInfo    = null;
     _loadedType  = null;
 }
Beispiel #26
0
        public Character(MemoryStream inStream)
        {
            LoadType     = LoadedType.Client;
            PendingFlags = PendingFlag.None;

            Byte[] stringBuffer = new Byte[20];
            Byte[] expBuffer    = new Byte[4];

            AccountId = 0;
            inStream.Seek(22, SeekOrigin.Current);
            Slot = (Byte)inStream.ReadByte();
            inStream.Seek(3, SeekOrigin.Current);
            inStream.Read(stringBuffer, 0, 20);
            Name                 = Encoding.ASCII.GetString(stringBuffer).Split((Char)0)[0];
            Agility              = (Byte)inStream.ReadByte();
            Constitution         = (Byte)inStream.ReadByte();
            Memory               = (Byte)inStream.ReadByte();
            Reasoning            = (Byte)inStream.ReadByte();
            Discipline           = (Byte)inStream.ReadByte();
            Empathy              = (Byte)inStream.ReadByte();
            Intuition            = (Byte)inStream.ReadByte();
            Presence             = (Byte)inStream.ReadByte();
            Quickness            = (Byte)inStream.ReadByte();
            Strength             = (Byte)inStream.ReadByte();
            SpentStatPoints      = 0;
            BonusStatPoints      = 0;
            BonusStatPointsSpent = 0;
            inStream.Seek(14, SeekOrigin.Current);
            List1  = (Byte)inStream.ReadByte();
            List2  = (Byte)inStream.ReadByte();
            List3  = (Byte)inStream.ReadByte();
            List4  = (Byte)inStream.ReadByte();
            List5  = (Byte)inStream.ReadByte();
            List6  = (Byte)inStream.ReadByte();
            List7  = (Byte)inStream.ReadByte();
            List8  = (Byte)inStream.ReadByte();
            List9  = (Byte)inStream.ReadByte();
            List10 = (Byte)inStream.ReadByte();
            inStream.Seek(2, SeekOrigin.Current);
            ListLevel1  = (Byte)inStream.ReadByte();
            ListLevel2  = (Byte)inStream.ReadByte();
            ListLevel3  = (Byte)inStream.ReadByte();
            ListLevel4  = (Byte)inStream.ReadByte();
            ListLevel5  = (Byte)inStream.ReadByte();
            ListLevel6  = (Byte)inStream.ReadByte();
            ListLevel7  = (Byte)inStream.ReadByte();
            ListLevel8  = (Byte)inStream.ReadByte();
            ListLevel9  = (Byte)inStream.ReadByte();
            ListLevel10 = (Byte)inStream.ReadByte();
            inStream.Seek(2, SeekOrigin.Current);

            Byte pClass = (Byte)inStream.ReadByte();

            if (pClass > 3)
            {
                pClass = 0;
            }
            Class = (PlayerClass)pClass;

            Level      = (Byte)inStream.ReadByte();
            SpellPicks = (Byte)inStream.ReadByte();
            inStream.Seek(1, SeekOrigin.Current);
            Model = (Byte)inStream.ReadByte();
            inStream.Seek(3, SeekOrigin.Current);

            inStream.Read(expBuffer, 0, 4);
            Experience = NetHelper.FlipBytes(BitConverter.ToUInt32(expBuffer, 0));

            Byte[] kBuffer = new Byte[2];
            inStream.Read(kBuffer, 0, 2);
            SpellKey1 = NetHelper.FlipBytes(BitConverter.ToUInt16(kBuffer, 0));
            inStream.Read(kBuffer, 0, 2);
            SpellKey2 = NetHelper.FlipBytes(BitConverter.ToUInt16(kBuffer, 0));
            inStream.Read(kBuffer, 0, 2);
            SpellKey3 = NetHelper.FlipBytes(BitConverter.ToUInt16(kBuffer, 0));
            inStream.Read(kBuffer, 0, 2);
            SpellKey4 = NetHelper.FlipBytes(BitConverter.ToUInt16(kBuffer, 0));
            inStream.Read(kBuffer, 0, 2);
            SpellKey5 = NetHelper.FlipBytes(BitConverter.ToUInt16(kBuffer, 0));
            inStream.Read(kBuffer, 0, 2);
            SpellKey6 = NetHelper.FlipBytes(BitConverter.ToUInt16(kBuffer, 0));
            inStream.Read(kBuffer, 0, 2);
            SpellKey7 = NetHelper.FlipBytes(BitConverter.ToUInt16(kBuffer, 0));
            inStream.Read(kBuffer, 0, 2);
            SpellKey8 = NetHelper.FlipBytes(BitConverter.ToUInt16(kBuffer, 0));
            inStream.Read(kBuffer, 0, 2);
            SpellKey9 = NetHelper.FlipBytes(BitConverter.ToUInt16(kBuffer, 0));
            inStream.Read(kBuffer, 0, 2);
            SpellKey10 = NetHelper.FlipBytes(BitConverter.ToUInt16(kBuffer, 0));
            inStream.Read(kBuffer, 0, 2);
            SpellKey11 = BitConverter.ToUInt16(kBuffer, 0);
            inStream.Read(kBuffer, 0, 2);
            SpellKey12 = BitConverter.ToUInt16(kBuffer, 0);
            inStream.Seek(12, SeekOrigin.Current);

            OpLevel = (Byte)inStream.ReadByte();

            inStream.Read(expBuffer, 0, 4);
            PlayerFlags = (PlayerFlag)NetHelper.FlipBytes(BitConverter.ToUInt32(expBuffer, 0));

            SpellTrees = new SpellTreeCollection
            {
                new SpellTree(SpellManager.SpellTrees.FindById(List1), ListLevel1),
                new SpellTree(SpellManager.SpellTrees.FindById(List2), ListLevel2),
                new SpellTree(SpellManager.SpellTrees.FindById(List3), ListLevel3),
                new SpellTree(SpellManager.SpellTrees.FindById(List4), ListLevel4),
                new SpellTree(SpellManager.SpellTrees.FindById(List5), ListLevel5),
                new SpellTree(SpellManager.SpellTrees.FindById(List6), ListLevel6),
                new SpellTree(SpellManager.SpellTrees.FindById(List7), ListLevel7),
                new SpellTree(SpellManager.SpellTrees.FindById(List8), ListLevel8),
                new SpellTree(SpellManager.SpellTrees.FindById(List9), ListLevel9),
                new SpellTree(SpellManager.SpellTrees.FindById(List10), ListLevel10)
            };

            SpellTrees.RemoveAll(spellTrees => spellTrees.TreeSpells == null);
        }
Beispiel #27
0
        public Character(Player player, DataRow data)
        {
            LoadType     = LoadedType.Server;
            PendingFlags = PendingFlag.None;

            CharacterId          = data.Field <Int32>("charid");
            AccountId            = data.Field <Int32>("accountid");
            Slot                 = data.Field <Byte>("slot");
            Name                 = data.Field <String>("name");
            Agility              = data.Field <Byte>("agility");
            Constitution         = data.Field <Byte>("constitution");
            Memory               = data.Field <Byte>("memory");
            Reasoning            = data.Field <Byte>("reasoning");
            Discipline           = data.Field <Byte>("discipline");
            Empathy              = data.Field <Byte>("empathy");
            Intuition            = data.Field <Byte>("intuition");
            Presence             = data.Field <Byte>("presence");
            Quickness            = data.Field <Byte>("quickness");
            Strength             = data.Field <Byte>("strength");
            SpentStatPoints      = data.Field <UInt32>("spent_stat");
            BonusStatPoints      = data.Field <UInt32>("bonus_stat");
            BonusStatPointsSpent = data.Field <UInt32>("bonus_spent");
            List1                = data.Field <Byte>("list_1");
            List2                = data.Field <Byte>("list_2");
            List3                = data.Field <Byte>("list_3");
            List4                = data.Field <Byte>("list_4");
            List5                = data.Field <Byte>("list_5");
            List6                = data.Field <Byte>("list_6");
            List7                = data.Field <Byte>("list_7");
            List8                = data.Field <Byte>("list_8");
            List9                = data.Field <Byte>("list_9");
            List10               = data.Field <Byte>("list_10");
            ListLevel1           = data.Field <Byte>("list_level_1");
            ListLevel2           = data.Field <Byte>("list_level_2");
            ListLevel3           = data.Field <Byte>("list_level_3");
            ListLevel4           = data.Field <Byte>("list_level_4");
            ListLevel5           = data.Field <Byte>("list_level_5");
            ListLevel6           = data.Field <Byte>("list_level_6");
            ListLevel7           = data.Field <Byte>("list_level_7");
            ListLevel8           = data.Field <Byte>("list_level_8");
            ListLevel9           = data.Field <Byte>("list_level_9");
            ListLevel10          = data.Field <Byte>("list_level_10");
            Class                = (PlayerClass)data.Field <Byte>("class");
            Level                = data.Field <Byte>("level");
            SpellPicks           = data.Field <Byte>("spell_picks");
            Model                = data.Field <Byte>("model");
            Experience           = data.Field <UInt64>("experience");
            SpellKey1            = data.Field <UInt16>("spell_key_1");
            SpellKey2            = data.Field <UInt16>("spell_key_2");
            SpellKey3            = data.Field <UInt16>("spell_key_3");
            SpellKey4            = data.Field <UInt16>("spell_key_4");
            SpellKey5            = data.Field <UInt16>("spell_key_5");
            SpellKey6            = data.Field <UInt16>("spell_key_6");
            SpellKey7            = data.Field <UInt16>("spell_key_7");
            SpellKey8            = data.Field <UInt16>("spell_key_8");
            SpellKey9            = data.Field <UInt16>("spell_key_9");
            SpellKey10           = data.Field <UInt16>("spell_key_10");
            SpellKey11           = data.Field <UInt16>("spell_key_11");
            SpellKey12           = data.Field <UInt16>("spell_key_12");
            OpLevel              = data.Field <Byte>("oplevel");
            PlayerFlags          = (PlayerFlag)data.Field <UInt32>("flags");

            Statistics = new StatisticSheet(player, this);

            SpellTrees = new SpellTreeCollection
            {
                new SpellTree(SpellManager.SpellTrees.FindById(List1), ListLevel1),
                new SpellTree(SpellManager.SpellTrees.FindById(List2), ListLevel2),
                new SpellTree(SpellManager.SpellTrees.FindById(List3), ListLevel3),
                new SpellTree(SpellManager.SpellTrees.FindById(List4), ListLevel4),
                new SpellTree(SpellManager.SpellTrees.FindById(List5), ListLevel5),
                new SpellTree(SpellManager.SpellTrees.FindById(List6), ListLevel6),
                new SpellTree(SpellManager.SpellTrees.FindById(List7), ListLevel7),
                new SpellTree(SpellManager.SpellTrees.FindById(List8), ListLevel8),
                new SpellTree(SpellManager.SpellTrees.FindById(List9), ListLevel9),
                new SpellTree(SpellManager.SpellTrees.FindById(List10), ListLevel10)
            };

            SpellTrees.RemoveAll(spellTrees => spellTrees.TreeSpells == null);

            LoadMilestones();
        }
        /// <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);
        }
        /// <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));
        }
Beispiel #30
0
        private static int RunTarget()
        {
            StaticTarget target;
            var          ser = new DataContractJsonSerializer(typeof(StaticTarget));

            using (var memoryStream = new MemoryStream())
            {
                using (var writer = new StreamWriter(memoryStream, Encoding.Default, 1024 * 4, true))
                {
                    string s;
                    while ((s = Console.ReadLine()) != null)
                    {
                        writer.WriteLine(s);
                    }
                }

                memoryStream.Position = 0;
                target = (StaticTarget)ser.ReadObject(memoryStream);
            }

            foreach (StaticTarget.Task staticTask in target.Tasks)
            {
                Type type;
                if (staticTask.AssemblyFile != null)
                {
                    AssemblyName an = AssemblyName.GetAssemblyName(staticTask.AssemblyFile);
                    if (an == null)
                    {
                        Console.WriteLine("Caouldn't get assembly name for assembly file: " + staticTask.AssemblyFile);
                        return(1);
                    }
                    Assembly a = Assembly.Load(an);
                    if (a == null)
                    {
                        Console.WriteLine("Couldn't loaded assembly for assembly: " + an.FullName + " from file: " + staticTask.AssemblyFile);
                        return(1);
                    }
                    type = a.GetType(staticTask.Name.Split(',')[0]);
                    if (type == null)
                    {
                        Console.WriteLine("Couldn't create type for string: " + staticTask.Name.Split(',')[0] + " assembly file: " + (staticTask.AssemblyFile ?? "null") + " and assembly name: " + (staticTask.AssemblyName ?? "null"));
                        Console.WriteLine("Types in the assembly:\n" + string.Join(",\n", a.GetTypes().Select(availableType => availableType.FullName)));
                        return(1);
                    }
                }
                else
                {
                    type = Type.GetType(staticTask.Name);
                    if (type == null)
                    {
                        Console.WriteLine("Couldn't create type for string: " + staticTask.Name + " assembly file: " + (staticTask.AssemblyFile ?? "null") + " and assembly name: " + (staticTask.AssemblyName ?? "null"));
                        return(1);
                    }
                }

                var assemblyLoadInfo = AssemblyLoadInfo.Create(assemblyFile: staticTask.AssemblyFile, assemblyName: staticTask.AssemblyName);
                if (assemblyLoadInfo == null)
                {
                    Console.WriteLine("Couldn't create type for assembly file: " + (staticTask.AssemblyFile ?? "null") + " and name: " + (staticTask.AssemblyName ?? "null"));
                    return(1);
                }

                LoadedType         loadedType     = new LoadedType(type, assemblyLoadInfo, null);
                TaskPropertyInfo[] taskProperties = AssemblyTaskFactory.GetTaskParameters(loadedType);

                ITask task = TaskLoader.CreateTask(loadedType, staticTask.Name, staticTask.AssemblyName, 0, 0, null

#if FEATURE_APPDOMAIN
                                                   , null
#endif
                                                   , false
#if FEATURE_APPDOMAIN
                                                   , out var appDomain
#endif
                                                   );
                foreach (var parameter in staticTask.Parameters)
                {
                    var taskPropertyInfo = taskProperties.FirstOrDefault(property => property.Name == parameter.Key);
                    if (taskPropertyInfo == null)
                    {
                        Console.Error.WriteLine("Could not find property: \"" + parameter.Key + "\" for task + \"" + staticTask.Name + "\"");
                        return(1);
                    }

                    StaticTarget.Task.ParameterType parameterType = parameter.Value.ParameterType;
                    switch (parameterType)
                    {
                    case StaticTarget.Task.ParameterType.Primitive:
                        object value = GetTypedValue(parameter.Value.Primitive.Type, parameter.Value.Primitive.Value);
                        TaskFactoryWrapper.SetPropertyValue(task, taskPropertyInfo, value);
                        break;

                    case StaticTarget.Task.ParameterType.Primitives:
                        var values = GetTypedArrayValue(parameter.Value.Primitives.Type, parameter.Value.Primitives.Values);
                        TaskFactoryWrapper.SetPropertyValue(task, taskPropertyInfo, values);
                        break;

                    case StaticTarget.Task.ParameterType.TaskItem:
                        TaskFactoryWrapper.SetPropertyValue(task, taskPropertyInfo, new TaskItem(parameter.Value.TaskItem.ItemSpec, parameter.Value.TaskItem.Metadata));
                        break;

                    case StaticTarget.Task.ParameterType.TaskItems:
                        ITaskItem[] taskItems = parameter.Value.TaskItems.Select(taskItem => new TaskItem(taskItem.ItemSpec, taskItem.Metadata)).ToArray();
                        TaskFactoryWrapper.SetPropertyValue(task, taskPropertyInfo, taskItems);
                        break;
                    }
                }


                task.BuildEngine = new SimpleBuildEngine();
                try
                {
                    // MSBuild ignores this return value :(
                    task.Execute();
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("TASK ERROR: " + e);
                    return(1);
                }
            }

            return(0);
        }