Exemplo n.º 1
0
        static IObservable <WebResponse> MakeWebRequest(
            Uri uri,
            IDictionary <string, string> headers = null,
            string content   = null,
            int retries      = 3,
            TimeSpan?timeout = null)
        {
            IObservable <WebResponse> request;

#if !SILVERLIGHT && !WINRT
            if (ModeDetector.InUnitTestRunner())
            {
                request = Observable.Defer(() =>
                {
                    var hwr = CreateWebRequest(uri, headers);

                    if (content == null)
                    {
                        return(Observable.Start(() => hwr.GetResponse(), BlobCache.TaskpoolScheduler));
                    }

                    var buf = Encoding.UTF8.GetBytes(content);
                    return(Observable.Start(() =>
                    {
                        hwr.GetRequestStream().Write(buf, 0, buf.Length);
                        return hwr.GetResponse();
                    }, BlobCache.TaskpoolScheduler));
                });
            }
            else
#endif
            {
                request = Observable.Defer(() =>
                {
                    var hwr = CreateWebRequest(uri, headers);

                    if (content == null)
                    {
                        return(Observable.FromAsyncPattern <WebResponse>(hwr.BeginGetResponse, hwr.EndGetResponse)());
                    }

                    var buf = Encoding.UTF8.GetBytes(content);

                    // NB: You'd think that BeginGetResponse would never block,
                    // seeing as how it's asynchronous. You'd be wrong :-/
                    var ret = new AsyncSubject <WebResponse>();
                    Observable.Start(() =>
                    {
                        Observable.FromAsyncPattern <Stream>(hwr.BeginGetRequestStream, hwr.EndGetRequestStream)()
                        .SelectMany(x => x.WriteAsyncRx(buf, 0, buf.Length))
                        .SelectMany(_ => Observable.FromAsyncPattern <WebResponse>(hwr.BeginGetResponse, hwr.EndGetResponse)())
                        .Multicast(ret).Connect();
                    }, BlobCache.TaskpoolScheduler);

                    return(ret);
                });
            }

            return(request.Timeout(timeout ?? TimeSpan.FromSeconds(15), BlobCache.TaskpoolScheduler).Retry(retries));
        }
Exemplo n.º 2
0
        Task <IDisposable> acquireUpdateLock()
        {
            if (updateLock != null)
            {
                return(Task.FromResult(updateLock));
            }

            return(Task.Run(() => {
                var key = Utility.CalculateStreamSHA1(new MemoryStream(Encoding.UTF8.GetBytes(rootAppDirectory)));

                IDisposable theLock;
                try {
                    theLock = ModeDetector.InUnitTestRunner() ?
                              Disposable.Create(() => {}) : new SingleGlobalInstance(key, TimeSpan.FromMilliseconds(2000));
                } catch (TimeoutException) {
                    throw new TimeoutException("Couldn't acquire update lock, another instance may be running updates");
                }

                var ret = Disposable.Create(() => {
                    theLock.Dispose();
                    updateLock = null;
                });

                updateLock = ret;
                return ret;
            }));
        }
Exemplo n.º 3
0
 // Start is called before the first frame update
 void Start()
 {
     manager = GameObject.Find("Manager");
     Assert.IsNotNull(manager);
     playMode     = manager.GetComponent <PlayMode>();
     modeDetector = GameObject.Find("ModeDetector").GetComponent <ModeDetector>();
 }
Exemplo n.º 4
0
 public SingleGlobalInstance(string key, TimeSpan timeOut)
 {
     if (!ModeDetector.InUnitTestRunner())
     {
         string    path      = Path.Combine(Path.GetTempPath(), ".squirrel-lock-" + key);
         Stopwatch stopwatch = new Stopwatch();
         this.Log <SingleGlobalInstance>().Info("Grabbing lockfile with timeout of " + timeOut);
         stopwatch.Start();
         FileStream fh = null;
         while (stopwatch.Elapsed < timeOut)
         {
             try
             {
                 fh = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Delete);
                 byte[] buffer = new byte[] { 0xba, 0xad, 240, 13 };
                 fh.Write(buffer, 0, 4);
                 break;
             }
             catch (Exception exception)
             {
                 this.Log <SingleGlobalInstance>().WarnException("Failed to grab lockfile, will retry: " + path, exception);
                 Thread.Sleep(250);
             }
         }
         stopwatch.Stop();
         if (fh == null)
         {
             throw new Exception("Couldn't acquire lock, is another instance running");
         }
         this.handle = Disposable.Create(delegate {
             fh.Dispose();
             File.Delete(path);
         });
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ViewModelViewHost"/> class.
        /// </summary>
        public ViewModelViewHost()
        {
            if (ModeDetector.InUnitTestRunner())
            {
                this.ViewContractObservable = Observable.Never <string>();
                return;
            }

            this.ViewContractObservable = Observable.FromEvent <SizeChangedEventHandler, string?>(
                eventHandler =>
            {
                void Handler(object sender, SizeChangedEventArgs e) => eventHandler(null);
                return(Handler);
            },
                x => SizeChanged += x,
                x => SizeChanged -= x)
                                          .StartWith((string?)null)
                                          .DistinctUntilChanged();

            var contractChanged = updateViewModel.Select(_ => ViewContractObservable).Switch();

            var contract = new BehaviorSubject <string?>(null);

            contractChanged.Subscribe(contract);

            updateViewModel.Subscribe(_ => ResolveViewForViewModel(ViewModel, contract.Value));

            contractChanged
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x => viewContract = x);
        }
Exemplo n.º 6
0
        /// <inheritdoc/>
        public void Register(Action <Func <object>, Type> registerFunction)
        {
            if (registerFunction is null)
            {
                throw new ArgumentNullException(nameof(registerFunction));
            }

            registerFunction(() => new PlatformOperations(), typeof(IPlatformOperations));

            registerFunction(() => new CreatesWinformsCommandBinding(), typeof(ICreatesCommandBinding));
            registerFunction(() => new WinformsCreatesObservableForProperty(), typeof(ICreatesObservableForProperty));
            registerFunction(() => new ActivationForViewFetcher(), typeof(IActivationForViewFetcher));
            registerFunction(() => new PanelSetMethodBindingConverter(), typeof(ISetMethodBindingConverter));
            registerFunction(() => new TableContentSetMethodBindingConverter(), typeof(ISetMethodBindingConverter));
            registerFunction(() => new StringConverter(), typeof(IBindingTypeConverter));
            registerFunction(() => new SingleToStringTypeConverter(), typeof(IBindingTypeConverter));
            registerFunction(() => new DoubleToStringTypeConverter(), typeof(IBindingTypeConverter));
            registerFunction(() => new DecimalToStringTypeConverter(), typeof(IBindingTypeConverter));
            registerFunction(() => new ComponentModelTypeConverter(), typeof(IBindingTypeConverter));

            if (!ModeDetector.InUnitTestRunner())
            {
                WindowsFormsSynchronizationContext.AutoInstall = true;
                RxApp.MainThreadScheduler = new WaitForDispatcherScheduler(() => new SynchronizationContextScheduler(new WindowsFormsSynchronizationContext()));
            }
        }
Exemplo n.º 7
0
        /// <inheritdoc/>
        public void Register(Action <Func <object>, Type> registerFunction)
        {
            if (registerFunction == null)
            {
                throw new ArgumentNullException(nameof(registerFunction));
            }

            registerFunction(() => new PlatformOperations(), typeof(IPlatformOperations));

            registerFunction(() => new ActivationForViewFetcher(), typeof(IActivationForViewFetcher));
            registerFunction(() => new DependencyObjectObservableForProperty(), typeof(ICreatesObservableForProperty));
            registerFunction(() => new BooleanToVisibilityTypeConverter(), typeof(IBindingTypeConverter));
            registerFunction(() => new AutoDataTemplateBindingHook(), typeof(IPropertyBindingHook));
            registerFunction(() => new ComponentModelTypeConverter(), typeof(IBindingTypeConverter));

            RxApp.TaskpoolScheduler = TaskPoolScheduler.Default;

            if (!ModeDetector.InUnitTestRunner())
            {
                // NB: On .NET Core, trying to touch DispatcherScheduler blows up :cry:
                RxApp.MainThreadScheduler = new WaitForDispatcherScheduler(() => DispatcherScheduler.Current);
            }

            RxApp.SuppressViewCommandBindingMessage = true;
        }
Exemplo n.º 8
0
        public SingleGlobalInstance(string key, int timeOut)
        {
            if (ModeDetector.InUnitTestRunner())
            {
                return;
            }

            scheduler = new EventLoopScheduler();

            initMutex(key);
            try {
                if (timeOut <= 0)
                {
                    HasHandle = scheduler.Enqueue(() => mutex.WaitOne(Timeout.Infinite, false)).Result;
                }
                else
                {
                    HasHandle = scheduler.Enqueue(() => mutex.WaitOne(timeOut, false)).Result;
                }

                if (HasHandle == false)
                {
                    throw new TimeoutException("Timeout waiting for exclusive access on SingleInstance");
                }
            } catch (AbandonedMutexException) {
                HasHandle = true;
            }
        }
Exemplo n.º 9
0
        public ViewModelViewHost()
        {
#if WINRT
            this.DefaultStyleKey = typeof(ViewModelViewHost);
#endif

            // NB: InUnitTestRunner also returns true in Design Mode
            if (ModeDetector.InUnitTestRunner())
            {
                ViewContractObservable = Observable.Never <string>();
                return;
            }

            var vmAndContract = Observable.CombineLatest(
                this.WhenAnyValue(x => x.ViewModel),
                this.WhenAnyObservable(x => x.ViewContractObservable),
                (vm, contract) => new { ViewModel = vm, Contract = contract, });

            var           platform       = Locator.Current.GetService <IPlatformOperations>();
            Func <string> platformGetter = () => default(string);

            if (platform == null)
            {
                // NB: This used to be an error but WPF design mode can't read
                // good or do other stuff good.
                this.Log().Error("Couldn't find an IPlatformOperations. This should never happen, your dependency resolver is broken");
            }
            else
            {
                platformGetter = () => platform.GetOrientation();
            }

            ViewContractObservable = Observable.FromEventPattern <SizeChangedEventHandler, SizeChangedEventArgs>(x => SizeChanged += x, x => SizeChanged -= x)
                                     .Select(_ => platformGetter())
                                     .DistinctUntilChanged()
                                     .StartWith(platformGetter())
                                     .Select(x => x != null ? x.ToString() : default(string));

            this.WhenActivated(d => {
                d(vmAndContract.Subscribe(x => {
                    if (x.ViewModel == null)
                    {
                        Content = DefaultContent;
                        return;
                    }

                    var viewLocator = ViewLocator ?? ReactiveUI.ViewLocator.Current;
                    var view        = viewLocator.ResolveView(x.ViewModel, x.Contract) ?? viewLocator.ResolveView(x.ViewModel, null);

                    if (view == null)
                    {
                        throw new Exception(String.Format("Couldn't find view for '{0}'.", x.ViewModel));
                    }

                    view.ViewModel = x.ViewModel;
                    Content        = view;
                }));
            });
        }
Exemplo n.º 10
0
 /// <inheritdoc/>
 public void Register(Action <Func <object>, Type> registerFunction)
 {
     if (!ModeDetector.InUnitTestRunner())
     {
         RxApp.TaskpoolScheduler   = TaskPoolScheduler.Default;
         RxApp.MainThreadScheduler = DefaultScheduler.Instance;
     }
 }
Exemplo n.º 11
0
        static RxApp()
        {
#if !PORTABLE
            _TaskpoolScheduler = TaskPoolScheduler.Default;
#endif

            // Initialize this to false as most platforms do not support
            // range notification for INotifyCollectionChanged
#if WP8 || WINRT
            SupportsRangeNotifications = false;
#else
            SupportsRangeNotifications = true;
#endif

            Locator.RegisterResolverCallbackChanged(() => {
                if (Locator.CurrentMutable == null)
                {
                    return;
                }
                Locator.CurrentMutable.InitializeReactiveUI();
            });

            DefaultExceptionHandler = Observer.Create <Exception>(ex => {
                // NB: If you're seeing this, it means that an
                // ObservableAsPropertyHelper or the CanExecute of a
                // ReactiveCommand ended in an OnError. Instead of silently
                // breaking, ReactiveUI will halt here if a debugger is attached.
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                RxApp.MainThreadScheduler.Schedule(() => {
                    throw new Exception(
                        "An OnError occurred on an object (usually ObservableAsPropertyHelper) that would break a binding or command. To prevent this, Subscribe to the ThrownExceptions property of your objects",
                        ex);
                });
            });

            if (ModeDetector.InUnitTestRunner())
            {
                LogHost.Default.Warn("*** Detected Unit Test Runner, setting MainThreadScheduler to CurrentThread ***");
                LogHost.Default.Warn("If we are not actually in a test runner, please file a bug\n");
                _MainThreadScheduler = CurrentThreadScheduler.Instance;
                return;
            }
            else
            {
                LogHost.Default.Info("Initializing to normal mode");
            }

            if (_MainThreadScheduler == null)
            {
                _MainThreadScheduler = DefaultScheduler.Instance;
            }

            SuspensionHost = new SuspensionHost();
        }
Exemplo n.º 12
0
        /// <summary>
        /// Initializes static members of the <see cref="RxApp"/> class.
        /// </summary>
        /// <exception cref="UnhandledErrorException">Default exception when we have unhandled exception in RxUI.</exception>
        static RxApp()
        {
#if !PORTABLE
            _taskpoolScheduler = TaskPoolScheduler.Default;
#endif

            Locator.RegisterResolverCallbackChanged(() =>
            {
                if (Locator.CurrentMutable == null)
                {
                    return;
                }

                Locator.CurrentMutable.InitializeReactiveUI();
            });

            DefaultExceptionHandler = Observer.Create <Exception>(ex =>
            {
                // NB: If you're seeing this, it means that an
                // ObservableAsPropertyHelper or the CanExecute of a
                // ReactiveCommand ended in an OnError. Instead of silently
                // breaking, ReactiveUI will halt here if a debugger is attached.
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                MainThreadScheduler.Schedule(() =>
                {
#pragma warning disable CA1065 // Avoid exceptions in constructors -- In scheduler.
                    throw new UnhandledErrorException(
                        "An object implementing IHandleObservableErrors (often a ReactiveCommand or ObservableAsPropertyHelper) has errored, thereby breaking its observable pipeline. To prevent this, ensure the pipeline does not error, or Subscribe to the ThrownExceptions property of the object in question to handle the erroneous case.",
                        ex);
#pragma warning restore CA1065
                });
            });

            if (ModeDetector.InUnitTestRunner())
            {
                LogHost.Default.Warn("*** Detected Unit Test Runner, setting MainThreadScheduler to CurrentThread ***");
                LogHost.Default.Warn("If we are not actually in a test runner, please file a bug\n\n");
                LogHost.Default.Warn("ReactiveUI acts differently under a test runner, see the docs\n");
                LogHost.Default.Warn("for more info about what to expect");

                _mainThreadScheduler = CurrentThreadScheduler.Instance;
                return;
            }

            LogHost.Default.Info("Initializing to normal mode");

            if (_mainThreadScheduler == null)
            {
                _mainThreadScheduler = DefaultScheduler.Instance;
            }

            SuspensionHost = new SuspensionHost();
        }
Exemplo n.º 13
0
    // Start is called before the first frame update
    void Start()
    {
        blocks       = GameObject.Find("Blocks");
        specials     = GameObject.Find("Specials");
        camera       = GameObject.Find("Camera");
        modeDetector = GameObject.Find("ModeDetector").GetComponent <ModeDetector>();

        rot = 0;
    }
Exemplo n.º 14
0
        public ViewModelViewHost()
        {
            // NB: InUnitTestRunner also returns true in Design Mode
            if (ModeDetector.InUnitTestRunner())
            {
                ViewContractObservable = Observable.Never <string>();
                return;
            }

            var vmAndContract = Observable.CombineLatest(
                this.WhenAnyValue(x => x.ViewModel),
                this.WhenAnyObservable(x => x.ViewContractObservable),
                (vm, contract) => new { ViewModel = vm, Contract = contract, });

            var platform = Locator.Current.GetService <IPlatformOperations>();

            if (platform == null)
            {
                throw new Exception("Couldn't find an IPlatformOperations. This should never happen, your dependency resolver is broken");
            }

            ViewContractObservable = Observable.FromEventPattern <EventHandler, EventArgs>(x => SizeChanged += x, x => SizeChanged -= x)
                                     .Select(_ => platform.GetOrientation())
                                     .DistinctUntilChanged()
                                     .StartWith(platform.GetOrientation())
                                     .Select(x => x != null ? x.ToString() : default(string));

            (this as IViewFor).WhenActivated(() => {
                return(new[] { vmAndContract.Subscribe(x => {
                        if (x.ViewModel == null)
                        {
                            this.Content = this.DefaultContent;
                            return;
                        }

                        var viewLocator = ViewLocator ?? ReactiveUI.ViewLocator.Current;
                        var view = viewLocator.ResolveView(x.ViewModel, x.Contract) ?? viewLocator.ResolveView(x.ViewModel, null);

                        if (view == null)
                        {
                            throw new Exception(String.Format("Couldn't find view for '{0}'.", x.ViewModel));
                        }

                        var castView = view as View;

                        if (castView == null)
                        {
                            throw new Exception(String.Format("View '{0}' is not a subclass of '{1}'.", view.GetType().FullName, typeof(View).FullName));
                        }

                        view.ViewModel = x.ViewModel;

                        this.Content = castView;
                    }) });
            });
        }
            public void CreateShortcutsForExecutable(string exeName, ShortcutLocation locations, bool updateOnly)
            {
                var releases    = Utility.LoadLocalReleases(Utility.LocalReleaseFileForAppDir(rootAppDirectory));
                var thisRelease = Utility.FindCurrentVersion(releases);

                var zf = new ZipPackage(Path.Combine(
                                            Utility.PackageDirectoryForAppDir(rootAppDirectory),
                                            thisRelease.Filename));

                var exePath     = Path.Combine(Utility.AppDirForRelease(rootAppDirectory, thisRelease), exeName);
                var fileVerInfo = FileVersionInfo.GetVersionInfo(exePath);

                foreach (var f in (ShortcutLocation[])Enum.GetValues(typeof(ShortcutLocation)))
                {
                    if (!locations.HasFlag(f))
                    {
                        continue;
                    }

                    var file       = linkTargetForVersionInfo(f, zf, fileVerInfo);
                    var fileExists = File.Exists(file);

                    // NB: If we've already installed the app, but the shortcut
                    // is no longer there, we have to assume that the user didn't
                    // want it there and explicitly deleted it, so we shouldn't
                    // annoy them by recreating it.
                    if (!fileExists && updateOnly)
                    {
                        this.Log().Warn("Wanted to update shortcut {0} but it appears user deleted it", file);
                        continue;
                    }

                    this.Log().Info("Creating shortcut for {0} => {1}", exeName, file);

                    this.ErrorIfThrows(() => {
                        if (fileExists)
                        {
                            File.Delete(file);
                        }

                        var sl = new ShellLink {
                            Target           = exePath,
                            IconPath         = exePath,
                            IconIndex        = 0,
                            WorkingDirectory = Path.GetDirectoryName(exePath),
                            Description      = zf.Description,
                        };

                        this.Log().Info("About to save shortcut: {0}", file);
                        if (ModeDetector.InUnitTestRunner() == false)
                        {
                            sl.Save(file);
                        }
                    }, "Can't write shortcut: " + file);
                }
            }
Exemplo n.º 16
0
 public static IDisposable Set()
 {
     PlatformModeDetector.OverrideModeDetector(Instance);
     ModeDetector.OverrideModeDetector(Instance);
     return(Disposable.Create(() =>
     {
         PlatformModeDetector.OverrideModeDetector(new DefaultPlatformModeDetector());
         ModeDetector.OverrideModeDetector(new DefaultModeDetector());
     }));
 }
Exemplo n.º 17
0
        static Registrations()
        {
            // override Splat's mode detector with our own. This allows us to by-pass the performance hit that
            // we would incur using the default Splat implementation
            ModeDetector.OverrideModeDetector(CustomModeDetector.Instance);

            // seems stupid, but this forces the RxApp static constructor to run
            // without this, our registrations below might be overwritten by RxUI when it eventually initializes
            RxApp.DefaultExceptionHandler = RxApp.DefaultExceptionHandler;
        }
Exemplo n.º 18
0
    // Start is called before the first frame update
    void Start()
    {
        camera       = GameObject.Find("Camera");
        blocks       = GameObject.Find("Blocks");
        modeDetector = GameObject.Find("ModeDetector").GetComponent <ModeDetector>();

        DisablePlayer();

        mb = gameObject.GetComponent <ModifyBlock>();
    }
Exemplo n.º 19
0
 public void Dispose()
 {
     if (!ModeDetector.InUnitTestRunner())
     {
         IDisposable disposable = Interlocked.Exchange <IDisposable>(ref this.handle, null);
         if (disposable != null)
         {
             disposable.Dispose();
         }
     }
 }
Exemplo n.º 20
0
        public void Dispose()
        {
            if (ModeDetector.InUnitTestRunner())
            {
                return;
            }

            var disp = Interlocked.Exchange(ref handle, null);

            disp?.Dispose();
        }
        /// <summary>
        /// Call this method as early as possible in app startup. This method
        /// will dispatch to your methods to set up your app. Depending on the
        /// parameter, your app will exit after this method is called, which
        /// is required by Squirrel. UpdateManager has methods to help you to
        /// do this, such as CreateShortcutForThisExe.
        /// </summary>
        /// <param name="onInitialInstall">Called when your app is initially
        /// installed. Set up app shortcuts here as well as file associations.
        /// </param>
        /// <param name="onAppUpdate">Called when your app is updated to a new
        /// version.</param>
        /// <param name="onAppObsoleted">Called when your app is no longer the
        /// latest version (i.e. they have installed a new version and your app
        /// is now the old version)</param>
        /// <param name="onAppUninstall">Called when your app is uninstalled
        /// via Programs and Features. Remove all of the things that you created
        /// in onInitialInstall.</param>
        /// <param name="onFirstRun">Called the first time an app is run after
        /// being installed. Your application will **not** exit after this is
        /// dispatched, you should use this as a hint (i.e. show a 'Welcome'
        /// screen, etc etc.</param>
        /// <param name="arguments">Use in a unit-test runner to mock the
        /// arguments. In your app, leave this as null.</param>
        public static void HandleEvents(
            Action <Version> onInitialInstall = null,
            Action <Version> onAppUpdate      = null,
            Action <Version> onAppObsoleted   = null,
            Action <Version> onAppUninstall   = null,
            Action onFirstRun  = null,
            string[] arguments = null)
        {
            Action <Version> defaultBlock = (v => { });
            var args = arguments ?? Environment.GetCommandLineArgs().Skip(1).ToArray();

            if (args.Length == 0)
            {
                return;
            }

            var lookup = new[] {
                new { Key = "--squirrel-install", Value = onInitialInstall ?? defaultBlock },
                new { Key = "--squirrel-updated", Value = onAppUpdate ?? defaultBlock },
                new { Key = "--squirrel-obsolete", Value = onAppObsoleted ?? defaultBlock },
                new { Key = "--squirrel-uninstall", Value = onAppUninstall ?? defaultBlock },
            }.ToDictionary(k => k.Key, v => v.Value);

            if (args[0] == "--squirrel-firstrun")
            {
                (onFirstRun ?? (() => {}))();
                return;
            }

            if (args.Length != 2)
            {
                return;
            }

            if (!lookup.ContainsKey(args[0]))
            {
                return;
            }
            var version = args[1].ToSemanticVersion().Version;

            try {
                lookup[args[0]](version);
                if (!ModeDetector.InUnitTestRunner())
                {
                    Environment.Exit(0);
                }
            } catch (Exception ex) {
                LogHost.Default.ErrorException("Failed to handle Squirrel events", ex);
                if (!ModeDetector.InUnitTestRunner())
                {
                    Environment.Exit(-1);
                }
            }
        }
        public void Setup()
        {
            ModeDetector.InUnitTestRunner();

            _taskPoolSchedulerMock = new Mock <IScheduler>();
            _mainSchedulerMock     = new Mock <IScheduler>();
            _screenMock            = new Mock <IScreen>();

            Locator.CurrentMutable.RegisterConstant(_taskPoolSchedulerMock.Object, "TaskPoolScheduler");
            Locator.CurrentMutable.RegisterConstant(_mainSchedulerMock.Object, "MainScheduler");
            Locator.CurrentMutable.RegisterConstant(_screenMock.Object);
        }
Exemplo n.º 23
0
        public static void TrackActivation <T>(T element, CompositeDisposable compositeDisposable)
        {
            if (ModeDetector.InUnitTestRunner())
            {
                return;
            }

            var tracker = GetTracker(element);

            tracker.DisposeWith(compositeDisposable);
            tracker.Activate();
        }
Exemplo n.º 24
0
    // Start is called before the first frame update
    void Start()
    {
        serialization = GetComponent <Serialization>();
        modeDetector  = GameObject.Find("ModeDetector").GetComponent <ModeDetector>();



        serialization.LoadMap();
        modeDetector.InGamePlayMode();

        CountCollectibles();
    }
 public static void Register(bool isDebugMode)
 {
     if (isDebugMode)
     {
         Locator.CurrentMutable.RegisterConstant(new DebugLogger(), typeof(ILogger));
         RxApp.DefaultExceptionHandler = new NavigationExceptionHandler();
     }
     else
     {
         Locator.CurrentMutable.RegisterConstant(new AppCenterLogger(), typeof(ILogger));
         ModeDetector.OverrideModeDetector(new SplatModeDetector());
     }
 }
    /// <inheritdoc/>
    public void Register(Action <Func <object>, Type> registerFunction)
    {
        if (registerFunction is null)
        {
            throw new ArgumentNullException(nameof(registerFunction));
        }

        if (!ModeDetector.InUnitTestRunner())
        {
            RxApp.TaskpoolScheduler   = TaskPoolScheduler.Default;
            RxApp.MainThreadScheduler = DefaultScheduler.Instance;
        }
    }
Exemplo n.º 27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ViewModelViewHost"/> class.
        /// </summary>
        public ViewModelViewHost()
        {
            // NB: InUnitTestRunner also returns true in Design Mode
            if (ModeDetector.InUnitTestRunner())
            {
                ViewContractObservable = Observable <string> .Never;
                return;
            }

            ViewContractObservable = Observable <string> .Default;

            var vmAndContract = Observable.CombineLatest(
                this.WhenAnyValue(x => x.ViewModel),
                this.WhenAnyObservable(x => x.ViewContractObservable),
                (vm, contract) => new { ViewModel = vm, Contract = contract, });

            this.WhenActivated(() =>
            {
                return(new[]
                {
                    vmAndContract.Subscribe(x =>
                    {
                        _viewContract = x.Contract;

                        if (x.ViewModel == null)
                        {
                            Content = DefaultContent;
                            return;
                        }

                        var viewLocator = ViewLocator ?? ReactiveUI.ViewLocator.Current;
                        var view = viewLocator.ResolveView(x.ViewModel, x.Contract) ?? viewLocator.ResolveView(x.ViewModel, null);

                        if (view == null)
                        {
                            throw new Exception(string.Format("Couldn't find view for '{0}'.", x.ViewModel));
                        }

                        var castView = view as View;

                        if (castView == null)
                        {
                            throw new Exception(string.Format("View '{0}' is not a subclass of '{1}'.", view.GetType().FullName, typeof(View).FullName));
                        }

                        view.ViewModel = x.ViewModel;
                        Content = castView;
                    })
                });
            });
        }
Exemplo n.º 28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RoutedViewHost"/> class.
        /// </summary>
        public RoutedViewHost()
        {
#if NETFX_CORE
            DefaultStyleKey = typeof(RoutedViewHost);
#endif
            HorizontalContentAlignment = HorizontalAlignment.Stretch;
            VerticalContentAlignment   = VerticalAlignment.Stretch;

            var            platform       = Locator.Current.GetService <IPlatformOperations>();
            Func <string?> platformGetter = () => default;

            if (platform is null)
            {
                // NB: This used to be an error but WPF design mode can't read
                // good or do other stuff good.
                this.Log().Error("Couldn't find an IPlatformOperations implementation. Please make sure you have installed the latest version of the ReactiveUI packages for your platform. See https://reactiveui.net/docs/getting-started/installation for guidance.");
            }
            else
            {
                platformGetter = () => platform.GetOrientation();
            }

            ViewContractObservable = ModeDetector.InUnitTestRunner()
                ? Observable <string> .Never
                : Observable.FromEvent <SizeChangedEventHandler, string?>(
                eventHandler =>
            {
                void Handler(object sender, SizeChangedEventArgs e) => eventHandler(platformGetter());
                return(Handler);
            },
                x => SizeChanged += x,
                x => SizeChanged -= x)
                                     .StartWith(platformGetter())
                                     .DistinctUntilChanged();

            IRoutableViewModel?currentViewModel = null;
            var vmAndContract = this.WhenAnyObservable(x => x.Router.CurrentViewModel).Do(x => currentViewModel = x).StartWith(currentViewModel).CombineLatest(
                this.WhenAnyObservable(x => x.ViewContractObservable).Do(x => _viewContract = x).StartWith(ViewContract),
                (viewModel, contract) => (viewModel, contract));

            this.WhenActivated(d =>
            {
                // NB: The DistinctUntilChanged is useful because most views in
                // WinRT will end up getting here twice - once for configuring
                // the RoutedViewHost's ViewModel, and once on load via SizeChanged
                d(vmAndContract.DistinctUntilChanged <(IRoutableViewModel?viewModel, string?contract)>().Subscribe(
                      ResolveViewForViewModel,
                      ex => RxApp.DefaultExceptionHandler.OnNext(ex)));
            });
        }
Exemplo n.º 29
0
        /// <inheritdoc/>
        public void Register(Action <Func <object>, Type> registerFunction)
        {
            registerFunction(() => new PlatformOperations(), typeof(IPlatformOperations));

            registerFunction(() => new CreatesWinformsCommandBinding(), typeof(ICreatesCommandBinding));
            registerFunction(() => new WinformsCreatesObservableForProperty(), typeof(ICreatesObservableForProperty));
            registerFunction(() => new ActivationForViewFetcher(), typeof(IActivationForViewFetcher));

            if (!ModeDetector.InUnitTestRunner())
            {
                WindowsFormsSynchronizationContext.AutoInstall = true;
                RxApp.MainThreadScheduler = new WaitForDispatcherScheduler(() => new SynchronizationContextScheduler(new WindowsFormsSynchronizationContext()));
            }
        }
Exemplo n.º 30
0
        public PersistentBlobCache(
            string cacheDirectory = null,
            IFilesystemProvider filesystemProvider = null,
            IScheduler scheduler = null,
            Action <AsyncSubject <byte[]> > invalidateCallback = null)
        {
            BlobCache.EnsureInitialized();

            this.filesystem = filesystemProvider ?? Locator.Current.GetService <IFilesystemProvider>();

            if (this.filesystem == null)
            {
                throw new Exception("No IFilesystemProvider available. This should never happen, your DependencyResolver is broken");
            }

            this.CacheDirectory = cacheDirectory ?? filesystem.GetDefaultRoamingCacheDirectory();
            this.Scheduler      = scheduler ?? BlobCache.TaskpoolScheduler;

            // Here, we're not actually caching the requests directly (i.e. as
            // byte[]s), but as the "replayed result of the request", in the
            // AsyncSubject - this makes the code infinitely simpler because
            // we don't have to keep a separate list of "in-flight reads" vs
            // "already completed and cached reads"
            memoizedRequests = new MemoizingMRUCache <string, AsyncSubject <byte[]> >(
                (x, c) => FetchOrWriteBlobFromDisk(x, c, false), 20, invalidateCallback);


            var cacheIndex = FetchOrWriteBlobFromDisk(BlobCacheIndexKey, null, true)
                             .Catch(Observable.Return(new byte[0]))
                             .Select(x => Encoding.UTF8.GetString(x, 0, x.Length).Split('\n')
                                     .SelectMany(ParseCacheIndexEntry)
                                     .ToDictionary(y => y.Key, y => y.Value))
                             .Select(x => new ConcurrentDictionary <string, CacheIndexEntry>(x));

            cacheIndex.Subscribe(x => CacheIndex = x);

            flushThreadSubscription = Disposable.Empty;

            if (!ModeDetector.InUnitTestRunner())
            {
                flushThreadSubscription = actionTaken
                                          .Where(_ => CacheIndex != null)
                                          .Throttle(TimeSpan.FromSeconds(30), Scheduler)
                                          .SelectMany(_ => FlushCacheIndex(true))
                                          .Subscribe(_ => this.Log().Debug("Flushing cache"));
            }

            this.Log().Info("{0} entries in blob cache index", CacheIndex.Count);
        }