how to download file form Google Drive asp.net - google-drive-api

I am trying to download files from google drive below is my code
private static IAuthenticator CreateAuthenticator()
{
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = ClientCredentials.CLIENT_ID;
provider.ClientSecret = ClientCredentials.CLIENT_SECRET;
return new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
}
public static System.IO.Stream DownloadFile(
IAuthenticator authenticator, Google.Apis.Drive.v2.Data.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;
}
}
in .aspx page code
{
System.IO.Stream stream = Utilities.DownloadFile(CreateAuthenticator(), FIle);
//Convert the stream to an array of bytes.
System.IO.BinaryReader br = new System.IO.BinaryReader(stream);
Byte[] byteArray = br.ReadBytes((int)stream.Length);
its showing This stream does not support seek operations.
where is error
thank u....

You do not have to seek the file if you are trying just to download the file. What you should do is just to read the stream i.e. through the DownloadFile API method and pass it to the browser. I have enable it through the following code:
public FileResult DownloadFile(string fileId)
{
DriveService service = Session["service"] as DriveService;
Google.Apis.Drive.v2.Data.File file = service.Files.Get(fileId).Fetch();
System.IO.Stream data = new GDriveRepository(Utils.ReturnIAuth((GoogleAuthenticator)Session["Gauthenticator"])).DownloadFile(file.DownloadUrl);
return File(data, System.Net.Mime.MediaTypeNames.Application.Octet, file.Title);
}

Related

Windows Phone: How to load html in webview from a local file

I have a html string and it has local css,js paths. But Html is not working with these local paths. We searced but in every example, they have loaded html with writing inline. But I have to work disconnect and there is so much css,js assests. If i write inline, i am worried about it will load slow and i think it so senseless. Then i decided to change a local html file and load html from that file.
How can i load html from a local file?
This is my example code:
StorageFolder localFolder =
Windows.Storage.ApplicationData.Current.LocalFolder;
string desiredName = "mobile.html";
StorageFile newFile =
await localFolder.CreateFileAsync(desiredName,CreationCollisionOption.OpenIfExists);
using (var stream = await newFile.OpenStreamForWriteAsync())
{
stream.Write(fileBytes, 0, fileBytes.Length);
}
webViewFormResponse.Source = new Uri(newFile.Path);
newFile.Path like this: C:\Data\Users\DefApps\APPDATA\Local\Packages\9f4082ad-ad69-4cb8-8749-751ee4c5e46d_x2xndhe6jjw20\LocalState\mobile.html
You can use the NavigateToLocalStreamUri method of the WebView
e.g.
In WebView Loaded event
private void WebView_Loaded(object sender, RoutedEventArgs e)
{
Uri uri = MyWebView.BuildLocalStreamUri("LocalData", "mobile.html");
LocalUriResolver resolver = new LocalUriResolver();
MyWebView.NavigateToLocalStreamUri(uri, resolver);
}
And the Uri resolver class
public sealed class LocalUriResolver : IUriToStreamResolver
{
public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
{
if (uri == null)
{
throw new Exception();
}
string path = uri.AbsolutePath;
return GetContent(path).AsAsyncOperation();
}
private async Task<IInputStream> GetContent(string uriPath)
{
try
{
Uri localUri = new Uri("ms-appdata:///local" + uriPath);
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(localUri);
IRandomAccessStream stream = await file.OpenReadAsync();
return stream.GetInputStreamAt(0);
}
catch (Exception)
{
throw new Exception("Invalid path");
}
}
}

HTTP error 500 on Android

So here is my code, its purpose is to fecth a json file. I get an error 500 from the server, which means I know that it is an internal server error. As I can't access to the logs of the the server, I'm pretty much stuck from now... I read about session and cookies, maybe that's it. What do you guy think of it ?
private class ListingFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "ListingFetcher";
public static final String SERVER_URL = "http://www.myurl.com/listing.json";
#Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<Listing> events = new ArrayList<Listing>();
events = Arrays.asList(gson.fromJson(reader, Listing[].class));
content.close();
handlePostsList(events);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}
}
My code is perfectly working. THe only mistake is on this line :
HttpPost post = new HttpPost(SERVER_URL);
Which should be
HttpGet get = new HttpGet(SERVER_URL);

Windows Phone 8 append to JSON file

I'm working on a Windows Phone 8 app.
I'm having issue appending to my JSON file.
It works fine if I keep the app open but once I close it and come back in it starts back writing from the beginning of the file.
Relevant code:
private async void btnSave_Click(object sender, RoutedEventArgs e)
{
// Create a entry and intialize some values from textbox...
GasInfoEntries _entry = null;
_entry = new GasInfoEntries();
_entry.Gallons = TxtBoxGas.Text;
_entry.Price = TxtBoxPrice.Text;
_GasList.Add(_entry);
//TxtBlockPricePerGallon.Text = (double.Parse(TxtBoxGas.Text) / double.Parse(TxtBoxPrice.Text)).ToString();
// Serialize our Product class into a string
string jsonContents = JsonConvert.SerializeObject(_GasList);
// Get the app data folder and create or open the file we are storing the JSON in.
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile textfile = await localFolder.CreateFileAsync("gasinfo.json", CreationCollisionOption.OpenIfExists); //if get await operator error add async to class (btnsave)
//open file
using (IRandomAccessStream textstream = await textfile.OpenAsync(FileAccessMode.ReadWrite))
{
//write JSON string
using (DataWriter textwriter = new DataWriter(textstream))
//using (DataWriter textwriter = new DataWriter(textstream))
{
textwriter.WriteString(jsonContents);
await textwriter.StoreAsync(); //writes buffer to store
}
}
}
private async void btnShow_Click(object sender, RoutedEventArgs e)
{
StorageFolder localfolder = ApplicationData.Current.LocalFolder;
try
{
// Getting JSON from file if it exists, or file not found exception if it does not
StorageFile textfile = await localfolder.GetFileAsync("gasinfo.json");
using (IRandomAccessStream textstream = await textfile.OpenReadAsync())
{
//read text stream
using (DataReader textreader = new DataReader(textstream))
{
//get size ...not sure what for think check the file size (lenght) then based on next 2 commands waits until its all read
uint textlength = (uint)textstream.Size;
await textreader.LoadAsync(textlength);
//read it
string jsonContents = textreader.ReadString(textlength);
// deserialize back to gas info
_GasList = JsonConvert.DeserializeObject<List<GasInfoEntries>>(jsonContents) as List<GasInfoEntries>;
displayGasInfoEntries();
}
}
}
catch
{
txtShow.Text = "something went wrong";
}
}
private void displayGasInfoEntries()
{
txtShow.Text = "";
StringBuilder GasString = new StringBuilder();
foreach (GasInfoEntries _entry in _GasList)
{
GasString.AppendFormat("Gallons: {0} \r\n Price: ${1} \r\n", _entry.Gallons, _entry.Price); // i think /r/n means Return and New line...{0} and {1} calls "variables" in json file
}
txtShow.Text = GasString.ToString();
}
Thanks
Do you call the btnShow_Click each time you've started the app? Because otherwise the _GasList will be empty; if you now call the btnSave_Click all previous made changes will be lost.
So please make sure, that you restore the previously saved json data before you add items to the _GasList.

how to handle http 400 and 401 error while using webclient to download JSON

I am using an api that returns an error 400 if URL is invalid and error 401 if daily qouta is exhausted by 50%. it also returns the json but am not able to download this json as an exception occurs if these error occurs. the api am using is
http://www.sharedcount.com/documentation.php
the code am using write now is...
private void _download_serialized_json_data(Uri Url)
{
var webClient = new WebClient();
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(Url);
}
catch (Exception) { }
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String Json = null;
try
{
Json = e.Result;
}
catch (Exception ex)
{
}
if(Json!=null)
{
data=JsonConvert.DeserializeObject<RootObject>(Json);
result.Text = "facebook : "+data.Facebook.like_count+"\nGooglePlus : "+data.GooglePlusOne;
}
else
{
result.Text = "Invald URL \nor you exceeded your daily quota of 100,000 queries by 50%.";
}
}
currently am showing both errors if exception occurs. but i want to download the json and display that. how should i do that
To get the response content, you will need to use System.Net.Http.HttpClient instead. Install it from here: Microsoft HTTP Client Libraries
Then try this:
private async void Foo2()
{
Uri uri = new Uri("http://localhost/fooooo");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync(uri);
HttpStatusCode statusCode = response.StatusCode; // E.g.: 404
string reason = response.ReasonPhrase; // E.g.: Not Found
string jsonString = await response.Content.ReadAsStringAsync(); // The response content.
}
You can try something like this,
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String Json = null;
if(e.Error != null)
{
//Some error occured, show the error message
var ErrorMsg = e.Error.Message;
}
else
{
//Got some response .. rest of your code
Json = e.Result;
}
}
I ran into this same issue using WebClient, I saw the error response stream being captured in Fiddler, but my .NET code was catching the exception and did not appear to be capturing the response stream.
You can read the Response stream from the WebException object to get the response data stream out.
using (System.Net.WebClient client = new System.Net.WebClient())
{
string response = "";
try
{
response = client.UploadString(someURL, "user=billy&pass=12345");
}
catch(WebException ex)
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(ex.Response.GetResponseStream()))
{
string exResponse = sr.ReadToEnd();
Console.WriteLine(exResponse);
}
}
}

Serializing and deserializing a list of objects in a Windows Phone 8 app

Given some list of objects:
List<Car> carlist = new List<Car>();
How can I serialize this list as an XML or binary file and deserialize it back?
I have this so far but it doesn't work.
//IsolatedStorageFile isFile = IsolatedStorageFile.GetUserStoreForApplication();
//IsolatedStorageFileStream ifs = new IsolatedStorageFileStream("myxml.xml", FileMode.Create,isFile);
//DataContractSerializer ser = new DataContractSerializer();
//XmlWriter writer = XmlWriter.Create(ifs);
//ser.WriteObject(writer, carlist);
I'm using these methods to Save and Load from a XML file in/to the IsolatedStorage :
public static class IsolatedStorageOperations
{
public static async Task Save<T>(this T obj, string file)
{
await Task.Run(() =>
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream stream = null;
try
{
stream = storage.CreateFile(file);
XmlSerializer serializer = new XmlSerializer(typeof (T));
serializer.Serialize(stream, obj);
}
catch (Exception)
{
}
finally
{
if (stream != null)
{
stream.Close();
stream.Dispose();
}
}
});
}
public static async Task<T> Load<T>(string file)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
T obj = Activator.CreateInstance<T>();
if (storage.FileExists(file))
{
IsolatedStorageFileStream stream = null;
try
{
stream = storage.OpenFile(file, FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof (T));
obj = (T) serializer.Deserialize(stream);
}
catch (Exception)
{
}
finally
{
if (stream != null)
{
stream.Close();
stream.Dispose();
}
}
return obj;
}
await obj.Save(file);
return obj;
}
}
You can customize the error handling in the catch().
Also, you can adjust the Load method to your needs, in my case I am trying to load from a file and if doesn't exist, it creates a default one and puts the default serialized object of the type provided according to the constructor.
UPDATE :
Let's say you have that list of cars :
List< Car > carlist= new List< Car >();
To save, you can just call them as await carlist.Save("myXML.xml"); , as it is an asynchronous Task(async).
To load, var MyCars = await IsolatedStorageOperations.Load< List< Car> >("myXML.xml"). (I think, I haven't used it like this, as a List so far...
DataContactJsonSerializer performs better than XmlSerializer. It creates smaller files and handles well lists inside properties.