Example #1
0
        public MainPage(IDependencyService serviceLocator)
        {
            var mainViewModel = serviceLocator.Get <MainViewModel>();

            Master = new DiaryListPage {
                BindingContext = mainViewModel
            };

            var diaryPage = new DiaryEntryPage {
                BindingContext = mainViewModel
            };

            Detail = new NavigationPage(diaryPage)
            {
                BarBackgroundColor = App.TintColor,
                BarTextColor       = App.TintTextColor,
            };
            Detail.SetBinding(TitleProperty, new Binding(nameof(diaryPage.Title), source: diaryPage));

            if (Device.Idiom != TargetIdiom.Desktop)
            {
                var navService = serviceLocator.Get <INavigationService>() as FormsNavigationPageService;
                Debug.Assert(navService != null);
                navService.RegisterAction(AppPage.Master, () => IsPresented = true);
                navService.RegisterAction(AppPage.Detail, () => IsPresented = false);
            }
            else if (Device.Idiom == TargetIdiom.Tablet)
            {
                MasterBehavior = MasterBehavior.SplitOnLandscape;
            }
            else if (Device.Idiom == TargetIdiom.Phone)
            {
                MasterBehavior = MasterBehavior.Popover;
            }
        }
 public void GetDirections()
 {
     if (_dependencyService.Get <IGoogleDirections>() != null)
     {
         _dependencyService.Get <IGoogleDirections>().OpenGoogleMapDirectionsApp(RecievedAttraction.latitude + "," + RecievedAttraction.longitude);
     }
 }
Example #3
0
 public SignInViewModel(IDependencyService depServ)
 {
     _dependencyService = depServ;
     CrossConnectivity.Current.ConnectivityChanged += UpdateNetworkStatus;
     SignInCmd = new Command(async() =>
     {
         IsBusy = true;
         try
         {
             didAuthenticate = await _dependencyService.Get <IAzureClient>().GetToken(platformParameters);
         }
         catch
         {
             new Exception("Erreur au login");
         }
         finally
         {
             if (didAuthenticate)
             {
                 await _dependencyService.Get <INavigationService>().PopToPage("Boardlist", new BoardListViewModel());
             }
             else
             {
                 await _dependencyService.Get <INavigationService>().GoBackAsync();
             }
         }
         IsBusy = false;
     }, () => canAuthenticate());
     noConnection = CrossConnectivity.Current.IsConnected ? false : true;
 }
        private async void nativeSpeech()
        {
            IsBusy = true;
            Title  = await _dependencyService.Get <ISpeechToText>().SpeechToTextAsync();

            IsBusy = false;
        }
Example #5
0
        public async Task MainViewModel_AddQuote_should_go_to_edit_page()
        {
            var vm = new MainViewModel(dependencyService);
            await vm.AddQuote.ExecuteAsync(null);

            var navService = dependencyService.Get <INavigationService>() as NavigationServiceStub;

            Assert.AreEqual(AppPages.Edit, navService.CurrentPage);
        }
Example #6
0
 private void GetApiBooks()
 {
     try
     {
         AvailableBooks = new List <BookProductInfo>(_dependencyService.Get <IBookApiService>().GetAllBooks());
     } catch (Exception e)
     {
         AvailableBooks = new List <BookProductInfo>();
     }
 }
Example #7
0
        private async Task ScanForDevices()
        {
            Devices.Clear();
            var devices = await _dependencyService.Get <IBluetooth>().Scan();

            Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
            {
                devices?.ForEach(device =>
                {
                    Devices.Add(device);
                });
            });
        }
        // Ajouter un contact en redirigeant vers la page d'édition
        private async Task OnAddContact()
        {
            ContactViewModel newContact = new ContactViewModel();

            Contacts.Add(newContact);

            SelectedContact = newContact;

            if (!serviceLocator.Get <INavigationService>().CanGoBack)
            {
                await serviceLocator.Get <INavigationService>()
                .NavigateAsync(AppPages.Edit, newContact);
            }
        }
Example #9
0
        public Storage(IDependencyService dependencyService)
        {
            string dbPath = dependencyService.Get <IFileHelper>().GetLocalFilePath("BelegSQLite.db3");

            database = new SQLiteAsyncConnection(dbPath);
            database.CreateTableAsync <Beleg>().Wait();
        }
Example #10
0
        private async void LoginFacebook()
        {
            string[] readPermissions = { "public_profile", "email" };
            var      fbtoken         = await _dependencyService.Get <IFacebookLoginService>().LoginAsync(readPermissions);

            IsLoading = true;
            var userProfile = await _facebookService.GetFacebookProfileAsync(fbtoken);

            if (userProfile != null)
            {
                var response = await _fitMeetRestService.FacebookLoginAsync(userProfile);

                if (response != null && response.Output?.Status == 1 && response.Output?.Response?.token != null)
                {
                    var token = response.Output.Response.token;
                    _tokenService.SetToken(token);
                    _fitMeetRestService.SetToken(token);
                    if ((response?.Output?.Validation).Equals("User already exists", StringComparison.CurrentCultureIgnoreCase))
                    {
                        NavigateCommand.Execute("app:///MainPage/NavigationPage/MainTabbedPage");
                    }
                    else
                    {
                        NavigateCommand.Execute("SecondSignUpPage");
                    }
                }
                else
                {
                    await _dialogService.DisplayAlertAsync("Error", "Could not register. Please try again", "Ok");
                }
            }


            IsLoading = false;
        }
Example #11
0
        public MainViewModel(IDependencyService serviceLocator)
        {
            this.serviceLocator = serviceLocator;

            SearchCriteria = new ObservableCollection <SearchCriteriaViewModel>()
            {
                new SearchCriteriaViewModel {
                    Field    = "Year",
                    Operator = ComparisonOperation.GreaterEqual,
                    Value    = "2000"
                }
            };

            Search             = new AsyncDelegateCommand(OnSearch, () => SearchCriteria.Count > 0);
            EditSearchCriteria = new AsyncDelegateCommand <SearchCriteriaViewModel>(OnEditSearchCriteria);
            CancelSearch       = new DelegateCommand(OnCancelSearch, () => cancellationTokenSource != null);
            AddSearchCriteria  = new AsyncDelegateCommand(OnAddSearchCriteria);

            MessagingCenter.Subscribe <SearchCriteriaViewModel>(this, "Delete", async scvm => {
                SearchCriteria.Remove(scvm);
                if (SearchCriteria.Count == 0)
                {
                    Search.RaiseCanExecuteChanged();
                }
                await serviceLocator.Get <INavigationService>().GoBackAsync();
            });
        }
Example #12
0
        public App()
        {
            InitializeComponent();

            _dependencyService = new DependencyServiceWrapper();
            try {
                Assembly assembly = Assembly.GetExecutingAssembly();
                // Load Config File Ressource
                string configResourceName = Path.Combine(assembly.GetManifestResourceNames()[0]);
                Stream ConfigStream       = Assembly.GetExecutingAssembly().GetManifestResourceStream(configResourceName);
                ConfigurationManager.Initialise(ConfigStream);
                ConfigurationHelper configurationHelper = _dependencyService.Get <ConfigurationHelper>();

                // Get the DB Path
                configurationHelper.DatabasePath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), ConfigurationManager.AppSettings["localDatabaseName"]);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            // Creating an instance of a TicketRepo (for making DB access possible)
            // The TicketRepository instantiates a DatabaseContext which makes sure the DB is Created / Migrated / Deleted.
            // !!!!! At this point the exception is happening !!!!!
            TicketRepository ticketRepository = new TicketRepository();

            DependencyService.Register <TicketRepository>();

            MainPage = new MainPage();
        }
Example #13
0
 protected async void DeleteAllAdverFromDb()
 {
     if (await _pageDialog.DisplayAlertAsync(_setting.GetAppNameAndVersion,
                                             "Czy napewno chcesz usunąć wszystkie ulubione ogłoszenia?", "Usuń wszystko", "Anuluj"))
     {
         if (await _setting.DeleteAdvertAllDBAsync())
         {
             _dependencyService.Get <IToast>().Show("Usunięto wszystkie ogłoszenia z bazy.");
             AdvertShortList.Clear();
         }
         else
         {
             _dependencyService.Get <IToast>().Show("Wystąpił błąd podczas usuwania ogłoszeń z bazy.");
         }
     }
 }
Example #14
0
        public DatabaseContext(IDependencyService dependencyService)
        {
            _dependencyService   = dependencyService;
            _configurationHelper = _dependencyService.Get <ConfigurationHelper>();
            _databasePath        = _configurationHelper.DatabasePath;

            try{
                #region if we use one or more of the following methods, the application stops running on a hardwaredevice
                // in case we want to delete the DB
                if (false)
                {
                    // Database.EnsureDeleted();
                }

                //Create and Migrate DB if necessary
                //Database.EnsureCreated();
                //Database.MigrateAsync();
                #endregion if we use one or more of the following methods, the application stops running on a hardwaredevice
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
 public MainPageViewModel(INavigationService navigationService,
                          IDependencyService dependencyService)
     : base(navigationService)
 {
     Title    = "Main Page";
     _shouter = dependencyService.Get <IShouterUtil>();
 }
        public LoginPageViewModel(INavigationService navigationService, IDependencyService dependencyService)
        {
            _navigationService = navigationService;
            _azureService      = dependencyService.Get <LoginService>();

            LoginFacebookCommand = new Command(async() => await ExecuteLoginFacebookCommandAsync());
            LoginGoogleCommand   = new Command(async() => await ExecuteLoginGoogleCommandAsync());
        }
Example #17
0
        public BaseViewModel(INavigation navigation, IDependencyService dependencyService)
        {
            DependencyServiceWrapper = dependencyService;
            Navigation = navigation;

            //WebApi = new WebServicesApi();
            WebApi = DependencyServiceWrapper.Get <IWebServicesApi>();
        }
Example #18
0
 public DraftsPageViewModel(INavigationService inavigarionServices, IPageDialogService dialogService, IUserServices userServices, IDeviceOrientationService deviceOrientationService, IDependencyService dependencyService) : base(inavigarionServices, dialogService, userServices, deviceOrientationService, dependencyService)
 {
     deviceOrientationService = dependencyService.Get <IDeviceOrientationService>();
     IsPresentCommand         = new DelegateCommand(() =>
     {
         MessagingCenter.Send(this, "IsPresentKey", IsPresent);
     });
 }
Example #19
0
        /// <summary>
        /// Constructor for the Main view model.
        /// </summary>
        /// <param name="serviceLocator"></param>
        public MainViewModel(IDependencyService serviceLocator)
        {
            this.serviceLocator = serviceLocator;
            diaryService        = serviceLocator.Get <IDiaryService>();

            AddEntry    = new AsyncDelegateCommand(OnAddEntryAsync);
            SaveEntry   = new AsyncDelegateCommand(OnSaveEntryAsync, () => SelectedEntry == null ? false : SelectedEntry.CanSave);
            DeleteEntry = new AsyncDelegateCommand(OnDeleteEntryAsync, de => de != null || (SelectedEntry != null && !SelectedEntry.IsNew));
            Refresh     = new AsyncDelegateCommand(() => deEntries.RefreshAsync());
            SelectEntry = new AsyncDelegateCommand(() => serviceLocator.Get <INavigationService>().NavigateAsync(AppPage.Detail));

            // Lab3: Add logout command
            Logout = new AsyncDelegateCommand(OnClearAuthAsync);

            deEntries = new RefreshingCollection <DiaryEntryViewModel>(LoadDiaryEntriesAsync)
            {
                BeforeRefresh = c =>
                {
                    IsBusy = true;
                    return(SelectedEntry);
                },

                AfterRefresh = (c, o) =>
                {
                    IsBusy        = false;
                    SelectedEntry = (DiaryEntryViewModel)o;
                },

                RefreshFailed = (c, ex) =>
                {
                    IsBusy = false;

                    return(serviceLocator.Get <IMessageVisualizerService>().ShowMessage(
                               "Are you connected?", ex.Flatten(), "OK"));
                }
            };

            // Set the 1st entry as active.
            deEntries.RefreshAsync()
            .ContinueWith(tr =>
            {
                SelectedEntry = deEntries.FirstOrDefault();
            },
                          CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());
        }
Example #20
0
 private void SetConnection()
 {
     if (client == null)
     {
         var messageHandler = dependencyService.Get <HttpMessageHandler>();
         client = messageHandler == null ? new HttpClient() : new HttpClient(messageHandler);
         client.MaxResponseContentBufferSize = 256000;
     }
 }
Example #21
0
        private async Task ReadHandle()
        {
            while (true)
            {
                var result = await _dependencyService.Get <IBluetooth>().ReadAsync();

                if (result is null)
                {
                    return;
                }
                //var value = result.FromByteArray<string>();
                var value = Encoding.ASCII.GetString(result).TrimEnd('\0');
                Device.BeginInvokeOnMainThread(() =>
                {
                    DataResult = value;
                });
            }
        }
Example #22
0
 public DataAccess(IDependencyService dependencyService)
 {
     _config         = dependencyService.Get <IConfig>();
     this.connection = new SQLiteConnection(
         _config.Platform,
         Path.Combine(_config.DirectoryDB, "PL.db3"));
     connection.CreateTable <DrawingResultLocal>();
     connection.CreateTable <CabalaNumbersLocal>();
     connection.CreateTable <CabalaWordsLocal>();
 }
        public UserProfilePageViewModel(INavigationService navigationService, PageDialogService pageDialogService, IDependencyService dependencyService)
        {
            _navigationService = navigationService;
            _pageDialogService = pageDialogService;
            _azureService      = dependencyService.Get <AzureService>();

            _azureService.Initialize();

            Tweets = new ObservableCollection <Tweet>();
            User   = new TwitterUser();
        }
        // いったんコメントアウト これが実行されない
        // ^> IDependencyService dependencyServiceすればいけるけど解せない
        // https://prismlibrary.com/docs/xamarin-forms/Dependency-Service.html
        public MainPageViewModel(IPageDialogService pageDialogService, INavigationService navigationService, IDependencyService dependencyService)
            : base(navigationService)
        {
            System.Diagnostics.Debug.WriteLine("(´・ω・`)ViewModel  start");
            ISaveAndLoad          sal = dependencyService.Get <ISaveAndLoad>();
            INotificationOnAndOff ins = dependencyService.Get <INotificationOnAndOff>();
            ICreateService        ics = dependencyService.Get <ICreateService>();

            Model = new MainPageModel(sal, ins, ics);

            this.Model.PropertyChanged += Model_PropertyChanged;

            _pageDialogService = pageDialogService;

            Title = "通知メモ";

            // _pageDialogService.DisplayAlertAsync("確認", "利用するには他のアプリの上に重ねて表示する権限を許可してください。", "はい");
            //if (!ics.CheckPermission())
            //{
            //    _pageDialogService.DisplayAlertAsync("確認", "利用するには他のアプリの上に重ねて表示する権限を許可してください。", "はい");
            //}
        }
        public async Task OnProcessPhotoStream(Func <Stream> mediaFile)
        {
            IDependencyService locator = XamUInfrastructure.ServiceLocator;

            string id = await locator.Get <IIdentifyPicture>().IdentifyAsync(mediaFile);

            if (string.IsNullOrEmpty(id))
            {
                Error = "Sorry, I was unable to identify that plant. Please try again.";
            }

            var plant = await locator.Get <IPlantDetails>().GetPlantFromIdAsync(id);

            if (plant != null)
            {
                await locator.Get <INavigationService>().NavigateAsync(AppPages.Details, new DetailsViewModel(plant, mediaFile.Invoke()));
            }
            else
            {
                Error = $"Sorry, I could not find any information on {id}.";
            }
        }
Example #26
0
        public async Task <ResponseMessage <SignUpResponse> > EmailSignUpAsync(string email, string password, bool isSubscibleNews, bool isShareInfo)
        {
            var position = await _geoService.GetPosition();

            var deviceToken = _dependencyService.Get <IPushNotificationSupportService>().DeviceToken();



            var param = new Dictionary <string, string>
            {
                { "email", email.Trim() },
                { "password", password },
                { "device_token", deviceToken },
                { "newsletter", isSubscibleNews?"1":"0" },
                { "share_info", isShareInfo?"1":"0" },
                { "device_type", DeviceType() },
                { "lat", position?.Latitude.ToString() },
                { "lng", position?.Longitude.ToString() }
            };

            return(await ApiPost <ResponseMessage <SignUpResponse> >(EmailSignUpUri, param));
        }
Example #27
0
        public BaseViewModel(IDependencyService dependencyService)
        {
            DependencyService    = dependencyService;
            ConnectivityServices = DependencyService.Get <IConnectivity>();
            NavigationService    = DependencyService.Get <INavigation>();

            ConnectivityServices.OnConnectivityChanged += async(sender, e) => {
                NotifyPropertyChanged("Online");
                NotifyPropertyChanged("Offline");
                if (Online)
                {
                    try
                    {
                        // Do something when connection recovered
                    }
                    catch { /* fail silently */ }
                }
                else
                {
                    CancelTasks();
                }
            };
        }
Example #28
0
        async void OnLoginButtonClicked(object sender, EventArgs e)
        {
            string url    = _identityService.CreateAuthorizationRequest();
            var    result = await _dependencyService.Get <INativeBrowser>().LaunchBrowserAsync(url);

            if (!result.IsError)
            {
                _authResponse = new AuthorizeResponse(result.Response);
                if (_authResponse.IsError)
                {
                    Debug.WriteLine("\tERROR: {0}", _authResponse.Error);
                }
            }
        }
        public void saveReminder()
        {
            EventModel em = PrepareEventModel();

            _dependencyService.Get <IEventKitHandler>().SaveEvent(em);
            if (validateForm())
            {
                _dialogService.DisplayAlertAsync("Reminder Saved", null, "OK");
            }
            else
            {
                _dialogService.DisplayAlertAsync("Please fill all Mandatory Fields", null, "OK");
            }
        }
        public MainViewModel(IDependencyService serviceLocator)
        {
            this.serviceLocator = serviceLocator;

            Quotes = new ObservableCollection <QuoteViewModel>(QuoteManager.Load(serviceLocator.Get <IQuoteLoader>())
                                                               .Select(q => new QuoteViewModel(q)));

            SelectedQuote = Quotes.FirstOrDefault();

            AddQuote        = new AsyncDelegateCommand(OnAddQuote);
            DeleteQuote     = new AsyncDelegateCommand <QuoteViewModel>(OnDeleteQuote);
            EditQuote       = new AsyncDelegateCommand <QuoteViewModel>(OnEditQuote);
            ShowQuoteDetail = new AsyncDelegateCommand <QuoteViewModel>(OnShowQuoteDetails);
        }