Ejemplo n.º 1
0
        public AppBootstrapper(IKernel testKernel = null, IRoutingState testRouter = null)
        {
            Router = testRouter ?? new RoutingState();
            var kernel = testKernel ?? CreateStandardKernel();

            // AppBootstrapper is a global variable, so bind up 
            kernel.Bind(typeof (IScreen), typeof(AppBootstrapper)).ToConstant(this);

            // Set up NInject to do DI
            RxApp.ConfigureServiceLocator(
                (iface, contract) => {
                    if (contract != null) return kernel.Get(iface, contract);
                    return kernel.Get(iface);
                },
                (iface, contract) => {
                    if (contract != null) return kernel.GetAll(iface, contract);
                    return kernel.GetAll(iface);
                },
                (realClass, iface, contract) => {
                    var binding = kernel.Bind(iface).To(realClass);
                    if (contract != null) binding.Named(contract);
                });

            // TODO: This is a good place to set up any other app 
            // startup tasks, like setting the logging level
            LogHost.Default.Level = LogLevel.Debug;

            // Navigate to the opening page of the application
            var welcomeVm = RxApp.GetService<IWelcomeViewModel>();
            Router.Navigate.Execute(welcomeVm);
        }
Ejemplo n.º 2
0
        public AppBootstrapper(IKernel testKernel = null, IRoutingState router = null)
        {
            Kernel = testKernel ?? createDefaultKernel();
            Kernel.Bind<IAppBootstrapper>().ToConstant(this);
            Router = router ?? new RoutingState();

            // XXX: This is a ReactiveUI Bug
            RxApp.DeferredScheduler = CoreDispatcherScheduler.Current;

            apiFactory = Kernel.TryGet<Func<IObservable<IPlayApi>>>("ApiFactory");

            RxApp.ConfigureServiceLocator(
                (type, contract) => Kernel.Get(type, contract),
                (type, contract) => Kernel.GetAll(type, contract),
                (c, i, s) => Kernel.Bind(i).To(c));

            LoadCredentials().Subscribe(
                x => {
                    CurrentAuthenticatedClient = x;
                    Router.Navigate.Execute(Kernel.Get<IPlayViewModel>());
                }, ex => {
                    this.Log().WarnException("Failed to load credentials, going to login screen", ex);

                    // XXX: FOR F***S SAKE DONT CHECK THIS IN
                    CurrentAuthenticatedClient = createPlayApiFromCreds("https://play.githubapp.com", "f07c8b");

                    Router.Navigate.Execute(Kernel.Get<IPlayViewModel>());
                });
        }
Ejemplo n.º 3
0
        IPlayViewModel setupStandardMock(MoqMockingKernel kernel, IRoutingState router, Action extraSetup = null)
        {
            kernel.Bind <IPlayViewModel>().To <PlayViewModel>();

            var playApi = kernel.GetMock <IPlayApi>();

            playApi.Setup(x => x.ListenUrl()).Returns(Observable.Never <string>());
            playApi.Setup(x => x.ConnectToSongChangeNotifications()).Returns(Observable.Never <Unit>());
            playApi.Setup(x => x.NowPlaying()).Returns(Observable.Return(Fakes.GetSong()));
            playApi.Setup(x => x.Queue()).Returns(Observable.Return(Fakes.GetAlbum()));
            playApi.Setup(x => x.FetchImageForAlbum(It.IsAny <Song>())).Returns(Observable.Return <BitmapImage>(null));

            kernel.GetMock <IScreen>().Setup(x => x.Router).Returns(router);

            kernel.GetMock <ILoginMethods>()
            .Setup(x => x.EraseCredentialsAndNavigateToLogin())
            .Callback(() => router.Navigate.Execute(kernel.Get <IWelcomeViewModel>()));

            kernel.GetMock <ILoginMethods>()
            .Setup(x => x.CurrentAuthenticatedClient)
            .Returns(kernel.Get <IPlayApi>());

            if (extraSetup != null)
            {
                extraSetup();
            }

            RxApp.ConfigureServiceLocator((t, s) => kernel.Get(t, s), (t, s) => kernel.GetAll(t, s));
            return(kernel.Get <IPlayViewModel>());
        }
Ejemplo n.º 4
0
        static ISearchViewModel setupStandardFixture(MoqMockingKernel kernel, IRoutingState router = null)
        {
            router = router ?? new RoutingState();
            kernel.Bind <ISearchViewModel>().To <SearchViewModel>();
            kernel.Bind <IBlobCache>().To <TestBlobCache>().Named("UserAccount");
            kernel.Bind <IBlobCache>().To <TestBlobCache>().Named("LocalMachine");

            kernel.GetMock <IPlayApi>().Setup(x => x.Search("Foo"))
            .Returns(Observable.Return(new List <Song>()
            {
                Fakes.GetSong()
            }))
            .Verifiable();

            kernel.GetMock <ILoginMethods>().Setup(x => x.CurrentAuthenticatedClient).Returns(kernel.Get <IPlayApi>());
            kernel.GetMock <IScreen>().Setup(x => x.Router).Returns(router);

            var img = new BitmapImage();

            kernel.GetMock <IPlayApi>().Setup(x => x.FetchImageForAlbum(It.IsAny <Song>()))
            .Returns(Observable.Return(img))
            .Verifiable();

            RxApp.ConfigureServiceLocator((t, s) => kernel.Get(t, s), (t, s) => kernel.GetAll(t, s));

            var fixture = kernel.Get <ISearchViewModel>();

            return(fixture);
        }
        public RouterUINavigationController(IRoutingState router, IViewLocator viewLocator = null)
        {
            this.router = router;
            viewLocator = viewLocator ?? ViewLocator.Current;

            var platform = RxApp.DependencyResolver.GetService <IPlatformOperations>();

            var vmAndContract = Observable.CombineLatest(
                router.Navigate,
                orientationChanged,
                (vm, _) => new { ViewModel = vm, Contract = platform.GetOrientation() });

            vmAndContract.Subscribe(x => {
                var view       = viewLocator.ResolveView(x.ViewModel, x.Contract);
                view.ViewModel = x.ViewModel;

                this.PushViewController((UIViewController)view, true);
            });

            router.NavigateBack.Subscribe(_ => this.PopViewControllerAnimated(true));
            router.NavigateAndReset.Subscribe(x => {
                this.PopToRootViewController(false);
                router.Navigate.Execute(x);
            });

            this.Delegate = new RouterUINavigationControllerDelegate(this, router);
        }
        public RouterUINavigationController(IRoutingState router, IViewLocator viewLocator = null)
        {
            this.router = router;
            viewLocator = viewLocator ?? ViewLocator.Current;

            var platform = RxApp.DependencyResolver.GetService<IPlatformOperations>();

            var vmAndContract = Observable.CombineLatest(
                router.Navigate,
                orientationChanged,
                (vm, _) => new { ViewModel = vm, Contract = platform.GetOrientation() });

            vmAndContract.Subscribe (x => {
                var view = viewLocator.ResolveView(x.ViewModel, x.Contract);
                view.ViewModel = x.ViewModel;

                this.PushViewController((UIViewController)view, true);
            });

            router.NavigateBack.Subscribe(_ => this.PopViewControllerAnimated(true));
            router.NavigateAndReset.Subscribe (x => {
                this.PopToRootViewController(false);
                router.Navigate.Execute(x);
            });

            this.Delegate = new RouterUINavigationControllerDelegate(this, router);
        }
        public AppBootstrapper(IKernel testKernel = null, IRoutingState router = null)
        {
            Kernel = testKernel ?? createDefaultKernel();
            Kernel.Bind <IAppBootstrapper>().ToConstant(this);
            Router = router ?? new RoutingState();

            // XXX: This is a ReactiveUI Bug
            RxApp.DeferredScheduler = CoreDispatcherScheduler.Current;

            apiFactory = Kernel.TryGet <Func <IObservable <IPlayApi> > >("ApiFactory");

            RxApp.ConfigureServiceLocator(
                (type, contract) => Kernel.Get(type, contract),
                (type, contract) => Kernel.GetAll(type, contract),
                (c, i, s) => Kernel.Bind(i).To(c));

            LoadCredentials().Subscribe(
                x => {
                CurrentAuthenticatedClient = x;
                Router.Navigate.Execute(Kernel.Get <IPlayViewModel>());
            }, ex => {
                this.Log().WarnException("Failed to load credentials, going to login screen", ex);

                // XXX: FOR F***S SAKE DONT CHECK THIS IN
                CurrentAuthenticatedClient = createPlayApiFromCreds("https://play.githubapp.com", "f07c8b");

                Router.Navigate.Execute(Kernel.Get <IPlayViewModel>());
            });
        }
Ejemplo n.º 8
0
        public AppBootstrapper(IDependencyResolver kernel = null, IRoutingState router = null)
        {
            RxApp.DependencyResolver = kernel ?? createStandardKernel();
            Router = router ?? new RoutingState();

            // Our first screen is "Open cache"
            Router.Navigate.Execute(new OpenCacheViewModel(this, this));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates a ReactiveCommand which will, when invoked, navigate to the
        /// type specified by the type parameter via looking it up in the
        /// Dependency Resolver.
        /// </summary>
        public static IReactiveCommand NavigateCommandFor <T>(this IRoutingState This)
            where T : IRoutableViewModel
        {
            var ret = new ReactiveCommand(This.Navigate.CanExecuteObservable);

            ret.Select(_ => (IRoutableViewModel)RxApp.DependencyResolver.GetService <T>()).InvokeCommand(This.Navigate);
            return(ret);
        }
Ejemplo n.º 10
0
        public AppBootstrapper()
        {
            Router = new RoutingState();
            Router.Navigate.Execute(new MainViewModel(this));

            App.Current.Locator.Register(() => this, typeof(IScreen));
            App.Current.Locator.Register(() => this, typeof(IApplicationRootState));
        }
Ejemplo n.º 11
0
        public AppBootstrapper()
        {
            Router = new RoutingState();
            Router.Navigate.Execute(new MainViewModel(this));

            App.Current.Locator.Register(() => this, typeof(IScreen));
            App.Current.Locator.Register(() => this, typeof(IApplicationRootState));
        }
Ejemplo n.º 12
0
 public DummyAppBootstrapper()
 {
     Router = new RoutingState();
     Router.NavigateAndReset.Execute(new DummyRoutedViewModel(this)
     {
         ARandomGuid = Guid.NewGuid()
     });
 }
Ejemplo n.º 13
0
        public AppBootstrapper(IDependencyResolver kernel = null, IRoutingState router = null)
        {
            RxApp.DependencyResolver = kernel ?? createStandardKernel();
            Router = router ?? new RoutingState();

            // Our first screen is "Open cache"
            Router.Navigate.Execute(new OpenCacheViewModel(this, this));
        }
Ejemplo n.º 14
0
        public AppBootstrapper(IMutableDependencyResolver dependencyResolver = null, IRoutingState testRouter = null)
        {
            Router = testRouter ?? new RoutingState();

            dependencyResolver = dependencyResolver ?? RxApp.MutableResolver;

            RegisterParts(dependencyResolver);
            Router.Navigate.Execute(new MainScreenViewModel(this));
        }
Ejemplo n.º 15
0
        public AppBootstrapper(IKernel kernel = null, IRoutingState router = null)
        {
            kernel = kernel ?? createStandardKernel();
            Router = router ?? new RoutingState();

            RxApp.ConfigureServiceLocator(
                (t, s) => kernel.Get(t, s), (t, s) => kernel.GetAll(t, s));

            Router.Navigate.Execute(RxApp.GetService<IDropRepoViewModel>());
        }
Ejemplo n.º 16
0
        public AppBootstrapper(IKernel kernel = null, IRoutingState router = null)
        {
            kernel = kernel ?? createStandardKernel();
            Router = router ?? new RoutingState();

            RxApp.ConfigureServiceLocator(
                (t, s) => kernel.Get(t, s), (t, s) => kernel.GetAll(t, s));

            Router.Navigate.Execute(RxApp.GetService <IDropRepoViewModel>());
        }
        public AppViewModel(IMutableDependencyResolver dependencyResolver = null, IRoutingState routingState = null)
        {
            Router = routingState ?? new RoutingState();
            dependencyResolver = dependencyResolver ?? RxApp.MutableResolver;

            RegisterDependencies(dependencyResolver);

            LogHost.Default.Level = LogLevel.Debug;

            Router.Navigate.Execute(new CustomerViewModel(dependencyResolver.GetService<IScreen>()));
        }
Ejemplo n.º 18
0
        public AppBootstrapper(IKernel kernel = null, IRoutingState router = null)
        {
            kernel = kernel ?? createStandardKernel();
            Router = router ?? new RoutingState();

            RxApp.ConfigureServiceLocator(
                (t, s) => kernel.Get(t, s), (t, s) => kernel.GetAll(t, s));

            // Our first screen is "Open cache"
            Router.Navigate.Execute(RxApp.GetService<IOpenCacheViewModel>());
        }
Ejemplo n.º 19
0
        public AppBootstrapper(IRoutingState testRouter = null, ContainerBuilder builder = null)
        {
            Router = testRouter ?? new RoutingState();

            LogHost.Default.Level = LogLevel.Debug;

            ReactiveUIMicro.RxApp.ConfigureFileLogging("SquirrelDesktopDemo");

            var containerBuilder = builder ?? CreateStandardContainer();

            // AppBootstrapper is a global variable, so bind up
            containerBuilder.RegisterInstance(this)
            .As <IScreen>()
            .SingleInstance();

            // we want to create our UpdateManager in the same way each time
            containerBuilder.Register(ctx => {
                var settings = ctx.Resolve <ISettingsProvider>();
                return(new UpdateManager(settings.UpdateLocation, "SquirrelDesktopDemo", FrameworkVersion.Net40));
            }).As <UpdateManager>();

            // by default i want this app to use the test feed
            // but you can change this value in the settings
            var settingsProvider = new SettingsProvider();

            settingsProvider.UpdateLocation = "http://shimmer-demo.herokuapp.com/demo/";

            var container = containerBuilder.Build();

            RxApp.ConfigureServiceLocator(
                (iface, contract) => container.Resolve(iface),
                (iface, contract) => {
                var collection = typeof(IEnumerable <>).MakeGenericType(iface);
                return(container.Resolve(collection) as IEnumerable <object>);
            },
                (realClass, iface, contract) => {
                var newBuilder = new ContainerBuilder();
                newBuilder.RegisterType(realClass).As(iface);
                newBuilder.Update(container);
            });

            UserError.RegisterHandler(ex => {
                var errorVm     = container.Resolve <ErrorViewModel>();
                errorVm.Message = string.Format("{0}\r\n\r\n{1}", ex.ErrorMessage, ex.InnerException);

                Router.Navigate.Execute(errorVm);
                return(Observable.Return(RecoveryOptionResult.CancelOperation));
            });

            var shell = container.Resolve <ShellViewModel>();

            Router.Navigate.Execute(shell);
        }
Ejemplo n.º 20
0
        public AppBootstrapper(IMutableDependencyResolver dependencyResolver = null, IRoutingState testRouter = null)
        {
            Router = testRouter ?? new RoutingState();

            dependencyResolver = dependencyResolver ?? RxApp.MutableResolver;

            //bind our shit up
            RegisterParts(dependencyResolver);

            //navigate to first screen
            Router.Navigate.Execute(new EditorViewModel(this));
        }
Ejemplo n.º 21
0
        public AppBootstrapper()
        {
            Router = new RoutingState();

            Kernel = new TinyIoCContainer();

            // XXX: This is gross
            Kernel.Register <UIViewController>(new RouterUINavigationController(Router), "InitialPage");

            Kernel.Register(typeof(IViewFor <iOSPlaygroundViewModel>), typeof(iOSPlaygroundViewController));
            Kernel.Register <IScreen>(this);

            var toRegister = new Dictionary <Tuple <Type, String>, List <Type> >();

            RxApp.ConfigureServiceLocator(
                (t, s) => s != null ? Kernel.Resolve(t, s) : Kernel.Resolve(t),
                (t, s) => Kernel.ResolveAll(t, true),
                (c, t, s) => {
                if (toRegister != null)
                {
                    var pair = Tuple.Create(t, s);
                    if (!toRegister.ContainsKey(pair))
                    {
                        toRegister[pair] = new List <Type>();
                    }
                    toRegister[pair].Add(c);
                    return;
                }

                if (s != null)
                {
                    Kernel.Register(t, c, s);
                }
                else
                {
                    Kernel.Register(t, c);
                }
            });

            foreach (var key in toRegister.Keys)
            {
                var val = toRegister[key].Distinct();
                Kernel.RegisterMultiple(key.Item1, val);
            }

            toRegister = null;

            var items = Kernel.ResolveAll(typeof(ICreatesObservableForProperty), true).ToArray();

            Router.Navigate.Go <iOSPlaygroundViewModel>();
        }
Ejemplo n.º 22
0
        public AppBootstrapper(IRoutingState testRouter = null, ContainerBuilder builder = null)
        {
            Router = testRouter ?? new RoutingState();

            LogHost.Default.Level = LogLevel.Debug;

            ReactiveUIMicro.RxApp.ConfigureFileLogging("SquirrelDesktopDemo");

            var containerBuilder = builder ?? CreateStandardContainer();

            // AppBootstrapper is a global variable, so bind up
            containerBuilder.RegisterInstance(this)
                            .As<IScreen>()
                            .SingleInstance();
            
            // we want to create our UpdateManager in the same way each time
            containerBuilder.Register(ctx => {
                var settings = ctx.Resolve<ISettingsProvider>();
                return new UpdateManager(settings.UpdateLocation, "SquirrelDesktopDemo", FrameworkVersion.Net40);
            }).As<UpdateManager>();

            // by default i want this app to use the test feed
            // but you can change this value in the settings
            var settingsProvider = new SettingsProvider();
            settingsProvider.UpdateLocation = "http://shimmer-demo.herokuapp.com/demo/";

            var container = containerBuilder.Build();

            RxApp.ConfigureServiceLocator(
                (iface, contract) => container.Resolve(iface),
                (iface, contract) => {
                    var collection = typeof(IEnumerable<>).MakeGenericType(iface);
                    return container.Resolve(collection) as IEnumerable<object>;
                },
                (realClass, iface, contract) => {
                    var newBuilder = new ContainerBuilder();
                    newBuilder.RegisterType(realClass).As(iface);
                    newBuilder.Update(container);
                });

            UserError.RegisterHandler(ex => {
                var errorVm = container.Resolve<ErrorViewModel>();
                errorVm.Message = string.Format("{0}\r\n\r\n{1}", ex.ErrorMessage, ex.InnerException);

                Router.Navigate.Execute(errorVm);
                return Observable.Return(RecoveryOptionResult.CancelOperation);
            });

            var shell = container.Resolve<ShellViewModel>();
            Router.Navigate.Execute(shell);
        }
Ejemplo n.º 23
0
        public Shell(IRoutingState routingState)
        {
            InitializeComponent();

            ViewHost.Router = routingState;

            Loaded += (sender, e) =>
            {
                ViewModel.OnCompomentsRegisted.ObserveOnDispatcher().Subscribe(_ =>
                {
                    ViewModel.GoToDefaultPage();
                });
            };
        }
Ejemplo n.º 24
0
        public AppBootstrapper(IMutableDependencyResolver dependencyResolver = null, IRoutingState testRouter = null)
        {
            // Initialize the defaults from the constructor
            // (i think they are there for unit test purposes), even though they aren't used now.
            Router = testRouter ?? new RoutingState();
            dependencyResolver = dependencyResolver ?? RxApp.MutableResolver;

            // Declare the application name for Akavache
            BlobCache.ApplicationName = "StarHub";

            // Bind
            RegisterParts(dependencyResolver);

            // TODO: This is a good place to set up any other app
            // startup tasks, like setting the logging level
            LogHost.Default.Level = LogLevel.Debug;

            // Connect to GitHub
            LoadCredentials().Subscribe(creds =>
                {
                    Connection conn = new Connection(new ProductHeaderValue("StarHub"));
                    if (creds != null)
                    {
                        conn.Credentials = creds;
                    }
                    else
                    {
                        // For now, look for a token in the environment while i figure out how to get logins working
                        var authToken = Environment.GetEnvironmentVariable("OCTOKIT_GITHUBPASSWORD");
                        conn.Credentials = new Credentials(authToken);
                    }

                    GHClient = new GitHubClient(conn);

                    // Instantiate my view models
                    HomeVM = new HomeViewModel(this, GHClient);
                    Router.Navigate.Execute(HomeVM);
                });

            //LogInVM = new LogInViewModel(this, GHClient);

            //BlobCache.UserAccount.GetObjectAsync<string>("UserName").Subscribe(user =>
            //    {

            //    });

            // Make sure routing is set up
            //SetRoutingHome();
            //SetRoutingLogIn();
        }
Ejemplo n.º 25
0
        public AppBootstrapper(IMutableDependencyResolver dependencyResolver = null, IRoutingState testRouter = null)
        {
            // Initialize the defaults from the constructor
            // (i think they are there for unit test purposes), even though they aren't used now.
            Router             = testRouter ?? new RoutingState();
            dependencyResolver = dependencyResolver ?? RxApp.MutableResolver;

            // Declare the application name for Akavache
            BlobCache.ApplicationName = "StarHub";

            // Bind
            RegisterParts(dependencyResolver);

            // TODO: This is a good place to set up any other app
            // startup tasks, like setting the logging level
            LogHost.Default.Level = LogLevel.Debug;

            // Connect to GitHub
            LoadCredentials().Subscribe(creds =>
            {
                Connection conn = new Connection(new ProductHeaderValue("StarHub"));
                if (creds != null)
                {
                    conn.Credentials = creds;
                }
                else
                {
                    // For now, look for a token in the environment while i figure out how to get logins working
                    var authToken    = Environment.GetEnvironmentVariable("OCTOKIT_GITHUBPASSWORD");
                    conn.Credentials = new Credentials(authToken);
                }

                GHClient = new GitHubClient(conn);

                // Instantiate my view models
                HomeVM = new HomeViewModel(this, GHClient);
                Router.Navigate.Execute(HomeVM);
            });

            //LogInVM = new LogInViewModel(this, GHClient);

            //BlobCache.UserAccount.GetObjectAsync<string>("UserName").Subscribe(user =>
            //    {

            //    });

            // Make sure routing is set up
            //SetRoutingHome();
            //SetRoutingLogIn();
        }
        public AppBootstrapper(IMutableDependencyResolver dependencyResolver = null, IRoutingState testRouter = null)
        {
            Router = testRouter ?? new RoutingState();
            dependencyResolver = dependencyResolver ?? RxApp.MutableResolver;

            // Bind 
            RegisterParts(dependencyResolver);

            // TODO: This is a good place to set up any other app 
            // startup tasks, like setting the logging level
            LogHost.Default.Level = LogLevel.Debug;

            // Navigate to the opening page of the application
            Router.Navigate.Execute(new WelcomeViewModel(this));
        }
Ejemplo n.º 27
0
        public AppBootstrapper(IMutableDependencyResolver dependencyResolver = null, IRoutingState testRouter = null)
        {
            Router             = testRouter ?? new RoutingState();
            dependencyResolver = dependencyResolver ?? RxApp.MutableResolver;

            // Bind
            RegisterParts(dependencyResolver);

            // TODO: This is a good place to set up any other app
            // startup tasks, like setting the logging level
            LogHost.Default.Level = LogLevel.Debug;

            // Navigate to the opening page of the application
            Router.Navigate.Execute(new WelcomeViewModel(this));
        }
Ejemplo n.º 28
0
        public AppBootstrapper()
        {
            Router = new RoutingState();

            var resolver = RxApp.MutableResolver;

            resolver.Register(() => new LoginView(), typeof(IViewFor <LoginViewModel>), "FullScreenLandscape");

            resolver.Register(() => new LoginViewModel(), typeof(LoginViewModel));

            resolver.RegisterConstant(this, typeof(IApplicationRootState));
            resolver.RegisterConstant(this, typeof(IScreen));
            resolver.RegisterConstant(new MainPage(), typeof(IViewFor), "InitialPage");

            Router.Navigate.Execute(new LoginViewModel(this));
        }
Ejemplo n.º 29
0
        public AppViewModel(IKernel testKernel)
        {
            Router = new RoutingState();

            Kernel = testKernel ?? Kernel;
            Kernel.Bind<IScreen>().ToConstant(this);
            Kernel.Bind<IAppViewModel>().ToConstant(this);

            MessageBus.Current.Listen<Tuple<string, string>>("login").Subscribe(login => {
                User = login.Item1;
                Password = login.Item2;

                Router.NavigateAndReset.Execute(Kernel.Get<IRepoSelectionViewModel>());
            });

            Router.Navigate.Execute(Kernel.Get<ILoginViewModel>());
        }
Ejemplo n.º 30
0
        public AppViewModel(IKernel testKernel)
        {
            Router = new RoutingState();

            Kernel = testKernel ?? Kernel;
            Kernel.Bind <IScreen>().ToConstant(this);
            Kernel.Bind <IAppViewModel>().ToConstant(this);

            MessageBus.Current.Listen <Tuple <string, string> >("login").Subscribe(login => {
                User     = login.Item1;
                Password = login.Item2;

                Router.NavigateAndReset.Execute(Kernel.Get <IRepoSelectionViewModel>());
            });

            Router.Navigate.Execute(Kernel.Get <ILoginViewModel>());
        }
Ejemplo n.º 31
0
        public AppBootstrapper()
        {
            Router = new RoutingState();

            Kernel = new TinyIoCContainer();

            // XXX: This is gross
            Kernel.Register<UIViewController>(new RouterUINavigationController(Router), "InitialPage");

            Kernel.Register(typeof(IViewFor<iOSPlaygroundViewModel>), typeof(iOSPlaygroundViewController));
            Kernel.Register<IScreen>(this);

            var toRegister = new Dictionary<Tuple<Type, String>, List<Type>>();

            RxApp.ConfigureServiceLocator(
                (t, s) => s != null ? Kernel.Resolve(t, s) : Kernel.Resolve(t),
                (t, s) => Kernel.ResolveAll(t, true),
                (c, t, s) => { 
                    if (toRegister != null) {
                        var pair = Tuple.Create(t,s);
                        if (!toRegister.ContainsKey(pair)) {
                            toRegister[pair] = new List<Type>();
                        }
                        toRegister[pair].Add(c);
                        return;
                    }

                    if (s != null) { 
                        Kernel.Register(t, c, s); 
                    } else { 
                        Kernel.Register(t, c); 
                    } 
                });

            foreach(var key in toRegister.Keys) {
                var val = toRegister[key].Distinct();
                Kernel.RegisterMultiple(key.Item1, val);
            }

            toRegister = null;

            var items = Kernel.ResolveAll(typeof(ICreatesObservableForProperty), true).ToArray();

            Router.Navigate.Go<iOSPlaygroundViewModel>();
        }
Ejemplo n.º 32
0
        public RouterUINavigationController(IRoutingState router)
        {
            this.router = router;

            router.Navigate.Subscribe(x => {
                var view       = RxRouting.ResolveView(x);
                view.ViewModel = x;

                this.PushViewController((UIViewController)view, true);
            });

            router.NavigateBack.Subscribe(_ => this.PopViewControllerAnimated(true));
            router.NavigateAndReset.Subscribe(x => {
                this.PopToRootViewController(false);
                router.Navigate.Execute(x);
            });

            this.Delegate = new RouterUINavigationControllerDelegate(this, router);
        }
Ejemplo n.º 33
0
        public AppBootstrapper()
        {
            Router = new RoutingState();

            var resolver = RxApp.MutableResolver;

            resolver.Register(() => new TestPage1View(), typeof(IViewFor<TestPage1ViewModel>), "FullScreenLandscape");
            resolver.Register(() => new TestPage2View(), typeof(IViewFor<TestPage2ViewModel>), "FullScreenLandscape");
            resolver.Register(() => new TestPage3View(), typeof(IViewFor<TestPage3ViewModel>), "FullScreenLandscape");

            resolver.Register(() => new TestPage1ViewModel(), typeof(TestPage1ViewModel));
            resolver.Register(() => new TestPage2ViewModel(), typeof(TestPage2ViewModel));
            resolver.Register(() => new TestPage3ViewModel(), typeof(TestPage3ViewModel));

            resolver.RegisterConstant(this, typeof(IApplicationRootState));
            resolver.RegisterConstant(this, typeof(IScreen));
            resolver.RegisterConstant(new MainPage(), typeof(IViewFor), "InitialPage");

            Router.Navigate.Execute(new TestPage1ViewModel(this));
        }
Ejemplo n.º 34
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            Router =new RoutingState();
            var dependencyResolver = (ModernDependencyResolver) RxApp.MutableResolver;

            RegisterParts(dependencyResolver);

            LogHost.Default.Level = LogLevel.Debug;

            var service = RxApp.DependencyResolver.GetService<IService>();
            if (!service.IsActive)
            {
                service.Start();
            }

            var message = RxApp.DependencyResolver.GetService<INotificationViewModel>();
            this.Router.Navigate.Execute(message);
        }
Ejemplo n.º 35
0
        public AppBootstrapper(IKernel testKernel = null, IRoutingState testRouter = null)
        {
            Router = testRouter ?? new RoutingState();
            var kernel = testKernel ?? CreateStandardKernel();

            // AppBootstrapper is a global variable, so bind up
            kernel.Bind(typeof(IScreen), typeof(AppBootstrapper)).ToConstant(this);

            // Set up NInject to do DI
            RxApp.ConfigureServiceLocator(
                (iface, contract) => {
                if (contract != null)
                {
                    return(kernel.Get(iface, contract));
                }
                return(kernel.Get(iface));
            },
                (iface, contract) => {
                if (contract != null)
                {
                    return(kernel.GetAll(iface, contract));
                }
                return(kernel.GetAll(iface));
            },
                (realClass, iface, contract) => {
                var binding = kernel.Bind(iface).To(realClass);
                if (contract != null)
                {
                    binding.Named(contract);
                }
            });

            // TODO: This is a good place to set up any other app
            // startup tasks, like setting the logging level
            LogHost.Default.Level = LogLevel.Debug;

            // Navigate to the opening page of the application
            var welcomeVm = RxApp.GetService <IWelcomeViewModel>();

            Router.Navigate.Execute(welcomeVm);
        }
Ejemplo n.º 36
0
        public ShellViewModel(EventAggregator eventAggregator, IRoutingState router)
        {
            var logger = NLog.LogManager.GetCurrentClassLogger();

            _router = router;

            OnCompomentsRegisted = Observable.Create <Unit>(observer => Scheduler.Default.Schedule(() =>
            {
                logger.Info(string.Format("Starting Compoments Registration on thread {0}.", Thread.CurrentThread));

                eventAggregator.Publish(new OpenNewLifetimeScopeCommand(builder =>
                {
                    builder.RegisterType <WelcomeViewModel>().InstancePerLifetimeScope();
                    builder.RegisterType <Welcome>().As <IViewFor <WelcomeViewModel> >().InstancePerLifetimeScope();

                    builder.RegisterType <NextPage1ViewModel>().InstancePerLifetimeScope();
                    builder.RegisterType <NextPage1>().As <IViewFor <NextPage1ViewModel> >().InstancePerLifetimeScope();
                }));
                observer.OnNext(Unit.Default);
                observer.OnCompleted();
            }));
        }
Ejemplo n.º 37
0
        public ShellViewModel(EventAggregator eventAggregator, IRoutingState router)
        {
            var logger = NLog.LogManager.GetCurrentClassLogger();

            _router = router;

            OnCompomentsRegisted = Observable.Create<Unit>(observer => Scheduler.Default.Schedule(() =>
            {
                logger.Info(string.Format("Starting Compoments Registration on thread {0}.", Thread.CurrentThread));

                eventAggregator.Publish(new OpenNewLifetimeScopeCommand(builder =>
                {
                    builder.RegisterType<WelcomeViewModel>().InstancePerLifetimeScope();
                    builder.RegisterType<Welcome>().As<IViewFor<WelcomeViewModel>>().InstancePerLifetimeScope();

                    builder.RegisterType<NextPage1ViewModel>().InstancePerLifetimeScope();
                    builder.RegisterType<NextPage1>().As<IViewFor<NextPage1ViewModel>>().InstancePerLifetimeScope();
                }));
                observer.OnNext(Unit.Default);
                observer.OnCompleted();
            }));
        }
Ejemplo n.º 38
0
        public AppBootstrapper(IKernel testKernel = null, IRoutingState router = null)
        {
            BlobCache.ApplicationName = "PlayForWindows";

            Kernel = testKernel ?? createDefaultKernel();
            Kernel.Bind<IAppBootstrapper>().ToConstant(this);
            Router = router ?? new RoutingState();

            apiFactory = Kernel.TryGet<Func<IObservable<IPlayApi>>>("ApiFactory");

            RxApp.ConfigureServiceLocator(
                (type, contract) => Kernel.Get(type, contract),
                (type, contract) => Kernel.GetAll(type, contract));

            LoadCredentials().Subscribe(
                x => {
                    CurrentAuthenticatedClient = x;
                    Router.Navigate.Execute(Kernel.Get<IPlayViewModel>());
                }, ex => {
                    this.Log().WarnException("Failed to load credentials, going to login screen", ex);
                    Router.Navigate.Execute(Kernel.Get<IPlayViewModel>());
                });
        }
Ejemplo n.º 39
0
        public AppBootstrapper(IKernel testKernel = null, IRoutingState router = null)
        {
            BlobCache.ApplicationName = "PlayForWindows";

            Kernel = testKernel ?? createDefaultKernel();
            Kernel.Bind <IAppBootstrapper>().ToConstant(this);
            Router = router ?? new RoutingState();

            apiFactory = Kernel.TryGet <Func <IObservable <IPlayApi> > >("ApiFactory");

            RxApp.ConfigureServiceLocator(
                (type, contract) => Kernel.Get(type, contract),
                (type, contract) => Kernel.GetAll(type, contract));

            LoadCredentials().Subscribe(
                x => {
                CurrentAuthenticatedClient = x;
                Router.Navigate.Execute(Kernel.Get <IPlayViewModel>());
            }, ex => {
                this.Log().WarnException("Failed to load credentials, going to login screen", ex);
                Router.Navigate.Execute(Kernel.Get <IPlayViewModel>());
            });
        }
        public AppBootstrapper(IMutableDependencyResolver dependencyResolver = null, IRoutingState routingState = null)
        {
            #region Handle Optional Parameters
            Router = routingState ?? new RoutingState();

            var kernel = new StandardKernel();

            RxApp.DependencyResolver = dependencyResolver ?? new FuncDependencyResolver((type, contract) => kernel.GetAll(type, contract));

            if (dependencyResolver == null)
                RxApp.InitializeCustomResolver((obj, type) => kernel.Bind(type).ToConstant(obj));
            #endregion

            #region Ninject Setup
            // Singletons
            kernel.Bind<IScreen>().ToConstant<AppBootstrapper>(this);
            kernel.Bind<ILogPeopleIn>().To<LoginManager>().InSingletonScope();

            // View resolution
            kernel.Bind<IViewFor<LoginWidgetViewModel>>().To<LoginWidgetView>();
            kernel.Bind<IViewFor<MainViewModel>>().To<MainView>();
            kernel.Bind<IViewFor<CreateTicketsViewModel>>().To<CreateTicketsView>();
            kernel.Bind<IViewFor<DispatchViewModel>>().To<DispatchView>();
            kernel.Bind<IViewFor<AssignedTicketsViewModel>>().To<AssignedTicketsView>();

            // Persistence
            kernel.Bind<ISession>().To<TicketingSession>().InParentScope();

            #endregion

            LogHost.Default.Level = LogLevel.Debug;

            LoginWidgetViewModel = kernel.Get<LoginWidgetViewModel>();

            Router.Navigate.Execute(kernel.Get<MainViewModel>());
        }
Ejemplo n.º 41
0
        public AppBootstrapper(IRoutingState router)
        {
            if (router == null) throw new ArgumentNullException("router");
            Router = router ;
            var container = CreateContainer();
            RxApp.ConfigureServiceLocator(
                (serviceType, contract) => {
                        if (contract != null) return container.ResolveNamed(contract, serviceType);
                        return container.Resolve(serviceType);
                    },
                (serviceType, contract) => {
                    var enumerableType = typeof(IEnumerable<>).MakeGenericType(serviceType);
                    var instance = contract != null
                        ? (IEnumerable)container.ResolveNamed(contract, enumerableType)
                        : (IEnumerable)container.Resolve(enumerableType);
                    return instance.Cast<object>();
                },
                (impl, serviveType, contract) => {
                    var builder = new ContainerBuilder();
                    builder.RegisterType(impl).As(serviveType);
                    if (contract != null)
                    {
                        builder.RegisterType(impl).Named(contract, serviveType);
                    }
                    builder.Update(container);
                }
            );

            // TODO: This is a good place to set up any other app
            // startup tasks, like setting the logging level
            LogHost.Default.Level = LogLevel.Debug;

            // Navigate to the opening page of the application
            var vm = RxApp.GetService<IHomeViewModel>();
            Router.Navigate.Execute(vm);
        }
Ejemplo n.º 42
0
        static void mockPerformInstall(
            IRoutingState router,
            IObserver <DetectPackageCompleteEventArgs> detectPackage,
            IObserver <PlanCompleteEventArgs> planComplete,
            IObserver <ApplyCompleteEventArgs> applyComplete,
            Mock <IEngine> engine)
        {
            // initialize the install process
            detectPackage.OnNext(new DetectPackageCompleteEventArgs("UserApplicationId", 0, PackageState.Present));

            // navigate to the next VM
            var viewModel = router.GetCurrentViewModel() as WelcomeViewModel;

            viewModel.ShouldProceed.Execute(null);

            // signal to start the install
            planComplete.OnNext(new PlanCompleteEventArgs(0));

            // wait until install is complete
            engine.WaitUntil(e => e.Apply(It.IsAny <IntPtr>()));

            // now signal it's completed
            applyComplete.OnNext(new ApplyCompleteEventArgs(0, ApplyRestart.None));
        }
Ejemplo n.º 43
0
        static ISearchViewModel setupStandardFixture(MoqMockingKernel kernel, IRoutingState router = null)
        {
            router = router ?? new RoutingState();
            kernel.Bind<ISearchViewModel>().To<SearchViewModel>();
            kernel.Bind<IBlobCache>().To<TestBlobCache>().Named("UserAccount");
            kernel.Bind<IBlobCache>().To<TestBlobCache>().Named("LocalMachine");

            kernel.GetMock<IPlayApi>().Setup(x => x.Search("Foo"))
                .Returns(Observable.Return(new List<Song>() { Fakes.GetSong() }))
                .Verifiable();

            kernel.GetMock<ILoginMethods>().Setup(x => x.CurrentAuthenticatedClient).Returns(kernel.Get<IPlayApi>());
            kernel.GetMock<IScreen>().Setup(x => x.Router).Returns(router);

            var img = new BitmapImage();
            kernel.GetMock<IPlayApi>().Setup(x => x.FetchImageForAlbum(It.IsAny<Song>()))
                .Returns(Observable.Return(img))
                .Verifiable();

            RxApp.ConfigureServiceLocator((t,s) => kernel.Get(t,s), (t,s) => kernel.GetAll(t,s));

            var fixture = kernel.Get<ISearchViewModel>();
            return fixture;
        }
Ejemplo n.º 44
0
 /// <summary>
 /// Returns the currently visible ViewModel
 /// </summary>
 public static IRoutableViewModel GetCurrentViewModel(this IRoutingState This)
 {
     return(This.NavigationStack.LastOrDefault());
 }
Ejemplo n.º 45
0
 /// <summary>
 /// Locate the first ViewModel in the stack that matches a certain Type.
 /// </summary>
 /// <returns>The matching ViewModel or null if none exists.</returns>
 public static T FindViewModelInStack <T>(this IRoutingState This)
     where T : IRoutableViewModel
 {
     return(This.NavigationStack.Reverse().OfType <T>().FirstOrDefault());
 }
Ejemplo n.º 46
0
 /// <summary>
 /// Returns an Observable that signals ViewModel changes.
 /// </summary>
 public static IObservable <IRoutableViewModel> ViewModelObservable(this IRoutingState This)
 {
     return(This.NavigationStack.CollectionCountChanged
            .Select(_ => This.GetCurrentViewModel())
            .StartWith(This.GetCurrentViewModel()));
 }
Ejemplo n.º 47
0
 /// <summary>
 /// Generates a routing Uri based on the current route state
 /// </summary>
 /// <returns></returns>
 public static string GetUrlForCurrentRoute(this IRoutingState This)
 {
     return("app://" + String.Join("/", This.NavigationStack.Select(x => x.UrlPathSegment)));
 }
Ejemplo n.º 48
0
        public WixUiBootstrapper(IWiXEvents wixEvents, TinyIoCContainer testKernel = null, IRoutingState router = null, IFileSystemFactory fileSystem = null, string currentAssemblyDir = null)
        {
            Kernel = testKernel ?? createDefaultKernel();
            this.fileSystem = fileSystem ?? AnonFileSystem.Default;
            this.currentAssemblyDir = currentAssemblyDir ?? Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            RxApp.ConfigureServiceLocator(
                (type, contract) => String.IsNullOrEmpty(contract) ?
                    Kernel.Resolve(type) :
                    Kernel.Resolve(type, contract),
                (type, contract) => Kernel.ResolveAll(type, true),
                (c, t, s) => {
                    if (String.IsNullOrEmpty(s)) {
                        Kernel.Register(t, c, Guid.NewGuid().ToString());
                    } else {
                        Kernel.Register(t, c, s);
                    }
                });

            RxRouting.ViewModelToViewFunc = findViewClassNameForViewModelName;

            Kernel.Register<IWixUiBootstrapper>(this);
            Kernel.Register<IScreen>(this);
            Kernel.Register(wixEvents);

            Router = router ?? new RoutingState();
            WiXEvents = wixEvents;

            _BundledRelease = new Lazy<ReleaseEntry>(readBundledReleasesFile);

            registerExtensionDlls(Kernel);

            UserError.RegisterHandler(ex => {
                if (wixEvents.DisplayMode != Display.Full) {
                    this.Log().Error(ex.ErrorMessage);
                    wixEvents.ShouldQuit();
                }

                var errorVm = RxApp.GetService<IErrorViewModel>();
                errorVm.Error = ex;

                RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(errorVm));
                return Observable.Return(RecoveryOptionResult.CancelOperation);
            });

            bundledPackageMetadata = new Lazy<IPackage>(openBundledPackage);

            wixEvents.DetectPackageCompleteObs.Subscribe(eventArgs => {
                var error = convertHResultToError(eventArgs.Status);
                if (error != null) {
                    UserError.Throw(error);
                    return;
                }

                if (wixEvents.Action == LaunchAction.Uninstall) {
                    var uninstallVm = RxApp.GetService<IUninstallingViewModel>();
                    Router.Navigate.Execute(uninstallVm);
                    wixEvents.Engine.Plan(LaunchAction.Uninstall);
                    return;
                }

                // TODO: If the app is already installed, run it and bail
                // If Display is silent, we should just exit here.

                if (wixEvents.Action == LaunchAction.Install) {
                    if (wixEvents.DisplayMode != Display.Full) {
                        wixEvents.Engine.Plan(LaunchAction.Install);
                        return;
                    }

                    var welcomeVm = RxApp.GetService<IWelcomeViewModel>();
                    welcomeVm.PackageMetadata = bundledPackageMetadata.Value;
                    welcomeVm.ShouldProceed.Subscribe(_ => wixEvents.Engine.Plan(LaunchAction.Install));

                    // NB: WiX runs a "Main thread" that all of these events
                    // come back on, and a "UI thread" where it actually runs
                    // the WPF window. Gotta proxy to the UI thread.
                    RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(welcomeVm));
                }
            });

            var executablesToStart = Enumerable.Empty<string>();

            wixEvents.PlanCompleteObs.Subscribe(eventArgs => {
                var installManager = new InstallManager(BundledRelease);
                var error = convertHResultToError(eventArgs.Status);
                if (error != null) {
                    UserError.Throw(error);
                    return;
                }

                if (wixEvents.Action == LaunchAction.Uninstall) {
                    installManager.ExecuteUninstall().Subscribe(
                        _ => wixEvents.Engine.Apply(wixEvents.MainWindowHwnd),
                        ex => UserError.Throw(new UserError("Failed to uninstall", ex.Message, innerException: ex)));
                    return;
                }

                IObserver<int> progress = null;

                if (wixEvents.DisplayMode == Display.Full) {
                    var installingVm = RxApp.GetService<IInstallingViewModel>();
                    progress = installingVm.ProgressValue;
                    installingVm.PackageMetadata = bundledPackageMetadata.Value;
                    RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(installingVm));
                }

                installManager.ExecuteInstall(this.currentAssemblyDir, bundledPackageMetadata.Value, progress).Subscribe(
                    toStart => {
                        executablesToStart = toStart ?? executablesToStart;
                        wixEvents.Engine.Apply(wixEvents.MainWindowHwnd);
                    },
                    ex => UserError.Throw("Failed to install application", ex));
            });

            wixEvents.ApplyCompleteObs.Subscribe(eventArgs => {
                var error = convertHResultToError(eventArgs.Status);
                if (error != null) {
                    UserError.Throw(error);
                    return;
                }

                if (wixEvents.DisplayMode == Display.Full && wixEvents.Action == LaunchAction.Install) {
                    foreach (var path in executablesToStart) { Process.Start(path); }
                }

                wixEvents.ShouldQuit();
            });

            wixEvents.ErrorObs.Subscribe(eventArgs => UserError.Throw("An installation error has occurred: " + eventArgs.ErrorMessage));

            wixEvents.Engine.Detect();
        }
Ejemplo n.º 49
0
        public WixUiBootstrapper(IWiXEvents wixEvents, TinyIoCContainer testKernel = null, IRoutingState router = null)
        {
            Kernel = testKernel ?? createDefaultKernel();

            Kernel.Register <IWixUiBootstrapper>(this);
            Kernel.Register <IScreen>(this);
            Kernel.Register(wixEvents);

            Router    = router ?? new RoutingState();
            WiXEvents = wixEvents;

            _BundledRelease = new Lazy <ReleaseEntry>(readBundledReleasesFile);

            registerExtensionDlls(Kernel);

            RxApp.ConfigureServiceLocator(
                (type, contract) => Kernel.Resolve(type, contract),
                (type, contract) => Kernel.ResolveAll(type),
                (c, t, s) => Kernel.Register(t, c, s));

            UserError.RegisterHandler(ex => {
                if (wixEvents.Command.Display != Display.Full)
                {
                    this.Log().Error(ex.ErrorMessage);
                    wixEvents.ShouldQuit();
                }

                var errorVm   = RxApp.GetService <IErrorViewModel>();
                errorVm.Error = ex;
                Router.Navigate.Execute(errorVm);

                return(Observable.Return(RecoveryOptionResult.CancelOperation));
            });

            var bundledPackageMetadata = openBundledPackage();

            wixEvents.DetectPackageCompleteObs.Subscribe(eventArgs => {
                var error = convertHResultToError(eventArgs.Status);
                if (error != null)
                {
                    UserError.Throw(error);
                    return;
                }

                // TODO: If the app is already installed, run it and bail

                if (wixEvents.Command.Action == LaunchAction.Uninstall)
                {
                    var updateManager = new UpdateManager("http://lol", BundledRelease.PackageName, FrameworkVersion.Net40);

                    var updateLock = updateManager.AcquireUpdateLock();
                    updateManager.FullUninstall()
                    .ObserveOn(RxApp.DeferredScheduler)
                    .Log(this, "Full uninstall")
                    .Finally(updateLock.Dispose)
                    .Subscribe(
                        _ => wixEvents.Engine.Plan(LaunchAction.Uninstall),
                        ex => UserError.Throw("Failed to uninstall application", ex),
                        () => wixEvents.ShouldQuit());

                    return;
                }

                if (wixEvents.Command.Action == LaunchAction.Install)
                {
                    if (wixEvents.Command.Display != Display.Full)
                    {
                        wixEvents.Engine.Plan(LaunchAction.Install);
                        return;
                    }

                    var welcomeVm             = RxApp.GetService <IWelcomeViewModel>();
                    welcomeVm.PackageMetadata = bundledPackageMetadata;
                    welcomeVm.ShouldProceed.Subscribe(_ => wixEvents.Engine.Plan(LaunchAction.Install));

                    Router.Navigate.Execute(welcomeVm);
                }
            });

            wixEvents.PlanCompleteObs.Subscribe(eventArgs => {
                var error = convertHResultToError(eventArgs.Status);
                if (error != null)
                {
                    UserError.Throw(error);
                    return;
                }

                if (wixEvents.Command.Action != LaunchAction.Install)
                {
                    wixEvents.Engine.Apply(wixEvents.MainWindowHwnd);
                    return;
                }

                // NB: Create a dummy subject to receive progress if we're in silent mode
                IObserver <int> progress = new Subject <int>();
                if (wixEvents.Command.Display == Display.Full)
                {
                    var installingVm             = RxApp.GetService <IInstallingViewModel>();
                    progress                     = installingVm.ProgressValue;
                    installingVm.PackageMetadata = bundledPackageMetadata;
                    Router.Navigate.Execute(installingVm);
                }

                // NB: This bit of code is a bit clever. The binaries that WiX
                // has installed *itself* meets the qualifications for being a
                // Shimmer update directory (a RELEASES file and the corresponding
                // NuGet packages).
                //
                // So, in order to reuse some code and not write the same things
                // twice we're going to "Eigenupdate" from our own directory;
                // UpdateManager will operate in bootstrap mode and create a
                // local directory for us.
                //
                // Then, we create a *new* UpdateManager whose target is the normal
                // update URL - we can then apply delta updates against the bundled
                // NuGet package to get up to vCurrent. The reason we go through
                // this rigamarole is so that developers don't have to rebuild the
                // installer as often (never, technically).

                var fxVersion    = determineFxVersionFromPackage(bundledPackageMetadata);
                var eigenUpdater = new UpdateManager(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), BundledRelease.PackageName, fxVersion);

                var eigenLock = eigenUpdater.AcquireUpdateLock();

                var eigenUpdateProgress = eigenUpdater.CheckForUpdate()
                                          .SelectMany(x => eigenUpdater.DownloadReleases(x.ReleasesToApply))
                                          .Finally(eigenLock.Dispose)
                                          .Select(x => x / 2)
                                          .Multicast(new Subject <int>());

                eigenUpdateProgress.Subscribe(progress);
                eigenUpdateProgress.Connect();

                var realUpdateProgress = eigenUpdateProgress.TakeLast(1)
                                         .SelectMany(_ => {
                    var realUpdateManager = new UpdateManager(bundledPackageMetadata.ProjectUrl.ToString(), BundledRelease.PackageName, fxVersion);

                    return(realUpdateManager.CheckForUpdate()
                           .SelectMany(updateInfo => {
                        return Observable.Concat(
                            realUpdateManager.DownloadReleases(updateInfo.ReleasesToApply).Select(x => x * 0.75),
                            realUpdateManager.ApplyReleases(updateInfo).Select(x => x * 0.25 + 75))
                        .Select(x => (int)x);
                    }).LoggedCatch(this, Observable.Return(100), "Failed to update to latest remote version"));
                })
                                         .Select(x => x / 2 + 50)
                                         .Multicast(new Subject <int>());

                realUpdateProgress.Subscribe(progress);
                realUpdateProgress.Connect();

                realUpdateProgress
                .TakeLast(1)
                .ObserveOn(RxApp.DeferredScheduler)
                .Subscribe(
                    _ => wixEvents.Engine.Apply(wixEvents.MainWindowHwnd),
                    ex => UserError.Throw("Failed to install application", ex));
            });

            wixEvents.ApplyCompleteObs.Subscribe(eventArgs => {
                var error = convertHResultToError(eventArgs.Status);
                if (error != null)
                {
                    UserError.Throw(error);
                    return;
                }

                if (wixEvents.Command.Display != Display.Full)
                {
                    wixEvents.ShouldQuit();
                }

                // TODO: Figure out what the "main app" is and run it
            });

            wixEvents.ErrorObs.Subscribe(eventArgs => UserError.Throw("An installation error has occurred: " + eventArgs.ErrorMessage));
        }
Ejemplo n.º 50
0
        public WixUiBootstrapper(IWiXEvents wixEvents, TinyIoCContainer testKernel = null, IRoutingState router = null)
        {
            Kernel = testKernel ?? createDefaultKernel();
            Kernel.Register<IWixUiBootstrapper>(this).AsSingleton();
            Kernel.Register<IScreen>(this);
            Kernel.Register(wixEvents);

            Router = router ?? new RoutingState();
            WiXEvents = wixEvents;

            _BundledRelease = new Lazy<ReleaseEntry>(readBundledReleasesFile);

            registerExtensionDlls(Kernel);

            RxApp.ConfigureServiceLocator(
                (type, contract) => Kernel.Resolve(type, contract),
                (type, contract) => Kernel.ResolveAll(type),
                (c, t, s) => Kernel.Register(t, c, s));

            UserError.RegisterHandler(ex => {
                if (wixEvents.Command.Display != Display.Full) {
                    this.Log().Error(ex.ErrorMessage);
                    wixEvents.ShouldQuit();
                }

                var errorVm = RxApp.GetService<IErrorViewModel>();
                errorVm.Error = ex;
                Router.Navigate.Execute(errorVm);

                return Observable.Return(RecoveryOptionResult.CancelOperation);
            });

            var bundledPackageMetadata = openBundledPackage();

            wixEvents.DetectPackageCompleteObs.Subscribe(eventArgs => {
                var error = convertHResultToError(eventArgs.Status);
                if (error != null) {
                    UserError.Throw(error);
                    return;
                }

                // TODO: If the app is already installed, run it and bail

                if (wixEvents.Command.Action == LaunchAction.Uninstall) {
                    var updateManager = new UpdateManager("http://lol", BundledRelease.PackageName, FrameworkVersion.Net40);

                    var updateLock = updateManager.AcquireUpdateLock();
                    updateManager.FullUninstall()
                        .ObserveOn(RxApp.DeferredScheduler)
                        .Log(this, "Failed uninstall")
                        .Finally(updateLock.Dispose)
                        .Subscribe(
                            _ => wixEvents.Engine.Plan(LaunchAction.Uninstall),
                            ex => UserError.Throw("Failed to uninstall application", ex),
                            () => wixEvents.ShouldQuit());

                    return;
                }

                if (wixEvents.Command.Action == LaunchAction.Install) {
                    if (wixEvents.Command.Display != Display.Full) {
                        wixEvents.Engine.Plan(LaunchAction.Install);
                        return;
                    }

                    var welcomeVm = RxApp.GetService<IWelcomeViewModel>();
                    welcomeVm.PackageMetadata = bundledPackageMetadata;
                    welcomeVm.ShouldProceed.Subscribe(_ => wixEvents.Engine.Plan(LaunchAction.Install));

                    Router.Navigate.Execute(welcomeVm);
                }
            });

            wixEvents.PlanCompleteObs.Subscribe(eventArgs => {
                var error = convertHResultToError(eventArgs.Status);
                if (error != null) {
                    UserError.Throw(error);
                    return;
                }

                if (wixEvents.Command.Action != LaunchAction.Install) {
                    wixEvents.Engine.Apply(wixEvents.MainWindowHwnd);
                    return;
                }

                // NB: Create a dummy subject to receive progress if we're in silent mode
                IObserver<int> progress = new Subject<int>();
                if (wixEvents.Command.Display == Display.Full) {
                    var installingVm = RxApp.GetService<IInstallingViewModel>();
                    progress = installingVm.ProgressValue;
                    installingVm.PackageMetadata = bundledPackageMetadata;
                    Router.Navigate.Execute(installingVm);
                }

                // NB: This bit of code is a bit clever. The binaries that WiX
                // has installed *itself* meets the qualifications for being a
                // Shimmer update directory (a RELEASES file and the corresponding
                // NuGet packages).
                //
                // So, in order to reuse some code and not write the same things
                // twice we're going to "Eigenupdate" from our own directory;
                // UpdateManager will operate in bootstrap mode and create a
                // local directory for us.
                //
                // Then, we create a *new* UpdateManager whose target is the normal
                // update URL - we can then apply delta updates against the bundled
                // NuGet package to get up to vCurrent. The reason we go through
                // this rigamarole is so that developers don't have to rebuild the
                // installer as often (never, technically).

                var fxVersion = determineFxVersionFromPackage(bundledPackageMetadata);
                var eigenUpdater = new UpdateManager(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), BundledRelease.PackageName, fxVersion);

                var eigenLock = eigenUpdater.AcquireUpdateLock();

                var eigenUpdateProgress = eigenUpdater.CheckForUpdate()
                    .SelectMany(x => eigenUpdater.DownloadReleases(x.ReleasesToApply))
                    .Finally(eigenLock.Dispose)
                    .Select(x => x / 2)
                    .Multicast(new Subject<int>());

                eigenUpdateProgress.Subscribe(progress);
                eigenUpdateProgress.Connect();

                var realUpdateProgress = eigenUpdateProgress.TakeLast(1)
                    .SelectMany(_ => {
                        var realUpdateManager = new UpdateManager(bundledPackageMetadata.ProjectUrl.ToString(), BundledRelease.PackageName, fxVersion);

                        return realUpdateManager.CheckForUpdate()
                            .SelectMany(updateInfo => {
                                return Observable.Concat(
                                    realUpdateManager.DownloadReleases(updateInfo.ReleasesToApply).Select(x => x * 0.75),
                                    realUpdateManager.ApplyReleases(updateInfo).Select(x => x * 0.25 + 75))
                                        .Select(x => (int)x);
                            }).LoggedCatch(this, Observable.Return(100), "Failed to update to latest remote version");
                    })
                    .Select(x => x / 2 + 50)
                    .Multicast(new Subject<int>());

                realUpdateProgress.Subscribe(progress);
                realUpdateProgress.Connect();

                realUpdateProgress
                    .TakeLast(1)
                    .ObserveOn(RxApp.DeferredScheduler)
                    .Subscribe(
                        _ => wixEvents.Engine.Apply(wixEvents.MainWindowHwnd),
                        ex => UserError.Throw("Failed to install application", ex));
            });

            wixEvents.ApplyCompleteObs.Subscribe(eventArgs => {
                var error = convertHResultToError(eventArgs.Status);
                if (error != null) {
                    UserError.Throw(error);
                    return;
                }

                if (wixEvents.Command.Display != Display.Full) {
                    wixEvents.ShouldQuit();
                }

                // TODO: Figure out what the "main app" is and run it
            });

            wixEvents.ErrorObs.Subscribe(eventArgs => UserError.Throw("An installation error has occurred: " + eventArgs.ErrorMessage));
        }
Ejemplo n.º 51
0
        public WixUiBootstrapper(IWiXEvents wixEvents, TinyIoCContainer testKernel = null, IRoutingState router = null, IFileSystemFactory fileSystem = null, string currentAssemblyDir = null)
        {
            Kernel                  = testKernel ?? createDefaultKernel();
            this.fileSystem         = fileSystem ?? AnonFileSystem.Default;
            this.currentAssemblyDir = currentAssemblyDir ?? Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            RxApp.ConfigureServiceLocator(
                (type, contract) => {
                this.Log().Info("Resolving type '{0}' with contract '{1}'", type, contract);
                return(String.IsNullOrEmpty(contract)
                        ? Kernel.Resolve(type)
                        : Kernel.Resolve(type, contract));
            },
                (type, contract) => Kernel.ResolveAll(type, true),
                (c, t, s) => {
                this.Log().Info("Registering type '{0}' for interface '{1}' and contract '{2}'", c, t, s);
                if (String.IsNullOrEmpty(s))
                {
                    Kernel.Register(t, c, Guid.NewGuid().ToString());
                }
                else
                {
                    Kernel.Register(t, c, s);
                }
            });

            RxRouting.ViewModelToViewFunc = findViewClassNameForViewModelName;

            Kernel.Register <IWixUiBootstrapper>(this);
            Kernel.Register <IScreen>(this);
            Kernel.Register(wixEvents);

            Router    = router ?? new RoutingState();
            WiXEvents = wixEvents;

            _BundledRelease = new Lazy <ReleaseEntry>(readBundledReleasesFile);

            registerExtensionDlls(Kernel);

            UserError.RegisterHandler(ex => {
                this.Log().ErrorException("Something unexpected happened", ex.InnerException);

                if (wixEvents.DisplayMode != Display.Full)
                {
                    this.Log().Error(ex.ErrorMessage);
                    wixEvents.ShouldQuit();
                }

                var errorVm   = RxApp.GetService <IErrorViewModel>();
                errorVm.Error = ex;
                errorVm.Shutdown.Subscribe(_ => wixEvents.ShouldQuit());
                errorVm.OpenLogsFolder.Subscribe(_ => openLogsFolder());

                RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(errorVm));
                return(Observable.Return(RecoveryOptionResult.CancelOperation));
            });

            bundledPackageMetadata = new Lazy <IPackage>(openBundledPackage);

            wixEvents.DetectPackageCompleteObs.Subscribe(eventArgs => {
                var error = convertHResultToError(eventArgs.Status);
                if (error != null)
                {
                    UserError.Throw(error);
                    return;
                }

                if (wixEvents.Action == LaunchAction.Uninstall)
                {
                    this.Log().Info("Shimmer is doing an uninstall! Sadface!");
                    var uninstallVm = RxApp.GetService <IUninstallingViewModel>();
                    Router.Navigate.Execute(uninstallVm);
                    wixEvents.Engine.Plan(LaunchAction.Uninstall);
                    return;
                }

                // TODO: If the app is already installed, run it and bail
                // If Display is silent, we should just exit here.

                if (wixEvents.Action == LaunchAction.Install)
                {
                    if (wixEvents.DisplayMode != Display.Full)
                    {
                        this.Log().Info("Shimmer is doing a silent install! Sneaky!");
                        wixEvents.Engine.Plan(LaunchAction.Install);
                        return;
                    }

                    this.Log().Info("We are doing an UI install! Huzzah!");

                    var welcomeVm             = RxApp.GetService <IWelcomeViewModel>();
                    welcomeVm.PackageMetadata = bundledPackageMetadata.Value;
                    welcomeVm.ShouldProceed.Subscribe(_ => wixEvents.Engine.Plan(LaunchAction.Install));

                    // NB: WiX runs a "Main thread" that all of these events
                    // come back on, and a "UI thread" where it actually runs
                    // the WPF window. Gotta proxy to the UI thread.
                    RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(welcomeVm));
                }
            });

            var executablesToStart = Enumerable.Empty <string>();

            wixEvents.PlanCompleteObs.Subscribe(eventArgs => {
                var installManager = new InstallManager(BundledRelease);
                var error          = convertHResultToError(eventArgs.Status);
                if (error != null)
                {
                    UserError.Throw(error);
                    return;
                }

                if (wixEvents.Action == LaunchAction.Uninstall)
                {
                    installManager.ExecuteUninstall().Subscribe(
                        _ => wixEvents.Engine.Apply(wixEvents.MainWindowHwnd),
                        ex => UserError.Throw(new UserError("Failed to uninstall", ex.Message, innerException: ex)));
                    return;
                }

                IObserver <int> progress = null;

                if (wixEvents.DisplayMode == Display.Full)
                {
                    var installingVm             = RxApp.GetService <IInstallingViewModel>();
                    progress                     = installingVm.ProgressValue;
                    installingVm.PackageMetadata = bundledPackageMetadata.Value;
                    RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(installingVm));
                }

                installManager.ExecuteInstall(this.currentAssemblyDir, bundledPackageMetadata.Value, progress).Subscribe(
                    toStart => {
                    executablesToStart = toStart ?? executablesToStart;
                    wixEvents.Engine.Apply(wixEvents.MainWindowHwnd);
                },
                    ex => UserError.Throw("Failed to install application", ex));
            });

            wixEvents.ApplyCompleteObs.Subscribe(eventArgs => {
                var error = convertHResultToError(eventArgs.Status);
                if (error != null)
                {
                    UserError.Throw(error);
                    return;
                }

                if (wixEvents.DisplayMode == Display.Full && wixEvents.Action == LaunchAction.Install)
                {
                    foreach (var path in executablesToStart)
                    {
                        Process.Start(path);
                    }
                }

                wixEvents.ShouldQuit();
            });

            wixEvents.ErrorObs.Subscribe(eventArgs => UserError.Throw("An installation error has occurred: " + eventArgs.ErrorMessage));

            wixEvents.Engine.Detect();
        }
Ejemplo n.º 52
0
        static void mockPerformInstall(
          IRoutingState router,
          IObserver<DetectPackageCompleteEventArgs> detectPackage,
          IObserver<PlanCompleteEventArgs> planComplete,
          IObserver<ApplyCompleteEventArgs> applyComplete,
          Mock<IEngine> engine)
        {
            // initialize the install process
            detectPackage.OnNext(new DetectPackageCompleteEventArgs("Foo", 0, PackageState.Present));

            // navigate to the next VM
            var viewModel = router.GetCurrentViewModel() as WelcomeViewModel;
            viewModel.ShouldProceed.Execute(null);

            // signal to start the install
            planComplete.OnNext(new PlanCompleteEventArgs(0));

            // wait until install is complete
            engine.WaitUntil(e => e.Apply(It.IsAny<IntPtr>()));

            // now signal it's completed
            applyComplete.OnNext(new ApplyCompleteEventArgs(0, ApplyRestart.None));
        }
 public RouterUINavigationControllerDelegate(RouterUINavigationController parent, IRoutingState router)
 {
     this.parent = parent;
     this.router = router;
 }
Ejemplo n.º 54
0
        public WixUiBootstrapper(
            IWiXEvents wixEvents,
            TinyIoCContainer testKernel = null,
            IRoutingState router = null,
            IFileSystemFactory fileSystem = null,
            string currentAssemblyDir = null,
            string targetRootDirectory = null)
        {
            Kernel = testKernel ?? createDefaultKernel();
            this.fileSystem = fileSystem ?? AnonFileSystem.Default;
            this.currentAssemblyDir = currentAssemblyDir ?? Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            RxApp.ConfigureServiceLocator(
                (type, contract) => {
                    this.Log().Debug("Resolving type '{0}' with contract '{1}'", type, contract);
                    return String.IsNullOrEmpty(contract)
                        ? Kernel.Resolve(type)
                        : Kernel.Resolve(type, contract);
                },
                (type, contract) => Kernel.ResolveAll(type, true),
                    (c, t, s) => {
                       this.Log().Debug("Registering type '{0}' for interface '{1}' and contract '{2}'", c, t, s);
                        if (String.IsNullOrEmpty(s)) {
                            Kernel.Register(t, c, Guid.NewGuid().ToString());
                        } else {
                            Kernel.Register(t, c, s);
                        }
                });

            RxRouting.ViewModelToViewFunc = findViewClassNameForViewModelName;

            Kernel.Register<IWixUiBootstrapper>(this);
            Kernel.Register<IScreen>(this);
            Kernel.Register(wixEvents);

            Router = router ?? new RoutingState();
            WiXEvents = wixEvents;

            _BundledRelease = new Lazy<ReleaseEntry>(readBundledReleasesFile);

            registerExtensionDlls(Kernel);

            UserError.RegisterHandler(ex => {
                this.Log().ErrorException("Something unexpected happened", ex.InnerException);

                if (wixEvents.DisplayMode != Display.Full) {
                    this.Log().Error(ex.ErrorMessage);
                    wixEvents.ShouldQuit();
                }

                var errorVm = RxApp.GetService<IErrorViewModel>();
                errorVm.Error = ex;
                errorVm.Shutdown.Subscribe(_ => wixEvents.ShouldQuit());
                errorVm.OpenLogsFolder.Subscribe(_ => openLogsFolder());
                    
                RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(errorVm));
                return Observable.Return(RecoveryOptionResult.CancelOperation);
            });

            bundledPackageMetadata = new Lazy<IPackage>(openBundledPackage);

            wixEvents.DetectPackageCompleteObs.Subscribe(eventArgs => {
                this.Log().Info("DetectPackageCompleteObs: got id: '{0}', state: '{1}', status: '{2}'", eventArgs.PackageId, eventArgs.State, eventArgs.Status);

                var error = convertHResultToError(eventArgs.Status);
                if (error != null) {
                    UserError.Throw(error);
                    return;
                }

                // we now have multiple applications in the chain
                // only run this code after the last entry in the chain
                if (eventArgs.PackageId != "UserApplicationId")
                    return;

                if (wixEvents.Action == LaunchAction.Uninstall) {

                    if (wixEvents.DisplayMode != Display.Full) {
                        this.Log().Info("Squirrel is doing a silent uninstall! Sneaky!");
                        wixEvents.Engine.Plan(LaunchAction.Uninstall);
                        return;
                    }

                    this.Log().Info("Squirrel is doing an uninstall! Sadface!");
                    var uninstallVm = RxApp.GetService<IUninstallingViewModel>();
                    Router.Navigate.Execute(uninstallVm);
                    wixEvents.Engine.Plan(LaunchAction.Uninstall);
                    return;
                }

                // TODO: If the app is already installed, run it and bail
                // If Display is silent, we should just exit here.

                if (wixEvents.Action == LaunchAction.Install) {
                    
                    if (wixEvents.DisplayMode != Display.Full) {
                        this.Log().Info("Squirrel is doing a silent install! Sneaky!");
                        wixEvents.Engine.Plan(LaunchAction.Install);
                        return;
                    }
                    
                    this.Log().Info("We are doing an UI install! Huzzah!");
                    
                    var welcomeVm = RxApp.GetService<IWelcomeViewModel>();
                    welcomeVm.PackageMetadata = bundledPackageMetadata.Value;
                    welcomeVm.ShouldProceed.Subscribe(_ => wixEvents.Engine.Plan(LaunchAction.Install));
                    
                    // NB: WiX runs a "Main thread" that all of these events 
                    // come back on, and a "UI thread" where it actually runs
                    // the WPF window. Gotta proxy to the UI thread.
                    RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(welcomeVm));
                }
            });

            var executablesToStart = Enumerable.Empty<string>();

            wixEvents.PlanCompleteObs.Subscribe(eventArgs => {
                this.Log().Info("PlanCompleteObs: got status: '{0}'", eventArgs.Status);

                var installManager = new InstallManager(BundledRelease, targetRootDirectory);
                var error = convertHResultToError(eventArgs.Status);
                if (error != null) {
                    UserError.Throw(error);
                    return;
                }

                if (wixEvents.Action == LaunchAction.Uninstall) {
                    var task = installManager.ExecuteUninstall(BundledRelease.Version);
                    task.Subscribe(
                        _ => wixEvents.Engine.Apply(wixEvents.MainWindowHwnd),
                        ex => UserError.Throw(new UserError("Failed to uninstall", ex.Message, innerException: ex)));
                    // the installer can close before the uninstall is done
                    // which means the UpdateManager is not disposed correctly
                    // which means an error is thrown in the destructor
                    //
                    // let's wait for it to finish
                    //
                    // oh, and .Wait() is unnecesary here
                    // because the subscriber handles an exception
                    var result = task.FirstOrDefault();
                    return;
                }

                IObserver<int> progress = null;

                if (wixEvents.DisplayMode == Display.Full) {
                    var installingVm = RxApp.GetService<IInstallingViewModel>();
                    progress = installingVm.ProgressValue;
                    installingVm.PackageMetadata = bundledPackageMetadata.Value;
                    RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(installingVm));
                }

                installManager.ExecuteInstall(this.currentAssemblyDir, bundledPackageMetadata.Value, progress).Subscribe(
                    toStart => {
                        executablesToStart = toStart ?? executablesToStart;
                        wixEvents.Engine.Apply(wixEvents.MainWindowHwnd);
                    },
                    ex => UserError.Throw("Failed to install application", ex));
            });

            wixEvents.ApplyCompleteObs.Subscribe(eventArgs => {
                this.Log().Info("ApplyCompleteObs: got restart: '{0}', result: '{1}', status: '{2}'", eventArgs.Restart, eventArgs.Result, eventArgs.Status);

                var error = convertHResultToError(eventArgs.Status);
                if (error != null) {
                    UserError.Throw(error);
                    return;
                }

                if (wixEvents.DisplayMode == Display.Full && wixEvents.Action == LaunchAction.Install) {
                    var processFactory = Kernel.Resolve<IProcessFactory>();
                    
                    foreach (var path in executablesToStart) {
                        processFactory.Start(path);
                    }
                }

                wixEvents.ShouldQuit();
            });

            wixEvents.ErrorObs.Subscribe(
                eventArgs => {
                    this.Log().Info("ErrorObs: got id: '{0}', result: '{1}', code: '{2}'", eventArgs.PackageId, eventArgs.Result, eventArgs.ErrorCode);
                    UserError.Throw("An installation error has occurred: " + eventArgs.ErrorMessage);
                });

            wixEvents.Engine.Detect();
        }
 public RouterUINavigationControllerDelegate(RouterUINavigationController parent, IRoutingState router)
 {
     this.parent = parent;
     this.router = router;
 }
Ejemplo n.º 56
0
 public TitleBarScreen(IRoutingState router)
 {
     Router = router;
 }
Ejemplo n.º 57
0
        IPlayViewModel setupStandardMock(MoqMockingKernel kernel, IRoutingState router, Action extraSetup = null)
        {
            kernel.Bind<IPlayViewModel>().To<PlayViewModel>();

            var playApi = kernel.GetMock<IPlayApi>();
            playApi.Setup(x => x.ListenUrl()).Returns(Observable.Never<string>());
            playApi.Setup(x => x.ConnectToSongChangeNotifications()).Returns(Observable.Never<Unit>());
            playApi.Setup(x => x.NowPlaying()).Returns(Observable.Return(Fakes.GetSong()));
            playApi.Setup(x => x.Queue()).Returns(Observable.Return(Fakes.GetAlbum()));
            playApi.Setup(x => x.FetchImageForAlbum(It.IsAny<Song>())).Returns(Observable.Return<BitmapImage>(null));

            kernel.GetMock<IScreen>().Setup(x => x.Router).Returns(router);

            kernel.GetMock<ILoginMethods>()
                .Setup(x => x.EraseCredentialsAndNavigateToLogin())
                .Callback(() => router.Navigate.Execute(kernel.Get<IWelcomeViewModel>()));

            kernel.GetMock<ILoginMethods>()
                .Setup(x => x.CurrentAuthenticatedClient)
                .Returns(kernel.Get<IPlayApi>());

            if (extraSetup != null) extraSetup();

            RxApp.ConfigureServiceLocator((t,s) => kernel.Get(t,s), (t,s) => kernel.GetAll(t,s));
            return kernel.Get<IPlayViewModel>();
        }