public void TestGetNullPath()
 {
     var connectClient = new LiveConnectClient(new LiveConnectSession());
     try
     {
         connectClient.GetAsync(null);
         Assert.Fail("Expected ArguementNullException to be thrown.");
     }
     catch (ArgumentNullException)
     {
     }
 }
 public void TestGetWhiteSpaceStringPath()
 {
     var connectClient = new LiveConnectClient(new LiveConnectSession());
     try
     {
         connectClient.GetAsync("\t\n ");
         Assert.Fail("Expected ArguementException to be thrown.");
     }
     catch (ArgumentException)
     {
     }
 }
Exemple #3
0
 public static void checkSkyDriveInitiatedStart(object sender, RoutedEventArgs e)
 {
     //Check to see if user is logged in
     if (SkyDrive.Properties.LoggedIn)
     {
         //Check to see if SkyDrive is initiated for UltiDrive
         LiveConnectClient client = new LiveConnectClient(SkyDrive.Properties.session);
         client.GetCompleted += skydrive_checkInitiated;
         client.GetAsync("me/skydrive/files"); //Get list of files in root directory of SkyDrive.
         //END Check to see if SkyDrive is initiated for UltiDrive
     }
 }
 private void btnListAllFiles_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         LiveConnectClient liveClient = new LiveConnectClient(Properties.session);
         liveClient.GetCompleted += this.ConnectClient_GetCompleted;
         liveClient.GetAsync("me/skydrive/files");
     }
     catch (LiveConnectException exception)
     {
         txtTestBox.Text = "Error getting folder info: " + exception.Message;
     }
 }
Exemple #5
0
        public static bool DeleteFile(string guid)
        {
            validateSession();
            try
            {
                guidToDeleteQueue.Enqueue(guid);
                LiveConnectClient client = new LiveConnectClient(Properties.session);
                client.GetCompleted += DeleteFileHelper;
                client.GetAsync(SkyDrive.Properties.UltiDriveFolderID + "/files");

                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return false;
            }
        }
        private async Task<LiveOperationResult> QueryUserData(LiveConnectClient client, string path)
        {
            try
            {
                return await client.GetAsync(path);
            }
            catch
            {
            }

            return null;
        }
        private async Task <IEnumerable <CatalogItemModel> > ReadAsync(string path)
        {
            List <CatalogItemModel> items = null;

            try
            {
                if (_skyDrive == null)
                {
                    _skyDrive = await _liveLogin.Login();
                }

                if (_skyDrive == null)
                {
                    throw new CatalogAuthorizationException(CatalogType.SkyDrive, path);
                }

                ChangeAccessToCatalog();

                _cancelSource = new CancellationTokenSource();
                var e = await _skyDrive.GetAsync(path, _cancelSource.Token);

                var skyDriveItems = new List <SkyDriveItem>();
                var data          = (List <object>)e.Result["data"];
                foreach (IDictionary <string, object> content in data)
                {
                    var          type = (string)content["type"];
                    SkyDriveItem item;
                    if (type == "folder")
                    {
                        item = new SkyDriveFolder
                        {
                            Id   = (string)content["id"],
                            Name = (string)content["name"]
                        };
                    }
                    else if (type == "file")
                    {
                        var name = (string)content["name"];

                        if (string.IsNullOrEmpty(_downloadController.GetBookType(name)))
                        {
                            continue;
                        }

                        item = new SkyDriveFile
                        {
                            Id   = (string)content["id"],
                            Name = name
                        };
                    }
                    else
                    {
                        continue;
                    }

                    skyDriveItems.Add(item);
                }

                var folders = skyDriveItems
                              .OfType <SkyDriveFolder>()
                              .Select(i => new CatalogItemModel
                {
                    Title   = i.Name,
                    OpdsUrl = i.Id
                });

                var files = skyDriveItems
                            .OfType <SkyDriveFile>()
                            .Select(file => new CatalogBookItemModel
                {
                    Title   = file.Name,
                    OpdsUrl = file.Id,
                    Links   = new List <BookDownloadLinkModel>
                    {
                        new BookDownloadLinkModel
                        {
                            Url  = file.Id,
                            Type = file.Name
                        }
                    },
                    Id = file.Id
                });

                items = Enumerable.Union(folders, files).ToList();
            }
            catch (OperationCanceledException)
            {
            }
            catch (LiveAuthException e)
            {
                if (e.ErrorCode == "access_denied")
                {
                    throw new CatalogAuthorizationException(e.Message, e, CatalogType.SkyDrive);
                }
                throw new ReadCatalogException(e.Message, e);
            }
            catch (Exception e)
            {
                throw new ReadCatalogException(e.Message, e);
            }

            return(items ?? new List <CatalogItemModel>());
        }
Exemple #8
0
        // Authenticate the user via Microsoft Account (the default on Windows Phone)
        // Authentication via Facebook, Twitter or Google ID will be added in a future release.
        private async Task Authenticate()
        {
            prgBusy.IsActive = true;
            Exception exception = null;

            try
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    TextUserName.Text = "Please wait while we log you in...";
                });

                LiveAuthClient liveIdClient = new LiveAuthClient(ConfigSecrets.AzureMobileServicesURI);

                while (session == null)
                {
                    // Force a logout to make it easier to test with multiple Microsoft Accounts
                    // This code should be commented for the release build
                    //if (liveIdClient.CanLogout)
                    //    liveIdClient.Logout();

                    // Microsoft Account Login
                    LiveLoginResult result = await liveIdClient.LoginAsync(new[] { "wl.basic" });

                    if (result.Status == LiveConnectSessionStatus.Connected)
                    {
                        session = result.Session;
                        LiveConnectClient   client   = new LiveConnectClient(result.Session);
                        LiveOperationResult meResult = await client.GetAsync("me");

                        user = await App.MobileService
                               .LoginWithMicrosoftAccountAsync(result.Session.AuthenticationToken);

                        userfirstname = meResult.Result["first_name"].ToString();
                        userlastname  = meResult.Result["last_name"].ToString();

                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            var message       = string.Format("Logged in as {0} {1}", userfirstname, userlastname);
                            TextUserName.Text = message;
                        });

                        // Debugging dialog, make sure it's commented for publishing
                        //var dialog = new MessageDialog(message, "Welcome!");
                        //dialog.Commands.Add(new UICommand("OK"));
                        //await dialog.ShowAsync();
                        isLoggedin = true;
                        SetUIState(true);
                    }
                    else
                    {
                        session = null;
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            UpdateStatus("You must log in before you can chat in this app.", true);
                            var dialog = new MessageDialog("You must log in.", "Login Required");
                            dialog.Commands.Add(new UICommand("OK"));
                            dialog.ShowAsync();
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null)
            {
                UpdateStatus("Something went wrong when trying to log you in.", true);
                string msg1 = "An error has occurred while trying to sign you in." + Environment.NewLine + Environment.NewLine;

                // TO DO: Dissect the various potential errors and provide a more appropriate
                //        error message in msg2 for each of them.
                string msg2 = "Make sure that you have an active Internet connection and try again.";

                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    new MessageDialog(msg1 + msg2, "Authentication Error").ShowAsync();
                });
            }
            prgBusy.IsActive = false;
        }
Exemple #9
0
 private void skydrive_setUltiDriveFolderID(object sender, LiveOperationCompletedEventArgs e)
 {
     LiveConnectClient client = new LiveConnectClient(SkyDrive.Properties.session);
     client.GetCompleted += skydrive_checkInitiated;
     client.GetAsync("me/skydrive/files");
 }
Exemple #10
0
        private async Task <string> CreateDirectoryAsync(string folderName, string parentFolder, LiveConnectClient client)
        {
            string folderId = null;
            string queryFolder;
            LiveOperationResult opResult;

            //Retrieves all the directories.
            if (!parentFolder.Equals(CloudManagerUI.Properties.Resources.OneDriveRoot))
            {
                queryFolder = await GetSkyDriveFolderID(parentFolder, client) + "/files?filter=folders,albums";

                opResult = await client.GetAsync(queryFolder);
            }
            else
            {
                queryFolder = CloudManagerUI.Properties.Resources.OneDriveRoot + "/files?filter=folders,albums";
                opResult    = await client.GetAsync(queryFolder);
            }


            dynamic result = opResult.Result;

            foreach (dynamic folder in result.data)
            {
                //Checks if current folder has the passed name.
                if (folder.name.ToLowerInvariant() == folderName.ToLowerInvariant())
                {
                    folderId = folder.id;
                    break;
                }
            }

            if (folderId == null)
            {
                //Directory hasn't been found, so creates it using the PostAsync method.
                var folderData = new Dictionary <string, object>();
                folderData.Add("name", folderName);

                if (parentFolder.Equals(CloudManagerUI.Properties.Resources.OneDriveRoot))
                {
                    var opResultPostRoot = await client.GetAsync(CloudManagerUI.Properties.Resources.OneDriveRoot);

                    var iEnum = opResultPostRoot.Result.Values.GetEnumerator();
                    iEnum.MoveNext();
                    var id = iEnum.Current.ToString();


                    opResult = await client.PostAsync(id, folderData);
                }
                else
                {
                    var opResultPost = await GetSkyDriveFolderID(parentFolder, client);

                    opResult = await client.PostAsync(opResultPost, folderData);
                }

                result = opResult.Result;

                //Retrieves the id of the created folder.
                folderId = result.id;
            }


            return(folderId);
        }
        private ODItemCollection GetFolderInformation(string pathWithOutChildren)
        {
            var result = Client.GetAsync(pathWithOutChildren + "/children").Result;

            return(JsonConvert.DeserializeObject <ODItemCollection>(result.RawResult));
        }
        async void skydriveList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SkyDriveListItem item = this.skydriveList.SelectedItem as SkyDriveListItem;

            if (item == null)
            {
                return;
            }

            ROMDatabase db = ROMDatabase.Current;

            if (App.IsTrial && (db.GetNumberOfROMs() + this.downloadsInProgress) >= 2)
            {
                this.skydriveList.SelectedItem = null;
                this.ShowBuyDialog();
                return;
            }

            try
            {
                LiveConnectClient client = new LiveConnectClient(this.session);
                if (item.Type == SkyDriveItemType.Folder)
                {
                    if (this.session != null)
                    {
                        this.skydriveList.ItemsSource = null;
                        this.currentFolderBox.Text    = item.Name;
                        LiveOperationResult result = await client.GetAsync(item.SkyDriveID + "/files");

                        this.client_GetCompleted(result);
                    }
                }
                else if (item.Type == SkyDriveItemType.ROM)
                {
                    // Download
                    if (!item.Downloading)
                    {
                        try
                        {
                            this.downloadsInProgress++;
                            item.Downloading = true;
                            await this.DownloadFile(item, client);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(String.Format(AppResources.DownloadErrorText, item.Name, ex.Message), AppResources.ErrorCaption, MessageBoxButton.OK);
                        }
                        finally
                        {
                            this.downloadsInProgress--;
                        }
                    }
                    else
                    {
                        MessageBox.Show(AppResources.AlreadyDownloadingText, AppResources.ErrorCaption, MessageBoxButton.OK);
                    }
                }
                this.statusLabel.Height = 0;
            }
            catch (LiveConnectException)
            {
                this.statusLabel.Height = this.labelHeight;
                this.statusLabel.Text   = AppResources.SkyDriveInternetLost;
            }
        }
Exemple #13
0
        /// <summary>
        /// Get the ID of the requested folder
        /// </summary>
        /// <param name="Foldername"></param>
        /// <param name="Create"></param>
        /// <returns></returns>
        public static async Task <string> GetFolderIDAsync(string Foldername, bool Create)
        {
            try
            {
                string queryString = "me/skydrive/files?filter=folders";

                //  get all folders
                LiveOperationResult loResults;
                System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource();

                try
                {
                    //Wait for 5 seconds.
                    var awaitableTask = liveClient.GetAsync(queryString, cts.Token);
                    int i             = 50;
                    while (awaitableTask.Status == TaskStatus.Running || awaitableTask.Status == TaskStatus.WaitingForActivation)
                    {
                        await Task.Delay(100);

                        i--;

                        if (i == 0)
                        {
                            cts.Cancel();
                            return(String.Empty);
                        }
                    }

                    loResults = awaitableTask.Result;
                }
                catch (Exception e)
                {
                    throw new OperationCanceledException(e.Message);
                }

                //LiveOperationResult loResults = await liveClient.GetAsync(queryString);
                dynamic folders = loResults.Result;

                foreach (dynamic folder in folders.data)
                {
                    if (string.Compare(folder.name, Foldername, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        //  found our folder
                        return(folder.id);
                    }
                }

                //  folder not found
                if (Create)
                {
                    //  create folder
                    Dictionary <string, object> folderDetails = new Dictionary <string, object>();
                    folderDetails.Add("name", Foldername);
                    loResults = await liveClient.PostAsync("me/skydrive", folderDetails);

                    folders = loResults.Result;

                    // return folder id
                    return(folders.id);
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(String.Empty);
        }
Exemple #14
0
        // Autentica al usuario a través de una cuenta de Microsoft (cuenta por defecto en Windows Phone)
        // Autenticación a través de Facebook, Twitter o Google se agregará en una versión futura.
        private async Task Authenticate()
        {
            prgBusy.IsActive = true;
            Exception exception = null;

            try
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    TextUserName.Text = "Por favor, espera mientras inicias sesión...";
                });


                LiveAuthClient liveIdClient = new LiveAuthClient(Configuracion.AzureMobileServicesURI);

                while (session == null)
                {
                    // Inicio de sesión en Microsoft Account
                    LiveLoginResult result = await liveIdClient.LoginAsync(new[] { "wl.basic" });

                    if (result.Status == LiveConnectSessionStatus.Connected)
                    {
                        session = result.Session;
                        LiveConnectClient   client   = new LiveConnectClient(result.Session);
                        LiveOperationResult meResult = await client.GetAsync("me");

                        user = await App.MobileService
                               .LoginWithMicrosoftAccountAsync(result.Session.AuthenticationToken);

                        userfirstname = meResult.Result["first_name"].ToString();
                        userlastname  = meResult.Result["last_name"].ToString();

                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            var message       = string.Format("Autenticado como: {0} {1}", userfirstname, userlastname);
                            TextUserName.Text = message;
                        });

                        isLoggedin = true;
                        SetUIState(true);
                    }
                    else
                    {
                        session = null;
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            UpdateStatus("Debes de iniciar sesión antes de que puedas usar esta aplicación.", true);
                            var dialog = new MessageDialog("Debes iniciar sesión.", "Inicio de sesión requerido.");
                            dialog.Commands.Add(new UICommand("OK"));
                            dialog.ShowAsync();
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null)
            {
                UpdateStatus("Algo salió mal al tratar de iniciar sesión.", true);
                string msg1 = "Se ha producido un error al intentar iniciar sesión." + Environment.NewLine + Environment.NewLine;

                // TO DO: Dividir los distintos errores y ofrecer un adecuado
                // Mensaje de error en msg2 para cada uno.
                string msg2 = "Asegúrate de que tienes una conexión a Internet activa y vuelve a intentarlo.";

                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    new MessageDialog(msg1 + msg2, "Error de Autenticación").ShowAsync();
                });
            }
            prgBusy.IsActive = false;
        }
Exemple #15
0
        private async void RunButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Validate parameters
                string path        = pathTextBox.Text;
                string destination = destinationTextBox.Text;
                string requestBody = requestBodyTextBox.Text;
                var    scope       = (authScopesComboBox.SelectedValue as ComboBoxItem).Content as string;
                var    method      = (methodsComboBox.SelectedValue as ComboBoxItem).Content as string;

                // acquire auth permissions
                var authClient = new LiveAuthClient();
                var authResult = await authClient.LoginAsync(new string[] { scope });

                if (authResult.Session == null)
                {
                    throw new InvalidOperationException("You need to login and give permission to the app.");
                }

                var liveConnectClient = new LiveConnectClient(authResult.Session);
                LiveOperationResult operationResult = null;
                switch (method)
                {
                case "GET":
                    operationResult = await liveConnectClient.GetAsync(path);

                    break;

                case "POST":
                    operationResult = await liveConnectClient.PostAsync(path, requestBody);

                    break;

                case "PUT":
                    operationResult = await liveConnectClient.PutAsync(path, requestBody);

                    break;

                case "DELETE":
                    operationResult = await liveConnectClient.DeleteAsync(path);

                    break;

                case "COPY":
                    operationResult = await liveConnectClient.CopyAsync(path, destination);

                    break;

                case "MOVE":
                    operationResult = await liveConnectClient.MoveAsync(path, destination);

                    break;
                }

                if (operationResult != null)
                {
                    Log("Operation succeeded: \r\n" + operationResult.RawResult);
                }
            }
            catch (Exception ex)
            {
                Log("Got error: " + ex.Message);
            }
        }
Exemple #16
0
        protected async override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (BrowseSkyDrive.FileID != "0")
            {
                fileLocation = BrowseSkyDrive.FileID;
                //                lcc = new LiveConnectClient(CoreConcepts.BrowseSkyDrive.Session);
                lcc = new LiveConnectClient(session);
                //while (lcc == null)
                //{
                //    Thread.Sleep(1000);
                //}
                this.progressBar.Value = 0;
                //               lcc=CoreConcepts.BrowseSkyDrive.
                //if (lcc == null)
                //{
                //    MessageBox.Show("首先,你要登陆....");
                //    return;
                //}
                var progressHandler = new Progress <LiveOperationProgress>((LiveOperationProgress progress) =>
                {
                    this.progressBar.Value = progress.ProgressPercentage;
                });
                try
                {
                    LiveOperationResult operationResult =
                        await lcc.GetAsync(fileLocation);

                    dynamic result = operationResult.Result;
                    //       this.infoTextBlock.Text = string.Join(" ", "File name:", result.name, "ID:", result.id);
                    LiveDownloadOperationResult downloadOperationResult =
                        await this.lcc.DownloadAsync(result.source, new CancellationToken(false), progressHandler);

                    using (Stream downloadStream = downloadOperationResult.Stream)
                    {
                        if (downloadStream != null)
                        {
                            using (IsolatedStorageFileStream file = storage.CreateFile("temp.zip"))
                            {
                                int    chunkSize = 4096;
                                byte[] bytes     = new byte[chunkSize];
                                int    byteCount;

                                while ((byteCount = downloadStream.Read(bytes, 0, chunkSize)) > 0)
                                {
                                    file.Write(bytes, 0, byteCount);
                                }
                                file.Close();
                            }
                            //                        MessageBox.Show("成功下载备份,正在准备解压……");
                            this.Dispatcher.BeginInvoke(() =>
                            {
                                ToastPrompt toast = new ToastPrompt();     //实例化
                                toast.Height      = 100;
                                //toast.Title = "通知"; //设置标题
                                toast.Message         = UVEngine.Resources.UVEngine.downloaded;       //设置正文消息
                                toast.FontSize        = 30;                                           //设置文本大小(可选)
                                toast.TextOrientation = System.Windows.Controls.Orientation.Vertical; //设置呈现为纵向
                                toast.Show();
                            });
                            if (DeCompress("temp.zip", "/"))
                            {
                                storage.DeleteFile("temp.zip");
                                ToastPrompt t = new ToastPrompt(); //实例化
                                t.Height = 100;
                                //toast.Title = "通知"; //设置标题
                                t.Message         = UVEngine.Resources.UVEngine.restorecompleted; //设置正文消息
                                t.FontSize        = 40;                                           //设置文本大小(可选)
                                t.TextOrientation = System.Windows.Controls.Orientation.Vertical; //设置呈现为纵向
                                t.Show();
                                //MessageBox.Show("存档恢复成功");
                            }
                            else
                            {
                                MessageBox.Show("Failed");
                            }
                        }
                        else
                        {
                            //MessageBox.Show("Stream Null Error");
                            MessageBox.Show("An Error Occurred...");
                        }
                    }
                }
                catch (Exception Ex)
                {
                    MessageBox.Show("以下为错误信息\n" + Ex.Message, "错误", MessageBoxButton.OK);
                }
                this.NavigationService.RemoveBackEntry();
            }
        }