Example #1
0
        public void TestExecutor_TreeInputNull_Success()
        {
            ExpressionExecutor ex         = new ExpressionExecutor(session: null, userContext: this.UserContext);
            string             expression = "TreeInput == null";

            Assert.IsTrue(ex.Execute <bool>(expression).GetAwaiter().GetResult(), "Expected ExpressionExecutor to successfully evaluate a true expression using TreeInput as null.");
        }
        public void ComponentTemplate_ParsesNamedScope()
        {
            var code = @"
<?using AbsoluteGraphicsPlatform.Tests.Common.Components?>
<component-template Name=""BasicComponent"">
    <Bar Name=""Comp-1"">
        <Foo Name=""Comp-1-default-1"" />
        <Foo Name=""Comp-1-default-2"" />

        <template scope=""other"">
            <Foo Name=""Comp-1-other"">
            </Foo>
        </template>
    </Bar>
</component-template>
";
            var expressionExecutor = new ExpressionExecutor();
            var template           = Common.ParseComponentTemplateCode(code);

            var root = template.Templates[0];

            Assert.Equal(new StringPropertyValue("Comp-1"), root.PropertySetters["Name"].Value);
            Assert.Equal(new StringPropertyValue("Comp-1-default-1"), root.Templates["default"].ToArray()[0].PropertySetters["Name"].Value);
            Assert.Equal(new StringPropertyValue("Comp-1-default-2"), root.Templates["default"].ToArray()[1].PropertySetters["Name"].Value);
            Assert.Equal(new StringPropertyValue("Comp-1-other"), root.Templates["other"].ToArray()[0].PropertySetters["Name"].Value);
        }
Example #3
0
        private static void SetElementData(PrintElementBuildContext buildContext, string sourceProperty,
                                           string sourceExpression)
        {
            buildContext.ElementSourceProperty   = sourceProperty;
            buildContext.ElementSourceExpression = sourceExpression;

            var elementSourceValue = buildContext.ElementSourceValue;

            // Если указано свойство данных
            if (!string.IsNullOrEmpty(sourceProperty))
            {
                if (sourceProperty != "$")
                {
                    elementSourceValue = sourceProperty.StartsWith("$.")
                        ? buildContext.PrintViewSource.GetProperty(sourceProperty.Substring(2))
                        : buildContext.ElementSourceValue.GetProperty(sourceProperty);
                }
                else
                {
                    elementSourceValue = buildContext.PrintViewSource;
                }
            }

            // Если указано выражение над данными
            if (!string.IsNullOrEmpty(sourceExpression))
            {
                elementSourceValue = ExpressionExecutor.Execute(sourceExpression, elementSourceValue);
            }

            buildContext.ElementSourceValue = elementSourceValue;
        }
        public void ComponentTemplate_ParsesTreeStructure()
        {
            var code = @"
<?using AbsoluteGraphicsPlatform.Tests.Common.Components?>
<component-template Name=""BasicComponent"">
    <Foo Name=""Comp-1"">
        <Foo Name=""Comp-1-1"">
            <Foo Name=""Comp-1-1-1"">
            </Foo>
        </Foo>
        <Foo Name=""Comp-1-2"" />
    </Foo>
    <Foo Name=""Comp-2"">
    </Foo>
</component-template>
";
            var expressionExecutor = new ExpressionExecutor();
            var template           = Common.ParseComponentTemplateCode(code);

            Assert.Equal(new StringPropertyValue("Comp-1"), template.Templates[0].PropertySetters["Name"].Value);
            Assert.Equal(new StringPropertyValue("Comp-1-1"), template.Templates[0].Templates[0].PropertySetters["Name"].Value);
            Assert.Equal(new StringPropertyValue("Comp-1-1-1"), template.Templates[0].Templates[0].Templates[0].PropertySetters["Name"].Value);
            Assert.Equal(new StringPropertyValue("Comp-1-2"), template.Templates[0].Templates[1].PropertySetters["Name"].Value);
            Assert.Equal(new StringPropertyValue("Comp-2"), template.Templates[1].PropertySetters["Name"].Value);
        }
Example #5
0
        public void TestExecutor_TreeInput_Success()
        {
            object             treeInput  = "TestValue";
            ExpressionExecutor ex         = new ExpressionExecutor(session: null, userContext: this.UserContext, dependencies: null, scriptCache: null, treeInput: treeInput);
            string             expression = "TreeInput == \"TestValue\"";

            Assert.IsTrue(ex.Execute <bool>(expression).GetAwaiter().GetResult(), "Expected ExpressionExecutor to successfully evaluate a true expression using TreeInput.");
        }
Example #6
0
        public void TestExecutor_Success_bool()
        {
            this.UserContext.Foo = "Bar";
            ExpressionExecutor ex         = new ExpressionExecutor(session: null, userContext: this.UserContext);
            string             expression = "UserContext.Foo == \"Bar\"";

            Assert.IsTrue(ex.Execute <bool>(expression).GetAwaiter().GetResult(), "Expected ExpressionExecutor to successfully evaluate a true expression.");
        }
Example #7
0
        public void TestExecutor_Success_int()
        {
            this.UserContext.Foo = 1000;
            ExpressionExecutor ex         = new ExpressionExecutor(session: null, userContext: this.UserContext);
            string             expression = "UserContext.Foo";

            Assert.AreEqual(1000, ex.Execute <int>(expression).GetAwaiter().GetResult(), "Expected ExpressionExecutor to successfully evaluate the expression.");
        }
Example #8
0
        public void TestExecutor_Success_long()
        {
            // Note that long requires casting where int does not.
            this.UserContext.Foo = (long)1000;
            ExpressionExecutor ex         = new ExpressionExecutor(session: null, userContext: this.UserContext);
            string             expression = "UserContext.Foo";

            Assert.AreEqual((long)1000, ex.Execute <long>(expression).GetAwaiter().GetResult(), "Expected ExpressionExecutor to successfully evaluate the expression.");
        }
Example #9
0
        private object Act(IExpression expression,
                           IConstantExpressionExecutor constantExpressionExecutor = null,
                           IFunctionExpressionExecutor functionExpressionExecutor = null,
                           IBatchExpressionExecutor batchExpressionExecutor       = null)
        {
            var expressionExecutor = new ExpressionExecutor(constantExpressionExecutor, functionExpressionExecutor, batchExpressionExecutor);

            return(expressionExecutor.Execute(expression));
        }
Example #10
0
        public static ComponentTemplateExecutor MockComponentTemplateExecutor()
        {
            var agpxOptions        = OptionsMocks.WrapOptions(OptionsMocks.CreateAgpxOptions());
            var propertySetter     = new PropertySetter(OptionsMocks.CreateApplicationOptions());
            var expressionExecutor = new ExpressionExecutor();
            var dssStyleSetter     = new DssStyleSetter(agpxOptions, propertySetter, expressionExecutor);

            return(new ComponentTemplateExecutor(ComponentFactory, dssStyleSetter, propertySetter, agpxOptions));
        }
        public void MathOperation_ShouldCalculateBasicOperations()
        {
            var instructions       = Common.ParseCode(".rule { property: 1 + 7 * (3 + 5); }");
            var expressionExecutor = new ExpressionExecutor();

            var ruleset  = (RulesetInstruction)instructions.Single();
            var property = (PropertyInstruction)ruleset.Instructions.Single();

            Assert.Equal(new ScalarPropertyValue(57), expressionExecutor.GetValues(property.Value.Values));
        }
Example #12
0
        public void TestExecutor_Success_ExecuteTwice()
        {
            this.UserContext.Foo = "Bar";
            ExpressionExecutor ex         = new ExpressionExecutor(session: null, userContext: this.UserContext);
            string             expression = "UserContext.Foo == \"Bar\" && UserContext.GetTopic(\"TopicName\").ResourceType == \"Node\"";

            // Test - confirm Execute can compile and execute the same code twice without crashing.
            Assert.IsTrue(ex.Execute <bool>(expression).GetAwaiter().GetResult(), "Expected ExpressionExecutor to successfully evaluate a true expression.");
            Assert.IsTrue(ex.Execute <bool>(expression).GetAwaiter().GetResult(), "Expected ExpressionExecutor to successfully evaluate a true expression.");
        }
        public static Stylesheet CompileCode(string code)
        {
            var expressionExecutor = new ExpressionExecutor();
            var dssParser          = new DssParser();
            var dssCompiler        = new DssCompiler(expressionExecutor);
            var sourceInfo         = new SourceCodeInfo("TestCode", code);
            var instructions       = dssParser.Parse(sourceInfo);

            return(dssCompiler.Compile(instructions));
        }
Example #14
0
        public void MathOperation_ShouldCalculateBasicOperations()
        {
            var style = Common.CompileCode(".rule { property: 1 + 7 * (3 + 5); }");
            var expressionExecutor = new ExpressionExecutor();

            var ruleset = style.Rulesets.Single();
            var setter  = ruleset.PropertySetters.Single();

            Assert.Equal(new ScalarPropertyValue(57), setter.Value);
        }
Example #15
0
        public void TestExecutor_Success_ChangingFunctionDefinition()
        {
            ExpressionExecutor ex = new ExpressionExecutor(session: null, userContext: this.UserContext);

            // Rewritting GetCount to return 2
            string expression = "UserContext.GetCount = new Func<int>(() => 2)";

            Assert.AreEqual(this.UserContext.GetCount(), 1);
            ex.Execute <Func <int> >(expression).GetAwaiter().GetResult();
            Assert.AreEqual(this.UserContext.GetCount(), 2);
        }
Example #16
0
        public void TestExecutor_Fail_BadExpression()
        {
            this.UserContext.Foo = "Bar";
            ExpressionExecutor ex         = new ExpressionExecutor(session: null, userContext: this.UserContext);
            string             expression = "UserContext.Foo";

            Assert.ThrowsException <InvalidCastException>(() =>
            {
                ex.Execute <bool>(expression).GetAwaiter().GetResult();
            }, "Expected ExpressionExecutor to fail evaluating an expression that cannot be evaluated.");
        }
Example #17
0
        public void TestExecutor_Success_CompileWithExternalDependencies()
        {
            this.UserContext.Foo = ExternalTestType.TestEnum;
            List <Type> dependencies = new List <Type>();

            dependencies.Add(typeof(ExternalTestType));
            ExpressionExecutor ex         = new ExpressionExecutor(session: null, userContext: this.UserContext, dependencies: dependencies);
            string             expression = "UserContext.Foo.ToString() == ExternalTestType.TestEnum.ToString()";

            Assert.IsTrue(ex.Execute <bool>(expression).GetAwaiter().GetResult(), "Expected ExpressionExecutor to successfully evaluate a true expression.");
        }
Example #18
0
        public void Setter_ShouldCreateBasicSetterWithValueNone()
        {
            var style = Common.CompileCode(".rule { property: none; }");
            var expressionExecutor = new ExpressionExecutor();

            var ruleset = style.Rulesets.Single();
            var setter  = ruleset.PropertySetters.Single();

            Assert.Equal("property", setter.PropertyName);
            Assert.Equal(PropertyValue.None, setter.Value);
        }
        public void Setter_ShouldCreatePropertyInstructionWithValueNone()
        {
            var instructions       = Common.ParseCode(".rule { property: none; }");
            var expressionExecutor = new ExpressionExecutor();

            var ruleset  = (RulesetInstruction)instructions.Single();
            var property = (PropertyInstruction)ruleset.Instructions.Single();

            Assert.Equal("property", property.Identifier);
            Assert.Single(property.Value.Values);
            Assert.Equal(PropertyValue.None, expressionExecutor.GetValues(property.Value.Values));
        }
Example #20
0
        public void TestExecutor_Success_ChangingFunctionReturnType()
        {
            ExpressionExecutor ex = new ExpressionExecutor(null, this.UserContext, null);

            // Changing return type of GetCount
            string expression = "UserContext.GetCount = new Func<string>(() => \"Test\")";

            Assert.AreEqual(this.UserContext.GetCount(), 1);
            // Since expected return type has been updated, this should pass
            ex.Execute <Func <string> >(expression).GetAwaiter().GetResult();
            Assert.AreEqual(this.UserContext.GetCount(), "Test");
        }
Example #21
0
        public void TestExecutor_TreeInputJObject_Success()
        {
            JObject treeInput = new JObject();

            treeInput["StringProperty"] = "TestValue";
            treeInput["IntProperty"]    = 10;

            ExpressionExecutor ex         = new ExpressionExecutor(session: null, userContext: this.UserContext, dependencies: null, scriptCache: null, treeInput: treeInput);
            string             expression = "TreeInput.StringProperty == \"TestValue\" && TreeInput.IntProperty == 10";

            Assert.IsTrue(ex.Execute <bool>(expression).GetAwaiter().GetResult(), "Expected ExpressionExecutor to successfully evaluate a true expression using TreeInput as JObject.");
        }
Example #22
0
        public void TestExecutor_Success_CompileExpressionWithMissingDependenciesButOtherExternalTypesInSameNamespace()
        {
            this.UserContext.Foo = ExternalTestType.TestEnum;
            this.UserContext.Bar = TestType.Test;
            List <Type> dependencies = new List <Type>();

            dependencies.Add(typeof(ExternalTestType));

            ExpressionExecutor ex         = new ExpressionExecutor(null, this.UserContext, dependencies);
            string             expression = "UserContext.Foo.ToString() == ExternalTestType.TestEnum.ToString() && UserContext.Bar.ToString() == TestType.Test.ToString()";

            Assert.IsTrue(ex.Execute <bool>(expression).GetAwaiter().GetResult(), "Expected ExpressionExecutor to successfully evaluate a true expression.");
        }
        private static IStyle parseTestStyle()
        {
            var fileInfo           = new PhysicalFileInfo(new System.IO.FileInfo(@"C:\Playground\AbsoluteGraphicsPlatform\tests\TestFiles\TestStyle1.dss"));
            var expressionExecutor = new ExpressionExecutor();
            var dssParser          = new DssParser();
            var dssCompiler        = new DssCompiler(expressionExecutor);

            var sourceInfo   = new SourceCodeInfo(fileInfo);
            var instructions = dssParser.Parse(sourceInfo);
            var style        = dssCompiler.Compile(instructions);

            return(style);
        }
Example #24
0
        public void TestExecutor_Fail_ChangingFunctionReturnType()
        {
            ExpressionExecutor ex = new ExpressionExecutor(session: null, userContext: this.UserContext);

            // Changing return type of GetCount
            string expression = "UserContext.GetCount = new Func<string>(() => \"Test\")";

            Assert.ThrowsException <InvalidCastException>(() =>
            {
                // Since expected return type matches the original Func<int> type, this should throw an error
                ex.Execute <Func <int> >(expression).GetAwaiter().GetResult();
            }, "Expected ExpressionExecutor to fail evaluating can not change return type");
        }
Example #25
0
        public static IStyle GetStyle(string filename)
        {
            var fileProvider       = IO.GetTestFileProvider();
            var expressionExecutor = new ExpressionExecutor();
            var dssParser          = new DssParser();
            var dssCompiler        = new DssCompiler(expressionExecutor);

            var fileInfo     = fileProvider.GetFileInfo(filename);
            var sourceInfo   = new SourceCodeInfo(fileInfo);
            var instructions = dssParser.Parse(sourceInfo);
            var style        = dssCompiler.Compile(instructions);

            return(style);
        }
Example #26
0
        public void TestExecutor_ScriptCacheContainsKey()
        {
            this.UserContext.Foo = "Bar";
            string expression = "UserContext.Foo == \"Bar\" && UserContext.GetTopic(\"TopicName\").ResourceType == \"Node\"";

            // Test - confirm ExpressionExecutor script cache does not contain script before executing.
            ExpressionExecutor ex = new ExpressionExecutor(null, this.UserContext, null);

            Assert.IsFalse(ex.ScriptCacheContainsKey(expression));

            // Test - confirm ExpressionExecutor script cache does contain script after executing.
            Assert.IsTrue(ex.Execute <bool>(expression).GetAwaiter().GetResult());
            Assert.IsTrue(ex.ScriptCacheContainsKey(expression));
        }
Example #27
0
        public void TestExecutor_Fail_MissingDefinitions()
        {
            this.UserContext.Foo = "Bar";
            ExpressionExecutor ex         = new ExpressionExecutor(session: null, userContext: this.UserContext);
            string             expression = "UserContext.Bar == \"Bar\"";

            try
            {
                ex.Execute <bool>(expression).GetAwaiter().GetResult();
                Assert.Fail("Expected ExpressionExecutor to fail evaluating an expression when UserContext does not contain a necessary definitions.");
            }
            catch (Exception)
            {
            }
        }
Example #28
0
        public void TestExecutor_Fail_CompileExpressionWithMissingDependencies()
        {
            this.UserContext.Foo = ExternalTestType.ExampleEnum;
            ExpressionExecutor ex         = new ExpressionExecutor(session: null, userContext: this.UserContext);
            string             expression = "UserContext.Foo == ExternalTestType.ExampleEnum";

            try
            {
                ex.Execute <bool>(expression).GetAwaiter().GetResult();
                Assert.Fail("Expected ExpressionExecutor to fail evaluating an expression because runtime assembly is missing required dependencies.");
            }
            catch (Exception)
            {
            }
        }
Example #29
0
        public void TestExecutor_ScriptCacheContainsKey()
        {
            this.UserContext.Foo = "Bar";
            string expression = "UserContext.Foo == \"Bar\" && UserContext.GetTopic(\"TopicName\").ResourceType == \"Node\"";

            // Test - confirm ExpressionExecutor script cache does not contain script before executing.
            ConcurrentDictionary <string, Script <object> > scriptCache = new ConcurrentDictionary <string, Script <object> >();
            ExpressionExecutor ex = new ExpressionExecutor(session: null, userContext: this.UserContext, dependencies: null, scriptCache: scriptCache);

            Assert.IsFalse(scriptCache.ContainsKey(expression));

            // Test - confirm ExpressionExecutor script cache does contain script after executing.
            Assert.IsTrue(ex.Execute <bool>(expression).GetAwaiter().GetResult());
            Assert.IsTrue(scriptCache.ContainsKey(expression));
        }
Example #30
0
        public void TestExecutor_Fail_ExecutingMultipleStatements()
        {
            ExpressionExecutor ex = new ExpressionExecutor(session: null, userContext: this.UserContext);

            // Changing return type of GetCount
            string expression = "int x = UserContext.GetCount() + 5; UserContext.GetCount = new Func<int>(() => x); return UserContext.GetCount()";

            try
            {
                ex.Execute <Func <int> >(expression).GetAwaiter().GetResult();
                Assert.Fail("Expected ExpressionExecutor to fail evaluating can not pass multiple statements to expression.");
            }
            catch (Exception)
            {
            }
        }
 public void Invoke(ExpressionExecutor executor, string messageContent)
 {
     Exception exception = null;
     try
     {
         OnBeforeExecution();
         executor.Execute(messageContent);
     }
     catch (Exception e)
     {
         exception = e;
         throw;
     }
     finally
     {
         OnAfterExecution(exception);
     }
 }
        private ResultState ProcessQueueMessages(int queueId, int batchSize, bool archiveMessages)
        {
            var state = new ResultState
            {
                IsFailed = false
            };

            var messages = Repository.FetchQueueMessages(queueId, batchSize);
            if (messages != null)
            {
                foreach (var message in messages)
                {
                    var timer = Stopwatch.StartNew();
                    var messageId = message.MessageId;

                    state.LastMessageId = messageId;

                    try
                    {
                        var messageContext = GetMessageContext(message.Context);

                        state.MaxRetries = messageContext.Settings.MaxRetriesBeforeFail.GetValueOrDefault();
                        state.RecoveryMode = messageContext.Settings.RecoveryMode;

                        PublishSettings settings = messageContext.Settings;
                        using (var transaction = Repository.CreateProcessingTransaction(settings.JobIsolationLevel, settings.JobTimeout))
                        {
                            var executor = new ExpressionExecutor(_serializer, _jobActivator);

                            if (!string.IsNullOrWhiteSpace(message.ContextFactory))
                            {
                                using (var context = executor.Execute<ExecutionContext>(message.ContextFactory))
                                {
                                    if (context != null)
                                    {
                                        context.Invoke(executor, message.Content);
                                    }
                                    else
                                    {
                                        executor.Execute(message.Content);
                                    }
                                }
                            }
                            else
                            {
                                executor.Execute(message.Content);
                            }

                            if (transaction.TransactionStatus.HasValue)
                            {
                                var transactionStatus = transaction.TransactionStatus.Value;

                                if (transactionStatus == TransactionStatus.Aborted ||
                                    transactionStatus == TransactionStatus.InDoubt)
                                {
                                    throw new Exception($"Invalid transaction status: [{transactionStatus}]! Unable to commit!");
                                }
                            }

                            Repository.RemoveMessage(messageId, archiveMessages && !settings.DiscardWhenComplete, transaction);

                            transaction.Complete();
                        }

                        state.ProcessedMessages += 1;
                    }
                    catch (Exception e)
                    {
                        var error = e.GetFormattedError(messageId);
                        Logger.Error(error);

                        state.Error = error;
                        state.IsFailed = true;
                    }
                    finally
                    {
                        timer.Stop();
                        Logger.Trace("Message {0} processed in {1}", messageId, timer.Elapsed);
                    }

                    if (Canceled || state.IsFailed)
                    {
                        break;
                    }
                }
            }

            return state;
        }