private static NavigatorTestingDetails <TNavigator> GetNavigatorToTest <TNavigator>(
            UrlPathDetails initialUrl,
            Assert assert,
            Func <IDispatcher, TNavigator> navigatorGenerator)
            where TNavigator : Navigator
        {
            if (initialUrl == null)
            {
                throw new ArgumentNullException("initialUrl");
            }
            if (assert == null)
            {
                throw new ArgumentNullException("assert");
            }
            if (navigatorGenerator == null)
            {
                throw new ArgumentNullException("navigatorGenerator");
            }

            var dispatcher     = new AppDispatcher();
            var historyHandler = new MockHistoryHandler(initialUrl: new UrlDetails(NonNullList <NonBlankTrimmedString> .Empty, Optional <QueryString> .Missing));
            var navigator      = navigatorGenerator(dispatcher);

            RouteCombiner.StartListening(historyHandler, navigator.Routes, dispatcher);

            var navigatorTestingDetails = new NavigatorTestingDetails <TNavigator>(navigator, historyHandler, dispatcher, assert);

            historyHandler.RaiseNavigateToForCurrentLocation();
            return(navigatorTestingDetails);
        }
        public SimpleExampleStore(HTMLElement renderContainer, AppDispatcher dispatcher)
        {
            if (renderContainer == null)
            {
                throw new ArgumentNullException("renderContainer");
            }
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher");
            }

            _renderContainer = renderContainer;
            _dispatcher      = dispatcher;
            _viewModel       = new ViewModel(lastUpdated: DateTime.Now, message: "Hi!", validationError: "");
            RenderIfActive();

            _dispatcher.Register(message =>
            {
                var recordChange = message.Action as RecordChangeAction <ViewModel>;
                if (recordChange != null)
                {
                    UserEdit(recordChange.Value);
                    return;
                }

                if (message.Action is TimePassedAction)
                {
                    _viewModel = new ViewModel(lastUpdated: DateTime.Now, message: _viewModel.Message, validationError: _viewModel.ValidationError);
                    RenderIfActive();
                    return;
                }
            });
        }
示例#3
0
        public SimpleExampleStore(AppDispatcher dispatcher)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher");
            }

            _dispatcher = dispatcher;

            LastUpdated     = DateTime.Now;
            Message         = "Hi!";
            ValidationError = "";

            _dispatcher.Register(message =>
            {
                message
                .If <MessageChangeAction>(action =>
                {
                    Message         = action.Value;
                    ValidationError = (action.Value.Trim() == "") ? "Why no message??" : "";
                })
                .Else <TimePassedAction>(action => LastUpdated = DateTime.Now)
                .IfAnyMatched(OnChange);
            });
        }
示例#4
0
        static void Main()
        {
            // Configure your DI container
            var container = new UnityContainer();

            container.RegisterType <IUserRepository, InMemoryUserRepository>();
            container.RegisterType <ILogger, ConsoleLogger>();
            container.RegisterType(typeof(IHandle <CreateUser>), typeof(UserService));
            // Create common service locator adapter
            var unityServiceLocatorAdapter = new UnityServiceLocator(container);

            // Initilaize the AppDispatcher
            AppDispatcher.Initialize(app =>
            {
                app.UseCommonServiceLocator(unityServiceLocatorAdapter);
            });

            // Create a request
            var request = new CreateUser {
                Name = "Jane Smith"
            };

            // Handle it using the dispatcher, if DI is configured correctly
            // the message handler in your application service will handle it.
            AppDispatcher.Handle(request);
        }
示例#5
0
        static void DoEvents()
        {
            DispatcherFrame frame = new DispatcherFrame();

            AppDispatcher.Invoke(DispatcherPriority.ApplicationIdle,
                                 new DispatcherOperationCallback(ExitFrame), frame);
            Dispatcher.PushFrame(frame);
        }
示例#6
0
        public Task <TQuery> BuildAsync <TQuery>(AppDispatcher appDispatcher, TQuery query)
            where TQuery : IQuery
        {
            IQueryBuilder <TQuery> queryBuilder = _GetQueryBuilder <TQuery>();

            var result = queryBuilder.BuildAsync(appDispatcher, query).ContinueWith(t => query);

            return(result);
        }
        public virtual Task <ICommandResult> ExecuteAsync(AppDispatcher appDispatcher, ICommand command)
        {
            if (command is TCommand targetCommand)
            {
                return(ExecuteAsync(appDispatcher, targetCommand));
            }

            throw new InvalidOperationException("Invalid command parameter");
        }
示例#8
0
        public Task HandleAsync(AppDispatcher appDispatcher, IEvent @event)
        {
            if (!(@event is TEvent targetEvent))
            {
                throw new InvalidOperationException("Invalid event parameter");
            }

            return(HandleAsync(appDispatcher, targetEvent));
        }
示例#9
0
        public Task <ICommandResult> SendAsync <TCommand>(AppDispatcher appDispatcher, TCommand command)
            where TCommand : ICommand
        {
            Task <ICommandResult>      result  = null;
            ICommandHandler <TCommand> handler = _GetHandler <TCommand>();

            result = handler.ExecuteAsync(appDispatcher, command);

            return(result);
        }
示例#10
0
        public Task BuildAsync(AppDispatcher appDispatcher, IQuery query)
        {
            TQuery targetQuery = query as TQuery;

            if (targetQuery == null)
            {
                throw new InvalidOperationException("Invalid query parameter");
            }

            return(BuildAsync(appDispatcher, targetQuery));
        }
示例#11
0
        public override Task BuildAsync(AppDispatcher appDispatcher, EntityConvertQuery <TFrom, TTo> query)
        {
            var toObject = ConvertAsync(appDispatcher, query.Object);

            var resultTask = toObject.ContinueWith(t =>
            {
                var result = QueryResult <TTo> .FromResult(t.Result);
                return(result);
            });

            return(resultTask);
        }
        private void HandleAnchorLocated(object sender, AnchorLocatedEventArgs args)
        {
            Debug.Log($"Anchor recognized as a possible Azure anchor");

            if (args.Status == LocateAnchorStatus.Located || args.Status == LocateAnchorStatus.AlreadyTracked)
            {
                currentCloudAnchor = args.Anchor;

                AppDispatcher.Instance().Enqueue(() =>
                {
                    Debug.Log($"Azure anchor located successfully");
                    var indicator = Instantiate(anchorPositionPrefab);

#if WINDOWS_UWP || UNITY_WSA
                    indicator.gameObject.CreateNativeAnchor();

                    if (currentCloudAnchor == null)
                    {
                        return;
                    }
                    Debug.Log("Local anchor position successfully set to Azure anchor position");

                    indicator.GetComponent <UnityEngine.XR.WSA.WorldAnchor>().SetNativeSpatialAnchorPtr(currentCloudAnchor.LocalAnchor);
#elif UNITY_ANDROID || UNITY_IOS
                    Pose anchorPose = Pose.identity;
                    anchorPose      = currentCloudAnchor.GetPose();

                    Debug.Log($"Setting object to anchor pose with position '{anchorPose.position}' and rotation '{anchorPose.rotation}'");
                    indicator.transform.position = anchorPose.position;
                    indicator.transform.rotation = anchorPose.rotation;

                    // Create a native anchor at the location of the object in question
                    indicator.gameObject.CreateNativeAnchor();
#endif

                    indicator.Init(currentTrackedObject);
                    anchorArrowGuide.SetTargetObject(indicator.transform);
                    activeAnchors.Add(currentTrackedObject.SpatialAnchorId, indicator);

                    // Notify subscribers
                    OnFindAnchorSucceeded?.Invoke(this, EventArgs.Empty);
                    currentWatcher?.Stop();
                    currentTrackedObject = null;
                });
            }
            else
            {
                Debug.Log($"Attempt to locate Anchor with ID '{args.Identifier}' failed, locate anchor status was not 'Located' but '{args.Status}'");
            }

            StopAzureSession();
        }
示例#13
0
        static void Run()
        {
            var dispatcher = new AppDispatcher();

            new SimpleExampleStore(
                Global.window.document.getElementById("main"),
                dispatcher
                );
            Global.window.setInterval(
                (Action)(() => dispatcher.HandleServerAction(new TimePassedAction())),
                500
                );
        }
        /// <summary>
        /// Take a photo from the WebCam. Make sure the camera is active.
        /// </summary>
        /// <returns>Image data with a Texture for thumbnail.</returns>
        public Task <ImageThumbnail> TakePhotoWithThumbnail()
        {
            if (!IsCameraActive)
            {
                throw new Exception("Can't take photo when camera is not ready.");
            }

            return(Task.Run(() =>
            {
                var completionSource = new TaskCompletionSource <ImageThumbnail>();

                AppDispatcher.Instance().Enqueue(() =>
                {
                    Debug.Log("Starting photo capture.");

#if UNITY_WSA
                    photoCapture.TakePhotoAsync((photoCaptureResult, frame) =>
                    {
                        Debug.Log("Photo capture done.");

                        var buffer = new List <byte>();
                        frame.CopyRawImageDataIntoBuffer(buffer);
                        var texture = new Texture2D(2, 2);
                        var imageData = buffer.ToArray();
                        texture.LoadImage(imageData);
                        var imageThumbnail = new ImageThumbnail
                        {
                            ImageData = imageData,
                            Texture = texture
                        };

                        completionSource.TrySetResult(imageThumbnail);
                    });
#else
                    var tex = new Texture2D(webCamTexture.width, webCamTexture.height);
                    tex.SetPixels(webCamTexture.GetPixels());
                    tex.Apply();
                    var data = tex.EncodeToPNG();
                    var imageThumbnail = new ImageThumbnail
                    {
                        ImageData = data,
                        Texture = tex
                    };

                    completionSource.TrySetResult(imageThumbnail);
#endif
                });

                return completionSource.Task;
            }));
        }
示例#15
0
            public Props(SimpleExampleStore store, AppDispatcher dispatcher)
            {
                if (store == null)
                {
                    throw new ArgumentNullException("store");
                }
                if (dispatcher == null)
                {
                    throw new ArgumentNullException("dispatcher");
                }

                Store      = store;
                Dispatcher = dispatcher;
            }
        public AppUIStore(AppDispatcher dispatcher, IReadAndWriteMessages messageApi)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher");
            }
            if (messageApi == null)
            {
                throw new ArgumentNullException("messageApi");
            }

            NewMessage     = GetEmptyNewMessage();
            MessageHistory = NonNullList <SavedMessageDetails> .Empty;

            _saveActionRequestId = null;

            dispatcher.Receive(a => a
                               .If <StoreInitialised>(
                                   condition: action => action.Store == this,
                                   work: action =>
            {
                // When it's time for a Store to be initialised (to set its initial state and call OnChange to let any interested Components know
                // that it's ready), a StoreInitialised action will be dispatched that references the Store. In a more complicated app, a router
                // might choose an initial Store based upon the current URL. (We don't need to do anything within this callback, we just need to
                // match the StoreInitialised so that IfAnyMatched will fire and call OnChange).
            }
                                   )
                               .Else <MessageEditStateChanged>(action => NewMessage = UpdateValidationFor(action.NewState))
                               .Else <MessageSaveRequested>(action =>
            {
                NewMessage           = NewMessage.With(_ => _.IsSaveInProgress, true);
                _saveActionRequestId = messageApi.SaveMessage(action.Message);
            })
                               .Else <MessageSaveSucceeded>(
                                   condition: action => action.RequestId == _saveActionRequestId,
                                   work: action =>
            {
                // The API's SaveMessage function will fire a MessageSaveSucceeded action when (if) the save is successful and then a subsequent
                // MessageHistoryUpdated action after it's automatically retrieved fresh data, including the newly-saved item (so we need only
                // reset the form here, a MessageHistoryUpdated should be along shortly containig the new item..)
                _saveActionRequestId = null;
                NewMessage           = GetEmptyNewMessage();
            }
                                   )
                               .Else <MessageHistoryUpdated>(action => MessageHistory = action.Messages)
                               .IfAnyMatched(OnChange)
                               );
        }
示例#17
0
        public Task <uint> PublishAsync <TEvent>(AppDispatcher appDispatcher, TEvent @event)
            where TEvent : IEvent
        {
            uint numListeners   = 0;
            var  eventListeners = _serviceLocator.Get <IEventListener <TEvent> >()
                                  .ToList();
            var tasks = new List <Task>(eventListeners.Count);

            foreach (var eventListener in eventListeners)
            {
                tasks.Add(eventListener.HandleAsync(appDispatcher, @event));
                ++numListeners;
            }

            return(Task.WhenAll(tasks).ContinueWith(t => numListeners));
        }
        private async void CreateAsaAnchorEditor(Transform indicatorTransform)
        {
            var indicator = Instantiate(anchorPositionPrefab, indicatorTransform.position, indicatorTransform.rotation);

            anchorCreationController.StartProgressIndicatorSession();
            await Task.Delay(2500);

            var mockAnchorId = Guid.NewGuid().ToString();

            currentTrackedObject.SpatialAnchorId = mockAnchorId;
            activeAnchors.Add(currentTrackedObject.SpatialAnchorId, indicator);
            AppDispatcher.Instance().Enqueue(() =>
            {
                indicator.Init(currentTrackedObject);
                OnCreateAnchorSucceeded?.Invoke(this, mockAnchorId);
                currentTrackedObject = null;
            });
        }
示例#19
0
        public static void Go()
        {
            var dispatcher = new AppDispatcher();
            var store      = new AppUIStore(dispatcher, new MessageApi(dispatcher));

            var container = Document.GetElementById("main");

            container.ClassName = string.Join(" ", container.ClassName.Split().Where(c => c != "loading"));
            React.Render(
                new AppContainer(store, dispatcher),
                container
                );

            // After the Dispatcher and the Store and the Container Component are all associated with each other, the Store needs to be told that
            // it's time to set its initial state, so that the Component can receive an OnChange event and draw itself accordingly. In a more
            // complicated app, this would probably be an event fired by the router - initialising the Store appropriate to the current URL,
            // but in this case there's only a single Store to initialise.
            dispatcher.Dispatch(new StoreInitialised(store));
        }
        private async void FindAsaAnchorEditor()
        {
            anchorCreationController.StartProgressIndicatorSession();
            await Task.Delay(3000);

            var targetPosition = Camera.main.transform.position;

            targetPosition.z += 0.5f;
            var indicator = Instantiate(anchorPositionPrefab);

            indicator.transform.position = targetPosition;
            indicator.Init(currentTrackedObject);
            anchorArrowGuide.SetTargetObject(indicator.transform);

            // Notify subscribers
            activeAnchors.Add(currentTrackedObject.SpatialAnchorId, indicator);
            AppDispatcher.Instance().Enqueue(() => OnFindAnchorSucceeded?.Invoke(this, EventArgs.Empty));
            currentTrackedObject = null;
        }
示例#21
0
        public static void Main()
        {
            var dispatcher = new AppDispatcher();
            var store      = new SimpleExampleStore(dispatcher);

            React.Render(
                new App(store, dispatcher),
                Document.GetElementById("main")
                );

            // This action would usually be fired off by a router to inform the Store for the current URL that it needs to
            // wake up, but in this example there is only a single Store! Sending it the StoreInitialisedAction means that
            // it can fire its OnChange event which the App component is waiting for, to know that it's show time.
            dispatcher.HandleViewAction(new StoreInitialisedAction(store));

            Window.SetInterval(
                () => dispatcher.HandleServerAction(new TimePassedAction()),
                500
                );
        }
示例#22
0
        static void Main()
        {
            // Look ma, no DI container!
            var logger = new ConsoleLogger();
            Func <IUserRepository> userRepositoryFactory =
                () => new InMemoryUserRepository();

            AppDispatcher.Initialize(app =>
            {
                app.RegisterHandler <CreateUser>(createUserRequest =>
                {
                    UserServiceModule.CreateUser(createUserRequest,
                                                 userRepositoryFactory, logger);
                });
            });

            var request = new CreateUser {
                Name = "Jane Smith"
            };

            AppDispatcher.Handle(request);
        }
示例#23
0
        static void Main()
        {
            var container = new Container();

            container.Register <IUserRepository, InMemoryUserRepository>();
            container.Register <ILogger, ConsoleLogger>();
            container.RegisterManyForOpenGeneric(typeof(IHandle <>), AppDomain.CurrentDomain.GetAssemblies());
            container.RegisterDecorator(typeof(IHandle <>), typeof(LoggingDecorator <>));

            var simpleInjectorServiceLocatorAdapter = new SimpleInjectorServiceLocatorAdapter(container);

            AppDispatcher.Initialize(app =>
            {
                // Decorating the pipline AND using IoC: you will see
                // the action pipleine below wraps any IoC decorators
                app.GlobalPipeline(pipeline => pipeline.Decorate(handler =>
                {
                    Console.WriteLine("before a");
                    handler();
                    Console.WriteLine("after a");
                }).Decorate(handler =>
                {
                    Console.WriteLine("before b");
                    handler();
                    Console.WriteLine("after b");
                }), true);

                app.UseCommonServiceLocator(simpleInjectorServiceLocatorAdapter);
            });

            var request = new CreateUser {
                Name = "Jane Smith"
            };

            AppDispatcher.Handle(request);

            Console.ReadLine();
        }
        public ExampleNavigator(AppDispatcher dispatcher) : base(dispatcher)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher");
            }

            // Declare pairs of routes and actions which will send the user along these routes. Doing both halves of the route management (registering and
            // following) together keeps each route's code localised while still allowing a static navigation interface to be created. When the user needs
            // to be sent to the an "Accommodation" sub-page, there won't be code to send them to "/Accommodation/xyz", a call will instead to be made to
            // the "Accommodation" method of this class, providing the sub-page id, and the target URL will be returned. This ensures that there is no
            // chance of changes to routes here not being reflected in other code (if "Accommodation" was changed to "WhereToStay", for example, then
            // no other code need be changed since it will all be calling the "Accommodation" method; if the other code was manually trying to go to
            // "/Accommodation/xyz" then that code would also have to be changed to "/WhereToStay/xyz" in all places and any mistakes wouldn't be
            // caught until runtime).

            // Register home
            _getHome = AddRelativeRoute(
                segments: NonNullList <string> .Empty,
                routeAction: new NavigateToHome(),
                urlGenerator: () => GetPath()
                );

            // Register "/Accommodation"
            _getAccommodation = AddRelativeRoute(
                segment: "Accommodation",
                routeAction: new NavigateToAccommodationList(),
                urlGenerator: () => GetPath("Accommodation")
                );

            // Register "/Accommodation/{string}"
            _getAccommodationWithSegment = AddRelativeRoute(
                routeDetails: RouteBuilder.Empty.Fixed("Accommodation").String(),
                routeActionGenerator: matchedValue => new NavigateToAccommodationSection(matchedValue),
                urlGenerator: segment => GetPath("Accommodation", segment)
                );
        }
示例#25
0
 public ICommandResult Send <TCommand>(AppDispatcher appDispatcher, TCommand command)
     where TCommand : ICommand
 {
     return(Task.Run(() => SendAsync(appDispatcher, command)).Result);
 }
示例#26
0
        public ToDoStore()
        {
            AppDispatcher.Register <CreateItemAction>(
                create =>
            {
                var newText = create.Message.Trim();
                if (string.IsNullOrWhiteSpace(newText))
                {
                    return;
                }

                Create(newText);
                text = "";
                EmitChange();
            });

            AppDispatcher.Register <CheckedItemAction>(
                action =>
            {
                if (items.ContainsKey(action.Id))
                {
                    var found = items[action.Id];
                    if (found.IsComplete)
                    {
                        System.Diagnostics.Debug.Fail("Item is not in a valid state for this action");
                    }
                    found.IsComplete = true;
                    EmitChange();
                }
            });

            AppDispatcher.Register <UncheckedItemAction>(
                action =>
            {
                if (items.ContainsKey(action.Id))
                {
                    var found = items[action.Id];
                    if (!found.IsComplete)
                    {
                        System.Diagnostics.Debug.Fail("Item is not in a valid state for this action");
                    }
                    found.IsComplete = false;
                    EmitChange();
                }
            });

            AppDispatcher.Register <EditItemAction>(
                action =>
            {
                if (items.ContainsKey(action.Id))
                {
                    var found = items[action.Id];
                    if (found.IsEditable)
                    {
                        System.Diagnostics.Debug.Fail("Item is not in a valid state for this action");
                    }
                    found.IsEditable = true;
                    EmitChange();
                }
            });

            AppDispatcher.Register <SaveItemAction>(
                action =>
            {
                if (items.ContainsKey(action.Id))
                {
                    var found = items[action.Id];
                    if (!found.IsEditable)
                    {
                        System.Diagnostics.Debug.Fail("Item is not in a valid state for this action");
                    }
                    found.Text       = action.Text;
                    found.IsEditable = false;
                    EmitChange();
                }
            });

            AppDispatcher.Register <ToggleAllCompletedAction>(
                action =>
            {
                foreach (var item in items)
                {
                    item.Value.IsComplete = action.IsCompleted;
                }
                EmitChange();
            });

            AppDispatcher.Register <ClearCompletedTasksAction>(
                action =>
            {
                foreach (var item in items.Where(x => x.Value.IsComplete).ToList())
                {
                    items.Remove(item.Key);
                }
                EmitChange();
            });
        }
示例#27
0
 public App(SimpleExampleStore store, AppDispatcher dispatcher) : base(new Props(store, dispatcher))
 {
 }
示例#28
0
 public abstract Task <TTo> ConvertAsync(AppDispatcher appDispatcher, TFrom entity);
示例#29
0
 public abstract Task HandleAsync(AppDispatcher appDispatcher, TEvent @event);
示例#30
0
 public abstract Task BuildAsync(AppDispatcher appDispatcher, TQuery query);