Exemplo n.º 1
0
        /// <summary>
        /// used for testing. Will load snippets of xml into the task generator
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static TaskParser LoadAndParse(string s, string desiredRule)
        {
            TaskParser tp = new TaskParser();

            tp.Parse(s.Replace("`", "\""), desiredRule);
            return(tp);
        }
Exemplo n.º 2
0
        public void TestLoadAndParseFromAbsoluteFilePath()
        {
            string xmlContents = @"<ProjectSchemaDefinitions xmlns=`clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework` xmlns:x=`http://schemas.microsoft.com/winfx/2006/xaml` xmlns:sys=`clr-namespace:System;assembly=mscorlib` xmlns:impl=`clr-namespace:Microsoft.VisualStudio.Project.Contracts.Implementation;assembly=Microsoft.VisualStudio.Project.Contracts.Implementation`>
                                     <Rule Name=`CL`>
                                       <StringProperty Name=`TargetAssembly` Switch=`/target:&quot;[value]&quot;` />
                                     </Rule>
                                   </ProjectSchemaDefinitions>";
            string tmpXamlFile = FileUtilities.GetTemporaryFile();

            try
            {
                File.WriteAllText(tmpXamlFile, xmlContents.Replace("`", "\""));
                TaskParser tp = new TaskParser();
                tp.Parse(tmpXamlFile, "CL");

                LinkedList <Property> properties = tp.Properties;

                Assert.Single(properties);              // "Expected one property but there were " + properties.Count
                Assert.NotNull(properties.First.Value); // "TargetAssembly switch should exist"
                Assert.Equal("TargetAssembly", properties.First.Value.Name);
                Assert.Equal(PropertyType.String, properties.First.Value.Type);
                Assert.Equal("/target:\"[value]\"", properties.First.Value.SwitchName);
            }
            finally
            {
                // This throws because the file is still in use!
                //if (File.Exists(tmpXamlFile))
                //    File.Delete(tmpXamlFile);
            }
        }
Exemplo n.º 3
0
        public void Parse_SerializedTaskNull_Exception()
        {
            // Arrange.
            var parser = new TaskParser();

            // Act and assert.
            parser.Parse(null);
        }
Exemplo n.º 4
0
 public void TestLoadXml()
 {
     TaskParser tp = new TaskParser();
     string s = @"<ProjectSchemaDefinitions xmlns=`clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework` xmlns:x=`http://schemas.microsoft.com/winfx/2006/xaml` xmlns:sys=`clr-namespace:System;assembly=mscorlib` xmlns:impl=`clr-namespace:Microsoft.VisualStudio.Project.Contracts.Implementation;assembly=Microsoft.VisualStudio.Project.Contracts.Implementation`>
                    <Rule Name=`TaskGeneratorLoadTest`>
                      <BoolProperty Name=`TestProperty1` Switch=`tp` />
                    </Rule>
                  </ProjectSchemaDefinitions>";
     Assert.True(tp.Parse(s.Replace("`", "\""), "TaskGeneratorLoadTest")); // "File failed to load correctly."
 }
Exemplo n.º 5
0
        public void Parse_SerializedTaskWhiteSpace_Null()
        {
            // Arrange.
            var parser = new TaskParser();

            // Act.
            var res = parser.Parse(" ");

            // Assert.
            Assert.IsNull(res);
        }
Exemplo n.º 6
0
        public void Parse_SerializedTaskEmpty_Exception()
        {
            // Arrange.
            var parser = new TaskParser();

            // Act.
            var res = parser.Parse("");

            // Assert.
            Assert.IsNull(res);
        }
Exemplo n.º 7
0
        public void ParseTask()
        {
            string input = @"
                $dim: 3;
                $parameters:
                    double[] a = new double[] { 2.0, 1.0 };
                $function:
                    x[0] * x[0] + a[0] * x[1] + a[1] * x[2];
                $constraints:
                    x[0] <= 100.0;
                    x[1] >= a[0];
                    x[2] >= a[1];
            ";

            Task task = parser.Parse(input);

            Assert.AreEqual(3, task.Dim);
            Assert.AreEqual(4.0 + 2.0 * 3.0 + 1.0 * 4.0, task.Cost.Function(makePoint(2.0, 3.0, 4.0)));
            Assert.AreEqual(3, task.Constraints.Count);
        }
Exemplo n.º 8
0
        public override void update(GameTime time)
        {
            string text = _textBox.Text;

            if (_previousText != text)
            {
                _previousText = text;
                _taskParser.Parse(text);
            }

            if (!_textBox.Selected && !Game1.options.SnappyMenus)
            {
                _textBox.SelectMe();
            }
        }
Exemplo n.º 9
0
        private void UpdateParameter()
        {
            TaskParser.Parse(Text);

            if (!TaskParser.SetParameterValue(TaskParameter))
            {
                if (TaskParameter.Type == typeof(string))
                {
                    TaskParameter.Value = Text.Trim();
                }
                else if (TaskParameter.Type == typeof(int) && int.TryParse(Text.Trim(), out int num))
                {
                    TaskParameter.Value = num;
                }
                else
                {
                    TaskParameter.Value = null;
                }
            }
        }
Exemplo n.º 10
0
        public void ParsingTest()
        {
            var samples = new Dictionary <string, DraftTask>();

            samples.Add(
                "A crazy sample task name with simple text",
                new DraftTask()
            {
                Description = "A crazy sample task name with simple text"
            }
                );

            samples.Add(
                "A task due today on: today",
                new DraftTask()
            {
                Description = "A task due today", Due = DateTime.Now.Date
            }
                );

            samples.Add(
                "A task due today in personal on: today in: personal",
                new DraftTask()
            {
                Description = "A task due today in personal",
                Due         = DateTime.Now.Date,
                FolderName  = "personal"
            });

            foreach (var pair in samples)
            {
                var task = TaskParser.Parse(pair.Key);
                Assert.IsTrue(
                    TestUtil.EditTaskEquals(pair.Value, task),
                    string.Format("Had issues with '{0}'", pair.Key));
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// MSBuild engine will call this to initialize the factory. This should initialize the factory enough so that the factory can be asked
        ///  whether or not task names can be created by the factory.
        /// </summary>
        public bool Initialize(string taskName, IDictionary <string, TaskPropertyInfo> taskParameters, string taskElementContents, IBuildEngine taskFactoryLoggingHost)
        {
            ErrorUtilities.VerifyThrowArgumentNull(taskName, nameof(taskName));
            ErrorUtilities.VerifyThrowArgumentNull(taskParameters, nameof(taskParameters));

            var log = new TaskLoggingHelper(taskFactoryLoggingHost, taskName)
            {
                TaskResources     = AssemblyResources.PrimaryResources,
                HelpKeywordPrefix = "MSBuild."
            };

            if (taskElementContents == null)
            {
                log.LogErrorWithCodeFromResources("Xaml.MissingTaskBody");
                return(false);
            }

            TaskElementContents = taskElementContents.Trim();

            // Attempt to load the task
            TaskParser parser = new TaskParser();

            bool parseSuccessful = parser.Parse(TaskElementContents, taskName);

            TaskName      = parser.GeneratedTaskName;
            TaskNamespace = parser.Namespace;
            var generator = new TaskGenerator(parser);

            CodeCompileUnit dom = generator.GenerateCode();

            string pathToMSBuildBinaries = ToolLocationHelper.GetPathToBuildTools(ToolLocationHelper.CurrentToolsVersion);

            // create the code generator options
            // Since we are running msbuild 12.0 these had better load.
            var compilerParameters = new CompilerParameters
                                     (
                new[]
            {
                "System.dll",
                Path.Combine(pathToMSBuildBinaries, "Microsoft.Build.Framework.dll"),
                Path.Combine(pathToMSBuildBinaries, "Microsoft.Build.Utilities.Core.dll"),
                Path.Combine(pathToMSBuildBinaries, "Microsoft.Build.Tasks.Core.dll")
            }
                                     )
            {
                GenerateInMemory      = true,
                TreatWarningsAsErrors = false
            };

            // create the code provider
            var             codegenerator = CodeDomProvider.CreateProvider("cs");
            CompilerResults results;
            bool            debugXamlTask = Environment.GetEnvironmentVariable("MSBUILDWRITEXAMLTASK") == "1";

            if (debugXamlTask)
            {
                using (var outputWriter = new StreamWriter(taskName + "_XamlTask.cs"))
                {
                    var options = new CodeGeneratorOptions
                    {
                        BlankLinesBetweenMembers = true,
                        BracingStyle             = "C"
                    };

                    codegenerator.GenerateCodeFromCompileUnit(dom, outputWriter, options);
                }

                results = codegenerator.CompileAssemblyFromFile(compilerParameters, taskName + "_XamlTask.cs");
            }
            else
            {
                results = codegenerator.CompileAssemblyFromDom(compilerParameters, dom);
            }

            try
            {
                _taskAssembly = results.CompiledAssembly;
            }
            catch (FileNotFoundException)
            {
                // This occurs if there is a failure to compile the assembly.  We just pass through because we will take care of the failure below.
            }

            if (_taskAssembly == null)
            {
                var errorList = new StringBuilder();
                errorList.AppendLine();
                foreach (CompilerError error in results.Errors)
                {
                    if (error.IsWarning)
                    {
                        continue;
                    }

                    if (debugXamlTask)
                    {
                        errorList.AppendFormat(Thread.CurrentThread.CurrentUICulture, "({0},{1}) {2}", error.Line, error.Column, error.ErrorText).AppendLine();
                    }
                    else
                    {
                        errorList.AppendLine(error.ErrorText);
                    }
                }

                log.LogErrorWithCodeFromResources("Xaml.TaskCreationFailed", errorList.ToString());
            }

            return(!log.HasLoggedErrors);
        }
Exemplo n.º 12
0
        public bool Initialize(string taskName, IDictionary <string, TaskPropertyInfo> taskParameters, string taskElementContents, IBuildEngine taskFactoryLoggingHost)
        {
            CompilerResults results;

            Microsoft.Build.Shared.ErrorUtilities.VerifyThrowArgumentNull(taskName, "taskName");
            Microsoft.Build.Shared.ErrorUtilities.VerifyThrowArgumentNull(taskParameters, "taskParameters");
            TaskLoggingHelper helper = new TaskLoggingHelper(taskFactoryLoggingHost, taskName)
            {
                TaskResources     = Microsoft.Build.Shared.AssemblyResources.PrimaryResources,
                HelpKeywordPrefix = "MSBuild."
            };

            if (taskElementContents == null)
            {
                helper.LogErrorWithCodeFromResources("Xaml.MissingTaskBody", new object[0]);
                return(false);
            }
            this.TaskElementContents = taskElementContents.Trim();
            TaskParser parser = new TaskParser();

            parser.Parse(this.TaskElementContents, taskName);
            this.TaskName      = parser.GeneratedTaskName;
            this.TaskNamespace = parser.Namespace;
            CodeCompileUnit    compileUnit = new TaskGenerator(parser).GenerateCode();
            Assembly           assembly    = Assembly.LoadWithPartialName("System");
            Assembly           assembly2   = Assembly.LoadWithPartialName("Microsoft.Build.Framework");
            Assembly           assembly3   = Assembly.LoadWithPartialName("Microsoft.Build.Utilities.V4.0");
            Assembly           assembly4   = Assembly.LoadWithPartialName("Microsoft.Build.Tasks.V4.0");
            CompilerParameters parameters  = new CompilerParameters(new string[] { assembly.Location, assembly2.Location, assembly3.Location, assembly4.Location })
            {
                GenerateInMemory      = true,
                TreatWarningsAsErrors = false
            };
            CodeDomProvider provider = CodeDomProvider.CreateProvider("cs");
            bool            flag     = Environment.GetEnvironmentVariable("MSBUILDWRITEXAMLTASK") == "1";

            if (flag)
            {
                using (StreamWriter writer = new StreamWriter(taskName + "_XamlTask.cs"))
                {
                    CodeGeneratorOptions options = new CodeGeneratorOptions {
                        BlankLinesBetweenMembers = true,
                        BracingStyle             = "C"
                    };
                    provider.GenerateCodeFromCompileUnit(compileUnit, writer, options);
                }
                results = provider.CompileAssemblyFromFile(parameters, new string[] { taskName + "_XamlTask.cs" });
            }
            else
            {
                results = provider.CompileAssemblyFromDom(parameters, new CodeCompileUnit[] { compileUnit });
            }
            try
            {
                this.taskAssembly = results.CompiledAssembly;
            }
            catch (FileNotFoundException)
            {
            }
            if (this.taskAssembly == null)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendLine();
                foreach (CompilerError error in results.Errors)
                {
                    if (!error.IsWarning)
                    {
                        if (flag)
                        {
                            builder.AppendLine(string.Format(Thread.CurrentThread.CurrentUICulture, "({0},{1}) {2}", new object[] { error.Line, error.Column, error.ErrorText }));
                        }
                        else
                        {
                            builder.AppendLine(error.ErrorText);
                        }
                    }
                }
                helper.LogErrorWithCodeFromResources("Xaml.TaskCreationFailed", new object[] { builder.ToString() });
            }
            return(!helper.HasLoggedErrors);
        }