I'm familiar with creating folder in my Google Drive, but I'm looking into doing this using the asynchronous method. However, in doing so, I'm not sure how to obtain a field that I explicitly added to the fields I'd like returned.
My code below:
private Task<Google.Apis.Drive.v3.Data.File> CreateGoogleDriveFolderAsync(DriveService service, string foldername, string parent_id = null)
{
IList<string> parent_ids = new List<string>();
Google.Apis.Drive.v3.Data.File folder = new Google.Apis.Drive.v3.Data.File
{
Name = foldername
, MimeType = "application/vnd.google-apps.folder"
, Description = "Client Name: blah\nUser: Rudy\n"
};
var insert = service.Files.Create(folder);
// The field I'd like to get somewhere.
insert.Fields = "id";
var task = insert.ExecuteAsync();
task.ContinueWith(t =>
{
// NotOnRanToCompletion - this code will be called if the upload fails
Console.WriteLine("Failed to create folder \"{0}\": " + t.Exception, foldername);
}, TaskContinuationOptions.NotOnRanToCompletion);
task.ContinueWith(t =>
{
// I'd like a way to access "id" from my insert execution.
log.insertLogging(foldername, "Directory Created");
});
return task;
}
Using an example from the documentation, await the task and get the file back from there you should have access to its properties
private async Task<File> CreateGoogleDriveFolderAsync(DriveService driveService, string foldername) {
var metadata = new File()
{
Name = foldername,
MimeType = "application/vnd.google-apps.folder"
};
var request = driveService.Files.Create(metadata);
request.Fields = "id";
var folder = await request.ExecuteAsync();
Console.WriteLine("Folder ID: " + folder.Id);
return folder;
}
Related
I am just trying to learn ASP.NET MVC and am having an issue, well not so much of an issue but lack of understanding any is not working I am trying to update an SQL table, the code below works fine if I want to delete a table but all I want to do is to add another file to the data table
public async Task<IActionResult> DeleteSnTFileFromFileSystem(int id)
{
var file = await context.SnTModels.Where(x => x.Id == id).FirstOrDefaultAsync();
if (file == null)
return null;
var basePath = Path.Combine(Directory.GetCurrentDirectory() + "\\wwwroot" + file.FilePath);
if (System.IO.File.Exists(basePath))
{
System.IO.File.Delete(basePath);
}
context.SnTModels.Remove(file);
context.SaveChanges();
TempData["Message"] = $"Removed {file.Name + file.Extension} successfully from File System.";
return RedirectToAction("Scenario");
}
Here is my code to create the table
[HttpPost]
public async Task<IActionResult> SnTUploadToFileSystem(List<IFormFile> files, string description)
{
foreach (var file in files)
{
var subPath = "\\*dir file\\";
var basePath = Path.Combine(Directory.GetCurrentDirectory() + "\\wwwroot" + subPath);
bool basePathExists = System.IO.Directory.Exists(basePath);
if (!basePathExists)
Directory.CreateDirectory(basePath);
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
var filePath = Path.Combine(basePath, file.FileName);
var extension = Path.GetExtension(file.FileName);
if (!System.IO.File.Exists(filePath))
{
// saving our file to the file system
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
// creating a model and save this model into the db
var SnTModel = new SnTOnFileSystem
{
CreatedOn = DateTime.UtcNow,
FileType = file.ContentType,
Extension = extension,
Name = fileName,
Description = description,
FilePath = subPath + file.FileName
};
context.SnTModels.Add(SnTModel);
context.SaveChanges();
}
}
TempData["Message"] = "File successfully uploaded to File System.";
return RedirectToAction("Index");
}
Here is the post to update the table
[HttpPost]
public async Task<IActionResult> SnTUpdateToFileSystem(List<IFormFile> files, int id)
{
var file = files[0];
var subPath = "\\Training\\SnT\\Document\\";
var basePath = Path.Combine(Directory.GetCurrentDirectory() + "\\wwwroot" + subPath);
bool basePathExists = System.IO.Directory.Exists(basePath);
if (!basePathExists)
Directory.CreateDirectory(basePath);
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
var documentFilePath = Path.Combine(basePath, file.FileName);
var extension = Path.GetExtension(file.FileName);
if (!System.IO.File.Exists(documentFilePath))
{
// saving our file to the file system
using (var stream = new FileStream(documentFilePath, FileMode.OpenOrCreate))
{
await file.CopyToAsync(stream);
}
// creating a model and save this model into the db
var SnTModel = new SnTOnFileSystem
{
Name = fileName,
DocumentFilePath = subPath + file.FileName
};
context.SnTModels.Update(SnTModel);
context.SaveChanges();
}
TempData["Message"] = "Document successfully uploaded to File System.";
return RedirectToAction("Scenario");
}
Using C# and amazon .Net core, able to list all the files with in a amazon S3 folder as below:
public async Task<string> GetMenuUrl(entities.Restaurant restaurant)
{
AmazonS3Client s3Client = new AmazonS3Client(_appSettings.AWSPublicKey, _appSettings.AWSPrivateKey, Amazon.RegionEndpoint.APSoutheast2);
string imagePath;
string restaurantName = trimSpecialCharacters(restaurant.Name);
int restaurantId = restaurant.RestaurantId;
ListObjectsRequest listRequest = new ListObjectsRequest();
ListObjectsResponse listResponse;
imagePath = $"Business_menu/{restaurantId}/";
listRequest.BucketName = _appSettings.AWSS3BucketName;
listRequest.Prefix = imagePath;
do
{
listResponse = await s3Client.ListObjectsAsync(listRequest);
} while (listResponse.IsTruncated);
var files = listResponse.S3Objects.Select(x => x.Key);
var arquivos = files.Select(x => Path.GetFileName(x)).ToList();
return arquivos.ToString();
}
Currently arquivos returns a list containing both the images (image1.jpg, image2.jpg) which is as expected and then I return it as a string.
But when I go to call this method from another function.
public async Task<VenueMenuResponse> GetVenueMenuUrl(int restaurantId)
{
var restaurant = await _context.Restaurant.Where(w => w.RestaurantId == restaurantId).FirstOrDefaultAsync();
var result = await _storyService.GetMenuUrl(restaurant);
var response = new MenuResponse() //just contains string variable called MenuUrl
{
MenuUrl = result
};
return response;
}
It returns this:
{
"menuUrl": "System.Collections.Generic.List`1[System.String]"
}
When I want it to return
{
"menuUrl": "Image1.jpg"
},
{
"menuUrl": "Image2.jpg"
}
You need to iterate thought results and return list of results.
public async Task<IEnumerable<VenueMenuResponse>> GetVenueMenuUrl(int restaurantId)
{
var restaurant = await _context.Restaurant.Where(w => w.RestaurantId == restaurantId).FirstOrDefaultAsync();
var result = await _storyService.GetMenuUrl(restaurant);
var response = result.Select(e => new MenuResponse() //just contains string variable called MenuUrl
{
MenuUrl = e
};
return response;
}
var result = string.Join(", ", fileName);
The default ToString() implementation of List simply prints the name of the type.
This magical line managed to solve things for me. The list was originally outputting just the object instead of the actual content of the list.
Is there any possible way to get the list of files with parent folder name and without making additional queries?
My Files.List() code sample:
var sheets = new List<File>();
var sheetsRequest = Service.Files.List();
sheetsRequest.Fields = "nextPageToken, files(id, name, owners, parents)";
sheetsRequest.Q = $"mimeType = '{mimeType}' and name = '{name}'";
sheetsRequest.PageSize = 500;
var sheetsFeed = await sheetsRequest.ExecuteAsync();
while (sheetsFeed.Files != null)
{
foreach (var file in sheetsFeed.Files)
{
sheets.Add(file);
}
if (sheetsFeed.NextPageToken == null)
break;
sheetsRequest.PageToken = sheetsFeed.NextPageToken;
sheetsFeed = await sheetsRequest.ExecuteAsync();
}
return sheets;
Because for now I making GetFileParentDirAsync call for each File using following method (and it's very slow):
public async Task<string> GetFileParentDirAsync(File file)
{
return await Task.Run(async () =>
{
var folderName = string.Empty;
if (file.Parents?.First() == null) return folderName;
var parentId = file.Parents.First();
var parentRequest = Service.Files.Get(parentId);
var parentResponse = await parentRequest.ExecuteAsync();
folderName = parentResponse.Name;
return folderName;
});
}
Thanks.
I'm trying to create a folder withing my Apps/[appName] folder.
Here is the code:
var request = OneDriveService.Drive.Special.AppRoot.Request().CreateAsync(new Item()
{
Name = name,
});
request.Wait();
But I keep getting the error message:
{Code: invalidRequest Throw site: 1c0e.2859 Message: The name in the
provided oneDrive.item does not match the name in the URL }
Does anyone know what it means?
Instead of CreateAsync I write this code:
try
{
var documentsBuilder = this.oneDriveClient.Drive.Root.ItemWithPath("Documents");
var children = await documentsBuilder.Children.Request().GetAsync();
// try to find existing folder
var folder = children.FirstOrDefault(c => c.Name.Equals("Some folder"));
// create it if it doesn't exist
if (folder == null)
{
var newFolder = new Item { Name = "Some folder", Folder = new Folder() };
await documentsBuilder.Children.Request().AddAsync(newFolder);
}
}
catch (OneDriveException exception)
{
throw;
}
I'm trying to use the Live SDK (v5.6) to include backup/restore from OneDrive in my Windows Phone 8.1 Silverlight application. I can read/write to the standard "me/skydrive" directory, but I am having a horrible time in finding a way to upload/download to a specified directory. I can create the folder if it doesn't exist no problem.
I have been trying below with no luck.
var res = await _client.UploadAsync("me/skydrive/mydir", fileName, isoStoreFileStream, OverwriteOption.Overwrite);
I've also tried getting the directory ID and passing that in also.
var res = await _client.UploadAsync("me/skydrive/" + folderId, fileName, isoStoreFileStream, OverwriteOption.Overwrite);
Same error.. I receive 'mydir' or the id isn't supported...
"{request_url_invalid: Microsoft.Live.LiveConnectException: The URL contains the path 'mydir', which isn't supported."
Any suggestions? If you suggest an answer for the uploadasync, could you also include how I could download my file from the specified directory? Thanks!
Here's an extension method that checks if a folder is created and:
If created returns the folder id.
If not created, creates it and returns the folder id.
You can then use this id to upload to and download from that folder.
public async static Task<string> CreateDirectoryAsync(this LiveConnectClient client,
string folderName, string parentFolder)
{
string folderId = null;
// Retrieves all the directories.
var queryFolder = parentFolder + "/files?filter=folders,albums";
var opResult = await client.GetAsync(queryFolder);
dynamic result = opResult.Result;
foreach (dynamic folder in result.data)
{
// Checks if current folder has the passed name.
if (folder.name.ToLowerInvariant() == folderName.ToLowerInvariant())
{
folderId = folder.id;
break;
}
}
if (folderId == null)
{
// Directory hasn't been found, so creates it using the PostAsync method.
var folderData = new Dictionary<string, object>();
folderData.Add("name", folderName);
opResult = await client.PostAsync(parentFolder, folderData);
result = opResult.Result;
// Retrieves the id of the created folder.
folderId = result.id;
}
return folderId;
}
You then use this as:
string skyDriveFolder = await CreateDirectoryAsync(liveConnectClient, "<YourFolderNameHere>", "me/skydrive");
Now skyDriveFolder has the folder id that you can use when uploading and downloading. Here's a sample Upload:
LiveOperationResult result = await liveConnectClient.UploadAsync(skyDriveFolder, fileName,
fileStream, OverwriteOption.Overwrite);
ADDITION TO COMPLETE THE ANSWER BY YnotDraw
Using what you provided, here's how to download a text file by specifying the file name. Below does not include if the file is not found and other potential exceptions, but here is what works when the stars align properly:
public async static Task<string> DownloadFileAsync(this LiveConnectClient client, string directory, string fileName)
{
string skyDriveFolder = await OneDriveHelper.CreateOrGetDirectoryAsync(client, directory, "me/skydrive");
var result = await client.DownloadAsync(skyDriveFolder);
var operation = await client.GetAsync(skyDriveFolder + "/files");
var items = operation.Result["data"] as List<object>;
string id = string.Empty;
// Search for the file - add handling here if File Not Found
foreach (object item in items)
{
IDictionary<string, object> file = item as IDictionary<string, object>;
if (file["name"].ToString() == fileName)
{
id = file["id"].ToString();
break;
}
}
var downloadResult= await client.DownloadAsync(string.Format("{0}/content", id));
var reader = new StreamReader(downloadResult.Stream);
string text = await reader.ReadToEndAsync();
return text;
}
And in usage:
var result = await DownloadFile(_client, "MyDir", "backup.txt");