0

I am new to Google Drive and have following scenarios for which I am not able to find anything (not sure if anything exists or not) –> I am creating a Windows app which will be SAAS based. Different Users will register and create their company logins and subusers under them. Now I want them to put the google drive credentials in one of the form and this should work for rest of the users. Currently the problem is that while development I got the google log in done and it never asks for the login again but when testing on a different system with different login, it keeps asking for google login. I simply want admin users to put their google drive credentials and it should work for upload and download files for all the users for that company.

–> I want to keep versions of the same file (just like google drive does by default) on google drive. Lets say user A uploaded file xyz and then user B downloaded and changed file xyz and uploaded it on the drive again. I want 2 things here – only the changed content should get uploaded and not the whole file (this will save time for the user) 2ndly I want to have history of the same file so I can show in my Windows application

    #region Get Service Object
    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    new ClientSecrets
                    {
                        ClientId = "GoogleDriveClientID",
                        ClientSecret = "GoogleDriveClientSecret"
                    },
                    new[] { DriveService.Scope.Drive }, "user", CancellationToken.None).Result;


            // Create the service.
            service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "AppName",
            });
#endregion


#region Uploading
public void uploadOnGoogleDrive(ObservableCollection<JobAttachments> AttachmentsColl, bool IsDocSaved)
        {
            try
            {
                service = getServiceObject();

                List<Google.Apis.Drive.v2.Data.File> fileList = retrieveAllFiles(service);
                List<Google.Apis.Drive.v2.Data.File> directoryList = GetDirectoryList(service);

                if (IsDocSaved)
                {
                    #region for checking if the file already exists
                    foreach (Google.Apis.Drive.v2.Data.File item in fileList)
                    {
                        foreach (JobAttachments attach in AttachmentsColl)
                        {
                            if (item.Title == attach.AttachmtGUID)
                            {                               
                                MessageBoxResult result = System.Windows.MessageBox.Show(LogMessages.GetResourceMessage(LogMessages.MessageEnumeration.GD_AlreadyExistsMsg), "Confirmation", MessageBoxButton.YesNoCancel);

                                if (result == MessageBoxResult.Yes)
                                {
                                    //DeleteFile(service, item);
                                    Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
                                    body.Title = attach.AttachmtGUID;
                                    body.MimeType = item.MimeType;
                                    fileSize = body.FileSize;
                                    byte[] byteArray = System.IO.File.ReadAllBytes(attach.AttachmentName);
                                    System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

                                    FilesResource.UpdateMediaUpload request = service.Files.Update(body, item.Id, stream, item.MimeType);

                                    request.Upload();
                                }
                                else
                                {
                                    return;
                                }
                                break;
                            }
                        }
                    }
                    #endregion
                }
                else
                {
                    #region for direct uploading on google drive
                    if (AttachmentsCollection != null && AttachmentsCollection.Count > 0)
                    {
                        string folderID = string.Empty;
                        if (_IsProject)
                        {
                            if (directoryList != null && directoryList.Count > 0)
                            {
                                foreach (var dir in directoryList)
                                {
                                    if (dir.Title.Equals(_ProjectName))
                                    {
                                        folderID = dir.Id;
                                        break;
                                    }
                                }
                            }
                            if (string.IsNullOrEmpty(folderID))
                            {
                                Google.Apis.Drive.v2.Data.File foldbody = new Google.Apis.Drive.v2.Data.File();
                                foldbody.Title = _ProjectName;
                                foldbody.MimeType = "application/vnd.google-apps.folder";
                                foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } };
                                Google.Apis.Drive.v2.Data.File file = service.Files.Insert(foldbody).Execute();
                                folderID = file.Id;
                            }
                        }
                        else
                        {
                            //project folder
                            string prjFolder = string.Empty;
                            string tskFolder = string.Empty;
                            Google.Apis.Drive.v2.Data.File foldbody;
                            if (directoryList != null && directoryList.Count > 0)
                            {
                                foreach (var dir in directoryList)
                                {
                                    if (dir.Title.Equals(_ProjectName))
                                    {
                                        prjFolder = dir.Id;
                                        break;
                                    }
                                }
                            }
                            if (string.IsNullOrEmpty(prjFolder))
                            {
                                foldbody = new Google.Apis.Drive.v2.Data.File();
                                foldbody.Title = _ProjectName;
                                foldbody.MimeType = "application/vnd.google-apps.folder";
                                foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } };
                                Google.Apis.Drive.v2.Data.File file = service.Files.Insert(foldbody).Execute();
                                prjFolder = file.Id;
                            }

                            //task folder
                            if (directoryList != null && directoryList.Count > 0)
                            {
                                foreach (var dir in directoryList)
                                {
                                    if (dir.Title.Equals(_TaskName) && dir.Parents[0].Id.Equals(prjFolder))
                                    {
                                        folderID = dir.Id;
                                        break;
                                    }
                                }
                            }
                            if (string.IsNullOrWhiteSpace(folderID))
                            {
                                foldbody = new Google.Apis.Drive.v2.Data.File();
                                foldbody.Title = _TaskName;
                                foldbody.MimeType = "application/vnd.google-apps.folder";
                                foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = prjFolder } };
                                Google.Apis.Drive.v2.Data.File file1 = service.Files.Insert(foldbody).Execute();
                                folderID = file1.Id;
                            }
                        }

                        foreach (JobAttachments item in AttachmentsColl)
                        {
                            if (!string.IsNullOrEmpty(item.AttachmentName))
                            {
                                Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
                                body.Title = item.AttachmtGUID;
                                body.MimeType = item.MimeType;
                                body.Parents = new List<ParentReference>() { new ParentReference() { Id = folderID } };
                                //fileSize = body.FileSize;
                                byte[] byteArray = System.IO.File.ReadAllBytes(item.AttachmentName);
                                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

                                FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, item.MimeType);

                                request.Upload();
                            }
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    throw ex.InnerException;
            }
        }
#endregion

#region Download File
  private async Task DownloadFile(DriveService service, string url, string title, long? fSize)
        {
 service = getServiceObject();

 var downloader = new MediaDownloader(service);
                //downloader.ChunkSize = 256 * 1024;
                downloader.ProgressChanged += Download_ProgressChanged;
                var fileName = string.Empty;

//for downloading on system
                    var SaveFileDialog = new SaveFileDialog();
                    SaveFileDialog.Title = "Save As";
                    SaveFileDialog.FileName = title;
                    Nullable<bool> result = SaveFileDialog.ShowDialog();

                    if (result == true)
                        fileName = SaveFileDialog.FileName;
                    else if (result == false)
                    {
                        prgrsBar.StyleSettings = new ProgressBarStyleSettings();
                        prgrsBar.Value = 0;
                        return;
                    }
                    else
                    {
                        if (Directory.Exists(@"\Downloads"))
                            fileName = @"\Downloads\" + title;
                    }

 if (!string.IsNullOrWhiteSpace(fileName))
                    using (var fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        fileSize = fSize;
                        var progress = await downloader.DownloadAsync(url, fileStream); 

                        if (progress.Status.ToString() == DownloadStatus.Completed.ToString())
                        {
                            fName = fileStream.Name;
                            prgrsBar.StyleSettings = new ProgressBarStyleSettings();
                            prgrsBar.Value = 0;
                            fileStream.Flush();
                        }
                        if (progress.Status.ToString() == DownloadStatus.Failed.ToString())
                        {
                            HandleDocuments.IsEditButtonClicked = false;
                            MessageBox.Show("Failed......." + progress.Exception.Message);
                        }
                    }
}

#endregion


#region Delete File
 private Task DeleteFile(DriveService service, Google.Apis.Drive.v2.Data.File file)
        {
        service = getServiceObject(); //comment this if calling from another function; create the service object in that function and pass it as parameter to this function.
            service.Files.Delete(file.Id).ExecuteAsync();
            service.Files.EmptyTrash();
            return null;
        }
#endregion


#region Get all Directories and Files from Google Drive
        public List<Google.Apis.Drive.v2.Data.File> GetDirectoryList(DriveService service)
        {
            //Creating the global list
           List<Google.Apis.Drive.v2.Data.File> AllDirectories = new List<Google.Apis.Drive.v2.Data.File>();

            //setting up the Request.
            FilesResource.ListRequest request = service.Files.List();
            //MaxResults: How many we want back at a time max is 1000
            request.MaxResults = 1000;
            //Q: Search results. all i want are folders that havent been trashed (deleted)
            request.Q = "mimeType='application/vnd.google-apps.folder' and trashed=false";

            do
            {
                try
                {
                    // getting the results
                    FileList files = request.Execute();
                    // adding the results to the list.
                    AllDirectories.AddRange(files.Items);
                    // If there are more results then your MaxResults you will have a nextPageToken to get the rest of the results.
                    request.PageToken = files.NextPageToken;
                }
                catch (Exception ex)
                {
                    request.PageToken = null;
                    if (ex.InnerException != null)
                        throw ex.InnerException;
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            List<Google.Apis.Drive.v2.Data.File> DirsInRoot = AllDirectories.Where(a => (a.Parents.Count > 0 && a.Parents.FirstOrDefault().IsRoot.HasValue) ? a.Parents.FirstOrDefault().IsRoot.Value : false).ToList<Google.Apis.Drive.v2.Data.File>();

            List<string> HirearcyList = new List<string>();
            // The first Dir is Root it doesnt get returned. But we need it if we 
            //   Want to be able to list the files that are in the root dir.
            HirearcyList.Add("Root");

            // recersive magic here.
            foreach (Google.Apis.Drive.v2.Data.File myDir in DirsInRoot)
            {
                HirearcyList.Add("     " + myDir.Title);
                HirearcyList.AddRange(RecsiveDir(AllDirectories, myDir.Id, "     "));
            }
            return AllDirectories;
        }

        public List<String> RecsiveDir(List<Google.Apis.Drive.v2.Data.File> allDirs, string ParentId, string Prefix)
        {
            List<string> result = new List<string>();
            List<Google.Apis.Drive.v2.Data.File> DirsInParentId = allDirs.Where(a => (a.Parents.Count > 0 && a.Parents.FirstOrDefault().IsRoot.HasValue) ? a.Parents.FirstOrDefault().Id == ParentId : false).ToList<Google.Apis.Drive.v2.Data.File>();

            foreach (Google.Apis.Drive.v2.Data.File myDir in DirsInParentId)
            {
                result.Add(Prefix + myDir.Title);
                result.AddRange(RecsiveDir(allDirs, myDir.Id, Prefix + "     "));
            }
            return result;
        }

        public static List<Google.Apis.Drive.v2.Data.File> retrieveAllFiles(DriveService service)
        {
            List<Google.Apis.Drive.v2.Data.File> result = new List<Google.Apis.Drive.v2.Data.File>();
            FilesResource.ListRequest request = service.Files.List();
            request.MaxResults = 1000;
            do
            {
                try
                {
                    FileList files = request.Execute();
                    result.AddRange(files.Items);
                    request.PageToken = files.NextPageToken;
                    //service.Revisions.List(files.Items[0].Id) // for getting the file Revision history
                }
                catch (Exception ex)
                {
                    request.PageToken = null;
                    if (ex.InnerException != null)
                        throw ex.InnerException;
                }
            } while (!String.IsNullOrEmpty(request.PageToken));
            return result;
        }
#endregion

Thanks Jatinder

2
  • Could you please add the code of what you have tried so far. Jul 2, 2014 at 8:59
  • You should be able to edit your original post there is link edit under the question under the tags. Jul 2, 2014 at 10:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.