how to call google acknowledge api from wcf service? - asp.net

i need to add a call to google acknowledge endpoint into existing dotnet web service app.
this is the refence page https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.products/acknowledge
i never worked on this app before, and i can not ask who developed it, He went away.
in the web.config are stored PlayStore ClientId and ClientSecret.
this is existing and working call to check a subscription:
internal PlayStoreSubscriptionPurchaseStatus verifySubscription(string packageName, string subscriptionId, string token, ref long timeMills)
{
Stopwatch watcher = new Stopwatch();
string accessToken = this.generateNewAccessToken(ref timeMills);
string verifySubscriptionAddress = _playStoreApisAddress + packageName + "/purchases/subscriptions/" + subscriptionId + "/tokens/" + token + "?access_token=" + accessToken;
PlayStoreSubscriptionPurchaseStatus playStoreResponse = null;
try
{
HttpWebRequest verifyRequest = WebRequest.Create(verifySubscriptionAddress) as HttpWebRequest;
verifyRequest.Method = "GET";
verifyRequest.ContentType = "application/json; charset=utf-8";
verifyRequest.Accept = "application/json; charset=utf-8";
watcher.Start();
using (HttpWebResponse verifyResponse = verifyRequest.GetResponse() as HttpWebResponse)
{
watcher.Stop();
Stream responseStream = verifyResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string responseAsString = streamReader.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
if (verifyResponse.StatusCode == HttpStatusCode.OK)
playStoreResponse = jss.Deserialize<PlayStoreSubscriptionPurchaseStatus>(responseAsString);
else
{
playStoreResponse = new PlayStoreSubscriptionPurchaseStatus() { Success = false, ErrorMessage = responseAsString };
}
}
}
catch (WebException webEx)
{
using (StreamReader streamReader = new StreamReader(webEx.Response.GetResponseStream()))
{
string webExResponse = streamReader.ReadToEnd();
throw new Exception("Errore nella verifica subscription google play.\nErrore restituito dalle api google play:\n" + webExResponse);
}
}
finally
{
if (watcher.IsRunning)
watcher.Stop();
timeMills += watcher.ElapsedMilliseconds;
}
return playStoreResponse;
}
this code generates access_token:
private string generateNewAccessToken(ref long timeMills)
{
Stopwatch watcher = new Stopwatch();
string newAccessToken = string.Empty;
string postDta = string.Format("grant_type={0}&client_id={1}&client_secret={2}&refresh_token={3}",
"refresh_token", Uri.EscapeDataString(_clientId), Uri.EscapeDataString(_clientSecret), Uri.EscapeDataString(_refreshToken));
try
{
HttpWebRequest refreshAccessTokenRequest = WebRequest.Create(_refreshTokenAddress) as HttpWebRequest;
refreshAccessTokenRequest.Method = "POST";
refreshAccessTokenRequest.ContentType = "application/x-www-form-urlencoded";
//refreshAccessTokenRequest.ContentLength = new UTF8Encoding().GetBytes(postDta).Length;
refreshAccessTokenRequest.Accept = "application/json; charset=utf-8";
Stream refreshTokenRequestStream = refreshAccessTokenRequest.GetRequestStream();
StreamWriter streamWriter = new StreamWriter(refreshTokenRequestStream);
streamWriter.Write(postDta);
streamWriter.Close();
watcher.Start();
using (HttpWebResponse refreshAccessTokenResponse = refreshAccessTokenRequest.GetResponse() as HttpWebResponse)
{
watcher.Stop();
Stream responseStream = refreshAccessTokenResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string responseAsString = streamReader.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
RenewAccessTokenResponse renewAccessTokenResponse = jss.Deserialize<RenewAccessTokenResponse>(responseAsString);
newAccessToken = renewAccessTokenResponse.access_token;
}
}
catch (WebException webEx)
{
using (StreamReader streamReader = new StreamReader(webEx.Response.GetResponseStream()))
{
string webExResponse = streamReader.ReadToEnd();
throw new Exception(webExResponse);
}
}
finally
{
if (watcher.IsRunning)
watcher.Stop();
timeMills += watcher.ElapsedMilliseconds;
}
return newAccessToken;
}
what i want to know is if i can, using only httpwebrequest, make a call to acknlowelage api,
access token generate from generateNewAccessToken is good for this api?
if yes where do i have to store it? acknlowelage is POST while all existing calls in the project are GET. do i have store the access code in body or into some header?
there is somewhere a working sample?
thanks.

Related

Uploading image to folder in ASP.net and C#

I have tried various answers here on StackOverflow but, none have solved the problem. I am trying to upload an image via file type to a folder called Images. The problem is that it always hits the catch in the try/catch. I have the block of code below but, removed the credentials for security. Please help!
[HttpPost]
public ActionResult UploadPhoto(HttpPostedFileBase file)
{
string http = "https://serverName";
string httpFolder = "/Images";
byte[] fileBytes = null;
string fileName = Path.GetFileName(file.FileName);
using (StreamReader fileStream = new StreamReader(file.InputStream))
{
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
fileStream.Close();
}
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(http + httpFolder + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
request.ContentLength = fileBytes.Length;
request.UsePassive = true;
request.UseBinary = true;
request.ServicePoint.ConnectionLimit = fileBytes.Length;
request.EnableSsl = false;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileBytes, 0, fileBytes.Length);
requestStream.Close();
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
ViewBag.FileUploaded = "File uploaded succesfully!";
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
return RedirectToAction("UploadPhoto");
}

You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse

I tried to upload file on oracle cloud infrastructure iaas but getting the error.I am not sure whether the file that I attached in the body is in
correct format or not. ApI signing is correct and I am doubt only about
whether the code that I wrote is upto mark or not. The code snippet is mentioned below.
The code Snippet :
FileInfo f = new FileInfo(FileUpload1.FileName);
byte[] filebyte =FileUpload1.FileBytes;
var postdata = Encoding.UTF8.GetBytes(filebyte.ToString());
Console.Write(postdata.Length);
var tenancyId = ConfigurationManager.AppSettings["BMCTenancyId"];
var userId = ConfigurationManager.AppSettings["BMCUserId"];
var fingerprint = ConfigurationManager.AppSettings["BMCFingerprint"];
var privateKeyPath = ConfigurationManager.AppSettings["BMCPrivateKeyPath"];
var privateKeyPassphrase = ConfigurationManager.AppSettings["BMCPrivateKeyPassphrase"];
var signer = new RequestSigner(tenancyId, userId, fingerprint, privateKeyPath, privateKeyPassphrase);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var uri = new Uri($"https://objectstorage.us-phoenix-1.oraclecloud.com/");
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Accept = "application/json";
request.SendChunked = true;
request.ContentType = "text/plain";
request.ContentLength =postdata.Length;
try
{
using (var stream = request.GetRequestStream())
{
stream.Write(postdata, 0, postdata.Length);
stream.Close();
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
request.Headers["x-content-sha256"] = Convert.ToBase64String(SHA256.Create().ComputeHash(postdata));
signer.SignRequest(request);
Console.WriteLine($"Authorization header: {request.Headers["authorization"]}");
ExecuteRequest(request);
Console.WriteLine("The value of 'ContentLength' property after sending the data is {0}", request.ContentLength);
}
private static void ExecuteRequest(HttpWebRequest request)
{
try
{
var webResponse = (HttpWebResponse)request.GetResponse();
var response = new StreamReader(webResponse.GetResponseStream()).ReadToEnd();
Console.WriteLine($"Response: {response}");
}
catch (WebException e)
{
Console.WriteLine($"Exception occurred: {e.Message}");
Console.WriteLine($"Response: {new StreamReader(e.Response.GetResponseStream()).ReadToEnd()}");
}
}
For one thing, you'll need to update the URL to the following format:
var uri = new Uri($"https://objectstorage.us-phoenix-1.oraclecloud.com/n/{namespaceName}/b/{bucketName}/o/{objectName}");
Docs: https://docs.cloud.oracle.com/iaas/api/#/en/objectstorage/20160918/Object/PutObject
Also, can you please edit the question to include the complete error you are receiving, that will help with debugging.

Mendeley Pagination

There are currently 1205 resources (citations) in the SciTS Mendeley group. However, no matter how we call the “getDocuments” method of the API, we only get the first 1000 resources. Is there a specific parameter we need to pass to get the full list of resources? Or is there a way to make a subsequent call that gets data pages not returned by the first call?
string grantType = "client_credentials";
string applicationID = "id";
string clientsecret = "XXXXXXX";
string redirecturi = "*******";
string url = "https://api-oauth2.mendeley.com/oauth/token";
string view = "all";
string group_id = "f7c0e437-f68b-34df-83c7-2877147ba8f9";
HttpWebResponse response = null;
try
{
// Create the data to send
StringBuilder data = new StringBuilder();
data.Append("client_id=" + Uri.EscapeDataString(applicationID));
data.Append("&client_secret=" + Uri.EscapeDataString(clientsecret));
data.Append("&redirect_uri=" + Uri.EscapeDataString(redirecturi));
data.Append("&grant_type=" + Uri.EscapeDataString(grantType));
data.Append("&response_type=" + Uri.EscapeDataString("code"));
data.Append("&scope=" + Uri.EscapeDataString("all"));
byte[] byteArray = Encoding.UTF8.GetBytes(data.ToString());
// Setup the Request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
// Write data
Stream postStream = request.GetRequestStream();
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Send Request & Get Response
response = (HttpWebResponse)request.GetResponse();
string accessToken;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
// Get the Response Stream
string json = reader.ReadLine();
Console.WriteLine(json);
// Retrieve and Return the Access Token
JavaScriptSerializer ser = new JavaScriptSerializer();
Dictionary<string, object> x = (Dictionary<string, object>)ser.DeserializeObject(json);
accessToken = x["access_token"].ToString();
}
// Console.WriteLine("Access TOken"+ accessToken);
var apiUrl = "https://api-oauth2.mendeley.com/oapi/documents/groups/3556001/docs/?details=true&items=1250";
try
{
request = (HttpWebRequest)WebRequest.Create(apiUrl);
request.Method = "GET";
request.Headers.Add("Authorization", "Bearer " + accessToken);
request.Host = "api-oauth2.mendeley.com";
response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
// Get the Response Stream
string json = reader.ReadLine();
Console.WriteLine(json);
//need this to import documents
}
}
catch (WebException ex1)
{
Console.WriteLine("Access TOken exception" + ex1.Message);
}
}
catch (WebException e)
{
if (e.Response != null)
{
using (HttpWebResponse err = (HttpWebResponse)e.Response)
{
Console.WriteLine("The server returned '{0}' with the status code '{1} ({2:d})'.",
err.StatusDescription, err.StatusCode, err.StatusCode);
}
}
}
The default number of items returned is limited to 1000 per page. For a paginated response you should get some additional fields in the response; notably 'items_per_page','total_pages','total_results'.
I suspect you have will two pages and to get the next result you need to append 'page=1'.

Google Drive api uploads file name as "Untitled"

I can upload file to google drive from my website, but my problem is it will show the file as Untitled after uploading.
How can I add or post title to the uploading file.
Thanks,
My Code:
public string UploadFile(string accessToken, byte[] file_data, string mime_type)
{
try
{
string result = "";
byte[] buffer = file_data;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/upload/drive/v2/files?uploadType=media");
request.Method = "POST";
request.ContentType = mime_type;
request.ContentLength = buffer.Length;
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + accessToken);
var stream = request.GetRequestStream();
stream.Write(file_data, 0, file_data.Length);
stream.Close();
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();//Get error here
if(webResponse.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
result = responseStreamReader.ReadToEnd();//parse token from result
var jLinq = JObject.Parse(result);
JObject jObject = JObject.Parse(jLinq.ToString());
webResponse.Close();
return jObject["alternateLink"].ToString();
}
return string.Empty;
}
catch
{
return string.Empty;
}
}
I used RestSharp for uploading a file to google drive.
public static void UploadFile(string accessToken, string parentId)
{
var client = new RestClient { BaseUrl = new Uri("https://www.googleapis.com/") };
var request = new RestRequest(string.Format("/upload/drive/v2/files?uploadType=multipart&access_token={0}", accessToken), Method.POST);
var bytes = File.ReadAllBytes(#"D:\mypdf.pdf");
var content = new { title = "mypdf.pdf", description = "mypdf.pdf", parents = new[] { new { id = parentId } }, mimeType = "application/pdf" };
var data = JsonConvert.SerializeObject(content);
request.AddFile("content", Encoding.UTF8.GetBytes(data), "content", "application/json; charset=utf-8");
request.AddFile("mypdf.pdf", bytes, "mypdf.pdf", "application/pdf");
var response = client.Execute(request);
if (response.StatusCode != HttpStatusCode.OK) throw new Exception("Unable to upload file to google drive");
}
Doing it with out using the google.apis dlls isnt that easy. You need to send the meta data before you send the rest of the file. For that you need to use uploadType=multipart
https://developers.google.com/drive/manage-uploads#multipart
This should get you started sorry its a wall of code. I havent had time to create a tutorial for this yet.
FileInfo info = new FileInfo(pFilename);
//Createing the MetaData to send
List<string> _postData = new List<string>();
_postData.Add("{");
_postData.Add("\"title\": \"" + info.Name + "\",");
_postData.Add("\"description\": \"Uploaded with SendToGoogleDrive\",");
_postData.Add("\"parents\": [{\"id\":\"" + pFolder + "\"}],");
_postData.Add("\"mimeType\": \"" + GetMimeType(pFilename).ToString() + "\"");
_postData.Add("}");
string postData = string.Join(" ", _postData.ToArray());
byte[] MetaDataByteArray = Encoding.UTF8.GetBytes(postData);
// creating the Data For the file
byte[] FileByteArray = System.IO.File.ReadAllBytes(pFilename);
string boundry = "foo_bar_baz";
string url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart" + "&access_token=" + myAutentication.accessToken;
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/related; boundary=\"" + boundry + "\"";
// Wrighting Meta Data
string headerJson = string.Format("--{0}\r\nContent-Type: {1}\r\n\r\n",
boundry,
"application/json; charset=UTF-8");
string headerFile = string.Format("\r\n--{0}\r\nContent-Type: {1}\r\n\r\n",
boundry,
GetMimeType(pFilename).ToString());
string footer = "\r\n--" + boundry + "--\r\n";
int headerLenght = headerJson.Length + headerFile.Length + footer.Length;
request.ContentLength = MetaDataByteArray.Length + FileByteArray.Length + headerLenght;
Stream dataStream = request.GetRequestStream();
dataStream.Write(Encoding.UTF8.GetBytes(headerJson), 0, Encoding.UTF8.GetByteCount(headerJson)); // write the MetaData ContentType
dataStream.Write(MetaDataByteArray, 0, MetaDataByteArray.Length); // write the MetaData
dataStream.Write(Encoding.UTF8.GetBytes(headerFile), 0, Encoding.UTF8.GetByteCount(headerFile)); // write the File ContentType
dataStream.Write(FileByteArray, 0, FileByteArray.Length); // write the file
// Add the end of the request. Start with a newline
dataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
dataStream.Close();
try
{
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
//Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
return "Exception uploading file: uploading file." + ex.Message;
}
If you need any explinations beyond the comments let me know. I strugled to get this working for a month. Its almost as bad as resumable upload.
I was searching for the solution of the given problem and previously I was putting uploadType=resumable that causes the given issue and when I used uploadType=multipart problem is resolved...

Using Bit.ly API in ASP.NET 2.0

Hey I was wondering if anyone can point me to some example on how to use Bit.ly API in ASP.NET 2.0
I've done a really quick convert from an answer I found in VB.
I haven't tested this (sorry) but it may be of some help in the meantime, and I will sort it out to be a bit more C# style friendly.
public static string BitlyIt(string user, string apiKey, string strLongUrl)
{
StringBuilder uri = new StringBuilder("http://api.bit.ly/shorten?");
uri.Append("version=2.0.1");
uri.Append("&format=xml");
uri.Append("&longUrl=");
uri.Append(HttpUtility.UrlEncode(strLongUrl));
uri.Append("&login=");
uri.Append(HttpUtility.UrlEncode(user));
uri.Append("&apiKey=");
uri.Append(HttpUtility.UrlEncode(apiKey));
HttpWebRequest request = WebRequest.Create(uri.ToString()) as HttpWebRequest;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.ServicePoint.Expect100Continue = false;
request.ContentLength = 0;
WebResponse objResponse = request.GetResponse();
XmlDocument objXML = new XmlDocument();
objXML.Load(objResponse.GetResponseStream());
XmlNode nShortUrl = objXML.SelectSingleNode("//shortUrl");
return nShortUrl.InnerText;
}
Original code taken from here -
http://www.dougv.com/blog/2009/07/02/shortening-urls-with-the-bit-ly-api-via-asp-net/
I found the answer from tim and it's pretty solid. I needed a vb.net version so converted it back from C# - I figured this may help someone. It appears the the bit.ly link has changed; not sure if the version is necessary anymore; added a little error handling in case you pass in a bad url.
Public Shared Function BitlyIt(ByVal strLongUrl As String) As String
Dim uri As New StringBuilder("http://api.bitly.com/v3/shorten?")
'uri.Append("version=2.0.1") 'doesnt appear to be required
uri.Append("&format=xml")
uri.Append("&longUrl=")
uri.Append(HttpUtility.UrlEncode(strLongUrl))
uri.Append("&login=")
uri.Append(HttpUtility.UrlEncode(user))
uri.Append("&apiKey=")
uri.Append(HttpUtility.UrlEncode(apiKey))
Dim request As HttpWebRequest = TryCast(WebRequest.Create(uri.ToString()), HttpWebRequest)
request.Method = "GET"
request.ContentType = "application/x-www-form-urlencoded"
request.ServicePoint.Expect100Continue = False
request.ContentLength = 0
Dim objResponse As WebResponse = request.GetResponse()
Dim myXML As New StreamReader(objResponse.GetResponseStream())
Dim xr = XmlReader.Create(myXML)
Dim xdoc = XDocument.Load(xr)
If xdoc.Descendants("status_txt").Value = "OK" Then
Return xdoc.Descendants("url").Value
Else
Return "Error " & "ReturnValue: " & xdoc.Descendants("status_txt").Value
End If
End Function
there is a bit shorter version of BitlyIn
public static string BitlyEncrypt2(string user, string apiKey, string pUrl)
{
string uri = "http://api.bit.ly/shorten?version=2.0.1&format=txt" +
"&longUrl=" + HttpUtility.UrlEncode(pUrl) +
"&login=" + HttpUtility.UrlEncode(user) +
"&apiKey=" + HttpUtility.UrlEncode(apiKey);
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.ServicePoint.Expect100Continue = false;
request.ContentLength = 0;
return (new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd());
}
Migrating from v3 to v4 of the Bitly API - Bitly V4 code for ASP.NET Applications
public string Shorten(string groupId, string token, string longUrl)
{
//string post = "{\"group_guid\": \"" + groupId + "\", \"long_url\": \"" + longUrl + "\"}";
string post = "{ \"long_url\": \"" + longUrl + "\"}";// If you've a free account.
string shortUrl = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api-ssl.bitly.com/v4/shorten");
try
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
request.ServicePoint.Expect100Continue = false;
request.Method = "POST";
request.ContentLength = post.Length;
request.ContentType = "application/json";
request.Headers.Add("Cache-Control", "no-cache");
request.Host = "api-ssl.bitly.com";
request.Headers.Add("Authorization", "Bearer " + token);
using (Stream requestStream = request.GetRequestStream())
{
byte[] postBuffer = Encoding.ASCII.GetBytes(post);
requestStream.Write(postBuffer, 0, postBuffer.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream))
{
string json = responseReader.ReadToEnd();
shortUrl = Regex.Match(json, #"""link"": ?""(?[^,;]+)""").Groups["link"].Value;
//return Regex.Match(json, #"{""short_url"":""([^""]*)""[,}]").Groups[1].Value;
}
}
}
}
catch (Exception ex)
{
LogManager.WriteLog(ex.Message);
}
if (shortUrl.Length > 0) // this check is if your bit.ly rate exceeded
return shortUrl;
else
return longUrl;
}

Resources