I am trying to make a download link for Google Drive documents through my MVC Google Drive API application using the DownloadFile method suggested by Google Drive documentation:
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;
}
}
In the View I build the controller call by the following line:
Download
which correctly sends data to my controller's action:
public FileStreamResult DownloadFile(string downloadUrl, string mimeType, string fileName){
System.IO.Stream stream = new GDriveRepository(Utils.ReturnIAuth((GoogleAuthenticator)Session["Gauthenticator"])).DownloadFile(downloadUrl);
return new FileStreamResult(stream, mimeType);
}
But the download fails and I cannot figure out where I am wrong!
The request to download the file must include authorization information, specifically your OAuth2 access token. See the Download Files guide in the developer documentation for more information and sample code.
I do not had to seek the file cause I was just trying to download the file. What I did is just read the stream i.e. through the DownloadFile API method and pass it to the browser. I enabled 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
Just new to ms graph and also to .net.
I'm trying to write a method that deletes a notification subscription. The code itself seems to work. But i need to know how to look up the actual return code from the upstream API instead of just sending back a 204.
Here's the code:
[Route("msgraphnotification/{subscriptionId}")]
[HttpDelete]
[AllowAnonymous]
public async Task<Int> delete(string subscriptionId)
{
try{
GraphServiceClient graphClient = await getAuthToken();
await graphClient.Subscriptions["{subscription-id}"]
.Request()
.DeleteAsync();
return 204; // this is what I want to fix.
}
catch(Exception ex){
Console.Write(ex);
return 404;
}
}
If you really need to know the response code you can send HTTP request with the .Net Microsoft Graph client library.
// Get the request URL for deleting a subscription
var requestUrl = client.Subscriptions["{subscription-id}"].Request().RequestUrl;
// Create the request message.
var hrm = new HttpRequestMessage(HttpMethod.Delete, requestUrl);
// Authenticate HttpRequestMessage
await client.AuthenticationProvider.AuthenticateRequestAsync(hrm);
// Send the request and get the response.
var response = await client.HttpProvider.SendAsync(hrm);
// Get the status code.
if (!response.IsSuccessStatusCode)
{
throw new ServiceException(
new Error
{
Code = response.StatusCode.ToString(),
Message = await response.Content.ReadAsStringAsync()
});
}
else
{
var statusCode = (int)response.StatusCode;
}
...
Purpose: I am creating here a method which generates the token for payment gateway.
Code to generate and get the response from Nodus Payfabric is in PCL and the same code is working for Xamarin.IOS but not for Xamarin.Android.
The method is as below:
public async Task<HttpWebResponse> GetWebResponseForSecurityToken(string deviceID)
{
try
{
HttpWebRequest httpWebRequest = WebRequest.Create("https://sandbox.payfabric.com/v2/rest/api/token/create") as HttpWebRequest;
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "GET";
httpWebRequest.Headers["authorization"] = deviceID;
return await httpWebRequest.GetResponseAsync() as HttpWebResponse; // ISSUE LINE
}
catch (Exception)
{
return null;
}
}
As mentioned in above method issue is in return line which is not generating any error or returning the response, instead debug mode is closed after executing this line.
Is there anything I am missing to support this code with Xamarin.Android?
I am trying to connect to the survey monekey API with this code, which is not working. It says "Invalid API key" even though I got the API from the API console.
public void fetch() {
String url = "https://api.surveymonkey.net/v2/surveys/get_survey_list?api_key=" + apiKey;
System.out.println("request being sent");
System.out.println(url);
JSONObject obj = new JSONObject();
try {
// byte[] postDataBytes = obj.toJSONString().getBytes("UTF-8");
URL ourl = new URL(url.toString());
HttpURLConnection conn = (HttpURLConnection) ourl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "bearer " + accessToken);
conn.setRequestProperty("Content-Type", "application/json");
conn.getRequestProperty(obj.toString().getBytes("UTF-8").toString());
int k = conn.getResponseCode();
System.out.println("The response code received is " + k);
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
output = br.readLine();
System.out.println(output);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here's the error:
request being sent
https://api.surveymonkey.net/v2/surveys/get_survey_list?api_key=---API-KEY----
The response code received is 200
Output from Server ....
{"status":3,"errmsg":"Expected object or value"}
I just got this url from the API console.
Ensure you are using the API key associated with your developer account registered at http://developer.surveymonkey.com, not the sample API key the console uses to let you try requests. The sample api key is not meant to be used with apps, only on the API console.
That particular error is generated when an empty string is sent for the POST data. The API expects an empty object at minimum ("{}"). If the issue pointed out by Miles above was just a typo (using 'getRequestProperty' instead of 'setRequestProperty',) check if toString on an empty JSONObject is returning "" or "{}".
i am getting the same issue as described in this post
. we have used almost exactly the same code. i have tried both with Client ID and Email address of the google service account in below mehotd
setServiceAccountId(GOOGLE_SERVICE_CLIENT_EMAIL) OR
setServiceAccountId(GOOGLE_CLIENT_ID)
error changes with the change in a/c id. if i use client id, error is
400 Bad Request { "error" : "invalid_grant" }
and if i use service email id, error is
401 Unauthorized {
"code" : 401, "errors" : [ {
"domain" : "androidpublisher",
"message" : "This developer account does not own the application.",
"reason" : "developerDoesNotOwnApplication" } ], "message" : "This developer account does not own the application." }
any idea?
There appears to be some evidence that Google Play API does not currently work with Service Accounts (madness). There is another thread on the issue here. You can read about the Google Service Accounts here. You can read about authentication for Android Google Play API here.
Once you have done the dance on the Google API Console to get a refresh_token you can get an access token like this:
private String getAccessToken()
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token"));
nameValuePairs.add(new BasicNameValuePair("client_id", "YOUR_CLIENT_ID);
nameValuePairs.add(new BasicNameValuePair("client_secret", "YOUR_CLIENT_SECRET"));
nameValuePairs.add(new BasicNameValuePair("refresh_token", "YOUR_REFRESH_TOKEN"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer();
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
buffer.append(line);
}
JSONObject json = new JSONObject(buffer.toString());
return json.getString("access_token");
}
catch (IOException e) { e.printStackTrace(); }
catch (JSONException e) { e.printStackTrace(); }
return null;
}
I need to create a simple folder in a document library in SharePoint, but I can't seem to find a scrap of documentation on the subject.
The dws webservice seems to be used to create physical folders in a workspace, I need a way to create a folder in a document library.
Not sure what to do , please help
I found this method to work :
HttpWebRequest request = (System.Net.HttpWebRequest)HttpWebRequest.Create("http://mySite/MyList/MyfolderIwantedtocreate");
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "MKCOL";
HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();
This is the code for similar request in JAVA using apache HttpClient
import org.apache.http.*;
private static HttpResponse makeFolder(
String url,
DefaultHttpClient httpClient) throws Exception {
BasicHttpRequest httpPost = new BasicHttpRequest("MKCOL", url);
HttpUriRequest httpUriRequest = new RequestWrapper(httpPost);
HttpResponse status = httpClient.execute(httpUriRequest);
EntityUtils.consume(status.getEntity());
return status;
}
Code to create the httpClient and call the makeFolder Function
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(
AuthScope.ANY,
new NTCredentials(config.getUserName(), config.getPasswords(),
"", config.getDomain()));
I know this is a pretty old question, but in case someone else finds it, this is how I've done it:
String CAML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<CreateFolder " + "xmlns=\"http://schemas.microsoft.com/sharepoint/soap/dws/\">"+
"<url>" + ParentFolder+'/'+NewFolderName+ "</url>"+
"</CreateFolder>"+
"</soap:Body>" +
"</soap:Envelope>";
String uri = "http://[your site]/_vti_bin/dws.asmx";
WebClient client = new WebClient();
client.Headers["SOAPAction"] = "http://schemas.microsoft.com/sharepoint/soap/dws/CreateFolder";
client.Headers["content-type"] = "text/xml; charset=utf-8";
client.Encoding = Encoding.UTF8;
client.UploadStringCompleted += UploadStringCompleted;
try
{
client.UploadStringAsync(new Uri(uri, UriKind.Absolute), "POST", CAML);
}
catch (Exception ex)
{
MessageBox.Show("Error in upload string async: " + ex.Message);
}
I was using silverlight, which is why I used upload string async, but this can be done other ways with the same http post method
I've done some work with the Web services but I can't find any code that creates a folder. However, I have code that copies files from a network share to an existing folder in a SharePoint document library using UNC paths. It uses System.IO.File - perhaps you could use that technique to create a folder?
Created folders in sharepoint by using Document Workspace Web Service (Dws). Works great.
public static bool CreateSPFolder(string FolderDir, string FolderName, yourCredentialsClass credentials)
{
FolderName = ReplaceInvalidChars(FolderName);
// create an instance of the sharepoint service reference
Dws.Dws dwsWebService = new Dws.Dws();
dwsWebService.Url = credentials.SharePointUrl + "/_vti_bin/Dws.asmx";
dwsWebService.Credentials = new NetworkCredential(credentials.UserId, credentials.Password);
string result = dwsWebService.CreateFolder(string.Format("{0}/{1}",FolderDir,FolderName));
dwsWebService.Dispose();
if (result == null)
{
throw new Exception("No response creating SharePoint folder");
}
if (result.Equals("<Result/>"))
{
return true;
}
return false;
}
public static string ReplaceInvalidChars(string strIn)
{
return Regex.Replace(strIn.Replace('"', '-'), #"[.~#%&*{}:<>?|/]", "-");
}