VersionConflictException when downloading document - google-drive-api

I sometimes get a VersionConflictException when trying to download a file from Google Docs. I'm guessing this is harmless but why does this happen?
I'm using gdata-media-1.0-1.41.3.jar
com.google.gdata.util.VersionConflictException: Conflict
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:612)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:563)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:552)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:530)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:535)
at com.google.gdata.client.media.MediaService.getMediaResource(MediaService.java:234)
at com.google.gdata.client.media.MediaService.getMedia(MediaService.java:276)
at com.google.gdata.client.media.MediaService.getMedia(MediaService.java:302)
The code we are using is as follows:
DocumentListEntry entry = ... // from the feed of changed documents
MediaContent documentContent = (com.google.gdata.data.MediaContent) entry.getContent();
String uri = documentContent.getUri();
MediaContent downloadContent = new MediaContent();
downloadContent.setUri(uri);
MediaSource mediaSource = docsService.getMedia(downloadContent);
InputStream inputStream = mediaSource.getInputStream();
File file = // some file
OutputStream output = new FileOutputStream(file);
try {
IOUtils.copy(inputStream, output);
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(inputStream);
}

Related

FileStream - Path found in console-application but not in mvc

Iv'e used this guide drive quickstart and successfully got it worked in a console-app.
Now I'm trying to do the same thing in an mvc-application, but I got error when creating a new FileStream.
The code a use is exactly the same in mvc instead this time i'ts triggered by a button-click. This is my code:
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 10;
listRequest.Fields = "nextPageToken, files(id, name)";
// List files.
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
.Files;
I got error at 'using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))'
My 'client_secret.json'-file is stored at the root of my mvc project.
And I've done the step: Select client_secret.json, and then go to the Properties window and set the Copy to Output Directory field to Copy always.
Why is this not working in my mvc-app?
The error I get is 'System.IO.FileNotFoundException' - '{"Cannot find file c:\windows\system32\inetsrv\client_secret.json.":"c:\windows\system32\inetsrv\client_secret.json"}'

Gdrive unable to download and not upload

I am using GDRive insertFile and RevtrieveAllFiles to upload and download files to googledrive.
I created a client secret and Id and modified the credentials.
the code is based on the post in code project http://www.codeproject.com/KB/WPF/488185/GDrive_Uploader_Sample.zip
but it fails debuggin the Utilities.InsertFile
in the file.upload it fails with exceptionvalue cannot be null - uriString .
in the download it fails in FileList files = request.Fetch(); with
// First, create a reference to the service you wish to use.
// For this app, it will be the Drive service. But it could be Tasks, Calendar, etc.
// The CreateAuthenticator method is passed to the service which will use that when it is time to authenticate
// the calls going to the service.
_service = new DriveService(CreateAuthenticator());
// Open a dialog box for the user to pick a file.
OpenFileDialog dialog = new OpenFileDialog();
dialog.AddExtension = true;
dialog.DefaultExt = ".txt";
dialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
dialog.Multiselect = false;
dialog.ShowDialog();
File body = new File();
body.Title = System.IO.Path.GetFileName(dialog.FileName);
body.Description = "A test document";
body.MimeType = "text/plain";
System.IO.Stream fileStream = dialog.OpenFile();
byte[] byteArray = new byte[fileStream.Length];
fileStream.Read(byteArray, 0, (int)fileStream.Length);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
// Get a listing of the existing files...
List<File> fileList = Utilities.RetrieveAllFiles(_service);
// Set a flag to keep track of whether the file already exists in the drive
bool fileExists = false;
foreach (File item in fileList)
{
if (item.Title == body.Title)
{
// File exists in the drive already!
fileExists = true;
MessageBoxResult result = System.Windows.MessageBox.Show("The file you picked already exists in your Google Drive. Do you wish to overwrite it?", "Confirmation", MessageBoxButton.YesNoCancel);
if (result == MessageBoxResult.Yes)
{
// Yes... overwrite the file
Utilities.UpdateFile(_service, item.Id, item.Title, item.Description, item.MimeType, dialog.FileName, true);
List<File> allFiles = Utilities.RetrieveAllFiles(_service);
}
else if (result == MessageBoxResult.No)
{
// MessageBoxResult.No code here
File f= Utilities.insertFile(_service, System.IO.Path.GetFileName(dialog.FileName), "An uploaded document", "", "text/plain", dialog.FileName);
}
else
{
// MessageBoxResult.Cancel code here
return;
}
break;
}
}
// Check to see if the file existed. If not, it is a new file and must be uploaded.
if (!fileExists)
{
File file= Utilities.insertFile(_service, System.IO.Path.GetFileName(dialog.FileName), "An uploaded document", "", "text/plain", dialog.FileName);
var list = Utilities.RetrieveAllFiles(_service);
}
System.Windows.MessageBox.Show("Upload Complete");
open gdrive and set sdk to On. that will enable the application to access the gdrive account

how to get pdf file to the temp storage file, from Url in windows phone 8.1

var uri = new System.Uri("ms-appx:///Assets/FixesViaMail_17Dec.pdf", UriKind.Absolute);
StorageFile file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
This code is working very well because i m using my system file path but whenever i am using this code
var uri = new System.Uri("http://www.visa.com/assets/upload/11458/Hotel/Voucher114581423144270.pdf", UriKind.Absolute);
StorageFile file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
then i am getting error that is.....
Value does not fall within the expected range.
Please Help me
GetFileFromApplicationUriAsync is only used for loading a file from within your application. To read a file from the web you'll need to download it. You can do this with either the HttpClient (for small files) or BackgroundDownloader (for large files) classes.
var uri = new Uri("http://www.visa.com/assets/upload/11458/Hotel/Voucher114581423144270.pdf");
var httpClient = new HttpClient();
// Always catch network exceptions for async methods
try
{
var response = await httpClient.GetAsync(uri);
// save response out
}
catch
{
// Details in ex.Message and ex.HResult.
}
See Connecting to an HTTP server using Windows.Web.Http.HttpClient (XAML) for more details.
var uri = new Uri("http://www.visa.com/assets/upload/11458/Hotel/Voucher114581423144270.pdf");
BackgroundDownloader download = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(uri, destinationFile);
See Transferring data in the background for more details.

Get a uri from a LocalStorage in Windows Phone

I write the following code to save some images from internet:
public static async Task SaveImage(string name, string uri)
{
var localfolder = ApplicationData.Current.LocalFolder;
var client = new HttpClient();
var imageStream = await client.GetStreamAsync(uri); //Secuencia de bytes
var storageFile = await localfolder.CreateFileAsync(name, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await imageStream.CopyToAsync(outputStream);
}
}
My problem is when I try to set these images store in the Local Storage to a CycleTile because this class needs the Uri's, and I don't know how to provide the uri here. This is what I have:
CycleTileData cycleicon = new CycleTileData();
cycleicon.Title = "Fotopantalla";
cycleicon.Count = 0;
cycleicon.SmallBackgroundImage = new Uri("/Assets/Tiles/FlipCycleTileSmall.png", UriKind.RelativeOrAbsolute);
List<Uri> images = new List<Uri>();
for (int i = 0; i < 9; i++)
{
/// tries...
string path1 = "ms-appdata:///local/image" + i + ".jpg";
string path2 = "isostore:/Shared/ShellContent/image" + i + ".jpg";
string path3 = "ms-appdata:///Local/Shared/ShellContent/image" + i + ".jpg";
///
Uri uri = new Uri(path2, UriKind.RelativeOrAbsolute);
images.Add(uri);
}
cycleicon.CycleImages = images;
What am I wrong or what am I missing?
For any ShellTileData related data structures you have to use path2:
"isostore:/Shared/ShellContent/*" if the images are not in the (read only) InstalledLocation folder.
For more details see: http://blogs.msdn.com/b/andy_wigley/archive/2013/04/10/live-apps-creating-custom-tile-and-lock-screen-images.aspx
I have something similar in my code:
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (!store.DirectoryExists("Shared/ShellContent"))
{
store.CreateDirectory("Shared/ShellContent");
}
StorageFolder shellContent = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("Shared", CreationCollisionOption.OpenIfExists);
shellContent = await shellContent.CreateFolderAsync("ShellContent", CreationCollisionOption.OpenIfExists);
Stream imgin = picture.GetImage();
//Picture read stream from Media Library or other input stream
StorageFile new_img = await shellContent.CreateFileAsync(newPictureName);
Stream imgout = await new_img.OpenStreamForWriteAsync();
imgin.CopyTo(imgout);
imgout.Close(); // <- necessary in your code or not?
imgin.Close(); // <-
I'm not sure, whether you really need the Isostore thing at the beginning, but it works, if I haven't done some stupid mistake while shortening the code. ;-)
Also have a look at "StandardTileData.BackgroundImage Property", "Data for Windows Phone" and "How to use the Isolated Storage Explorer tool for Windows Phone" from Microsoft's Dev Center. (The last one is about how to have a look at the saved image file on your device.)

QrCode Open Source Library for WinRT

I need to generate the Qr Code for my Windows 8 Store App.Is there any Open Source Qr Code Library which is based on Win Rt.
I have made use of zxing library which is available on codeplex.
The method I wrote is as follows:
I'm making use of the DecodeQRcode with storage file from the camera's CaptureFileAsync method which returns the storage file of the qrImgage.
public async void DecodeQRCode(StorageFile file)
{
// load a jpeg, be sure to have the Pictures Library capability in your manifest
var data = await FileIO.ReadBufferAsync(file);
// create a stream from the file
var ms = new InMemoryRandomAccessStream();
var dw = new Windows.Storage.Streams.DataWriter(ms);
dw.WriteBuffer(data);
await dw.StoreAsync();
ms.Seek(0);
// find out how big the image is, don't need this if you already know
var bm = new BitmapImage();
await bm.SetSourceAsync(ms);
// create a writable bitmap of the right size
var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);
ms.Seek(0);
// load the writable bitpamp from the stream
await wb.SetSourceAsync(ms);
var lsource = new BitmapLuminanceSource(wb);
var binarizer = new HybridBinarizer(lsource);
var bbmp = new BinaryBitmap(binarizer);
var c = new QRCodeReader();
Result res= c.decode(bbmp);
}
While taking the image of the QR code you must make sure that you crop the image properly or else you won't get the expected result.
I have not used this, but ZXing.Net is....
A library which supports decoding and generating of barcodes (like QR
Code, PDF 417, EAN, UPC, Aztec, Data Matrix, Codabar) within images.
and has assembles available for WindowsRT (as well as phone)
You can use the ZXing.NET: https://zxingnet.codeplex.com/
Code for load image to get QR Code result:
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".png");
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".bmp");
StorageFile file = await openPicker.PickSingleFileAsync();
if (null != file)
{
try
{
BitmapImage bitmap = new BitmapImage();
using (IRandomAccessStream fileStream1 = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
bitmap.SetSource(fileStream1);
}
using (IRandomAccessStream fileStream2 = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
WriteableBitmap writeableBitmap = new WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight);
writeableBitmap.SetSource(fileStream2); IBarcodeReader reader = new BarcodeReader();
var result = reader.Decode(writeableBitmap);
txt1.Text = result.ToString();
}
}
catch (Exception exception)
{
//
}
}
Code for get QR from camera (use the MSDN demo: http://code.msdn.microsoft.com/windowsapps/CameraCaptureUI-Sample-845a53ac and customized):
private async void CapturePhoto_Click(object sender, RoutedEventArgs e)
{
try
{
rootPage.NotifyUser("", NotifyType.StatusMessage);
// Using Windows.Media.Capture.CameraCaptureUI API to capture a photo
CameraCaptureUI dialog = new CameraCaptureUI();
Size aspectRatio = new Size(1, 1);
dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;
StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
BitmapImage bitmapImage = new BitmapImage();
using (IRandomAccessStream fileStream1 = await file.OpenAsync(FileAccessMode.Read))
{
bitmapImage.SetSource(fileStream1);
}
CapturedPhoto.Source = bitmapImage;
ResetButton.Visibility = Visibility.Visible;
ZXing.BarcodeReader br = new ZXing.BarcodeReader();
WriteableBitmap wrb = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
BitmapImage img = new BitmapImage();
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
using (IRandomAccessStream fileStream2 = await file.OpenAsync(FileAccessMode.Read))
{
wrb.SetSource(fileStream2);
}
var res = br.Decode(wrb);
rootPage.NotifyUser(res.ToString(), NotifyType.ErrorMessage);
}
else
{
rootPage.NotifyUser("No photo captured.", NotifyType.StatusMessage);
}
}
catch (Exception ex)
{
rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
}
}