public void ProviderShouldRestoreViewModelState()
        {
            DataConstant <string> key   = "key";
            const string          value = "value";
            var loadViewModel           = new ViewModel();
            var childIoc     = new IocContainerMock();
            var iocContainer = new IocContainerMock
            {
                GetFunc = (type, s, arg3) =>
                {
                    typeof(ViewModel).ShouldEqual(type);
                    return(loadViewModel);
                },
                CreateChild = mock => childIoc
            };

            childIoc.GetFunc = iocContainer.GetFunc;
            var viewModel = new ViewModel();

            viewModel.Settings.State.Add(key, value);
            ViewModelProvider provider = GetViewModelProvider(iocContainer);

            var state            = provider.PreserveViewModel(viewModel, DataContext.Empty);
            var restoreViewModel = provider.RestoreViewModel(state, DataContext.Empty, true);

            restoreViewModel.IocContainer.ShouldEqual(childIoc);
            restoreViewModel.ShouldEqual(loadViewModel);
            restoreViewModel.Settings.State.GetData(key).ShouldEqual(value);
        }
        public void GetViewModelShouldUseIocContainerToCreateViewModel()
        {
            var context    = new DataContext();
            int initialize = 0;
            var vm         = new ViewModel
            {
                InitializeViewModel = dataContext =>
                {
                    dataContext.ShouldEqual(context);
                    ++initialize;
                }
            };
            var iocContainer = new IocContainerMock
            {
                GetFunc = (type, s, arg3) =>
                {
                    type.ShouldEqual(typeof(ViewModel));
                    return(vm);
                }
            };

            ViewModelProvider provider  = GetViewModelProvider(iocContainer);
            IViewModel        viewModel = provider.GetViewModel(typeof(ViewModel), context);

            viewModel.ShouldEqual(vm);
            initialize.ShouldEqual(1);
        }
Exemplo n.º 3
0
        public void PreserveViewModels([NotNull] IDataContext context)
        {
            Should.NotBeNull(context, nameof(context));
            context.Remove(MultiViewModelState.ViewModelState);
            if (ItemsSource.Count == 0)
            {
                return;
            }
            var states = new MultiViewModelState {
                State = new List <IDataContext>()
            };

            for (int index = 0; index < ItemsSource.Count; index++)
            {
                var viewModel = ItemsSource[index];
                states.State.Add(ViewModelProvider.PreserveViewModel(viewModel, DataContext.Empty));
                if (ReferenceEquals(viewModel, SelectedItem))
                {
                    context.AddOrUpdate(MultiViewModelState.SelectedIndex, index);
                }
            }
            if (states.State.Count != 0)
            {
                context.AddOrUpdate(MultiViewModelState.ViewModelState, states);
            }
        }
        public void ProviderShouldBindIocContainerBindIocContainerTrue()
        {
            Type   typeFrom     = null;
            object item         = null;
            string name         = null;
            var    iocContainer = new IocContainerMock
            {
                BindToConstantFunc = (type, arg2, arg3) =>
                {
                    typeFrom = type;
                    item     = arg2;
                    name     = arg3;
                }
            };
            ViewModelProvider provider = GetViewModelProvider(iocContainer);

            provider.BindIocContainer = true;
            var context = new DataContext();

            IViewModel viewModel = provider.GetViewModel(container => new ViewModel(), context);

            typeFrom.ShouldEqual(typeof(IIocContainer));
            item.ShouldEqual(viewModel.IocContainer);
            name.ShouldBeNull();
        }
Exemplo n.º 5
0
 public void SetUp()
 {
     ServiceProvider.DesignTimeManager     = DesignTimeManagerImpl.Instance;
     ServiceProvider.AttachedValueProvider = new AttachedValueProvider();
     CanBeResolvedTypes = new List <Type>
     {
         typeof(IThreadManager),
         typeof(IViewModelSettings),
         typeof(IViewManager),
         typeof(IDisplayNameProvider),
         typeof(IViewModelProvider),
         typeof(IVisualStateManager),
         typeof(OperationCallbackManagerMock)
     };
     OperationCallbackManager = new OperationCallbackManagerMock();
     ViewManager   = new ViewManagerMock();
     ThreadManager = new ThreadManagerMock();
     ServiceProvider.ThreadManager = ThreadManager;
     Settings = new ViewModelSettingsMock();
     ApplicationSettings.ViewModelSettings = Settings;
     DisplayNameProvider = new DisplayNameProviderMock();
     IocContainer        = new IocContainerMock
     {
         GetFunc            = GetFunc,
         CanResolveDelegate = CanResolve
     };
     ServiceProvider.Tracer = new ConsoleTracer();
     ServiceProvider.Initialize(IocContainer, PlatformInfo.UnitTest);
     ViewModelProvider = new ViewModelProvider(IocContainer);
     OnInit();
 }
Exemplo n.º 6
0
        public override void UpdateBindings()
        {
            base.UpdateBindings();

            if (_dstView != null)
            {
                var props = _dstView.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                DstProps = props.Where(prop => prop.GetSetMethod(false) != null &&
                                       prop.GetSetMethod(false) != null &&
                                       !prop.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any()
                                       ).Select(e => new BindablePropertyInfo {
                    PropertyName = e.Name, PropertyType = e.PropertyType.Name
                }).ToList();
            }

            if (!string.IsNullOrEmpty(ViewModelName))
            {
                var props = ViewModelProvider.GetViewModelFields(ViewModelName);
                SrcProps = props.Where(prop =>
                                       prop.FieldType.IsAssignableToGenericType(typeof(Reactive.ReactiveProperty <>)) &&
                                       !prop.GetCustomAttributes(typeof(ObsoleteAttribute), true)
                                       .Any())
                           .Select(e => new BindablePropertyInfo(e.Name, e.FieldType.IsGenericType ? e.FieldType.GetGenericArguments()[0].Name : e.FieldType.BaseType.GetGenericArguments()[0].Name)).ToList();
                SrcProps.AddRange(GetExtraViewModelProperties(props));
            }
        }
Exemplo n.º 7
0
        private void OpenSettingsExecute()
        {
            SettingsViewModel settings = ViewModelProvider.GetInstance <SettingsViewModel>();

            ServiceProvider.GetInstance <InteractionService>().ShowContent(settings);
            UpdateConnectionStatusCommand.Execute(null);
        }
Exemplo n.º 8
0
        protected virtual INavigationContext CreateContextNavigateTo(NavigationEventArgsBase args)
        {
            IViewModel viewModelFrom = null, viewModelTo = null;

            if (args.NavigationMode.IsClose())
            {
                viewModelFrom = args.Context.GetData(NavigationConstants.ViewModel);
            }
            else
            {
                viewModelTo = args.Context.GetData(NavigationConstants.ViewModel);
            }

            if (viewModelFrom == null)
            {
                viewModelFrom = CurrentViewModel;
            }
            if (args.NavigationMode == NavigationMode.Remove)
            {
                if (viewModelFrom != null)
                {
                    return(new NavigationContext(NavigationType.Page, NavigationMode.Remove, viewModelFrom, null, this, args.Context));
                }
                Tracer.Error("Possible bug in navigation, navigate with mode Remove mode without ViewModel");
            }

            Guid viewModelId;
            var  vmType = GetViewModelTypeFromParameter(args.Parameter, out viewModelId);

            if (viewModelTo == null && vmType != null)
            {
                viewModelTo = ViewModelProvider.TryGetViewModelById(viewModelId);
            }
            if (vmType == null)
            {
                if (args.Content != null)
                {
                    var items = ViewMappingProvider.FindMappingsForView(args.Content.GetType(), false);
                    if (items.Count == 1)
                    {
                        var type = items[0].ViewModelType;
#if WINDOWS_UWP || XAMARIN_FORMS
                        if (!type.GetTypeInfo().IsGenericTypeDefinition)
#else
                        if (!type.IsGenericTypeDefinition)
#endif

                        { vmType = type; }
                    }
                }
                if (vmType == null)
                {
                    return(new NavigationContext(NavigationType.Page, args.NavigationMode, viewModelFrom, viewModelTo, this, args.Context));
                }
            }
            return(new NavigationContext(NavigationType.Page, args.NavigationMode, viewModelFrom, viewModelTo, this, args.Context)
            {
                { ViewModelTypeConstant, vmType }
            });
        }
Exemplo n.º 9
0
        protected override void OnPropertyChanged(string propertyName)
        {
            base.OnPropertyChanged(propertyName);

            if (propertyName == GetPropertyName(() => CurrentTab))
            {
                if (CurrentTab == "Home")
                {
                    DataViewModel = ViewModelProvider.GetInstance <HomeViewModel>();
                }
                else if (CurrentTab == "Items")
                {
                    DataViewModel = ViewModelProvider.GetInstance <ItemLocalizationViewModel>();
                }
                else if (CurrentTab == "Game Objects")
                {
                    DataViewModel = ViewModelProvider.GetInstance <GameObjectLocalizationViewModel>();
                }
                else if (CurrentTab == "Quests")
                {
                    DataViewModel = ViewModelProvider.GetInstance <QuestLocalizationViewModel>();
                }
                else
                {
                    DataViewModel = null;
                }
            }
        }
Exemplo n.º 10
0
        private void InitApp()
        {
            var container = new SimpleIoc();

            container.Register <IUserProfileRepository>(
                () => new UserProfileRepository());

            container.Register <INavigationService>(
                () => new NavigationService());

            container.Register(
                () => new EntryViewModel(
                    container.Get <INavigationService>()));

            container.Register(
                () => new UserProfileViewModel(
                    container.Get <IUserProfileRepository>(),
                    container.Get <INavigationService>()));

            container.Register(
                () => new LanguagesViewModel(
                    container.Get <INavigationService>()));

            ViewModelProvider.SetFactory(new DependencyProviderViewModelFactory(container));
        }
Exemplo n.º 11
0
        protected virtual void BindViewModelProvider(IModuleContext context, IIocContainer container)
        {
            IViewModelProvider viewModelProvider = new ViewModelProvider(container.GetRoot());

            ServiceProvider.ViewModelProvider = viewModelProvider;
            container.BindToConstant(viewModelProvider);
        }
Exemplo n.º 12
0
        public void SetUp()
        {
            ServiceProvider.AttachedValueProvider    = new AttachedValueProvider();
            ServiceProvider.ViewModelSettingsFactory = model => new DefaultViewModelSettings();
            ServiceProvider.ReflectionManager        = new ExpressionReflectionManager();
            CanBeResolvedTypes = new List <Type>
            {
                typeof(IThreadManager),
                typeof(IViewManager),
                typeof(IDisplayNameProvider),
                typeof(IViewModelProvider),
                typeof(OperationCallbackManagerMock),
                typeof(INavigationDispatcher),
                typeof(IViewModelPresenter)
            };
            OperationCallbackManager = new OperationCallbackManagerMock();
            NavigationDispatcher     = new NavigationDispatcherMock();
            ViewManager                   = new ViewManagerMock();
            ThreadManager                 = new ThreadManagerMock();
            ViewModelPresenter            = new ViewModelPresenterMock();
            ServiceProvider.ThreadManager = ThreadManager;
            DisplayNameProvider           = new DisplayNameProviderMock();
            IocContainer                  = new IocContainerMock
            {
                GetFunc            = GetFunc,
                CanResolveDelegate = CanResolve
            };
            Tracer.TraceInformation = true;
            ServiceProvider.Tracer  = new ConsoleTracer();
            ViewModelProvider       = new ViewModelProvider(IocContainer);
            OnInit();
            var app = new UnitTestApp();

            app.Initialize(PlatformInfo.UnitTest, IocContainer, Empty.Array <Assembly>(), DataContext.Empty);
        }
Exemplo n.º 13
0
        public void SetUp()
        {
            ServiceProvider.DesignTimeManager     = DesignTimeManagerImpl.Instance;
            ServiceProvider.AttachedValueProvider = new AttachedValueProvider();
            CanBeResolvedTypes = new List <Type>
            {
                typeof(IThreadManager),
                typeof(IViewModelSettings),
                typeof(IViewManager),
                typeof(IDisplayNameProvider),
                typeof(IViewModelProvider),
                typeof(IVisualStateManager),
                typeof(OperationCallbackManagerMock)
            };
            OperationCallbackManager = new OperationCallbackManagerMock();
            ViewManager   = new ViewManagerMock();
            ThreadManager = new ThreadManagerMock();
            ServiceProvider.ThreadManager = ThreadManager;
            Settings            = new ViewModelSettingsMock();
            DisplayNameProvider = new DisplayNameProviderMock();
            IocContainer        = new IocContainerMock
            {
                GetFunc            = GetFunc,
                CanResolveDelegate = CanResolve
            };
            Tracer.TraceInformation = true;
            ServiceProvider.Tracer  = new ConsoleTracer();
            ViewModelProvider       = new ViewModelProvider(IocContainer);
            OnInit();
            var app = new UnitTestApp(this);

            app.Initialize(PlatformInfo.UnitTest, IocContainer, Empty.Array <Assembly>(), DataContext.Empty);
        }
Exemplo n.º 14
0
        public void UpdateBindings()
        {
            ViewModels = ViewModelProvider.Instance.ViewModels;

            if (_srcView != null)
            {
                var props = _srcView.GetType().GetProperties(/*BindingFlags.DeclaredOnly |*/ BindingFlags.Instance | BindingFlags.Public);

                SrcEvents = props
                            .Where(p => p.PropertyType.IsSubclassOf(typeof(UnityEventBase)) &&
                                   !p.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any())
                            .Select(p => p.Name).ToList();

                if (!string.IsNullOrEmpty(SrcEventName))
                {
                    _srcEventProp = _srcView.GetType().GetProperty(SrcEventName);
                }
            }

            if (!string.IsNullOrEmpty(ViewModelName))
            {
                var methods = ViewModelProvider.GetViewModelType(ViewModelName)
                              .GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);

                DstMethods = methods.Where(m => !m.IsSpecialName && !m.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any()).Select(e => e.Name).ToList();;
            }


            if (!string.IsNullOrEmpty(DstMethodName))
            {
                _method = ViewModelProvider.GetViewModelType(ViewModelName).GetMethod(DstMethodName);
            }
        }
        public void ReInitializationShouldNotThrowExceptionThrowOnMultiInitFalse()
        {
            ThreadManager.ImmediateInvokeAsync = true;
            ViewModelBase viewModel = GetViewModelBase();

            ViewModelProvider.InitializeViewModel(viewModel, null);
        }
Exemplo n.º 16
0
        protected virtual void BindEvent()
        {
            _dstViewModel = ViewModelProvider.Instance.GetViewModelBehaviour(ViewModelName);

            //TODO: Wrap PropertyInfo & MethodInfo in Serializable classes so we don't need reflection here

            if (_srcEventProp == null)
            {
                _srcEventProp = _srcView.GetType().GetProperty(SrcEventName);
            }

            if (_method == null)
            {
                _method = ViewModelProvider.GetViewModelType(ViewModelName).GetMethod(DstMethodName);
            }

            if (_method == null)
            {
                Debug.LogErrorFormat("EventBinding error in {0}. No method found in {1} with name {2}", gameObject.name, ViewModelName, DstMethodName);

                return;
            }

            var method = UnityEventBinder.GetAddListener(_srcEventProp.GetValue(_srcView));

            var arg = method.GetParameters()[0];

            d = Delegate.CreateDelegate(arg.ParameterType, _dstViewModel, _method);

            var p = new object[] { d };

            method.Invoke(_srcEventProp.GetValue(_srcView), p);
        }
Exemplo n.º 17
0
            private IViewModel FindViewModel(ICollection <IViewModel> viewModels)
            {
                Guid id     = Guid.Empty;
                var  vmType = Type.GetType(TypeName, true);

                if (State is Guid)
                {
                    id = (Guid)State;
                }

                var vm = ViewModelProvider.TryGetViewModelById(id);

                if (vm != null)
                {
                    return(vm);
                }
                foreach (var viewModel in viewModels)
                {
                    if (viewModel.GetViewModelId() == id)
                    {
                        return(viewModel);
                    }
                    if (viewModel.GetType() == vmType)
                    {
                        vm = viewModel;
                    }
                }
                return(vm);
            }
        public static StonehengeResourceLoader CreateDefaultLoader(IStonehengeResourceProvider provider)
        {
            var assemblies = new List <Assembly>
            {
                Assembly.GetEntryAssembly(),
                Assembly.GetExecutingAssembly(),
                Assembly.GetAssembly(typeof(ResourceLoader)),
                Assembly.GetCallingAssembly()
            }
            .Distinct()
            .ToList();

            var resLoader = new ResourceLoader(assemblies, Assembly.GetCallingAssembly());

            if (provider != null)
            {
                resLoader.AddAssembly(provider.GetType().Assembly);
            }

            var path       = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location) ?? Directory.GetCurrentDirectory();
            var fileLoader = new FileLoader(Path.Combine(path, "App"));

            var viewModelCreator = new ViewModelProvider();

            var loader = new StonehengeResourceLoader(new List <IStonehengeResourceProvider> {
                fileLoader, resLoader, viewModelCreator
            });

            if (provider != null)
            {
                loader.Loaders.Add(provider);
            }
            return(loader);
        }
        public override bool ExecuteTest()
        {
            if (_binder is null)
            {
                LogNotMineError();
                return(false);
            }

            bool ValidateSrcCollection(Type ownerType, BindablePropertyInfo property)
            {
                var propInfo = ownerType.GetProperty(property.PropertyName);

                return(!(propInfo is null) &&
                       propInfo.PropertyType.IsAssignableToGenericType(typeof(RxCollection <>)) &&
                       !propInfo.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any());
            }

            var validateSrcCollection = ValidateSrcCollection(ViewModelProvider.GetViewModelType(_binder.ViewModelName), _binder.SrcCollectionName);

            if (!validateSrcCollection)
            {
                Errors.Push("Source collection is not valid");
            }
            return(validateSrcCollection);
        }
Exemplo n.º 20
0
        public override bool ExecuteTest()
        {
            if (!base.ExecuteTest())
            {
                return(false);
            }

            if (_binder is null)
            {
                LogNotMineError();
                return(false);
            }

            bool ValidateSrcProperty(Type ownerType, BindablePropertyInfo property)
            {
                var propInfo = ownerType.GetProperty(property.PropertyName);

                if (propInfo == null)
                {
                    return(false);
                }

                var genericType = (property.IsStatic
                    ? propInfo.PropertyType
                    : propInfo.PropertyType.GetGenericTypeRecursive()?.GetGenericArguments()[0])?.Name;

                return(!propInfo.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any() &&
                       property.PropertyType == genericType);
            }

            bool ValidateDstProperty(Type ownerType, BindablePropertyInfo property)
            {
                var propInfo = ownerType.GetProperty(property.PropertyName);

                return(!(propInfo is null) && propInfo.PropertyType.Name == property.PropertyType);
            }

            var validateSrcProperty = ValidateSrcProperty(ViewModelProvider.GetViewModelType(_binder.ViewModelName), _binder.SrcPropertyName);

            if (!validateSrcProperty)
            {
                Errors.Push("Source property is not valid");
            }
            var validateDstView = !(_binder._dstView is null);

            if (!validateDstView)
            {
                Errors.Push("Destination view is not valid");
            }
            var validateDstProperty = validateDstView && ValidateDstProperty(_binder._dstView.GetType(), _binder.DstPropertyName);

            if (!validateDstProperty)
            {
                Errors.Push("Destination property is not valid");
            }
            return(validateSrcProperty &&
                   validateDstView &&
                   validateDstProperty);
        }
        protected override void OnAppearing()
        {
            CommonActions.OnNavigateToPage += CommonActions_OnNavigateToPage;
            var vm = ViewModelProvider.GetViewModel <MainPageViewModel>();

            vm.RefreshChildren();
            base.OnAppearing();
        }
Exemplo n.º 22
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Hopefully, the CurrentThread scheduler is the MacOS dispatcher thread.
            DispatcherHelper.DefaultDispatcherScheduler = Scheduler.CurrentThread;
            ViewModel = ViewModelProvider.ProvideMainViewModel();
        }
        public void WhenVmIsInitializedPropertyIsInitializedShouldChanged()
        {
            var testViewModel = new TestViewModelBase();

            testViewModel.IsInitialized.ShouldBeFalse();
            ViewModelProvider.InitializeViewModel(testViewModel, null);
            testViewModel.IsInitialized.ShouldBeTrue();
        }
        public virtual void LoadState(IDataContext state)
        {
            var context = state.GetData <IDataContext>(StateKey);

            if (context != null)
            {
                SelectedItem = ViewModelProvider.RestoreViewModel(context, null, true);
            }
        }
        public virtual void SaveState(IDataContext state)
        {
            var selectedItem = SelectedItem;

            if (selectedItem != null)
            {
                state.AddOrUpdate(StateKey, ViewModelProvider.PreserveViewModel(selectedItem, null));
            }
        }
        public void ProviderShouldCallSaveStateMethodOnPreserveViewModel()
        {
            var iocContainer           = new IocContainerMock();
            var viewModel              = new ViewModel();
            ViewModelProvider provider = GetViewModelProvider(iocContainer);

            provider.PreserveViewModel(viewModel, DataContext.Empty);
            viewModel.SaveStateCount.ShouldEqual(1);
            viewModel.LoadStateCount.ShouldEqual(0);
        }
        /// <summary>
        ///     Saves state.
        /// </summary>
        void IHasState.SaveState(IDataContext state)
        {
            object data;

            if (ViewModel != null && (!ViewModel.Settings.Metadata.TryGetData(ViewModelConstants.StateManager, out data) || ReferenceEquals(data, ViewModelConstants.StateManager)))
            {
                state.AddOrUpdate(ViewModelConstants.ViewModelTypeName, ViewModel.GetType().AssemblyQualifiedName);
                state.AddOrUpdate(ViewModelConstants.ViewModelState, ViewModelProvider.PreserveViewModel(ViewModel, DataContext.Empty));
            }
            OnSaveState(state);
        }
Exemplo n.º 28
0
        protected override void CollectPropertyLists()
        {
            var bindingMode = (BindingMode)_bindingModeProp.enumValueIndex;

            base.CollectPropertyLists();

            if (_viewModelChanged)
            {
                _srcNames.Value = null;
                _srcPaths.Value = null;
            }

            if (string.IsNullOrEmpty(_viewModelProp.Value))
            {
                return;
            }

            var view = _dstViewProp.objectReferenceValue as Component;

            _srcNames.Clear();
            _srcPaths.Clear();
            _dstNames.Clear();
            _dstPaths.Clear();

            _dstChangeEvents.Clear();


            if (view)
            {
                var dstNeedsGetter = bindingMode != BindingMode.OneWay;
                var dstNeedsSetter = bindingMode != BindingMode.OneWayToSource;

                _dstNames.Values        = view.GetBindablePropertyList(needsGetter: dstNeedsGetter, needsSetter: dstNeedsSetter);
                _dstPaths.Values        = view.GetPropertiesAndFieldsList(_dstNames.Value);
                _dstChangeEvents.Values = view.GetBindableEventsList();
            }
            else
            {
                _dstNames.Value        = null;
                _dstPaths.Value        = null;
                _dstChangeEvents.Value = null;
            }

            var vmType = ViewModelProvider.GetViewModelType(ViewModelName);

            _srcNames.Values = ViewModelProvider.GetViewModelPropertyList(ViewModelName);

            var propType = vmType.GetProperty(_srcNames.Value)?.PropertyType;

            if (propType != null)
            {
                _srcPaths.Values = propType.GetNestedFields();
            }
        }
        public MainWindow()
        {
            var fileAccess = new Persistence.HardDrivesRepository();

            _reader   = fileAccess;
            _reWriter = fileAccess;
            _provider = new ViewModelProvider(fileAccess);
            InitializeComponent();
            myVar        = new Stack <string>();
            PlaceChanger = new FIlePlaceChanger(fileAccess, fileAccess);
        }
Exemplo n.º 30
0
        public async Task PushAsync <TViewModel>(Action <TViewModel> customInit = null)
            where TViewModel : ViewModelBase, new()
        {
            var viewmodel = ViewModelProvider.GetViewModel <TViewModel>(customInit);

            // TODO: Throw new custom exception if unable to create VM?

            if (viewmodel != null)
            {
                await PushAsync(viewmodel);
            }
        }