Using Bit.ly API in ASP.NET 2.0 - asp.net

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

Related

how to call google acknowledge api from wcf service?

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.

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

curl Request with ASP.NET

I have read some other posts on Stack but I can't get this to work. It works fine on my when I run the curl command in git on my windows machine but when I convert it to asp.net it's not working:
private void BeeBoleRequest()
{
string url = "https://mycompany.beebole-apps.com/api";
WebRequest myReq = WebRequest.Create(url);
string username = "e26f3a722f46996d77dd78c5dbe82f15298a6385";
string password = "x";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Response.Write(content);
}
This is the BeeBole API. Its pretty straight fwd. http://beebole.com/api but I am getting a following 500 error when I run the above:
The remote server returned an error: (500) Internal Server Error.
The default HTTP method for WebRequest is GET. Try setting it to POST, as that's what the API is expecting
myReq.Method = "POST";
I assume you are posting something. As a test, I'm going to post the same data from their curl example.
string url = "https://YOUR_COMPANY_HERE.beebole-apps.com/api";
string data = "{\"service\":\"absence.list\", \"company_id\":3}";
WebRequest myReq = WebRequest.Create(url);
myReq.Method = "POST";
myReq.ContentLength = data.Length;
myReq.ContentType = "application/json; charset=UTF-8";
string usernamePassword = "YOUR API TOKEN HERE" + ":" + "x";
UTF8Encoding enc = new UTF8Encoding();
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(enc.GetBytes(usernamePassword)));
using (Stream ds = myReq.GetRequestStream())
{
ds.Write(enc.GetBytes(data), 0, data.Length);
}
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Response.Write(content);

DotNet API Library to get access HostelsClub searchengine

i am developing a application to make reservation and searching on www.hostelclub.com from my website. for that i have got a library and API Document. but both are in php. please give me a download link from where i can download it API library and docuemnt.
from code below we can ping HostelsClub in asp.net:
string targetUri = "http://www.hostelspoint.com/xml/xml.php";
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\ping.xml"));
string formParameterName = "OTA_request";
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
//string sendString = HttpUtility.UrlEncode(xmlData);
byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
string respStr = "";
if (request.HaveResponse)
{
if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
{
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respStr = respReader.ReadToEnd(); // get the xml result in the string object
XmlDocument doc = new XmlDocument();
doc.LoadXml(respStr);
Label1.Text = doc.InnerXml.ToString();
}
}

Resources