public static void OnCreate(this IMvxFragmentView fragmentView, IMvxBundle bundle, MvxViewModelRequest request = null)
        {
            if (fragmentView.ViewModel != null)
            {
                //TODO call MvxViewModelLoader.Reload when it's added in MvvmCross, tracked by #1165
                //until then, we're going to re-run the viewmodel lifecycle here.
                RunViewModelLifecycle(fragmentView.ViewModel, bundle, request);

                return;
            }

            Fragment fragment = fragmentView as Fragment;
            if (fragmentView == null)
                throw new InvalidOperationException($"Something really weird. ${nameof(fragmentView)} passed is not a Fragment!");

            // as it is called during onCreate it is safe to assume that fragment has Activity attached.
            var viewModelType = fragmentView.FindAssociatedViewModelType(fragment.Activity.GetType());
            var view = fragmentView as IMvxView;

            var cache = Mvx.Resolve<IMvxMultipleViewModelCache>();
            var cached = cache.GetAndClear(viewModelType, fragmentView.UniqueImmutableCacheTag);

            view.OnViewCreate(() => cached ?? LoadViewModel(fragmentView, bundle, fragment.Activity.GetType(), request));

        }
        public void Test_Round_Trip_Works_For_Normal_ViewModel_Requests()
        {
            ClearAll();

            var viewModelNameLookup = new MvxViewModelByNameLookup();
            viewModelNameLookup.AddAll(this.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"]);
        }
        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 sealed override void Show(MvxViewModelRequest request)
 {
     if (_fragmentHostRegistrationSettings.IsTypeRegisteredAsFragment(request.ViewModelType))
         ShowFragment(request);
     else
         ShowActivity(request);
 }
 protected virtual void ShowActivity(MvxViewModelRequest request, MvxViewModelRequest fragmentRequest = null)
 {
     if (fragmentRequest == null)
         base.Show(request);
     else
         Show(request, fragmentRequest);
 }
        public override void Show(MvxViewModelRequest request)
        {
            if (TryShowPage(request))
                return;

            Mvx.Error("Skipping request for {0}", request.ViewModelType.Name);
        }
Esempio n. 7
0
        private bool TryShowPage(MvxViewModelRequest request)
        {
            var page = MvxPresenterHelpers.CreatePage(request);
            if (page == null)
                return false;

            var viewModel = MvxPresenterHelpers.LoadViewModel(request);

            var mainPage = _mvxFormsApp.MainPage as NavigationPage;
            page.BindingContext = viewModel;

            if (mainPage == null)
            {
                _mvxFormsApp.MainPage = new NavigationPage(page);
                mainPage = MvxFormsApp.MainPage as NavigationPage;
                CustomPlatformInitialization(mainPage);
            }
            else
            {
                try
                {
					// calling this sync blocks UI and never navigates hence code continues regardless here
					mainPage.PushAsync(page);
                }
                catch (Exception e)
                {
                    Mvx.Error("Exception pushing {0}: {1}\n{2}", page.GetType(), e.Message, e.StackTrace);
                    return false;
                }
            }

            return true;
        }
Esempio n. 8
0
        public static bool Handle(string path)
        {
            var viewDispatcher = Mvx.Resolve<IMvxViewDispatcher>();
            var appService = Mvx.Resolve<IApplicationService>();
            if (!path.EndsWith("/", StringComparison.Ordinal))
                path += "/";

            foreach (var route in Routes)
            {
                var regex = new Regex(route.Path, RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
                var match = regex.Match(path);
                var groups = regex.GetGroupNames().Skip(1);

                if (match.Success)
                {
                    var rec = new MvxViewModelRequest();
                    rec.ViewModelType = route.ViewModelType;
                    rec.ParameterValues = new Dictionary<string, string>();
                    foreach (var group in groups)
                        rec.ParameterValues.Add(group, match.Groups[group].Value);
                    appService.SetUserActivationAction(() => viewDispatcher.ShowViewModel(rec));
                    return true;
                }
            }

            return false;
        }
        public override void Show(MvxViewModelRequest request)
        {
            var viewType = Mvx.Resolve<IMvxWatchOSViewTranslator>().GetViewTypeFromViewModelRequest(request);
            var modelPath = viewType.ToString();
            var viewName = modelPath.Split('.').Last();

            _interfaceControllers.Last().PushController(viewName, (NSObject)null);
        }
Esempio n. 10
0
 public bool ShowViewModel(MvxViewModelRequest request)
 {
     Action action = () =>
         {
             MvxTrace.TaggedTrace("iOSNavigation", "Navigate requested");
             this._presenter.Show(request);
         };
     return this.RequestMainThreadAction(action);
 }
Esempio n. 11
0
        public override void Show(MvxViewModelRequest request)
        {
            var view = this.CreateViewControllerFor(request);

#warning Need to reinsert ClearTop type functionality here
            //if (request.ClearTop)
            //    ClearBackStack();

            this.Show(view);
        }
Esempio n. 12
0
 public AccountsView()
 {
     Request = new MvxViewModelRequest { ViewModelType = typeof(AccountsViewModel) };
     Style = UITableViewStyle.Plain;
     Title = "Accounts";
     NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Add, (s, e) => 
         NavigationController.PushViewController(new LoginView(), true));
     NavigationItem.LeftBarButtonItem = new UIBarButtonItem(Theme.CurrentTheme.CancelButton, UIBarButtonItemStyle.Plain, 
         (s, e) => DismissViewController(true, null));
 }
Esempio n. 13
0
            public void Start(object hint = null)
            {
                var userSettings = Mvx.Resolve<IUserSettings>();

                var startRequest = new MvxViewModelRequest();

                var districtSetting = userSettings?.DistrictSetting?.GetValueAsync()?.Result;
                startRequest.ViewModelType = districtSetting != null ? typeof (PersonalFeedsViewModel) : typeof (FirstUseViewModel);

                Mvx.Resolve<IMvxViewPresenter>().Show(startRequest);
            }
        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);
        }
Esempio n. 15
0
        public IMvxViewModel LoadViewModel(MvxViewModelRequest request, IMvxBundle savedState)
        {
            if (request.ViewModelType == typeof(MvxNullViewModel))
            {
                return new MvxNullViewModel();
            }

            var viewModelLocator = this.FindViewModelLocator(request);

            return this.LoadViewModel(request, savedState, viewModelLocator);
        }
        protected override Intent CreateIntentForRequest(MvxViewModelRequest request)
        {
            var intent = base.CreateIntentForRequest(request);

            if(request.ViewModelType == typeof(LoginViewModel))
            {
                intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
            }

            return intent;
        }
Esempio n. 17
0
        public void Show(MvxViewModelRequest request, MvxViewModelRequest fragmentRequest)
        {
            var intent = CreateIntentForRequest(request);
            if (fragmentRequest != null)
            {
                var converter = Mvx.Resolve<IMvxNavigationSerializer>();
                var requestText = converter.Serializer.SerializeObject(fragmentRequest);
                intent.PutExtra(ViewModelRequestBundleKey, requestText);
            }

            Show(intent);
        }
        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 static Page CreatePage(MvxViewModelRequest request)
 {
     IMvxFormsPageLoader viewPageLoader;
     Mvx.TryResolve(out viewPageLoader);
     if (viewPageLoader == null)
     {
         // load default instead
         viewPageLoader = new MvxFormsPageLoader();
         Mvx.RegisterSingleton(viewPageLoader);
     }
     var page = viewPageLoader.LoadPage(request);
     return page;
 }
        public override Fragment GetItem(int position)
        {
            var fragInfo = Fragments.ElementAt(position);

            if (fragInfo.CachedFragment == null)
            {
                fragInfo.CachedFragment = Fragment.Instantiate(_context, FragmentJavaName(fragInfo.FragmentType));

                var request = new MvxViewModelRequest (fragInfo.ViewModelType, null, null, null);
                ((IMvxView)fragInfo.CachedFragment).ViewModel = Mvx.Resolve<IMvxViewModelLoader>().LoadViewModel(request, null);
            }

            return fragInfo.CachedFragment;
        }
Esempio n. 21
0
 public override void Show(MvxViewModelRequest request)
 {
     try
     {
         var loader = Mvx.Resolve<IMvxSimpleWpfViewLoader>();
         var view = loader.CreateView(request);
         this.Present(view);
     }
     catch (Exception exception)
     {
         MvxTrace.Error("Error seen during navigation request to {0} - error {1}", request.ViewModelType.Name,
                        exception.ToLongString());
     }
 }
        public async Task TryShow(MvxViewModelRequest request, INavigation navigation)
        {
            Page page = null;
            if (request.ViewModelType.GetTypeInfo().ImplementedInterfaces.Contains(typeof (IFeedsViewModel)))
            {
                page = new FeedsPage();
            }
            else
            {
                try
                {
                    page = MvxPresenterHelpers.CreatePage(request);
                }
                catch (Exception e)
                {
                    
                }
            }

            bool flag;
            if (page == null)
            {
                flag = false;
            }
            else
            {
                IMvxViewModel mvxViewModel = MvxPresenterHelpers.LoadViewModel(request);
                page.BindingContext = mvxViewModel;

                var busy = Binding.Create<BaseViewModel>(vm => vm.IsLoading);
                page.SetBinding(Page.IsBusyProperty, busy);

                var titleBinding = Binding.Create<BaseViewModel>(vm => vm.Title);
                page.SetBinding(Page.TitleProperty, titleBinding);

                try
                {
                    await navigation.PushAsync(page);
                }
                catch (Exception ex)
                {
                    Mvx.Error("Exception pushing {0}: {1}\n{2}", (object) page.GetType(), (object) ex.Message,
                        (object) ex.StackTrace);
                }
            }

            flag = true;
        }
        private static IMvxViewModel LoadViewModel(this IMvxStoreView storeView,
                                                   MvxViewModelRequest viewModelRequest,
                                                   IMvxBundle bundle)
        {
#warning ClearingBackStack disabled for now
            //            if (viewModelRequest.ClearTop)
            //            {
            //#warning TODO - BackStack not cleared for WinRT
            //phoneView.ClearBackStack();
            //            }

            var loaderService = Mvx.Resolve<IMvxViewModelLoader>();
            var viewModel = loaderService.LoadViewModel(viewModelRequest, bundle);

            return viewModel;
        }
Esempio n. 24
0
        protected virtual Type GetPageType(MvxViewModelRequest request)
        {
            if (_viewFinder == null)
                _viewFinder = Mvx.Resolve<IMvxViewsContainer> ();

            try
            {
                return _viewFinder.GetViewType (request.ViewModelType);
            }
            catch(KeyNotFoundException)
            {
                var pageName = GetPageName(request);
                return request.ViewModelType.GetTypeInfo().Assembly.CreatableTypes()
                    .FirstOrDefault(t => t.Name == pageName);
            }
        }
        public override async void Show(MvxViewModelRequest request)
        {
            var page = MvxPresenterHelpers.CreatePage(request);
            if (page == null)
                return;

            var viewModel = MvxPresenterHelpers.LoadViewModel(request);

            var mainPage = Application.Current.MainPage as NavigationPage;
            page.BindingContext = viewModel;

            if (mainPage == null)
            {
                Application.Current.MainPage = new NavigationPage(page);
                mainPage = Application.Current.MainPage as NavigationPage;
                _viewStack.Add(page);

                // disable navigation bar
                NavigationPage.SetHasNavigationBar(mainPage, false);
                NavigationPage.SetHasNavigationBar(page, false);

                CustomPlatformInitialization(mainPage);
            }
            else
            {
                try
                {
                    NavigationPage.SetHasNavigationBar(page, false);

                    if (IsModal(page))
                    {
                        await mainPage.Navigation.PushModalAsync(page, true);
                    }
                    else
                    {
                        await mainPage.PushAsync(page);
                    }
                    
                    _viewStack.Add(page);
                }
                catch (Exception e)
                {
                    Mvx.Error("Exception pushing {0}: {1}\n{2}", page.GetType(), e.Message, e.StackTrace);
                }
            }
        }
Esempio n. 26
0
        private bool Intercept(MvxViewModelRequest request)
        {
            if (request.ViewModelType == typeof(ThirdFragment))
            {
                var activity = Mvx.Resolve<IMvxAndroidCurrentTopActivity>().Activity;
                var viewModel = MvxViewModelLoader.LoadViewModel(request, null) as ThirdFragment;
                _modal = new CustomDialog(activity, Resource.Layout.modal_popup, viewModel);
                _modal.Show();
                return true;
            }

            if (_modal != null)
            {
                _modal.Dismiss();
                _modal = null;
            }
            return false;
        }
Esempio n. 27
0
 public override void Show(MvxViewModelRequest request)
 {
     lock (this)
     {
         var viewType = GetViewType(request.ViewModelType);
         if (viewType == null)
         {
             throw new MvxException("View Type not found for " + request.ViewModelType);
         }
         var view = (IMvxConsoleView)Activator.CreateInstance(viewType);
         var viewModelLoader = Mvx.Resolve<IMvxViewModelLoader>();
         IMvxBundle savedState = null;
         var viewModel = viewModelLoader.LoadViewModel(request, savedState);
         view.HackSetViewModel(viewModel);
         Mvx.Resolve<IMvxConsoleCurrentView>().CurrentView = view;
         this._navigationStack.Push(request);
     }
 }
Esempio n. 28
0
        public Page LoadPage(MvxViewModelRequest request)
        {
            var pageName = GetPageName(request);
            var pageType = GetPageType(request);

            if (pageType == null)
            {
                Mvx.Trace("Page not found for {0}", pageName);
                return null;
            }

            var page = Activator.CreateInstance(pageType) as Page;
            if (page == null)
            {
                Mvx.Error("Failed to create ContentPage {0}", pageName);
            }
            return page;
        }
        public override void Show(MvxViewModelRequest request)
        {
            try
            {
                var requestTranslator = Mvx.Resolve<IMvxViewsContainer>();
                var viewType = requestTranslator.GetViewType(request.ViewModelType);

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

                this._rootFrame.Navigate(viewType, requestText); //Frame won't allow serialization of it's nav-state if it gets a non-simple type as a nav param
            }
            catch (Exception exception)
            {
                MvxTrace.Trace("Error seen during navigation request to {0} - error {1}", request.ViewModelType.Name,
                               exception.ToLongString());
            }
        }
Esempio n. 30
0
        public virtual IMvxIosView CreateView(MvxViewModelRequest request)
        {
            try
            {
                this.CurrentRequest = request;
                var viewType = this.GetViewType(request.ViewModelType);
                if (viewType == null)
                    throw new MvxException("View Type not found for " + request.ViewModelType);

                var view = this.CreateViewOfType(viewType, request);
                view.Request = request;
                return view;
            }
            finally
            {
                this.CurrentRequest = null;
            }
        }
Esempio n. 31
0
        public override void Show(MvvmCross.Core.ViewModels.MvxViewModelRequest request)
        {
            if (request.PresentationValues != null)
            {
                #region ClearStack
                if (request.PresentationValues.ContainsKey(PresentationBundleFlagKeys.ClearStack))
                {
                    //MasterNavigationController.PopToRootViewController(false);
                    var nextViewController = (UIViewController)ViewCreator.CreateView(request);
                    MasterNavigationController.PushViewController(nextViewController, true);
                    return;
                }
                #endregion

                #region ShowBack
                if (request.PresentationValues.ContainsKey(PresentationBundleFlagKeys.ShowBack))
                {
                    var  nextViewController    = (UIViewController)ViewCreator.CreateView(request);
                    var  currentViewController = MasterNavigationController.TopViewController;
                    bool animated = false;

                    while (!animated && currentViewController != null && currentViewController.GetType() != nextViewController.GetType())
                    {
                        if (MasterNavigationController.ViewControllers.Length > 1)
                        {
                            var backViewController = MasterNavigationController.ViewControllers[MasterNavigationController.ViewControllers.Length - 2];
                            if (backViewController.GetType() == nextViewController.GetType())
                            {
                                animated = true;
                            }
                        }
                        else
                        {
                            break;
                        }

                        MasterNavigationController.PopViewController(animated);

                        if (animated)
                        {
                            MemoryUtils.DelayReleaseObject(2000, currentViewController);
                        }
                        else
                        {
                            MemoryUtils.ReleaseObject(currentViewController);
                        }

                        currentViewController = MasterNavigationController.TopViewController;
                    }

                    if (MasterNavigationController.ViewControllers.Length <= 1)
                    {
                        MasterNavigationController.PushViewController(nextViewController, true);
                    }

                    return;
                }
                #endregion

                #region CloseCurrentAndShow
                if (request.PresentationValues.ContainsKey(PresentationBundleFlagKeys.CloseCurrentAndShow))
                {
                    // let make a async task to remove current from history to not make UI flash
                    System.Threading.Tasks.Task.Run(async() =>
                    {
                        await System.Threading.Tasks.Task.Delay(1000);

                        if (closeViewController == null)
                        {
                            return;
                        }
                        MasterNavigationController.InvokeOnMainThread(async() =>
                        {
                            //wait for until top view controller is showed
                            while (closeViewController != MasterNavigationController.TopViewController)
                            {
                                await System.Threading.Tasks.Task.Delay(100);
                            }

                            int countVc = MasterNavigationController.ViewControllers.Length;

                            if (countVc > 1)
                            {
                                UIViewController releaseViewController = MasterNavigationController.ViewControllers[countVc - 2];
                                UIViewController[] newHistory          = new UIViewController[countVc - 1];
                                for (int i = 0; i < countVc - 2; i++)
                                {
                                    newHistory[i] = MasterNavigationController.ViewControllers[i];
                                }
                                newHistory[countVc - 2] = MasterNavigationController.ViewControllers[countVc - 1];
                                MasterNavigationController.ViewControllers = newHistory;

                                MemoryUtils.ReleaseObject(releaseViewController);
                            }

                            closeViewController = null;
                        });
                    });
                }
                #endregion
            }
            base.Show(request);
        }
Esempio n. 32
0
        public IMvxViewModel ReloadViewModel <TParameter>(IMvxViewModel <TParameter> viewModel, TParameter param, MvxViewModelRequest request, IMvxBundle savedState)
        {
            var viewModelLocator = FindViewModelLocator(request);

            var parameterValues = new MvxBundle(request.ParameterValues);

            try
            {
                viewModel = viewModelLocator.Reload(viewModel, param, 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);
            }

            return(viewModel);
        }
Esempio n. 33
0
        // Reload should be used to re-run cached ViewModels lifecycle if required.
        public IMvxViewModel ReloadViewModel(IMvxViewModel viewModel, MvxViewModelRequest request, IMvxBundle savedState)
        {
            var viewModelLocator = this.FindViewModelLocator(request);

            return(this.ReloadViewModel(viewModel, request, savedState, viewModelLocator));
        }
Esempio n. 34
0
 public IMvxViewModelLocator FindViewModelLocator(MvxViewModelRequest request)
 {
     return(DefaultLocator);
 }