public override View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
        {
            var builtinBean  = new ObjectArrayEventBean(ExpressionViewOAFieldEnumExtensions.GetPrototypeOA(), BuiltinMapType);
            var randomAccess = ViewServiceHelper.GetOptPreviousExprRandomAccess(agentInstanceViewFactoryContext);

            return(new ExpressionWindowView(this, randomAccess, ExpiryExpression.ExprEvaluator, AggregationServiceFactoryDesc, builtinBean, VariableNames, agentInstanceViewFactoryContext));
        }
Ejemplo n.º 2
0
        public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
        {
            IStreamRelativeAccess relativeAccessByEvent =
                ViewServiceHelper.GetOptPreviousExprRelativeAccess(agentInstanceViewFactoryContext);

            return(new TimeLengthBatchView(
                       this, agentInstanceViewFactoryContext, timeDeltaComputation, NumberOfEvents, isForceUpdate,
                       isStartEager, relativeAccessByEvent));
        }
Ejemplo n.º 3
0
        public void check_that_the_correct_view_is_resolved_from_the_viewmodel_UseViewAttribute()
        {
            var container = AutoMock.GetStrict();

            container.Provide <IDispatcherSchedulerProvider>(new TestDispatcherSchedulerProvider());

            var viewModel = container.Create <StubViewModelWithUseViewAttribute>();

            var view = ViewServiceHelper.CreateView(viewModel.GetType());

            Assert.That(view.GetType(), Is.EqualTo(typeof(StubViewNameNotMatchingView)));
        }
Ejemplo n.º 4
0
        public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
        {
            IStreamRandomAccess randomAccess = ViewServiceHelper.GetOptPreviousExprRandomAccess(agentInstanceViewFactoryContext);

            if (agentInstanceViewFactoryContext.IsRemoveStream)
            {
                return(new LengthWindowViewRStream(agentInstanceViewFactoryContext, this, Size));
            }
            else
            {
                return(new LengthWindowView(agentInstanceViewFactoryContext, this, Size, randomAccess));
            }
        }
Ejemplo n.º 5
0
        public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
        {
            IStreamRelativeAccess relativeAccessByEvent = ViewServiceHelper.GetOptPreviousExprRelativeAccess(agentInstanceViewFactoryContext);

            if (agentInstanceViewFactoryContext.IsRemoveStream)
            {
                return(new LengthBatchViewRStream(agentInstanceViewFactoryContext, this, Size));
            }
            else
            {
                return(new LengthBatchView(agentInstanceViewFactoryContext, this, Size, relativeAccessByEvent));
            }
        }
Ejemplo n.º 6
0
        public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
        {
            IStreamRandomAccess randomAccess = ViewServiceHelper.GetOptPreviousExprRandomAccess(agentInstanceViewFactoryContext);

            if (agentInstanceViewFactoryContext.IsRemoveStream)
            {
                return(new TimeAccumViewRStream(this, agentInstanceViewFactoryContext, _timeDeltaComputation));
            }
            else
            {
                return(new TimeAccumView(this, agentInstanceViewFactoryContext, _timeDeltaComputation, randomAccess));
            }
        }
Ejemplo n.º 7
0
        public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
        {
            IStreamRelativeAccess relativeAccessByEvent = ViewServiceHelper.GetOptPreviousExprRelativeAccess(agentInstanceViewFactoryContext);

            if (agentInstanceViewFactoryContext.IsRemoveStream)
            {
                return(new TimeBatchViewRStream(this, agentInstanceViewFactoryContext, timeDeltaComputation, OptionalReferencePoint, isForceUpdate, isStartEager));
            }
            else
            {
                return(new TimeBatchView(this, agentInstanceViewFactoryContext, timeDeltaComputation, OptionalReferencePoint, isForceUpdate, isStartEager, relativeAccessByEvent));
            }
        }
Ejemplo n.º 8
0
        private void CreateAndShowShell()
        {
            // Setup the Shell
            var shellView = ViewServiceHelper.CreateView(_shellViewModel.GetType());

            ViewServiceHelper.BindViewModel(shellView, _shellViewModel);

            // Setup application shutdown
            Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;

            // Show the Shell and activate it
            Application.Current.MainWindow = (Window)shellView;
            Application.Current.MainWindow.Show();
            Application.Current.MainWindow.Activate();
        }
Ejemplo n.º 9
0
 public void AddUniquenessInfo(ViewFactoryChain[] unmaterializedViewChain, Attribute[] annotations)
 {
     for (int i = 0; i < unmaterializedViewChain.Length; i++)
     {
         if (unmaterializedViewChain[i].DataWindowViewFactoryCount > 0)
         {
             var uniquenessProps = ViewServiceHelper.GetUniqueCandidateProperties(unmaterializedViewChain[i].FactoryChain, annotations);
             if (uniquenessProps != null)
             {
                 _uniqueKeys[i]    = new String[1][];
                 _uniqueKeys[i][0] = uniquenessProps.ToArray();
             }
         }
     }
 }
Ejemplo n.º 10
0
        public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
        {
            var sortedRandomAccess = ViewServiceHelper.GetOptPreviousExprSortedRankedAccess(agentInstanceViewFactoryContext);

            var useCollatorSort = false;

            if (agentInstanceViewFactoryContext.AgentInstanceContext.StatementContext.ConfigSnapshot != null)
            {
                useCollatorSort = agentInstanceViewFactoryContext.AgentInstanceContext.StatementContext.ConfigSnapshot.EngineDefaults.LanguageConfig.IsSortUsingCollator;
            }

            var childEvals = ExprNodeUtility.GetEvaluators(sortCriteriaExpressions);

            return(new SortWindowView(this, sortCriteriaExpressions, childEvals, isDescendingValues, sortWindowSize, sortedRandomAccess, useCollatorSort, agentInstanceViewFactoryContext));
        }
Ejemplo n.º 11
0
        public void check_viewmodel_is_set_as_the_datacontext_of_the_view()
        {
            var container = AutoMock.GetStrict();

            container.Provide <IDispatcherSchedulerProvider>(new TestDispatcherSchedulerProvider());

            var view = new UserControl();

            Assert.That(view.DataContext, Is.Null);

            var viewModel = container.Create <StubViewModel>();

            ViewServiceHelper.BindViewModel(view, viewModel);

            Assert.That(view.DataContext, Is.EqualTo(viewModel));
        }
Ejemplo n.º 12
0
        public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
        {
            IStreamRandomAccess randomAccess = ViewServiceHelper.GetOptPreviousExprRandomAccess(agentInstanceViewFactoryContext);

            return(new KeepAllView(agentInstanceViewFactoryContext, this, randomAccess));
        }
Ejemplo n.º 13
0
        public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
        {
            IStreamRandomAccess randomAccess = ViewServiceHelper.GetOptPreviousExprRandomAccess(agentInstanceViewFactoryContext);

            return(new ExternallyTimedWindowView(this, TimestampExpression, TimestampExpressionEval, TimeDeltaComputation, randomAccess, agentInstanceViewFactoryContext));
        }
        protected override StatementAgentInstanceFactoryResult NewContextInternal(AgentInstanceContext agentInstanceContext, bool isRecoveringResilient)
        {
            IList <StopCallback> stopCallbacks = new List <StopCallback>(2);

            Viewable finalView;
            var      viewableActivationResult = new ViewableActivationResult[_eventStreamParentViewableActivators.Length];
            IDictionary <ExprSubselectNode, SubSelectStrategyHolder> subselectStrategies;
            AggregationService aggregationService;

            Viewable[] streamViews;
            Viewable[] eventStreamParentViewable;
            Viewable[] topViews;
            IDictionary <ExprPriorNode, ExprPriorEvalStrategy>             priorNodeStrategies;
            IDictionary <ExprPreviousNode, ExprPreviousEvalStrategy>       previousNodeStrategies;
            IDictionary <ExprTableAccessNode, ExprTableAccessEvalStrategy> tableAccessStrategies;
            RegexExprPreviousEvalStrategy         regexExprPreviousEvalStrategy = null;
            IList <StatementAgentInstancePreload> preloadList = new List <StatementAgentInstancePreload>();

            EvalRootState[] patternRoots;
            StatementAgentInstancePostLoad postLoadJoin = null;
            var suppressSameEventMatches = false;
            var discardPartialsOnMatch   = false;
            EvalRootMatchRemover evalRootMatchRemover = null;

            try {
                // create root viewables
                eventStreamParentViewable = new Viewable[_numStreams];
                patternRoots = new EvalRootState[_numStreams];

                for (var stream = 0; stream < _eventStreamParentViewableActivators.Length; stream++)
                {
                    var activationResult = _eventStreamParentViewableActivators[stream].Activate(agentInstanceContext, false, isRecoveringResilient);
                    viewableActivationResult[stream] = activationResult;
                    stopCallbacks.Add(activationResult.StopCallback);
                    suppressSameEventMatches = activationResult.IsSuppressSameEventMatches;
                    discardPartialsOnMatch   = activationResult.IsDiscardPartialsOnMatch;

                    // add stop callback for any stream-level viewable when applicable
                    if (activationResult.Viewable is StopCallback)
                    {
                        stopCallbacks.Add((StopCallback)activationResult.Viewable);
                    }

                    eventStreamParentViewable[stream] = activationResult.Viewable;
                    patternRoots[stream] = activationResult.OptionalPatternRoot;
                    if (stream == 0)
                    {
                        evalRootMatchRemover = activationResult.OptEvalRootMatchRemover;
                    }

                    if (activationResult.OptionalLock != null)
                    {
                        agentInstanceContext.EpStatementAgentInstanceHandle.StatementAgentInstanceLock = activationResult.OptionalLock;
                        _statementContext.DefaultAgentInstanceLock = activationResult.OptionalLock;
                    }
                }

                // compile view factories adding "prior" as necessary
                var viewFactoryChains = new IList <ViewFactory> [_numStreams];
                for (var i = 0; i < _numStreams; i++)
                {
                    var viewFactoryChain = _unmaterializedViewChain[i].FactoryChain;

                    // add "prior" view factory
                    var hasPrior = _viewResourceDelegate.PerStream[i].PriorRequests != null && !_viewResourceDelegate.PerStream[i].PriorRequests.IsEmpty();
                    if (hasPrior)
                    {
                        var priorEventViewFactory = EPStatementStartMethodHelperPrior.GetPriorEventViewFactory(
                            agentInstanceContext.StatementContext, i, viewFactoryChain.IsEmpty(), false, -1);
                        viewFactoryChain = new List <ViewFactory>(viewFactoryChain);
                        viewFactoryChain.Add(priorEventViewFactory);
                    }
                    viewFactoryChains[i] = viewFactoryChain;
                }

                // create view factory chain context: holds stream-specific services
                var viewFactoryChainContexts = new AgentInstanceViewFactoryChainContext[_numStreams];
                for (var i = 0; i < _numStreams; i++)
                {
                    viewFactoryChainContexts[i] = AgentInstanceViewFactoryChainContext.Create(viewFactoryChains[i], agentInstanceContext, _viewResourceDelegate.PerStream[i]);
                }

                // handle "prior" nodes and their strategies
                priorNodeStrategies = EPStatementStartMethodHelperPrior.CompilePriorNodeStrategies(_viewResourceDelegate, viewFactoryChainContexts);

                // handle "previous" nodes and their strategies
                previousNodeStrategies = EPStatementStartMethodHelperPrevious.CompilePreviousNodeStrategies(_viewResourceDelegate, viewFactoryChainContexts);

                // materialize views
                streamViews = new Viewable[_numStreams];
                topViews    = new Viewable[_numStreams];
                for (var i = 0; i < _numStreams; i++)
                {
                    var hasPreviousNode = _viewResourceDelegate.PerStream[i].PreviousRequests != null && !_viewResourceDelegate.PerStream[i].PreviousRequests.IsEmpty();

                    var createResult = _services.ViewService.CreateViews(eventStreamParentViewable[i], viewFactoryChains[i], viewFactoryChainContexts[i], hasPreviousNode);
                    topViews[i]    = createResult.TopViewable;
                    streamViews[i] = createResult.FinalViewable;

                    var isReuseableView = _eventStreamParentViewableActivators[i] is ViewableActivatorStreamReuseView;
                    if (isReuseableView)
                    {
                        var viewsCreated = createResult.NewViews;
                        var stopCallback = new ProxyStopCallback(() => {
                            ViewServiceHelper.RemoveFirstUnsharedView(viewsCreated);
                        });
                        stopCallbacks.Add(stopCallback);
                    }

                    // add views to stop callback if applicable
                    AddViewStopCallback(stopCallbacks, createResult.NewViews);
                }

                // determine match-recognize "previous"-node strategy (none if not present, or one handling and number of nodes)
                var matchRecognize = EventRowRegexHelper.RecursiveFindRegexService(topViews[0]);
                if (matchRecognize != null)
                {
                    regexExprPreviousEvalStrategy = matchRecognize.PreviousEvaluationStrategy;
                    stopCallbacks.Add(new ProxyStopCallback(matchRecognize.Stop));
                }

                // start subselects
                subselectStrategies = EPStatementStartMethodHelperSubselect.StartSubselects(_services, _subSelectStrategyCollection, agentInstanceContext, stopCallbacks, isRecoveringResilient);

                // plan table access
                tableAccessStrategies = EPStatementStartMethodHelperTableAccess.AttachTableAccess(_services, agentInstanceContext, _statementSpec.TableNodes);

                // obtain result set processor and aggregation services
                var processorPair      = EPStatementStartMethodHelperUtil.StartResultSetAndAggregation(_resultSetProcessorFactoryDesc, agentInstanceContext, false, null);
                var resultSetProcessor = processorPair.First;
                aggregationService = processorPair.Second;
                stopCallbacks.Add(aggregationService);
                stopCallbacks.Add(resultSetProcessor);

                // for just 1 event stream without joins, handle the one-table process separately.
                JoinPreloadMethod   joinPreloadMethod;
                JoinSetComposerDesc joinSetComposer = null;
                if (streamViews.Length == 1)
                {
                    finalView         = HandleSimpleSelect(streamViews[0], resultSetProcessor, agentInstanceContext, evalRootMatchRemover, suppressSameEventMatches, discardPartialsOnMatch);
                    joinPreloadMethod = null;
                }
                else
                {
                    var joinPlanResult = HandleJoin(_typeService.StreamNames, streamViews, resultSetProcessor,
                                                    agentInstanceContext, stopCallbacks, _joinAnalysisResult, isRecoveringResilient);
                    finalView         = joinPlanResult.Viewable;
                    joinPreloadMethod = joinPlanResult.PreloadMethod;
                    joinSetComposer   = joinPlanResult.JoinSetComposerDesc;
                }

                // for stoppable final views, add callback
                if (finalView is StopCallback)
                {
                    stopCallbacks.Add((StopCallback)finalView);
                }

                // Replay any named window data, for later consumers of named data windows
                if (_services.EventTableIndexService.AllowInitIndex(isRecoveringResilient))
                {
                    var hasNamedWindow             = false;
                    var namedWindowPostloadFilters = new FilterSpecCompiled[_statementSpec.StreamSpecs.Length];
                    var namedWindowTailViews       = new NamedWindowTailViewInstance[_statementSpec.StreamSpecs.Length];
                    var namedWindowFilters         = new IList <ExprNode> [_statementSpec.StreamSpecs.Length];

                    for (var i = 0; i < _statementSpec.StreamSpecs.Length; i++)
                    {
                        var streamNum  = i;
                        var streamSpec = _statementSpec.StreamSpecs[i];

                        if (streamSpec is NamedWindowConsumerStreamSpec)
                        {
                            hasNamedWindow = true;
                            var namedSpec = (NamedWindowConsumerStreamSpec)streamSpec;
                            NamedWindowProcessor processor = _services.NamedWindowMgmtService.GetProcessor(namedSpec.WindowName);
                            var processorInstance          = processor.GetProcessorInstance(agentInstanceContext);
                            if (processorInstance != null)
                            {
                                var consumerView = processorInstance.TailViewInstance;
                                namedWindowTailViews[i] = consumerView;
                                var view = (NamedWindowConsumerView)viewableActivationResult[i].Viewable;

                                // determine preload/postload filter for index access
                                if (!namedSpec.FilterExpressions.IsEmpty())
                                {
                                    namedWindowFilters[streamNum] = namedSpec.FilterExpressions;
                                    try {
                                        var streamName = streamSpec.OptionalStreamName != null ? streamSpec.OptionalStreamName : consumerView.EventType.Name;
                                        var types      = new StreamTypeServiceImpl(consumerView.EventType, streamName, false, _services.EngineURI);
                                        var tagged     = new LinkedHashMap <string, Pair <EventType, string> >();
                                        namedWindowPostloadFilters[i] = FilterSpecCompiler.MakeFilterSpec(types.EventTypes[0], types.StreamNames[0],
                                                                                                          namedSpec.FilterExpressions, null, tagged, tagged, types, null, _statementContext, Collections.SingletonSet(0));
                                    }
                                    catch (Exception ex) {
                                        Log.Warn("Unexpected exception analyzing filter paths: " + ex.Message, ex);
                                    }
                                }

                                // preload view for stream unless the expiry policy is batch window
                                var preload = !consumerView.TailView.IsParentBatchWindow && consumerView.HasFirst();
                                if (preload)
                                {
                                    if (isRecoveringResilient && _numStreams < 2)
                                    {
                                        preload = false;
                                    }
                                }
                                if (preload)
                                {
                                    var yesRecoveringResilient = isRecoveringResilient;
                                    var preloadFilterSpec      = namedWindowPostloadFilters[i];
                                    preloadList.Add(new ProxyStatementAgentInstancePreload()
                                    {
                                        ProcExecutePreload = () => {
                                            var snapshot       = consumerView.Snapshot(preloadFilterSpec, _statementContext.Annotations);
                                            var eventsInWindow = new List <EventBean>(snapshot.Count);
                                            ExprNodeUtility.ApplyFilterExpressionsIterable(snapshot, namedSpec.FilterExpressions, agentInstanceContext, eventsInWindow);
                                            EventBean[] newEvents = eventsInWindow.ToArray();
                                            view.Update(newEvents, null);
                                            if (!yesRecoveringResilient && joinPreloadMethod != null && !joinPreloadMethod.IsPreloading && agentInstanceContext.EpStatementAgentInstanceHandle.OptionalDispatchable != null)
                                            {
                                                agentInstanceContext.EpStatementAgentInstanceHandle.OptionalDispatchable.Execute();
                                            }
                                        },
                                    });
                                }
                            }
                            else
                            {
                                Log.Info("Named window access is out-of-context, the named window '" + namedSpec.WindowName + "' has been declared for a different context then the current statement, the aggregation and join state will not be initialized for statement expression [" + _statementContext.Expression + "]");
                            }

                            preloadList.Add(new ProxyStatementAgentInstancePreload()
                            {
                                ProcExecutePreload = () => {
                                    // in a join, preload indexes, if any
                                    if (joinPreloadMethod != null)
                                    {
                                        joinPreloadMethod.PreloadFromBuffer(streamNum);
                                    }
                                    else
                                    {
                                        if (agentInstanceContext.EpStatementAgentInstanceHandle.OptionalDispatchable != null)
                                        {
                                            agentInstanceContext.EpStatementAgentInstanceHandle.OptionalDispatchable.Execute();
                                        }
                                    }
                                },
                            });
                        }
                    }

                    // last, for aggregation we need to send the current join results to the result set processor
                    if ((hasNamedWindow) && (joinPreloadMethod != null) && (!isRecoveringResilient) && _resultSetProcessorFactoryDesc.ResultSetProcessorFactory.HasAggregation)
                    {
                        preloadList.Add(new ProxyStatementAgentInstancePreload()
                        {
                            ProcExecutePreload = () => {
                                joinPreloadMethod.PreloadAggregation(resultSetProcessor);
                            },
                        });
                    }

                    if (isRecoveringResilient)
                    {
                        postLoadJoin = new StatementAgentInstancePostLoadSelect(streamViews, joinSetComposer, namedWindowTailViews, namedWindowPostloadFilters, namedWindowFilters, _statementContext.Annotations, agentInstanceContext);
                    }
                    else if (joinSetComposer != null)
                    {
                        postLoadJoin = new StatementAgentInstancePostLoadIndexVisiting(joinSetComposer.JoinSetComposer);
                    }
                }
            }
            catch (Exception) {
                var stopCallback = StatementAgentInstanceUtil.GetStopCallback(stopCallbacks, agentInstanceContext);
                StatementAgentInstanceUtil.StopSafe(stopCallback, _statementContext);
                if (InstrumentationHelper.ENABLED)
                {
                    InstrumentationHelper.Get().AContextPartitionAllocate();
                }
                throw;
            }

            var selectResult = new StatementAgentInstanceFactorySelectResult(finalView, null, agentInstanceContext, aggregationService, subselectStrategies, priorNodeStrategies, previousNodeStrategies, regexExprPreviousEvalStrategy, tableAccessStrategies, preloadList, patternRoots, postLoadJoin, topViews, eventStreamParentViewable, viewableActivationResult);

            if (_statementContext.StatementExtensionServicesContext != null)
            {
                _statementContext.StatementExtensionServicesContext.ContributeStopCallback(selectResult, stopCallbacks);
            }
            var stopCallbackX = StatementAgentInstanceUtil.GetStopCallback(stopCallbacks, agentInstanceContext);

            selectResult.StopCallback = stopCallbackX;

            return(selectResult);
        }
Ejemplo n.º 15
0
        public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
        {
            IStreamRelativeAccess relativeAccessByEvent = ViewServiceHelper.GetOptPreviousExprRelativeAccess(agentInstanceViewFactoryContext);

            return(new ExternallyTimedBatchView(this, TimestampExpression, TimestampExpressionEval, TimeDeltaComputation, OptionalReferencePoint, relativeAccessByEvent, agentInstanceViewFactoryContext));
        }
Ejemplo n.º 16
0
        public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
        {
            IStreamRandomAccess randomAccess = ViewServiceHelper.GetOptPreviousExprRandomAccess(agentInstanceViewFactoryContext);

            return(new TimeWindowView(agentInstanceViewFactoryContext, this, _timeDeltaComputation, randomAccess));
        }
Ejemplo n.º 17
0
        public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
        {
            var sortedRandomAccess = ViewServiceHelper.GetOptPreviousExprSortedRankedAccess(agentInstanceViewFactoryContext);

            return(new TimeOrderView(agentInstanceViewFactoryContext, this, TimestampExpression, TimestampExpression.ExprEvaluator, TimeDeltaComputation, sortedRandomAccess));
        }
        public override EPStatementStartResult StartInternal(
            EPServicesContext services,
            StatementContext statementContext,
            bool isNewStatement,
            bool isRecoveringStatement,
            bool isRecoveringResilient)
        {
            // define stop
            var stopCallbacks = new List <StopCallback>();

            // determine context
            var contextName = _statementSpec.OptionalContextName;

            // Create view factories and parent view based on a filter specification
            // Since only for non-joins we get the existing stream's lock and try to reuse it's views
            var filterStreamSpec = (FilterStreamSpecCompiled)_statementSpec.StreamSpecs[0];
            InstrumentationAgent instrumentationAgentCreateWindowInsert = null;

            if (InstrumentationHelper.ENABLED)
            {
                var eventTypeName = filterStreamSpec.FilterSpec.FilterForEventType.Name;
                instrumentationAgentCreateWindowInsert = new ProxyInstrumentationAgent()
                {
                    ProcIndicateQ = () => InstrumentationHelper.Get().QFilterActivationNamedWindowInsert(eventTypeName),
                    ProcIndicateA = () => InstrumentationHelper.Get().AFilterActivationNamedWindowInsert(),
                };
            }
            var activator = services.ViewableActivatorFactory.CreateFilterProxy(services, filterStreamSpec.FilterSpec, statementContext.Annotations, false, instrumentationAgentCreateWindowInsert, false, 0);

            // create data window view factories
            var unmaterializedViewChain = services.ViewService.CreateFactories(0, filterStreamSpec.FilterSpec.ResultEventType, filterStreamSpec.ViewSpecs, filterStreamSpec.Options, statementContext, false, -1);

            // verify data window
            VerifyDataWindowViewFactoryChain(unmaterializedViewChain.FactoryChain);

            // get processor for variant-streams and versioned typed
            var windowName = _statementSpec.CreateWindowDesc.WindowName;
            var optionalRevisionProcessor = statementContext.ValueAddEventService.GetValueAddProcessor(windowName);

            // add named window processor (one per named window for all agent instances)
            var isPrioritized = services.EngineSettingsService.EngineSettings.ExecutionConfig.IsPrioritized;
            var isEnableSubqueryIndexShare = HintEnum.ENABLE_WINDOW_SUBQUERY_INDEXSHARE.GetHint(_statementSpec.Annotations) != null;

            if (!isEnableSubqueryIndexShare && unmaterializedViewChain.FactoryChain[0] is VirtualDWViewFactory)
            {
                isEnableSubqueryIndexShare = true;      // index share is always enabled for virtual data window (otherwise it wouldn't make sense)
            }
            var isBatchingDataWindow     = DetermineBatchingDataWindow(unmaterializedViewChain.FactoryChain);
            var virtualDataWindowFactory = DetermineVirtualDataWindow(unmaterializedViewChain.FactoryChain);
            var optionalUniqueKeyProps   = ViewServiceHelper.GetUniqueCandidateProperties(unmaterializedViewChain.FactoryChain, _statementSpec.Annotations);
            var processor = services.NamedWindowMgmtService.AddProcessor(
                windowName, contextName, filterStreamSpec.FilterSpec.ResultEventType,
                statementContext.StatementResultService, optionalRevisionProcessor, statementContext.Expression,
                statementContext.StatementName, isPrioritized, isEnableSubqueryIndexShare, isBatchingDataWindow,
                virtualDataWindowFactory != null, optionalUniqueKeyProps,
                _statementSpec.CreateWindowDesc.AsEventTypeName,
                statementContext, services.NamedWindowDispatchService);

            Viewable finalViewable;
            EPStatementStopMethod    stopStatementMethod;
            EPStatementDestroyMethod destroyStatementMethod;

            try {
                // add stop callback
                stopCallbacks.Add(new ProxyStopCallback(() =>
                {
                    services.NamedWindowMgmtService.RemoveProcessor(windowName);
                    if (virtualDataWindowFactory != null)
                    {
                        virtualDataWindowFactory.DestroyNamedWindow();
                    }
                }));

                // Add a wildcard to the select clause as subscribers received the window contents
                _statementSpec.SelectClauseSpec.SetSelectExprList(new SelectClauseElementWildcard());
                _statementSpec.SelectStreamDirEnum = SelectClauseStreamSelectorEnum.RSTREAM_ISTREAM_BOTH;

                // obtain result set processor factory
                StreamTypeService typeService   = new StreamTypeServiceImpl(new EventType[] { processor.NamedWindowType }, new string[] { windowName }, new bool[] { true }, services.EngineURI, false);
                var resultSetProcessorPrototype = ResultSetProcessorFactoryFactory.GetProcessorPrototype(
                    _statementSpec, statementContext, typeService, null, new bool[0], true, null, null, services.ConfigSnapshot, services.ResultSetProcessorHelperFactory, false, false);

                // obtain factory for output limiting
                var outputViewFactory = OutputProcessViewFactoryFactory.Make(
                    _statementSpec,
                    services.InternalEventRouter,
                    statementContext,
                    resultSetProcessorPrototype.ResultSetProcessorFactory.ResultEventType, null,
                    services.TableService,
                    resultSetProcessorPrototype.ResultSetProcessorFactory.ResultSetProcessorType,
                    services.ResultSetProcessorHelperFactory,
                    services.StatementVariableRefService);

                // create context factory
                // Factory for statement-context instances
                var contextFactory = new StatementAgentInstanceFactoryCreateWindow(statementContext, _statementSpec, services, activator, unmaterializedViewChain, resultSetProcessorPrototype, outputViewFactory, isRecoveringStatement);
                statementContext.StatementAgentInstanceFactory = contextFactory;

                // With context - delegate instantiation to context
                EPStatementStopMethod stopMethod = new EPStatementStopMethodImpl(statementContext, stopCallbacks);
                if (_statementSpec.OptionalContextName != null)
                {
                    var mergeView = new ContextMergeView(processor.NamedWindowType);
                    finalViewable = mergeView;

                    var statement = new ContextManagedStatementCreateWindowDesc(_statementSpec, statementContext, mergeView, contextFactory);
                    services.ContextManagementService.AddStatement(contextName, statement, isRecoveringResilient);
                    stopStatementMethod = new ProxyEPStatementStopMethod(() =>
                    {
                        services.ContextManagementService.StoppedStatement(contextName, statementContext.StatementName, statementContext.StatementId, statementContext.Expression, statementContext.ExceptionHandlingService);
                        stopMethod.Stop();
                    });

                    destroyStatementMethod = new ProxyEPStatementDestroyMethod(() =>
                                                                               services.ContextManagementService.DestroyedStatement(contextName, statementContext.StatementName, statementContext.StatementId));
                }
                // Without context - start here
                else
                {
                    var agentInstanceContext = GetDefaultAgentInstanceContext(statementContext);
                    StatementAgentInstanceFactoryCreateWindowResult resultOfStart;
                    try {
                        resultOfStart = (StatementAgentInstanceFactoryCreateWindowResult)contextFactory.NewContext(agentInstanceContext, isRecoveringResilient);
                    }
                    catch (Exception) {
                        services.NamedWindowMgmtService.RemoveProcessor(windowName);
                        throw;
                    }
                    finalViewable = resultOfStart.FinalView;
                    var stopCallback = services.EpStatementFactory.MakeStopMethod(resultOfStart);
                    stopStatementMethod = new ProxyEPStatementStopMethod(() =>
                    {
                        stopCallback.Stop();
                        stopMethod.Stop();
                    });
                    destroyStatementMethod = null;

                    if (statementContext.StatementExtensionServicesContext != null && statementContext.StatementExtensionServicesContext.StmtResources != null)
                    {
                        var holder = statementContext.StatementExtensionServicesContext.ExtractStatementResourceHolder(resultOfStart);
                        statementContext.StatementExtensionServicesContext.StmtResources.Unpartitioned = holder;
                        statementContext.StatementExtensionServicesContext.PostProcessStart(resultOfStart, isRecoveringResilient);
                    }
                }
            }
            catch (ExprValidationException) {
                services.NamedWindowMgmtService.RemoveProcessor(windowName);
                throw;
            }
            catch (Exception) {
                services.NamedWindowMgmtService.RemoveProcessor(windowName);
                throw;
            }

            services.StatementVariableRefService.AddReferences(statementContext.StatementName, windowName);

            return(new EPStatementStartResult(finalViewable, stopStatementMethod, destroyStatementMethod));
        }