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;
}
Related
I'm working on an ASP.NET Core 5 project. I have this action method:
public async Task<IActionResult> CreateV3EnterCheckFile(IFormFile MarksFile)
{
var filesCount = Directory.GetFiles("Uploads").Length;
string path = Path.Combine("Uploads", filesCount + 1 + ".xlsx");
await MarksFile.SaveToAsync(path);
var xlImporter = new XLImporter();
var importedData = await xlImporter.ImportSheetAsync(path, 0);
var r = (from x in importedData select new { ID = x[0], StudentId = x[1] }).ToList();
System.IO.File.Delete(path);
return View();
}
I tried to get IFormFile uploaded file by the user to save it on the server and querying it using one of my projects (that uses LinqToExcel library).
I am querying the data and everything is perfect I still have just one problem it is this line of code:
System.IO.File.Delete(path);
It throws an exception and the message is I can't delete that file because it is still being used by another process.
I'm very sure that the process is related to the LinqToExcel library.
More details :
SaveToAsync is an extension method created by me that is its definition
public static Task SaveToAsync(this IFormFile file, string pathToSaveTo)
{
return Task.Factory.StartNew(() =>
{
using (Stream fileStream = File.Open(pathToSaveTo, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
file.CopyTo(fileStream);
}
});
}
Please - is there any way or method or solution to delete this file even if it is being used by another process?
Massive thanks in advance.
Based on the source code of ExcelQueryFactory (https://github.com/paulyoder/LinqToExcel/blob/master/src/LinqToExcel/ExcelQueryFactory.cs) I would try the following:
ExcelQueryFactory has a ReadOnly Property. For read only access (if applicable) I would set it to true when creating the instance.
More important: IExcelQueryFactory implements IDisposable, so you can (should) use a using block:
using (var excelFile = new ExcelQueryFactory(pathToExcelFile) {ReadOnly = true})
{
// Do your work.
}
Of course you can use using var ..., but if you need a more reduced scope, the "old" using syntax allows more control.
I assumed that your Uploads folder is under webroot.
You can try this:-
public YourControllerName(IHostingEnvironment he) //input parameter
{
_he = he;
}
public async Task<IActionResult> CreateV3EnterCheckFile(IFormFile MarksFile)
{
try
{
var filesCount = Directory.GetFiles("Uploads").Length;
string contentRootPath = _he.ContentRootPath;
string path = Path.Combine(contentRootPath +"\\Uploads", filesCount + 1 + ".xlsx");
await MarksFile.SaveToAsync(path);
var xlImporter = new XLImporter();
var importedData = await xlImporter.ImportSheetAsync(path, 0);
var r = (from x in importedData select new { ID = x[0], StudentId = x[1] }).ToList();
//System.IO.File.Delete(path);
if (File.Exists(path))
{
File.Delete(path);
}
else
{
Debug.WriteLine("File does not exist.");
}
return View();
}
catch(Exception e)
{
Console.WriteLine(e);
}
Or you can try another process:-
try
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.IO.File.Delete(path);
}
catch(Exception e){
}
}
Or this:-
if (System.IO.File.Exists(path))
{
try
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.IO.File.Delete(path);
}
catch (Exception e) { }
}
it should resolve your issue I hope. by the way, if your Upload folder is not under the webroot path. you can find your path using your process.
I'm reading data from remote MongoDB realm which syncs to my local realm, but it seems I can't read from my local realm after sync.
This is the message I get when I try to read from my local realm:
Unable to open a realm at path '/data/user/0/com.companyname.appname/files/default.realm': Incompatible histories. Expected a Realm with no or in-realm history, but found history type 3 Path:Exception backtrace:\n<backtrace not supported on this platform>.
Here is my code:
private async Task<Realm> OpenRealm()
{
try
{
var user = App.realmApp.CurrentUser;
//if user is not logged on yet log on the user and sync
if (user == null)
{
var CurrentUser = await App.realmApp.LogInAsync(Credentials.Anonymous());
var config = new SyncConfiguration("Hirschs", CurrentUser);
_realm = await Realm.GetInstanceAsync(config);
return _realm;
}
else
{
return _realm = Realm.GetInstance();
}
}
catch (Exception ex)
{
await UserDialogs.Instance.AlertAsync(new AlertConfig
{
Title = "An error has occurred",
Message = $"An error occurred while trying to open the Realm: {ex.Message}"
});
// Try again
return await OpenRealm();
}
}
The problem here is that you are trying to create a new local realm in the same path where the synced realm already is.
I suppose that you would like to open the same realm synchronously (that is necessary if the device is offline). In this case you would just need to use the same configuration for both the sync and async calls, as reported in the documentation here.
You could do something like:
private async Task<Realm> OpenRealm()
{
try
{
var currentUser = App.realmApp.CurrentUser;
if (currentUser == null)
{
var currentUser = await App.realmApp.LogInAsync(Credentials.Anonymous());
var config = new SyncConfiguration("Hirschs", currentUser);
_realm = await Realm.GetInstanceAsync(config);
return _realm;
}
else
{
var config = new SyncConfiguration("Hirschs", currentUser);
_realm = Realm.GetInstance(config);
return _realm;
}
}
catch (Exception ex)
{
await UserDialogs.Instance.AlertAsync(new AlertConfig
{
Title = "An error has occurred",
Message = $"An error occurred while trying to open the Realm: {ex.Message}"
});
}
}
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;
}
I have some data to save into a database.
I have created a web api post method to save data. Following is my post method:
[Route("PostRequirementTypeProcessing")]
public IEnumerable<NPAAddRequirementTypeProcessing> PostRequirementTypeProcessing(mdlAddAddRequirementTypeProcessing requTypeProcess)
{
mdlAddAddRequirementTypeProcessing rTyeProcessing = new mdlAddAddRequirementTypeProcessing();
rTyeProcessing.szDescription = requTypeProcess.szDescription;
rTyeProcessing.iRequirementTypeId = requTypeProcess.iRequirementTypeId;
rTyeProcessing.szRequirementNumber = requTypeProcess.szRequirementNumber;
rTyeProcessing.szRequirementIssuer = requTypeProcess.szRequirementIssuer;
rTyeProcessing.szOrganization = requTypeProcess.szOrganization;
rTyeProcessing.dIssuedate = requTypeProcess.dIssuedate;
rTyeProcessing.dExpirydate = requTypeProcess.dExpirydate;
rTyeProcessing.szSignedBy = requTypeProcess.szSignedBy;
rTyeProcessing.szAttachedDocumentNo = requTypeProcess.szAttachedDocumentNo;
if (String.IsNullOrEmpty(rTyeProcessing.szAttachedDocumentNo))
{
}
else
{
UploadFile();
}
rTyeProcessing.szSubject = requTypeProcess.szSubject;
rTyeProcessing.iApplicationDetailsId = requTypeProcess.iApplicationDetailsId;
rTyeProcessing.iEmpId = requTypeProcess.iEmpId;
NPAEntities context = new NPAEntities();
Log.Debug("PostRequirementTypeProcessing Request traced");
var newRTP = context.NPAAddRequirementTypeProcessing(requTypeProcess.szDescription, requTypeProcess.iRequirementTypeId,
requTypeProcess.szRequirementNumber, requTypeProcess.szRequirementIssuer, requTypeProcess.szOrganization,
requTypeProcess.dIssuedate, requTypeProcess.dExpirydate, requTypeProcess.szSignedBy,
requTypeProcess.szAttachedDocumentNo, requTypeProcess.szSubject, requTypeProcess.iApplicationDetailsId,
requTypeProcess.iEmpId);
return newRTP.ToList();
}
There is a field called 'szAttachedDocumentNo' which is a document that's being saved in the database as well.
After saving all data, I want the physical file of the 'szAttachedDocumentNo' to be saved on the server. So i created a method called "UploadFile" as follows:
[HttpPost]
public void UploadFile()
{
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
// Get the uploaded file from the Files collection
var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
string folderPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");
//string folderPath1 = Convert.ToString(ConfigurationManager.AppSettings["DocPath"]);
//Directory not exists then create new directory
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
// Get the complete file path
var fileSavePath = Path.Combine(folderPath, httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
}
Before running the project, i debbugged the post method, so when it comes to "UploadFile" line, it takes me to its method.
From the file line, it skipped the remaining lines and went to the last line; what means it didn't see any file.
I am able to save everything to the database, just that i didn't see the physical file in the specified location.
Any help would be much appreciated.
Regards,
Somad
Makes sure the request "content-type": "multipart/form-data" is set
[HttpPost()]
public async Task<IHttpActionResult> UploadFile()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
try
{
MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
if (provider.Contents != null && provider.Contents.Count == 0)
{
return BadRequest("No files provided.");
}
foreach (HttpContent file in provider.Contents)
{
string filename = file.Headers.ContentDisposition.FileName.Trim('\"');
byte[] buffer = await file.ReadAsByteArrayAsync();
using (MemoryStream stream = new MemoryStream(buffer))
{
// save the file whereever you want
}
}
return Ok("files Uploded");
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
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");