How to cancel upload in Google Drive API? - c#

i am developing a application for uploading file in Google drive using drive API.I am able to upload image successfully.but my problem is, when i cancel uploading it is not cancelled.I am uaing following code:
Google.Apis.Drive.v2.Data.File image = new Google.Apis.Drive.v2.Data.File();
//set the title of file
image.Title = fileName;
//set Mime Type of file
image.MimeType = "image/jpeg";
//set the stream position 0 because stream is readed already
strm.Position = 0;
//create a request for insert a file
System.Threading.CancellationTokenSource ctsUpload = new CancellationTokenSource();
FilesResource.InsertMediaUpload request = App.GoogleDriveClient.Files.Insert(image, strm, "image/jpeg");
request.ChunkSize = 512 * 1024;
request.ProgressChanged += request_ProgressChanged;
//visible the uploading progress
//upload file
request.UploadAsync(ctsUpload.Token);
Following code is written on cancel botton click event
ctsUpload.Cancel();

Based on the following answer (Google drive SDK: Cancel upload) seems google has still this issue "unresolved".
In case of need axe found a solution.

Related

WebAPI to download PowerPoint file using memory stream

I'm having trouble downloading a file with content using a Powerpoint presentation library (Syncfusion). The docs only supply ASP examples, no Web API specifically.
I can save a file to the file system which has the context I add to the Powerpoint.
I can get the API to download a file to the users browser but this Powerpoint is empty.
Syncfusion has a function to save the Powerpoint to a memory stream so I guess my question is what is the correct way to save a file to the users browser with the content from the stream?
I'm using HTTPGet and hitting the link through the browser. Do I need to sent the context-type or anything like that?
Thanks for your help, I can provide what I have so far if that helps.
Kurtis
Edit:
[HttpGet, Route("")]
public HttpResponseMessage Get()
{
var presentation = Presentation.Create();
var firstSlide = presentation.Slides.Add(SlideLayoutType.Blank);
var textShape = firstSlide.AddTextBox(100, 75, 756, 200);
var paragraph = textShape.TextBody.AddParagraph();
paragraph.HorizontalAlignment = HorizontalAlignmentType.Center;
var textPart = paragraph.AddTextPart("Kurtis' Presentation");
textPart.Font.FontSize = 80;
var memoryStream = new MemoryStream();
presentation.Save(memoryStream);
var result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(memoryStream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "export.pptx"
};
return result;
}
This is what I have, the library saves the presentation to the memory stream, you can change the parameter to a string which writes this to a file and there is an option to pass a filename, format and HttpResponse for MVC but I couldn't get this working with my API controller. I kept getting a network error but didn't know why.
Thanks again
I found my problem with the help of others in the comments.
The code above work but I needed to reset the stream position to zero to actually write the data.
memoryStream.Position = 0;
Thanks for those who commented. :-)

File uploading and processing in ASP MVC

I'm need to implement next page:
User click on button Upload file, select file and uploading it on server. After uploading file will be processed by converter. Converter can return percentage of conversion. How to implement continuous progress bar on page (progress = upload progress + convert progress)?
I'm using PlUpload - this tool can return percentage of uploading file to server, but I can't override returning percentage.
That my upload action:
public ActionResult ConferenceAttachment(int? chunk, string name, Identity cid)
{
var fileUpload = Request.Files[0];
var tempfolder = Path.GetTempFileName().Replace('.', '-');
Directory.CreateDirectory(tempfolder);
var fn = Path.Combine(tempfolder, name);
chunk = chunk ?? 0;
using (var fs = new FileStream(fn, chunk == 0 ? FileMode.Create : FileMode.Append))
{
var buffer = new byte[fileUpload.InputStream.Length];
fileUpload.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
}
// CONVERTING ....
return Content("OK", "text/plain");
}
Which architecture solution can solve my problem? Or which JS upload library?
You must use some kind of Real-Time connection or a Streaming to do this.
1) Using SignalR you can create a Hub to notificate the client about the progress, easy to implement and powerfull.
Learn About ASP.NET SignalR
2) You can adapte this example about PushStreamContent to send the progress while you are converting:
Asynchronously streaming video with ASP.NET Web API
You can set buffer size as much as you want. But, I would say to upload 8kb data of file at a time & meanwhile start streaming conversion process asynchronously. But, for smooth progress again what kind of file you wanna upload?

Save a file on a ftp server in a subdirectory

I have code that allows me to access a server to do ftp transactions. I have tested the connection and it works. the problem is saving files. to help paint a picture this is how the address are set up.
ftp server: ftp.MyMainDomain.com
path login ftp points to: www.another_website_Under_myDomain.com/gallery/images
when I tested connection, ftp server tacks me directly to images folder and I have even read the subdirectories out (ie ..images/subdirectory1, ..images/subdirectory2).
What I need now it to be able to save files into each of the folders. I thought that all I had to do was add subdir that I wanted to access to the end of the ftp_server uri but that doesn't work. What should I do?
Uri ftpUri = new Uri((Ftp_Server_Address + "/" + SubDirectory+ "/"), UriKind.Absolute);
if (ftpUri.Scheme == Uri.UriSchemeFtp)// check ftp address,
{
DirRequest = (FtpWebRequest)FtpWebRequest.Create(ftpUri);
DirRequest.Method = ReqMethod;
DirRequest.Credentials = new NetworkCredential(FtpUserName, FtpPassword);
DirRequest.UsePassive = true;
DirRequest.UseBinary = true;
DirRequest.KeepAlive = false;
//change picture to stream
Stream PicAsStream = Pic.Bitmap_to_Stream(Pic.BitmapImage_to_Bitmap(Pic.Photo));
//send ftp with picture
Stream ftpReqStream = DirRequest.GetRequestStream();
ftpReqStream = PicAsStream;
ftpReqStream.Close();
SendFtpRequest(ReqMethod);
}
In this line:
ftpReqStream = PicAsStream;
You are not sending the Stream to ftp Server but you are assigning PicAsStream to ftpReqStream and then closing it. Your code does nothing.
Do it like this:
Create a buffer of your image file (not a stream):
FileStream ImageFileStream = File.OpenRead(your_file_path_Here);
byte[] ImageBuffer = new byte[ImageFileStream.Length];
ImageFileStream.Read(ImageBuffer, 0, ImageBuffer.Length);
ImageFileStream.Close();
and then simply write it to your ftpReqStream:
Stream ftpReqStream = DirRequest.GetRequestStream();
ftpReqStream.Write(ImageBuffer, 0, ImageBuffer.Length);
ftpReqStream.Close();

Issues with webscraping in C#: Downloading and parsing zipped text files

I am writing an webscraper, to do the download content from a website.
Traversing to the website/URL, triggers the creation of a temporary URL. This new URL has a zipped text file. This zipped file has to be downloaded and parsed.
I have written a scraper in C# using WebClient and its function DownloadFileAsync(). The zipped file is read from the designated location on a trapped DownloadFileCompleted event.
My issue is The Windows Open/Save dialog are triggered. This requires user input and the automation is disrupted.
Can you suggest a way to bypass the issue ? I am cool with rewriting the code using any alternate libraries. :)
Thanks for reading
You can use 'HttpWebRequest' to perform the request and save the streamed bytes to disk.
var request = WebRequest.Create(#"your url here");
request.Method=WebRequestMethods.Http.Get;
var response = request.GetResponse();
using (var writeStream = new FileStream(#"path", FileMode.Create))
{
using (var readStream = response.GetResponseStream())
{
var buffer = new byte[1024];
var readCount = readStream.Read(buffer,0,buffer.Length);
while (readCount > 0)
{
writeStream.Write(buffer,0,buffer.Length);
readCount= readStream.Read(buffer,0,buffer.Length);
}
}
}

C# Google Api Upload Stream

I have read a few questions around and i tried those examples and they worked for me, here are links:
- Link 1
- Link 2
- Link 3
However,
What i'm tryin to accomplish its a little bit different, im trying to modify/upload a .DAT file that contains plain text inside. Im able to read file contents with no problems but i always get 400 Bad Request(Protocol Error). Heres my code.
DocumentsService service = new DocumentsService("Man");
service.setUserCredentials(UserName, Passwod);
DocumentsListQuery fileQuery = new DocumentsListQuery();
fileQuery.Query = User.FileName;
fileQuery.TitleExact = true;
DocumentsFeed feed = service.Query(fileQuery);
//Here I get my file to update
DocumentEntry entry = (DocumentEntry)feed.Entries[0];
// Set the media source
//Here I have tried application/octet-stream also
entry.MediaSource = new MediaFileSource(DataStream, User.FileName, text/plain");
// Instantiate the ResumableUploader component.
ResumableUploader uploader = new ResumableUploader();
// Set the handlers for the completion and progress events
uploader.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(OnDone);
uploader.AsyncOperationProgress += new syncOperationProgressEventHandler(OnProgress);
ClientLoginAuthenticator authenticator = new ClientLoginAuthenticator("Man", ServiceNames.Documents,Credentials);
Uri updateUploadUrl = new Uri(UploadUrl);
AtomLink aLink = new AtomLink(updateUploadUrl.AbsoluteUri);
aLink.Rel = ResumableUploader.CreateMediaRelation;
entry.Links.Add(aLink);
// Start the update process.
uploader.UpdateAsync(authenticator,entry,new object());
Thanks.
EDIT:
This is how i solved it. Thanks to Claudio for guide me on the proper direction
Download Example Application from : Download Sample (.zip)
Implement to your project from SampleHelper Project these: AuthorizationMgr, INativeAuthorizationFlow, LoopbackServerAuthorizationFlow, WindowTitleNativeAuthorizationFlow
Use it with this code:
//Call Authorization method... (omitted)
File body = new File();
body.Title = title;
body.Description = description;
body.MimeType = mimeType;
byte[] byteArray = System.IO.File.ReadAllBytes(filename);
MemoryStream stream = new MemoryStream(byteArray);
try {
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
request.Upload();
File file = request.ResponseBody;
// Uncomment the following line to print the File ID.
// Console.WriteLine("File ID: " + file.Id);
return file;
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
Whenever the server returns a 400 Bad Request, it also includes a descriptive error message telling what is invalid in your request. If you can't get to it from the debugger, you should install Fiddler and capture the HTTP request and response.
Another advice I have for you is to start using the newer Drive API instead of the Documents List API. Here is a 5-minute C# quickstart sample showing how to upload a file to Google Drive:
https://developers.google.com/drive/quickstart

Categories