예제 #1
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();

            if (ApplicationData.Current.LocalSettings.Values.ContainsKey("RefreshToken"))
            {
                string          refreshToken = ApplicationData.Current.LocalSettings.Values["RefreshToken"].ToString();
                string          returnUrl    = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();
                IOneDriveClient client       = await OneDriveClient.GetSilentlyAuthenticatedMicrosoftAccountClient(ClientId, returnUrl, Scopes,
                                                                                                                   refreshToken);

                bool isFolderExisting = true;
                try
                {
                    await client.Drive.Root.ItemWithPath("OneDrive Sample").Request().GetAsync();
                }
                catch (OneDriveException exc)
                {
                    isFolderExisting = false;
                }

                if (isFolderExisting)
                {
                    StorageFile file = await Package.Current.InstalledLocation.GetFileAsync("BackgroundWallpaper.jpg");

                    using (Stream stream = await file.OpenStreamForReadAsync())
                    {
                        await client.Drive.Root.ItemWithPath("OneDrive Sample/BackgroundWallpaper.png").Content.Request().PutAsync <Item>(stream);
                    }
                }
            }

            deferral.Complete();
        }
예제 #2
0
        internal static OneDriveItem CreateFromRawJson(string rawJsonData, OneDriveClient sourceClient)
        {
            OneDriveItem item = JsonConvert.DeserializeObject<OneDriveItem>(rawJsonData);
            item.Client = sourceClient;

            return item;
        }
        public async Task GetSilentlyAuthenticatedMicrosoftAccountClient_WithSecret()
        {
            var appId        = "appId";
            var clientSecret = "secret";
            var refreshToken = "refresh";
            var returnUrl    = "returnUrl";
            var scopes       = new string[] { "scope" };

            this.authenticationProvider.SetupSet(provider => provider.CurrentAccountSession = It.IsAny <AccountSession>()).Verifiable();

            this.SetupServiceInfoProviderForMicrosoftAccount(appId, clientSecret, returnUrl, scopes);

            var client = await OneDriveClient.GetSilentlyAuthenticatedMicrosoftAccountClient(
                appId,
                returnUrl,
                scopes,
                clientSecret,
                refreshToken,
                this.serviceInfoProvider.Object,
                this.credentialCache.Object,
                this.httpProvider.Object);

            this.authenticationProvider.VerifySet(
                provider => provider.CurrentAccountSession = It.Is <AccountSession>(session => refreshToken.Equals(session.RefreshToken)),
                Times.Once);

            this.authenticationProvider.Verify(provider => provider.AuthenticateAsync(), Times.Once);
        }
예제 #4
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);
        }
        public void GetMicrosoftAccountClient_NoSecret_InitializeDefaults()
        {
            var appId     = "appId";
            var returnUrl = "returnUrl";
            var scopes    = new string[] { "scope" };

            var client = OneDriveClient.GetMicrosoftAccountClient(
                appId,
                returnUrl,
                scopes) as OneDriveClient;

            Assert.IsNotNull(client.credentialCache, "Cache not initialized.");

            var initializedServiceInfoProvider = client.serviceInfoProvider as ServiceInfoProvider;

            Assert.IsNotNull(initializedServiceInfoProvider, "Service info provider not correctly initialized.");

            var initializedHttpProvider = client.HttpProvider as HttpProvider;

            Assert.IsNotNull(initializedHttpProvider, "HTTP provider not correctly initialized.");

            Assert.AreEqual(appId, client.appConfig.MicrosoftAccountAppId, "Incorrect app ID set.");
            Assert.IsNull(client.appConfig.MicrosoftAccountClientSecret, "Client secret set.");
            Assert.AreEqual(returnUrl, client.appConfig.MicrosoftAccountReturnUrl, "Incorrect return URL set.");
            Assert.AreEqual(scopes, client.appConfig.MicrosoftAccountScopes, "Incorrect scopes set.");
        }
예제 #6
0
        private async Task loggin()
        {
            msaProvider = new OnlineIdAuthenticationProvider(scopes);
            await msaProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync();

            this.client = new OneDriveClient(msaProvider);
        }
예제 #7
0
        public async Task SyncMediaToOneDrive(string trackingNumber)
        {
            OneDriveClient oneDriveClient = new OneDriveClient();



            var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

            documentsPath = documentsPath + "/" + trackingNumber;


            //Pictures captured by camera
            string[] jpgFileList = Directory.Exists(documentsPath)
                                         ? Directory.GetFiles(documentsPath, "*.jpg")
                                            : null;
            foreach (string filePathAndName in jpgFileList)
            {
                FileInfo info     = new FileInfo(filePathAndName);
                string   fileName = info.Name;
                //var imagePath = "/Users/rei/Library/" + "693_CellCultureandFermentation_A1_CellCultureandFermentation_A_Question1Camera.jpg"; //documentsPath + "/" + fileName;
                await oneDriveClient.PostMediaToOneDrive(filePathAndName, fileName, trackingNumber);
            }

            //videos captured by camera
            string[] mp4FileList = Directory.Exists(documentsPath)
                                         ? Directory.GetFiles(documentsPath, "*.mp4")
                                            : null;
            foreach (string filePathAndName in mp4FileList)
            {
                FileInfo info     = new FileInfo(filePathAndName);
                string   fileName = info.Name;
                //var imagePath = "/Users/rei/Library/" + "693_CellCultureandFermentation_A1_CellCultureandFermentation_A_Question1Camera.jpg"; //documentsPath + "/" + fileName;
                await oneDriveClient.PostMediaToOneDrive(filePathAndName, fileName, trackingNumber);
            }

            //signature captured by scratch pad
            string[] pngFileList = Directory.Exists(documentsPath)
                                         ? Directory.GetFiles(documentsPath, "*.png")
                                            : null;
            foreach (string filePathAndName in pngFileList)
            {
                FileInfo info     = new FileInfo(filePathAndName);
                string   fileName = info.Name;
                //var imagePath = "/Users/rei/Library/" + "693_CellCultureandFermentation_A1_CellCultureandFermentation_A_Question1Camera.jpg"; //documentsPath + "/" + fileName;
                await oneDriveClient.PostMediaToOneDrive(filePathAndName, fileName, trackingNumber);
            }


            //voice
            string[] wavFileList = Directory.Exists(documentsPath)
                                         ? Directory.GetFiles(documentsPath, "*.wav")
                                            : null;
            foreach (string filePathAndName in wavFileList)
            {
                FileInfo info     = new FileInfo(filePathAndName);
                string   fileName = info.Name;
                //var imagePath = "/Users/rei/Library/" + "693_CellCultureandFermentation_A1_CellCultureandFermentation_A_Question1Camera.jpg"; //documentsPath + "/" + fileName;
                await oneDriveClient.PostMediaToOneDrive(filePathAndName, fileName, trackingNumber);
            }
        }
예제 #8
0
        public void OneDriveFileUploadNotEnoughData()
        {
            if (!GlobalTestSettings.RunNetworkTests)
            {
                Assert.Inconclusive(GlobalTestSettings.NetworkTestsDisabledMessage);
            }

            int payloadSize = 262144; // 256k

            TokenResponse currentToken = GetCurrentToken();

            Guid remoteTestFolderName = Guid.NewGuid();
            Item remoteTestFolder     = CreateOneDriveTestDirectory(currentToken, remoteTestFolderName.ToString("D")).Result;

            using (OneDriveClient client = new OneDriveClient(currentToken))
            {
                // Specify the upload size as 16 bytes larger than we are actually going to send.
                OneDriveUploadSession session =
                    client.CreateUploadSession(remoteTestFolder.Id, "uploadTest.txt", payloadSize + 16).Result;

                using (OneDriveFileUploadStream stream = new OneDriveFileUploadStream(client, session))
                {
                    byte[] data = CreateUploadBuffer(payloadSize);

                    // Write the data in 1k chunks
                    int writeSize = 1024;
                    for (int j = 0; j < payloadSize; j += writeSize)
                    {
                        stream.Write(data, j, writeSize);
                    }
                }

                Assert.AreEqual(OneDriveFileUploadState.Cancelled, session.State);
            }
        }
예제 #9
0
        public void OneDrive1ByteFileUploadTest()
        {
            if (!GlobalTestSettings.RunNetworkTests)
            {
                Assert.Inconclusive(GlobalTestSettings.NetworkTestsDisabledMessage);
            }

            int fragmentSize = 327680; // 320k
            int payloadSize  = 1;

            TokenResponse currentToken = GetCurrentToken();

            Guid remoteTestFolderName = Guid.NewGuid();
            Item remoteTestFolder     = CreateOneDriveTestDirectory(currentToken, remoteTestFolderName.ToString("D")).Result;

            using (OneDriveClient client = new OneDriveClient(currentToken))
            {
                OneDriveUploadSession session =
                    client.CreateUploadSession(remoteTestFolder.Id, "uploadTest.txt", payloadSize).Result;

                using (OneDriveFileUploadStream stream = new OneDriveFileUploadStream(client, session, fragmentSize))
                {
                    // Create a buffer for the data we want to send, and fill it with ASCII text
                    stream.Write(new byte[] { 0xAB }, 0, 1);
                }

                Assert.AreEqual(OneDriveFileUploadState.Completed, session.State);
            }
        }
예제 #10
0
        public void OneDriveFileUploadSingleFragment()
        {
            if (!GlobalTestSettings.RunNetworkTests)
            {
                Assert.Inconclusive(GlobalTestSettings.NetworkTestsDisabledMessage);
            }

            int fragmentSize = OneDriveFileUploadStream.DefaultFragmentSize; // 10M
            int payloadSize  = 524288;                                       // < 1 fragments

            TokenResponse currentToken = GetCurrentToken();

            Guid remoteTestFolderName = Guid.NewGuid();
            Item remoteTestFolder     = CreateOneDriveTestDirectory(currentToken, remoteTestFolderName.ToString("D")).Result;

            using (OneDriveClient client = new OneDriveClient(currentToken))
            {
                OneDriveUploadSession session =
                    client.CreateUploadSession(remoteTestFolder.Id, "uploadTest.txt", payloadSize).Result;

                using (OneDriveFileUploadStream stream = new OneDriveFileUploadStream(client, session, fragmentSize))
                {
                    byte[] data = CreateUploadBuffer(payloadSize);
                    stream.Write(data, 0, data.Length);
                }

                Assert.AreEqual(OneDriveFileUploadState.Completed, session.State);
                Assert.IsNotNull(session.Item);
            }
        }
예제 #11
0
        private async Task InitOneDrive()
        {
            string[] scopes = { "onedrive.readonly", "wl.signin" };
            try
            {
                // get provider
                authenticationProvider = new OnlineIdAuthenticationProvider(scopes);
                await authenticationProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync();

                // init client
                oneDriveClient = new OneDriveClient(BaseUrl, authenticationProvider);
            }
            catch (Exception e)
            {
                Analytics.TrackEvent("Exception when initializing OneDrive", new Dictionary <string, string>
                {
                    { "Error", e.Message },
                    { "InnerError", e.InnerException != null ? e.InnerException.Message : "" },
                    { "Where", "MainPage.xaml:InitOneDrive" }
                });
                authenticationProvider = null;
                oneDriveClient         = null;
                throw;
            }
        }
        /// <summary>
        /// OneDriveとの接続が確立された時
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public async void OnOneDriveConnectionEstablished(object sender, OneDriveConnectionEstablishedEventArgs e)
        {
            this.client = e.Client;

            // ルートディレクトリのファイル・フォルダリストを作成する
            await this.UpdateDirectoryAsync();
        }
예제 #13
0
        public async Task Authenticate()
        {
            var msaAuthenticationProvider = new OnlineIdAuthenticationProvider(new string[] { "onedrive.readwrite" });
            await msaAuthenticationProvider.AuthenticateUserAsync();

            client = new OneDriveClient("https://api.onedrive.com/v1.0", msaAuthenticationProvider);
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var parameters = (VideoNavigationParameter)e.Parameter;

            oneDriveClient = parameters.oneDriveClient;
            pathComponents = parameters.PathComponents;
            _ = SetVideoSourceKeepingPlaytime(true);
        }
예제 #15
0
        private async void ConnectOneDriveServer()
        {
            //이미 연결중이면 수행하지 않음.
            if (IsConnecting)
            {
                return;
            }

            //현재 연결이 되어 있다면 연결 해제
            await DisconnectOneDriveServer(false);

            //연결중...
            IsConnecting     = true;
            ShowErrorMessage = false;

            var    resource      = ResourceLoader.GetForCurrentView();
            string errMsg        = resource.GetString("Message/Error/FailServerAuthentication"); //"인증에 실패하였습니다. 아이디/패스워드를 확인하세요. ";
            var    isOrderByName = _Sort == SortType.Name || _Sort == SortType.NameDescending;

            Task authTask = null;

            var msaAuthProvider = new MsaAuthenticationProvider(
                this.oneDriveConsumerClientId,
                this.oneDriveConsumerReturnUrl,
                this.scopes,
                new CredentialVault(this.oneDriveConsumerClientId));

            await msaAuthProvider.SignOutAsync();

            authTask = msaAuthProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync();

            OneDriveClient = new OneDriveClient(this.oneDriveConsumerBaseUrl, msaAuthProvider);
            AuthProvider   = msaAuthProvider;

            try
            {
                await authTask;

                //서버타입 설정
                ConnectedServerType = ServerTypes.OneDrive;

                await LoadOneDriveFoldersAsync();

                //인증 성공
                IsConnecting   = false;
                IsDisconnected = false;
            }
            catch (ServiceException exception)
            {
                // Swallow the auth exception but write message for debugging.
                Debug.WriteLine(exception.Error.Message);

                pathStack.Clear();
                IsConnecting   = false;
                IsDisconnected = true;
                ShowOrderBy    = false;
            }
        }
예제 #16
0
        static private void scanRemoteFolder(OneDriveClient odc, Item dirItem, string relRemoteFolder)
        {
            FileHistory fh;

            if (!testFilePattern(relRemoteFolder, false))
            {
                return;
            }

            fh = setRemoteFileEntry(relRemoteFolder, dirItem);
            addLog(!fh.remoteChanged, string.Format("r\tVerzeichnis \"{0}\" ({1}, {2})", relRemoteFolder.Substring(config.Options.RemoteBaseDir.Length - 1), fh.remoteChanged ? "1" : "0", fh.remoteWriteTime.ToString()));

            IItemChildrenCollectionPage childs = odc.Drive.Items[dirItem.Id].Children.Request().GetAsync().Result;

            while (true)
            {
                foreach (Item remoteItem in childs)
                {
                    string relFullItemName = relRemoteFolder + remoteItem.Name;
                    if (remoteItem.Folder != null)
                    {
                        relFullItemName += "/";

                        scanRemoteFolder(odc, remoteItem, relFullItemName);
                    }
                    else if (remoteItem.File != null)
                    {
                        if (!testFilePattern(relFullItemName, false))
                        {
                            continue;
                        }

                        fh = setRemoteFileEntry(relFullItemName, remoteItem);
                        addLog(!fh.remoteChanged, string.Format("r\tDatei: \"{0}\" ({1}, {2}, {3})", remoteItem.Name, fh.remoteChanged ? "1" : "0", fh.remoteWriteTime.ToString(), fh.remote_cTag));
                    }
                    else
                    {
                        if (!testFilePattern(relFullItemName, false))
                        {
                            continue;
                        }

                        bool isOneNote = remoteItem.AdditionalData != null && remoteItem.AdditionalData["package"] != null &&
                                         remoteItem.AdditionalData["package"] is Newtonsoft.Json.Linq.JObject &&
                                         ((Newtonsoft.Json.Linq.JObject)remoteItem.AdditionalData["package"]).GetValue("type").ToString() == "oneNote";
                        addLog(false, "HINWEIS: Datei wird übersprungen: " + relRemoteFolder + remoteItem.Name + (isOneNote ? " (OneNote Datei kann nicht gesichert werden)" : " (Inhaltstyp unbekannt)"));
                    }
                }

                if (childs.NextPageRequest != null)
                {
                    childs = childs.NextPageRequest.GetAsync().Result;
                    continue;
                }
                break;
            }
        }
예제 #17
0
        public void Initialize()
        {
            var authorization = new AuthenticationProvider();

            var oneDriveClient = new OneDriveClient(
                "https://api.onedrive.com/v1.0",
                authorization);
            //, this.httpProvider.Object);
        }
예제 #18
0
        public static void ClassInitialize(TestContext testContext)
        {
            if (!GlobalTestSettings.RunNetworkTests)
            {
                return;
            }

            string tokenFilePath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
                "SyncProTesting",
                "OneDriveTestingToken.json");

            if (!File.Exists(tokenFilePath))
            {
                string  tokenHelperPath = "OneDriveTokenHelper.exe";
                Process p = Process.Start(tokenHelperPath, "/getToken /path \"" + tokenFilePath + "\"");
                Pre.Assert(p != null, "p != null");
                p.WaitForExit();

                if (p.ExitCode != 1)
                {
                    throw new Exception("Failed to get token using OneDriveTokenHelper");
                }

                //throw new FileNotFoundException("Token file was not present at path " + tokenFilePath);
            }

            string tokenContent = File.ReadAllText(tokenFilePath);

            var token = JsonConvert.DeserializeObject <TokenResponse>(tokenContent);

            if (!token.IsEncrypted)
            {
                // The token file is NOT encrypted. Immediately encrypt and  save the file back to disk
                // for security before using it.
                token.Protect();
                tokenContent = JsonConvert.SerializeObject(token, Formatting.Indented);
                File.WriteAllText(tokenFilePath, tokenContent);
            }

            // The token file on disk is encrypted. Decrypt the values for in-memory use.
            token.Unprotect();

            using (OneDriveClient client = new OneDriveClient(token))
            {
                client.TokenRefreshed += (sender, args) =>
                {
                    // The token was refreshed, so save a protected copy of the token to the token file.
                    token = args.NewToken;
                    token.SaveProtectedToken(tokenFilePath);
                };

                client.GetUserProfileAsync().Wait();
            }

            classCurrentToken = token;
        }
        public void Constructor_BaseAddress_MustBeAsSpected()
        {
            var client = new OneDriveClient(TokenBuilder.Create().Build());

            var expected = "https://graph.microsoft.com/v1.0/";
            var value    = client._HttpClient.BaseAddress.AbsoluteUri;

            Assert.Equal(expected, value);
        }
예제 #20
0
        private void SignIn(object obj)
        {
            string logoutUri        = OneDriveClient.GetDefaultLogoutUri();
            string authorizationUri = OneDriveClient.GetDefaultAuthorizationUri();

            AuthenticationResult        authenticationResult = null;
            BrowserAuthenticationWindow authWindow           = new BrowserAuthenticationWindow();

            authWindow.Browser.Navigated += (sender, args) =>
            {
                if (string.Equals(args.Uri.AbsolutePath, "/oauth20_logout.srf", StringComparison.OrdinalIgnoreCase))
                {
                    // The logout page has finished loading, so we can now load the login page.
                    authWindow.Browser.Navigate(authorizationUri);
                }

                // If the browser is directed to the redirect URI, the new URI will contain the access code that we can use to
                // get a token for OneDrive.
                if (string.Equals(args.Uri.AbsolutePath, "ietf:wg:oauth:2.0:oob", StringComparison.OrdinalIgnoreCase))
                {
                    // We were directed back to the redirect URI. Extract the code from the query string
                    Dictionary <string, string> queryParametes = args.Uri.GetQueryParameters();

                    if (queryParametes.ContainsKey("code"))
                    {
                        authenticationResult = new AuthenticationResult()
                        {
                            Code = queryParametes["code"]
                        };
                    }

                    // All done. Close the window.
                    authWindow.Close();
                }
            };

            authWindow.Closed += (sender, args) =>
            {
                if (authenticationResult == null)
                {
                    return;
                }

                this.CanSignIn     = false;
                this.SignInMessage = "Working...";
                this.Adapter.SignIn(authenticationResult).ContinueWith(t => this.SetSignInStatus());
            };

            authWindow.Loaded += (sender, args) =>
            {
                authWindow.Browser.Navigate(logoutUri);
                NativeMethods.User32.SetForegroundWindow(new WindowInteropHelper(authWindow).Handle);
            };

            authWindow.ShowDialog();
        }
        private async Task SignIn(ClientType clientType)
        {
            if (this.oneDriveClient == null)
            {
                this.oneDriveClient = clientType == ClientType.Consumer
                    ? OneDriveClient.GetMicrosoftAccountClient(
                    FormBrowser.MsaClientId,
                    FormBrowser.MsaReturnUrl,
                    FormBrowser.Scopes,
                    webAuthenticationUi: new FormsWebAuthenticationUi())
                    : BusinessClientExtensions.GetClient(
                    new BusinessAppConfig
                {
                    ActiveDirectoryAppId     = FormBrowser.AadClientId,
                    ActiveDirectoryReturnUrl = FormBrowser.AadReturnUrl,
                });
            }

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

                await LoadFolderFromPath();

                UpdateConnectedStateUx(true);
            }
            catch (OneDriveException exception)
            {
                // Swallow authentication cancelled exceptions, but reset the client
                if (!exception.IsMatch(OneDriveErrorCode.AuthenticationCancelled.ToString()))
                {
                    if (exception.IsMatch(OneDriveErrorCode.AuthenticationFailure.ToString()))
                    {
                        MessageBox.Show(
                            "Authentication failed",
                            "Authentication failed",
                            MessageBoxButtons.OK);

                        ((OneDriveClient)this.oneDriveClient).Dispose();
                        this.oneDriveClient = null;
                    }
                    else
                    {
                        PresentOneDriveException(exception);
                    }
                }
                else
                {
                    ((OneDriveClient)this.oneDriveClient).Dispose();
                    this.oneDriveClient = null;
                }
            }
        }
예제 #22
0
        internal async void Authenticate()
        {
            MsaAuthenticationProvider msaAuthProvider = new MsaAuthenticationProvider(clientID, "https://login.live.com/oauth20_desktop.srf", scopes);

            await msaAuthProvider.AuthenticateUserAsync();

            OneDriveClient oneDriveClient = new OneDriveClient("https://api.onedrive.com/v1.0", msaAuthProvider);

            OneDriveClient = oneDriveClient;
        }
예제 #23
0
        private async Task SilentAuthenticate()
        {
            if (authenticator == null)
            {
                InitAuthenticator();
            }
            await authenticator.RestoreMostRecentFromCacheAsync();

            client = new OneDriveClient("https://api.onedrive.com/v1.0", authenticator);
        }
예제 #24
0
        public OneDriveFileSystem()
        {
            var client = new OneDriveClient();

            client.ApplicationId         = "000000004418B915";
            client.AuthorizationProvider = new AuthorizationCodeProvider();
            client.RefreshTokenHandler   = new MemoryRefreshTokenHandler();

            Client = client;
        }
예제 #25
0
        /*
         * One Drive Initialization - Uses the Web Forms Authenticator
         */
        public async void initOneDriveAPI()
        {
            oneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
                onedrive_client_id,
                onedrive_redirect_uri,
                onedrive_scope,
                webAuthenticationUi: new FormsWebAuthenticationUi()
                );

            Console.WriteLine("OneDrive auth? " + oneDriveClient.IsAuthenticated);
        }
예제 #26
0
        public async void Starter(string accessToken)
        {
            string[] scopes = new string[] { "onedrive.readonly", "wl.signin" };
            var      msaAuthenticationProvider = new MsaAuthenticationProvider(accessToken,
                                                                               "https://login.live.com/oauth20_desktop.srf",
                                                                               scopes);
            await msaAuthenticationProvider.AuthenticateUserAsync();

            oneDriveClient = new OneDriveClient(msaAuthenticationProvider);

            Getroot();
        }
예제 #27
0
        // public OneDriveService inse = Microsoft.Toolkit.Services.OneDrive.OneDriveService.Instance.Initialize( appClientId:OneDriveService., scopes, null, null);

        private async void btn_Login_Click(object sender, RoutedEventArgs e)
        {
            if (this.oneDriveClient == null)
            {
                try
                {
                    // Setting up the client here, passing in our Client Id, Return Url,
                    // Scopes that we want permission to, and building a Web Broker to
                    // go do our authentication.



                    this.oneDriveClient = await OneDriveClient.GetAuthenticatedMicrosoftAccountClient(
                        clientId,
                        returnUrl,
                        scopes,
                        webAuthenticationUi : new WebAuthenticationBrokerWebAuthenticationUi());



                    // Show in text box that we are connected.
                    txtBox_Response.Text = "We are now connected";

                    // We are either just autheticated and connected or we already connected,
                    // either way we need the drive button now.
                    btn_GetDriveId.Visibility = Visibility.Visible;
                }
                catch (OneDriveException exception)
                {
                    // Eating the authentication cancelled exceptions and resetting our client.
                    if (!exception.IsMatch(OneDriveErrorCode.AuthenticationCancelled.ToString()))
                    {
                        if (exception.IsMatch(OneDriveErrorCode.AuthenticationFailure.ToString()))
                        {
                            txtBox_Response.Text = "Authentication failed/cancelled, disposing of the client...";

                            ((OneDriveClient)this.oneDriveClient).Dispose();
                            this.oneDriveClient = null;
                        }
                        else
                        {
                            // Or we failed due to someother reason, let get that exception printed out.
                            txtBox_Response.Text = exception.Error.ToString();
                        }
                    }
                    else
                    {
                        ((OneDriveClient)this.oneDriveClient).Dispose();
                        this.oneDriveClient = null;
                    }
                }
            }
        }
예제 #28
0
 public static async Task <IOneDriveClient> GetOneDriveClientForAccountAsync(Account account)
 {
     try
     {
         return(await OneDriveClient.GetSilentlyAuthenticatedMicrosoftAccountClient(AppClientID, RedirectUri, Scopes, AppClientSecret, account.RefreshToken));
     }
     catch (OneDriveException ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.ToString());
     }
     return(null);
 }
예제 #29
0
        private async void ExecuteSingIn()
        {
            if (this._OneDriveClient == null)
            {
                this._OneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
                    ClientId,
                    ReturnUrl,
                    Scopes,
                    webAuthenticationUi: new FormsWebAuthenticationUi());
            }

            try
            {
                if (!this._OneDriveClient.IsAuthenticated)
                {
                    await this._OneDriveClient.AuthenticateAsync();
                }

                if (this._OneDriveClient.IsAuthenticated)
                {
                    MessageBox.Show(
                        "Authentication was successful",
                        "Authentication was successful",
                        MessageBoxButton.OK);
                }
            }
            catch (OneDriveException exception)
            {
                if (!exception.IsMatch(OneDriveErrorCode.AuthenticationCancelled.ToString()))
                {
                    if (exception.IsMatch(OneDriveErrorCode.AuthenticationFailure.ToString()))
                    {
                        MessageBox.Show(
                            "Authentication failed",
                            "Authentication failed",
                            MessageBoxButton.OK);

                        var httpProvider = this._OneDriveClient.HttpProvider as HttpProvider;
                        if (httpProvider != null)
                        {
                            httpProvider.Dispose();
                        }

                        this._OneDriveClient = null;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
예제 #30
0
        /// <summary>
        /// 認証が完了した時
        /// </summary>
        /// <param name="sender">送信者</param>
        /// <param name="e">イベント</param>
        public async void OnAuthenticationFinished(object sender, OneDriveAuthFinishedEventArgs e)
        {
            this.client = new OneDriveClient(e.Provider);
            this.OneDriveConnectionEstablished?.Invoke(this, new OneDriveConnectionEstablishedEventArgs(this.client));

            //var status = "ログインに成功しました\nRoot直下:\n";
            //var rootChildren = await this.client.Drive.Root.Children.Request().GetAsync();
            //foreach (var c in rootChildren)
            //{
            //	status += "    " + c.Name + "\n";
            //}
            //this.Status = status;
        }
        /// <summary>
        /// Signs user out of OneDrive.
        /// </summary>
        public async Task SignOutAsync()
        {
            try
            {
                await authProvider.SignOutAsync();

                drive = null;
            }
            finally
            {
                oneDriveClient = null;
            }
        }
        private static async Task<OneDriveClient> OnAuthComplete(LiveAuthClient authClient, AuthResult result)
        {
            if (null != result.AuthorizeCode)
            {
                try
                {
                    LiveConnectSession session = await authClient.ExchangeAuthCodeAsync(result.AuthorizeCode);
                    var OneDrive = new OneDriveClient(new LiveConnectClient(session));
                    return OneDrive;
                }
                catch (LiveAuthException aex)
                {
                    throw;
                }
                catch (LiveConnectException cex)
                {
                    throw;
                }
            }

            return null; ;
        }