public void Test_Round_Trip_Works_For_Normal_ViewModel_Requests()
        {
            ClearAll();

            var viewModelNameLookup = new MvxViewModelByNameLookup();
            viewModelNameLookup.AddAll(GetType().Assembly);
            Mvx.RegisterSingleton<IMvxViewModelByNameLookup>(viewModelNameLookup);

            var parameterBundle = new MvxBundle(new Dictionary<string, string> { { "On'e", "1'\\" }, { "Two", "2" } });
            var presentationBundle =
                new MvxBundle(new Dictionary<string, string> { { "Thre\"\'\\e", "3\"\'\\" }, { "Four", null } });
            var request = new MvxViewModelRequest<Test1ViewModel>(parameterBundle, presentationBundle,
                                                                  new MvxRequestedBy(
                                                                      MvxRequestedByType.AutomatedService, "HelloWorld"));

            var serializer = new MvxViewModelRequestCustomTextSerializer();
            var output = serializer.SerializeObject(request);

            var deserializer = new MvxViewModelRequestCustomTextSerializer();
            var deserialized = deserializer.DeserializeObject<MvxViewModelRequest>(output);

            Assert.AreEqual(typeof(Test1ViewModel), deserialized.ViewModelType);
            Assert.AreEqual(MvxRequestedByType.AutomatedService, deserialized.RequestedBy.Type);
            Assert.AreEqual("HelloWorld", deserialized.RequestedBy.AdditionalInfo);
            Assert.AreEqual(2, deserialized.PresentationValues.Count);
            Assert.AreEqual(2, deserialized.ParameterValues.Count);
            Assert.AreEqual("1'\\", deserialized.ParameterValues["On'e"]);
            Assert.AreEqual("2", deserialized.ParameterValues["Two"]);
            Assert.AreEqual("3\"\'\\", deserialized.PresentationValues["Thre\"\'\\e"]);
            Assert.AreEqual(null, deserialized.PresentationValues["Four"]);
        }
Example #2
0
		protected virtual IMvxBundle LoadStateBundle(NavigationEventArgs e)
		{
			// nothing loaded by default
			var frameState = this.SuspensionManager.SessionStateForFrame(this.WrappedFrame);
			this.PageKey = "Page-" + this.Frame.BackStackDepth;
			IMvxBundle bundle = null;

			if (e.NavigationMode == NavigationMode.New)
			{
				// Clear existing state for forward navigation when adding a new page to the
				// navigation stack
				var nextPageKey = this.PageKey;
				int nextPageIndex = this.Frame.BackStackDepth;
				while (frameState.Remove(nextPageKey))
				{
					nextPageIndex++;
					nextPageKey = "Page-" + nextPageIndex;
				}
			}
			else
			{
				var dictionary = (IDictionary<string, string>)frameState[this.PageKey];
				bundle = new MvxBundle(dictionary);
			}

			return bundle;
		}
        public void Test_NormalViewModel()
        {
            ClearAll();

            IMvxViewModel outViewModel = new Test2ViewModel();

            var mockLocator = new Mock<IMvxViewModelLocator>();
            mockLocator.Setup(
                m => m.Load(It.IsAny<Type>(), It.IsAny<IMvxBundle>(), It.IsAny<IMvxBundle>()))
                       .Returns(() => outViewModel);

            var mockCollection = new Moq.Mock<IMvxViewModelLocatorCollection>();
            mockCollection.Setup(m => m.FindViewModelLocator(It.IsAny<MvxViewModelRequest>()))
                          .Returns(() => mockLocator.Object);

            Ioc.RegisterSingleton(mockCollection.Object);

            var parameters = new Dictionary<string, string> { { "foo", "bar" } };
            var request = new MvxViewModelRequest<Test2ViewModel>(new MvxBundle(parameters), null,
                                                                  MvxRequestedBy.UserAction);
            var state = new MvxBundle();
            var loader = new MvxViewModelLoader();
            var viewModel = loader.LoadViewModel(request, state);

            Assert.AreSame(outViewModel, viewModel);
            Assert.AreEqual(MvxRequestedBy.UserAction, viewModel.RequestedBy);
        }
        public void Test_FillArguments()
        {
            ClearAll();

            var testObject = new BundleObject
                {
                    TheBool1 = false,
                    TheBool2 = true,
                    TheGuid1 = Guid.NewGuid(),
                    TheGuid2 = new Guid(123, 10, 444, 1, 2, 3, 4, 5, 6, 7, 8),
                    TheInt1 = 123,
                    TheInt2 = 456,
                    TheString1 = "Hello World",
                    TheString2 = "Goo"
                };
            var bundle = new MvxBundle();
            bundle.Write(testObject);

            var method = GetType().GetMethod("TestFunction");
            var args = bundle.CreateArgumentList(method.GetParameters(), "ignored debug text");
            var output = method.Invoke(this, args.ToArray());

            var expected = new BundleObject
                {
                    TheBool1 = false,
                    TheBool2 = true,
                    TheGuid1 = Guid.Empty,
                    TheGuid2 = new Guid(123, 10, 444, 1, 2, 3, 4, 5, 6, 7, 8),
                    TheInt1 = 0,
                    TheInt2 = 456,
                    TheString1 = "Hello World",
                    TheString2 = null
                };
            Assert.AreEqual(expected, output);
        }
Example #5
0
        private void LoadFirstFragment()
        {
            // Create our ViewModel parameters...
            var test = new MvxBundle ( );
            test.Data.Add ( "one", "first parameter" );
            test.Data.Add ( "two", "2" );

            ShowViewModel<FirstFragViewModel> ( test );
        }
        public void Test_WithReloadState()
        {
            ClearAll();

            Ioc.RegisterSingleton<IMvxStringToTypeParser>(new MvxStringToTypeParser());

            var testThing = new MockTestThing();
            Ioc.RegisterSingleton<ITestThing>(testThing);

            var initBundleObject = new BundleObject
                {
                    TheBool1 = false,
                    TheBool2 = true,
                    TheGuid1 = Guid.NewGuid(),
                    TheGuid2 = new Guid(123, 10, 444, 1, 2, 3, 4, 5, 6, 7, 8),
                    TheInt1 = 123,
                    TheInt2 = 456,
                    TheString1 = "Hello World",
                    TheString2 = null
                };
            var initBundle = new MvxBundle();
            initBundle.Write(initBundleObject);

            var reloadBundleObject = new BundleObject
                {
                    TheBool1 = true,
                    TheBool2 = true,
                    TheGuid1 = Guid.NewGuid(),
                    TheGuid2 = new Guid(1123, 10, 444, 1, 2, 3, 4, 5, 6, 7, 8),
                    TheInt1 = 1234,
                    TheInt2 = 4567,
                    TheString1 = "Foo Bar",
                    TheString2 = null
                };
            var reloadBundle = new MvxBundle();
            reloadBundle.Write(reloadBundleObject);

            var toTest = new MvxDefaultViewModelLocator();
            IMvxViewModel viewModel = toTest.Load(typeof(Test1ViewModel), initBundle, reloadBundle);

            Assert.IsNotNull(viewModel);
            var typedViewModel = (Test1ViewModel)viewModel;
            Assert.AreSame(initBundle, typedViewModel.BundleInit);
            Assert.AreSame(reloadBundle, typedViewModel.BundleState);
            Assert.AreSame(testThing, typedViewModel.Thing);
            Assert.AreEqual(initBundleObject, typedViewModel.TheInitBundleSet);
            Assert.AreEqual(reloadBundleObject, typedViewModel.TheReloadBundleSet);
            Assert.AreEqual(initBundleObject.TheGuid1, typedViewModel.TheInitGuid1Set);
            Assert.AreEqual(initBundleObject.TheGuid2, typedViewModel.TheInitGuid2Set);
            Assert.AreEqual(initBundleObject.TheString1, typedViewModel.TheInitString1Set);
            Assert.AreEqual(reloadBundleObject.TheGuid1, typedViewModel.TheReloadGuid1Set);
            Assert.AreEqual(reloadBundleObject.TheGuid2, typedViewModel.TheReloadGuid2Set);
            Assert.AreEqual(reloadBundleObject.TheString1, typedViewModel.TheReloadString1Set);
            Assert.IsTrue(typedViewModel.StartCalled);
        }
        public void Test_LoaderForNull()
        {
            ClearAll();

            var request = new MvxViewModelRequest<MvxNullViewModel>(null, null, MvxRequestedBy.UserAction);
            var state = new MvxBundle();
            var loader = new MvxViewModelLoader();
            var viewModel = loader.LoadViewModel(request, state);

            Assert.IsInstanceOf<MvxNullViewModel>(viewModel);
        }
        private IMvxViewModel CreateViewModel(int position)
        {
            var fragInfo = Fragments.ElementAt(position);

            MvxBundle mvxBundle = null;
            if (fragInfo.ParameterValuesObject != null)
                mvxBundle = new MvxBundle(fragInfo.ParameterValuesObject.ToSimplePropertyDictionary());

            var request = new MvxViewModelRequest(fragInfo.ViewModelType, mvxBundle, null, null);

            return Mvx.Resolve<IMvxViewModelLoader>().LoadViewModel(request, null);
        }
        public FeedViewModel(IUserSettings settings)
        {
            if (settings == null) throw new ArgumentNullException(nameof(settings));

            this.userFilterSetting = settings.UserFiltersSetting;
            this.ShowDetails = new RelayCommand<Article>(a => this.ShowViewModel<DetailsViewModel>(new Identifier(a.Id.ToString())));
            this.ShowMore = new RelayCommand(() =>
            {
                var parameter = new MvxBundle();
                if (parameter.Data != null) parameter.Data["preset"] = JsonConvert.SerializeObject(this.FilterPreset);
                this.ShowViewModel<FeedViewModel>(parameter);
            });
        }
Example #10
0
        public async Task Test_NavigateTypeOfWithBundle()
        {
            var navigationService = Ioc.Resolve <IMvxNavigationService>();

            var bundle = new MvxBundle();

            bundle.Write(new { hello = "world" });

            await navigationService.Navigate(typeof(SimpleTestViewModel), presentationBundle : bundle);

            //TODO: fix NavigationService not allowing parameter values in request and only presentation values
            //mockVm.Verify(vm => vm.Init(It.Is<string>(s => s == "world")), Times.Once);
        }
        public void Test_FailingDependency()
        {
            _fixture.ClearAll();

            _fixture.Ioc.RegisterSingleton <ITestThing>(() => new FailingMockTestThing());

            var bundle = new MvxBundle();

            var toTest = new MvxDefaultViewModelLocator();

            Assert.Throws <MvxException>(() => {
                IMvxViewModel viewModel = toTest.Load(typeof(Test4ViewModel), bundle, null);
            });
        }
Example #12
0
        public void Test_MissingDependency()
        {
            _fixture.ClearAll();

            var bundle = new MvxBundle();

            var toTest = new MvxDefaultViewModelLocator();
            var args   = new MvxNavigateEventArgs(NavigationMode.Show);

            Assert.Throws <MvxException>(() =>
            {
                IMvxViewModel viewModel = toTest.Load(typeof(Test4ViewModel), bundle, null, args);
            });
        }
Example #13
0
        public override async void Prepare(MvxBundle parameters)
        {
            base.Prepare(parameters);

            _characteristic = await GetCharacteristicFromBundleAsync(parameters);

            if (_characteristic == null)
            {
                return;
            }

            Descriptors = await _characteristic.GetDescriptorsAsync();
            await RaisePropertyChanged(nameof(Descriptors));
        }
        public void Test_FailingDependency()
        {
            ClearAll();

            Ioc.RegisterSingleton <ITestThing>(() => new FailingMockTestThing());

            var bundle = new MvxBundle();

            var toTest = new MvxDefaultViewModelLocator();

            IMvxViewModel viewModel = toTest.Load(typeof(Test4ViewModel), bundle, null);

            Assert.Fail("We should never reach this line");
        }
        public void Test_MissingDependency()
        {
            ClearAll();

            var bundle = new MvxBundle();

            var toTest = new MvxDefaultViewModelLocator();

            Assert.That(
                () => {
                IMvxViewModel viewModel = toTest.Load(typeof(Test4ViewModel), bundle, null);
            },
                Throws.TypeOf <MvxException>().With.Message.StartWith("Problem creating viewModel"));
        }
        private IMvxViewModel LoadViewModel(MvxViewModelRequest request, IMvxBundle savedState,
                                            IMvxViewModelLocator viewModelLocator)
        {
            IMvxViewModel viewModel = null;
            var parameterValues = new MvxBundle(request.ParameterValues);
            if (!viewModelLocator.TryLoad(request.ViewModelType, parameterValues, savedState, out viewModel))
            {
                throw new MvxException(
                    "Failed to construct and initialize ViewModel for type {0} from locator {1} - check MvxTrace for more information",
                    request.ViewModelType, viewModelLocator.GetType().Name);
            }

            viewModel.RequestedBy = request.RequestedBy;
            return viewModel;
        }
Example #17
0
        private IMvxViewModel CreateViewModel(int position)
        {
            var fragInfo = Fragments.ElementAt(position);

            MvxBundle mvxBundle = null;

            if (fragInfo.ParameterValuesObject != null)
            {
                mvxBundle = new MvxBundle(fragInfo.ParameterValuesObject.ToSimplePropertyDictionary());
            }

            var request = new MvxViewModelRequest(fragInfo.ViewModelType, mvxBundle, null, null);

            return(Mvx.Resolve <IMvxViewModelLoader>().LoadViewModel(request, null));
        }
        protected void ShowViewModel <TViewModel>(object parameters = null, bool clearbackstack = false) where TViewModel : MvxViewModel
        {
            if (clearbackstack)
            {
                var presentationBundle = new MvxBundle(new Dictionary <string, string> {
                    { "ClearBackFlag", "" }
                });

                ShowViewModel <TViewModel>(parameters, presentationBundle: presentationBundle);
                return;
            }

            // Normal start
            base.ShowViewModel <TViewModel>(parameters);
        }
        public void InitFromBundle_accessToken()
        {
            ClearAll();
            CreateMockNavigation();
            var bundle = new MvxBundle();

            bundle.Data.Add(Whistle.Core.Helpers.Settings.AccessTokenKey, "{accessToken:\"token\"}");

            var main = new MainViewModel(_messenger.Object);

            // act
            main.Init(bundle);
            // assert..
            Assert.AreEqual("token", main.NewUser.AccessToken);
        }
Example #20
0
        public void Test_Round_Trip_Works_For_Part_Empty_ViewModel_Requests()
        {
            var parameterBundle    = new MvxBundle();
            var presentationBundle = new MvxBundle();
            var request            = new MvxViewModelRequest <Test1ViewModel>(parameterBundle, presentationBundle);

            var serializer = new MvxViewModelRequestCustomTextSerializer();
            var output     = serializer.SerializeObject(request);

            var deserializer = new MvxViewModelRequestCustomTextSerializer();
            var deserialized = deserializer.DeserializeObject <MvxViewModelRequest>(output);

            Assert.Equal(typeof(Test1ViewModel), deserialized.ViewModelType);
            Assert.Equal(0, deserialized.PresentationValues.Count);
            Assert.Equal(0, deserialized.ParameterValues.Count);
        }
Example #21
0
        public async Task Test_NavigateWithBundle()
        {
            var navigationService = _fixture.Ioc.Resolve <IMvxNavigationService>();

            var mockVm = new Mock <SimpleTestViewModel>();

            var bundle = new MvxBundle();

            bundle.Write(new { hello = "world" });

            var result = await navigationService.Navigate(mockVm.Object, bundle).ConfigureAwait(false);

            Assert.True(result);
            //TODO: fix NavigationService not allowing parameter values in request and only presentation values
            //mockVm.Verify(vm => vm.Init(It.Is<string>(s => s == "world")), Times.Once);
        }
        public void InitFromBundle_complete()
        {
            ClearAll();
            CreateMockNavigation();
            var bundle = new MvxBundle();

            bundle.Data.Add(Whistle.Core.Helpers.Settings.AccessTokenKey, JsonResources.InitFromBundle_complete);

            var main = new MainViewModel(_messenger.Object);

            // act
            main.Init(bundle);
            // assert..
            Assert.AreEqual(JsonResources.InitFromBundle_complete_token, main.NewUser.AccessToken);
            Assert.AreEqual(5, main.TrackingViewModel.ConsumerWhistleCollection.Count);
        }
        public void InitFromBundle_whistles()
        {
            ClearAll();
            CreateMockNavigation();
            var bundle = new MvxBundle();

            bundle.Data.Add(Whistle.Core.Helpers.Settings.AccessTokenKey, "{accessToken:\"token\", whistles:[{comment:\"test\" }] }");

            var main = new MainViewModel(_messenger.Object);

            // act
            main.Init(bundle);
            // assert..
            Assert.AreEqual("token", main.NewUser.AccessToken);
            Assert.AreEqual(1, main.TrackingViewModel.ConsumerWhistleCollection.Count);
        }
        public void Test_FailingDependency()
        {
            ClearAll();

            Ioc.RegisterSingleton <ITestThing>(() => new FailingMockTestThing());

            var bundle = new MvxBundle();

            var toTest = new MvxDefaultViewModelLocator();

            Assert.That(
                () => {
                IMvxViewModel viewModel = toTest.Load(typeof(Test4ViewModel), bundle, null);
            },
                Throws.TypeOf <MvxException>().With.Message.StartWith("Problem creating viewModel"));
        }
        public void Test_NoReloadState()
        {
            _fixture.ClearAll();

            _fixture.Ioc.RegisterSingleton <IMvxStringToTypeParser>(new MvxStringToTypeParser());

            var testThing = new MockTestThing();

            _fixture.Ioc.RegisterSingleton <ITestThing>(testThing);

            var testObject = new BundleObject
            {
                TheBool1   = false,
                TheBool2   = true,
                TheGuid1   = Guid.NewGuid(),
                TheGuid2   = new Guid(123, 10, 444, 1, 2, 3, 4, 5, 6, 7, 8),
                TheInt1    = 123,
                TheInt2    = 456,
                TheString1 = "Hello World",
                TheString2 = null
            };
            var bundle = new MvxBundle();

            bundle.Write(testObject);

            var navigationService = _fixture.Ioc.Resolve <IMvxNavigationService>();
            var toTest            = new MvxDefaultViewModelLocator(navigationService);
            var args = new MvxNavigateEventArgs(NavigationMode.Show);

            IMvxViewModel viewModel = toTest.Load(typeof(Test1ViewModel), bundle, null, args);

            Assert.NotNull(viewModel);
            var typedViewModel = (Test1ViewModel)viewModel;

            Assert.Equal(bundle, typedViewModel.BundleInit);
            Assert.Null(typedViewModel.BundleState);
            Assert.Equal(testThing, typedViewModel.Thing);
            Assert.Equal(testObject, typedViewModel.TheInitBundleSet);
            Assert.Null(typedViewModel.TheReloadBundleSet);
            Assert.Equal(testObject.TheGuid1, typedViewModel.TheInitGuid1Set);
            Assert.Equal(testObject.TheGuid2, typedViewModel.TheInitGuid2Set);
            Assert.Equal(testObject.TheString1, typedViewModel.TheInitString1Set);
            Assert.Equal(Guid.Empty, typedViewModel.TheReloadGuid1Set);
            Assert.Equal(Guid.Empty, typedViewModel.TheReloadGuid2Set);
            Assert.Null(typedViewModel.TheReloadString1Set);
            Assert.True(typedViewModel.StartCalled);
        }
        public void Test_FailingDependency()
        {
            _fixture.ClearAll();

            _fixture.Ioc.RegisterSingleton <ITestThing>(() => new FailingMockTestThing());

            var bundle = new MvxBundle();

            var navigationService = _fixture.Ioc.Resolve <IMvxNavigationService>();
            var toTest            = new MvxDefaultViewModelLocator(navigationService);
            var args = new MvxNavigateEventArgs(NavigationMode.Show);

            Assert.Throws <MvxException>(() =>
            {
                IMvxViewModel viewModel = toTest.Load(typeof(Test4ViewModel), bundle, null, args);
            });
        }
Example #27
0
        public void Test_FailingInitialisation()
        {
            _fixture.ClearAll();

            var testThing = new MockTestThing();

            _fixture.Ioc.RegisterSingleton <ITestThing>(testThing);

            var bundle = new MvxBundle();

            var navigationService = _fixture.Ioc.Resolve <IMvxNavigationService>();
            var toTest            = new MvxDefaultViewModelLocator(navigationService);

            Assert.Throws <MvxException>(() => {
                IMvxViewModel viewModel = toTest.Load(typeof(Test4ViewModel), bundle, null);
            });
        }
        public void Test_NoReloadState()
        {
            ClearAll();

            Ioc.RegisterSingleton <IMvxStringToTypeParser>(new MvxStringToTypeParser());

            var testThing = new MockTestThing();

            Ioc.RegisterSingleton <ITestThing>(testThing);

            var testObject = new BundleObject
            {
                TheBool1   = false,
                TheBool2   = true,
                TheGuid1   = Guid.NewGuid(),
                TheGuid2   = new Guid(123, 10, 444, 1, 2, 3, 4, 5, 6, 7, 8),
                TheInt1    = 123,
                TheInt2    = 456,
                TheString1 = "Hello World",
                TheString2 = null
            };
            var bundle = new MvxBundle();

            bundle.Write(testObject);

            var toTest = new MvxDefaultViewModelLocator();

            IMvxViewModel viewModel = toTest.Load(typeof(Test1ViewModel), bundle, null);

            Assert.IsNotNull(viewModel);
            var typedViewModel = (Test1ViewModel)viewModel;

            Assert.AreSame(bundle, typedViewModel.BundleInit);
            Assert.IsNull(typedViewModel.BundleState);
            Assert.AreSame(testThing, typedViewModel.Thing);
            Assert.AreEqual(testObject, typedViewModel.TheInitBundleSet);
            Assert.IsNull(typedViewModel.TheReloadBundleSet);
            Assert.AreEqual(testObject.TheGuid1, typedViewModel.TheInitGuid1Set);
            Assert.AreEqual(testObject.TheGuid2, typedViewModel.TheInitGuid2Set);
            Assert.AreEqual(testObject.TheString1, typedViewModel.TheInitString1Set);
            Assert.AreEqual(Guid.Empty, typedViewModel.TheReloadGuid1Set);
            Assert.AreEqual(Guid.Empty, typedViewModel.TheReloadGuid2Set);
            Assert.AreEqual(null, typedViewModel.TheReloadString1Set);
            Assert.IsTrue(typedViewModel.StartCalled);
        }
Example #29
0
        public void Test_FailingInitialisation()
        {
            _fixture.ClearAll();

            var testThing = new MockTestThing();

            _fixture.Ioc.RegisterSingleton <ITestThing>(testThing);

            var bundle = new MvxBundle();

            var toTest = new MvxDefaultViewModelLocator();
            var args   = new MvxNavigateEventArgs(NavigationMode.Show);

            Assert.Throws <MvxException>(() =>
            {
                IMvxViewModel viewModel = toTest.Load(typeof(Test4ViewModel), bundle, null, args);
            });
        }
Example #30
0
        public async Task Test_NavigateWithBundle()
        {
            var navigationService = Ioc.Resolve <IMvxNavigationService>();

            var mockVm = new Mock <SimpleTestViewModel>();

            var bundle = new MvxBundle();

            bundle.Write(new { hello = "world" });

            await navigationService.Navigate(mockVm.Object, bundle);

            mockVm.Verify(vm => vm.Initialize(), Times.Once);
            mockVm.Verify(vm => vm.Init(), Times.Once);

            // todo fix NavigationService not allowing parameter values in request and only presentation values
            //mockVm.Verify(vm => vm.Init(It.Is<string>(s => s == "world")), Times.Once);
        }
 private static void RunViewModelLifecycle(IMvxViewModel viewModel, IMvxBundle savedState,
                                           MvxViewModelRequest request)
 {
     try
     {
         var parameterValues = new MvxBundle(request.ParameterValues);
         viewModel.CallBundleMethods("Init", parameterValues);
         if (savedState != null)
         {
             viewModel.CallBundleMethods("ReloadState", savedState);
         }
         viewModel.Start();
     }
     catch (Exception exception)
     {
         throw exception.MvxWrap("Problem running viewModel lifecycle of type {0}", viewModel.GetType().Name);
     }
 }
Example #32
0
        public void Test_FailingInitialisation()
        {
            ClearAll();

            var testThing = new MockTestThing();

            Ioc.RegisterSingleton <ITestThing>(testThing);

            var bundle = new MvxBundle();

            var toTest = new MvxDefaultViewModelLocator();

            Assert.That(
                () => {
                IMvxViewModel viewModel = toTest.Load(typeof(Test4ViewModel), bundle, null);
            },
                Throws.TypeOf <MvxException>().With.Message.StartWith("Problem running viewModel lifecycle"));
        }
Example #33
0
        private void AttemptLogin()
        {
            if (_loginService.Login(Username, Password))
            {
                //_dialogService.Alert("Logged in successfully!", "Logged in!", "OK");

                var presentationBundle = new MvxBundle(new Dictionary <string, string> {
                    { "NavigationMode", "ClearStack" }
                });

                ShowViewModel <FirstViewModel>(presentationBundle: presentationBundle);
                ChangePresentation(new ClearBackStackHint());
            }
            else
            {
                _dialogService.Alert("We were unable to log you in!", "Login Failed", "OK");
            }
        }
 private IMvxViewModel LoadViewModel(MvxViewModelRequest request, IMvxBundle savedState,
                                     IMvxViewModelLocator viewModelLocator)
 {
     IMvxViewModel viewModel = null;
     var parameterValues = new MvxBundle(request.ParameterValues);
     try
     {
         viewModel = viewModelLocator.Load(request.ViewModelType, parameterValues, savedState);
     }
     catch (Exception exception)
     {
         throw exception.MvxWrap(
             "Failed to construct and initialize ViewModel for type {0} from locator {1} - check InnerException for more information",
             request.ViewModelType, viewModelLocator.GetType().Name);
     }
     viewModel.RequestedBy = request.RequestedBy;
     return viewModel;
 }
        public void Test_FailedViewModelLocatorCollection()
        {
            var mockCollection = new Moq.Mock <IMvxViewModelLocatorCollection>();

            mockCollection.Setup(m => m.FindViewModelLocator(It.IsAny <MvxViewModelRequest>()))
            .Returns(() => null);

            Ioc.RegisterSingleton(mockCollection.Object);

            var parameters = new Dictionary <string, string> {
                { "foo", "bar" }
            };
            var request   = new MvxViewModelRequest <Test2ViewModel>(new MvxBundle(parameters), null, MvxRequestedBy.UserAction);
            var state     = new MvxBundle();
            var loader    = new MvxViewModelLoader();
            var viewModel = loader.LoadViewModel(request, state);

            Assert.Fail("We should never reach this line");
        }
        protected async void onLogin()
        {
            IsBusy = true;
            var result = await ServiceHandler.PostAction <User, User>(NewUser, ApiAction.LOGIN);

            IsBusy = false;
            if (result.HasError)
            {
                _messenger.Publish(new MessageHandler(this, LandingConstants.RESULT_BACKEND_ERROR).WithPayload(result.Error.GetErrorMessage()));
                this.NewUser = getNewUser();
                return;
            }
            else
            {
                var bundle = new MvxBundle();
                bundle.Data.Add(Settings.AccessTokenKey, result.RawJsonResponse);
                this.ShowViewModel <MainViewModel>(bundle);
            }
        }
        public void SetupViewPager(View view)
        {
            var viewPager = view.FindViewById <ViewPager>(Resource.Id.viewPager);
            var fragments = new List <MvxViewPagerFragmentInfo>();

            foreach (var i in ViewModel.Files)
            {
                var data = new Dictionary <string, string>();
                data.Add("ImageUrl", i.PathToDisplay);
                data.Add("ImageName", i.RealName);
                var bundle = new MvxBundle(data);
                fragments.Add(new MvxViewPagerFragmentInfo(string.Empty, string.Empty, typeof(DocumentContentFullScreenView),
                                                           new MvxViewModelRequest <DocumentContentFullScreenViewModel>(bundle, null)));
            }

            viewPager.Adapter = new MvxCachingFragmentStatePagerAdapter(Activity, ChildFragmentManager, fragments);
            viewPager.SetPageTransformer(true, new ZoomOutPageTransformer());
            viewPager.CurrentItem = ViewModel.SelectedIndex;
        }
        public void Test_Round_Trip_Works_For_Part_Empty_ViewModel_Requests()
        {
            var parameterBundle = new MvxBundle();
            var presentationBundle = new MvxBundle();
            var request = new MvxViewModelRequest<Test1ViewModel>(parameterBundle, presentationBundle,
                                                                  null);

            var serializer = new MvxViewModelRequestCustomTextSerializer();
            var output = serializer.SerializeObject(request);

            var deserializer = new MvxViewModelRequestCustomTextSerializer();
            var deserialized = deserializer.DeserializeObject<MvxViewModelRequest>(output);

            Assert.AreEqual(typeof(Test1ViewModel), deserialized.ViewModelType);
            Assert.AreEqual(MvxRequestedByType.Unknown, deserialized.RequestedBy.Type);
            Assert.AreEqual(null, deserialized.RequestedBy.AdditionalInfo);
            Assert.AreEqual(0, deserialized.PresentationValues.Count);
            Assert.AreEqual(0, deserialized.ParameterValues.Count);
        }
        private PendingIntent GetContentIntent(Newsfeed newsfeed)
        {
            MvxBundle bundle = new MvxBundle();

            bundle.Write(newsfeed);

            MvxViewModelRequest <NewsfeedItemViewModel> request = new MvxViewModelRequest <NewsfeedItemViewModel>(bundle, null);

            IMvxNavigationSerializer converter = Mvx.IoCProvider.Resolve <IMvxNavigationSerializer>();
            string requestText = converter.Serializer.SerializeObject(request);

            Intent intent = new Intent(Application.Context, typeof(MainActivity));

            // We only want one activity started
            intent.AddFlags(flags: ActivityFlags.SingleTop);
            intent.PutExtra("Request", requestText);

            // Create Pending intent, with OneShot. We're not going to want to update this.
            return(PendingIntent.GetActivity(Application.Context, (int)(DateTimeOffset.Now.ToUnixTimeMilliseconds() / 1000), intent, PendingIntentFlags.OneShot));
        }
Example #40
0
        public void SetupViewPager(View view)
        {
            var viewPager = view.FindViewById <ViewPager>(Resource.Id.viewPager);
            var fragments = new List <MvxViewPagerFragmentInfo>();

            var numberOfFiles = ViewModel.ChatMessage.Files.Count;

            for (int i = 0; i < numberOfFiles; i++)
            {
                var data = new Dictionary <string, string>();
                data.Add("ImageUrl", ViewModel.ChatMessage.Files[i].FilePath);
                data.Add("ImageName", $"{i + 1}/{numberOfFiles}");
                var bundle = new MvxBundle(data);
                fragments.Add(new MvxViewPagerFragmentInfo(string.Empty, string.Empty, typeof(PictureGalleryView),
                                                           new MvxViewModelRequest <PictureGalleryViewModel>(bundle, null)));
            }

            viewPager.Adapter = new MvxCachingFragmentStatePagerAdapter(Activity, ChildFragmentManager, fragments);
            viewPager.SetPageTransformer(true, new ZoomOutPageTransformer());
        }
        /// <summary>
        /// Attempts to call the 'SaveState' method
        /// on a controller to create a saved state bundle
        /// </summary>
        /// <param name="controller"></param>
        /// <returns>An IMvxBundle object that contains any saved state collected.</returns>
        public static IMvxBundle GetSavedState(this IMvxController controller)
        {
            var mvxBundle = new MvxBundle();
            var methods   =
                controller.GetType()
                .GetTypeInfo()
                .DeclaredMethods.Where(m => m.Name == "SaveState")
                .Where(m => m.ReturnType != typeof(void))
                .Where(m => !m.GetParameters().Any());

            foreach (MethodInfo methodBase in methods)
            {
                object toStore = methodBase.Invoke(controller, new object[0]);
                if (toStore != null)
                {
                    mvxBundle.Write(toStore);
                }
            }
            return(mvxBundle);
        }
        public void Test_FailedViewModelLocatorCollection()
        {
            _fixture.ClearAll();

            var mockCollection = new Mock <IMvxViewModelLocatorCollection>();

            mockCollection.Setup(m => m.FindViewModelLocator(It.IsAny <MvxViewModelRequest>()))
            .Returns(() => null);

            var parameters = new Dictionary <string, string> {
                { "foo", "bar" }
            };
            var request = new MvxViewModelRequest <Test2ViewModel>(new MvxBundle(parameters), null);
            var state   = new MvxBundle();
            var loader  = new MvxViewModelLoader(mockCollection.Object);

            Assert.Throws <MvxException>(() => {
                var viewModel = loader.LoadViewModel(request, state);
            });
        }
        public void Test_NoReloadState()
        {
            ClearAll();

            var testThing = new MockTestThing();
            Ioc.RegisterSingleton<ITestThing>(testThing);

            var testObject = new BundleObject
                {
                    TheBool1 = false,
                    TheBool2 = true,
                    TheGuid1 = Guid.NewGuid(),
                    TheGuid2 = new Guid(123, 10, 444, 1, 2, 3, 4, 5, 6, 7, 8),
                    TheInt1 = 123,
                    TheInt2 = 456,
                    TheString1 = "Hello World",
                    TheString2 = null
                };
            var bundle = new MvxBundle();
            bundle.Write(testObject);

            var toTest = new MvxDefaultViewModelLocator();
            IMvxViewModel viewModel;

            var result = toTest.TryLoad(typeof (Test1ViewModel), bundle, null, out viewModel);

            Assert.IsTrue(result);
            var typedViewModel = (Test1ViewModel) viewModel;
            Assert.AreSame(bundle, typedViewModel.BundleInit);
            Assert.IsNull(typedViewModel.BundleState);
            Assert.AreSame(testThing, typedViewModel.Thing);
            Assert.AreEqual(testObject, typedViewModel.TheInitBundleSet);
            Assert.IsNull(typedViewModel.TheReloadBundleSet);
            Assert.AreEqual(testObject.TheGuid1, typedViewModel.TheInitGuid1Set);
            Assert.AreEqual(testObject.TheGuid2, typedViewModel.TheInitGuid2Set);
            Assert.AreEqual(testObject.TheString1, typedViewModel.TheInitString1Set);
            Assert.AreEqual(Guid.Empty, typedViewModel.TheReloadGuid1Set);
            Assert.AreEqual(Guid.Empty, typedViewModel.TheReloadGuid2Set);
            Assert.AreEqual(null, typedViewModel.TheReloadString1Set);
            Assert.IsTrue(typedViewModel.StartCalled);
        }
        private IMvxViewModel ReloadViewModel(IMvxViewModel viewModel, MvxViewModelRequest request, IMvxBundle savedState,
                                    IMvxViewModelLocator viewModelLocator)
        {
            if (viewModelLocator == null)
            {
                throw new MvxException("Received view model is null, view model reload failed. ", request.ViewModelType);
            }

            var parameterValues = new MvxBundle(request.ParameterValues);
            try
            {
                viewModel = viewModelLocator.Reload(viewModel, parameterValues, savedState);
            }
            catch (Exception exception)
            {
                throw exception.MvxWrap(
                    "Failed to reload a previously created created ViewModel for type {0} from locator {1} - check InnerException for more information",
                    request.ViewModelType, viewModelLocator.GetType().Name);
            }
            viewModel.RequestedBy = request.RequestedBy;
            return viewModel;
        }
        public void Test_RoundTrip()
        {
            ClearAll();

            var testObject = new BundleObject
                {
                    TheBool1 = false,
                    TheBool2 = true,
                    TheGuid1 = Guid.NewGuid(),
                    TheGuid2 = new Guid(123, 10, 444, 1, 2, 3, 4, 5, 6, 7, 8),
                    TheInt1 = 123,
                    TheInt2 = 456,
                    TheString1 = "Hello World",
                    TheString2 = null
                };
            var bundle = new MvxBundle();
            bundle.Write(testObject);

            var output = bundle.Read<BundleObject>();

            Assert.AreEqual(testObject, output);
        }
        public void Test_FailedViewModel()
        {
            IMvxViewModel outViewModel = null;

            var mockLocator = new Mock<IMvxViewModelLocator>();
            mockLocator.Setup(
                m => m.TryLoad(It.IsAny<Type>(), It.IsAny<IMvxBundle>(), It.IsAny<IMvxBundle>(), out outViewModel))
                       .Returns(() => false);

            var mockCollection = new Moq.Mock<IMvxViewModelLocatorCollection>();
            mockCollection.Setup(m => m.FindViewModelLocator(It.IsAny<MvxViewModelRequest>()))
                          .Returns(() => mockLocator.Object);

            Ioc.RegisterSingleton(mockCollection.Object);

            var parameters = new Dictionary<string, string> {{"foo", "bar"}};
            var request = new MvxViewModelRequest<Test2ViewModel>(new MvxBundle(parameters), null, MvxRequestedBy.UserAction);
            var state = new MvxBundle();
            var loader = new MvxViewModelLoader();
            var viewModel = loader.LoadViewModel(request, state);

            Assert.Fail("We should never reach this line");
        }
        public static IMvxBundle SaveStateBundle(this IMvxViewModel viewModel)
        {
            var toReturn = new MvxBundle();
            var methods = viewModel.GetType()
                                   .GetMethods()
                                   .Where(m => m.Name == "SaveState")
                                   .Where(m => m.ReturnType != typeof(void))
                                   .Where(m => !m.GetParameters().Any());

            foreach (var methodInfo in methods)
            {
                // use methods like `public T SaveState()`
                var stateObject = methodInfo.Invoke(viewModel, new object[0]);
                if (stateObject != null)
                {
                    toReturn.Write(stateObject);
                }
            }

            // call the general `public void SaveState(bundle)` method too
            viewModel.SaveState(toReturn);

            return toReturn;
        }
        public void Test_MissingDependency()
        {
            ClearAll();

            var bundle = new MvxBundle();

            var toTest = new MvxDefaultViewModelLocator();

            Assert.That(
                () => {
                    IMvxViewModel viewModel = toTest.Load(typeof(Test4ViewModel), bundle, null);
                },
                Throws.TypeOf<MvxException>().With.Message.StartWith("Problem creating viewModel"));
        }
        public void Test_FailingDependency()
        {
            ClearAll();

            Ioc.RegisterSingleton<ITestThing>(() => new FailingMockTestThing());

            var bundle = new MvxBundle();

            var toTest = new MvxDefaultViewModelLocator();

            Assert.That(
                () => {
                    IMvxViewModel viewModel = toTest.Load(typeof(Test4ViewModel), bundle, null);
                },
                Throws.TypeOf<MvxException>().With.Message.StartWith("Problem creating viewModel"));
        }
        public void Test_FailingInitialisation()
        {
            ClearAll();

            var testThing = new MockTestThing();
            Ioc.RegisterSingleton<ITestThing>(testThing);

            var bundle = new MvxBundle();

            var toTest = new MvxDefaultViewModelLocator();

            Assert.That(
                () => {
                    IMvxViewModel viewModel = toTest.Load(typeof(Test4ViewModel), bundle, null);
                },
                Throws.TypeOf<MvxException>().With.Message.StartWith("Problem running viewModel lifecycle"));
        }
        private void ShowAppointment()
        {
            var parameters = new MvxBundle(new Dictionary<string, string>
            {
                //["appointmentId"] = SecondAppointment.AppointmentId.ToString(CultureInfo.InvariantCulture)
                ["appointmentId"] = Appointments.ElementAt(1).AppointmentId.ToString(CultureInfo.InvariantCulture)
            });

            ShowViewModel<AppointmentDetailsViewModel>(parameters);
        }
Example #52
0
 protected override IMvxBundle LoadStateBundle(NavigationEventArgs navigationEventArgs)
 {
     try
     {
         var bundle = base.LoadStateBundle(navigationEventArgs);
         if (bundle == null)
         {
             bundle = new MvxBundle();
         }
         foreach (var data in State)
         {
             bundle.Data[data.Key] = data.Value.ToString();
         }
         return bundle;
     }
     catch (Exception exception)
     {
         Debug.WriteLine(exception.Message);
         return null;
     }
 }
        /// <summary>
        /// Attempts to call the 'SaveState' method
        /// on a controller to create a saved state bundle
        /// </summary>
        /// <param name="controller"></param>
        /// <returns>An IMvxBundle object that contains any saved state collected.</returns>
        public static IMvxBundle GetSavedState(this IMvxController controller)
        {
            var mvxBundle = new MvxBundle();
            var methods =
                controller.GetType()
                    .GetTypeInfo()
                    .DeclaredMethods.Where(m => m.Name == "SaveState")
                    .Where(m => m.ReturnType != typeof (void))
                    .Where(m => !m.GetParameters().Any());

            foreach (MethodInfo methodBase in methods)
            {
                object toStore = methodBase.Invoke(controller, new object[0]);
                if (toStore != null)
                    mvxBundle.Write(toStore);
            }
            return mvxBundle;
        }
        public void Test_FailingInitialisation()
        {
            ClearAll();

            var testThing = new MockTestThing();
            Ioc.RegisterSingleton<ITestThing>(testThing);

            var bundle = new MvxBundle();

            var toTest = new MvxDefaultViewModelLocator();

            IMvxViewModel viewModel = toTest.Load(typeof(Test4ViewModel), bundle, null);

            Assert.Fail("We should never reach this line");
        }
 private static void RunViewModelLifecycle(IMvxViewModel viewModel, IMvxBundle savedState,
     MvxViewModelRequest request)
 {
     try
     {
         if (request != null)
         {
             var parameterValues = new MvxBundle(request.ParameterValues);
             viewModel.CallBundleMethods("Init", parameterValues);
         }
         if (savedState != null)
         {
             viewModel.CallBundleMethods("ReloadState", savedState);
         }
         viewModel.Start();
     }
     catch (Exception exception)
     {
         throw exception.MvxWrap("Problem running viewModel lifecycle of type {0}", viewModel.GetType().Name);
     }
 }
        /// <summary>
        /// Checks for network connectivity, launches the user login, and if successful navigates to the
        /// appropriate start page based on the user's role (manager or not). Note also that we're using a
        /// presentation bundle in order to control clearing the navigation stack when showing the post-login
        /// page [so we don't end up with a Back button in iOS].
        /// </summary>
        /// <returns>Task.</returns>
        /// <exception cref="System.ArgumentException">Login Service must be set.</exception>
        private async Task LoginAndGo()
        {
            if (_loginService == null)
            {
                throw new ArgumentException("Login Service must be set.");
            }

            if (!NetworkService.IsConnected)
            {
                await
                    UserDialogs.AlertAsync("Device not connected to network, cannot login. Please try again later",
                        "Network Error");
                return;
            }

            try
            {
                var service = _azureService.MobileService;
                
                await _loginService.LoginAsync().ConfigureAwait(true);
                var profile = await LoadProfileAsync(service);
                UserContext.UserProfile = profile;

                var clearStackBundle = new MvxBundle(new Dictionary<string, string> { {PresentationBundleFlagKeys.ClearStack, "" } });

                if (profile.Manager)
                {
                    ShowViewModel<DashboardViewModel>(presentationBundle: clearStackBundle);
                }
                else
                {
                    ShowViewModel<WorkerQueueViewModel>(new { userId = profile.UserId }, clearStackBundle);
                }
                Close(this);
            }
            catch (InvalidOperationException)
            {
                UserDialogs.Alert("User login canceled", "Login Error");
            }
            catch (Exception)
            {
                UserDialogs.Alert("An unknown exception occurred logging in, please try again.", "Login Error");
            }
        }
		private void OnShowDetails(Appointment appointment)
		{
			var parameters = new MvxBundle(new Dictionary<string, string>
				{
					["appointmentId"] = appointment.AppointmentId.ToString(CultureInfo.InvariantCulture)
				});

			ShowViewModel<AppointmentDetailsViewModel>(parameters);
		}
 protected MvxPresentationHint(MvxBundle body)
 {
     Body = body;
 }
Example #59
0
        private MvxViewModelRequest GetViewModelRequestByHashCode(int hashCode)
        {
            // Select appropriate fragment based on hash-code value provide
            if (hashCode.Equals(SecondFragment)) return new MvxViewModelRequest() {ViewModelType = typeof (SecondFragViewModel)};
            if (hashCode.Equals(ThirdFragment)) return new MvxViewModelRequest() {ViewModelType = typeof(ThirdFragViewModel)};

            // Defaulting to first fragment if the appropriate fragment is not found above.
            // We will pass parameters into our first fragment.
            var test = new MvxBundle ( );
            test.Data.Add ( "one", "first parameter" );
            test.Data.Add ( "two", "2" );
            return new MvxViewModelRequest ( ) {
                ViewModelType = typeof ( FirstFragViewModel ),
                ParameterValues = test.Data
            };
        }
        public void Test_MissingDependency()
        {
            ClearAll();

            var bundle = new MvxBundle();

            var toTest = new MvxDefaultViewModelLocator();

            IMvxViewModel viewModel = toTest.Load(typeof(Test4ViewModel), bundle, null);

            Assert.Fail("We should never reach this line");
        }