Esempio n. 1
0
        public async Task<string> UploadImageToCloud(byte[] byteArrayContent, string fileName, string fileExstension,
            string parentPath = WebStorageConstants.Collection)
        {
            // var parentId = await this.CreateDirectory(parentPath);

            Permission permission = new Permission()
            {
                Role = "reader",
                Type = "anyone",
                WithLink = true
            };

            File body = new File
            {
                Title = fileName,
                Shared = true,
                Permissions = new List<Permission>() { permission }
            };

            MemoryStream stream = new MemoryStream(byteArrayContent);
            try
            {
                FilesResource.InsertMediaUpload request = this.service.Files.Insert(body, stream, "image/" + fileExstension);
                var result = await request.UploadAsync();

                return WebStorageConstants.GoogleDriveSourceLink + request.ResponseBody.Id;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Create a new file and return it.
        /// </summary>
        public static File Create(DriveService service, String title)
        {
            // File's metadata.
            File body = new File();

            body.Title    = title;
            body.MimeType = "application/vnd.google-apps.document";
            var request = service.Files.Insert(body);

            request.Convert = true;
            var file = request.Execute();

            var p = new Permission()
            {
                Role     = "reader",
                Type     = "anyone",
                WithLink = true
            };

            var perm = service.Permissions.Insert(p, file.Id).Execute();

            perm.AdditionalRoles = new List <string>()
            {
                "commenter"
            };

            service.Permissions.Patch(perm, file.Id, perm.Id).Execute();

            return(file);
        }
Esempio n. 3
0
        //// <summary>
        /// Create a new Directory.
        /// Documentation: https://developers.google.com/drive/v2/reference/files/insert
        /// </summary>
        /// <param name="_service">a Valid authenticated DriveService</param>
        /// <param name="_title">The title of the file. Used to identify file or folder name.</param>
        /// <param name="_description">A short description of the file.</param>
        /// <param name="_parent">Collection of parent folders which contain this file.
        ///                       Setting this field will put the file in all of the provided folders. root folder.</param>
        /// <returns></returns>
        public static File createDirectory(DriveService _service, string _title, string _description, string _parent)
        {
            File NewDirectory = null;

            // Create metaData for a new Directory
            File body = new File();

            body.Title       = _title;
            body.Description = _description;
            body.MimeType    = "application/vnd.google-apps.folder";
            body.Parents     = new List <ParentReference>()
            {
                new ParentReference()
                {
                    Id = _parent
                }
            };
            try
            {
                FilesResource.InsertRequest request = _service.Files.Insert(body);
                NewDirectory = request.Execute();
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
            }

            return(NewDirectory);
        }
Esempio n. 4
0
        /// <summary>
        /// Updates a file
        /// Documentation: https://developers.google.com/drive/v2/reference/files/update
        /// </summary>
        /// <param name="service">a Valid authenticated DriveService</param>
        /// <param name="uploadFile">path to the file to upload</param>
        /// <param name="parentIdFolder">Collection of parent folders which contain this file.
        ///                       Setting this field will put the file in all of the provided folders. root folder.</param>
        /// <param name="idFile">the resource id for the file we would like to update</param>
        /// <returns>If upload succeeded returns the File resource of the uploaded file
        ///          If the upload fails returns null</returns>
        public static File UpdateFile(DriveService service, string uploadFile, string parentIdFolder, string idFile)
        {
            if (System.IO.File.Exists(uploadFile))
            {
                File body = new File
                {
                    Title       = Path.GetFileName(uploadFile),
                    Description = "File updated Drive",
                    MimeType    = GetMimeType(uploadFile),
                    Parents     = new List <ParentReference> {
                        new ParentReference {
                            Id = parentIdFolder
                        }
                    }
                };

                // File's content.
                byte[]       byteArray = System.IO.File.ReadAllBytes(uploadFile);
                MemoryStream stream    = new MemoryStream(byteArray);
                try
                {
                    FilesResource.UpdateMediaUpload request = service.Files.Update(body, idFile, stream, GetMimeType(uploadFile));
                    request.Upload();
                    return(request.ResponseBody);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
            return(null);
        }
Esempio n. 5
0
        public async Task <FileInfoContract> NewFileItemAsync(RootName root, DirectoryId parent, string name, Stream content, IProgress <ProgressValue> progress)
        {
            if (content.Length == 0)
            {
                return(new ProxyFileInfoContract(name));
            }

            var context = await RequireContextAsync(root);

            var file = new GoogleFile()
            {
                Title = name, MimeType = MIME_TYPE_FILE, Parents = new[] { new ParentReference()
                                                                           {
                                                                               Id = parent.Value
                                                                           } }
            };
            var insert = context.Service.Files.Insert(file, content, MIME_TYPE_FILE);

            if (progress != null)
            {
                insert.ProgressChanged += p => progress.Report(new ProgressValue((int)p.BytesSent, (int)content.Length));
            }
            var retryPolicyWithAction = Policy.Handle <GoogleApiException>().WaitAndRetryAsync(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                                                                                               (ex, ts) => content.Seek(0, SeekOrigin.Begin));
            var upload = await retryPolicyWithAction.ExecuteAsync(() => insert.UploadAsync());

            var item = insert.ResponseBody;

            return(new FileInfoContract(item.Id, item.Title, new DateTimeOffset(item.CreatedDate.Value), new DateTimeOffset(item.ModifiedDate.Value), (FileSize)item.FileSize.Value, item.Md5Checksum));
        }
Esempio n. 6
0
 // 刪除重複 file
 public void DeleteDuplicatedFile(Google.Apis.Drive.v2.Data.File file, string fileName)
 {
     if (file.Title == fileName)
     {
         DeleteFile(file.Id);
     }
 }
Esempio n. 7
0
        /*   internal void DownloadLastBuild()
         * {
         *     var googleLastBuildFolder = GetLastBuildFolder();
         *
         *     var lastCreatedLocalBuildFolder = Paths.LastBuildFolder;
         *     var saveToFolderPath = Path.Combine(Paths.ATPRO_INSTALLATION_PATH,googleLastBuildFolder.Title);
         *
         *
         *     var shareDir = new DirectoryInfo(Paths.ATPRODEBUG_INSTALLATION_SHARE_PATH);
         *     var shareDirPath = Path.Combine(Paths.ATPRODEBUG_INSTALLATION_SHARE_PATH, googleLastBuildFolder.Title);
         *
         *     try
         *     {
         *         shareDirPath = shareDir.GetDirectories().First(d => d.Name.StartsWith(googleLastBuildFolder.Title)).FullName;
         *         if (!Directory.Exists(saveToFolderPath))
         *             Directory.CreateDirectory(saveToFolderPath);
         *         IOHelper.DirectoryCopy(shareDirPath, saveToFolderPath, true);
         *     }
         *     catch (Exception e )
         *     {
         *         Log.InfoFormat("Seems to be an Azure machine {0}", e.Message);
         *         var filesToDownload = GetFileList(googleLastBuildFolder.Id);
         *         var tasks =  new List<Task>();
         *
         *         if ((lastCreatedLocalBuildFolder.ToString() != googleLastBuildFolder.Title))
         *         {
         *             Log.Info(String.Format("Create dir for new version '{0}'", googleLastBuildFolder.Title));
         *             if (!Directory.Exists(saveToFolderPath))
         *                 Directory.CreateDirectory(saveToFolderPath);
         *             lastCreatedLocalBuildFolder = Paths.LastBuildFolder;
         *         }
         *
         *         if ((lastCreatedLocalBuildFolder.GetFiles().Count() != filesToDownload.Count))
         *         {
         *             Log.Info("Downloading missing files from Google Drive...");
         *             tasks.Add(
         *                 Task.Factory.StartNew(
         *                     () =>
         *                         filesToDownload.Where(t => !System.IO.File.Exists(saveToFolderPath + @"\" + t.Title))
         *                             .ToList()
         *                             .ForEach(
         *                                 file =>
         *                                 {
         *                                     Log.Info("Downloading file " + file.Title + "...");
         *                                     DownloadFile(file, saveToFolderPath + @"\" + file.Title);
         *                                 })));
         *         }
         *         Task.WaitAll(tasks.ToArray(),new TimeSpan(0,30,0));
         *     }
         * }*/

        /* public void UploadLastBuild()
         * {
         *
         *   var filesToUpload = new List<string>()
         *   {
         *       ATProDebugApp.INSTALLATION_APPLICATION_NAME + "Setup.exe",
         *       ATProCIApp.INSTALLATION_APPLICATION_NAME + "Setup.exe",
         *       ChartApp.INSTALLATION_APPLICATION_NAME + ".zip",
         *       MarginLiveApp.INSTALLATION_APPLICATION_NAME + "Setup.exe",
         *       InteractiveMarketsApp.INSTALLATION_APPLICATION_NAME + "Setup.exe",
         *       FlatTraderApp.INSTALLATION_APPLICATION_NAME + "Setup.exe",
         *       SharePriceTraderApp.INSTALLATION_APPLICATION_NAME + "Setup.exe",
         *       TradeFairProApp.INSTALLATION_APPLICATION_NAME + "Setup.exe",
         *       MarginLiveIMCApp.INSTALLATION_APPLICATION_NAME + "Setup.exe",
         *       ForexATApp.INSTALLATION_APPLICATION_NAME + "Setup.exe",
         *       ATProIMCApp.INSTALLATION_APPLICATION_NAME + "Setup.exe"
         *   };
         *   var tasks = new List<Task>();
         *
         *   //Compare filenames at Google Drive and local
         *   var googleLastBuildFolder = GetLastBuildFolder();
         *
         *   Wait.UntilNumberOfExceptions(() =>
         *   {
         *       var fileList = GetFileList(googleLastBuildFolder.Id);
         *       //Compare last build folder numbers
         *       var localShareLastVersion = InstallUninstall.GetAppLastVersionFromShare();
         *       var pattern = Paths.GET_VERSION_NUMBER_PATTERN;
         *
         *       var googleLastBuildNumber = new Regex(pattern).Match(googleLastBuildFolder.Title).Groups["number"].Value;
         *       var googleNumber = Int32.Parse(googleLastBuildNumber);
         *       var vm_mc231_appsrvLastBuildNumber =
         *           Int32.Parse(new Regex(pattern).Match(localShareLastVersion).Groups["number"].Value);
         *
         *       if (vm_mc231_appsrvLastBuildNumber > googleNumber) // uploading all files
         *       {
         *           Log.InfoFormat("Started uploading version {0} ...", localShareLastVersion);
         *           var newVersionFolder = createDirectory(localShareLastVersion, "Created by automation script",
         *               BUILDS_FOLDER_ID);
         *           for (var i = 0; i < filesToUpload.Count; i++)
         *           {
         *               var fileName = filesToUpload[i];
         *
         *               tasks.Add(Task.Factory.StartNew(() =>
         *               {
         *                   Log.InfoFormat("Uploading file '{0}' ...", fileName);
         *                   uploadFile(
         *                       Paths.ATPRODEBUG_INSTALLATION_SHARE_PATH + @"\" + localShareLastVersion + @"\" +
         *                       fileName,
         *                       newVersionFolder.Id);
         *               }));
         *           }
         *       }
         *
         *       else if (vm_mc231_appsrvLastBuildNumber == googleNumber) // uploading only missing files
         *       {
         *           var missingFiles = filesToUpload.Where(f => !fileList.Select(r => r.Title.ToString()).Contains(f));
         *           Log.InfoFormat("Downloading missing files: {0}", missingFiles.JoinByComma());
         *
         *           foreach (var file in missingFiles)
         *           {
         *               tasks.Add(Task.Factory.StartNew(() =>
         *               {
         *                   Log.InfoFormat("Uploading file '{0}' ...", file);
         *                   uploadFile(
         *                       Paths.ATPRODEBUG_INSTALLATION_SHARE_PATH + @"\" + localShareLastVersion + @"\" + file,
         *                       googleLastBuildFolder.Id);
         *               }));
         *           }
         *       }
         *       Task.WaitAll(tasks.ToArray(), new TimeSpan(0, 30, 0));
         *   });
         * }*/

        private void DownloadFile(File fileResource, string _saveTo)
        {
            //Log.Info("Downloading file " + fileResource.DownloadUrl + " from share " + service.Name);
            Wait.UntilNumberOfExceptions(() =>
            {
                if (!String.IsNullOrEmpty(fileResource.DownloadUrl))
                {
                    /*var x = service.HttpClient.GetByteArrayAsync(fileResource.DownloadUrl);
                     * byte[] arrBytes = x.Result;
                     * System.IO.File.WriteAllBytes(_saveTo, arrBytes);*/
                    var outputStream = new MemoryStream();

                    var t = _service.Files.Get(fileResource.Id);
                    t.Download(outputStream);
                    if (outputStream.Length != fileResource.FileSize)
                    {
                        throw new Exception("Downloaded size invalid: " + fileResource.Title);
                    }
                    System.IO.File.WriteAllBytes(_saveTo, outputStream.ToArray());
                }
                else
                {
                    throw new Exception("DownloadUrl is null or emrty: " + fileResource.DownloadUrl);
                }
            });
        }
Esempio n. 8
0
        public static Google.Apis.Drive.v2.Data.File createDirectory(DriveService _service, string _title, string _description, string _parent)
        {
            Google.Apis.Drive.v2.Data.File NewDirectory = null;

            // Create metaData for a new Directory
            Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
            body.Title       = _title;
            body.Description = _description;
            body.MimeType    = "application/vnd.google-apps.folder";
            body.Parents     = new List <ParentReference>()
            {
                new ParentReference()
                {
                    Id = _parent
                }
            };

            try
            {
                if (!_service.Files.Equals("_title"))
                {
                    FilesResource.InsertRequest request = _service.Files.Insert(body);
                    NewDirectory = request.Execute();
                }
            }
            catch //(Exception e)
            {
                //Form1.AppendOutputText("ERROR (createDirectory): " + e.Message, Color.Red);
            }

            return(NewDirectory);
        }
Esempio n. 9
0
        public string  getchildInFolder(DriveService service, String folderId)
        {
            ChildrenResource.ListRequest request = service.Children.List(folderId);
            string file_id = "";

            do
            {
                try
                {
                    ChildList children = request.Execute();

                    foreach (ChildReference child in children.Items)
                    {
                        Google.Apis.Drive.v2.Data.File file1 = service.Files.Get(child.Id).Execute();
                        if (file1.Title.StartsWith("Build Plan"))
                        {
                            ListViewItem item = new ListViewItem(new string[2] {
                                file1.Title, child.Id
                            });
                            //  googleshareDoc = file1.Title;
                            this.spreadsheetListView.Items.Add(item);
                        }
                    }
                    request.PageToken = children.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    request.PageToken = null;
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(file_id);
        }
Esempio n. 10
0
        /// <summary>
        /// Update both metadata and content of a file and return the updated file.
        /// </summary>
        public static Google.Apis.Drive.v2.Data.File UpdateResource(Google.Apis.Drive.v2.DriveService service, IAuthenticator auth, String fileId, String newTitle,
                                                                    String newDescription, String newMimeType, String content, bool newRevision)
        {
            // First retrieve the file from the API.
            Google.Apis.Drive.v2.Data.File body = service.Files.Get(fileId).Fetch();

            body.Title       = newTitle;
            body.Description = newDescription;
            body.MimeType    = newMimeType;

            //byte[] byteArray = Encoding.ASCII.GetBytes(content);
            byte[]       byteArray = Encoding.UTF8.GetBytes(content);
            MemoryStream stream    = new MemoryStream(byteArray);

            Google.Apis.Drive.v2.FilesResource.UpdateMediaUpload request = service.Files.Update(body, fileId, stream, newMimeType);
            request.Upload();


            Permission newPermission = new Permission();

            newPermission.Type     = "anyone";
            newPermission.Role     = "reader";
            newPermission.Value    = "";
            newPermission.WithLink = true;
            service.Permissions.Insert(newPermission, fileId).Fetch();


            return(request.ResponseBody);
        }
Esempio n. 11
0
        public Google.Apis.Drive.v2.Data.File InsertFile(String title, String description, String parentId, String mimeType, FileInfo filename)
        {
            Google.Apis.Drive.v2.Data.File gooleFile = new Google.Apis.Drive.v2.Data.File();
            gooleFile.Title       = title;
            gooleFile.Description = description;
            gooleFile.MimeType    = mimeType;

            gooleFile.Shared   = true;
            gooleFile.Editable = true;

            if (!String.IsNullOrEmpty(parentId))
            {
                gooleFile.Parents = new List <ParentReference>()
                {
                    new ParentReference()
                    {
                        Id = parentId
                    }
                };
            }

            byte[] byteArray = System.IO.File.ReadAllBytes(filename.FullName);
            using (MemoryStream stream = new MemoryStream(byteArray))
            {
                FilesResource.InsertMediaUpload request = GoogleService.GetInstance().Service(this.m_User).Files.Insert(gooleFile, stream, mimeType);
                request.Upload();

                return(request.ResponseBody);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// 上傳檔案
        /// </summary>
        /// <param name="uploadFileName">上傳的檔案名稱 </param>
        /// <param name="contentType">上傳的檔案種類,請參考MIME Type : http://www.iana.org/assignments/media-types/media-types.xhtml </param>
        /// <param name="uploadProgressEventHandler"> 上傳進度改變時呼叫的函式</param>
        /// <param name="responseReceivedEventHandler">收到回應時呼叫的函式 </param>
        /// <returns>上傳成功,回傳上傳成功的 Google Drive 格式之File</returns>
        public Google.Apis.Drive.v2.Data.File UploadFile(string uploadFileName, string contentType, Action <IUploadProgress> uploadProgressEventHandler = null, Action <Google.Apis.Drive.v2.Data.File> responseReceivedEventHandler = null)
        {
            FileStream uploadStream = new FileStream(uploadFileName, FileMode.Open, FileAccess.Read);
            string     title        = SubstractFileName(uploadFileName);

            this.CheckCredentialTimeStamp();
            Google.Apis.Drive.v2.Data.File fileToInsert = new Google.Apis.Drive.v2.Data.File
            {
                Title = title
            };
            FilesResource.InsertMediaUpload insertRequest = _service.Files.Insert(fileToInsert, uploadStream, contentType);
            insertRequest.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize * 2;

            AddUploadEventHandler(uploadProgressEventHandler, responseReceivedEventHandler, insertRequest);

            try
            {
                insertRequest.Upload();
            }
            catch (Exception exception)
            {
                ShowMessage(exception.Message.ToString());
                throw exception;
            }
            finally
            {
                uploadStream.Close();
            }

            return(insertRequest.ResponseBody);
        }
Esempio n. 13
0
        public File FileFromString(string fileJsonString)
        {
            var fileJson = JObject.Parse(fileJsonString);

            var file = new File
            {
                Id           = fileJson.Value <string>("id"),
                Title        = fileJson.Value <string>("title"),
                MimeType     = fileJson.Value <string>("mimeType"),
                FileSize     = fileJson.Value <long>("fileSize"),
                CreatedDate  = fileJson.Value <DateTime>("createdDate"),
                ModifiedDate = fileJson.Value <DateTime>("modifiedDate"),
            };

            var folderId = (string)fileJson.SelectToken("parents[0].id");

            if (!String.IsNullOrEmpty(folderId))
            {
                file.Parents = new List <ParentReference> {
                    new ParentReference {
                        Id = folderId
                    }
                }
            }
            ;

            return(file);
        }
Esempio n. 14
0
        public void DownloadFile(Google.Apis.Drive.v2.Data.File file, string saveTo)
        {
            var request = _driveService.Files.Get(file.Id);
            var stream  = new System.IO.MemoryStream();

            // Add a handler which will be notified on progress changes.
            // It will notify on each chunk download and when the
            // download is completed or failed.
            request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
            {
                switch (progress.Status)
                {
                case Google.Apis.Download.DownloadStatus.Downloading:
                {
                    Console.WriteLine(progress.BytesDownloaded);
                    break;
                }

                case Google.Apis.Download.DownloadStatus.Completed:
                {
                    Console.WriteLine("Download complete.");
                    SaveStream(stream, saveTo);
                    break;
                }

                case Google.Apis.Download.DownloadStatus.Failed:
                {
                    Console.WriteLine("Download failed.");
                    break;
                }
                }
            };
            request.Download(stream);
        }
        //Download content of a file as stream
        public async Task <Stream> GetContentStreamAsync(Google.Apis.Drive.v2.Data.File fileEntry)
        {
            //Not every file resources in Google Drive has file content.
            //For example, a folder
            if (fileEntry.FileSize == null)
            {
                Console.WriteLine(fileEntry.Title + " is not a file. Skipped.");
                Console.WriteLine();
                return(null);
            }

            //Generate URI to file resource
            //"alt=media" indicates downloading file content instead of JSON metadata
            Uri fileUri = new Uri(BASE_URI + fileEntry.Id + "?alt=media");

            try
            {
                //Use HTTP client in DriveService to obtain response
                Task <Stream> fileContentStream = driveService.HttpClient.GetStreamAsync(fileUri);
                Console.WriteLine("Downloading file {0}...", fileEntry.Title);

                return(await fileContentStream);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error while downloading file: " + e.Message);
                return(null);
            }
        }
Esempio n. 16
0
        public File UpdateEntry(File entry)
        {
            var request = _driveService.Files.Update(entry, entry.Id);

            request.NewRevision = false;
            return(request.Execute());
        }
Esempio n. 17
0
 public void DownloadFile(string FilePath, string DirectoryPath)
 {
     if (System.IO.Directory.Exists(DirectoryPath))
     {
         Google.Apis.Drive.v2.Data.File File = GetFileByPath(FilePath);
         if (File != null)
         {
             if (File.DownloadUrl != null)
             {
                 byte[] FileBytes = service.HttpClient.GetByteArrayAsync(File.DownloadUrl).Result;
                 System.IO.File.WriteAllBytes(DirectoryPath + File.Title, FileBytes);
             }
             else if (File.MimeType.Equals("application/vnd.google-apps.folder"))
             {
                 throw new Exception("Cannot download a directory");
             }
         }
         else
         {
             throw new Exception("File not found");
         }
     }
     else
     {
         throw new Exception("No such local directory");
     }
 }
 public static Google.Apis.Drive.v2.Data.File UploadFile(DriveService _service, string _uploadFile, string _parent)
 {
     GException = null;
     if (System.IO.File.Exists(_uploadFile))
     {
         Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File
         {
             Title       = System.IO.Path.GetFileName(_uploadFile),
             Description = "File uploaded by " + Application.ProductName,
             MimeType    = GetMimeType(_uploadFile),
             Parents     = new List <ParentReference>()
             {
                 new ParentReference()
                 {
                     Id = _parent
                 }
             }
         };
         byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
         System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
         try
         {
             FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
             request.Upload();
             return(request.ResponseBody);
         }
         catch (Exception ex) { GException = ex; return(null); }
     }
     else
     {
         GException = new Exception("File does not exist: " + _uploadFile); return(null);
     }
 }
        public static Google.Apis.Drive.v2.Data.File createDirectory(DriveService _service, string _title, string _description, string _parent)
        {
            Google.Apis.Drive.v2.Data.File NewDirectory = null;
            Google.Apis.Drive.v2.Data.File body         = new Google.Apis.Drive.v2.Data.File
            {
                Title       = _title,
                Description = _description,
                MimeType    = "application/vnd.google-apps.folder",
                Parents     = new List <ParentReference>()
                {
                    new ParentReference()
                    {
                        Id = _parent
                    }
                }
            };

            try
            {
                GException = null;
                FilesResource.InsertRequest request = _service.Files.Insert(body);
                NewDirectory = request.Execute();
            }
            catch (Exception ex) { GException = ex; }

            return(NewDirectory);
        }
Esempio n. 20
0
        public async Task <FileSystemInfoContract> CopyItemAsync(RootName root, FileSystemId source, string copyName, DirectoryId destination, bool recurse)
        {
            if (source is DirectoryId)
            {
                throw new NotSupportedException(Properties.Resources.CopyingOfDirectoriesNotSupported);
            }

            var context = await RequireContextAsync(root);

            var copy = new GoogleFile()
            {
                Title = copyName
            };

            if (destination != null)
            {
                copy.Parents = new[] { new ParentReference()
                                       {
                                           Id = destination.Value
                                       } }
            }
            ;
            var item = await retryPolicy.ExecuteAsync(() => context.Service.Files.Copy(copy, source.Value).ExecuteAsync());

            return(item.ToFileSystemInfoContract());
        }
Esempio n. 21
0
        public void DrainQueue()
        {
            Google.Apis.Drive.v2.Data.File file           = new Google.Apis.Drive.v2.Data.File();
            DataContractJsonSerializer     jsonSerializer = new DataContractJsonSerializer(file.GetType());
            CloudQueueMessage message = null;

            do
            {
                try
                {
                    message = queue.GetMessage();
                    if (message != null)
                    {
                        try
                        {
                            MemoryStream memoryStream = new MemoryStream(Encoding.Default.GetBytes(message.AsString));
                            file = jsonSerializer.ReadObject(memoryStream) as Google.Apis.Drive.v2.Data.File;
                            ProcessGDriveFile(file, ProcessFile);
                        }
                        finally
                        {
                            queue.DeleteMessage(message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception: {0} {1}", ex.Message.ToString(), ex.StackTrace.ToString());
                }
            }while (message != null);
        }
        private static File CreateFolderToUpload(string name, string parentId)
        {
            var property = new Property
            {
                Key        = SyncFolderPropertyKey,
                Value      = SyncFolderPropertyValue,
                Visibility = "PRIVATE"
            };

            var file = new File
            {
                Title      = name,
                MimeType   = "application/vnd.google-apps.folder",
                Properties = new List <Property> {
                    property
                }
            };

            if (!string.IsNullOrWhiteSpace(parentId))
            {
                file.Parents = new List <ParentReference>
                {
                    new ParentReference
                    {
                        Id = parentId
                    }
                };
            }

            return(file);
        }
Esempio n. 23
0
        /// <summary>
        /// Update an existing file's metadata and content.
        /// </summary>
        /// <param name="service">Drive API service instance.</param>
        /// <param name="fileId">ID of the file to update.</param>
        /// <param name="newTitle">New title for the file.</param>
        /// <param name="newDescription">New description for the file.</param>
        /// <param name="newMimeType">New MIME type for the file.</param>
        /// <param name="newFilename">Filename of the new content to upload.</param>
        /// <param name="newRevision">Whether or not to create a new revision for this file.</param>
        /// <returns>Updated file metadata, null is returned if an API error occurred.</returns>
        public static Google.Apis.Drive.v2.Data.File updateFile(String fileId, String newTitle, String newContent, String newFilename, bool newRevision)
        {
            try
            {
                // First retrieve the file from the API.
                Google.Apis.Drive.v2.Data.File file = service.Files.Get(fileId).Execute();

                // File's new metadata.
                file.Title = newTitle;

                // File's new content.
                //byte[] byteArray = System.IO.File.ReadAllBytes(newFilename);
                byte[] byteArray = System.Text.Encoding.Unicode.GetBytes(newContent);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

                // Send the request to the API.
                FilesResource.UpdateMediaUpload request = service.Files.Update(file, fileId, stream, file.MimeType);
                request.NewRevision = newRevision;
                request.Upload();

                currentJobFile = request.ResponseBody;
                return(currentJobFile);
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
                return(null);
            }
        }
Esempio n. 24
0
        private static void UploadFile(DriveService service)
        {
            Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
            body.Title       = "test upload";
            body.Description = "test upload";
            body.MimeType    = "application/vnd.ms-excel";


            // GoogleFile's content.
            byte[]       byteArray = System.IO.File.ReadAllBytes(@"C:\Users\Jasarsoft\Google Drive\Private\Expense\Boravak - Mostar.xlsx");
            MemoryStream stream    = new MemoryStream(byteArray);

            try
            {
                FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "application/vnd.google-apps.spreadsheet");
                request.Upload();

                Google.Apis.Drive.v2.Data.File file = request.ResponseBody;

                // Uncomment the following line to print the GoogleFile ID.
                // Console.WriteLine("GoogleFile ID: " + file.Id);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                //Console.WriteLine("An error occurred: " + e.Message);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Creates the files for the very first time on Google Drive
        /// </summary>
        /// <param name="title">Title of the Document.</param>
        /// <param name="contents">Document's body.</param>
        /// <returns></returns>
        public static bool createFile(string title, string contents)
        {
            try
            {
                Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
                body.Title       = title;
                body.Description = "Uploaded from Google Docs Desktop Utility.";
                body.MimeType    = "text/plain";

                //byte[] byteArray = System.IO.File.ReadAllBytes("document.txt");
                byte[] byteArray = System.Text.Encoding.Unicode.GetBytes(contents);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

                FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
                FilesResource             filesResource = service.Files;
                FilesResource.ListRequest listRequest   = filesResource.List();
                request.Upload();

                currentJobFile = request.ResponseBody;

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Esempio n. 26
0
        /*      public Boolean DownloadFile(DriveService service, GFile _fileResource, string _saveTo)
        {
            try {
                  //File file = service.Files.Get(fileId).Execute();
                FilesResource.GetRequest request = service.Files.Get(_fileResource.Id);
                request.url
                  return true;
                }
            catch (Exception e) {
                return false;
                }
        }*/
        public Boolean DownloadFile(DriveService service, GFile _fileResource, string _saveTo)
        {
            GFile newFile = service.Files.Get(_fileResource.Id).Execute();
            if (!String.IsNullOrEmpty(_fileResource.DownloadUrl))
            {
                using (FileStream fs = System.IO.File.Create(_saveTo))
                {
                    //Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
                    // Add some information to the file.

                    var x = service.HttpClient.GetByteArrayAsync(newFile.DownloadUrl);
                    byte[] arrBytes = x.Result;
                    //fs.WriteAllBytes(_saveTo, arrBytes);
                    fs.Write(arrBytes, 0, arrBytes.Length);
                    //fs.WriteAsync()
                    //fs.Write(arrBytes, 0, arrBytes.Length);
                    return true;
                }
            }
            else
            {
                // The file doesn't have any content stored on Drive.
                //winform.AddText("Error2");
                return false;
            }
            return false;
        }
Esempio n. 27
0
        public async Task <Google.Apis.Drive.v2.Data.File> UploadFile(string uploadFileName, string contentType, Action <IUploadProgress> uploadProgressEventHandler = null, Action <Google.Apis.Drive.v2.Data.File> responseReceivedEventHandler = null)//上傳檔案
        {
            Windows.Storage.StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFile file = await folder.GetFileAsync(uploadFileName);

            IRandomAccessStream readStream = await file.OpenReadAsync();

            Stream uploadStream = readStream.AsStream();
            string title        = uploadFileName;

            this.CheckCredentialTimeStamp();
            Google.Apis.Drive.v2.Data.File fileToInsert = new Google.Apis.Drive.v2.Data.File
            {
                Title = title
            };
            FilesResource.InsertMediaUpload insertRequest = _service.Files.Insert(fileToInsert, uploadStream, contentType);
            insertRequest.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize * DOUBLE;
            AddUploadEventHandler(uploadProgressEventHandler, responseReceivedEventHandler, insertRequest);
            try
            {
                insertRequest.Upload();
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                uploadStream.Dispose();
            }
            return(insertRequest.ResponseBody);
        }
Esempio n. 28
0
        /// <summary>Deletes the given file from drive (not the file system).</summary>
        private async Task DeleteFile(DriveService service, Google.Apis.Drive.v2.Data.File file)
        {
            Console.WriteLine("Deleting file '{0}'...", file.Id);
            await service.Files.Delete(file.Id).ExecuteAsync();

            Console.WriteLine("File was deleted successfully");
        }
Esempio n. 29
0
        public void getBookFromOnlineLibrary(int element)
        {
            string fileId = System.IO.File.ReadLines(_toReadWeb.FullName).Skip(element).First().Split(":".ToCharArray())[0];

            Google.Apis.Drive.v2.Data.File file = _webService.Files.Get(fileId).Execute();
            downloadFile(_webService, file, _toReadPath + file.Title);
        }
Esempio n. 30
0
        /// <summary>
        /// Uploads a file
        /// Documentation: https://developers.google.com/drive/v2/reference/files/insert
        /// </summary>
        /// <param name="service">a Valid authenticated DriveService</param>
        /// <param name="uploadFile">path to the file to upload</param>
        /// <param name="parentIdFolder">Collection of parent folders which contain this file.
        ///                       Setting this field will put the file in all of the provided folders. root folder.</param>
        /// <returns>If upload succeeded returns the File resource of the uploaded file
        ///          If the upload fails returns null</returns>
        public static File UploadFile(DriveService service, string uploadFile, string parentIdFolder)
        {
            if (System.IO.File.Exists(uploadFile))
            {
                File body = new File
                {
                    Title       = Path.GetFileName(uploadFile),
                    Description = "File uploaded",
                    MimeType    = GetMimeType(uploadFile),
                    Parents     = new List <ParentReference> {
                        new ParentReference {
                            Id = parentIdFolder
                        }
                    }
                };

                // File's content.
                byte[]       byteArray = System.IO.File.ReadAllBytes(uploadFile);
                MemoryStream stream    = new MemoryStream(byteArray);
                try
                {
                    FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, GetMimeType(uploadFile));
                    request.Upload();
                    return(request.ResponseBody);
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    return(null);
                }
            }
            Console.WriteLine("File does not exist: " + uploadFile);
            return(null);
        }
        /// <summary>
        /// 上傳檔案
        /// </summary>
        /// <param name="uploadFileName">上傳的檔案名稱 </param>
        /// <param name="contentType">上傳的檔案種類,請參考MIME Type : http://www.iana.org/assignments/media-types/media-types.xhtml </param>
        /// <param name="uploadProgressEventHandler"> 上傳進度改變時呼叫的函式</param>
        /// <param name="responseReceivedEventHandler">收到回應時呼叫的函式 </param>
        /// <returns>上傳成功,回傳上傳成功的 Google Drive 格式之File</returns>
        public async Task <Google.Apis.Drive.v2.Data.File> UploadFile(string uploadFileName, string contentType, Action <IUploadProgress> uploadProgressEventHandler = null, Action <Google.Apis.Drive.v2.Data.File> responseReceivedEventHandler = null)
        {
            StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(uploadFileName);

            Stream uploadStream = await file.OpenStreamForReadAsync();

            string title = SubstractFileName(uploadFileName);

            this.CheckCredentialTimeStamp();
            Google.Apis.Drive.v2.Data.File fileToInsert = new Google.Apis.Drive.v2.Data.File
            {
                Title = title
            };

            FilesResource.InsertMediaUpload insertRequest = _service.Files.Insert(fileToInsert, uploadStream, contentType);
            insertRequest.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize * 2;
            AddUploadEventHandler(uploadProgressEventHandler, responseReceivedEventHandler, insertRequest);

            try
            {
                insertRequest.Upload();
            }
            catch (Exception e)
            {
                ShowMessage(e.Message);
            }
            finally
            {
                uploadStream.Dispose();
            }

            return(insertRequest.ResponseBody);
        }
Esempio n. 32
0
        /// <summary>
        /// Create a new file and return it.
        /// </summary>
        public static File CreateFile(
            [NotNull] DriveService service,
            [NotNull] String title,
            [NotNull] String description,
            [NotNull] String mimeType, [NotNull] MemoryStream fileContent, IList<ParentReference> parentReference = null)
        {
            if (service == null) throw new ArgumentNullException("service");
            if (title == null) throw new ArgumentNullException("title");
            if (description == null) throw new ArgumentNullException("description");
            if (mimeType == null) throw new ArgumentNullException("mimeType");
            if (fileContent == null) throw new ArgumentNullException("fileContent");

            // File's metadata.
            var fileBody = new File
            {
                Title = title,
                Description = description,
                MimeType = mimeType,
                Parents = parentReference
            };

            var request = service.Files.Insert(fileBody, fileContent, mimeType);
            request.Upload();

            return request.ResponseBody;
        }
        // Returns the image
        public FileStreamResult GetImage(string path, string id, bool allowCompress, ImageSize size, params FileManagerDirectoryContent[] data)
        {
            DriveService service = GetService();
            File         file    = service.Files.Get(id).Execute();

            return(new FileStreamResult(new MemoryStream((service.HttpClient.GetByteArrayAsync(file.DownloadUrl).Result)), "APPLICATION/octet-stream"));
        }
Esempio n. 34
0
        public string UploadFolderWithParent(ParentReference parentId, string title)
        {
            var folder = new File {Title = title, Parents = new List<ParentReference> {parentId}, MimeType = "application/vnd.google-apps.folder"};
              var request = mService.Files.Insert(folder);
              request.Convert = true;
              var result = request.Fetch();

              return result.Id;
        }
Esempio n. 35
0
 private FileMetadata GetFileMetadata(File file)
 {
     return new FileMetadata
     {
         IsFolder = string.Equals(file.MimeType, "application/vnd.google-apps.folder", StringComparison.OrdinalIgnoreCase),
         Name = file.Title,
         Id = file.Id,
         MimeType = file.MimeType
     };
 }
Esempio n. 36
0
        public void UploadFileWithParent(ParentReference parentId, string path, string title)
        {
            var file = new File {Title = title, Parents = new List<ParentReference> {parentId}, MimeType = DetermineContentType(path)};
              var byteArray = System.IO.File.ReadAllBytes(path);
              var stream = new MemoryStream(byteArray);

              var request = mService.Files.Insert(file, stream , DetermineContentType(path));
              request.Convert = true;
              request.Upload();
        }
        public Google.Apis.Drive.v2.Data.File CreateDirectory(string parent_path, string file_name)
        {
            Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
            body.Title = file_name;
            body.MimeType = "application/vnd.google-apps.folder";
            body.Parents = new List<ParentReference>() 
            {
                new ParentReference() { Id = GetIdByPath(parent_path) } 
            };

            return _driveService.Files.Insert(body).Execute();
        }
Esempio n. 38
0
        private static Google.Apis.Drive.v2.Data.File GetFile(DriveService drvService)
        {
            FilesResource.ListRequest request = drvService.Files.List();
            FileList files = request.Execute();
            Google.Apis.Drive.v2.Data.File pepitoTweets = new File();

            foreach (Google.Apis.Drive.v2.Data.File item in files.Items)
            {
                if (item.Title.Equals("Tweets.txt", StringComparison.CurrentCultureIgnoreCase))
                {
                    pepitoTweets = item;
                }
            }
            return pepitoTweets;
        }
Esempio n. 39
0
        /// <summary>
        /// Create a new file and return it.
        /// </summary>
        public static File CreateFolder(
            [NotNull] DriveService service,
            [NotNull] String title,
            [NotNull] String description)
        {
            if (service == null) throw new ArgumentNullException("service");
            if (title == null) throw new ArgumentNullException("title");
            if (description == null) throw new ArgumentNullException("description");

            var files = service.Files.List().Fetch();
            var pt = files.NextPageToken;

            // Folder's metadata.
            var folderBody = new File { Title = title, Description = description, MimeType = "application/vnd.google-apps.folder" };
            return service.Files.Insert(folderBody).Fetch();
        }
Esempio n. 40
0
        private async Task<string> CreateDirectory(string title, string parent = null)
        {
            File directory = null;
            File body = new File
            {
                Title = title,
                MimeType = "application/vnd.google-apps.folder"
            };

            try
            {
                FilesResource.InsertRequest request = this.service.Files.Insert(body);
                directory = await request.ExecuteAsync();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            return directory.Id;
        }
        /// <summary>
        ///     Create a new Directory.
        ///     Documentation: https://developers.google.com/drive/v2/reference/files/insert
        /// </summary>
        /// <param name="service">a Valid authenticated DriveService</param>
        /// <param name="title">The title of the file. Used to identify file or folder name.</param>
        /// <param name="description">A short description of the file.</param>
        /// <param name="parentDirectoryId">
        ///     Collection of parent folders which contain this file.
        ///     Setting this field will put the file in all of the provided folders. root folder.
        /// </param>
        /// <returns></returns>
        public static File CreateDirectory(
            DriveService service,
            string title,
            string description,
            string parentDirectoryId)
        {
            if (string.IsNullOrWhiteSpace(parentDirectoryId))
            {
                throw new ArgumentNullException("Parent folder ID can not be empty!");
            }

            if (string.IsNullOrWhiteSpace(title))
            {
                throw new ArgumentNullException("parentDirectoryId name can not be empty!");
            }

            if (service == null)
            {
                throw new ArgumentNullException("Google Drive DriveService is not initialized!");
            }

            if (service.HttpClientInitializer == null)
            {
                throw new AuthenticationException("Authentication error! Please use the Authentication class to initialize the Google Drive service!");
            }

            File newDirectory = null;

            // Create metaData for a new Directory
            var body = new File();
            body.Title = title;
            body.Description = description;
            body.MimeType = "application/vnd.google-apps.folder";
            body.Parents = new List<ParentReference> { new ParentReference { Id = parentDirectoryId } };

            var request = service.Files.Insert(body);
            newDirectory = request.Execute();

            return newDirectory;
        }
Esempio n. 42
0
        /// <summary>
        /// Create a new Directory.
        /// Documentation: https://developers.google.com/drive/v2/reference/files/insert
        /// </summary>
        /// <param name="_service">a Valid authenticated DriveService</param>
        /// <param name="_title">The title of the file. Used to identify file or folder name.</param>
        /// <param name="_description">A short description of the file.</param>
        /// <param name="_parent">Collection of parent folders which contain this file. 
        ///                       Setting this field will put the file in all of the provided folders. root folder.</param>
        /// <returns></returns>
        public static File createDirectory(DriveService _service, string _title, string _description, string _parent)
        {
            File NewDirectory = null;

            // Create metaData for a new Directory
            File body = new File();
            body.Title = _title;
            body.Description = _description;
            body.MimeType = "application/vnd.google-apps.folder";
            body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };
            try
            {
                FilesResource.InsertRequest request = _service.Files.Insert(body);
                NewDirectory = request.Execute();
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
            }

            return NewDirectory;
        }
Esempio n. 43
0
 /// <summary>
 /// Download a file
 /// Documentation: https://developers.google.com/drive/v2/reference/files/get
 /// </summary>
 /// <param name="_service">a Valid authenticated DriveService</param>
 /// <param name="_fileResource">File resource of the file to download</param>
 /// <param name="_saveTo">location of where to save the file including the file name to save it as.</param>
 /// <returns></returns>
 public static Boolean downloadFile(DriveService _service, File _fileResource, string _saveTo)
 {
     if (!String.IsNullOrEmpty(_fileResource.DownloadUrl))
     {
         try
         {
             var x = _service.HttpClient.GetByteArrayAsync(_fileResource.DownloadUrl);
             byte[] arrBytes = x.Result;
             System.IO.File.WriteAllBytes(_saveTo, arrBytes);
             return true;
         }
         catch (Exception e)
         {
             Console.WriteLine("An error occurred: " + e.Message);
             return false;
         }
     }
     else
     {
         // The file doesn't have any content stored on Drive.
         return false;
     }
 }
    public async Task Upload(string fileName, string path)
    {
        Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
        body.Title = System.IO.Path.GetFileName(path);
        body.Description = "File uploaded OneBox";
        body.MimeType = GetMimeType(fileName);

        byte[] byteArray = System.IO.File.ReadAllBytes(path);
        MemoryStream stream = new MemoryStream(byteArray);
        string id = CheckForDuplicates(body);

        if (id == null)
        {
            FilesResource.InsertMediaUpload request = this.service.Files.Insert(body, stream, body.MimeType);
            request.Upload();
        }
        //else
        //{
        //    FilesResource.UpdateRequest request = this.service.Files.Update(body, id);
        //    request.Execute();
        //}

        stream.Close();
    }
Esempio n. 45
0
        /// <summary>
        /// Inserts a new file into the Google Drive.
        /// </summary>
        /// <param name="service">Drive API service instance.</param>
        /// <param name="title">Title (name) of the file to insert, including the extension.</param>
        /// <param name="description">Description of the file to insert.</param>
        /// <param name="parentId">Parent folder's ID. (Empty string to put the file in the drive root)</param>
        /// <param name="mimeType">MIME type of the file to insert.</param>
        /// <param name="filename">Filename (including path) of the file to upload relative to the local machine.</param>
        /// <returns>Inserted file metadata, null is returned if an API error occurred.</returns>
        /// <remarks>The filename passed to this function should be the entire path and filename (with extension) for the source file on the
        /// local machine. The API will put the file in the Google Drive using the "Title" property.</remarks>
        public static Google.Apis.Drive.v2.Data.File InsertFile(DriveService service, String title, String description, String parentId, String mimeType, String filename)
        {
            // File's metadata.
            Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
            body.Title = title;
            body.Description = description;
            body.MimeType = mimeType;

            // Set the parent folder.
            if (!String.IsNullOrEmpty(parentId))
            {
            body.Parents = new List<ParentReference>() { new ParentReference() { Id = parentId } };
            }

            // Load the File's content and put it into a memory stream
            byte[] byteArray = System.IO.File.ReadAllBytes(filename);
            MemoryStream stream = new MemoryStream(byteArray);

            try
            {
            // When we add a file, we create an Insert request then call the Upload method on the request.
            // (If we were updating an existing file, we would use the Update function)
            FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
            request.Upload();

            // Set the file object to the response of the upload
            Google.Apis.Drive.v2.Data.File file = request.ResponseBody;

            // Uncomment the following line to print the File ID.
            // Console.WriteLine("File ID: " + file.Id);

            // return the file object so the caller has a reference to it.
            return file;
            }
            catch (Exception e)
            {
            // May want to log this or do something with it other than just dumping to the console.
            Console.WriteLine("An error occurred: " + e.Message);
            return null;
            }
        }
 private FileSystemMetadata GetFileMetadata(File file)
 {
     return new FileSystemMetadata
     {
         IsDirectory = string.Equals(file.MimeType, "application/vnd.google-apps.folder", StringComparison.OrdinalIgnoreCase),
         Name = file.Title,
         FullName = file.Id,
         //MimeType = file.MimeType
     };
 }
        private static File CreateFolderToUpload(string name, string parentId)
        {
            var property = new Property
            {
                Key = SyncFolderPropertyKey,
                Value = SyncFolderPropertyValue,
                Visibility = "PRIVATE"
            };

            File file = new File
            {
                Title = name,
                MimeType = "application/vnd.google-apps.folder",
                Properties = new List<Property> { property }
            };

            if (!string.IsNullOrWhiteSpace(parentId))
            {
                file.Parents = new List<ParentReference>
                {
                    new ParentReference
                    {
                       Id = parentId
                    }
                };
            }

            return file;
        }
        private static async Task ExecuteUpload(DriveService driveService, Stream stream, File file, IProgress<double> progress, CancellationToken cancellationToken)
        {
            var request = driveService.Files.Insert(file, stream, "application/octet-stream");

            var streamLength = stream.Length;
            request.ProgressChanged += (uploadProgress) => progress.Report(uploadProgress.BytesSent / streamLength * 100);

            await request.UploadAsync(cancellationToken);
        }
        public async Task<FileInfoContract> NewFileItemAsync(RootName root, DirectoryId parent, string name, Stream content, IProgress<ProgressValue> progress)
        {
            var context = await RequireContext(root);

            var file = new GoogleFile() { Title = name, MimeType = MIME_TYPE_FILE, Parents = new[] { new ParentReference() { Id = parent.Value } } };
            var insert = context.Service.Files.Insert(file, content, MIME_TYPE_FILE);
            insert.ProgressChanged += p => progress.Report(new ProgressValue((int)p.BytesSent, (int)content.Length));
            var upload = await AsyncFunc.Retry<IUploadProgress, GoogleApiException>(async () => await insert.UploadAsync(), RETRIES);
            var item = insert.ResponseBody;

            return new FileInfoContract(item.Id, item.Title, new DateTimeOffset(item.CreatedDate.Value), new DateTimeOffset(item.ModifiedDate.Value), item.FileSize.Value, item.Md5Checksum);
        }
        private void button1_Click(object sender, EventArgs e)
        {
         
            listBoxCloud.Items.Clear();
            Google.Apis.Drive.v2.Data.File fFile = Business.getFile(curFolder.Title);
            if (fFile.Parents[0].IsRoot == true)
                foreach (var file in Business.elem)
                {
                    if (file.Parents.Count != 0)
                    {
                        if (file.Parents[0].IsRoot == true)
                            listBoxCloud.Items.Add(file.Title);
                    }
                }
            else
            {
                curFolder = Business.getFilebyID(fFile.Parents[0].Id);
                foreach (var file in Business.elem)
                {
                    if (file.Parents[0].Id == curFolder.Id)
                        listBoxCloud.Items.Add(file.Title);

                }
            }
        
        }
        public async Task<FileSystemInfoContract> CopyItemAsync(RootName root, FileSystemId source, string copyName, DirectoryId destination, bool recurse)
        {
            var context = await RequireContext(root);

            var copy = new GoogleFile() { Title = copyName };
            if (destination != null)
                copy.Parents = new[] { new ParentReference() { Id = destination.Value } };
            var item = await AsyncFunc.Retry<GoogleFile, GoogleApiException>(async () => await context.Service.Files.Copy(copy, source.Value).ExecuteAsync(), RETRIES);

            return item.ToFileSystemInfoContract();
        }
        public async Task<FileSystemInfoContract> MoveItemAsync(RootName root, FileSystemId source, string moveName, DirectoryId destination, Func<FileSystemInfoLocator> locatorResolver)
        {
            var context = await RequireContext(root);

            var move = new GoogleFile() { Parents = new[] { new ParentReference() { Id = destination.Value } }, Title = moveName };
            var patch = context.Service.Files.Patch(move, source.Value);
            var item = await AsyncFunc.Retry<GoogleFile, GoogleApiException>(async () => await patch.ExecuteAsync(), RETRIES);

            return item.ToFileSystemInfoContract();
        }
        private File CopyFile(string newFileName, File file, string parentId)
        {
            var body = new File
            {
                Title = newFileName,
                MimeType = file.MimeType,
                Parents = new[]
                              {
                                  new ParentReference
                                  {
                                          Id = parentId
                                      }
                              }
            };

            var request = _driveService.Files.Copy(body, file.Id);
            var copy = request.Execute();
            if (copy == null)
            {
                throw new ApplicationException("Couldn't copy google drive file");
            }

            return copy;
        }
        private File CreateFile(string title, string parentId, string mimeType)
        {
            var body = new File
            {
                Title = title,
                MimeType = mimeType,
                Parents = new[]
                              {
                                  new ParentReference
                                  {
                                          Id = parentId
                                      }
                              }
            };

            var request = _driveService.Files.Insert(body);
            var file = request.Execute();
            if (file == null)
            {
                throw new ApplicationException("Couldn't create google drive file/folder");
            }

            return file;
        }
        public async Task<DirectoryInfoContract> NewDirectoryItemAsync(RootName root, DirectoryId parent, string name)
        {
            var context = await RequireContext(root);

            var file = new GoogleFile() { Title = name, MimeType = MIME_TYPE_DIRECTORY, Parents = new[] { new ParentReference() { Id = parent.Value } } };
            var item = await AsyncFunc.Retry<GoogleFile, GoogleApiException>(async () => await context.Service.Files.Insert(file).ExecuteAsync(), RETRIES);

            return new DirectoryInfoContract(item.Id, item.Title, new DateTimeOffset(item.CreatedDate.Value), new DateTimeOffset(item.ModifiedDate.Value));
        }
Esempio n. 56
0
        public void UploadFile(string file, string _parent)
        {
            Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
            body.Title = System.IO.Path.GetFileName(file);
            body.Description = "File uploaded by Diamto Drive Sample";
            body.MimeType = GetMimeType(file);
            body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };

            //// File's content.
            byte[] byteArray = System.IO.File.ReadAllBytes(file);
            System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);


            FilesResource.InsertMediaUpload request = Service.Files.Insert(body, stream, GetMimeType(file));
            //request.Convert = true;   // uncomment this line if you want files to be converted to Drive format
            request.Upload();
         ///////   return request.ResponseBody;
        }
        private void listBoxCloud_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            
            string curItem = listBoxCloud.SelectedItem.ToString();
            Google.Apis.Drive.v2.Data.File fFile = Business.getFile(curItem);
            if (fFile.MimeType.ToString() == "application/vnd.google-apps.folder")
            {
                curFolder = fFile;
                listBoxCloud.Items.Clear();
                foreach (var file in Business.elem)
                {
                    if (file.Parents.Count != 0)
                    {
                        if (file.Parents[0].Id == fFile.Id)
                            listBoxCloud.Items.Add(file.Title);
                    }
                }

            }


        }
Esempio n. 58
0
  public  Google.Apis.Drive.v2.Data.File CopyFile(String originFileId, String copyTitle)
  {
      Google.Apis.Drive.v2.Data.File copiedFile = new Google.Apis.Drive.v2.Data.File();
      copiedFile.Title = copyTitle;
 //     try
 //     {
          return Service.Files.Copy(copiedFile, originFileId).Execute();
          
 //     }
 //     catch (Exception e)
 //     {
 //         Console.WriteLine("An error occurred: " + e.Message);
 //     }
 //     return null;
  }
Esempio n. 59
0
        public Google.Apis.Drive.v2.Data.File CreateDirectory(string path)
        {
            path = path.Substring(1);
            string file_name = path.Substring(path.LastIndexOf('/'), path.Length);
            string parent_path = path.Substring(0, path.LastIndexOf('/'));

            Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
            body.Title = file_name;
            body.MimeType = "application/vnd.google-apps.folder";
            body.Parents = new List<ParentReference>()
            {
                new ParentReference() { Id = GetIdByPath(parent_path) }
            };

            return _driveService.Files.Insert(body).Execute();
        }
        public async Task<Google.Apis.Drive.v2.Data.File> SaveFileToDriveAppFolderAsync(string title, string contentType, Stream contentStream)
        {
            await InitAppFolderIdAsync().ConfigureAwait(false);

            Logger.Info($"Saving file {title} to appfolder...");

            Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File
            {
                Title = title,
                Parents = new List<ParentReference> { new ParentReference { Id = _appFolderId } },
                MimeType = contentType
            };

            FilesResource.InsertMediaUpload request = _driveService.Files.Insert(body, contentStream, contentType);
            await request.UploadAsync().ConfigureAwait(false);
            return request.ResponseBody;
        }