public async Task <string> Upload(string targetPath, string targetFileName, Stream stream, CancellationToken?ct = null)
        {
            LiveOperationResult res;

            if (ct != null)
            {
                res = await _liveConnectClient.UploadAsync("me/skydrive/" + targetPath, targetFileName, stream, OverwriteOption.Overwrite, ct.Value, null);
            }
            else
            {
                res = await _liveConnectClient.UploadAsync("me/skydrive/" + targetPath, targetFileName, stream, OverwriteOption.Overwrite);
            }

            return(res.Result["id"].ToString());
        }
Exemple #2
0
        public async Task BackupLocalDatabase()
        {
            string toUploadDatabaseName = "toUploadDatabase.sdf";

            //release all resources from DB
            App.AppViewModel.DisposeCurrentDB();
            // Obtain the virtual store for the application.
            IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();

            iso.CopyFile(AppResources.DatabaseName + ".sdf", toUploadDatabaseName, true);
            App.AppViewModel.ConnectDB();

            LiveConnectClient liveClient = new LiveConnectClient(oneDriveAuthClient.Session);

            try
            {
                using (Stream uploadStream = iso.OpenFile(toUploadDatabaseName, FileMode.Open))
                {
                    if (uploadStream != null)
                    {
                        LiveOperationResult uploadResult = await liveClient.UploadAsync(oneDriveFolderId, databaseBackupname + ".sdf", uploadStream, OverwriteOption.Overwrite);

                        MessageBox.Show("Upload successful.");
                    }
                }
                iso.DeleteFile(toUploadDatabaseName);
                await getFileFromBackupFolderAsync();
            }
            catch (LiveConnectException ex)
            {
                App.AppViewModel.SendExceptionReport(ex);
            }
        }
        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...
        }
Exemple #4
0
        void client_GetCompleted(object sender, LiveOperationCompletedEventArgs e)
        {
            try
            {
                if (e.Result.ContainsKey("available"))
                {
                    Int64  available = Convert.ToInt64(e.Result["available"]);
                    byte[] data      = RecordManager.GetRecordByteArray(MainPageViewModel.Instance.CurrentlyUploading);

                    if (available >= data.Length)
                    {
                        MemoryStream stream = new MemoryStream(data);

                        client = new LiveConnectClient(App.MicrosoftAccountSession);
                        client.UploadCompleted       += MicrosoftAccountClient_UploadCompleted;
                        client.UploadProgressChanged += MicrosoftAccountClient_UploadProgressChanged;
                        client.UploadAsync("me/skydrive", MainPageViewModel.Instance.CurrentlyUploading,
                                           stream, OverwriteOption.Overwrite);
                        grdUpload.Visibility     = System.Windows.Visibility.Visible;
                        ApplicationBar.IsVisible = false;
                    }
                    else
                    {
                        MessageBox.Show("Looks like you don't have enough space on your SkyDrive. Go to http://skydrive.com and either purchase more space or clean up the existing storage.", "Upload",
                                        MessageBoxButton.OK);
                    }
                }
            }
            catch
            {
                FailureAlert();
            }
        }
Exemple #5
0
        /// <summary>
        /// uplaods a picture to sky drive.
        /// </summary>
        /// <param name="e"></param>
        private void UploadPicture(PhotoResult e)
        {
            LiveConnectClient uploadClient = new LiveConnectClient(App.Session);

            uploadClient.UploadCompleted
                += new EventHandler <LiveOperationCompletedEventArgs>(ISFile_UploadCompleted);

            if (e.OriginalFileName == null)
            {
                return;
            }

            // file name is the current datetime stapm
            string   ext      = e.OriginalFileName.Substring(e.OriginalFileName.LastIndexOf('.'));
            DateTime dt       = DateTime.Now;
            string   fileName = String.Format("{0:d_MM_yyy_HH_mm_ss}", dt);

            fileName = fileName + ext;

            string progMsgUpPic = SkyPhoto.Resources.Resources.progMsgUpPic;

            ShowProgressBar(progMsgUpPic);

            try
            {
                uploadClient.UploadAsync(App.CurrentAlbum.ID, fileName, e.ChosenPhoto, OverwriteOption.Overwrite);
            }
            catch (Exception)
            {
                string upFaild = SkyPhoto.Resources.Resources.upFaild;
                MessageBox.Show(upFaild);
                HideProgressBar();
            }
        }
Exemple #6
0
        public void uploadFile(string filename, System.IO.Stream file, string skydrivePath = "folder.559920a76be10760.559920A76BE10760!162")
        {
            LiveConnectClient client = new LiveConnectClient(App.Session);

            client.UploadAsync(skydrivePath, filename, file, OverwriteOption.Overwrite);
            client.UploadCompleted += new EventHandler <LiveOperationCompletedEventArgs>(UploadCompleted);
        }
Exemple #7
0
 private void CreateFolder3_Completed(object sender, LiveOperationCompletedEventArgs e)
 {
     if (e.Error == null)
     {
         infoTextBlock.Text = txtnote.Resources.StringLibrary.shareInfo_3;
         Dictionary <string, object> folder = (Dictionary <string, object>)e.Result;
         skyDriveFolderID_merge = folder["id"].ToString(); //grab the folder ID
         //merge文件夹建立后,自动上传merge的空文件
         byte[]       b2   = System.Text.Encoding.UTF8.GetBytes("");
         MemoryStream file = new MemoryStream(b2);
         client.UploadAsync(skyDriveFolderID_merge, "txtNote_Merge.txt", file, OverwriteOption.Overwrite);
     }
     else
     {
         MessageBox.Show(e.Error.Message);
     }
 }
        private void SaveButtonClick(object sender, EventArgs e)
        {
            TextBox textBox = new TextBox()
            {
                Margin = new Thickness(0, 14, 0, -2)
            };

            CustomMessageBox box = new CustomMessageBox()
            {
                Caption            = "Save to SkyDrive",
                Message            = "Enter file name",
                LeftButtonContent  = "ok",
                RightButtonContent = "cancel",
                Content            = textBox
            };

            box.Dismissed += async(s, boxEventArgs) =>
            {
                switch (boxEventArgs.Result)
                {
                case CustomMessageBoxResult.LeftButton:
                    if (!string.IsNullOrWhiteSpace(textBox.Text))
                    {
                        using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            try
                            {
                                using (var fileStream = store.OpenFile("sound.wav", FileMode.Open, FileAccess.Read, FileShare.Read))
                                {
                                    string filename         = textBox.Text + ".wav";
                                    LiveOperationResult res = await client.UploadAsync("me/skydrive",
                                                                                       filename,
                                                                                       fileStream,
                                                                                       OverwriteOption.Overwrite);

                                    MessageBoxResult result =
                                        MessageBox.Show("File " + filename + " uploaded",
                                                        "SkyDrive Sign-in", MessageBoxButton.OK);
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                    break;

                default:
                    break;
                }
            };

            box.Show();


            /**/
        }
Exemple #9
0
        public void UploadFile()
        {
            if (skyDriveFolderID != string.Empty) //the folder must exist, it should have already been created
            {
                this.client.UploadCompleted
                    += new EventHandler <LiveOperationCompletedEventArgs>(ISFile_UploadCompleted);

                _progressIndicator.IsVisible = true;
                _progressIndicator.Text      = "Przesyłanie kopii zapasowej...";
                // tblDate.Text = "";

                try
                {
                    int count      = 0;
                    var fotoToSync = App.ViewModel.GetAllFotoToSync();

                    foreach (Foto ft in fotoToSync)
                    {
                        count += 1;
                        _progressIndicator.Text = "Przesyłanie pliku " + count + " z " + fotoToSync.Count;
                        object[] state = new object[1];
                        state[0] = ft.FotoId;


                        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile(ft.FotoPath, System.IO.FileMode.Create))
                            {
                                stream.Write(ft.FotoImage, 0, ft.FotoImage.Length);
                            }

                            readStream = myIsolatedStorage.OpenFile(ft.FotoPath, FileMode.Open);
                            client.UploadAsync(skyDriveFolderID, ft.FotoPath, true, readStream, ft.FotoId);
                        }
                    }

                    if (!fotoToSync.Any())
                    {
                        tblInfo.Text = "Brak plików do przesłania.";
                    }
                }

                catch
                {
                    _progressIndicator.IsVisible = false;
                    MessageBox.Show("Błąd dostępu IsolatedStorage. Proszę zamknąć aplikację i otworzyć ją ponownie, a następnie spróbuj ponownie stworzenie kopii zapasowyej!", "Backup Failed", MessageBoxButton.OK);
                    tblInfo.Text = "Błąd. Zamknij aplikację i uruchom ponownie.";
                    //tblDate.Text = "";
                }
                finally
                {
                    _progressIndicator.IsVisible = false;
                }
            }
        }
Exemple #10
0
        public void SaveFile()
        {
            byte[] myBytes = AES.Encrypt(this.SerializeToXML(), _password);

            MemoryStream ms           = new MemoryStream(myBytes);
            var          clientFolder = new LiveConnectClient(App.Session);

            clientFolder.UploadCompleted += (object sender, LiveOperationCompletedEventArgs e) =>
            {
                if (e.Error != null)
                {
                    MessageBox.Show(e.Error.Message, "Upload Failed", MessageBoxButton.OK);
                }

                string name = e.Result["name"].ToString();
                string id   = e.Result["id"].ToString();

                if (App.MyWalletFile == null)
                {
                    App.MyWalletFile = new WalletFileWM {
                        FileId = id, FileName = name
                    };
                    App.MyWallet = this;
                }

                ms.Dispose();
            };
            if (App.MyWalletFile == null)
            {
                clientFolder.UploadAsync("me/skydrive", FileName, ms, OverwriteOption.Rename);
            }
            else
            {
                clientFolder.UploadAsync(App.MyWalletFile.FileId, FileName, ms, OverwriteOption.Overwrite);
            }

            if (OnSaveCompleted != null)
            {
                OnSaveCompleted(this, null);
            }
        }
        void task_Completed(object sender, PhotoResult e)
        {
            if (e.ChosenPhoto == null)
            {
                return;
            }

            LiveConnectClient uploadClient = new LiveConnectClient(App.Session);

            uploadClient.UploadCompleted += new EventHandler <LiveOperationCompletedEventArgs>(uploadClient_UploadCompleted);
            uploadClient.UploadAsync(SelectedAlbum.ID, "Image" + DateTime.Now.Millisecond + ".jpg", e.ChosenPhoto);
        }
        public async void UploadFile(string fileName)
        {
            try
            {
                var stream = _memoryService.ReadFile(fileName);
                await _client.UploadAsync(_folderId, fileName, stream, OverwriteOption.Overwrite);

                OnUploadCompleted(fileName, true);
            }
            catch (Exception)
            {
                OnUploadCompleted(fileName, false);
            }
        }
 public bool Upload(string currentFolderID, string remoteFileName, Stream fileStream, OverwriteOption overwriteOption, Action <SkyDriveResult <bool> > callback)
 {
     lock (_syncRoot)
     {
         if (!IsWorking && Logged)
         {
             IsWorking       = true;
             _uploadCallback = callback;
             LiveClient.UploadAsync(currentFolderID, remoteFileName, fileStream, overwriteOption);
             return(true);
         }
     }
     return(false);
 }
Exemple #14
0
        public virtual async Task UploadPasswords()
        {
            if (!IsConnected)
            {
                await Login();
            }
            if (!IsConnected)
            {
                return;
            }

            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

            if (isoStore.FileExists("accounts.dat"))
            {
                using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("accounts.dat", FileMode.Open, isoStore))
                {
                    var res = await _connectClient.UploadAsync(_pkFolderId, "passwords.txt", isoStream, OverwriteOption.Overwrite);

                    _filePasswordsId = res.Result["id"] as string;
                }
            }
        }
Exemple #15
0
        internal async void RunTaskAsync(LiveConnectClient client, Action <bool> callback)
        {
            bool succeeded = true;

            using (var stream = await File.OpenStreamForReadAsync())
            {
                try
                {
                    const int backgroundTheshold = 1024 * 1024 * 100;
                    if (stream.Length >= backgroundTheshold)
                    {
                        const string rootPath     = "/shell/transfers";
                        var          tempFilePath = string.Format("{0}/{1}/{2}", rootPath, FolderId, FileName);
                        using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            if (!storage.DirectoryExists(rootPath))
                            {
                                storage.CreateDirectory(rootPath);
                            }
                            if (storage.FileExists(tempFilePath))
                            {
                                storage.DeleteFile(tempFilePath);
                            }
                            using (var file = storage.CreateFile(tempFilePath))
                            {
                                var position = stream.Position;
                                await stream.CopyToAsync(file);

                                stream.Position = position;
                            }
                        }
                        client.BackgroundTransferPreferences = BackgroundTransferPreferences.None;
                        await client.BackgroundUploadAsync(FolderId, new Uri(tempFilePath, UriKind.Relative), OverwriteOption.Overwrite);
                    }
                    else
                    {
                        await client.UploadAsync(FolderId, FileName, stream, OverwriteOption.Overwrite);
                    }
                }
                catch (Exception)
                {
                    succeeded = false;
                }
            }
            if (callback != null)
            {
                callback(succeeded);
            }
        }
Exemple #16
0
 void Folder_Upload()
 {
     if (sky_base_folder_id != null)
     {
         if (wait_async == false)
         {
             wait_async          = true;
             list_files_isolated = My_Isolated_Storage.GetFileNames("GPX\\*.gpx");
             progress_multiple   = true;
             Progress_Init();
             int loop_count = 0;
             client.UploadCompleted += new EventHandler <LiveOperationCompletedEventArgs>(Folder_Upload_Completed);
             foreach (string content in list_files_isolated)
             {
                 int  scan_loop       = 0;
                 bool scan_file_exist = false;
                 while (scan_loop + 1 <= list_files_skydrive.Count())
                 {
                     if (content == list_files_skydrive.ElementAt(scan_loop).Name.ToString())
                     {
                         scan_file_exist = true;
                         //MessageBox.Show("Deja existant : " + content);
                     }
                     scan_loop += 1;
                 }
                 if (scan_file_exist == false)
                 {
                     progress_list.Add(0);
                     IsolatedStorageFileStream fileStream = My_Isolated_Storage.OpenFile("GPX\\" + content, FileMode.Open, FileAccess.Read);
                     StreamReader reader = new StreamReader(fileStream);
                     client.UploadAsync(sky_base_folder_id, content + ".txt", fileStream, OverwriteOption.DoNotOverwrite, loop_count);
                     loop_count = loop_count + 1;
                 }
             }
             if (loop_count == 0)
             {
                 wait_async              = false;
                 client.UploadCompleted -= Folder_Upload_Completed;
                 SystemTray.ProgressIndicator.IsVisible = false;
                 //MessageBox.Show("Tous les fichiers ont été envoyés.");
             }
         }
     }
     else
     {
         MessageBox.Show("Erreur upload: sky_base_folder_id = null");
     }
 }
        public async Task <bool> SaveToSkyDrive(SkyDriveSaveArgs args)
        {
            bool uploadSuccess = false;

            try
            {
                var loginResult = await _authClient.LoginAsync(LiveConfig.Scopes);

                if (loginResult.Status == LiveConnectSessionStatus.Connected)
                {
                    LiveConnectClient client = new LiveConnectClient(loginResult.Session);
                    var foldersResult        = await client.GetAsync("me/skydrive/files?filter=folders");

                    var folders = foldersResult.Result["data"] as List <object>;
                    if (folders != null)
                    {
                        var folderQuery = (from f in folders
                                           where f is IDictionary <string, object>
                                           select(IDictionary <string, object>) f);
                        _whatIEatFolderId = folderQuery.Where(it => it["name"].ToString().ToLowerInvariant().Equals("what i eat")).Select(it => it["id"].ToString()).FirstOrDefault();
                    }
                    if (string.IsNullOrWhiteSpace(_whatIEatFolderId))
                    {
                        Dictionary <string, object> folderData = new Dictionary <string, object>();
                        folderData.Add("name", "What I Eat");
                        var folderCreateResult = await client.PostAsync("me/skydrive", folderData);

                        _whatIEatFolderId = folderCreateResult.Result["id"].ToString();
                    }
                    if (!string.IsNullOrWhiteSpace(_whatIEatFolderId))
                    {
                        using (var ms = new MemoryStream(args.Encoding.GetBytes(args.Content)))
                        {
                            var uploadResult = await client.UploadAsync(_whatIEatFolderId, args.Filename, ms, OverwriteOption.Overwrite);

                            uploadSuccess = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //TODO: Log Exception
                _log.LogException(ex, "SkyDrive Upload Error");
            }
            return(uploadSuccess);
        }
Exemple #18
0
        public static async Task <string> upload(string filename)
        {
            string res = "";

            //diagLog("Uploading " + file);
            try
            {
                string[]       requiredScope = { "wl.offline_access", "wl.skydrive_update" };
                LiveAuthClient auth          = new LiveAuthClient(Secrets.ClientID);
                await auth.InitializeAsync(requiredScope);

                if (auth.Session == null)
                {
                    await auth.LoginAsync(requiredScope);
                }
                LiveConnectClient liveClient = new LiveConnectClient(auth.Session);

                string folderid = await GetSkyDriveFolderID(FOLDER, liveClient);

                if (folderid == null)
                {
                    folderid = await createSkyDriveFolder(FOLDER, liveClient);

                    res = "Created folder: " + FOLDER + "\n"; // , "ID:", folderid);
                }

                var store = IsolatedStorageFile.GetUserStoreForApplication();
                if (store.FileExists(filename))
                {
                    var file = store.OpenFile(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    LiveOperationResult operationResult = await liveClient.UploadAsync(folderid, filename, file, OverwriteOption.Overwrite);

                    dynamic result = operationResult.Result;
                    res += "Uploaded :" + result.name; //, "ID:", result.id);
                }
                else
                {
                    throw new Exception("file does not exist");
                }
            }
            catch (Exception exception)
            {
                res = "Error uploading file: " + exception.Message;
            }
            return(res);
        }
        private void PerformDeviceToCloudSync(LiveConnectSession session, string syncFilename, Action <BookmarkserviceImportCompletedEventArgs> completedAction, BookmarkserviceImportCompletedEventArgs completedEventArgs)
        {
            //get device bookmarks
            List <Bookmark> deviceBookmarks = RetrieveDeviceBookmarks();

            //upload
            string syncFileContents = GenerateNetscapBookmarkFile(syncFilename, deviceBookmarks);

            LiveConnectClient uploadClient = new LiveConnectClient(session);

            uploadClient.UploadCompleted += delegate(object uploadSender, LiveOperationCompletedEventArgs e)
            {
                #warning update the internal file name if non existant
                completedEventArgs.StatusCode = ImportStatusCode.Success;
                completedAction(completedEventArgs);
            };

            Stream uploadStream = new MemoryStream(Encoding.UTF8.GetBytes(syncFileContents));
            uploadClient.UploadAsync("me/skydrive", syncFilename, true, uploadStream, null);
        }
Exemple #20
0
        private void UploadItems(ListItem item)
        {
            _uploadCounter++;
            var newFile = new MemoryStream();
            var writer  = new StreamWriter(newFile);

            foreach (var listItem in item.Items)
            {
                if (listItem.Deleted)
                {
                    continue;
                }
                writer.WriteLine("{0}{1}", listItem.Mark ? "-" : "", listItem.Name);
            }
            writer.Flush();
            newFile.Flush();
            newFile.Seek(0, SeekOrigin.Begin);
            //writer.Close();
            _client.UploadAsync(App.Current.SkyDriveFolders.FolderID, item.Name + ".txt", true, newFile, item);
        }
Exemple #21
0
        public async static Task <string> UploadAsync(string folderId, string fileName, Stream data)
        {
            string fileId = null;

            try
            {
                LiveOperationResult operationResult = await _client.UploadAsync(folderId, fileName, data, OverwriteOption.Overwrite);

                foreach (var item in operationResult.Result)
                {
                    if (item.Key == "id")
                    {
                        fileId = item.Value as string;
                        break;
                    }
                }
            }
            catch (Exception) { }
            return(fileId);
        }
        public static async Task <string> UploadFileAsync(string sourceFileName, string destinationFileName, CancellationToken ct, IProgress <LiveOperationProgress> progress)
        {
            if (_session == null)
            {
                throw new InvalidOperationException("Session is null");
            }

            string uploadFileName = _specialRegEx.Replace(destinationFileName, "-");

            LiveConnectClient client = new LiveConnectClient(_session);

            using (var fileStream = await StorageHelper.OpenFileForReadAsync(sourceFileName))
            {
                var folderId = await GetOrCreateFolderAsync("Voice Memos", ct);

                var operationResult = await client.UploadAsync(folderId, uploadFileName, fileStream, OverwriteOption.Overwrite, ct, progress);

                dynamic result = operationResult.Result;
                return(result.id);
            }
        }
Exemple #23
0
        private void BeginUpload(string localFilePath)
        {
            try
            {
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    _currentUlFileStream = isf.OpenFile(localFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);

                    Log("Starts UploadAsync");

                    StartTaskAndContinueWith(
                        () => _liveClient.UploadAsync(_uploadsFolderId, Path.GetFileName(localFilePath), _currentUlFileStream, OverwriteOption.Overwrite),
                        t => OnLiveClientUploadCompleted(t, localFilePath));
                }
            }
            catch (Exception e)
            {
                Geowigo.Utils.DebugUtils.DumpException(e, "BeginUpload failed for " + localFilePath, true);

                // Forces a post-process of the upload to discard this file and try another one.
                PostProcessUpload(localFilePath);
            }
        }
        private static async Task updateSourceAsync(WebFileStream stream)
        {
            var skyProfile = stream.Profile as SkyDriveProfile;
            var skyModel   = stream.EntryModel as SkyDriveItemModel;

            await skyProfile.checkLoginAsync();

            CancellationTokenSource cts = new CancellationTokenSource();
            var progressHandler         = new Progress <LiveOperationProgress>(
                (progress) => { });


            LiveConnectClient   liveClient = new LiveConnectClient(skyProfile.Session);
            LiveOperationResult result;

            stream.Seek(0, SeekOrigin.Begin);
            var uid = (skyModel.Parent as SkyDriveItemModel).UniqueId;

            result = await liveClient.UploadAsync(uid,
                                                  skyModel.Name, stream, OverwriteOption.Overwrite, cts.Token, progressHandler);

            skyModel.init(skyProfile, skyModel.FullPath, result.Result);
        }
Exemple #25
0
        public static void UploadFile()
        {
            if (skyDriveFolderID != string.Empty) //the folder must exist, it should have already been created
            {
                client.UploadCompleted
                    += new EventHandler <LiveOperationCompletedEventArgs>(ISFile_UploadCompleted);

                try
                {
                    var fotoToSync = App.ViewModel.GetAllFotoToSync();

                    foreach (Foto ft in fotoToSync)
                    {
                        object[] state = new object[1];
                        state[0] = ft.FotoId;


                        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile(ft.FotoPath, System.IO.FileMode.Create))
                            {
                                stream.Write(ft.FotoImage, 0, ft.FotoImage.Length);
                            }

                            readStream = myIsolatedStorage.OpenFile(ft.FotoPath, FileMode.Open);
                            client.UploadAsync(skyDriveFolderID, ft.FotoPath, true, readStream, ft.FotoId);
                        }
                    }
                }

                catch
                {
                    MessageBox.Show("Błąd dostępu IsolatedStorage. Proszę zamknąć aplikację i otworzyć ją ponownie, a następnie spróbuj ponownie stworzenie kopii zapasowyej!", "Backup Failed", MessageBoxButton.OK);
                }
            }
        }
        public async void uploadFilesToFolder(string folderId)
        {
            if (_session == null)
            {
                return;
            }

            try
            {
                var client = new LiveConnectClient(_session);

                SystemTray.ProgressIndicator                 = new ProgressIndicator();
                SystemTray.ProgressIndicator.Text            = "Uploading...";
                SystemTray.ProgressIndicator.IsIndeterminate = true;
                SystemTray.ProgressIndicator.IsVisible       = true;

                var isf = IsolatedStorageFile.GetUserStoreForApplication();

                foreach (string filePath in App.filesToSave)
                {
                    string[] segments = filePath.Split('\\');
                    var      fileName = segments[segments.Length - 1];

                    IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.OpenOrCreate, isf);
                    //FileStream fileStream = new FileStream(filePath, FileMode.Open);
                    await client.UploadAsync(folderId, fileName, fileStream, OverwriteOption.Overwrite);

                    fileStream.Dispose();
                }

                SystemTray.ProgressIndicator.IsVisible = false;

                MessageBox.Show("Finsihed uploading: " + App.filesToSave.Count + " files");
            }
            catch (Exception) { }
        }
        private void btnUploadFile_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog picker = new Microsoft.Win32.OpenFileDialog();
            picker.Filter = "All Files (*.*)|*.*";
            picker.ShowDialog();

            string filePath = picker.FileName;

            if (filePath != "")
            {
                LiveConnectClient liveClient = new LiveConnectClient(Properties.session);
                liveClient.UploadCompleted += this.ConnectClient_UploadCompleted;
                var stream = default(Stream);
                stream = File.OpenRead(filePath);
                liveClient.UploadAsync("folder.6f717ff8a3b1a691.6F717FF8A3B1A691!192/files", filePath, stream, stream);
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("You didn't select a file.");
            }
        }
        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 void exportToSkyDrive(String opmlExportFileName, IsolatedStorageFileStream sourceStream)
 {
     liveConnect.UploadCompleted += new EventHandler <LiveOperationCompletedEventArgs>(opmlLiveOperation_UploadCompleted);
     liveConnect.UploadAsync("me/skydrive", opmlExportFileName, sourceStream, OverwriteOption.Overwrite);
 }
Exemple #30
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;
            }
        }
Exemple #31
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
        }
        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");
                }
            }
        }
Exemple #33
0
        public static bool UploadFile(string guid, string filePath)
        {
            validateSession();
            try
            {
                LiveConnectClient client = new LiveConnectClient(Properties.session);

                client.UploadCompleted += UltiDrive.SkyDrive.Utilities.ConnectClient_UploadCompleted;
                var stream = default(Stream);
                stream = File.OpenRead(filePath);
                string directoryName = Path.GetDirectoryName(filePath) + "\\";
                client.UploadAsync(Properties.UltiDriveFolderID + "/files", directoryName + guid, stream, stream);

                //System.Windows.MessageBox.Show(stream.ToString());
                //stream.Close();
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine("SkyDriveApi.UploadFile() failed. --> " + e.ToString());
                return false;
            }
        }