private static void RegisterViewModels(IMutableDependencyResolver services, IReadonlyDependencyResolver resolver)
 {
     services.Register(() => new MainWindowViewModel(
                           resolver.GetService <IPreferencesService>(),
                           resolver.GetService <INotesService>()
                           ));
 }
Exemple #2
0
 private static void RegisterFileSystemWatcherServices(IMutableDependencyResolver services, IReadonlyDependencyResolver resolver)
 {
     services.RegisterLazySingleton <IFileSystemWatcherFactory>(() => new FileSystemWatcherFactory(
                                                                    resolver.GetService <IPathService>(),
                                                                    resolver.GetService <FileSystemWatcherConfiguration>()
                                                                    ));
 }
Exemple #3
0
        /// <inheritdoc />
        public void Register(IMutableDependencyResolver resolver, IReadonlyDependencyResolver readonlyDependencyResolver)
        {
            if (resolver is null)
            {
                throw new ArgumentNullException(nameof(resolver));
            }

            resolver.Register(
                () => new JsonSerializerSettings
            {
                ObjectCreationHandling = ObjectCreationHandling.Replace,
                ReferenceLoopHandling  = ReferenceLoopHandling.Ignore,
                TypeNameHandling       = TypeNameHandling.All,
            },
                typeof(JsonSerializerSettings),
                null);

            var akavacheDriver = new AkavacheDriver();

            resolver.Register(() => akavacheDriver, typeof(ISuspensionDriver), null);

            // NB: These correspond to the hacks in Akavache.Http's registrations
            resolver.Register(
                () => readonlyDependencyResolver.GetService <ISuspensionHost>().ShouldPersistState,
                typeof(IObservable <IDisposable>),
                "ShouldPersistState");

            resolver.Register(
                () => readonlyDependencyResolver.GetService <ISuspensionHost>().IsUnpausing,
                typeof(IObservable <Unit>),
                "IsUnpausing");

            resolver.Register(() => RxApp.TaskpoolScheduler, typeof(IScheduler), "Taskpool");
        }
Exemple #4
0
        /// <summary>
        /// The run application.
        /// </summary>
        private static void RunApplication()
        {
            app = new App();
            try
            {
                var mainWindow = container.GetService <ShellView>();
                app.MainWindow          = mainWindow;
                app.MainWindow.Closing += ShellViewClosing;
                app.InitializeComponent();
                Startup();
#if DEBUG
                app.MainWindow.Show();
#endif
                app.Run();
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    "Maalasef ölümcül bir hata ile karşılaştık ayrıntılı bilgi kurulum klasöründe bulunan log.txt dosyasına bakınız!",
                    "Hata!",
                    MessageBoxButton.OK);
                container.GetService <ILogger>()
                .Fatal(ex, "Ölümcül hata!!");
            }
        }
Exemple #5
0
        public Database(string path, IReadonlyDependencyResolver dr)
        {
            scheduler   = dr.GetService <IScheduler>() ?? RxApp.MainThreadScheduler;
            authService = new Lazy <IAuthService>(() => dr.GetService <IAuthService>());
            logger      = this.GetLogger(dr);

            // we use new BsonMapper() instead of BsonMapper.Global because in tests the same mapper cannot .Ignore the same field twice
            mapper = new BsonMapper();
            mapper.Entity <User>();
            mapper.Entity <Log>().DbRef(l => l.User);
            mapper.EmptyStringToNull = false;

            // We set mode to exclusive because the default value is shared and mac os doesn't support shared mode
            // We need this because unit tests run on mac os build machine and we don't need to support access to the same db file from several processes
            var connectionString = new ConnectionString(path)
            {
                Mode = FileMode.Exclusive
            };

            db = new LiteDatabase(connectionString, mapper);

            collections = new Dictionary <Type, object>
            {
                { typeof(User), db.GetCollection <User>() },
                { typeof(Log), db.GetCollection <Log>() },
            };
        }
Exemple #6
0
 public LoggingService(IReadonlyDependencyResolver dr)
 {
     crashlyticsService = dr.GetService <ICrashlyticsService>();
     db          = new Lazy <IDatabase>(() => dr.GetService <IDatabase>());
     scheduler   = dr.GetService <IScheduler>() ?? RxApp.MainThreadScheduler;
     AuthService = new Lazy <IAuthService>(() => dr.GetService <IAuthService>());
     logger      = GetLogger <LoggingService>();
 }
Exemple #7
0
        public RecoverPasswordViewModel(IReadonlyDependencyResolver dr) : base(dr)
        {
            this.dr        = dr;
            authService    = dr.GetService <IAuthService>();
            LoginCommand   = ReactiveCommand.Create(Login).LogInvocation(nameof(LoginCommand), Logger, dr);
            RecoverCommand = ReactiveCommand.CreateFromTask(Recover, CanRecover()).LogInvocation(nameof(RecoverCommand), Logger, dr);

            var timeScheduler = dr.GetService <IScheduler>() ?? DefaultScheduler.Instance;

            this.LogPropertyChangeThrottling(vm => vm.Email, nameof(Email), scheduler: timeScheduler);
        }
        private static void RegisterServices(IMutableDependencyResolver services, IReadonlyDependencyResolver resolver)
        {
            services.RegisterLazySingleton <IPreferencesService>(() => new PreferencesService());
            services.RegisterLazySingleton <INotesMetadataService>(() => new NotesMetadataService());

            services.RegisterLazySingleton <INotesRepository>(() => new FileSystemRepository(
                                                                  resolver.GetService <IPreferencesService>()
                                                                  ));

            services.RegisterLazySingleton <INotesService>(() => new NotesService(
                                                               resolver.GetService <INotesMetadataService>(),
                                                               resolver.GetService <INotesRepository>()));
        }
        private AuthToken userAuthToken;    // The token is used to perform requests on behalf of user

        public AuthService(IReadonlyDependencyResolver dr)
        {
            // IMPORTANT: when you switch from debug to release or back clear SecureStorage!
            // SecureStorage.RemoveAll();

            logger = this.GetLogger(dr);

            settingsService = dr.GetService <ISettingsService>();
            restClient      = new RestClient(settingsService.ServiceAddress);
            db        = dr.GetService <IDatabase>();
            scheduler = dr.GetService <IScheduler>() ?? RxApp.MainThreadScheduler;

            // we should get current user synchronously because on it depends first view in bootstrapper (i's main page or register page)
            CurrentUser = db.GetCurrentUser();
        }
Exemple #10
0
        private static void RegisterPlatformSpecificServices(IMutableDependencyResolver services, IReadonlyDependencyResolver resolver)
        {
            var platformService = resolver.GetService <IPlatformService>();
            var platform        = platformService.GetPlatform();

            switch (platform)
            {
            case Platform.Linux:
                RegisterLinuxServices(services, resolver);
                break;

            case Platform.MacOs:
                RegisterMacServices(services, resolver);
                break;

            case Platform.Windows:
                RegisterWindowsServices(services, resolver);
                break;

            case Platform.Unknown:
                throw new InvalidOperationException("Unsupported platform");

            default:
                throw new ArgumentOutOfRangeException(nameof(platform));
            }
        }
Exemple #11
0
 protected PageViewModel(IReadonlyDependencyResolver dr)
 {
     Logger          = this.GetLogger(dr, GetType());
     Activator       = new ViewModelActivator();
     NavigationState = dr.GetService <INavigationState>();
     NavigateBack    = ReactiveCommand.Create(NavigationState.NavigateBack).LogInvocation(nameof(NavigationState.NavigateBack), Logger, dr);
 }
        private async Task Create()
        {
            Error = " ";

            var authService = dr.GetService <IAuthService>();
            var registered  = await authService.Register(Name, Email, Password);

            if (!registered)
            {
                Logger.Value.Error("Registration has failed");
                Error = @"Something went wrong. Please try again.";
                return;
            }

            var authenticated = await authService.Login(Email, Password);

            if (!authenticated)
            {
                Logger.Value.Error("Login has failed. Redirecting to login page");
                // ki.
                NavigationState.NavigateAndReset(new RecoverPasswordViewModel(dr));
                return;
            }

            NavigationState.NavigateAndReset(new WebViewModel("test_page.htm", dr));
        }
Exemple #13
0
 private static void RegisterDataAccess(IMutableDependencyResolver services, IReadonlyDependencyResolver resolver)
 {
     services.RegisterLazySingleton <IUnitOfWorkFactory>(() => new LiteDbUnitOfWorkFactory(
                                                             resolver.GetService <DatabaseConfiguration>()
                                                             ));
     services.RegisterLazySingleton <IClipboardService>(() => new ClipboardService());
     services.RegisterLazySingleton <IMainWindowProvider>(() => new MainWindowProvider());
 }
        /// <summary>
        /// Gets an instance of the given <typeparamref name="T"/>. Must return <c>null</c>
        /// if the service is not available (must not throw).
        /// </summary>
        /// <typeparam name="T">The type for the object we want to retrieve.</typeparam>
        /// <param name="resolver">The resolver we are getting the service from.</param>
        /// <param name="contract">A optional value which will retrieve only a object registered with the same contract.</param>
        /// <returns>The requested object, if found; <c>null</c> otherwise.</returns>
        public static T GetService <T>(this IReadonlyDependencyResolver resolver, string contract = null)
        {
            if (resolver is null)
            {
                throw new ArgumentNullException(nameof(resolver));
            }

            return((T)resolver.GetService(typeof(T), contract));
        }
Exemple #15
0
        public SettingsViewModel(IReadonlyDependencyResolver dr) : base(dr)
        {
            this.dr     = dr;
            authService = dr.GetService <IAuthService>();

            Email = authService.CurrentUser.Email;

            LogoutCommand = ReactiveCommand.CreateFromTask(Logout).LogInvocation(nameof(LogoutCommand), Logger, dr);
        }
        /// <summary>
        /// Gets the navigation view.
        /// </summary>
        /// <param name="dependencyResolver">The dependency resolver.</param>
        /// <param name="contract">The contract.</param>
        /// <returns>The navigation view.</returns>
        public static NavigationView GetNavigationView(this IReadonlyDependencyResolver dependencyResolver, string contract = null)
        {
            if (dependencyResolver is null)
            {
                throw new ArgumentNullException(nameof(dependencyResolver));
            }

            return(dependencyResolver.GetService <IView>(contract ?? NavigationView) as NavigationView);
        }
 public EmailService(IReadonlyDependencyResolver dr)
 {
     logger          = this.GetLogger(dr);
     settingsService = new Lazy <ISettingsService>(() => dr.GetService <ISettingsService>());
     restClient      = new Lazy <IRestClient>(() => new RestClient("https://api.mailgun.net/v3")
     {
         Authenticator = new HttpBasicAuthenticator("api", settingsService.Value.MailgunApiKey)
     });
 }
Exemple #18
0
        public static void RegisterServices(IMutableDependencyResolver services, IReadonlyDependencyResolver resolver, IConfiguration config)
        {
            var appSettings = config.Get <AppSettings>() ?? new AppSettings();

            // Splat.Locator.CurrentMutable.Register<EmailService>(() => new EmailExchangeService());

            services.Register <AppSettings>(() => config.Get <AppSettings>());
            services.Register <AppSettingsWriter>(() => new AppSettingsWriter());
            services.Register <IEmailService>(() => new EmailService());
            services.Register <IProcessWritterService>(() => new ProcessWritterService()
            {
                DelayToShowWindow = appSettings?.DelayToShowVpnClient ?? AppSettings.DEFAULT_DelayToShowVpnClient
            });

            services.RegisterLazySingleton <FortiConnector>(() => {
                var emailService          = resolver.GetService <IEmailService>();
                var processWritterService = resolver.GetService <IProcessWritterService>();
                var fortiConnector        = new FortiConnector(emailService, processWritterService, appSettings.EmailAccount?.MarkVpnEmailAsRead ?? false);
                fortiConnector.LoginPasswordFocusSequence     = appSettings?.FortiClient?.LoginPasswordFocusSequence;
                fortiConnector.LoginVerificationFocusSequence = appSettings?.FortiClient?.LoginVerificationFocusSequence;
                if (!string.IsNullOrWhiteSpace(appSettings?.FortiClient?.ExeFullPath))
                {
                    fortiConnector.FortiClientExeFullPath = appSettings.FortiClient.ExeFullPath;
                }
                if (!string.IsNullOrWhiteSpace(appSettings?.FortiClient?.ProcessName))
                {
                    fortiConnector.FortiClientProcessName = appSettings.FortiClient.ProcessName;
                }
                if (appSettings?.DelayToSpawnFortiClientProcess != null)
                {
                    fortiConnector.DelayToSpawnFortiClientProcess = appSettings.DelayToSpawnFortiClientProcess.Value;
                }
                if (appSettings?.DelayToFetchVpnCodeEmail != null)
                {
                    fortiConnector.DelayToFetchVpnCodeEmail = appSettings.DelayToFetchVpnCodeEmail.Value;
                }
                return(fortiConnector);
            });

            services.RegisterLazySingleton <FortiConnectFormViewModel>(() => {
                var fortiConnectFormViewModel = new FortiConnectFormViewModel();
                return(fortiConnectFormViewModel);
            });
        }
        public static TService GetRequiredService <TService>(this IReadonlyDependencyResolver resolver)
        {
            var service = resolver.GetService <TService>();

            if (service == null)
            {
                throw new InvalidOperationException($"Failed to resolve object of type {typeof(TService)}");
            }
            return(service);
        }
Exemple #20
0
        public static object GetRequiredService(this IReadonlyDependencyResolver resolver, Type type)
        {
            var service = resolver.GetService(type);

            if (service is null)
            {
                throw new InvalidOperationException($"Failed to resolve object of type {type}");
            }

            return(service);
        }
Exemple #21
0
        public static TService GetRequiredService <TService>(this IReadonlyDependencyResolver resolver)
        {
            var service = resolver.GetService <TService>();

            if (service is null)                                                                             // Splat is not able to resolve type for us
            {
                throw new InvalidOperationException($"Failed to resolve object of type {typeof(TService)}"); // throw error with detailed description
            }

            return(service); // return instance if not null
        }
        /// <summary>Initializes a new instance of the <see cref="AppBootstrapper"/> class.</summary>
        /// <param name="resolver">The dependency injection resolver which will resolve the programs dependencies.</param>
        /// <param name="dependencyResolver">The dependency injection resolver which will allow registration of new dependencies.</param>
        /// <param name="testRouter">The router.</param>
        public AppBootstrapper(IReadonlyDependencyResolver resolver = null, IMutableDependencyResolver dependencyResolver = null, RoutingState testRouter = null)
        {
            Router             = testRouter ?? new RoutingState();
            resolver           = resolver ?? Locator.Current;
            dependencyResolver = dependencyResolver ?? Locator.CurrentMutable;

            RegisterParts(dependencyResolver);

            // Navigate to the opening page of the application
            Router.Navigate.Execute(resolver.GetService <IMainViewModel>()).Subscribe();
        }
Exemple #23
0
        /// <summary>
        /// Helper method to get view type for viewmodel.
        /// </summary>
        /// <typeparam name="TViewModel">The viewmodel Type.</typeparam>
        /// <param name="dependencyResolver">The dependencyResolver.</param>
        /// <param name="contract">The contract.</param>
        /// <returns>The view Type again.</returns>
        public static Type?ResolveView <TViewModel>(this IReadonlyDependencyResolver dependencyResolver, string?contract = null)
            where TViewModel : class
        {
            if (dependencyResolver is null)
            {
                throw new ArgumentNullException(nameof(dependencyResolver));
            }

            var uwpViewTypeResolver = dependencyResolver.GetService <ViewTypeResolver>(contract);

            return(uwpViewTypeResolver?.ResolveViewType <TViewModel>());
        }
Exemple #24
0
 private static void RegisterWindowsServices(IMutableDependencyResolver services, IReadonlyDependencyResolver resolver)
 {
     services.RegisterLazySingleton <ITrashCanService>(() => new WindowsTrashCanService(
                                                           resolver.GetService <IDriveService>(),
                                                           resolver.GetService <IOperationsService>(),
                                                           resolver.GetService <IPathService>(),
                                                           resolver.GetService <IFileService>(),
                                                           resolver.GetService <IEnvironmentService>(),
                                                           resolver.GetService <IProcessService>()
                                                           ));
     services.RegisterLazySingleton <IResourceOpeningService>(() => new WindowsResourceOpeningService(
                                                                  resolver.GetService <IProcessService>()
                                                                  ));
     services.RegisterLazySingleton <ITerminalService>(() => new WindowsTerminalService(
                                                           resolver.GetService <IProcessService>(),
                                                           resolver.GetService <IUnitOfWorkFactory>()
                                                           ));
 }
Exemple #25
0
        /// <summary>
        /// Resolves navigation view from a dependency resolver.
        /// </summary>
        /// <param name="dependencyResolver">The dependency resolver.</param>
        /// <param name="contract">Optional contract.</param>
        /// <returns>The dependency resolver for builder use.</returns>
        public static IView GetNavigationView(
            this IReadonlyDependencyResolver dependencyResolver,
            string?contract = null)
        {
            var view = dependencyResolver.GetService <IView>(contract ?? "NavigationView");

            if (view is null)
            {
                throw new InvalidOperationException("NavigationView not registered.");
            }

            return(view);
        }
Exemple #26
0
        public void Register(IMutableDependencyResolver services, IReadonlyDependencyResolver resolver)
        {
            services.RegisterLazySingleton <IApplicationStorage>(() => ApplicationStorage.Instance);
            services.RegisterLazySingleton <IApplicationInfo>(() => new ApplicationInfo(Assembly.GetExecutingAssembly()));
            services.Register <Serilog.ILogger>(
                () =>
            {
                var storage = resolver.GetService <IApplicationStorage>();
                return(new LoggerConfiguration()
                       .WriteTo.Console()
                       .WriteTo.File(Path.Combine(storage.LogDirectory, "application.log"))
                       .CreateLogger());
            });
            services.RegisterLazySingleton <IScheduler>(() => RxApp.MainThreadScheduler);

            services.Register <PgApplicationContext>(() => new PgApplicationContext());
            services.Register <IPhoneRepositoryAsync>(() => new PhoneRepositoryAsync(resolver.GetService <PgApplicationContext>()));

            services.RegisterLazySingleton <IDialogProvider>(() => new DialogProvider(typeof(App).Assembly));
            services.RegisterLazySingleton <IDialogManager>(() => new DialogManager(resolver.GetService <IDialogProvider>()));
            // services.RegisterLazySingleton<IMainViewModel>(() => new MainViewModel(resolver.GetService<IPhoneRepositoryAsync>(), resolver.GetService<IScheduler>()));
        }
Exemple #27
0
 private static void RegisterLinuxServices(IMutableDependencyResolver services, IReadonlyDependencyResolver resolver)
 {
     services.RegisterLazySingleton <ITrashCanService>(() => new LinuxTrashCanService(
                                                           resolver.GetService <IDriveService>(),
                                                           resolver.GetService <IOperationsService>(),
                                                           resolver.GetService <IPathService>(),
                                                           resolver.GetService <IFileService>(),
                                                           resolver.GetService <IEnvironmentService>(),
                                                           resolver.GetService <IDirectoryService>()
                                                           ));
     services.RegisterLazySingleton <IResourceOpeningService>(() => new LinuxResourceOpeningService(
                                                                  resolver.GetService <IProcessService>(),
                                                                  resolver.GetService <IEnvironmentService>()
                                                                  ));
 }
Exemple #28
0
        private static IFilesPanelViewModel CreateFilesPanelViewModel(
            IReadonlyDependencyResolver resolver,
            string panelKey)
        {
            var filesPanelStateService = new FilesPanelStateService(
                resolver.GetService <IUnitOfWorkFactory>(),
                panelKey
                );
            var filesPanelViewModel = new FilesPanelViewModel(
                resolver.GetService <IFileService>(),
                resolver.GetService <IDirectoryService>(),
                resolver.GetService <IFilesSelectionService>(),
                resolver.GetService <IFileSystemNodeViewModelFactory>(),
                resolver.GetService <IFileSystemWatchingService>(),
                resolver.GetService <IApplicationDispatcher>(),
                filesPanelStateService,
                resolver.GetService <ITabViewModelFactory>(),
                resolver.GetService <IFileSizeFormatter>(),
                resolver.GetService <IClipboardOperationsService>()
                );

            return(filesPanelViewModel);
        }
        public LoginViewModel(IReadonlyDependencyResolver dr, string description = null) : base(dr)
        {
            this.dr     = dr;
            Description = description;

            LoginCommand           = ReactiveCommand.CreateFromTask(Login, CanLogin()).LogInvocation(nameof(LoginCommand), Logger, dr);
            RecoverPasswordCommand = ReactiveCommand.Create(Recover).LogInvocation(nameof(RecoverPasswordCommand), Logger, dr);
            CreateCommand          = ReactiveCommand.Create(Create).LogInvocation(nameof(CreateCommand), Logger, dr);

            var timeScheduler = dr.GetService <IScheduler>() ?? DefaultScheduler.Instance;

            this.LogPropertyChangeThrottling(vm => vm.Email, nameof(Email), scheduler: timeScheduler);
            this.LogPropertyChangeThrottling(vm => vm.Password, nameof(Password), password => "***", timeScheduler);
        }
        /// <summary>
        /// DIで取得するインスタンスを登録します
        /// </summary>
        /// <param name="services"></param>
        /// <param name="resolver"></param>
        /// <remarks>
        /// 以下を参照して作成。
        /// https://dev.to/ingvarx/avaloniaui-dependency-injection-4aka
        /// </remarks>
        public static async Task RegisterAsync(IMutableDependencyResolver services, IReadonlyDependencyResolver resolver)
        {
            // サービス登録
            // youtubeサービスはAuthentication Tokenの発行処理が入り、ブラウザとのやり取りが必要となるため遅延せずに初めに必ず行う
            var youtubeService = new YouTubeServiceWrapper();

            youtubeService.Initialize().Wait();

            services.RegisterConstant <IYouTubeService>(youtubeService);
            services.RegisterLazySingleton <IWebClientService>(() => new WebClientService());

            // VM登録
            services.RegisterLazySingleton <IPlaylistListViewViewModel>(() => {
                var vm = new PlaylistListViewViewModel(resolver.GetService <IYouTubeService>(), resolver.GetService <IWebClientService>());
                _      = vm.Initialize();
                return(vm);
            });
            services.RegisterLazySingleton <IPlaylistContentViewViewModel>(() => new PlaylistContentViewViewModel(
                                                                               resolver.GetService <IYouTubeService>(), resolver.GetService <IWebClientService>(), resolver.GetService <IPlaylistListViewViewModel>()));
            services.RegisterLazySingleton <IMainWindowViewModel>(() => new MainWindowViewModel(
                                                                      resolver.GetService <IPlaylistListViewViewModel>(),
                                                                      resolver.GetService <IPlaylistContentViewViewModel>()
                                                                      ));
        }