Updating new revision for google drive native documents - google-drive-api

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
}

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!!

Unity - Read JSON file From android [duplicate]

This is how i read my textfile in android.
#if UNITY_ANDROID
string full_path = string.Format("{0}/{1}",Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
// Android only use WWW to read file
WWW reader = new WWW(full_path);
while (!reader.isDone){}
json = reader.text;
// PK Debug 2017.12.11
Debug.Log(json);
#endif
and this is how i read my textfile from pc.
#if UNITY_STANDALONE
string full_path = string.Format("{0}/{1}", Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
StreamReader reader = new StreamReader(full_path);
json = reader.ReadToEnd().Trim();
reader.Close();
#endif
Now my problem is that i don't know how to write the file on mobile cause i do it like this on the standalone
#if UNITY_STANDALONE
StreamWriter writer = new StreamWriter(path, false);
writer.WriteLine(json);
writer.Close();
#endif
Help anyone
UPDATED QUESTION
This is the json file that it is in my streamingasset folder that i need to get
Now my problem is that i don't know how to write the file on mobile
cause I do it like this on the standalone
You can't save to this location. Application.streamingAssetsPath is read-only. It doesn't matter if it works on the Editor or not. It is read only and cannot be used to load data.
Reading data from the StreamingAssets:
IEnumerator loadStreamingAsset(string fileName)
{
string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, fileName);
string result;
if (filePath.Contains("://") || filePath.Contains(":///"))
{
WWW www = new WWW(filePath);
yield return www;
result = www.text;
}
else
{
result = System.IO.File.ReadAllText(filePath);
}
Debug.Log("Loaded file: " + result);
}
Usage:
Let's load your "datacenter.json" file from your screenshot:
void Start()
{
StartCoroutine(loadStreamingAsset("datacenter.json"));
}
Saving Data:
The path to save a data that works on all platform is Application.persistentDataPath. Make sure to create a folder inside that path before saving data to it. The StreamReader in your question can be used to read or write to this path.
Saving to the Application.persistentDataPath path:
Use File.WriteAllBytes
Reading from the Application.persistentDataPath path
Use File.ReadAllBytes.
See this post for a complete example of how to save data in Unity.
This is the way I do it without the WWW class (works for Android an iOS), hope its useful
public void WriteDataToFile(string jsonString)
{
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
File.WriteAllText(filePath, jsonString);
}
else
{
File.WriteAllText(filePath, jsonString);
}
}

Location of folders created in Windows Phone 8

Where do I find the location of the folders and text files I created in windows phone 8. Can we see it in the explorer like we search for the app data in Windows 8? I'm not using IsolatedStorage, instead Windows.Storage. I want to check if the folders and files are created as I want.
This is how I write the file
IStorageFolder dataFolder = await m_localfolder.CreateFolderAsync(App.ALL_PAGE_FOLDER, CreationCollisionOption.OpenIfExists);
StorageFile PageConfig = null;
try
{
PageConfig = await dataFolder.CreateFileAsync("PageConfig.txt", CreationCollisionOption.OpenIfExists);
}
catch (FileNotFoundException)
{
return false;
}
EDIT
try
{
if (PageConfig != null)
{
using (var stream = await PageConfig.OpenStreamForWriteAsync())
{
DataWriter writer = new DataWriter(stream.AsOutputStream());
writer.WriteString(jsonString);
}
}
}
catch (Exception e)
{
string txt = e.Message;
return false;
}
And this is how I read the file from the folder
try
{
var dataFolder = await m_localfolder.GetFolderAsync(App.ALL_PAGE_FOLDER);
var retpng = await dataFolder.OpenStreamForReadAsync("PageConfig.txt");
if (retpng != null)
{
try
{
using (StreamReader streamReader = new StreamReader(retpng))
{
jsonString = streamReader.ReadToEnd();
}
return jsonString;
}
catch (Exception)
{
}
}
}
catch (FileNotFoundException)
{
}
There are also other folders created. I dont receive any exceptions while writing but when I read the string is empty.
Windows.Storage.ApplicationData.LocalFolder(MSDN link here) is another name for Isolated Storage that is in Windows.Storage namespace. The only other location you can access is your app's install directory (and only read-only).
You can use Windows Phone Power Tools to browse what files are in your app's Isolated Storage, or the command line tool that comes with the SDK.
With the help of Windows Phone Power tools, I figured out that there was no text being written in file.
So I converted string to byte and then wrote it to the file and it works! Don't know why the other one does not work though..
using (var stream = await PageConfig.OpenStreamForWriteAsync())
{
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(jsonString);
stream.Write(fileBytes, 0, fileBytes.Length);
}
The command line tool that comes with Windows Phone SDK 8.0 is Isolated Storage Explorer (ISETool.exe) which reside in "Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Tools\IsolatedStorageExplorerTool" folder for default installation
ISETool.exe is used to view and manage the contents of the local folder

Direct network transfers C#

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;
}
}

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();
}