Direct network transfers C# - google-drive-api

I was just curious, is it possible to have direct network transfers in c#, without local caching.
e.g.
I have response stream which represents GoogleDrive file and request stream to upload file to another GoogleDrive account.
At that momment I can download file to local pc and next upload it to the google drive. But is it possible to upload it directly from one google drive to another or, at least, start uploading before full download will be completed.
Thank

Yes you can, with Google Drive api you download file into a stream and you keep it in memory so you can upload it to another google drive account after login.
You get your token on first account and download a file keeping it in a stream.
THen you authenticate on other google drive account and upload the file using the stream.
PS: When you are inserting the file on the second drive account, instead of getting
the byte[] array reading the file from disk you get the byte array from the stream you have in memory.
File Download Example:
public static System.IO.Stream DownloadFile(
IAuthenticator authenticator, File file) {
if (!String.IsNullOrEmpty(file.DownloadUrl)) {
try {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
new Uri(file.DownloadUrl));
authenticator.ApplyAuthenticationToRequest(request);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) {
return response.GetResponseStream();
} else {
Console.WriteLine(
"An error occurred: " + response.StatusDescription);
return null;
}
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
File insert example:
private static File insertFile(DriveService service, String title, String description, String parentId, String mimeType, String filename) {
// File's metadata.
File body = new File();
body.Title = title;
body.Description = description;
body.MimeType = mimeType;
// Set the parent folder.
if (!String.IsNullOrEmpty(parentId)) {
body.Parents = new List<ParentReference>()
{new ParentReference() {Id = parentId}};
}
// File's content.
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;
}
}

Related

Updating realm file on Google Drive Api

I have a function to upload files to Google Drive.
I tried to upload with a pdf file, It's working.
public Task<String> createFilePDF(String filePath){
return Tasks.call(mExecutor,()->{
File fileMetaData = new File();
fileMetaData.setName("DinotesDemo");
java.io.File file = new java.io.File(filePath);
FileContent mediaContent = new FileContent("application/pdf",file);
File myFile = null;
try {
myFile = mDriveService.files().create(fileMetaData,mediaContent).execute();
}catch (Exception e){
}
if (myFile == null){
throw new IOException("Null result");
}
return myFile.getId();
});
}
And now, I need to upload the realm file to drive. What should I do?
Thanks very much!!

getting error while download the file in mvc2

In my site, i gave download option to download the file. when i am checking in local server it is working properly. But after deploy the server, if i click the link means it will show the following error,
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
My code here
public ActionResult Download(string fileName)
{
string pfn = Server.MapPath("~/Content/Files/" + fileName);
if (!System.IO.File.Exists(pfn))
{
//throw new ArgumentException("Invalid file name or file not exists!");
return Json(new JsonActionResult { Success = false, Message = "Invalid file name or file not exists!" });
}
else
{
return new BinaryContentResult()
{
FileName = fileName,
ContentType = "application/octet-stream",
Content = System.IO.File.ReadAllBytes(pfn)
};
}
}
This is my code. I don't know what mistake here, Can anyone find my problem and tell me ?
The Problem with ur code is that u r missing 'JsonRequestBehavior.AllowGet' while returning json.
public ActionResult Download(string fileName)
{
string pfn = Server.MapPath("~/Content/Files/" + fileName);
if (!System.IO.File.Exists(pfn))
{
//throw new ArgumentException("Invalid file name or file not exists!");
return Json(new JsonActionResult { Success = false, Message = "Invalid file name or file not exists!" },JsonRequestBehavior.AllowGet });
}
else
{
return new BinaryContentResult()
{
FileName = fileName,
ContentType = "application/octet-stream",
Content = System.IO.File.ReadAllBytes(pfn)
};
}
}

Updating new revision for google drive native documents

I created a document in google drive. I want to upload a new revision for the same document using google drive android sdk. I tried the code like,
try{
// First retrieve the file from the API.
File file = service.files().get(fileId).execute();
java.io.File fileContent = new java.io.File("sdcard0/temp/test.doc");
FileContent mediaContent = new FileContent("application/vnd.google-apps.document", fileContent);
File updatedFile = service.files().update(getID(), file, mediaContent).execute();
} catch (IOException e1) {
Log.d("","An error occurred: " + e1); //No i18n
} catch (Exception e){
Log.d("","EXCEPTION IN SAVING"+e); //No i18n
}
But the content looks like corrupted in docs.google.com like
Please guide me if am doing anything wrong.
Note: the same code works well for uploaded document.
You cannot use those revisions for native formats like google docs. Those have their own apis to modify them. For example spreadsheets has the spreadsheet feed api.
You can create a new revision for a Google Docs/Spreadsheet format using the convert parameter in the update request.
Following your code modified to enable conversion while uploading (not tested but confident it's correct)
try{
// First retrieve the file from the API.
File file = service.files().get(fileId).execute();
java.io.File fileContent = new java.io.File("sdcard0/temp/test.doc");
FileContent mediaContent = new FileContent("application/msword", fileContent); //Changed the mime type to original
File updatedFile = service.files().update(getID(), file, mediaContent)
.setConvert(true) //Convert the file while uploading
.execute();
} catch (IOException e1) {
Log.d("","An error occurred: " + e1); //No i18n
} catch (Exception e){
Log.d("","EXCEPTION IN SAVING"+e); //No i18n
}

How to download a zip file from a url and extract it on windows phone 8 .The zip file contains compressed sqlite files from server

I am not able to use DownloadDataAsync method.The only option present is DownloadStringAsync method.How can I download a zip file using this method.(I am new to windows phone 8 app development)
I just thought to share the solution that worked for me.
I created a web request to the url given and downloaded the gzip file into isolated storage file.Now after downloading i created a destination file stream and stored the compressed gzip stream file from source file to destination file using WriteByte method of GZipStream.Now we get uncompressed file.
Note:-GZipStream can be added to Visual studio from NuGet manager.
Here is the code snippet which i used to download and extract GZip file.
public async Task DownloadZipFile(Uri fileAdress, string fileName)
{
try
{
WebRequest request = WebRequest.Create(fileAdress);
if (request != null)
{
WebResponse webResponse = await request.GetResponseAsync();
if (webResponse.ContentLength != 0)
{
using (Stream response = webResponse.GetResponseStream())
{
if (response.Length != 0)
{
using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(fileName))
isolatedStorage.DeleteFile(fileName);
using (IsolatedStorageFileStream file = isolatedStorage.CreateFile(fileName))
{
const int BUFFER_SIZE = 100 * 1024;
byte[] buf = new byte[BUFFER_SIZE];
int bytesread;
while ((bytesread = await response.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
{
file.Write(buf, 0, bytesread);
}
file.Close();
FileStream sourceFileStream = File.OpenRead(file.Name);
FileStream destFileStream = File.Create(AppResources.OpenZipFileName);
GZipStream decompressingStream = new GZipStream(sourceFileStream, CompressionMode.Decompress);
int byteRead;
while ((byteRead = decompressingStream.ReadByte()) != -1)
{
destFileStream.WriteByte((byte)byteRead);
}
decompressingStream.Close();
sourceFileStream.Close();
destFileStream.Close();
PhoneApplicationService.Current.State["DestinationFilePath"] = destFileStream.Name;
}
}
FileDownload = true;
}
}
}
}
if (FileDownload == true)
{
return DownloadStatus.Ok;
}
else
{
return DownloadStatus.Other;
}
}
catch (Exception exc)
{
return DownloadStatus.Other;
}
}
Do you must use DownloadStrringAsync method? otherwise you can check these:
How to extract zipped file received from HttpWebResponse?
download and decompress a zip file in windows phone 8 application
Extract zip file from isolatedstorage
How to download a GZIP file from web to Windows Phone 7 and unzip the contents
To download zip file from the url first there is need to store zip files into isolated storage and after that extract it and read the file as per requirement.
http://axilis.hr/uznip-archives-windows-phone

HTML2PDF using Google Drive API

Is it possible to upload and convert an HTML file to PDF using Google Drive API without user interaction?
Yes, it is, with two requests. You can import the file as a Google Docs, then export it to PDF. Using the Drive API.
https://developers.google.com/drive/v2/reference/files/insert
https://developers.google.com/drive/v2/reference/files/get
worked for me (Drive docs only...)
ByteArrayContent mediaContent = new ByteArrayContent("text/html", "HTML PAGE HERE".getBytes());
File body = new File();
body.setTitle("test.html");
body.setMimeType("text/html");
Insert request = null;
try
{
request = service.files().insert(body, mediaContent);
request.setConvert(true);
File file = request.execute();
HttpResponse resp = service.getRequestFactory().buildGetRequest(new GenericUrl(file.getExportLinks().get("application/pdf"))).execute();
OutputStream out = new FileOutputStream(getExternalFilesDir(null).getAbsolutePath() + "/test.pdf");
byte[] buf = new byte[1024];
int len;
while ((len = resp.getContent().read(buf)) > 0)
{
out.write(buf, 0, len);
}
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}