Пример #1
0
        public void TestBasicStringArrayProperty()
        {
            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`>
                                       <StringListProperty Name=`TargetAssembly` Switch=`/target:&quot;[value]&quot;` Separator=`;` />
                                     </Rule>
                                   </ProjectSchemaDefinitions>";
            TaskParser tp          = XamlTestHelpers.LoadAndParse(xmlContents, "CL");

            LinkedList <Property> properties = tp.Properties;

            Assert.AreEqual(1, properties.Count, "Expected one property but there were " + properties.Count);
            Assert.IsNotNull(properties.First.Value, "TargetAssembly switch should exist");
            Assert.AreEqual("TargetAssembly", properties.First.Value.Name);
            Assert.AreEqual(PropertyType.StringArray, properties.First.Value.Type);
            Assert.AreEqual("/target:\"[value]\"", properties.First.Value.SwitchName);
            Assert.AreEqual(";", properties.First.Value.Separator);
        }
Пример #2
0
        public StateMachine()
        {
            this.reader  = null;
            this.astRoot = null;
            if (RemoteTask.FileExist(Settings.TaskFile))
            {
                this.reader = RemoteTask.GetFile(Settings.TaskFile);
            }
            else
            {
                MessageBox.Show(string.Format("Your selected task file wasn't found:\n{0}", Settings.TaskFile));
                this.StopAll("");
            }

            if (this.reader != null)
            {
                this.pproc      = new Preprocessor(this.reader);
                this.taskParser = new TaskParser(new StreamReader(this.pproc.ProcessedStream));
                this.astRoot    = this.taskParser.ParseTask(null);
                this.reader.Close();
            }
            else
            {
                this.StopAll("TextReader was null. File not found?");
            }
            this.root = new RootNode();
            this.root.AddTask(this.astRoot);
            this.root.BindSymbols(); // Just to make it a tad faster

            this.taskQueue     = new Stack <Task>();
            this.activityQueue = new Stack <Activity>();
            this.rootTask      = TaskCreator.CreateTaskFromNode(this.root, null);
            if (this.rootTask == null)
            {
                this.StopAll("No root task");
            }
            TaskInfo.Root = this.rootTask;
            TaskCreator.CreateTreeFromTasks(this.rootTask);
            this.activity         = null;
            this.taskTimer        = new GTimer(300); //300
            this.nothingToDoTimer = new GTimer(3 * 1000);
            this.tick             = new GTimer(100);
        }
Пример #3
0
        public void ValidTaskParsed()
        {
            // Arrange.
            const string taskName       = "Task #1";
            const string serializedTask = "[ ] " + taskName;
            var          parser         = new TaskParser();
            var          store          = new MemoryTaskStore();
            var          factory        = new TaskFactory(parser, store);

            // Act.
            var task = factory.Create(new DateTime(), serializedTask);

            // Assert.
            Assert.IsNotNull(task);
            var tasks = store.Tasks;

            Assert.AreEqual(1, tasks.Count());
            Assert.AreEqual(taskName, tasks.First().Name);
        }
Пример #4
0
        public void GlobalSetup()
        {
            // prepare some functions
            AllSections sections = new AllSections()
            {
                DimensionSection  = new DimensionSection(),
                ParametersSection = new ParametersSection()
                {
                    Content = ""
                },
                CostFunctionSection = new CostFunctionSection(),
                ConstraintsSection  = new ConstraintsSection()
            };

            TaskParser parser = new TaskParser();

            sections.DimensionSection.Dim         = 1;
            sections.CostFunctionSection.Function = "pow2(x[0]) + 10";
            funcRank1Simple = parser.compileCostFunction(sections).Function;

            sections.DimensionSection.Dim         = 4;
            sections.CostFunctionSection.Function = "x[0] + x[1] + x[2] + x[3]";
            funcRank4Simple = parser.compileCostFunction(sections).Function;

            sections.DimensionSection.Dim         = 1;
            sections.CostFunctionSection.Function = "sin(x[0]) * exp(x[0]) + ln(x[0]) * x[0]";
            funcRank1Complex = parser.compileCostFunction(sections).Function;

            sections.DimensionSection.Dim         = 4;
            sections.CostFunctionSection.Function = "sin(x[0]) * exp(x[1]) + ln(x[2]) * x[3]";
            funcRank4Complex = parser.compileCostFunction(sections).Function;


            Random r = new Random();

            x0 = r.NextDouble();
            x1 = r.NextDouble();
            x2 = r.NextDouble();
            x3 = r.NextDouble();

            point = new DenseVector(new double[] { x0, x1, x2, x3 });
        }
Пример #5
0
        public void TestBasicNonReversibleBooleanSwitch_WithDefault()
        {
            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`>
                                       <BoolProperty Name=`SuppressStartupBanner` Switch=`nologo` Default=`true` />
                                     </Rule>
                                   </ProjectSchemaDefinitions>";
            TaskParser tp          = XamlTestHelpers.LoadAndParse(xmlContents, "CL");

            LinkedList <Property> properties = tp.Properties;

            Assert.Single(properties);              // "Expected one property but there were " + properties.Count
            Assert.NotNull(properties.First.Value); // "SuppressStartupBanner switch should exist"
            Assert.Equal("SuppressStartupBanner", properties.First.Value.Name);
            Assert.Equal("nologo", properties.First.Value.SwitchName);
            Assert.Null(properties.First.Value.ReverseSwitchName);         // "SuppressStartupBanner shouldn't have a reverse switch value"
            Assert.Equal(String.Empty, properties.First.Value.Reversible); // "Switch should NOT be marked as reversible"
            Assert.Equal("true", properties.First.Value.DefaultValue);     // "Switch should default to true"
            Assert.Equal(PropertyType.Boolean, properties.First.Value.Type);
        }
Пример #6
0
        public void TestParseIncorrect_NoMatchingRule()
        {
            bool exceptionCaught = false;

            try
            {
                string     incorrectXmlContents = @"<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>";
                TaskParser tp = XamlTestHelpers.LoadAndParse(incorrectXmlContents, "CL");
            }
            catch (XamlParseException)
            {
                exceptionCaught = true;
            }

            Assert.True(exceptionCaught); // "Should have caught a XamlParseException"
        }
Пример #7
0
        public void TestBasicNonReversibleBooleanSwitch()
        {
            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`>
                                       <BoolProperty Name=`KeepComments` Switch=`C` />
                                     </Rule>
                                   </ProjectSchemaDefinitions>";
            TaskParser tp          = XamlTestHelpers.LoadAndParse(xmlContents, "CL");

            LinkedList <Property> properties = tp.Properties;

            Assert.AreEqual(1, properties.Count, "Expected one property but there were " + properties.Count);
            Assert.IsNotNull(properties.First.Value, "KeepComments switch should exist");
            Assert.AreEqual("KeepComments", properties.First.Value.Name);
            Assert.AreEqual("C", properties.First.Value.SwitchName);
            Assert.IsNull(properties.First.Value.ReverseSwitchName, "KeepComments shouldn't have a reverse switch value");
            Assert.AreEqual(String.Empty, properties.First.Value.Reversible, "Switch should NOT marked as reversible");
            Assert.AreEqual(String.Empty, properties.First.Value.DefaultValue, "Switch should NOT have a default value");
            Assert.AreEqual(PropertyType.Boolean, properties.First.Value.Type);
        }
Пример #8
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;
                }
            }
        }
Пример #9
0
        public void TestBasicEnumProperty()
        {
            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`>
                                       <EnumProperty Name=`GeneratePreprocessedFile` Switch=`nologo`>
                                         <EnumValue Name=`Disabled` />
                                         <EnumValue Name=`Yes` Switch=`P` />
                                         <EnumValue Name=`NoLineNumbers` Switch=`EP` />
                                       </EnumProperty>
                                     </Rule>
                                   </ProjectSchemaDefinitions>";
            TaskParser tp          = XamlTestHelpers.LoadAndParse(xmlContents, "CL");

            LinkedList <Property> properties = tp.Properties;

            Assert.Single(properties);                                      // "Expected one property but there were " + properties.Count
            Assert.NotNull(properties.First.Value);                         // "GeneratePreprocessedFile switch should exist"
            Assert.Equal("GeneratePreprocessedFile", properties.First.Value.Name);
            Assert.Equal(PropertyType.String, properties.First.Value.Type); // Enum properties are represented as string types
            Assert.Equal(3, properties.First.Value.Values.Count);           // "GeneratePreprocessedFile should have three values"
        }
Пример #10
0
        public void TestStringArrayPropertyWithDataSource_DataSourceIsItem()
        {
            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`>
                                       <StringListProperty Name=`TargetAssembly` Switch=`/target:&quot;[value]&quot;` Separator=`;`>
                                         <StringListProperty.DataSource>
                                           <DataSource SourceType=`Item` Persistence=`ProjectFile` ItemType=`AssemblyName` />
                                         </StringListProperty.DataSource>
                                       </StringListProperty>
                                     </Rule>
                                   </ProjectSchemaDefinitions>";
            TaskParser tp          = XamlTestHelpers.LoadAndParse(xmlContents, "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.ItemArray, properties.First.Value.Type); // Although it's a String array property, DataSource.SourceType overrides that
            Assert.Equal("/target:\"[value]\"", properties.First.Value.SwitchName);
            Assert.Equal(";", properties.First.Value.Separator);
        }
Пример #11
0
        public void Setup()
        {
            ILogger <TaskParser> log = loggerFactory.CreateLogger <TaskParser>();

            parser = new TaskParser(log,
                                    (string userName, ILogger logger) =>
            {
                User user;
                if (!users.TryGetValue(userName, out user))
                {
                    logger.LogDebug("User not found: Creating user with name {userName}", userName);
                    user = new User()
                    {
                        ID    = ++userIdCounter,
                        Name  = userName,
                        Tasks = new List <UserTaskMap>()
                    };
                    users.Add(userName, user);
                }
                else
                {
                    logger.LogDebug("Found User with username {username}", userName);
                }
                return(user);
            },
                                    (User owner, IEnumerable <User> assignees, string taskDescription, ILogger logger, DateTime? dueDate) =>
            {
                logger.LogDebug("{username} added new task for {assignees}", owner.Name, assignees.Select(u => u.Name).Aggregate((a, b) => a + ", " + b));
                tasks.Add(new Task()
                {
                    CreationDate = DateTime.Now,
                    DueDate      = dueDate ?? default,
                    ID           = 1,
                    Title        = taskDescription,
                    Initiator    = owner,
                    InitiatorID  = owner.ID
                });
                return(tasks.Last());
            });
Пример #12
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));
            }
        }
Пример #13
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);
        }
Пример #14
0
        public void DateSeparatedTest()
        {
            string     parsedText = null;
            DateTime   dateTime   = DateTime.MinValue;
            TaskParser parser     = TaskParser.Instance;

            DateTime expected = GetMonthDate(11, 12);

            Assert.IsTrue(parser.TryParse("Something 11/12",               // as in Monday
                                          out parsedText,
                                          out dateTime),
                          "#0");
            Assert.AreEqual("Something", parsedText, "#1");
            Assert.AreEqual(expected.Year, dateTime.Year, "#2");
            Assert.AreEqual(expected.Month, dateTime.Month, "#3");
            Assert.AreEqual(expected.Day, dateTime.Day, "#4");
            dateTime = DateTime.MinValue;

            expected = GetMonthDate(3, 11);
            Assert.IsTrue(parser.TryParse("Something 3-11",
                                          out parsedText,
                                          out dateTime),
                          "#5");
            Assert.AreEqual("Something", parsedText, "#6");
            Assert.AreEqual(expected.Year, dateTime.Year, "#7");
            Assert.AreEqual(expected.Month, dateTime.Month, "#8");
            Assert.AreEqual(expected.Day, dateTime.Day, "#9");
            dateTime = DateTime.MinValue;

            expected = new DateTime(DateTime.Now.Year + 1, 1, 22);
            Assert.IsTrue(parser.TryParse(string.Format("Something 1/22/{0}",
                                                        DateTime.Now.Year + 1),
                                          out parsedText,
                                          out dateTime),
                          "#10");
            Assert.AreEqual("Something", parsedText, "#11");
            Assert.AreEqual(expected.Year, dateTime.Year, "#12");
            Assert.AreEqual(expected.Month, dateTime.Month, "#13");
            Assert.AreEqual(expected.Day, dateTime.Day, "#14");
            dateTime = DateTime.MinValue;

            expected = new DateTime(2011, 11, 11);
            Assert.IsTrue(parser.TryParse("Something 11-11-11 soon!",
                                          out parsedText,
                                          out dateTime),
                          "#15");
            Assert.AreEqual("Something soon!", parsedText, "#16");
            Assert.AreEqual(expected.Year, dateTime.Year, "#17");
            Assert.AreEqual(expected.Month, dateTime.Month, "#18");
            Assert.AreEqual(expected.Day, dateTime.Day, "#19");
            dateTime = DateTime.MinValue;

            // The year doesn't make sense, but is still valid
            expected = new DateTime(102, 1, 13);
            Assert.IsTrue(parser.TryParse("Something 1-13-102 soon!!",
                                          out parsedText,
                                          out dateTime),
                          "#20");
            Assert.AreEqual("Something soon!!", parsedText, "#21");
            Assert.AreEqual(expected.Year, dateTime.Year, "#22");
            Assert.AreEqual(expected.Month, dateTime.Month, "#23");
            Assert.AreEqual(expected.Day, dateTime.Day, "#24");
            dateTime = DateTime.MinValue;

            // Matches "11/11"
            expected = GetMonthDate(11, 11);
            Assert.IsTrue(parser.TryParse("Buy beer 11/11/3 for party",
                                          out parsedText,
                                          out dateTime),
                          "#25");
            Assert.AreEqual("Buy beer/3 for party", parsedText, "#26");
            Assert.AreEqual(expected.Year, dateTime.Year, "#27");
            Assert.AreEqual(expected.Month, dateTime.Month, "#28");
            Assert.AreEqual(expected.Day, dateTime.Day, "#29");
        }
Пример #15
0
        public void DateTest()
        {
            string     parsedText = null;
            DateTime   dateTime   = DateTime.MinValue;
            TaskParser parser     = TaskParser.Instance;

            DateTime expected = GetMonthDate(12, 1);

            Assert.IsTrue(parser.TryParse("Something due by December 1st",
                                          out parsedText,
                                          out dateTime));
            Assert.AreEqual("Something", parsedText, "#0");
            Assert.AreEqual(expected.Year, dateTime.Year, "#1");
            Assert.AreEqual(expected.Month, dateTime.Month, "#2");
            Assert.AreEqual(expected.Day, dateTime.Day, "#3");
            dateTime = DateTime.MinValue;

            expected = GetMonthDate(12, 1);
            Assert.IsTrue(parser.TryParse("Something due Dec 1",
                                          out parsedText,
                                          out dateTime));
            Assert.AreEqual("Something", parsedText, "#4");
            Assert.AreEqual(expected.Year, dateTime.Year, "#5");
            Assert.AreEqual(expected.Month, dateTime.Month, "#6");
            Assert.AreEqual(expected.Day, dateTime.Day, "#7");
            dateTime = DateTime.MinValue;

            expected = GetMonthDate(12, -1);
            Assert.IsTrue(parser.TryParse("Something due before December",
                                          out parsedText,
                                          out dateTime));
            Assert.AreEqual("Something", parsedText, "#8");
            Assert.AreEqual(expected.Year, dateTime.Year, "#9");
            Assert.AreEqual(expected.Month, dateTime.Month, "#10");
            Assert.AreEqual(expected.Day, dateTime.Day, "#11");
            dateTime = DateTime.MinValue;

            expected = GetMonthDate(-1, 15);
            Assert.IsTrue(parser.TryParse("Something due by 15th",
                                          out parsedText,
                                          out dateTime));
            Assert.AreEqual("Something", parsedText, "#12");
            Assert.AreEqual(expected.Year, dateTime.Year, "#13");
            Assert.AreEqual(expected.Month, dateTime.Month, "#14");
            Assert.AreEqual(expected.Day, dateTime.Day, "#15");
            dateTime = DateTime.MinValue;

            // Invalid date, it should be 15th, but we accept it
            expected = GetMonthDate(-1, 15);
            Assert.IsTrue(parser.TryParse("Something important due by 15nd",
                                          out parsedText,
                                          out dateTime),
                          "#16");
            Assert.AreEqual("Something important", parsedText, "#17");
            Assert.AreEqual(expected.Year, dateTime.Year, "#18");
            Assert.AreEqual(expected.Month, dateTime.Month, "#19");
            Assert.AreEqual(expected.Day, dateTime.Day, "#20");

            expected = GetMonthDate(3, 15);
            Assert.IsTrue(parser.TryParse("Something important March 15th",
                                          out parsedText,
                                          out dateTime),
                          "#21");
            Assert.AreEqual("Something important", parsedText, "#22");
            Assert.AreEqual(expected.Year, dateTime.Year, "#23");
            Assert.AreEqual(expected.Month, dateTime.Month, "#24");
            Assert.AreEqual(expected.Day, dateTime.Day, "#25");

            expected = GetMonthDate(DateTime.Now.Month, 2);
            Assert.IsTrue(parser.TryParse(string.Format("Something important {0} 2nd",
                                                        expected.ToString("MMMM")),
                                          out parsedText,
                                          out dateTime),
                          "#26");
            Assert.AreEqual("Something important", parsedText, "#27");
            Assert.AreEqual(expected.Year, dateTime.Year, "#28");
            Assert.AreEqual(expected.Month, dateTime.Month, "#29");
            Assert.AreEqual(expected.Day, dateTime.Day, "#30");
        }
Пример #16
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);
        }
Пример #17
0
        static void ServerEvent(object pObject)
        {
            if (pObject.GetType() == typeof(SocketEventArgs))
            {
                SocketEventArgs pSocketEvent = (SocketEventArgs)pObject;
                #region
                if (pSocketEvent.Link)
                {
                    Console.Write("※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※");
                    Console.WriteLine("Client [{0}] Connected!", pSocketEvent.Connection.SocketEndPoint.Address.ToString());
                }
                else
                {
                    string        strProcParams = "SP_VERIFY_LOGOUT";
                    DbParameter[] paramCache    = DataUtilities.GetParameters(strProcParams);

                    if (paramCache == null)
                    {
                        paramCache = new SqlParameter[] {
                            new SqlParameter("@strSession", SqlDbType.VarChar, 50)
                        };
                        DataUtilities.SetParameters(strProcParams, paramCache);
                    }

                    paramCache[0].Value = pSocketEvent.Connection.Session;

                    MSSQLOperate pLogout = new MSSQLOperate(strAnalyse);
                    pLogout.Connect(false);
                    pLogout.ExecuteQuery(false, strProcParams, paramCache);
                    pLogout.GetResult(RecordStyle.NONE);

                    Console.WriteLine("Client [{0}, {1}] Disconnected!", pSocketEvent.Connection.SocketEndPoint.Address.ToString(), pSocketEvent.Connection.Session);

                    if (null != pSocketEvent.SocketException)
                    {
                        Console.WriteLine("Socket Exception : {0}", pSocketEvent.SocketException.Message);
                    }

                    Console.Write("※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※");
                }
                #endregion
                ((SocketEventArgs)pObject).Connection.OnRecive();
            }
            else if (pObject.GetType() == typeof(MessageEventArgs))
            {
                DateTime tStartTime = DateTime.Now;

                TaskParser pTaskParser = new TaskParser(pNotesSession, (MessageEventArgs)pObject, strAnalyse, strOnline, strAccess);

                if (!pTaskParser.Parser())
                {
                    Console.WriteLine(pTaskParser.Error);
                }

                pTaskParser.Dispose();

                #region 发送/保存消息

                /*TaskService pMessageID = pTaskParser.SocketMessage;
                 *
                 * MSSQLOperate pMessageADO = new MSSQLOperate(strMessage);
                 *
                 * if (pMessageADO.Connect(false))
                 * {
                 *  string strProcParams = "SP_SEND_INSTANTMESSAGE";
                 *  DbParameter[] paramCache = DataUtilities.GetParameters(strProcParams);
                 *
                 *  if (paramCache == null)
                 *  {
                 *      paramCache = new SqlParameter[]{
                 *                                 new SqlParameter("@strCommand",SqlDbType.VarChar, 50),
                 *                                 new SqlParameter("@strSession",SqlDbType.VarChar, 50)
                 *                             };
                 *      DataUtilities.SetParameters(strProcParams, paramCache);
                 *  }
                 *
                 *  paramCache[0].Value = pMessageID.ToString();
                 *  paramCache[1].Value = ((MessageEventArgs)pObject).Connection.Session;
                 *
                 *  pMessageADO.ExecuteQuery(false, strProcParams, paramCache);
                 *  pMessageADO.GetResult(RecordStyle.DATASET);
                 *  DataSet pMessageData = (DataSet)pMessageADO.RecordData;
                 *
                 *  if (pMessageADO.AffectRow > 0)
                 *  {
                 *      for (int i = 0; i < pMessageData.Tables[0].Rows.Count; i++)
                 *      {
                 *          if (pMessageData.Tables[0].Rows[i][1].ToString() != "")
                 *          {
                 *              //离线消息
                 *              if (pMessageData.Tables[0].Rows[i][3].ToString() == "N/A")
                 *              {
                 *                  string strInput = @"INSERT INTO Message_Content(Content_Message, Content_Sender, Content_Recive, Content_Desc)
                 *                      VALUES(" + pMessageData.Tables[0].Rows[i][0].ToString() + "," + pMessageData.Tables[0].Rows[i][1].ToString()
                 + "," + pMessageData.Tables[0].Rows[i][2].ToString();
                 +
                 +                  pMessageADO.ExecuteQuery(strInput);
                 +                  pMessageADO.GetResult(RecordStyle.NONE);
                 +              }
                 +              //及时消息
                 +              else
                 +              {
                 +                  CustomDataCollection mSendContent = new CustomDataCollection(StructType.CUSTOMDATA);
                 +
                 +                  mSendContent.Add("用户:" + pMessageData.Tables[0].Rows[i][4].ToString() + "触发了命令:" + pMessageData.Tables[0].Rows[i][5].ToString() + "内容为:");
                 +
                 +                  SocketPacket pSourcePacket = new SocketPacket(pMessageID, mSendContent);
                 +                  byte[] pSendBuffer = pSourcePacket.CoalitionInfo();
                 +
                 +                  //byte[] pSendBuffer = mSocketDate.setSocketData(CEnum.ServiceKey.INSTANT_CONTENT_RECIVE, CEnum.Msg_Category.INSTANT, mSendContent).bMsgBuffer;
                 +
                 +                  //((MessageEventArgs)pObject).SocketConnection.OnSend(pMessageData.Tables[0].Rows[i][3].ToString(), pSendBuffer);
                 +              }
                 +          }
                 +      }
                 +  }
                 +  pMessageADO.DisConnected();
                 + }
                 + else
                 + {
                 +  Console.ForegroundColor = ConsoleColor.Red;
                 +  Console.WriteLine(String.Format("      DB Connect Error!"));
                 +  Console.ForegroundColor = ConsoleColor.Gray;
                 +  Console.WriteLine();
                 + }*/
                #endregion

                ((MessageEventArgs)pObject).Connection.OnRecive();

                //Print Message
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(String.Format("      Total Times : {0}", DateTime.Now.Subtract(tStartTime)));
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine();
            }
        }
Пример #18
0
        public AddTaskMenu(ITranslationHelper translation) : base(0, 0, 612, 64)
        {
            xPositionOnScreen = (Game1.uiViewport.Width / 2) - (width / 2);
            yPositionOnScreen = (Game1.uiViewport.Height / 2) - (height / 2);

            _translation  = translation;
            _taskParser   = new TaskParser(translation);
            _previousText = "";
            _hoverText    = "";

            optionsButton = new ClickableTextureComponent(
                new Rectangle(xPositionOnScreen - 88, yPositionOnScreen - 6, 64, 64),
                DeluxeJournalMod.UiTexture,
                new Rectangle(16, 80, 16, 16),
                4f)
            {
                myID            = 100,
                downNeighborID  = SNAP_AUTOMATIC,
                rightNeighborID = SNAP_AUTOMATIC
            };

            closeTipButton = new ClickableTextureComponent(
                new Rectangle(xPositionOnScreen + 444, yPositionOnScreen + height + 18, 24, 24),
                Game1.mouseCursors,
                new Rectangle(337, 494, 12, 12),
                2f)
            {
                myID            = 101,
                upNeighborID    = 0,
                downNeighborID  = SNAP_AUTOMATIC,
                rightNeighborID = SNAP_AUTOMATIC,
                leftNeighborID  = SNAP_AUTOMATIC,
                visible         = false
            };

            cancelButton = new ClickableTextureComponent(
                new Rectangle(xPositionOnScreen + width + 32, yPositionOnScreen - 6, 64, 64),
                DeluxeJournalMod.UiTexture,
                new Rectangle(0, 80, 16, 16),
                4f)
            {
                myID           = 102,
                downNeighborID = SNAP_AUTOMATIC,
                leftNeighborID = SNAP_AUTOMATIC
            };

            okButton = new ClickableTextureComponent(
                new Rectangle(xPositionOnScreen + width - 36, yPositionOnScreen + height + 18, 64, 64),
                DeluxeJournalMod.UiTexture,
                new Rectangle(32, 80, 16, 16),
                4f)
            {
                myID           = 103,
                upNeighborID   = 0,
                leftNeighborID = SNAP_AUTOMATIC
            };

            smartOkButton = new ClickableTextureComponent(
                new Rectangle(xPositionOnScreen + width - 108, okButton.bounds.Y, 64, 64),
                DeluxeJournalMod.UiTexture,
                new Rectangle(48, 80, 16, 16),
                4f)
            {
                myID            = 104,
                upNeighborID    = 0,
                rightNeighborID = SNAP_AUTOMATIC,
                leftNeighborID  = SNAP_AUTOMATIC
            };

            smartItemIcon = new ClickableTextureComponent(
                new Rectangle(xPositionOnScreen + 60, okButton.bounds.Y, 56, 56),
                DeluxeJournalMod.UiTexture,
                new Rectangle(14, 110, 14, 14),
                4f)
            {
                myID            = 105,
                upNeighborID    = 0,
                rightNeighborID = SNAP_AUTOMATIC,
                leftNeighborID  = SNAP_AUTOMATIC,
                visible         = false
            };

            smartNPCIcon = new ClickableTextureComponent(
                smartItemIcon.bounds,
                DeluxeJournalMod.UiTexture,
                new Rectangle(0, 110, 14, 14),
                4f)
            {
                myID            = 106,
                upNeighborID    = 0,
                rightNeighborID = SNAP_AUTOMATIC,
                leftNeighborID  = SNAP_AUTOMATIC,
                visible         = false
            };

            smartNameIcon = new ClickableTextureComponent(
                smartItemIcon.bounds,
                DeluxeJournalMod.UiTexture,
                new Rectangle(28, 110, 14, 14),
                4f)
            {
                myID            = 107,
                upNeighborID    = 0,
                rightNeighborID = SNAP_AUTOMATIC,
                leftNeighborID  = SNAP_AUTOMATIC,
                visible         = false
            };

            smartTypeIconCC = new ClickableComponent(new Rectangle(xPositionOnScreen, okButton.bounds.Y, 56, 56), "")
            {
                myID            = 108,
                upNeighborID    = 0,
                rightNeighborID = SNAP_AUTOMATIC,
                leftNeighborID  = SNAP_AUTOMATIC,
                visible         = false
            };

            _textBox = new SideScrollingTextBox(null, null, Game1.dialogueFont, Game1.textColor)
            {
                X        = xPositionOnScreen,
                Y        = yPositionOnScreen,
                Width    = width,
                Height   = 192,
                Selected = true
            };

            textBoxCC = new ClickableComponent(new Rectangle(_textBox.X, _textBox.Y, _textBox.Width, 64), "")
            {
                myID            = 0,
                downNeighborID  = SNAP_AUTOMATIC,
                rightNeighborID = SNAP_AUTOMATIC,
                leftNeighborID  = SNAP_AUTOMATIC
            };

            Game1.playSound("shwip");

            exitFunction = OnExit;
        }
Пример #19
0
        public static Assembly SetupGeneratedCode(string xml)
        {
            TaskParser tp = null;

            try
            {
                tp = LoadAndParse(xml, "FakeTask");
            }
            catch (XamlParseException)
            {
                Assert.True(false, "Parse of FakeTask XML failed");
            }

            TaskGenerator   tg            = new TaskGenerator(tp);
            CodeCompileUnit compileUnit   = tg.GenerateCode();
            CodeDomProvider codeGenerator = CodeDomProvider.CreateProvider("CSharp");

            using (StringWriter sw = new StringWriter(CultureInfo.CurrentCulture))
            {
                CodeGeneratorOptions options = new CodeGeneratorOptions();
                options.BlankLinesBetweenMembers = true;
                options.BracingStyle             = "C";

                codeGenerator.GenerateCodeFromCompileUnit(compileUnit, sw, options);
                CSharpCodeProvider provider = new CSharpCodeProvider();
                // Build the parameters for source compilation.
                CompilerParameters cp = new CompilerParameters();

                // Add an assembly reference.
                cp.ReferencedAssemblies.Add("System.dll");
                cp.ReferencedAssemblies.Add("System.Data.dll");
                cp.ReferencedAssemblies.Add("System.Xml.dll");
                cp.ReferencedAssemblies.Add(Path.Combine(PathToMSBuildBinaries, "net.r_eg.IeXod.Framework.dll"));
                cp.ReferencedAssemblies.Add(Path.Combine(PathToMSBuildBinaries, "net.r_eg.IeXod.Utilities.Core.dll"));
                cp.ReferencedAssemblies.Add(Path.Combine(PathToMSBuildBinaries, "net.r_eg.IeXod.Tasks.Core.dll"));

                // Generate an executable instead of
                // a class library.
                cp.GenerateExecutable = false;
                // Set the assembly file name to generate.
                cp.GenerateInMemory = true;
                // Invoke compilation
                CompilerResults cr = provider.CompileAssemblyFromSource(cp, sw.ToString());

                foreach (CompilerError error in cr.Errors)
                {
                    Console.WriteLine(error.ToString());
                }
                if (cr.Errors.Count > 0)
                {
                    Console.WriteLine(sw.ToString());
                }
                Assert.Empty(cr.Errors);
                if (cr.Errors.Count > 0)
                {
                    foreach (CompilerError error in cr.Errors)
                    {
                        Console.WriteLine(error.ErrorText);
                    }
                }
                return(cr.CompiledAssembly);
            }
        }
Пример #20
0
        public void DoWork()
        {
            if (this.activity == null || this.taskTimer.IsReady())
            {
                this.taskTimer.Reset();
                Activity newActivity = null;
                if (this.rootTask.WantToDoSomething())
                {
                    newActivity = this.rootTask.GetActivity();
                    this.nothingToDoTimer.Reset();
                }

                if (newActivity != null)
                {
                    if (newActivity.Task.GetType().ToString() == "Pather.Tasks.LoadTask")
                    {
                        Logger.Log("Queueing the old task tree");
                        this.taskQueue.Push(this.rootTask);
                        this.activityQueue.Push(this.activity);
                        if (this.activity != null)
                        {
                            bool done;
                            int  wait = 0;
                            do
                            {
                                done = this.activity.Do();
                                wait++;
                            } while (!done && (wait > 100));

                            if (!done)
                            {
                                this.activity.Stop();
                            }

                            Task tr = this.activity.Task;
                            while (tr != null)
                            {
                                tr.IsActive = false;
                                tr          = tr.Parent;
                            }
                            this.activity = null;
                        }
                        this.reader  = null;
                        this.astRoot = null;

                        string loadfile = Functions.GetTaskFilePath() + ((LoadTask)newActivity.Task).File;
                        Logger.Log("Loading file - " + loadfile);
                        if (RemoteTask.FileExist(loadfile))
                        {
                            this.reader = RemoteTask.GetFile(loadfile);
                        }
                        else
                        {
                            Logger.Log("File could not be loaded - " + loadfile);
                        }
                        if (this.reader != null)
                        {
                            Preprocessor pproc = new Preprocessor(this.reader);
                            TaskParser   t     = new TaskParser(new StreamReader(pproc.ProcessedStream));
                            this.astRoot = t.ParseTask(null);
                            this.reader.Close();
                            this.root = null;
                            this.root = new RootNode();
                            this.root.AddTask(this.astRoot);
                            this.root.BindSymbols(); // Just to make it a tad faster

                            this.rootTask         = null;
                            this.rootTask         = TaskCreator.CreateTaskFromNode(this.root, null);
                            Helpers.TaskInfo.Root = this.rootTask; // Desired?
                            TaskCreator.CreateTreeFromTasks(this.rootTask);
                            this.activity = null;
                            newActivity.Task.Restart();
                            newActivity = null;

                            if (this.rootTask == null)
                            {
                                Logger.Log("Load: No root task!");
                            }
                            else
                            {
                                Logger.Log("Load has been successful");
                                this.rootTask.Restart();
                                if (this.rootTask.WantToDoSomething())
                                {
                                    newActivity = this.rootTask.GetActivity();
                                    this.nothingToDoTimer.Reset();
                                }
                            }
                        }
                    }
                    else if (newActivity.Task.GetType().ToString() == "Pather.Tasks.UnloadTask")
                    {
                        if (this.activity != null)
                        {
                            this.activity.Stop();
                            this.activity = null;
                        }
                        this.rootTask = this.taskQueue.Pop();
                        this.activity = this.activityQueue.Pop();
                        newActivity.Task.Restart();
                        newActivity = null;
                        if (this.rootTask.WantToDoSomething())
                        {
                            newActivity = this.rootTask.GetActivity();
                            this.nothingToDoTimer.Reset();
                        }
                    }
                }

                if (newActivity != this.activity)
                {
                    if (this.activity != null)
                    {
                        // change _activity before it was finished
                        this.activity.Stop();
                        Task tr = this.activity.Task;
                        while (tr != null)
                        {
                            tr.IsActive = false;
                            tr          = tr.Parent;
                        }
                    }
                    this.activity = newActivity;
                    if (this.activity != null)
                    {
                        Task tr = this.activity.Task;
                        while (tr != null)
                        {
                            tr.IsActive = true;
                            tr          = tr.Parent;
                        }
                    }
                    else
                    {
                        Logger.Log("Got a null activity");
                    }

                    Logger.Log("Current activity: {0}", this.activity);

                    if (this.activity != null)
                    {
                        Logger.Log("Got a new activity: " + this.activity);
                        this.activity.Start();
                    }
                }
                if (newActivity == null)
                {
                    this.activity = null;
                }
            }
            if (this.activity == null)
            {
                if (this.nothingToDoTimer.IsReady())
                {
                    Logger.Log("Script ended. Stopping");
                    this.StopAll("Script ended - stopping");
                    return;
                }
            }
            else
            {
                this.nothingToDoTimer.Reset();
            }
            //form.SetTask(task);

            if (this.activity != null)
            {
                bool done = this.activity.Do();
                this.nothingToDoTimer.Reset(); // did something
                if (done)
                {
                    this.activity.Task.ActivityDone(this.activity);
                    Task tr = this.activity.Task;
                    while (tr != null)
                    {
                        tr.IsActive = false;
                        tr          = tr.Parent;
                    }
                    this.activity = null;
                }
            }

            this.tick.Reset();
        }