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; }
public void SetupFolders(int numberOfFolders) { var parent = new ParentReference {Id = "root"}; for (var x = 0; x < numberOfFolders; x++) { var folder = new File {MimeType = "application/vnd.google-apps.folder", Title = "TestingFolder" + x, Parents = new[] {parent}}; var result = mService.Files.Insert(folder).Fetch(); parent = new ParentReference {Id = result.Id}; } }
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 void UploadFileWithFolderSet(string file, string fileTitle, string[] foldersToUpload) { var parent = new ParentReference {Id = "root"}; foreach (var f in foldersToUpload) { var folderQueryResult = SearchForFolder(f, parent.Id); if (folderQueryResult.Exists) { var parentFolder = new ParentReference {Id = ReturnMatchingFolder(folderQueryResult.Index, parent.Id).Id}; parent = new ParentReference {Id = parentFolder.Id}; } else { var lastFolderUploaded = UploadFolderWithParent(parent, f); parent = new ParentReference {Id = lastFolderUploaded}; } } UploadFileWithParent(parent, file, fileTitle); }
protected FileInfo CopyFile(string parentId, FileInfo fileInfo) { try { FileInfoStatus currentStatus = API.DriveService.GetFileInfoStatus(fileInfo); File file = fileInfo._file; if (file.Parents.Count > 0) { file.Parents.RemoveAt(0); } var parentReference = new ParentReference {Id = parentId}; if (file.Parents == null) { file.Parents = new List<ParentReference>(); } file.Parents.Insert(0, parentReference); using (API.DriveService.Connection connection = API.DriveService.Connection.Create()) { FilesResource.CopyRequest request = connection.Service.Files.Copy(file, file.Id); request.Fields = API.DriveService.RequestFields.FileFields; _CancellationTokenSource = new System.Threading.CancellationTokenSource(); file = request.Execute(); fileInfo = GetFileInfo(file); FileInfoStatus newStatus = API.DriveService.GetFileInfoStatus(fileInfo); if (currentStatus == FileInfoStatus.OnDisk) { DateTime modifiedDate = API.DriveService.GetDateTime(file.ModifiedDate); try { API.DriveService.SetFileLastWriteTime(fileInfo.FilePath, modifiedDate); } catch { } fileInfo = GetFileInfo(file); newStatus = API.DriveService.GetFileInfoStatus(fileInfo); } return fileInfo; } } catch (Exception exception) { Log.Error(exception); return null; } }
public GoogleDriveAPIController() { this.cloudFolder = new ParentReference() { Kind = "drive#file", Id = FolderId }; this.service = Initialize(); }
public async Task<bool> UploadFileStreamAsync(string folderId, string fileName, Stream inputStream) { try { Google.Apis.Drive.v2.Data.File file = new Google.Apis.Drive.v2.Data.File(); file.Title = fileName; ParentReference p = new ParentReference(); p.Id = folderId; file.Parents = new List<ParentReference>(); file.Parents.Add(p); string extension = fileName.Split('.').Last(); var insert = this.Service.Files.Insert(file, inputStream, GoogleDriveManager.MimeTypeMapper[extension]); var task = await insert.UploadAsync(); } catch { return false; } return true; }
public void InsertEntryIntoFolder(string entryId, string folderId) { var newParent = new ParentReference { Id = folderId }; _driveService.Parents.Insert(newParent, entryId).Execute(); }
protected override void Start() { try { if (Status != StatusType.Queued) { throw new Exception("Stream has not been queued."); } base.Start(); List<File> children = null; File parent = API.DriveService._GetCachedFile(_parentId, true, false, ref children); string fileName = System.IO.Path.GetFileNameWithoutExtension(_originalTitle); string fileExtenstion = System.IO.Path.GetExtension(_originalTitle); string title = fileName; if (!String.IsNullOrEmpty(fileExtenstion)) { title += fileExtenstion; } int index = 0; while (true) { bool found = false; foreach (File child in children) { if (child.Title == title) { FileInfoType fileInfoType = API.DriveService.GetFileInfoType(child); if (IsFolder && fileInfoType == FileInfoType.Folder) { found = true; } else if (!IsFolder && fileInfoType != FileInfoType.Folder) { found = true; } } } if (!found) { break; } index++; title = fileName + " (" + index + ")"; if (!String.IsNullOrEmpty(fileExtenstion)) { title += fileExtenstion; } } _title = title; var file = new File(); var parentReference = new ParentReference {Id = _parentId}; file.Parents = new List<ParentReference> {parentReference}; file.Title = _title; file.Description = "Created by Google Drive Proxy."; file.FileExtension = System.IO.Path.GetExtension(_title); file.MimeType = _mimeType; file.ModifiedDate = _lastWriteTime.ToUniversalTime(); _FileInfo = API.DriveService.GetFileInfo(file); if (_FileInfo.IsFolder) { Lock(); using (API.DriveService.Connection connection = API.DriveService.Connection.Create()) { FilesResource.InsertRequest request = connection.Service.Files.Insert(file); request.Fields = API.DriveService.RequestFields.FileFields; file = request.Execute(); _FileId = file.Id; _FileInfo = API.DriveService.GetFileInfo(file); DriveService_ProgressChanged(UploadStatus.Completed, 0, null); } } else { Lock(_filePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); using (API.DriveService.Connection connection = API.DriveService.Connection.Create()) { FilesResource.InsertMediaUpload request = connection.Service.Files.Insert(file, _FileStream, _mimeType); request.Fields = API.DriveService.RequestFields.FileFields; request.ProgressChanged += DriveService_ProgressChanged; request.ResponseReceived += DriveService_ResponseReceived; request.ChunkSize = FilesResource.InsertMediaUpload.DefaultChunkSize; request.Pinned = _parameters.Pinned; request.UseContentAsIndexableText = _parameters.UseContentAsIndexableText; _CancellationTokenSource = new System.Threading.CancellationTokenSource(); System.Threading.Tasks.Task<IUploadProgress> task = request.UploadAsync(_CancellationTokenSource.Token); } } } catch (Exception exception) { try { _Status = StatusType.Failed; _ExceptionMessage = exception.Message; DriveService_ProgressChanged(UploadStatus.Failed, 0, exception); } catch { Debugger.Break(); } Log.Error(exception); } }
public async Task Dispatch(Path destination, bool copySubDirs, Dictionary <FileDescription, byte[]> fileDescToBytesMapping, List <DirectoryDescription> subDirectories) { if (driveService == null) { throw new Exception("Google drive provider is not authenticated"); } DriveOptions drop = new DriveOptions(); try { FilesResource.ListRequest list = driveService.Files.List(); FileList filesFeed = null; Google.Apis.Drive.v2.Data.File gDir = null; if (destination.AbsolutePath != "") // Destination is not root { // Get directory list.MaxResults = 1000; drop.Parent = string.IsNullOrEmpty(destination.Parent) ? "root" : destination.Parent; list.Q = GetDriveQuery(drop); filesFeed = await list.ExecuteAsync(); // Try and locate the folder in google drive if it already exists while (filesFeed.Items != null) { gDir = filesFeed.Items.SingleOrDefault(x => x.MimeType == "application/vnd.google-apps.folder" && x.Title == destination.AbsolutePath.Split('\\').Last()); if (filesFeed.NextPageToken == null) { break; // Break if there are no more pages and the directory has not been found } list.PageToken = filesFeed.NextPageToken; filesFeed = await list.ExecuteAsync(); } // If the destination directory doesn't exist, create it. if (gDir == null) { // Create directory Google.Apis.Drive.v2.Data.File file = new Google.Apis.Drive.v2.Data.File(); file.Title = destination.AbsolutePath.Split('\\').Last(); file.MimeType = "application/vnd.google-apps.folder"; file.Parents = new List <ParentReference>(); ParentReference pr = new ParentReference() { Id = drop.Parent, IsRoot = drop.Parent == "root" }; file.Parents.Add(pr); gDir = await driveService.Files.Insert(file).ExecuteAsync(); } drop.Parent = gDir.Id; } else // Destination is root { drop.Parent = "root"; } // Remove all files/folders(and their contents) that don't exist in the source RemoveExtras(drop, fileDescToBytesMapping.Keys.ToList(), subDirectories); // Update/upload files foreach (var item in fileDescToBytesMapping) { MemoryStream stream = new MemoryStream(item.Value); list.Q = GetDriveQuery(new DriveOptions { Title = item.Key.Name, MimeType = item.Key.MimeType, Parent = gDir.Id }); var gFile = list.Execute().Items.Count > 0 ? list.Execute().Items[0] : null; if (gFile == null) { if (item.Key.MimeType != "application/vnd.google-apps.folder") { // Create files Google.Apis.Drive.v2.Data.File f = new Google.Apis.Drive.v2.Data.File(); f.MimeType = item.Key.MimeType; f.Title = item.Key.Name; f.Parents = new List <ParentReference>(); ParentReference pr = new ParentReference() { Id = gDir.Id }; if (drop.Parent == "root") { pr.IsRoot = true; } else { pr.IsRoot = false; } f.Parents.Add(pr); var status = await driveService.Files.Insert(f, stream, f.MimeType).UploadAsync(); } } else { // Update files if (item.Key.LastWriteTime > gFile.ModifiedDate) { var status = await driveService.Files.Update(gFile, gFile.Id, stream, gFile.MimeType).UploadAsync(); } } } if (copySubDirs) { foreach (var item in subDirectories) { item.DestinationParentId = gDir.Id; } } } catch (Exception e) { throw e; } }
public void CanCreateNodesWithContent() { AuthenticationUtils.startSession("admin", "admin"); Store spacesStore = new Store(StoreEnum.workspace, "SpacesStore"); String name = "AWS Book - Chapter 2 - " + DateTime.Now.Ticks; String description = "This is a content created with a sample of the book"; String mimeType = "text/plain"; String encoding = "UTF-8"; //custom value object CreateSampleVO createSampleVo = Builder.BuildCreateSampleVO(name, name, description); try { ParentReference parent = new ParentReference( spacesStore, null, "/app:company_home", Constants.ASSOC_CONTAINS, "{" + Constants.NAMESPACE_CONTENT_MODEL + "}" + name ); //build properties NamedValue[] properties = Builder.BuildCustomProperties(createSampleVo); //create operation CMLCreate create = new CMLCreate(); create.id = "1"; create.parent = parent; create.type = Constants.TYPE_CONTENT; create.property = properties; //create the node reference Reference reference = new Reference(); reference.store = spacesStore; reference.path = "/app:company_home/cm:" + ISO9075.Encode(name); //create the predicate Predicate predicate = new Predicate(); predicate.Items = new Reference[] { reference }; //build the CML object CML cml = new CML(); cml.create = new CMLCreate[] { create }; //perform a CML update for the node UpdateResult[] result = WebServiceFactory.getRepositoryService().update(cml); //get the new node reference Alfresco.ContentWebService.Reference referenceForContent = Alfresco.ContentWebService.Reference.From(result[0].destination); //create content with ContentService Alfresco.ContentWebService.ContentFormat format = new Alfresco.ContentWebService.ContentFormat(mimeType, encoding); Alfresco.ContentWebService.Content content = WebServiceFactory.getContentService().write( referenceForContent, Constants.PROP_CONTENT, new ASCIIEncoding().GetBytes("This is the content for the new node"), format ); String expectedPath = "/app:company_home/cm:AWS_x0020_Book_x0020_-_x0020_Chapter_x0020_2_x0020_-_x0020_"; Assert.IsTrue(content.node.path.StartsWith(expectedPath)); } finally { AuthenticationUtils.endSession(); } }
protected override void Start() { try { if (Status != StatusType.Queued) { throw new Exception("Stream has not been queued."); } base.Start(); _FileInfo = _DriveService.GetFile(FileId); if (_FileInfo == null) { throw new Exception("File '" + FileId + "' no longer exists."); } Lock(); if (_FileInfo.ParentId == ParentId) { DriveService_ProgressChanged(StatusType.Completed, null); } else { FileInfoStatus currentStatus = API.DriveService.GetFileInfoStatus(_FileInfo); Google.Apis.Drive.v2.Data.File file = _FileInfo._file; using (API.DriveService.Connection connection = API.DriveService.Connection.Create()) { file = connection.Service.Files.Get(file.Id).Execute(); if (file.Parents.Count > 0) { file.Parents.RemoveAt(0); } var parentReference = new ParentReference {Id = _ParentId}; file.Parents.Insert(0, parentReference); FilesResource.UpdateRequest request = connection.Service.Files.Update(file, FileId); file = request.Execute(); _FileInfo = GetFileInfo(file); FileInfoStatus newStatus = API.DriveService.GetFileInfoStatus(_FileInfo); if (currentStatus == FileInfoStatus.OnDisk) { DateTime modifiedDate = API.DriveService.GetDateTime(file.ModifiedDate); try { API.DriveService.SetFileLastWriteTime(_FileInfo.FilePath, modifiedDate); } catch { } _FileInfo = GetFileInfo(file); newStatus = API.DriveService.GetFileInfoStatus(_FileInfo); } DriveService_ProgressChanged(StatusType.Completed, null); } } } catch (Exception exception) { try { _Status = StatusType.Failed; _ExceptionMessage = exception.Message; DriveService_ProgressChanged(StatusType.Failed, exception); } catch { Debugger.Break(); } Log.Error(exception); } }
protected FileInfo CopyFile(string parentId, FileInfo fileInfo) { try { FileInfoStatus currentStatus = API.DriveService.GetFileInfoStatus(fileInfo); File file = fileInfo._file; if (file.Parents.Count > 0) { file.Parents.RemoveAt(0); } var parentReference = new ParentReference { Id = parentId }; if (file.Parents == null) { file.Parents = new List <ParentReference>(); } file.Parents.Insert(0, parentReference); using (API.DriveService.Connection connection = API.DriveService.Connection.Create()) { FilesResource.CopyRequest request = connection.Service.Files.Copy(file, file.Id); request.Fields = API.DriveService.RequestFields.FileFields; _CancellationTokenSource = new System.Threading.CancellationTokenSource(); file = request.Execute(); fileInfo = GetFileInfo(file); FileInfoStatus newStatus = API.DriveService.GetFileInfoStatus(fileInfo); if (currentStatus == FileInfoStatus.OnDisk) { DateTime modifiedDate = API.DriveService.GetDateTime(file.ModifiedDate); try { API.DriveService.SetFileLastWriteTime(fileInfo.FilePath, modifiedDate); } catch { } fileInfo = GetFileInfo(file); newStatus = API.DriveService.GetFileInfoStatus(fileInfo); } return(fileInfo); } } catch (Exception exception) { Log.Error(exception); return(null); } }
public void Commit() { if (IsNew) { if (ParentReference.AddNewChild == null) { throw new InvalidOperationException(String.Format("Для {0} не настроена функция AddNewChild. Без нее, подчиненный Uow, не может работать.", ParentReference.GetType())); } ParentReference.AddNewChild(ParentUoW.Root, Root); IsNew = false; } foreach (var obj in ObjectToDelete) { Session.Delete(obj); } foreach (var obj in ObjectToSave) { Session.SaveOrUpdate(obj); } }
public void CanModeNodes() { AuthenticationUtils.startSession("admin", "admin"); Store spacesStore = new Store(StoreEnum.workspace, "SpacesStore"); String name = "AWS Book - Content Moved " + DateTime.Now.Ticks; String spaceNameForMove = "AWS Book - Move Space Sample " + DateTime.Now.Ticks; String description = "This is a content created with a sample of the book"; //custom value object CreateSampleVO createSampleVo = Builder.BuildCreateSampleVO(name, name, description); CreateSampleVO createFolderSampleVo = Builder.BuildCreateSampleVO(spaceNameForMove, spaceNameForMove, description); try { //parent for the new node ParentReference parentForNode = new ParentReference( spacesStore, null, "/app:company_home", Constants.ASSOC_CONTAINS, "{" + Constants.NAMESPACE_CONTENT_MODEL + "}" + name ); //parent for the new space ParentReference parentForSpace = new ParentReference( spacesStore, null, "/app:company_home", Constants.ASSOC_CONTAINS, "{" + Constants.NAMESPACE_CONTENT_MODEL + "}" + spaceNameForMove ); //build properties NamedValue[] properties = Builder.BuildCustomProperties(createSampleVo); NamedValue[] propertiesForSpace = Builder.BuildCustomPropertiesForSpace(createFolderSampleVo); //create a node CMLCreate create = new CMLCreate(); create.id = "1"; create.parent = parentForNode; create.type = Constants.TYPE_CONTENT; create.property = properties; //create a space CMLCreate createSpace = new CMLCreate(); createSpace.id = "2"; createSpace.parent = parentForSpace; createSpace.type = Constants.TYPE_FOLDER; createSpace.property = propertiesForSpace; //build the CML object CML cmlAdd = new CML(); cmlAdd.create = new CMLCreate[] { create, createSpace }; //perform a CML update to create nodes UpdateResult[] result = WebServiceFactory.getRepositoryService().update(cmlAdd); String expectedPath = "/app:company_home/cm:AWS_x0020_Book_x0020_-_x0020_Content_x0020_Moved_x0020_"; Assert.IsTrue(result[0].destination.path.StartsWith(expectedPath)); expectedPath = "/app:company_home/cm:AWS_x0020_Book_x0020_-_x0020_Move_x0020_Space_x0020_Sample_x0020_"; Assert.IsTrue(result[1].destination.path.StartsWith(expectedPath)); //create a predicate with the first CMLCreate result Reference referenceForNode = result[0].destination; Predicate sourcePredicate = new Predicate(new Reference[] { referenceForNode }, spacesStore, null); //create a reference from the second CMLCreate performed for space Reference referenceForTargetSpace = result[1].destination; //reference for the target space ParentReference targetSpace = new ParentReference(); targetSpace.store = spacesStore; targetSpace.path = referenceForTargetSpace.path; targetSpace.associationType = Constants.ASSOC_CONTAINS; targetSpace.childName = name; //move content CMLMove move = new CMLMove(); move.where = sourcePredicate; move.to = targetSpace; CML cmlMove = new CML(); cmlMove.move = new CMLMove[] { move }; //perform a CML update to move the node WebServiceFactory.getRepositoryService().update(cmlMove); expectedPath = "/app:company_home/cm:AWS_x0020_Book_x0020_-_x0020_Content_x0020_Moved_x0020_"; Assert.IsTrue(referenceForNode.path.StartsWith(expectedPath)); expectedPath = "/app:company_home/cm:AWS_x0020_Book_x0020_-_x0020_Move_x0020_Space_x0020_Sample_x0020_"; Assert.IsTrue(targetSpace.path.StartsWith(expectedPath)); } finally { AuthenticationUtils.endSession(); } }
protected override void Start() { try { if (Status != StatusType.Queued) { throw new Exception("Stream has not been queued."); } base.Start(); List <File> children = null; File parent = API.DriveService._GetCachedFile(_parentId, true, false, ref children); string fileName = System.IO.Path.GetFileNameWithoutExtension(_originalTitle); string fileExtenstion = System.IO.Path.GetExtension(_originalTitle); string title = fileName; if (!String.IsNullOrEmpty(fileExtenstion)) { title += fileExtenstion; } int index = 0; while (true) { bool found = false; foreach (File child in children) { if (child.Title == title) { FileInfoType fileInfoType = API.DriveService.GetFileInfoType(child); if (IsFolder && fileInfoType == FileInfoType.Folder) { found = true; } else if (!IsFolder && fileInfoType != FileInfoType.Folder) { found = true; } } } if (!found) { break; } index++; title = fileName + " (" + index + ")"; if (!String.IsNullOrEmpty(fileExtenstion)) { title += fileExtenstion; } } _title = title; var file = new File(); var parentReference = new ParentReference { Id = _parentId }; file.Parents = new List <ParentReference> { parentReference }; file.Title = _title; file.Description = "Created by Drive Fusion Shell Extention"; file.FileExtension = System.IO.Path.GetExtension(_title); file.MimeType = _mimeType; file.ModifiedDate = _lastWriteTime.ToUniversalTime(); _FileInfo = API.DriveService.GetFileInfo(file); if (_FileInfo.IsFolder) { Lock(); using (API.DriveService.Connection connection = API.DriveService.Connection.Create()) { FilesResource.InsertRequest request = connection.Service.Files.Insert(file); request.Fields = API.DriveService.RequestFields.FileFields; file = request.Execute(); _FileId = file.Id; _FileInfo = API.DriveService.GetFileInfo(file); DriveService_ProgressChanged(UploadStatus.Completed, 0, null); } } else { Lock(_filePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); using (API.DriveService.Connection connection = API.DriveService.Connection.Create()) { FilesResource.InsertMediaUpload request = connection.Service.Files.Insert(file, _FileStream, _mimeType); request.Fields = API.DriveService.RequestFields.FileFields; request.ProgressChanged += DriveService_ProgressChanged; request.ResponseReceived += DriveService_ResponseReceived; request.ChunkSize = FilesResource.InsertMediaUpload.DefaultChunkSize; request.Pinned = _parameters.Pinned; request.UseContentAsIndexableText = _parameters.UseContentAsIndexableText; _CancellationTokenSource = new System.Threading.CancellationTokenSource(); System.Threading.Tasks.Task <IUploadProgress> task = request.UploadAsync(_CancellationTokenSource.Token); } } } catch (Exception exception) { try { _Status = StatusType.Failed; _ExceptionMessage = exception.Message; DriveService_ProgressChanged(UploadStatus.Failed, 0, exception); } catch { Debugger.Break(); } Log.Error(exception); } }
public ParentReference insertFileIntoFolder(String folderId, String fileId) { ParentReference newParent = new ParentReference(); newParent.Id = folderId; // try // { return Service.Parents.Insert(newParent, fileId).Execute(); // } // catch (Exception e) // { // Console.WriteLine("An error occurred: " + e.Message); // } // return null; }
/// <summary>For derived references, this is the base reference from which this reference was derived. Otherwise, this is the reference name.</summary> public override string OriginatingReferenceName() { return(ParentReference.OriginatingReferenceName()); }