public StreamCopyOperation(
            LiveConnectClient client, 
            ApiMethod method, 
            Stream inputStream, 
            Stream outputStream, 
            long contentLength, 
            object progress,
            SynchronizationContextWrapper syncContext, 
            Action<bool, Exception> onCopyCompleted)
            : base(syncContext)
        {
            Debug.Assert(client != null, "client must not be null.");
            Debug.Assert(
                method == ApiMethod.Download || method == ApiMethod.Upload,
                "Only Download and Upload methods are allowed.");
            Debug.Assert(inputStream.CanRead, "Input stream is not readable.");
            Debug.Assert(outputStream.CanWrite, "Output stream is not writable.");

            this.LiveClient = client;
            this.Method = method;
            this.InputStream = inputStream;
            this.OutputStream = outputStream;
            this.ContentLength = contentLength;
            this.buffer = new byte[StreamCopyOperation.BufferSize];
            this.copyCompletedCallback = onCopyCompleted;
            this.progress = progress;
        }
예제 #2
0
        private void btnUploadDirectory_Click(object sender, RoutedEventArgs e)
        {
            //Show folder picker...
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.ShowDialog();
            //END Show folder picker...

            //Get a recusive list of all files...
            if (dialog.SelectedPath == "")
            {
                System.Windows.MessageBox.Show("No folder selected.");
                return;
            }
            string[] files = Directory.GetFiles(dialog.SelectedPath, "*.*", SearchOption.AllDirectories);

            foreach (string file in files)
            {
                txtRaw.Text += file + "\r\n";
                LiveConnectClient client = new LiveConnectClient(Properties.session);

                client.UploadCompleted += this.ConnectClient_UploadCompleted;
                var stream = default(Stream);
                stream = File.OpenRead(file);
                client.UploadAsync(Properties.UltiDriveFolderID + "/files", file, stream, stream);
                stream.Close();
                //System.Windows.MessageBox.Show(file);
            }
            //END Get a recursive list of all files...
        }
 /// <summary>
 /// Creates a new TailoredDownloadOperation instance.
 /// </summary>
 public CreateBackgroundDownloadOperation(
     LiveConnectClient client, 
     Uri url, 
     IStorageFile outputFile)
     : base(client, url, ApiMethod.Download, null, null)
 {
     this.OutputFile = outputFile;
 }
 public ForegroundUploadOperation(LiveConnectClient client, Uri url, string filename, IFileSource inputFile, OverwriteOption option, IProgress<LiveOperationProgress> progress, SynchronizationContextWrapper syncContext)
     : base(client, url, ApiMethod.Upload, null, syncContext)
 {
     this.Filename = filename;
     this.Progress = progress;
     this.OverwriteOption = option;
     this.FileSource = inputFile;
 }
 public DownloadOperation(
     LiveConnectClient client, 
     Uri url, 
     object progress, 
     SynchronizationContextWrapper syncContext)
     : base(client, url, ApiMethod.Download, null, syncContext)
 {
     this.progress = progress;
 }
 public ApiWriteOperation(
     LiveConnectClient client, 
     Uri url, 
     ApiMethod method, 
     string body, 
     SynchronizationContextWrapper syncContext)
     : base(client, url, method, body, syncContext)
 {
 }
 /// <summary>
 /// Creates a new TailoredDownloadOperation instance.
 /// </summary>
 public TailoredDownloadOperation(
     LiveConnectClient client, 
     Uri url, 
     IStorageFile outputFile, 
     IProgress<LiveOperationProgress> progress,
     SynchronizationContextWrapper syncContext)
     : base(client, url, ApiMethod.Download, null, syncContext)
 {
     this.OutputFile = outputFile;
     this.Progress = progress;
 }
 public GetUploadLinkOperation(
     LiveConnectClient client, 
     Uri url, 
     string fileName, 
     OverwriteOption option, 
     SynchronizationContextWrapper syncContext)
     : base(client, url, ApiMethod.Get, null, syncContext)
 {
     this.FileName = fileName;
     this.OverwriteOption = option;
 }
예제 #9
0
 /// <summary>
 /// Constructs a new ApiOperation object.
 /// </summary>
 public ApiOperation(
     LiveConnectClient client, 
     Uri url, 
     ApiMethod method, 
     string body, 
     SynchronizationContextWrapper syncContext)
     : base(url, body, syncContext)
 {
     this.Method = method;
     this.LiveClient = client;
 }
 public void TestDeleteNullPath()
 {
     var connectClient = new LiveConnectClient(new LiveConnectSession());
     try
     {
         connectClient.DeleteAsync(null);
         Assert.Fail("Expected ArguementNullException to be thrown.");
     }
     catch (ArgumentNullException)
     {
     }
 }
        public void TestExecute()
        {
            WebRequestFactory.Current = new TestWebRequestFactory();
            LiveConnectClient connectClient = new LiveConnectClient(new LiveConnectSession());
            Uri requestUri = new Uri("http://foo.com");
            string fileName = string.Empty;
            OverwriteOption overwriteOption = OverwriteOption.Overwrite;
            SynchronizationContextWrapper syncContextWrapper = SynchronizationContextWrapper.Current;

            var apiOperation =
                new GetUploadLinkOperation(connectClient, requestUri, fileName, overwriteOption, syncContextWrapper);
        }
        public void TestExecute()
        {
            WebRequestFactory.Current = new TestWebRequestFactory();
            var connectClient = new LiveConnectClient(new LiveConnectSession());
            var requestUrl = new Uri("http://foo.com");
            IStorageFile outputFile = new StorageFileStub();
            IProgress<LiveOperationProgress> progress = new Progress<LiveOperationProgress>();
            SynchronizationContextWrapper syncContext = SynchronizationContextWrapper.Current;

            var tailoredDownloadOperation =
                new TailoredDownloadOperation(connectClient, requestUrl, outputFile, progress, syncContext);
        }
        public void TestExecute()
        {
            WebRequestFactory.Current = new TestWebRequestFactory();
            LiveConnectClient connectClient = new LiveConnectClient(new LiveConnectSession());
            Uri requestUri = new Uri("http://foo.com");
            ApiMethod apiMethod = ApiMethod.Copy;
            string body = string.Empty;
            SynchronizationContextWrapper syncContextWrapper = SynchronizationContextWrapper.Current;

            var apiOperation =
                new ApiWriteOperation(connectClient, requestUri, apiMethod, body, syncContextWrapper);
        }
예제 #14
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
     }
 }
 public void TestGetWhiteSpaceStringPath()
 {
     var connectClient = new LiveConnectClient(new LiveConnectSession());
     try
     {
         connectClient.GetAsync("\t\n ");
         Assert.Fail("Expected ArguementException to be thrown.");
     }
     catch (ArgumentException)
     {
     }
 }
예제 #16
0
 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;
     }
 }
 /// <summary>
 /// This class implements the upload operation on Windows 8 using the background uploader.
 /// </summary>
 /// <remarks>This constructor is used when uploading a stream created by the application.</remarks>
 public TailoredUploadOperation(
     LiveConnectClient client,
     Uri url,
     string fileName,
     IInputStream inputStream,
     OverwriteOption option,
     IProgress<LiveOperationProgress> progress,
     SynchronizationContextWrapper syncContext)
     : this(client, url, fileName, option, progress, syncContext)
 {
     Debug.Assert(inputStream != null, "inputStream is null.");
     this.InputStream = inputStream;
 }
 /// <summary>
 /// This class implements the upload operation on Windows 8 using the background uploader.
 /// </summary>
 /// <remarks>This constructor is used when uploading a stream created by the application.</remarks>
 internal TailoredUploadOperation(
     LiveConnectClient client,
     Uri url,
     string fileName,
     OverwriteOption option,
     IProgress<LiveOperationProgress> progress,
     SynchronizationContextWrapper syncContext)
     : base(client, url, ApiMethod.Upload, null, syncContext)
 {
     this.FileName = fileName;
     this.Progress = progress;
     this.OverwriteOption = option;
 }
        /// <summary>
        /// This class implements the upload operation on Windows 8 using the background uploader.
        /// </summary>
        /// <remarks>This constructor is used when uploading a stream created by the application.</remarks>
        public CreateBackgroundUploadOperation(
            LiveConnectClient client,
            Uri url,
            string fileName,
            IInputStream inputStream,
            OverwriteOption option)
            : base(client, url, ApiMethod.Upload, null, null)
        {
            Debug.Assert(inputStream != null, "inputStream is null.");

            this.InputStream = inputStream;
            this.FileName = fileName;
            this.OverwriteOption = option;
        }
예제 #20
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;
            }
        }
예제 #21
0
        public UploadOperation(
            LiveConnectClient client, 
            Uri url, 
            string fileName,
            Stream inputStream, 
            OverwriteOption option,
            object progress,
            SynchronizationContextWrapper syncContext)
            : base(client, url, ApiMethod.Upload, null, syncContext)
        {
            this.FileName = fileName;
            this.OverwriteOption = option;
            this.InputStream = inputStream;
            this.progress = progress;

            this.totalBytesToSend = this.InputStream.CanSeek ?
                                    this.InputStream.Length :
                                    UploadOperation.UnknownFileSize;
        }
        public void TestExecuteMethod()
        {
            WebRequestFactory.Current = new TestWebRequestFactory();
            LiveConnectClient connectClient = new LiveConnectClient(new LiveConnectSession());
            Uri requestUri = new Uri("http://foo.com");
            string fileName = "fileName.txt";
            IStorageFile inputFile = new StorageFileStub();
            OverwriteOption option = OverwriteOption.Overwrite;
            IProgress<LiveOperationProgress> progress = new Progress<LiveOperationProgress>();
            SynchronizationContextWrapper syncContext = SynchronizationContextWrapper.Current;

            var tailoredUploadOperation = new TailoredUploadOperation(
                connectClient,
                requestUri,
                fileName,
                inputFile,
                option,
                progress,
                syncContext);
        }
예제 #23
0
        public async static Task <string> CreateDirectoryAsync(LiveConnectClient client,
                                                               string folderName, string parentFolder)
        {
            string folderId = null;

            // Retrieves all the directories.
            var queryFolder = parentFolder + "/files?filter=folders,albums";
            var 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);
                opResult = await client.PostAsync(parentFolder, folderData);

                result = opResult.Result;

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

            return(folderId);
        }
예제 #24
0
 private void OnSessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
 {
     this.liveClient = (e.Status == LiveConnectSessionStatus.Connected) ? new LiveConnectClient(e.Session) : null;
 }
예제 #25
0
        async void skydriveList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SkyDriveListItem item = this.skydriveList.SelectedItem as SkyDriveListItem;

            if (item == null)
            {
                return;
            }

            ROMDatabase db = ROMDatabase.Current;


            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.Zip || item.Type == SkyDriveItemType.Rar || item.Type == SkyDriveItemType.SevenZip)
                {
                    if (this.session != null)
                    {
                        this.skydriveList.ItemsSource = null;
                        this.currentFolderBox.Text    = item.Name;
                        this.downloadsInProgress++;

                        await this.DownloadFile(item, client);

                        try
                        {
                            List <SkyDriveListItem> listItems;

                            listItems = this.GetFilesInArchive(item);

                            this.skydriveStack.Add(listItems);
                            this.skydriveList.ItemsSource = listItems;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, AppResources.ErrorCaption, MessageBoxButton.OK);
                        }

                        this.downloadsInProgress--;
                    }
                }

                else if (item.Type == SkyDriveItemType.ROM)
                {
                    // Download
                    if (!item.Downloading)
                    {
                        this.downloadsInProgress++;
                        if (item.Stream == null)
                        {
                            await this.DownloadFile(item, client);
                        }


                        await ImportROM(item, this);

                        this.downloadsInProgress--;
                    }
                    else
                    {
                        MessageBox.Show(AppResources.AlreadyDownloadingText, AppResources.ErrorCaption, MessageBoxButton.OK);
                    }
                }
                else if (item.Type == SkyDriveItemType.Savestate || item.Type == SkyDriveItemType.SRAM)
                {
                    //check to make sure there is a rom with matching name
                    ROMDBEntry entry = null;

                    if (item.Type == SkyDriveItemType.Savestate)
                    {
                        entry = db.GetROMFromSavestateName(item.Name);
                    }
                    else if (item.Type == SkyDriveItemType.SRAM)
                    {
                        entry = db.GetROMFromSRAMName(item.Name);
                    }

                    if (entry == null) //no matching file name
                    {
                        MessageBox.Show(AppResources.NoMatchingNameText, AppResources.ErrorCaption, MessageBoxButton.OK);
                        return;
                    }

                    //determine the slot number
                    if (item.Type == SkyDriveItemType.Savestate)
                    {
                        string slot       = item.Name.Substring(item.Name.Length - 1, 1);
                        int    parsedSlot = 0;
                        if (!int.TryParse(slot, out parsedSlot))
                        {
                            MessageBox.Show(AppResources.ImportSavestateInvalidFormat, AppResources.ErrorCaption, MessageBoxButton.OK);
                            return;
                        }
                    }
                    // Download
                    if (!item.Downloading)
                    {
                        this.downloadsInProgress++;

                        if (item.Stream == null)
                        {
                            await this.DownloadFile(item, client);
                        }

                        await ImportSave(item, this);

                        this.downloadsInProgress--;
                    }
                    else
                    {
                        MessageBox.Show(AppResources.AlreadyDownloadingText, AppResources.ErrorCaption, MessageBoxButton.OK);
                    }
                }


                this.statusLabel.Height = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, AppResources.ErrorCaption, MessageBoxButton.OK);
            }
        }
예제 #26
0
 /// <summary>
 /// Create a new instance of the OneDrive client connected to a LiveConnect client that has signed in.
 /// </summary>
 /// <param name="client"></param>
 public OneDriveClient(LiveConnectClient client)
 {
     // We should validate that the client is actually signed in at this point.
     this.LiveClient = client;
 }
예제 #27
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;
        }
 internal static async Task <OneDriveInfoResult> CreateFolderInFolderAsync(this LiveConnectClient client, string desiredFolderName, string rootFolderId = RootFolderName)
 {
     return(await client.CreateFolderInFolderAsync(desiredFolderName, rootFolderId, CancellationToken.None));
 }
 public void TestMoveWhiteSpaceStringDestination()
 {
     var connectClient = new LiveConnectClient(new LiveConnectSession());
     try
     {
         connectClient.MoveAsync("fileId.123", "\t\n ");
         Assert.Fail("Expected ArguementException to be thrown.");
     }
     catch (ArgumentException)
     {
     }
 }
예제 #30
0
 public void MyTestCleanup()
 {
     this.authClient = null;
     this.apiClient  = null;
 }
예제 #31
0
        void ClientGetFolderList_GetCompleted(object sender, LiveOperationCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    bool          dataFolderExists = false;
                    List <object> data             = (List <object>)e.Result["data"];
                    foreach (IDictionary <string, object> dictionary in data)
                    {
                        if (string.IsNullOrEmpty(skyDriveFolderID))
                        {
                            if (dictionary.ContainsKey("name") && (string)dictionary["name"] == SettingsApi.SkyDriveFolderName &&
                                dictionary.ContainsKey("type") && (string)dictionary["type"] == "folder")
                            {
                                if (dictionary.ContainsKey("id"))
                                {
                                    skyDriveFolderID   = (string)dictionary["id"];
                                    dataFolderExists   = true;
                                    btBackup.IsEnabled = true;
                                    //tblInfo.Text = "Gotowy do baskup'u.";
                                    //tblDate.Text = "";
                                    //btBackup.IsEnabled = true;

                                    ////get the file ID's if they exist
                                    //client = new LiveConnectClient(App.Session);
                                    //client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(GetFiles_GetCompleted);
                                    //client.GetAsync(skyDriveFolderID + "/files"); //check through the files in the folder
                                    //break;
                                }
                            }
                        }
                    }

                    if (!dataFolderExists)
                    {
                        // create SkyDrive data folder
                        Dictionary <string, object> body = new Dictionary <string, object>();
                        body.Add("name", SettingsApi.SkyDriveFolderName);
                        object[] state = new object[2];
                        state[0] = "create folder";
                        state[1] = body["name"];

                        try
                        {
                            LiveConnectClient createFolderClient = new LiveConnectClient(App.Session);
                            createFolderClient.PostCompleted += new EventHandler <LiveOperationCompletedEventArgs>(CreateFolder_Completed);
                            _progressIndicator.IsVisible      = true;
                            _progressIndicator.Text           = "Tworzenie folderu...";
                            createFolderClient.PostAsync("/me/skydrive", body, state);
                        }
                        catch (Exception eCreateFolder)
                        {
                            _progressIndicator.IsVisible = false;
                            MessageBox.Show("Nie można utworzyć folderu na SkyDrive: " + eCreateFolder.Message);
                        }
                    }
                }
                else
                {
                    _progressIndicator.IsVisible = false;
                    MessageBox.Show("Problem z dostępem do SkyDrive: " + e.Error.Message);
                }
            }
            catch (Exception eFolder)
            {
                Debug.WriteLine("Błąd konfiguracji folderu: " + eFolder.Message);
            }
        }
 public void TestDeleteEmptyStringPath()
 {
     var connectClient = new LiveConnectClient(new LiveConnectSession());
     try
     {
         connectClient.DeleteAsync(string.Empty);
         Assert.Fail("Expected ArguementException to be thrown.");
     }
     catch (ArgumentException)
     {
     }
 }
예제 #33
0
        private async Task UploadFileToSkydrive(StorageFile file, string eventBuddyFolderId, LiveConnectClient client)
        {
            using (var stream = await file.OpenStreamForReadAsync())
            {
                var progressHandler = InitializeProgressBar();
                var hasErrors       = false;

                do
                {
                    try
                    {
                        hasErrors          = false;
                        this.retrySelected = false;
                        LiveOperationResult result = await client.BackgroundUploadAsync(eventBuddyFolderId, file.Name, stream.AsInputStream(), OverwriteOption.Overwrite, cancellationToken.Token, progressHandler);

                        this.FileNameTextBlock.Text = file.Name;
                        await UpdateSession(client, result);
                    }
                    catch (LiveConnectException)
                    {
                        hasErrors = true;
                    }

                    if (hasErrors)
                    {
                        var errorTitle = "Upload file error";
                        await ShowMessage(errorTitle, "Exception occured while trying to upload the " + file.Name + " file to Skydrive.");
                    }

                    uploadProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                } while(this.retrySelected);
            }
        }
예제 #34
0
        private async Task DownloadFile(SkyDriveListItem item, LiveConnectClient client)
        {
            StorageFolder folder    = ApplicationData.Current.LocalFolder;
            StorageFolder romFolder = await folder.CreateFolderAsync(FileHandler.ROM_DIRECTORY, CreationCollisionOption.OpenIfExists);

            StorageFolder saveFolder = await romFolder.CreateFolderAsync(FileHandler.SAVE_DIRECTORY, CreationCollisionOption.OpenIfExists);

            String path     = romFolder.Path;
            String savePath = saveFolder.Path;

            ROMDatabase db = ROMDatabase.Current;

            var indicator = SystemTray.GetProgressIndicator(this);

            indicator.IsIndeterminate = true;
            indicator.Text            = String.Format(AppResources.DownloadingProgressText, item.Name);

            LiveDownloadOperationResult e = await client.DownloadAsync(item.SkyDriveID + "/content");

            if (e != null)
            {
                byte[]      tmpBuf          = new byte[e.Stream.Length];
                StorageFile destinationFile = null;

                ROMDBEntry entry = null;

                if (item.Type == SkyDriveItemType.SRAM)
                {
                    entry = db.GetROMFromSRAMName(item.Name);
                    if (entry != null)
                    {
                        destinationFile = await saveFolder.CreateFileAsync(Path.GetFileNameWithoutExtension(entry.FileName) + ".sav", CreationCollisionOption.ReplaceExisting);
                    }

                    else
                    {
                        destinationFile = await saveFolder.CreateFileAsync(item.Name, CreationCollisionOption.ReplaceExisting);
                    }
                }
                else if (item.Type == SkyDriveItemType.Savestate)
                {
                    entry = db.GetROMFromSavestateName(item.Name);


                    if (entry != null)
                    {
                        destinationFile = await saveFolder.CreateFileAsync(Path.GetFileNameWithoutExtension(entry.FileName) + item.Name.Substring(item.Name.Length - 5), CreationCollisionOption.ReplaceExisting);
                    }
                    else
                    {
                        destinationFile = await saveFolder.CreateFileAsync(item.Name, CreationCollisionOption.ReplaceExisting);
                    }
                }

                using (IRandomAccessStream destStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
                    using (DataWriter writer = new DataWriter(destStream))
                    {
                        while (e.Stream.Read(tmpBuf, 0, tmpBuf.Length) != 0)
                        {
                            writer.WriteBytes(tmpBuf);
                        }
                        await writer.StoreAsync();

                        await writer.FlushAsync();

                        writer.DetachStream();
                    }
                e.Stream.Close();
                item.Downloading = false;

                if (item.Type == SkyDriveItemType.Savestate)
                {
                    String number = item.Name.Substring(item.Name.Length - 5, 1);
                    int    slot   = int.Parse(number);

                    if (entry != null) //NULL = do nothing
                    {
                        SavestateEntry saveentry = db.SavestateEntryExisting(entry.FileName, slot);
                        if (saveentry != null)
                        {
                            //delete entry
                            db.RemoveSavestateFromDB(saveentry);
                        }
                        SavestateEntry ssEntry = new SavestateEntry()
                        {
                            ROM      = entry,
                            Savetime = DateTime.Now,
                            Slot     = slot,
                            FileName = item.Name
                        };
                        db.Add(ssEntry);
                        db.CommitChanges();
                    }
                }

                MessageBox.Show(String.Format(AppResources.DownloadCompleteText, item.Name));
            }
            else
            {
                MessageBox.Show(String.Format(AppResources.DownloadErrorText, item.Name, "Api error"), AppResources.ErrorCaption, MessageBoxButton.OK);
            }

#if GBC
            indicator.Text = AppResources.ApplicationTitle2;
#else
            indicator.Text = AppResources.ApplicationTitle;
#endif
            indicator.IsIndeterminate = false;
        }
 public void TestBackgroundUploadNullPath()
 {
     var connectClient = new LiveConnectClient(new LiveConnectSession());
     try
     {
         var uploadLocation = new Uri("/shared/transfers/uploadLocation.txt", UriKind.RelativeOrAbsolute);
         connectClient.BackgroundUploadAsync(
             null,
             uploadLocation,
             OverwriteOption.Overwrite);
         Assert.Fail("Expected ArguementException to be thrown.");
     }
     catch (ArgumentException)
     {
     }
 }
        private async Task PopulateMSAccountData(MSAccountPageModel model, AccountDataContent content)
        {
            string errorText = null;
            LiveConnectClient client = new LiveConnectClient(this.MSAuthClient.Session);
            LiveOperationResult meResult = await QueryUserData(client, "me");
            if (meResult != null)
            {
                dynamic meInfo = meResult.Result;
                model.Name = meInfo.name;
                model.ProfileImage = await GetProfileImageData(client);
            }
            else
            {
                errorText = "There was an error while retrieving the user's information. Please try again later.";
            }

            if (errorText == null && 
                (content & AccountDataContent.Contacts) == AccountDataContent.Contacts)
            {
                LiveOperationResult contactsResult = await QueryUserData(client, "me/contacts");
                if (contactsResult != null)
                {
                    dynamic contacts = contactsResult.Result;
                    model.Contacts = contacts.data;
                }
                else
                {
                    errorText = "There was an error while retrieving the user's contacts data. Please try again later.";
                }
            }

            model.Error = errorText;
        }
예제 #37
0
        /// <summary>
        /// Gibt einen Isolated Storage Pfad zu einem Profilbild einer Person an.
        /// Bei Bedarf wird dieses erst von Server geladen.
        /// </summary>
        /// <param name="authenticationUserId">Nutzer dessen Profilbild geladen werden soll.</param>
        /// <returns></returns>
        internal static async Task <string> GetProfilePicture(string authenticationUserId)
        {
            if (authenticationUserId == null)
            {
                return(null);
            }
            try
            {
                string fileName = authenticationUserId + ".png";
                using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (file.FileExists(fileName))
                    {
                        //Wenn die Datei weniger als einen Monat alt ist vewende sie.
                        if ((file.GetCreationTime(fileName).DateTime - DateTime.Now) < TimeSpan.FromDays(30))
                        {
                            return(fileName);
                        }
                        else //Ansonsten löschen und neu downloaden, dadurch immer schön aktuell.
                        {
                            file.DeleteFile(fileName);
                        }
                    }

                    //LiveConnectClient bereitstellen
                    LiveConnectClient client = new LiveConnectClient(session);

                    //Pfad des Profilbildes von Windows Live abrufen.
                    var path = authenticationUserId + "/picture";

                    var task = client.DownloadAsync((string)(await client.GetAsync(path)).Result["location"]);
                    using (var fileStream = (await task).Stream)

                    //Filestream auf Platte abspeichern
                    {
                        using (FileStream fileStreamSave = file.CreateFile(fileName))
                        {
                            byte[] buffer = new byte[8 * 1024];
                            int    length;

                            while ((length = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                fileStreamSave.Write(buffer, 0, length);
                            }

                            fileStreamSave.Flush();
                        }
                    }

                    return(fileName);
                }
            }
            catch (Exception e)
            {
                //Wenn Debugger vorhanden ist, Fehler beachten ansonsten Silent einfach ohne Profilbild arbeiten.
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    throw new Exception("Could not load profile picture.", e);
                }
                else
                {
                    return(null);
                }
            }
        }
        private async void BackupFilesAndUpload(string _backupFileName)
        {
            if (_backupFileName == null)
            {
                throw new ArgumentNullException("_backupFileName");
            }
            //
            //
            string filename = _backupFileName;
            //byte[] b = new byte[0x16] {0x50,0x4b,0x05,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
            var b = new byte[0x16];

            b[0] = 0x50;
            b[1] = 0x4b;
            b[2] = 0x05;
            b[4] = 0x06;
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
                using (IsolatedStorageFileStream f = store.OpenFile(filename, FileMode.Create)) {
                    f.Write(b, 0, b.Length);
                }
            }


            using (var store = IsolatedStorageFile.GetUserStoreForApplication()) {
                using (var file = new IsolatedStorageFileStream(filename, FileMode.Create, store))
                {
                    var zz = new ZipOutputStream(file);
                    foreach (string f in store.GetFileNames())
                    {
                        if (f.Equals(filename))
                        {
                            continue;
                        }
                        var ze = new ZipEntry(f);
                        zz.PutNextEntry(ze);
                        using (IsolatedStorageFileStream ss = store.OpenFile(f, FileMode.Open))
                        {
                            var bytes = new byte[100];
                            int x     = ss.Read(bytes, 0, 100);
                            while (x > 0)
                            {
                                zz.Write(bytes, 0, x);
                                bytes = new byte[100];
                                x     = ss.Read(bytes, 0, 100);
                            }
                        }
                    }
                    zz.Finish();
                }
                try
                {
                    pbProgress.Value   = 0;
                    bBackup.IsEnabled  = false;
                    bRestore.IsEnabled = false;
                    var progressHandler = new Progress <LiveOperationProgress>(
                        (e) =>
                    {
                        pbProgress.Value      = e.ProgressPercentage;
                        pbProgress.Visibility = Visibility.Visible;
                        lblLastBackup.Text    =
                            string.Format(
                                StringResources
                                .BackupAndRestorePage_Messages_Progress,
                                e.BytesTransferred, e.TotalBytes);
                    });
                    _ctsUpload = new CancellationTokenSource();
                    _client    = new LiveConnectClient(App.LiveSession);
                    using (
                        var file = new IsolatedStorageFileStream(filename, FileMode.Open,
                                                                 FileAccess.Read, FileShare.Read,
                                                                 IsolatedStorageFile.GetUserStoreForApplication()))
                    {
                        await
                        _client.UploadAsync("me/skydrive", filename, file,
                                            OverwriteOption.Overwrite, _ctsUpload.Token,
                                            progressHandler);
                    }
                    pbProgress.Visibility = Visibility.Collapsed;
                }
                catch (TaskCanceledException)
                {
                    App.ToastMe("Upload Cancelled");
                }
                catch (LiveConnectException ee)
                {
                    lblLastBackup.Text = string.Format("Error uploading File:{0}",
                                                       ee.Message);
                }
                finally
                {
                    bBackup.IsEnabled  = true;
                    bRestore.IsEnabled = true;
                    lblLastBackup.Text = DateTime.Now.ToString("MM/dd/yyyy");
                }
            }
        }
 public static async Task <OneDriveInfoResult> GetItemsInFolderAsync(this LiveConnectClient client, string rootFolderId = ListFileCommandName)
 {
     return(await client.GetItemsInFolderAsync(rootFolderId, CancellationToken.None));
 }
예제 #40
0
 public RestClient(LiveConnectClient oauthClient)
 {
     OAuthClient = oauthClient;
 }
 public static async Task <OneDriveInfoResult> GetFolderInFolder(this LiveConnectClient client, string desiredFolderName, string rootFolderId = RootFolderName)
 {
     return(await client.GetFolderInFolder(desiredFolderName, rootFolderId, CancellationToken.None));
 }
예제 #42
0
        private async void OnAuthCompleted(AuthResult result)
        {
            this.CleanupAuthForm();
            if (result.AuthorizeCode != null)
            {
                try
                {
                    LiveConnectSession session = await this.AuthClient.ExchangeAuthCodeAsync(result.AuthorizeCode);
                    this.liveConnectClient = new LiveConnectClient(session);
                    LiveOperationResult meRs = await this.liveConnectClient.GetAsync("me");
                    dynamic meData = meRs.Result;
                    this.meNameLabel.Text = meData.name;

                    LiveDownloadOperationResult meImgResult = await this.liveConnectClient.DownloadAsync("me/picture");
                    this.mePictureBox.Image = Image.FromStream(meImgResult.Stream);
                }
                catch (LiveAuthException aex)
                {
                    this.LogOutput("Failed to retrieve access token. Error: " + aex.Message);
                }
                catch (LiveConnectException cex)
                {
                    this.LogOutput("Failed to retrieve the user's data. Error: " + cex.Message);
                }
            }
            else
            {
                this.LogOutput(string.Format("Error received. Error: {0} Detail: {1}", result.ErrorCode, result.ErrorDescription));
            }
        }
예제 #43
0
        private async void Export_Click(object sender, EventArgs e)
        {
            if (fileList.CheckedItems.Count == 0)
            {
                MessageBox.Show(AppResources.ExportNoSelection);
                return;
            }

            //can only export 1 file if use cloudsix
            if (backupMedium == "cloudsix" && fileList.CheckedItems.Count > 1 && ZipCheckBox.IsChecked.Value == false)
            {
                MessageBox.Show(AppResources.CloudSixOneFileLimitText);
                return;
            }

            if (this.uploading)
            {
                MessageBox.Show(AppResources.BackupWaitForUpload, AppResources.ErrorCaption, MessageBoxButton.OK);
                return;
            }

            //zip file if users choose to do so
            if (ZipCheckBox.IsChecked.Value)
            {
                using (ZipFile zip = new ZipFile())
                {
                    using (var iso = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        foreach (ExportFileItem file in fileList.CheckedItems)
                        {
                            IsolatedStorageFileStream fs = iso.OpenFile(file.Path, System.IO.FileMode.Open);
                            zip.AddEntry(file.Name, fs);
                        }

                        MemoryStream stream = new MemoryStream();
                        zip.Save(stream);

                        if (backupMedium == "cloudsix")
                        {
                            var saver = new CloudSixSaver(currentEntry.DisplayName + ".zip", stream);
                            await saver.Launch();
                        }
                        else if (backupMedium == "onedrive")
                        {
                            var indicator = SystemTray.GetProgressIndicator(this);
                            indicator.IsIndeterminate = true;

                            this.uploading = true;
                            bool errors = false;

                            try
                            {
                                LiveConnectClient client   = new LiveConnectClient(this.session);
                                String            folderID = await CreateExportFolder(client);

                                indicator.Text = String.Format(AppResources.UploadProgressText, currentEntry.DisplayName + ".zip");
                                stream.Seek(0, SeekOrigin.Begin);
                                await client.UploadAsync(folderID, currentEntry.DisplayName + ".zip", stream, OverwriteOption.Overwrite);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(String.Format(AppResources.BackupErrorUpload, ex.Message), AppResources.ErrorCaption, MessageBoxButton.OK);
                                errors = true;
                            }

                            this.uploading = false;

                            if (errors)
                            {
                                MessageBox.Show(AppResources.BackupUploadUnsuccessful, AppResources.ErrorCaption, MessageBoxButton.OK);
                            }
                            else
                            {
                                MessageBox.Show(AppResources.BackupUploadSuccessful);
                            }


#if GBC
                            indicator.Text = AppResources.ApplicationTitle2;
#else
                            indicator.Text = AppResources.ApplicationTitle;
#endif
                            indicator.IsIndeterminate = false;
                        } //end of if (backupMedium == "onedrive")

                        stream.Close();
                    }
                }
            }
            else //does not use zip function
            {
                using (var iso = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (backupMedium == "cloudsix")
                    {
                        ExportFileItem file = this.fileList.CheckedItems[0] as ExportFileItem;
                        using (IsolatedStorageFileStream fs = iso.OpenFile(file.Path, System.IO.FileMode.Open))
                        {
                            var saver = new CloudSixSaver(file.Name, fs);
                            await saver.Launch();
                        }
                    }
                    else if (backupMedium == "onedrive")
                    {
                        var indicator = SystemTray.GetProgressIndicator(this);
                        indicator.IsIndeterminate = true;

                        this.uploading = true;
                        bool errors = false;

                        try
                        {
                            LiveConnectClient client   = new LiveConnectClient(this.session);
                            String            folderID = await CreateExportFolder(client);

                            foreach (ExportFileItem file in this.fileList.CheckedItems)
                            {
                                indicator.Text = String.Format(AppResources.UploadProgressText, file.Name);

                                using (IsolatedStorageFileStream fs = iso.OpenFile(file.Path, System.IO.FileMode.Open))
                                {
                                    await client.UploadAsync(folderID, file.Name, fs, OverwriteOption.Overwrite);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(String.Format(AppResources.BackupErrorUpload, ex.Message), AppResources.ErrorCaption, MessageBoxButton.OK);
                            errors = true;
                        }

                        this.uploading = false;

                        if (errors)
                        {
                            MessageBox.Show(AppResources.BackupUploadUnsuccessful, AppResources.ErrorCaption, MessageBoxButton.OK);
                        }
                        else
                        {
                            MessageBox.Show(AppResources.BackupUploadSuccessful);
                        }


#if GBC
                        indicator.Text = AppResources.ApplicationTitle2;
#else
                        indicator.Text = AppResources.ApplicationTitle;
#endif
                        indicator.IsIndeterminate = false;
                    }
                } //IsolatedStorage
            }     //using zip upload or not
        }
예제 #44
0
        private async void MainForm_Load(object sender, EventArgs e)
        {
            this.methodComboBox.SelectedIndex = 0;
            this.scopeListBox.SelectedIndex = 0;

            try
            {
                LiveLoginResult loginResult = await this.AuthClient.InitializeAsync();
                if (loginResult.Session != null)
                {
                    this.liveConnectClient = new LiveConnectClient(loginResult.Session);
                }
            }
            catch (Exception ex)
            {
                this.LogOutput("Received an error during initializing. " + ex.Message);
            }
        }
예제 #45
0
        private async Task <LiveConnectSessionStatus> Connect(bool includeEmailAddress = false)
        {
            if (client != null)
            {
                return(LiveConnectSessionStatus.Connected);
            }

            LiveAuthException liveConnectException = null;

            try
            {
                var liveAuth       = new LiveAuthClient(Constants.MICROSOFT_LIVE_CLIENTID);
                var liveAuthResult = includeEmailAddress
                                        ? await liveAuth.InitializeAsync(new[]
                {
                    Constants.MICROSOFT_LIVE_SCOPE_BASIC,
                    Constants.MICROSOFT_LIVE_SCOPE_EMAILS,
                    Constants.MICROSOFT_LIVE_SCOPE_SIGNIN,
                    Constants.MICROSOFT_LIVE_SCOPE_OFFLINEACCESS,
                    Constants.MICROSOFT_LIVE_SCOPE_SKYDRIVE,
                    Constants.MICROSOFT_LIVE_SCOPE_SKYDRIVEUPDATE
                })
                                        : await liveAuth.InitializeAsync(new[]
                {
                    Constants.MICROSOFT_LIVE_SCOPE_BASIC,
                    Constants.MICROSOFT_LIVE_SCOPE_SIGNIN,
                    Constants.MICROSOFT_LIVE_SCOPE_OFFLINEACCESS,
                    Constants.MICROSOFT_LIVE_SCOPE_SKYDRIVE,
                    Constants.MICROSOFT_LIVE_SCOPE_SKYDRIVEUPDATE
                });

                if (liveAuthResult.Status == LiveConnectSessionStatus.Connected)
                {
                    client = CreateClientForSession(liveAuth.Session);
                }
                else
                {
                    liveAuthResult = includeEmailAddress
                                        ? await liveAuth.LoginAsync(new[]
                    {
                        Constants.MICROSOFT_LIVE_SCOPE_BASIC,
                        Constants.MICROSOFT_LIVE_SCOPE_EMAILS,
                        Constants.MICROSOFT_LIVE_SCOPE_SIGNIN,
                        Constants.MICROSOFT_LIVE_SCOPE_OFFLINEACCESS,
                        Constants.MICROSOFT_LIVE_SCOPE_SKYDRIVE,
                        Constants.MICROSOFT_LIVE_SCOPE_SKYDRIVEUPDATE
                    })
                                        : await liveAuth.LoginAsync(new[]
                    {
                        Constants.MICROSOFT_LIVE_SCOPE_BASIC,
                        Constants.MICROSOFT_LIVE_SCOPE_SIGNIN,
                        Constants.MICROSOFT_LIVE_SCOPE_OFFLINEACCESS,
                        Constants.MICROSOFT_LIVE_SCOPE_SKYDRIVE,
                        Constants.MICROSOFT_LIVE_SCOPE_SKYDRIVEUPDATE
                    });

                    client   = liveAuthResult.Status == LiveConnectSessionStatus.Connected ? CreateClientForSession(liveAuth.Session) : null;
                    meResult = null;
                }
                return(liveAuthResult.Status);
            }
            catch (TaskCanceledException)
            {
                client = null;
                return(LiveConnectSessionStatus.NotConnected);
            }
            catch (LiveAuthException ex)
            {
                if (ex.ErrorCode.Equals("access_denied", StringComparison.OrdinalIgnoreCase))
                {
                    client = null;
                    return(LiveConnectSessionStatus.NotConnected);
                }
                liveConnectException = ex;
            }
            if (liveConnectException != null)
            {
                var extraCrashData = new BugSense.Core.Model.LimitedCrashExtraDataList();
                extraCrashData.Add("ErrorCode", liveConnectException.ErrorCode);
                extraCrashData.Add("Message", liveConnectException.Message);
                await BugSenseHandler.Instance.LogExceptionAsync(liveConnectException, extraCrashData);
            }
            return(LiveConnectSessionStatus.Unknown);
        }
예제 #46
0
        private async Task DownloadFile(SkyDriveListItem item, LiveConnectClient client)
        {
            StorageFolder folder    = ApplicationData.Current.LocalFolder;
            StorageFolder romFolder = await folder.CreateFolderAsync(FileHandler.ROM_DIRECTORY, CreationCollisionOption.OpenIfExists);

            StorageFolder saveFolder = await romFolder.CreateFolderAsync(FileHandler.SAVE_DIRECTORY, CreationCollisionOption.OpenIfExists);

            String path     = romFolder.Path;
            String savePath = saveFolder.Path;

            ROMDatabase db        = ROMDatabase.Current;
            var         indicator = new ProgressIndicator()
            {
                IsIndeterminate = true,
                IsVisible       = true,
                Text            = String.Format(AppResources.DownloadingProgressText, item.Name)
            };

            SystemTray.SetProgressIndicator(this, indicator);

            LiveDownloadOperationResult e = await client.DownloadAsync(item.SkyDriveID + "/content");

            if (e != null)
            {
                byte[]      tmpBuf          = new byte[e.Stream.Length];
                StorageFile destinationFile = await saveFolder.CreateFileAsync(item.Name, CreationCollisionOption.ReplaceExisting);

                using (IRandomAccessStream destStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
                    using (DataWriter writer = new DataWriter(destStream))
                    {
                        while (e.Stream.Read(tmpBuf, 0, tmpBuf.Length) != 0)
                        {
                            writer.WriteBytes(tmpBuf);
                        }
                        await writer.StoreAsync();

                        await writer.FlushAsync();

                        writer.DetachStream();
                    }
                e.Stream.Close();
                item.Downloading = false;
                SystemTray.GetProgressIndicator(this).IsVisible = false;

                if (item.Type == SkyDriveItemType.Savestate)
                {
                    if (!db.SavestateEntryExisting(item.Name))
                    {
                        String     number = item.Name.Substring(item.Name.Length - 5, 1);
                        int        slot   = int.Parse(number);
                        ROMDBEntry entry  = db.GetROMFromSavestateName(item.Name);
                        // Null = No ROM existing for this file -> skip inserting into database. The file will be inserted when the corresponding ROM is downloaded.
                        if (entry != null)
                        {
                            SavestateEntry ssEntry = new SavestateEntry()
                            {
                                ROM      = entry,
                                Savetime = DateTime.Now,
                                Slot     = slot,
                                FileName = item.Name
                            };
                            db.Add(ssEntry);
                            db.CommitChanges();
                        }
                    }
                }

                MessageBox.Show(String.Format(AppResources.DownloadCompleteText, item.Name));
            }
            else
            {
                SystemTray.GetProgressIndicator(this).IsVisible = false;
                MessageBox.Show(String.Format(AppResources.DownloadErrorText, item.Name, "Api error"), AppResources.ErrorCaption, MessageBoxButton.OK);
            }
        }
예제 #47
0
 public LiveClient()
 {
     client             = null;
     trackTimerFolderId = null;
     meResult           = null;
 }
예제 #48
0
 public async Task DeleteCalendarEventAsync(String eventId)
 {
     // requires wl.calendars_update
     var client = new LiveConnectClient(_session);
     await client.DeleteAsync(eventId);
 }
예제 #49
0
        private async void SendFileToSkyDrive(LiveConnectClient client, String folder, ArticleContent content)
        {
            if (folder != null)
            {
                Dispatcher.BeginInvoke(() => AppUtils.ToastPromptShow("阅FM", "正在准备文件"));

                var store = IsolatedStorageFile.GetUserStoreForApplication();

                string filePath = "tmp.html";

                if (store.FileExists(filePath))
                {
                    store.DeleteFile(filePath);
                }

                var tmpfile = store.OpenFile(filePath,
                                             FileMode.OpenOrCreate, FileAccess.Write);
                if (tmpfile != null)
                {
                    try
                    {
                        using (StreamWriter sw =
                                   new StreamWriter(tmpfile))
                        {
                            string             css;
                            string             fileName     = "css.txt";
                            StreamResourceInfo resourceInfo = Application.GetResourceStream(new Uri(fileName, UriKind.Relative));
                            using (StreamReader reader = new StreamReader(resourceInfo.Stream))
                            {
                                css = reader.ReadToEnd();
                            }

                            String html = "";
                            html += "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><style>" + css + "</style></head>";
                            html += "<body><div class=\"page\"><div class=\"article\">";
                            html += "<a target=\"_blank\" href=" + content.source + " class=\"source\">来源</a>";
                            html += "<h1 class=\"title\">" + content.title + "</h1><div class=\"body\">";
                            html += content.body;
                            html += "</div></div></div></body></html>";
                            sw.Write(html);
                            sw.Flush();
                        }
                    }
                    catch (IsolatedStorageException ex)
                    {
                        Dispatcher.BeginInvoke(() => AppUtils.ToastPromptShow("阅FM", "上传失败,准备文件时发生错误"));
                        is_upload_started = false;
                        return;
                    }
                }
                tmpfile.Close();

                Dispatcher.BeginInvoke(() => AppUtils.ToastPromptShow("阅FM", "开始上传.."));

                await client.UploadAsync(folder, content.title + ".html", store.OpenFile(filePath,
                                                                                         FileMode.Open, FileAccess.Read), OverwriteOption.Overwrite);

                Dispatcher.BeginInvoke(() => AppUtils.ToastPromptShow("阅FM", "上传成功!")); is_upload_started = false;
            }
            else
            {
                Dispatcher.BeginInvoke(() => AppUtils.ToastPromptShow("阅FM", "上传失败,找不到目标文件夹"));
                is_upload_started = false;
            }
        }
예제 #50
0
 public async Task DeleteSkyDriveItemAsync(String skyDriveItemId)
 {
     // requires wl.skydrive_update scope
     var client = new LiveConnectClient(_session);
     await client.DeleteAsync(skyDriveItemId);
 }
        private async Task<byte[]> GetProfileImageData(LiveConnectClient client)
        {
            byte[] imgData = null;
            try
            {
                LiveDownloadOperationResult meImgResult = await client.DownloadAsync("me/picture");
                imgData = new byte[meImgResult.Stream.Length];
                await meImgResult.Stream.ReadAsync(imgData, 0, imgData.Length);
            }
            catch
            {
                // Failed to download image data.
            }

            return imgData;
        }
예제 #52
0
        private async void romList_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            ROMDBEntry entry = this.romList.SelectedItem as ROMDBEntry;

            if (entry == null)
            {
                return;
            }

            if (this.uploading)
            {
                MessageBox.Show(AppResources.BackupWaitForUpload, AppResources.ErrorCaption, MessageBoxButton.OK);
                this.romList.SelectedItem = null;
                return;
            }

            var indicator = new ProgressIndicator()
            {
                IsIndeterminate = true,
                IsVisible       = true,
                Text            = String.Format(AppResources.BackupUploadProgressText, entry.DisplayName)
            };

            SystemTray.SetProgressIndicator(this, indicator);
            this.uploading = true;

            try
            {
                LiveConnectClient client   = new LiveConnectClient(this.session);
                String            folderID = await this.CreateExportFolder(client);

                IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
                bool errors             = false;
                foreach (var savestate in entry.Savestates)
                {
                    String path = FileHandler.ROM_DIRECTORY + "/" + FileHandler.SAVE_DIRECTORY + "/" + savestate.FileName;
                    try
                    {
                        using (IsolatedStorageFileStream fs = iso.OpenFile(path, System.IO.FileMode.Open))
                        {
                            await client.UploadAsync(folderID, savestate.FileName, fs, OverwriteOption.Overwrite);
                        }
                    }
                    catch (FileNotFoundException)
                    {
                        errors = true;
                    }
                    catch (LiveConnectException ex)
                    {
                        MessageBox.Show(String.Format(AppResources.BackupErrorUpload, ex.Message), AppResources.ErrorCaption, MessageBoxButton.OK);
                        errors = true;
                    }
                }

                String sramName = entry.FileName.Substring(0, entry.FileName.Length - 3) + "srm";
                String sramPath = FileHandler.ROM_DIRECTORY + "/" + FileHandler.SAVE_DIRECTORY + "/" + sramName;
                try
                {
                    if (iso.FileExists(sramPath))
                    {
                        using (IsolatedStorageFileStream fs = iso.OpenFile(sramPath, FileMode.Open))
                        {
                            await client.UploadAsync(folderID, sramName, fs, OverwriteOption.Overwrite);
                        }
                    }
                }
                catch (Exception)
                {
                    errors = true;
                }

                if (errors)
                {
                    MessageBox.Show(AppResources.BackupUploadUnsuccessful, AppResources.ErrorCaption, MessageBoxButton.OK);
                }
                else
                {
                    MessageBox.Show(AppResources.BackupUploadSuccessful);
                }
            }
            catch (NullReferenceException)
            {
                MessageBox.Show(AppResources.CreateBackupFolderError, AppResources.ErrorCaption, MessageBoxButton.OK);
            }
            catch (LiveConnectException)
            {
                MessageBox.Show(AppResources.SkyDriveInternetLost, AppResources.ErrorCaption, MessageBoxButton.OK);
            }
            finally
            {
                SystemTray.GetProgressIndicator(this).IsVisible = false;
                this.uploading = false;
            }
        }
        private async Task<LiveOperationResult> QueryUserData(LiveConnectClient client, string path)
        {
            try
            {
                return await client.GetAsync(path);
            }
            catch
            {
            }

            return null;
        }
예제 #54
0
        private async void SkyDriveItem_Click(object sender, EventArgs e)
        {
            AppUtils.FlurryLog("SkyDrive");

            if (client == null)
            {
                return;
            }
            if (is_upload_started)
            {
                Dispatcher.BeginInvoke(() => AppUtils.ToastPromptShow("阅FM", "请等待上传操作结束后开始新上传"));
                return;
            }
            is_upload_started = true;

            Dispatcher.BeginInvoke(() => AppUtils.ToastPromptShow("阅FM", "正在处理上传请求.."));

            if (this.apiManager.currentArticle == null)
            {
                return;
            }
            ArticleContent content = this.apiManager.currentArticle;

            var folderData = new Dictionary <string, object>();

            client = new LiveConnectClient(client.Session);

            try
            {
                var result = await client.GetAsync("me/skydrive/files");

                SkyDriveContent            sdc = new SkyDriveContent();
                DataContractJsonSerializer ds  = new DataContractJsonSerializer(typeof(SkyDriveContent));
                byte[]       bs = System.Text.Encoding.Unicode.GetBytes(result.RawResult);
                MemoryStream ms = new MemoryStream(bs);
                sdc = ds.ReadObject(ms) as SkyDriveContent;
                string folder = null;
                foreach (var item in sdc.data)
                {
                    if (item.name == "阅FM")
                    {
                        folder = item.id;
                    }
                }
                if (folder == null)
                {
                    Dispatcher.BeginInvoke(() => AppUtils.ToastPromptShow("阅FM", "正在创建上传目标文件夹.."));

                    folderData.Add("name", "阅FM");
                    result = await client.PostAsync("me/skydrive", folderData);

                    folder = result.Result.ContainsKey("id") ? result.Result["id"].ToString() : null;
                    SendFileToSkyDrive(client, folder, content);
                    return;
                }
                SendFileToSkyDrive(client, folder, content);
            }
            catch (Exception e5)
            {
            }
        }
예제 #55
0
 public ApiOperation GetUploadOperation(LiveConnectClient client, Uri url, IFileSource inputFile, OverwriteOption option, IProgress <LiveOperationProgress> progress, SynchronizationContextWrapper syncContext)
 {
     return(new UploadOperation(client, url, inputFile.Filename, inputFile.GetReadStream(), option, progress, syncContext));
 }
예제 #56
0
        private static LiveConnectClient CreateClientForSession(LiveConnectSession session)
        {
            var client = new LiveConnectClient(session);

            return(client);
        }
예제 #57
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);
            }
        }
        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>());
        }
        private async void GetMeAndFileListing()
        {
            try
            {
                _client = new LiveConnectClient(App.LiveSession);
                var opResult = await _client.GetAsync("me");

                dynamic e = opResult.Result;
                try
                {
                    lblLoginResult.Text = string.Format(
                        StringResources.BackupAndRestorePage_Messages_Welcome, e.name, "!");
                }
                catch
                {
                    lblLoginResult.Text = "Welcome!";
                }
                try
                {
                    _client = new LiveConnectClient(App.LiveSession);
                    var filesResult = await _client.GetAsync("/me/skydrive/files");

                    IDictionary <string, object> ee = filesResult.Result;
                    List <object> data = (List <object>)ee["data"];
                    _newestFile = null;
                    DateTime newestDate = DateTime.MinValue;
                    foreach (dynamic d in data)
                    {
                        string name = d.name.ToString();
                        if (name.Contains("fieldservicebackup"))
                        {
                            string   date  = Regex.Match(name, @"^fieldservicebackup_(?<date>\d\d\-\d\d\-\d\d\d\d)\.zip$").Groups["date"].Value;
                            DateTime dateT = DateTime.ParseExact(date, "MM-dd-yyyy", CultureInfo.InvariantCulture);

                            if (dateT > newestDate)
                            {
                                _newestFile = d.id.ToString();
                                newestDate  = dateT;
                            }
                        }
                    }
                    bBackup.Visibility       = Visibility.Visible;
                    lblLastBackup.Visibility = Visibility.Visible;
                    if (string.IsNullOrEmpty(_newestFile))
                    {
                        lblLastBackup.Text  = StringResources.BackupAndRestorePage_Messages_NeverBackedUp;
                        bRestore.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        lblLastBackup.Text  = string.Format("{0:MM/dd/yyyy}", newestDate);
                        bRestore.Visibility = Visibility.Visible;
                    }
                } catch (Exception)
                {
                }
            }
            catch (LiveConnectException)
            {
                lblLastBackup.Text = StringResources.BackupAndRestorePage_Messages_SkyDriveListingFailed;
            }
        }
예제 #60
0
        async void skydriveList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SkyDriveListItem item = this.skydriveList.SelectedItem as SkyDriveListItem;

            if (item == null)
            {
                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.Savestate || item.Type == SkyDriveItemType.SRAM)
                {
                    //check to make sure there is a rom with matching name
                    ROMDatabase db    = ROMDatabase.Current;
                    ROMDBEntry  entry = null;

                    if (item.Type == SkyDriveItemType.Savestate)
                    {
                        entry = db.GetROMFromSavestateName(item.Name);
                    }
                    else if (item.Type == SkyDriveItemType.SRAM)
                    {
                        entry = db.GetROMFromSRAMName(item.Name);
                    }

                    if (entry == null) //no matching file name
                    {
                        MessageBox.Show(AppResources.NoMatchingNameText, AppResources.ErrorCaption, MessageBoxButton.OK);
                        return;
                    }

                    //check to make sure format is right
                    if (item.Type == SkyDriveItemType.Savestate)
                    {
                        string slot       = item.Name.Substring(item.Name.Length - 5, 1);
                        int    parsedSlot = 0;
                        if (!int.TryParse(slot, out parsedSlot))
                        {
                            MessageBox.Show(AppResources.ImportSavestateInvalidFormat, AppResources.ErrorCaption, MessageBoxButton.OK);
                            return;
                        }
                    }
                    // Download
                    if (!item.Downloading)
                    {
                        try
                        {
                            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);
                        }
                    }
                    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;
            }
        }