public FilterSpecCompilerArgs(
     IDictionary<string, Pair<EventType, string>> taggedEventTypes,
     IDictionary<string, Pair<EventType, string>> arrayEventTypes,
     ExprEvaluatorContext exprEvaluatorContext,
     string statementName,
     string statementId,
     StreamTypeService streamTypeService,
     MethodResolutionService methodResolutionService,
     TimeProvider timeProvider,
     VariableService variableService,
     TableService tableService,
     EventAdapterService eventAdapterService,
     ScriptingService scriptingService,
     Attribute[] annotations,
     ContextDescriptor contextDescriptor,
     ConfigurationInformation configurationInformation)
 {
     TaggedEventTypes = taggedEventTypes;
     ArrayEventTypes = arrayEventTypes;
     ExprEvaluatorContext = exprEvaluatorContext;
     StatementName = statementName;
     StatementId = statementId;
     StreamTypeService = streamTypeService;
     MethodResolutionService = methodResolutionService;
     TimeProvider = timeProvider;
     VariableService = variableService;
     TableService = tableService;
     EventAdapterService = eventAdapterService;
     ScriptingService = scriptingService;
     Annotations = annotations;
     ContextDescriptor = contextDescriptor;
     ConfigurationInformation = configurationInformation;
 }
        public async Task InvokeLoadEventFromJsAndCustomEventFromJsAndCs()
        {
            var service  = new ScriptingService();
            var cfg      = Configuration.Default.With(service);
            var html     = @"<!doctype html>
<html>
<body>
<script>
var log = [];
log.push('a');
document.addEventListener('hello', function() {
    log.push('c');
}, false);
log.push('b');
</script>
</body>";
            var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));

            var log = service.Engine.GetJint(document).GetValue("log").AsArray();

            document.AddEventListener("hello", (s, ev) =>
            {
                log.Put(log.Get("length").AsNumber().ToString(), "d", false);
            });

            document.Dispatch(new Event("hello"));

            Assert.AreEqual(4.0, log.Get("length").AsNumber());
            Assert.AreEqual("a", log.Get("0").AsString());
            Assert.AreEqual("b", log.Get("1").AsString());
            Assert.AreEqual("c", log.Get("2").AsString());
            Assert.AreEqual("d", log.Get("3").AsString());
        }
Beispiel #3
0
        public ScriptViewModel(ScriptingService model)
        {
            this.ExecuteCommand = new DelegateCommand(this.ExecuteCommandExecute);
            this.service        = model;

            this.AttatchedDatamodel = new ScriptModel();
        }
        public async Task InvokeLoadEventFromJsAndCustomEventFromJsAndCs()
        {
            var service = new ScriptingService();
            var cfg = Configuration.Default.With(service);
            var html = @"<!doctype html>
<html>
<body>
<script>
var log = [];
log.push('a');
document.addEventListener('hello', function() {
    log.push('c');
}, false);
log.push('b');
</script>
</body>";
            var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));
            var log = service.Engine.GetJint(document).GetValue("log").AsArray();

            document.AddEventListener("hello", (s, ev) =>
            {
                log.Put(log.Get("length").AsNumber().ToString(), "d", false);
            });

            document.Dispatch(new Event("hello"));
            
            Assert.AreEqual(4.0, log.Get("length").AsNumber());
            Assert.AreEqual("a", log.Get("0").AsString());
            Assert.AreEqual("b", log.Get("1").AsString());
            Assert.AreEqual("c", log.Get("2").AsString());
            Assert.AreEqual("d", log.Get("3").AsString());
        }
Beispiel #5
0
 private void CompileScript(ScriptingService scriptingService, ExprEvaluator[] evaluators)
 {
     Script.Compiled = new ExpressionScriptCompiledImpl(
         scriptingService.Compile(
             Script.OptionalDialect ?? _defaultDialect,
             Script));
 }
Beispiel #6
0
        public ExprValidationContext(StreamTypeService streamTypeService, EngineImportService engineImportService, StatementExtensionSvcContext statementExtensionSvcContext, ViewResourceDelegateUnverified viewResourceDelegate, TimeProvider timeProvider, VariableService variableService, TableService tableService, ExprEvaluatorContext exprEvaluatorContext, EventAdapterService eventAdapterService, string statementName, int statementId, Attribute[] annotations, ContextDescriptor contextDescriptor, ScriptingService scriptingService, bool disablePropertyExpressionEventCollCache, bool allowRollupFunctions, bool allowBindingConsumption, bool isUnidirectionalJoin, string intoTableName, bool isFilterExpression)
        {
            StreamTypeService            = streamTypeService;
            EngineImportService          = engineImportService;
            StatementExtensionSvcContext = statementExtensionSvcContext;
            ViewResourceDelegate         = viewResourceDelegate;
            TimeProvider         = timeProvider;
            VariableService      = variableService;
            TableService         = tableService;
            ExprEvaluatorContext = exprEvaluatorContext;
            EventAdapterService  = eventAdapterService;
            StatementName        = statementName;
            StatementId          = statementId;
            Annotations          = annotations;
            ContextDescriptor    = contextDescriptor;
            ScriptingService     = scriptingService;
            IsDisablePropertyExpressionEventCollCache = disablePropertyExpressionEventCollCache;
            IsAllowRollupFunctions    = allowRollupFunctions;
            IsAllowBindingConsumption = allowBindingConsumption;
            IsResettingAggregations   = isUnidirectionalJoin;
            IntoTableName             = intoTableName;
            IsFilterExpression        = isFilterExpression;

            IsExpressionAudit       = AuditEnum.EXPRESSION.GetAudit(annotations) != null;
            IsExpressionNestedAudit = AuditEnum.EXPRESSION_NESTED.GetAudit(annotations) != null;
        }
Beispiel #7
0
        public void TestQuery()
        {
            MetadataServiceSettings settings = new MetadataServiceSettings();

            settings.Catalog = @"C:\Users\User\Desktop\GitHub\publish\one-c-sharp-sql\bin\metadata";
            IMetadataService metadata = new MetadataService();

            metadata.Configure(settings);
            metadata.UseServer("sqlexpress");
            metadata.UseDatabase("trade_11_2_3_159_demo");
            metadata.UseDatabase("accounting_3_0_72_72_demo");
            IQueryExecutor     executor  = new QueryExecutor(metadata);
            IScriptingService  scripting = new ScriptingService(metadata, executor);
            IList <ParseError> errors;
            string             sql = scripting.PrepareScript(GetTestQueryText(), out errors);

            foreach (ParseError error in errors)
            {
                Console.WriteLine(error.Message);
            }
            if (errors.Count == 0)
            {
                Console.WriteLine(sql);
            }
        }
Beispiel #8
0
        private async Task <Mock <RequestContext <ScriptingResult> > > SendAndValidateScriptRequest(bool isSelectScript)
        {
            var result         = GetLiveAutoCompleteTestObjects();
            var requestContext = new Mock <RequestContext <ScriptingResult> >();

            requestContext.Setup(x => x.SendResult(It.IsAny <ScriptingResult>())).Returns(Task.FromResult(new object()));

            var scriptingParams = new ScriptingParams
            {
                OwnerUri = ConnectionService.BuildConnectionString(result.ConnectionInfo.ConnectionDetails)
            };

            if (isSelectScript)
            {
                scriptingParams.ScriptOptions = new ScriptOptions {
                    ScriptCreateDrop = "ScriptSelect"
                };
                List <ScriptingObject> scriptingObjects = new List <ScriptingObject>();
                scriptingObjects.Add(new ScriptingObject {
                    Type = "View", Name = "sysobjects", Schema = "sys"
                });
                scriptingParams.ScriptingObjects = scriptingObjects;
            }
            ScriptingService service = new ScriptingService();
            await service.HandleScriptExecuteRequest(scriptingParams, requestContext.Object);

            return(requestContext);
        }
Beispiel #9
0
        // settable for view-sharing

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="stmtEngineServices">is the engine services for the statement</param>
        /// <param name="schedulingService">implementation for schedule registration</param>
        /// <param name="scheduleBucket">is for ordering scheduled callbacks within the view statements</param>
        /// <param name="epStatementHandle">is the statements-own handle for use in registering callbacks with services</param>
        /// <param name="viewResultionService">is a service for resolving view namespace and name to a view factory</param>
        /// <param name="patternResolutionService">is the service that resolves pattern objects for the statement</param>
        /// <param name="statementExtensionSvcContext">provide extension points for custom statement resources</param>
        /// <param name="statementStopService">for registering a callback invoked when a statement is stopped</param>
        /// <param name="methodResolutionService">is a service for resolving static methods and aggregation functions</param>
        /// <param name="patternContextFactory">is the pattern-level services and context information factory</param>
        /// <param name="filterService">is the filtering service</param>
        /// <param name="statementResultService">handles awareness of listeners/subscriptions for a statement customizing output produced</param>
        /// <param name="internalEventEngineRouteDest">routing destination</param>
        /// <param name="annotations">The annotations.</param>
        /// <param name="statementAgentInstanceRegistry">The statement agent instance registry.</param>
        /// <param name="defaultAgentInstanceLock">The default agent instance lock.</param>
        /// <param name="contextDescriptor">The context descriptor.</param>
        /// <param name="patternSubexpressionPoolSvc">The pattern subexpression pool SVC.</param>
        /// <param name="matchRecognizeStatePoolStmtSvc">The match recognize state pool statement SVC.</param>
        /// <param name="statelessSelect">if set to <c>true</c> [stateless select].</param>
        /// <param name="contextControllerFactoryService">The context controller factory service.</param>
        /// <param name="defaultAgentInstanceScriptContext">The default agent instance script context.</param>
        /// <param name="aggregationServiceFactoryService">The aggregation service factory service.</param>
        /// <param name="scriptingService">The scripting service.</param>
        /// <param name="writesToTables">if set to <c>true</c> [writes to tables].</param>
        /// <param name="statementUserObject">The statement user object.</param>
        /// <param name="statementSemiAnonymousTypeRegistry">The statement semi anonymous type registry.</param>
        /// <param name="priority">The priority.</param>
        public StatementContext(
            StatementContextEngineServices stmtEngineServices,
            SchedulingService schedulingService,
            ScheduleBucket scheduleBucket,
            EPStatementHandle epStatementHandle,
            ViewResolutionService viewResultionService,
            PatternObjectResolutionService patternResolutionService,
            StatementExtensionSvcContext statementExtensionSvcContext,
            StatementStopService statementStopService,
            MethodResolutionService methodResolutionService,
            PatternContextFactory patternContextFactory,
            FilterService filterService,
            StatementResultService statementResultService,
            InternalEventRouteDest internalEventEngineRouteDest,
            Attribute[] annotations,
            StatementAIResourceRegistry statementAgentInstanceRegistry,
            IReaderWriterLock defaultAgentInstanceLock,
            ContextDescriptor contextDescriptor,
            PatternSubexpressionPoolStmtSvc patternSubexpressionPoolSvc,
            MatchRecognizeStatePoolStmtSvc matchRecognizeStatePoolStmtSvc,
            bool statelessSelect,
            ContextControllerFactoryService contextControllerFactoryService,
            AgentInstanceScriptContext defaultAgentInstanceScriptContext,
            AggregationServiceFactoryService aggregationServiceFactoryService,
            ScriptingService scriptingService,
            bool writesToTables,
            object statementUserObject,
            StatementSemiAnonymousTypeRegistry statementSemiAnonymousTypeRegistry,
            int priority)
        {
            _stmtEngineServices               = stmtEngineServices;
            SchedulingService                 = schedulingService;
            ScheduleBucket                    = scheduleBucket;
            EpStatementHandle                 = epStatementHandle;
            ViewResolutionService             = viewResultionService;
            PatternResolutionService          = patternResolutionService;
            StatementExtensionServicesContext = statementExtensionSvcContext;
            StatementStopService              = statementStopService;
            MethodResolutionService           = methodResolutionService;
            PatternContextFactory             = patternContextFactory;
            FilterService                = filterService;
            _statementResultService      = statementResultService;
            InternalEventEngineRouteDest = internalEventEngineRouteDest;
            ScheduleAdjustmentService    = stmtEngineServices.ConfigSnapshot.EngineDefaults.ExecutionConfig.IsAllowIsolatedService ? new ScheduleAdjustmentService() : null;
            Annotations = annotations;
            StatementAgentInstanceRegistry = statementAgentInstanceRegistry;
            DefaultAgentInstanceLock       = defaultAgentInstanceLock;
            ContextDescriptor                 = contextDescriptor;
            PatternSubexpressionPoolSvc       = patternSubexpressionPoolSvc;
            MatchRecognizeStatePoolStmtSvc    = matchRecognizeStatePoolStmtSvc;
            IsStatelessSelect                 = statelessSelect;
            ContextControllerFactoryService   = contextControllerFactoryService;
            DefaultAgentInstanceScriptContext = defaultAgentInstanceScriptContext;
            AggregationServiceFactoryService  = aggregationServiceFactoryService;
            ScriptingService    = scriptingService;
            IsWritesToTables    = writesToTables;
            StatementUserObject = statementUserObject;
            StatementSemiAnonymousTypeRegistry = statementSemiAnonymousTypeRegistry;
            Priority = priority;
        }
Beispiel #10
0
 public void SetPythonScriptService(ScriptingService scriptService)
 {
     if (m_pythonService != null)
     {
         return;                          // it is already set.
     }
     m_pythonService = (BasicPythonService)scriptService;
 }
Beispiel #11
0
        /*endblock:abstractMethod*/

/*block:usermethod*/ public /*name:autoUsermethod*/ string User_DoPrototype(string settings = "") /*endname*/
        {
#if !NO_LUA_TESTING
            ScriptingService.ReplayWrite_CustomLua($"/*name:scriptName*/PrototypeService/*endname*/./*name|pre#User_:methodName*/User_DoPrototype/*endname*/(/*name:replayparams*/{settings}/*endname*/)");
#endif
            /*name:return*/
            return /*endname*/ /*name:methodName*/ (DoPrototype/*endname*/ (/*name:proxyparams*/ settings /*endname*/));
        }
Beispiel #12
0
        public LessonParagraphMathViewModel(ScriptingService scriptingService)
        {
            this.ExecuteScriptCommand = new DelegateCommand(this.ExecuteScriptCommandExecute);
            this.scriptingService     = scriptingService;

            this.PropertyChanged += this.LessonParagraphMathViewModelPropertyChanged;

            this.ResetViewCommand = new DelegateCommand(this.ResetViewCommandExecute);
        }
        /// <summary>
        /// Sets scripting to true, registers the JavaScript engine and returns
        /// a new configuration with the scripting service.
        /// </summary>
        /// <param name="configuration">The configuration to use.</param>
        /// <returns>The new configuration.</returns>
        public static IConfiguration WithJavaScript(this IConfiguration configuration)
        {
            if (!configuration.Services.OfType <ScriptingService>().Any())
            {
                var service = new ScriptingService();
                return(configuration.With(service));
            }

            return(configuration);
        }
 public async Task RunCSharpFunctionFromJavaScript()
 {
     var service = new ScriptingService();
     var cfg = Configuration.Default.With(service);
     var storedValue = 0.0;
     service.Engine.External["square"] = new Action<Double>(x => storedValue = x);
     var html = "<!doctype html><script>square(4 * 4);</script>";
     var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));
     Assert.AreEqual(16.0, storedValue);
 }
 public async Task ReadStoredJavaScriptValueFromCSharp()
 {
     var service = new ScriptingService();
     var cfg = Configuration.Default.With(service);
     var html = "<!doctype html><script>var foo = 'test';</script>";
     var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));
     var foo = service.Engine.GetJint(document).GetValue("foo");
     Assert.AreEqual(Types.String, foo.Type);
     Assert.AreEqual("test", foo.AsString());
 }
 public async Task RunJavaScriptFunctionFromCSharp()
 {
     var service = new ScriptingService();
     var cfg = Configuration.Default.With(service);
     var html = "<!doctype html><script>function square(x) { return x * x; }</script>";
     var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));
     var square = service.Engine.GetJint(document).GetValue("square");
     var result = square.Invoke(4);
     Assert.AreEqual(Types.Number, result.Type);
     Assert.AreEqual(16.0, result.AsNumber());
 }
 public async Task InvokeFunctionOnLoadEventShouldFireDelayed()
 {
     var service = new ScriptingService();
     var cfg = Configuration.Default.With(service);
     var html = "<!doctype html><div id=result></div><script>document.addEventListener('load', function () { document.querySelector('#result').textContent = 'done'; }, false);</script>";
     var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));
     var div = document.QuerySelector("#result");
     Assert.AreEqual("", div.TextContent);
     await Task.Delay(50);
     Assert.AreEqual("done", div.TextContent);
 }
 public async Task AccessCSharpInstanceMembersFromJavaScript()
 {
     var service = new ScriptingService();
     var cfg = Configuration.Default.With(service);
     service.Engine.External["person"] = new Person { Age = 20, Name = "Foobar" };
     var html = "<!doctype html><script>var str = person.Name + ' is ' + person.Age + ' years old';</script>";
     var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));
     var str = service.Engine.GetJint(document).GetValue("str");
     Assert.AreEqual(Types.String, str.Type);
     Assert.AreEqual("Foobar is 20 years old", str.AsString());
 }
 public async Task InvokeFunctionOnCustomEvent()
 {
     var service = new ScriptingService();
     var cfg = Configuration.Default.With(service);
     var html = "<!doctype html><div id=result>0</div><script>var i = 0; document.addEventListener('hello', function () { i++; document.querySelector('#result').textContent = i.toString(); }, false);</script>";
     var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));
     var div = document.QuerySelector("#result");
     document.Dispatch(new CustomEvent("hello"));
     Assert.AreEqual("1", div.TextContent);
     document.Dispatch(new CustomEvent("hello"));
     Assert.AreEqual("2", div.TextContent);
 }
        /// <summary>
        /// Validate the view.
        /// </summary>
        /// <param name="engineImportService">The engine import service.</param>
        /// <param name="streamTypeService">supplies the types of streams against which to validate</param>
        /// <param name="methodResolutionService">for resolving imports and classes and methods</param>
        /// <param name="timeProvider">for providing current time</param>
        /// <param name="variableService">for access to variables</param>
        /// <param name="tableService"></param>
        /// <param name="scriptingService">The scripting service.</param>
        /// <param name="exprEvaluatorContext">The expression evaluator context.</param>
        /// <param name="configSnapshot">The config snapshot.</param>
        /// <param name="schedulingService">The scheduling service.</param>
        /// <param name="engineURI">The engine URI.</param>
        /// <param name="sqlParameters">The SQL parameters.</param>
        /// <param name="eventAdapterService">The event adapter service.</param>
        /// <param name="statementName">Name of the statement.</param>
        /// <param name="statementId">The statement id.</param>
        /// <param name="annotations">The annotations.</param>
        /// <throws>  ExprValidationException is thrown to indicate an exception in validating the view </throws>
        public void Validate(
            EngineImportService engineImportService,
            StreamTypeService streamTypeService,
            MethodResolutionService methodResolutionService,
            TimeProvider timeProvider,
            VariableService variableService,
            TableService tableService,
            ScriptingService scriptingService,
            ExprEvaluatorContext exprEvaluatorContext,
            ConfigurationInformation configSnapshot,
            SchedulingService schedulingService,
            string engineURI,
            IDictionary <int, IList <ExprNode> > sqlParameters,
            EventAdapterService eventAdapterService,
            string statementName,
            string statementId,
            Attribute[] annotations)
        {
            _evaluators           = new ExprEvaluator[_inputParameters.Count];
            _subordinateStreams   = new SortedSet <int>();
            _exprEvaluatorContext = exprEvaluatorContext;

            int count             = 0;
            var validationContext = new ExprValidationContext(
                streamTypeService, methodResolutionService, null, timeProvider, variableService, tableService,
                exprEvaluatorContext, eventAdapterService, statementName, statementId, annotations, null, scriptingService,
                false, false, true, false, null, false);

            foreach (string inputParam in _inputParameters)
            {
                ExprNode raw = FindSQLExpressionNode(_myStreamNumber, count, sqlParameters);
                if (raw == null)
                {
                    throw new ExprValidationException(
                              "Internal error find expression for historical stream parameter " + count + " stream " +
                              _myStreamNumber);
                }
                ExprNode evaluator = ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.DATABASEPOLL, raw, validationContext);
                _evaluators[count++] = evaluator.ExprEvaluator;

                ExprNodeIdentifierCollectVisitor visitor = new ExprNodeIdentifierCollectVisitor();
                visitor.Visit(evaluator);
                foreach (ExprIdentNode identNode in visitor.ExprProperties)
                {
                    if (identNode.StreamId == _myStreamNumber)
                    {
                        throw new ExprValidationException("Invalid expression '" + inputParam +
                                                          "' resolves to the historical data itself");
                    }
                    _subordinateStreams.Add(identNode.StreamId);
                }
            }
        }
Beispiel #21
0
        private async Task VerifyScriptAs(string query, ScriptingObject scriptingObject, string scriptCreateDrop, string expectedScript)
        {
            var testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, query, "ScriptingTests");

            try
            {
                var requestContext = new Mock <RequestContext <ScriptingResult> >();
                requestContext.Setup(x => x.SendResult(It.IsAny <ScriptingResult>())).Returns(Task.FromResult(new object()));
                ConnectionService connectionService = LiveConnectionHelper.GetLiveTestConnectionService();
                using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
                {
                    //Opening a connection to db to lock the db
                    TestConnectionResult connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync(testDb.DatabaseName, queryTempFile.FilePath, ConnectionType.Default);

                    var scriptingParams = new ScriptingParams
                    {
                        OwnerUri          = queryTempFile.FilePath,
                        ScriptDestination = "ToEditor"
                    };

                    scriptingParams.ScriptOptions = new ScriptOptions
                    {
                        ScriptCreateDrop = scriptCreateDrop,
                    };

                    scriptingParams.ScriptingObjects = new List <ScriptingObject>
                    {
                        scriptingObject
                    };


                    ScriptingService service = new ScriptingService();
                    await service.HandleScriptingScriptAsRequest(scriptingParams, requestContext.Object);

                    Thread.Sleep(2000);
                    await service.ScriptingTask;

                    requestContext.Verify(x => x.SendResult(It.Is <ScriptingResult>(r => VerifyScriptingResult(r, expectedScript))));
                    connectionService.Disconnect(new ServiceLayer.Connection.Contracts.DisconnectParams
                    {
                        OwnerUri = queryTempFile.FilePath
                    });
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                await testDb.CleanupAsync();
            }
        }
Beispiel #22
0
        public async Task ReadStoredJavaScriptValueFromCSharp()
        {
            var service  = new ScriptingService();
            var cfg      = Configuration.Default.With(service);
            var html     = "<!doctype html><script>var foo = 'test';</script>";
            var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));

            var foo = service.Engine.GetJint(document).GetValue("foo");

            Assert.AreEqual(Types.String, foo.Type);
            Assert.AreEqual("test", foo.AsString());
        }
Beispiel #23
0
        public async Task RunCSharpFunctionFromJavaScript()
        {
            var service     = new ScriptingService();
            var cfg         = Configuration.Default.With(service);
            var storedValue = 0.0;

            service.Engine.External["square"] = new Action <Double>(x => storedValue = x);
            var html     = "<!doctype html><script>square(4 * 4);</script>";
            var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));

            Assert.AreEqual(16.0, storedValue);
        }
Beispiel #24
0
        public async Task RunJavaScriptFunctionFromCSharp()
        {
            var service  = new ScriptingService();
            var cfg      = Configuration.Default.With(service);
            var html     = "<!doctype html><script>function square(x) { return x * x; }</script>";
            var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));

            var square = service.Engine.GetJint(document).GetValue("square");
            var result = square.Invoke(4);

            Assert.AreEqual(Types.Number, result.Type);
            Assert.AreEqual(16.0, result.AsNumber());
        }
        public async Task InvokeFunctionOnCustomEvent()
        {
            var service  = new ScriptingService();
            var cfg      = Configuration.Default.With(service);
            var html     = "<!doctype html><div id=result>0</div><script>var i = 0; document.addEventListener('hello', function () { i++; document.querySelector('#result').textContent = i.toString(); }, false);</script>";
            var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));

            var div = document.QuerySelector("#result");

            document.Dispatch(new CustomEvent("hello"));
            Assert.AreEqual("1", div.TextContent);
            document.Dispatch(new CustomEvent("hello"));
            Assert.AreEqual("2", div.TextContent);
        }
        public async Task InvokeFunctionOnLoadEventShouldFireDelayed()
        {
            var service  = new ScriptingService();
            var cfg      = Configuration.Default.With(service);
            var html     = "<!doctype html><div id=result></div><script>document.addEventListener('load', function () { document.querySelector('#result').textContent = 'done'; }, false);</script>";
            var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));

            var div = document.QuerySelector("#result");

            Assert.AreEqual("", div.TextContent);
            await Task.Delay(50);

            Assert.AreEqual("done", div.TextContent);
        }
Beispiel #27
0
        public async Task AccessCSharpInstanceMembersFromJavaScript()
        {
            var service = new ScriptingService();
            var cfg     = Configuration.Default.With(service);

            service.Engine.External["person"] = new Person {
                Age = 20, Name = "Foobar"
            };
            var html     = "<!doctype html><script>var str = person.Name + ' is ' + person.Age + ' years old';</script>";
            var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));

            var str = service.Engine.GetJint(document).GetValue("str");

            Assert.AreEqual(Types.String, str.Type);
            Assert.AreEqual("Foobar is 20 years old", str.AsString());
        }
        private async Task <Mock <RequestContext <ScriptingScriptAsResult> > > SendAndValidateScriptRequest(ScriptOperation operation, string objectType)
        {
            var result         = GetLiveAutoCompleteTestObjects();
            var requestContext = new Mock <RequestContext <ScriptingScriptAsResult> >();

            requestContext.Setup(x => x.SendResult(It.IsAny <ScriptingScriptAsResult>())).Returns(Task.FromResult(new object()));

            var scriptingParams = new ScriptingScriptAsParams
            {
                OwnerUri  = result.ConnectionInfo.OwnerUri,
                Operation = operation,
                Metadata  = GenerateMetadata(objectType)
            };

            await ScriptingService.HandleScriptingScriptAsRequest(scriptingParams, requestContext.Object);

            return(requestContext);
        }
        public async Task AddClickHandlerClassicallyWillExecute()
        {
            var service = new ScriptingService();
            var cfg = Configuration.Default.With(service);
            var html = @"<!doctype html>
<html>
<body>
<script>
var clicked = false;
document.onclick = function () {
    clicked = true;
};
document.dispatchEvent(new MouseEvent('click'));
</script>
</body>";
            var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));
            var clicked = service.Engine.GetJint(document).GetValue("clicked").AsBoolean();
            Assert.IsTrue(clicked);
        }
Beispiel #30
0
        /// <summary>
        /// Since this application is really just a wrapper around 3 other editors, the scripting service
        /// needs to do some special handling for commonly named variables. </summary>
        /// <param name="container"></param>
        private static void InitializeScriptingVariables(CompositionContainer container)
        {
            try
            {
                ScriptingService scriptingService = container.GetExportedValue <ScriptingService>();
                if (scriptingService != null)
                {
                    scriptingService.RemoveVariable("editor");
                    StatechartEditorSample.Editor stateChartEditor = container.GetExportedValue <StatechartEditorSample.Editor>();
                    if (stateChartEditor != null)
                    {
                        scriptingService.SetVariable("stateChartEditor", stateChartEditor);
                    }
                    CircuitEditorSample.Editor circuitEditor = container.GetExportedValue <CircuitEditorSample.Editor>();
                    if (circuitEditor != null)
                    {
                        scriptingService.SetVariable("circuitEditor", circuitEditor);
                    }
                    FsmEditorSample.Editor fsmEditor = container.GetExportedValue <FsmEditorSample.Editor>();
                    if (fsmEditor != null)
                    {
                        scriptingService.SetVariable("fsmEditor", fsmEditor);
                    }

                    IContextRegistry contextRegistry = container.GetExportedValue <IContextRegistry>();
                    if (contextRegistry != null)
                    {
                        contextRegistry.ActiveContextChanged += delegate
                        {
                            //Note this assumes this is the last ActiveContextChanged listener to be called.
                            //Each of the Circuit/Fsm/StatechartEditors also set these variables
                            //(2 out of 3 will set them to null), so it is important this is the last listener invoked.
                            EditingContext editingContext = contextRegistry.ActiveContext.As <EditingContext>();
                            scriptingService.SetVariable("editingContext", editingContext);
                            IViewingContext viewContext = contextRegistry.GetActiveContext <IViewingContext>();
                            scriptingService.SetVariable("view", viewContext);
                        };
                    }
                }
            }
            catch { }
        }
        public async Task AddClickHandlerClassicallyWillExecute()
        {
            var service  = new ScriptingService();
            var cfg      = Configuration.Default.With(service);
            var html     = @"<!doctype html>
<html>
<body>
<script>
var clicked = false;
document.onclick = function () {
    clicked = true;
};
document.dispatchEvent(new MouseEvent('click'));
</script>
</body>";
            var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));

            var clicked = service.Engine.GetJint(document).GetValue("clicked").AsBoolean();

            Assert.IsTrue(clicked);
        }
        public async Task AddAndInvokeClickHandlerWillChangeCapturedValue()
        {
            var service  = new ScriptingService();
            var cfg      = Configuration.Default.With(service);
            var html     = @"<!doctype html>
<html>
<body>
<script>
var clicked = false;
document.onclick = function () {
    clicked = true;
};
document.onclick();
</script>
</body>";
            var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));

            var clicked = service.Engine.GetJint(document).GetValue("clicked").AsBoolean();

            Assert.IsTrue(clicked);
        }
Beispiel #33
0
 public FilterSpecCompilerArgs(
     IContainer container,
     IDictionary<string, Pair<EventType, string>> taggedEventTypes,
     IDictionary<string, Pair<EventType, string>> arrayEventTypes,
     ExprEvaluatorContext exprEvaluatorContext,
     string statementName,
     int statementId,
     StreamTypeService streamTypeService,
     EngineImportService engineImportService,
     TimeProvider timeProvider,
     VariableService variableService,
     TableService tableService,
     EventAdapterService eventAdapterService,
     FilterBooleanExpressionFactory filterBooleanExpressionFactory,
     ScriptingService scriptingService,
     Attribute[] annotations,
     ContextDescriptor contextDescriptor,
     ConfigurationInformation configurationInformation,
     StatementExtensionSvcContext statementExtensionSvcContext)
 {
     Container = container;
     TaggedEventTypes = taggedEventTypes;
     ArrayEventTypes = arrayEventTypes;
     ExprEvaluatorContext = exprEvaluatorContext;
     StatementName = statementName;
     StatementId = statementId;
     StreamTypeService = streamTypeService;
     EngineImportService = engineImportService;
     TimeProvider = timeProvider;
     VariableService = variableService;
     TableService = tableService;
     EventAdapterService = eventAdapterService;
     FilterBooleanExpressionFactory = filterBooleanExpressionFactory;
     ScriptingService = scriptingService;
     Annotations = annotations;
     ContextDescriptor = contextDescriptor;
     ConfigurationInformation = configurationInformation;
     StatementExtensionSvcContext = statementExtensionSvcContext;
 }
Beispiel #34
0
        private async Task <Mock <RequestContext <ScriptingScriptAsResult> > > SendAndValidateScriptRequest(ScriptOperation operation)
        {
            var result         = GetLiveAutoCompleteTestObjects();
            var requestContext = new Mock <RequestContext <ScriptingScriptAsResult> >();

            requestContext.Setup(x => x.SendResult(It.IsAny <ScriptingScriptAsResult>())).Returns(Task.FromResult(new object()));

            var scriptingParams = new ScriptingScriptAsParams
            {
                OwnerUri  = result.ConnectionInfo.OwnerUri,
                Operation = operation,
                Metadata  = new ObjectMetadata()
                {
                    MetadataType     = MetadataType.Table,
                    MetadataTypeName = "Table",
                    Schema           = SchemaName,
                    Name             = TableName
                }
            };

            await ScriptingService.HandleScriptingScriptAsRequest(scriptingParams, requestContext.Object);

            return(requestContext);
        }
Beispiel #35
0
 /// <summary>Dispose services. </summary>
 public void Dispose()
 {
     if (ScriptingService != null)
     {
         ScriptingService.Dispose();
     }
     if (ExprDeclaredService != null)
     {
         ExprDeclaredService.Dispose();
     }
     if (DataFlowService != null)
     {
         DataFlowService.Dispose();
     }
     if (VariableService != null)
     {
         VariableService.Dispose();
     }
     if (MetricsReportingService != null)
     {
         MetricsReportingService.Dispose();
     }
     if (ThreadingService != null)
     {
         ThreadingService.Dispose();
     }
     if (StatementLifecycleSvc != null)
     {
         StatementLifecycleSvc.Dispose();
     }
     if (FilterService != null)
     {
         FilterService.Dispose();
     }
     if (SchedulingService != null)
     {
         SchedulingService.Dispose();
     }
     if (SchedulingMgmtService != null)
     {
         SchedulingMgmtService.Dispose();
     }
     if (StreamService != null)
     {
         StreamService.Destroy();
     }
     if (NamedWindowMgmtService != null)
     {
         NamedWindowMgmtService.Dispose();
     }
     if (NamedWindowDispatchService != null)
     {
         NamedWindowDispatchService.Dispose();
     }
     if (EngineLevelExtensionServicesContext != null)
     {
         EngineLevelExtensionServicesContext.Dispose();
     }
     if (StatementIsolationService != null)
     {
         StatementIsolationService.Dispose();
     }
     if (DeploymentStateService != null)
     {
         DeploymentStateService.Dispose();
     }
 }
Beispiel #36
0
        // Supplied after construction to avoid circular dependency

        /// <summary>
        /// Constructor - sets up new set of services.
        /// </summary>
        /// <param name="engineURI">is the engine URI</param>
        /// <param name="schedulingService">service to get time and schedule callbacks</param>
        /// <param name="eventAdapterService">service to resolve event types</param>
        /// <param name="engineImportService">is engine imported static func packages and aggregation functions</param>
        /// <param name="engineSettingsService">provides engine settings</param>
        /// <param name="databaseConfigService">service to resolve a database name to database connection factory and configs</param>
        /// <param name="plugInViews">resolves view namespace and name to view factory class</param>
        /// <param name="statementLockFactory">creates statement-level locks</param>
        /// <param name="eventProcessingRWLock">is the engine lock for statement management</param>
        /// <param name="extensionServicesContext">marker interface allows adding additional services</param>
        /// <param name="engineEnvContext">is engine environment/directory information for use with adapters and external env</param>
        /// <param name="statementContextFactory">is the factory to use to create statement context objects</param>
        /// <param name="plugInPatternObjects">resolves plug-in pattern objects</param>
        /// <param name="timerService">is the timer service</param>
        /// <param name="filterService">the filter service</param>
        /// <param name="streamFactoryService">is hooking up filters to streams</param>
        /// <param name="namedWindowMgmtService">The named window MGMT service.</param>
        /// <param name="namedWindowDispatchService">The named window dispatch service.</param>
        /// <param name="variableService">provides access to variable values</param>
        /// <param name="tableService">The table service.</param>
        /// <param name="timeSourceService">time source provider class</param>
        /// <param name="valueAddEventService">handles Update events</param>
        /// <param name="metricsReportingService">for metric reporting</param>
        /// <param name="statementEventTypeRef">statement to event type reference holding</param>
        /// <param name="statementVariableRef">statement to variabke reference holding</param>
        /// <param name="configSnapshot">configuration snapshot</param>
        /// <param name="threadingServiceImpl">engine-level threading services</param>
        /// <param name="internalEventRouter">routing of events</param>
        /// <param name="statementIsolationService">maintains isolation information per statement</param>
        /// <param name="schedulingMgmtService">schedule management for statements</param>
        /// <param name="deploymentStateService">The deployment state service.</param>
        /// <param name="exceptionHandlingService">The exception handling service.</param>
        /// <param name="patternNodeFactory">The pattern node factory.</param>
        /// <param name="eventTypeIdGenerator">The event type id generator.</param>
        /// <param name="statementMetadataFactory">The statement metadata factory.</param>
        /// <param name="contextManagementService">The context management service.</param>
        /// <param name="patternSubexpressionPoolSvc">The pattern subexpression pool SVC.</param>
        /// <param name="matchRecognizeStatePoolEngineSvc">The match recognize state pool engine SVC.</param>
        /// <param name="dataFlowService">The data flow service.</param>
        /// <param name="exprDeclaredService">The expr declared service.</param>
        /// <param name="contextControllerFactoryFactorySvc">The context controller factory factory SVC.</param>
        /// <param name="contextManagerFactoryService">The context manager factory service.</param>
        /// <param name="epStatementFactory">The ep statement factory.</param>
        /// <param name="regexHandlerFactory">The regex handler factory.</param>
        /// <param name="viewableActivatorFactory">The viewable activator factory.</param>
        /// <param name="filterNonPropertyRegisteryService">The filter non property registery service.</param>
        /// <param name="resultSetProcessorHelperFactory">The result set processor helper factory.</param>
        /// <param name="viewServicePreviousFactory">The view service previous factory.</param>
        /// <param name="eventTableIndexService">The event table index service.</param>
        /// <param name="epRuntimeIsolatedFactory">The ep runtime isolated factory.</param>
        /// <param name="filterBooleanExpressionFactory">The filter boolean expression factory.</param>
        /// <param name="dataCacheFactory">The data cache factory.</param>
        /// <param name="multiMatchHandlerFactory">The multi match handler factory.</param>
        /// <param name="namedWindowConsumerMgmtService">The named window consumer MGMT service.</param>
        /// <param name="aggregationFactoryFactory"></param>
        /// <param name="scriptingService">The scripting service.</param>
        public EPServicesContext(
            string engineURI,
            SchedulingServiceSPI schedulingService,
            EventAdapterService eventAdapterService,
            EngineImportService engineImportService,
            EngineSettingsService engineSettingsService,
            DatabaseConfigService databaseConfigService,
            PluggableObjectCollection plugInViews,
            StatementLockFactory statementLockFactory,
            IReaderWriterLock eventProcessingRWLock,
            EngineLevelExtensionServicesContext extensionServicesContext,
            Directory engineEnvContext,
            StatementContextFactory statementContextFactory,
            PluggableObjectCollection plugInPatternObjects,
            TimerService timerService,
            FilterServiceSPI filterService,
            StreamFactoryService streamFactoryService,
            NamedWindowMgmtService namedWindowMgmtService,
            NamedWindowDispatchService namedWindowDispatchService,
            VariableService variableService,
            TableService tableService,
            TimeSourceService timeSourceService,
            ValueAddEventService valueAddEventService,
            MetricReportingServiceSPI metricsReportingService,
            StatementEventTypeRef statementEventTypeRef,
            StatementVariableRef statementVariableRef,
            ConfigurationInformation configSnapshot,
            ThreadingService threadingServiceImpl,
            InternalEventRouterImpl internalEventRouter,
            StatementIsolationService statementIsolationService,
            SchedulingMgmtService schedulingMgmtService,
            DeploymentStateService deploymentStateService,
            ExceptionHandlingService exceptionHandlingService,
            PatternNodeFactory patternNodeFactory,
            EventTypeIdGenerator eventTypeIdGenerator,
            StatementMetadataFactory statementMetadataFactory,
            ContextManagementService contextManagementService,
            PatternSubexpressionPoolEngineSvc patternSubexpressionPoolSvc,
            MatchRecognizeStatePoolEngineSvc matchRecognizeStatePoolEngineSvc,
            DataFlowService dataFlowService,
            ExprDeclaredService exprDeclaredService,
            ContextControllerFactoryFactorySvc contextControllerFactoryFactorySvc,
            ContextManagerFactoryService contextManagerFactoryService,
            EPStatementFactory epStatementFactory,
            RegexHandlerFactory regexHandlerFactory,
            ViewableActivatorFactory viewableActivatorFactory,
            FilterNonPropertyRegisteryService filterNonPropertyRegisteryService,
            ResultSetProcessorHelperFactory resultSetProcessorHelperFactory,
            ViewServicePreviousFactory viewServicePreviousFactory,
            EventTableIndexService eventTableIndexService,
            EPRuntimeIsolatedFactory epRuntimeIsolatedFactory,
            FilterBooleanExpressionFactory filterBooleanExpressionFactory,
            DataCacheFactory dataCacheFactory,
            MultiMatchHandlerFactory multiMatchHandlerFactory,
            NamedWindowConsumerMgmtService namedWindowConsumerMgmtService,
            AggregationFactoryFactory aggregationFactoryFactory,
            ScriptingService scriptingService)
        {
            EngineURI             = engineURI;
            SchedulingService     = schedulingService;
            EventAdapterService   = eventAdapterService;
            EngineImportService   = engineImportService;
            EngineSettingsService = engineSettingsService;
            DatabaseRefService    = databaseConfigService;
            FilterService         = filterService;
            TimerService          = timerService;
            DispatchService       = DispatchServiceProvider.NewService();
            ViewService           = ViewServiceProvider.NewService();
            StreamService         = streamFactoryService;
            PlugInViews           = plugInViews;
            StatementLockFactory  = statementLockFactory;
            EventProcessingRWLock = eventProcessingRWLock;
            EngineLevelExtensionServicesContext = extensionServicesContext;
            EngineEnvContext           = engineEnvContext;
            StatementContextFactory    = statementContextFactory;
            PlugInPatternObjects       = plugInPatternObjects;
            NamedWindowMgmtService     = namedWindowMgmtService;
            NamedWindowDispatchService = namedWindowDispatchService;
            VariableService            = variableService;
            TableService                     = tableService;
            TimeSource                       = timeSourceService;
            ValueAddEventService             = valueAddEventService;
            MetricsReportingService          = metricsReportingService;
            StatementEventTypeRefService     = statementEventTypeRef;
            ConfigSnapshot                   = configSnapshot;
            ThreadingService                 = threadingServiceImpl;
            InternalEventRouter              = internalEventRouter;
            StatementIsolationService        = statementIsolationService;
            SchedulingMgmtService            = schedulingMgmtService;
            StatementVariableRefService      = statementVariableRef;
            DeploymentStateService           = deploymentStateService;
            ExceptionHandlingService         = exceptionHandlingService;
            PatternNodeFactory               = patternNodeFactory;
            EventTypeIdGenerator             = eventTypeIdGenerator;
            StatementMetadataFactory         = statementMetadataFactory;
            ContextManagementService         = contextManagementService;
            PatternSubexpressionPoolSvc      = patternSubexpressionPoolSvc;
            MatchRecognizeStatePoolEngineSvc = matchRecognizeStatePoolEngineSvc;
            DataFlowService                  = dataFlowService;
            ExprDeclaredService              = exprDeclaredService;
            ExpressionResultCacheSharable    = new ExpressionResultCacheService(
                configSnapshot.EngineDefaults.ExecutionConfig.DeclaredExprValueCacheSize);
            ContextControllerFactoryFactorySvc = contextControllerFactoryFactorySvc;
            ContextManagerFactoryService       = contextManagerFactoryService;
            EpStatementFactory                = epStatementFactory;
            RegexHandlerFactory               = regexHandlerFactory;
            ViewableActivatorFactory          = viewableActivatorFactory;
            FilterNonPropertyRegisteryService = filterNonPropertyRegisteryService;
            ResultSetProcessorHelperFactory   = resultSetProcessorHelperFactory;
            ViewServicePreviousFactory        = viewServicePreviousFactory;
            EventTableIndexService            = eventTableIndexService;
            EpRuntimeIsolatedFactory          = epRuntimeIsolatedFactory;
            FilterBooleanExpressionFactory    = filterBooleanExpressionFactory;
            DataCacheFactory               = dataCacheFactory;
            MultiMatchHandlerFactory       = multiMatchHandlerFactory;
            NamedWindowConsumerMgmtService = namedWindowConsumerMgmtService;
            AggregationFactoryFactory      = aggregationFactoryFactory;
            ScriptingService               = scriptingService;
        }
Beispiel #37
0
        public void Validate(
            EngineImportService engineImportService,
            StreamTypeService streamTypeService,
            TimeProvider timeProvider,
            VariableService variableService,
            TableService tableService,
            ScriptingService scriptingService,
            ExprEvaluatorContext exprEvaluatorContext,
            ConfigurationInformation configSnapshot,
            SchedulingService schedulingService,
            string engineURI,
            IDictionary <int, IList <ExprNode> > sqlParameters,
            EventAdapterService eventAdapterService,
            StatementContext statementContext)
        {
            _statementContext = statementContext;

            // validate and visit
            var validationContext        = new ExprValidationContext(streamTypeService, engineImportService, statementContext.StatementExtensionServicesContext, null, timeProvider, variableService, tableService, exprEvaluatorContext, eventAdapterService, statementContext.StatementName, statementContext.StatementId, statementContext.Annotations, null, statementContext.ScriptingService, false, false, true, false, null, false);
            var visitor                  = new ExprNodeIdentifierVisitor(true);
            var validatedInputParameters = new List <ExprNode>();

            foreach (var exprNode in _methodStreamSpec.Expressions)
            {
                var validated = ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.METHODINVJOIN, exprNode, validationContext);
                validatedInputParameters.Add(validated);
                validated.Accept(visitor);
            }

            // determine required streams
            _requiredStreams = new SortedSet <int>();
            foreach (var identifier in visitor.ExprProperties)
            {
                _requiredStreams.Add(identifier.First);
            }

            // class-based evaluation
            if (_metadata.MethodProviderClass != null)
            {
                // resolve actual method to use
                var handler = new ProxyExprNodeUtilResolveExceptionHandler {
                    ProcHandle = e => {
                        if (_methodStreamSpec.Expressions.Count == 0)
                        {
                            return(new ExprValidationException("Method footprint does not match the number or type of expression parameters, expecting no parameters in method: " + e.Message, e));
                        }
                        var resultTypes = ExprNodeUtility.GetExprResultTypes(validatedInputParameters);
                        return(new ExprValidationException(
                                   string.Format("Method footprint does not match the number or type of expression parameters, expecting a method where parameters are typed '{0}': {1}", TypeHelper.GetParameterAsString(resultTypes), e.Message), e));
                    }
                };
                var desc = ExprNodeUtility.ResolveMethodAllowWildcardAndStream(
                    _metadata.MethodProviderClass.FullName, _metadata.IsStaticMethod ? null : _metadata.MethodProviderClass,
                    _methodStreamSpec.MethodName, validatedInputParameters, engineImportService, eventAdapterService, statementContext.StatementId,
                    false, null, handler, _methodStreamSpec.MethodName, tableService, statementContext.EngineURI);
                _validatedExprNodes = desc.ChildEvals;

                // Construct polling strategy as a method invocation
                var invocationTarget = _metadata.InvocationTarget;
                var strategy         = _metadata.Strategy;
                var variableReader   = _metadata.VariableReader;
                var variableName     = _metadata.VariableName;
                var methodFastClass  = desc.FastMethod;
                if (_metadata.EventTypeEventBeanArray != null)
                {
                    _pollExecStrategy = new MethodPollingExecStrategyEventBeans(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                }
                else if (_metadata.OptionalMapType != null)
                {
                    if (desc.FastMethod.ReturnType.IsArray)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyMapArray(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else if (_metadata.IsCollection)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyMapCollection(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else if (_metadata.IsEnumerator)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyMapIterator(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyMapPlain(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                }
                else if (_metadata.OptionalOaType != null)
                {
                    if (desc.FastMethod.ReturnType == typeof(Object[][]))
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyOAArray(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else if (_metadata.IsCollection)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyOACollection(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else if (_metadata.IsEnumerator)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyOAIterator(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyOAPlain(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                }
                else
                {
                    if (desc.FastMethod.ReturnType.IsArray)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyPONOArray(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else if (_metadata.IsCollection)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyPONOCollection(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else if (_metadata.IsEnumerator)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyPONOIterator(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyPONOPlain(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                }
            }
            else
            {
                // script-based evaluation
                _pollExecStrategy   = new MethodPollingExecStrategyScript(_metadata.ScriptExpression, _metadata.EventTypeEventBeanArray);
                _validatedExprNodes = ExprNodeUtility.GetEvaluators(validatedInputParameters);
            }
        }
Beispiel #38
0
        public void Validate(
            EngineImportService engineImportService,
            StreamTypeService streamTypeService,
            MethodResolutionService methodResolutionService,
            TimeProvider timeProvider,
            VariableService variableService,
            TableService tableService,
            ScriptingService scriptingService,
            ExprEvaluatorContext exprEvaluatorContext,
            ConfigurationInformation configSnapshot,
            SchedulingService schedulingService,
            string engineURI,
            IDictionary <int, IList <ExprNode> > sqlParameters,
            EventAdapterService eventAdapterService,
            string statementName,
            string statementId,
            Attribute[] annotations)
        {
            // validate and visit
            var validationContext = new ExprValidationContext(
                streamTypeService, methodResolutionService, null, timeProvider, variableService, tableService,
                exprEvaluatorContext, eventAdapterService, statementName, statementId, annotations, null,
                scriptingService, false, false, true, false, null, false);
            var visitor = new ExprNodeIdentifierVisitor(true);
            IList <ExprNode> validatedInputParameters = new List <ExprNode>();

            foreach (var exprNode in _inputParameters)
            {
                var validated = ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.METHODINVJOIN, exprNode, validationContext);
                validatedInputParameters.Add(validated);
                validated.Accept(visitor);
            }

            // determine required streams
            _requiredStreams = new SortedSet <int>();
            foreach (var identifier in visitor.ExprProperties)
            {
                _requiredStreams.Add(identifier.First);
            }

            ExprNodeUtilResolveExceptionHandler handler = new ProxyExprNodeUtilResolveExceptionHandler()
            {
                ProcHandle = (e) => {
                    if (_inputParameters.Count == 0)
                    {
                        return(new ExprValidationException("Method footprint does not match the number or type of expression parameters, expecting no parameters in method: " + e.Message));
                    }
                    var resultTypes = ExprNodeUtility.GetExprResultTypes(validatedInputParameters);
                    return(new ExprValidationException("Method footprint does not match the number or type of expression parameters, expecting a method where parameters are typed '" +
                                                       TypeHelper.GetParameterAsString(resultTypes) + "': " + e.Message));
                },
            };

            var desc = ExprNodeUtility.ResolveMethodAllowWildcardAndStream(
                _methodProviderClass.FullName,
                _isStaticMethod ? null : _methodProviderClass,
                _methodStreamSpec.MethodName, validatedInputParameters, methodResolutionService, eventAdapterService, statementId,
                false, null, handler,
                _methodStreamSpec.MethodName, tableService);

            _validatedExprNodes = desc.ChildEvals;
        }
 public AtfScriptVariables(ScriptingService scriptService)
 {
     m_scriptingService = scriptService;
 }
Beispiel #40
0
 /// <summary>
 /// Constructor for when MEF isn't used. The caller is responsible for registering
 /// the Control with a control host service, if applicable.</summary>
 /// <param name="scriptService">ScriptingService to expose C# objects to a scripting language</param>
 /// <param name="controlHostService">Control host service</param>
 public ScriptConsole(ScriptingService scriptService, IControlHostService controlHostService)
     : this()
 {
     m_controlHostService = controlHostService;
     m_scriptService = scriptService;
 }
Beispiel #41
0
 /// <summary>
 /// Constructor for when MEF isn't used. The caller is responsible for registering
 /// the Control with a control host service, if applicable.</summary>
 /// <param name="scriptService">ScriptingService to expose C# objects to a scripting language</param>
 public ScriptConsole(ScriptingService scriptService)
     : this()
 {
     m_scriptService = scriptService;
 }
        public async Task AddAndInvokeClickHandlerWillChangeCapturedValue()
        {
            var service = new ScriptingService();
            var cfg = Configuration.Default.With(service);
            var html = @"<!doctype html>
<html>
<body>
<script>
var clicked = false;
document.onclick = function () {
    clicked = true;
};
document.onclick();
</script>
</body>";
            var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html));
            var clicked = service.Engine.GetJint(document).GetValue("clicked").AsBoolean();
            Assert.IsTrue(clicked);
        }
Beispiel #43
0
 public void SetPythonScriptService(ScriptingService scriptService)
 {
     if (m_pythonService != null) return; // it is already set.            
     m_pythonService = (BasicPythonService)scriptService;
 }
 public StandardViewCommands(ICommandService commandService, IContextRegistry contextRegistry, ScriptingService scriptingService)
 {
     m_commandService = commandService;
     m_contextRegistry = contextRegistry;
     m_scriptingService = scriptingService;
 }
Beispiel #45
0
 public void Initialize(ScriptingService scriptingService)
 {
     scriptingService.LoadAssembly(GetType().Assembly);
 }