Uploading to Dropbox using Sharpbox API - c#

I am attempting to use the Sharpbox API to upload a file to my dropbox account. However, when I attempt to upload a file to the "Public" folder, I get an error stating: "Couldn't retrieve child elements from the server".
I have followed the steps on page 10-11 of the documentation pdf and here is the code I am currently using (as a test I am trying to upload the token.txt file):
Public Sub StoreOnDropbox()
Dim oDBox As New CloudStorage
Dim oDBoxConfig As AppLimit.CloudComputing.SharpBox.ICloudStorageConfiguration = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox)
Dim oAccessToken As ICloudStorageAccessToken = Nothing
Using fs As IO.FileStream = File.Open("C:\Users\davidd5\Desktop\token.txt", FileMode.Open, FileAccess.Read, FileShare.None)
oAccessToken = oDBox.DeserializeSecurityToken(fs)
End Using
Dim oStorageToken = oDBox.Open(oDBoxConfig, oAccessToken)
Dim srcFile = Environment.ExpandEnvironmentVariables("C:\Users\davidd5\Desktop\token.txt")
Dim publicFolder = oDBox.GetFolder("/Public")
oDBox.UploadFile(srcFile, publicFolder)
oDBox.Close()
End Sub
The error occurs on the GetFolder function. I have tagged both vb.net and C# as the documentation is in C# and I've translated it to vb.net.
After reading about then posting about the same error in the link provided by IanBailey, I changed:
var publicFolder = dropBoxStorage.GetFolder("/Public");
to
var publicFolder = dropBoxStorage.GetRoot();
The file then uploaded successfully.
EDIT: However, I just realised that you cannot share files within the apps folder (that GetRoot points to), so therefore the problem is still occurring for me.
EDIT 2: I think the problem is due to permissions when creating your app on dropbox. When you first create the app, there is the option to grant access to either the "Apps" folder, or the entire users' dropbox. I was getting the error then I created a new app that requested access to the entire users' dropbox and was then able to get at the public folder.

The problem is due to permissions when creating your app on dropbox. When you first create the app, there is the option to grant access to either the "Apps" folder, or the entire users' dropbox. I was getting the error until I created a new app that requested access to the entire users' dropbox and was then able to get at the public folder.

Related

How to upload to OneDrive using Microsoft Graph Api in c#

I have been trying to upload to a OneDrive account and I am hopelessly stuck not being able to upload neither less or greater than 4MB files. I have no issues accessing the drive at all, since I have working functions that create a folder, rename files/folders, and a delete files/folders.
https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=csharp
This documentation on Microsoft Graph API is very friendly to HTTP code, and I believe I am able to fairly "translate" the documentation to C#, but still fail to grab a file and upload to OneDrive. Some places online seem to be using byte arrays? Which I am completely unfamiliar with since my primary language is C++ and we just use ifstream/ofstream. Anyways, here is the portion of code in specific (I hope this is enough):
var item = await _client.Users[userID].Drive.Items[FolderID]//"01YZM7SMVOQ7YVNBXPZFFKNQAU5OB3XA3K"].Content
.ItemWithPath("LessThan4MB.txt")//"D:\\LessThan4MB.txt")
.CreateUploadSession()
.Request()
.PostAsync();
Console.WriteLine("done printing");
As it stands, it uploads a temporary file that has a tilde "~" in the OneDrive (like as if I was only able to open but not import any data from the file onto it). If I swap the name of the file so it includes the file location it throws an error:
Message: Found a function 'microsoft.graph.createUploadSession' on an open property. Functions on open properties are not supported.
Try this approach with memory stream and PutAsync<DriveItem> request:
string path = "D:\\LessThan4MB.txt";
byte[] data = System.IO.File.ReadAllBytes(path);
using (Stream stream = new MemoryStream(data))
{
var item = await _client.Me.Drive.Items[FolderID]
.ItemWithPath("LessThan4MB.txt")
.Content
.Request()
.PutAsync<DriveItem>(stream);
}
I am assuming you have already granted Microsoft Graph Files.ReadWrite.All permission. Check your API permission. I tested this code snippet with pretty old Microsoft.Graph library version 1.21.0. Hopefully it will work for you too.

c# file upload to AWS

Hello and apologies in advance for the noob question. I'm also relatively new to c#. In ASP.NET core, I can save files via the file upload control to AWS S3. However, this relies on me saving the files first to a location on my hard drive and then I can send in the path for the AWS code to pick it up from there. I'm sure it will be a simple answer but I can't find this after a few days' searching. As anyone who uses my site can upload (and later download) pdfs and jpegs, how do I either (1) save the file to a temporary location on their machine or phone, or, preferably, (2) 'somehow' send in the path so the AWS code can pick it up? There are many posts stating how you can't get at the path for security reasons but as far as I can tell, the AWS code relies on it.
Here's the AWS code I'm using (from their documentation). It works for me (overwrites the last file and there's no error handling yet, but one thing at once for me). The bucketName and keyName are set up elsewhere.
It's how to send in the filePath without saving it anywhere that I can't get to work. The error just says that it can't find the file, understandably.
public void FileProcess(string filePath)
{
client = new AmazonS3Client(Amazon.RegionEndpoint.EUWest2);
Amazon.S3.Model.PutObjectRequest request = new Amazon.S3.Model.PutObjectRequest()
{
BucketName = bucketName,
Key = keyName,
FilePath = filePath
};
PutObjectResponse response2 = client.PutObject(request);
}

A default path when downloading PDF file in computer/mobile phone

I created a PDF webapp where users are able to generate various type of PDF on both the computer and mobile phone. However, i run my program on a localhost and this is how i save my PDF based on my computer's file directory
var output = new FileStream(Path.Combine("C:\\Users\\apr13mpsip\\Downloads", filename), FileMode.Create);
However, when i publish my webapp onto azure, i wasn't able to download from both my computer and mobile phone. Therefore i believe that it could be due to my default file directory.
Hence i would like to ask how to do a default file directory for all computer and mobile phone?
Or could it be i left out something that is necessary when the webapp is published online
Thanks.
PS : I hardcoded a default file path in order for me to test my application on a localhost to ensure a perfect working condition. Therefore i'm finding a way to find a default common file directory for all mobile/computer users when they attempt to download the PDF instead of my usual hard-coded file path
UPDATE
I tried using the method Server.MapPath but receive some error.
var doc1 = new Document();
var filename = Server.MapPath("~/pdf") + "MyTestPDF" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf";
// var output = new FileStream(Path.Combine("C:\\Users\\apr13mpsip\\Downloads", filename), FileMode.Create);
//iTextSharp.text.pdf.PdfWriter.GetInstance(doc1, output);
using (var output = File.Create(filename))
{
iTextSharp.text.pdf.PdfWriter.GetInstance(doc1, output);
}
doc1.Open();
This is the error i received
ObjectDisposedException was unhandled by user code
Cannot access a closed file.
When you write a Web Application you shall never use hard coded paths, and the last place where you should save files is C:\Users !! It does not matter whether this is Azure or not. It is general rule for any kind of web applications!
In your case I suggest that you create a folder within your application named pdf or something like that and save files there with the following code:
var fileName = Server.MapPath("~/pdf") + filename;
using (var output = File.Create(fileName) )
{
// do what you want with that stream
// usually generate the file and send to the end user
}
However there is even more efficient way. Use the Response.OutputStream and write the resulted PDF directly to the response. Will save you a lot of space on the local server, and the logic to delete unused generated files.

Can't delete a file in C# - unauthorized access exception

In my ASP.Net web application, I have loaded one image on the HTML 5 canvas and allow the user to draw some graphics (rectangle box) over the images. Once the user has finished their drawings on the image I have to save the image back to the server with the same name at same location.
I am using AJAX to transmit the image data to the server. This part is done successfully.
In my server code, first I am trying to delete a file and then create a new file with the same name at same location.
So, When I am deleting the file, it is raising UnAuthorizedAccessException is handled by user code Access to the path 'D:\vs-2010projects\delete_sample\delete_sample\myimages\page_1.png' is denied.
Here is my Server Side C# Code...
[WebMethod()]
public static void UploadImage(string imageData)
{
byte[] data = Convert.FromBase64String(imageData);
if(File.Exists("D:\\vs-2010projects\\delete_sample\\delete_sample\\myimages\\page_1.png"))
{
File.Delete("D:\\vs-2010projects\\delete_sample\\delete_sample\\myimages\\page_1.png");
}
FileStream fs = new FileStream("D:\\vs-2010projects\\delete_sample\\delete_sample\\myimages\\page_1.png", FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(data);
bw.Close();
}//UploadImage
Is there any way to delete a file?
Please guide me out of this issue.
First of all you should pack your stream statements into using clause that will automatically handle dispose action (even in case of exception) - it will save you a lot of time during debugging strange issues coming from not-closed streams
using(var fs = new FileStream(...))
{
using(var bw = new BinaryWriter(fs)
{
bw.Write(data);
}
}
Now the exception often comes because your current process does not have access rights for the file (can't delete file) - to solve it
add full permissions for your user
You can do this by finding the file in the Windows Explorer , checking its properties and under security tab you will find specific permissions.
For example if you host your page on IIS then it is identified as application pool identity which is either IIS_IUSRS or NETWORK SERVICE and those parties are usually not trusted (or not enough trusted to be able to delete file0
I presume, it has something to do with privilege. When a user tries to connect to your Web site, IIS assigns the connection to the IUSER_ComputerName account, which belongs to the Guests group. This group has security restrictions. Try to elevate access of IUSER_ComputerName.
More can be found here.

Reading File From Network Location

I am having Bunch of Files in A folder which is shared on Network Drive . I am trying to Access those Files into my Code . But It is giving an error:
System.IO.DirectoryNotFoundException was unhandled by user code
Fname = txtwbs.Text;
DirectoryInfo objDir = new DirectoryInfo("Y:\\");
_xmlpath = objDir + "\\" + Fname + "\\" + Fname + ".xml";
if (File.Exists(_xmlpath ))
{
reader(_xmlpath);
}
I have Also used:
file = fopen("\\\\10.0.2.20\\smartjobs\\Eto\\"+Fname);
I am Able to Read File from My Local PC But it is giving Exception Only for Network Location .Please let me know how can I read File From Network Shared Location .
And Also How Can I Make A tree view of Folders into Asp.net Web Application .
Directory Structure is Like that
\\10.0.2.20\Smartjobs\Eto\
this is Parent Directory It is congaing Nos of Folder having XML Documents.
In asp.net, you cannot access network folder directly because asp.net runs under anonymous user account, that account does not have access to that location.
You can give rights to "Everyone" in that shared location and see if it is working. However this is not advisable.
Alternativly You may have to do impersonation in asp.net code when accessing network location. You will have to do implersonation with the user who has access to that shared location.
You may have map the shared directory as a user, but you forget that the asp.net is running under the account of the pool, and there you do not have connect the y:\ with the shared directory.
The next think that you can do is to direct try to connect via the network shared name, eg: \\SharedCom\fulldir\file.xml
You need to specify that the ASP.net page run as a certain user with access to the file. Then, you need to enable impersonation in your web.config file in order for ASP.net to actually access the file as that user.
Your Y drive is a mapped network drive. You need to use the network
url eg \\server\Smartjobs\Eto\xyz.xml
You specify the name of the file on the network just like you do from anywhere else:
Dim myStream As IO.FileStream = IO.File.Open("\\myserver\myshare\myfile", IO.FileMode.Open)
Dim myBytes As Byte()
myStream.Read(myBytes, 0, numberOfBytesToRead)
More reference:
Unable to List File or Directory Contents on ASP.NET Page using Shared Drive
Using file on network via IIS

Categories