Ejemplo n.º 1
0
        public MainPage()
        {
            InitializeComponent();

            instance = this;

            // Navigate to the first page
            Navigate(typeof(AccountsPage), this);

            if (SettingsManager.Get <bool>(Setting.UseCloudSynchronization))
            {
                PasswordVault vault = new PasswordVault();
                IReadOnlyList <PasswordCredential> credentials = vault.RetrieveAll();

                if (credentials.Any())
                {
                    credentials[0].RetrievePassword();

                    ISynchronizer synchronizer = new OneDriveSynchronizer(OneDriveClientExtensions.GetUniversalClient(new[] { "onedrive.appfolder" }));
                    IEncrypter    encrypter    = new AESEncrypter();

                    synchronizer.SetEncrypter(encrypter, credentials[0].Password);

                    AccountStorage.Instance.SetSynchronizer(synchronizer);
                }
            }

            SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
        }
Ejemplo n.º 2
0
        private async void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                oneDriveClient = OneDriveClientExtensions.GetUniversalClient(scopes);
                var accountSession = await oneDriveClient.AuthenticateAsync();

                if (accountSession != null)
                {
                    var rootItem = await oneDriveClient
                                   .Drive
                                   .Root
                                   .Request()
                                   .GetAsync();

                    var items = await oneDriveClient
                                .Drive
                                .Items[rootItem.Id]
                                .Children
                                .Request()
                                .GetAsync();
                    gridView.ItemsSource = items.CurrentPage;
                }
            }
            catch (OneDriveException oe)
            {
                txtMsg.Text = "登陆失败";
            }
        }
Ejemplo n.º 3
0
 public static IOneDriveClient GetUniversalClient(
     string[] scopes,
     string returnUrl           = null,
     IHttpProvider httpProvider = null)
 {
     return(OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator(scopes, returnUrl, httpProvider));
 }
        private async void InitializeClient(ClientType clientType, RoutedEventArgs e)
        {
            if (((App)Application.Current).OneDriveClient == null)
            {
                var client = clientType == ClientType.Consumer
                    ? OneDriveClientExtensions.GetUniversalClient(this.scopes) as OneDriveClient
                    : BusinessClientExtensions.GetActiveDirectoryClient(
                    oneDriveForBusinessAppId,
                    oneDriveForBusinessReturnUrl) as OneDriveClient;

                try
                {
                    await client.AuthenticateAsync();

                    ((App)Application.Current).OneDriveClient = client;
                    ((App)Application.Current).NavigationStack.Add(new ItemModel(new Item()));
                    Frame.Navigate(typeof(MainPage), e);
                }
                catch (OneDriveException exception)
                {
                    // Swallow the auth exception but write message for debugging.
                    Debug.WriteLine(exception.Error.Message);
                    client.Dispose();
                }
            }
            else
            {
                Frame.Navigate(typeof(MainPage), e);
            }
        }
Ejemplo n.º 5
0
        public async Task <IOneDriveClient> LoginAsync()
        {
            try {
                if (oneDriveClient == null)
                {
                    oneDriveClient = OneDriveClientExtensions.GetUniversalClient(ServiceConstants.Scopes);
                    await oneDriveClient.AuthenticateAsync();
                }

                if (!oneDriveClient.IsAuthenticated)
                {
                    await oneDriveClient.AuthenticateAsync();
                }

                return(oneDriveClient);
            }
            catch (OneDriveException exception) {
                // Swallow authentication cancelled exceptions
                if (!exception.IsMatch(OneDriveErrorCode.AuthenticationCancelled.ToString()))
                {
                    if (exception.IsMatch(OneDriveErrorCode.AuthenticationFailure.ToString()))
                    {
                        await dialogService.ShowMessage(
                            "Authentication failed",
                            "Authentication failed");
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            return(oneDriveClient);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets the universal client (Windows 10) and attempts to authenticate with OneDrive.
        /// </summary>
        /// <returns>True if the authentication was successful, otherwise false.</returns>
        public async Task <bool> InitializeAsync()
        {
            var scopes   = new[] { "wl.offline_access", "wl.signin", "office.onenote_update", "onedrive.readwrite" };
            var redirect = "urn:ietf:wg:oauth:2.0:oob";

            OneDriveClient = OneDriveClientExtensions.GetUniversalClient(scopes, redirect) as OneDriveClient;

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

            try
            {
                await OneDriveClient.AuthenticateAsync();

                Debug.WriteLine("Successfully authenticated with OneDrive");
            }
            catch (OneDriveException ex)
            {
                Debug.WriteLine("error authenticating" + ex);
                OneDriveClient.Dispose();
                return(false);
            }

            return(OneDriveClient.IsAuthenticated);
        }
Ejemplo n.º 7
0
        public async Task <bool> AuthenticateAsync()
        {
            try
            {
                oneDriveClient = OneDriveClientExtensions.GetUniversalClient(Scopes);
                await oneDriveClient.AuthenticateAsync();
            }
            catch
            {
                System.Diagnostics.Debug.WriteLine("Fail auth. Make sure app is registered in store.");
            }

            try
            {
                // little hack to make shure the service works
                await oneDriveClient.Drive.Request().GetAsync();

                IsAuthenticated = true;
            }
            catch (Exception)
            {
                IsAuthenticated = false;
            }

            return(IsAuthenticated);
        }
        private async void Continue_Tapped(object sender, TappedRoutedEventArgs e)
        {
            try
            {
                MainPage.ShowLoader(ResourceLoader.GetForCurrentView().GetString("SynchronizingAccountsWithCloud"));

                IOneDriveClient oneDriveClient = OneDriveClientExtensions.GetUniversalClient(new[] { "onedrive.appfolder" });
                AccountSession  session        = await oneDriveClient.AuthenticateAsync();

                IEncrypter encrypter = new AESEncrypter();

                if (session.AccountType == AccountType.MicrosoftAccount)
                {
                    synchronizer.SetEncrypter(encrypter, userKey);
                    await AccountStorage.Instance.Synchronize();

                    MainPage.HideLoader();

                    Frame.Navigate(typeof(SetupSynchronizationFinishedPage), mainPage);
                }
            }
            catch (OneDriveException ex)
            {
                MessageDialog dialog = GetOneDriveErrorMessageDialog(ex);
                await dialog.ShowAsync();
            }
        }
Ejemplo n.º 9
0
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            oneDriveClient = OneDriveClientExtensions.GetUniversalClient(new[] { "onedrive.appfolder" });

            vault = new PasswordVault();

            ShowInformation();
        }
Ejemplo n.º 10
0
        private async void OnOneDriveWebViewLogin(object sender, RoutedEventArgs e)
        {
            _client = OneDriveClientExtensions.GetClientUsingWebAuthenticationBroker(ClientId, Scopes);
            await _client.AuthenticateAsync();

            refreshToken = _client.AuthenticationProvider.CurrentAccountSession.RefreshToken;
            ApplicationData.Current.LocalSettings.Values["RefreshToken"] = refreshToken;
        }
Ejemplo n.º 11
0
        private async void OneDriveButton_Click(object sender, RoutedEventArgs e)
        {
            var scopes = new[]
            {
                "onedrive.readwrite",
                "onedrive.appfolder",
                "wl.signin"
            };

            SongListStorage._client = OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator(scopes);
            var session = await SongListStorage._client.AuthenticateAsync();

            //Debug.WriteLine($"Token: {session.AccessToken}");
        }
Ejemplo n.º 12
0
 public async Task <AccountSession> Initialize()
 {
     // onedrive
     try
     {
         var scopes = new string[] { "wl.basic", "wl.signin", "onedrive.readwrite" };
         client = OneDriveClientExtensions.GetUniversalClient(scopes);
         return(await client.AuthenticateAsync());
     }
     catch (Exception)
     {
         throw;
     }
 }
Ejemplo n.º 13
0
        private async Task DecommissionSyncWithOnedrive()
        {
            IOneDriveClient onedriveClient =
                OneDriveClientExtensions.GetUniversalClient(new[] { "onedrive.appfolder" });

            IReadOnlyList <PasswordCredential> credentials = vault.RetrieveAll();

            foreach (PasswordCredential credential in credentials)
            {
                vault.Remove(credential);
            }
            await onedriveClient.SignOutAsync();

            SettingsManager.Save(Setting.UseCloudSynchronization, false);
        }
Ejemplo n.º 14
0
        private async void AuthenticateClick(object sender, RoutedEventArgs e)
        {
            ShowBusy(true);
            Exception error = null;

            try
            {
                _session = null;

                // Using the OnlineIdAuthenticator
                _client = OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator(
                    _scopes);

                // Using the WebAuthenticationBroker
                //_client = OneDriveClientExtensions.GetClientUsingWebAuthenticationBroker(
                //    "000000004C172C3F",
                //    _scopes);

                _session = await _client.AuthenticateAsync();

                Debug.WriteLine($"Token: {_session.AccessToken}");

                var dialog = new MessageDialog("You are authenticated!", "Success!");
                await dialog.ShowAsync();

                ShowBusy(false);
            }
            catch (Exception ex)
            {
                error = ex;
            }

            if (error != null)
            {
                var dialog = new MessageDialog("Problem when authenticating!", "Sorry!");
                await dialog.ShowAsync();

                ShowBusy(false);
            }
        }
Ejemplo n.º 15
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (((App)Application.Current).OneDriveClient == null)
            {
                ((App)Application.Current).OneDriveClient = OneDriveClientExtensions.GetUniversalClient(
                    this.scopes);

                await((App)Application.Current).OneDriveClient.AuthenticateAsync();
            }

            if (this.itemsController == null)
            {
                this.itemsController = new ItemsController(((App)Application.Current).OneDriveClient);
            }

            var last = ((App)Application.Current).NavigationStack.Last();

            ((App)Application.Current).Items = await this.itemsController.GetImagesAndFolders(last.Id);

            this.DataContext = ((App)Application.Current).Items;
            wait.IsActive    = false;
        }
        /// <summary>
        /// Tests logging into MobileService with Microsoft Account token (via OneDrive SDK).
        /// App needs to be assosciated with a WindowsStoreApp
        /// </summary>
        private async Task TestClientDirectedMicrosoftAccountLogin()
        {
            try
            {
                Task <AccountSession> sessionTask = null;

                // Force AuthenticateAsync() to run on the UI thread.
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    IOneDriveClient oneDriveClient = OneDriveClientExtensions.GetUniversalClient(new string[] { "wl.signin" });
                    sessionTask = oneDriveClient.AuthenticateAsync();
                });

                AccountSession session = await sessionTask;

                if (session != null && session.AccessToken != null)
                {
                    JObject accessToken = new JObject();
                    accessToken["access_token"] = session.AccessToken;

                    MobileServiceUser user = await this.GetClient().LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount, accessToken);

                    Log(string.Format("Log in with Microsoft Account OneDrive SDK succeeded - userId {0}", user.UserId));
                }
                else
                {
                    Assert.Fail("Log in with Microsoft Account OneDrive SDK failed");
                }
            }
            catch (Exception exception)
            {
                Log(string.Format("ExceptionType: {0} Message: {1} StackTrace: {2}",
                                  exception.GetType().ToString(),
                                  exception.Message,
                                  exception.StackTrace));
                Assert.Fail("Log in with Microsoft Account OneDrive SDK failed");
            }
        }
Ejemplo n.º 17
0
 private async void OnOneDriveLogin(object sender, RoutedEventArgs e)
 {
     _client = OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator(Scopes);
     await _client.AuthenticateAsync();
 }
Ejemplo n.º 18
0
        /// <summary>
        /// 将str做备份
        /// </summary>
        /// <param name="str">需要备份的string</param>
        /// <param name="st">备份的类型</param>
        /// <returns>返回成功与否</returns>
        public async static Task <string> BackupAsync(string str, SaveType st)
        {
            try
            {
                switch (st)
                {
                case SaveType.LocalState:
                    StorageFolder localFolder    = ApplicationData.Current.LocalFolder;
                    StorageFile   LocalStateFile = await localFolder.CreateFileAsync("data.pwsv", CreationCollisionOption.ReplaceExisting);

                    await FileIO.WriteTextAsync(LocalStateFile, str);

                    break;

                case SaveType.LocalFile:
                    FileSavePicker picker = new FileSavePicker();
                    picker.DefaultFileExtension = ".pwsv";
                    picker.FileTypeChoices.Add("密码计算器文件", new List <string>()
                    {
                        ".pwsv"
                    });
                    picker.SuggestedFileName      = "backup";
                    picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                    StorageFile LocalFileFile = await picker.PickSaveFileAsync();

                    if (LocalFileFile == null)
                    {
                        return("-未选择文件!");
                    }
                    await FileIO.WriteTextAsync(LocalFileFile, str);

                    break;

                case SaveType.RoamingData:
                    StorageFolder RoamingFolder = ApplicationData.Current.RoamingFolder;
                    //Debug.WriteLine(ApplicationData.Current.RoamingStorageQuota);
                    StorageFile RoamingDataFile = await RoamingFolder.CreateFileAsync("data.pwsv", CreationCollisionOption.ReplaceExisting);

                    await FileIO.WriteTextAsync(RoamingDataFile, str);

                    break;

                case SaveType.OneDrive:
                    try {
                        //string[] scopes = new string[] { "wl.signin", "wl.offline_access", "onedrive.readwrite" };
                        string[] scopes         = new string[] { "wl.signin", "onedrive.readwrite" };
                        var      oneDriveClient = OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator(scopes);
                        await oneDriveClient.AuthenticateAsync();

                        byte[]       array        = Encoding.UTF8.GetBytes(str);
                        MemoryStream stream       = new MemoryStream(array);
                        var          uploadedItem = await oneDriveClient
                                                    .Drive
                                                    .Root
                                                    .ItemWithPath("Documents/backup.pwsv")
                                                    .Content
                                                    .Request()
                                                    .PutAsync <Item>(stream);
                    }
                    catch (Exception exc)
                    {
                        return("-" + exc.Message + "\n详细信息:" + exc.InnerException.Message);
                    }
                    break;

                default: return("-备份时遇到未知参数");
                }
                return("1");
            }
            catch (Exception ex)
            { return("-" + ex.Message); }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 还原数据
        /// </summary>
        /// <param name="st">还原的类型</param>
        /// <returns>还原回的string,开头为-则失败</returns>
        public async static Task <string> RecoverAsync(SaveType st)
        {
            try {
                switch (st)
                {
                case SaveType.LocalState:
                    StorageFolder localFolder    = ApplicationData.Current.LocalFolder;
                    StorageFile   LocalStateFile = await localFolder.GetFileAsync("data.pwsv");

                    if (LocalStateFile == null)
                    {
                        return("-本地不存在此文件");
                    }
                    return(await FileIO.ReadTextAsync(LocalStateFile));

                case SaveType.LocalFile:
                    FileOpenPicker openFile = new FileOpenPicker();
                    openFile.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                    openFile.FileTypeFilter.Add(".pwsv");
                    StorageFile LocalFileFile = await openFile.PickSingleFileAsync();

                    if (LocalFileFile == null)
                    {
                        return("-未选择文件");
                    }
                    return(await FileIO.ReadTextAsync(LocalFileFile));

                case SaveType.RoamingData:
                    StorageFolder RoamingFolder   = ApplicationData.Current.RoamingFolder;
                    StorageFile   RoamingDataFile = await RoamingFolder.GetFileAsync("data.pwsv");

                    return(await FileIO.ReadTextAsync(RoamingDataFile));

                case SaveType.OneDrive:
                    try {
                        //string[] scopes = new string[] { "wl.signin", "wl.offline_access", "onedrive.readwrite" };
                        string[] scopes         = new string[] { "wl.signin", "onedrive.readwrite" };
                        var      oneDriveClient = OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator(scopes);
                        await oneDriveClient.AuthenticateAsync();

                        var item = await oneDriveClient
                                   .Drive
                                   .Root
                                   .ItemWithPath("Documents/backup.pwsv")
                                   .Request()
                                   .GetAsync();

                        using (var contentStream = await oneDriveClient.Drive.Items[item.Id].Content.Request().GetAsync())
                        {
                            StreamReader reader = new StreamReader(contentStream);
                            return(reader.ReadToEnd());
                        }
                    }
                    catch (Exception exc)
                    {
                        return("-" + exc.Message + "\n详细信息:" + exc.InnerException.Message);
                    }

                default: return("-还原时遇到未知参数");
                }
            }
            catch (Exception ex)
            { return("-" + ex.Message); }
        }
Ejemplo n.º 20
0
 public void InitInstance()
 {
     oneDriveClient = OneDriveClientExtensions
                      .GetClientUsingOnlineIdAuthenticator(new string[] { "onedrive.appfolder", "offline_access" });
 }