Yahoo Weather API using Oauth - c#

I am stuck on implementing the Yahoo Weather private API call. This is my code snippet, whenever I call it using valid clientId & Secret it returns 401 (unauthorized).
var outhWc = new WebClient();
outhWc.Credentials = new NetworkCredential(clientId, clientSecret);
outhWc.Headers.Add(HttpRequestHeader.Accept, "application/json");
var outhresponse = outhWc.DownloadData("https://query.yahooapis.com/v1/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json");
It always throws an exception. I also try to pass username and password in NetworkCredentials and also try to pass clientId and Secret in Header but I cannot find a successful call.

So I've been stuck with the same issue here. Finally I implemented the following code, based on the oAuth c# simple class found at http://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs
public void LoadWeather() {
string URLDes, Params = "";
string Signature, BaseURL, cKey, cSecret = "";
OAuthBase oAuth = new OAuthBase();
BaseURL = "http://weather.yahooapis.com/forecastrss?w=" + textBox1.Text + "&u=f";
cKey = "YOUR API KEY";
cSecret = "YOUR API SECRET";
Signature = oAuth.GenerateSignature(new Uri(BaseURL), cKey, cSecret, "", "", "GET", oAuth.GenerateTimeStamp(), oAuth.GenerateNonce(), out URLDes, out Params);
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri(String.Format("{0}?{1}&oauth_signature={2}", URLDes, Params, Signature)));
}
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e) {
if (e.Error == null) {
XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
xdoc.Save("c:\\weather.xml");
richTextBox1.Text = xdoc.FirstNode.ToString();
} else {
richTextBox1.Text = e.Error.Message;
}
}
As you can see, I already have the city ID. This sample downloads the xml string returned by the API. Worked for me, hope it helps!

Related

c# send discord webhook

Does anyone know how i would send all the data from the user to a discord webhook message?
So my code is like so:
private void materialSingleLineTextField1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
userName = materialSingleLineTextField1.Text;
rapcount(userName);
materialLabel2.Text = "Username: " + materialSingleLineTextField1.Text;
var client = new WebClient();
var text = client.DownloadString("https://api.roblox.com/users/get-by-username?username=" + materialSingleLineTextField1.Text);
Post post = JsonConvert.DeserializeObject<Post>(text);
Id = post.Id;
materialLabel3.Text = "ID: " + post.Id;
materialLabel4.Text = "Online: " + post.IsOnline;
var request = WebRequest.Create("https://www.roblox.com/headshot-thumbnail/image?userId=" + Id + "&width=420&height=420&format=png");
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
pictureBox1.Image = Bitmap.FromStream(stream);
}
//https://discordapp.com/api/webhooks/450790622446485525/HW8nYfZ39J0VPKDcxEuLoYpwVbBt8qxF4uM1SMJGp8WXIlZ33jlqzSvMThM7rSoxJUJU
materialSingleLineTextField1.Text = "";
}
}
and I want the username and ID sent as a message. Please help <3
Uhm i just got this from someone else
class
Link
code
using (dWebHook dcWeb = new dWebHook())
{
dcWeb.ProfilePicture = "https://static.giantbomb.com/uploads/original/4/42381/1196379-gas_mask_respirator.jpg";
dcWeb.UserName = "Bot";
dcWeb.WebHook = webHook;
dcWeb.SendMessage("Hello");
}
I know this thread is getting pretty old and dated but being the first result on Google as of right now, I felt posting my version and my preferred way of doing this, considering it took me a while to figure out.
Make sure to add a reference to System.Net.
using System.Net;
Method for keeping same webhook:
static void SendMs(string message)
{
string webhook = "WEBHOOK_HERE";
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
string payload = "{\"content\": \"" + message + "\"}";
client.UploadData(webhook, Encoding.UTF8.GetBytes(payload));
}
Using this method:
SendMs("Hello, world!");
Method for changing webhook on call:
static void SendMs(string message, string webhook)
{
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
string payload = "{\"content\": \"" + message + "\"}";
client.UploadData(whurl, Encoding.UTF8.GetBytes(payload));
}
Using this method:
SendMs("Hello, world!", "https://discord.com/api/webhooks/...");
Hope this helps somebody out!

How to pass body data with UploadStringAsync C#

I'm trying pass a string in the body of my POST request using WebClient class. Below is my code:
protected void GetAccessToken(string client_id, string secret)
{
var urlEncodedSecret = HttpUtility.UrlEncode(secret);
var urlEncodedSid = HttpUtility.UrlEncode(client_id);
string bodyData = String.Format("grant_type=client_credentials&client_id=ms-app%3a%2f%2f{0}&client_secret={1}&scope=notify.windows.com", client_id, secret);
string address = "https://login.live.com/accesstoken.srf";
string myParameters = "param1=value1&param2=value2&param3=value3";
Uri URI = new Uri(address);
System.Net.WebClient webClient = new WebClient();
webClient.BaseAddress = address;
webClient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
webClient.Headers["Content-Length"] = "211";
webClient.Headers["Host"] = "https://login.live.com";
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(uploadStringCompleted);
webClient.UploadStringAsync(URI, "POST", bodyData);
}
private void uploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
string json = e.Result.ToString();
_oAuthToken = GetOAuthTokenFromJson(json);
}
When i run the application, i received the exception "The remote server returned an error: NotFound.".
I succeeded to make the same request using the Postman:
Anyone know something wrong about my request? Or something that puting me on a right way!?

oauth_problem=token_rejected when refreshing Yahoo's OAuth Access Token

I've done Oauth with Hammock, I succeed to get access token, access token secret and session handle but now I must get the refresh access token when the token expired.
I've followed the instruction and I tried to pass the access token with urldecode and without urldecode but I can't get the token, I obtain
oauth_problem=token_rejected
UPDATE:
that's my code:
##the call##
var AccessTokenQuery = OAuthUtil.GetAccessTokenQueryRenewal(accessToken, session_handle, accessTokenSecret);
AccessTokenQuery.RequestAsync(AppSettings.AccessTokenUri, null);
AccessTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(AccessTokenQuery_QueryResponse);
internal static OAuthWebQuery GetAccessTokenQueryRenewal(string oauth_token,string session_handle, string oauth_token_secret)
{
var oauth = new OAuthWorkflow
{
AccessTokenUrl = AppSettings.AccessTokenUri,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
TokenSecret = oauth_token_secret,
Token = oauth_token,
SessionHandle = session_handle,
Version = AppSettings.oAuthVersion
};
var info = oauth.BuildAccessTokenInfo(WebMethod.Post);
var objOAuthWebQuery = new OAuthWebQuery(info, false);
objOAuthWebQuery.HasElevatedPermissions = true;
objOAuthWebQuery.SilverlightUserAgentHeader = "Hammock";
return objOAuthWebQuery;
}
void AccessTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e)
{
try
{
StreamReader reader = new StreamReader(e.Response);
string strResponse = reader.ReadToEnd();
var parameters = MainUtil.GetQueryParameters(strResponse);
accessToken = parameters["oauth_token"];
accessTokenSecret = parameters["oauth_token_secret"];
session_handle = parameters["oauth_session_handle"];
MainUtil.SetKeyValue<string>("AccessToken", accessToken);
MainUtil.SetKeyValue<string>("AccessTokenSecret", accessTokenSecret);
MainUtil.SetKeyValue<string>("SessionHandle", session_handle);
userLoggedIn();
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(ex.Message);
});
}
}
Quick possibility you could try: you said you 'tried to pass the access token with urldecode'. Have you tried using urlencode? Urldecode is used for decoding urls returned from a web call, encoding is what is done before passing to a web call.
Also, note that the encoding scheme for Oauth is slightly different than the one used in .NET 's default encoding. You can easily write your own encoding routine though, check out the oauth spec for details.
Ex:
private string UrlEncode(string value)
{
string unreserved = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
StringBuilder result = new StringBuilder();
foreach (char symbol in value)
{
if (unreserved.IndexOf(symbol) != -1)
result.Append(symbol);
else
result.Append('%' + String.Format("{0:X2}", (int)symbol));
}
return result.ToString();
}

Couldn't parse share document: error in LinkedIn REST API share

I try to call a share REST API with Hammock library function in my MVC 4 application.
Please see my code below
public ActionResult SharePost()
{
string content = "";
try
{
var credentials = new OAuthCredentials
{
ConsumerKey = "xxxxxxxxxxxxxx",
ConsumerSecret = "xxxxxxxxxxxxxxxx",
Token = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
TokenSecret = "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
Verifier = verifier,
Type = OAuthType.AccessToken,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
Version = "1.0"
};
var client = new RestClient { Authority = "http://api.linkedin.com/v1", Credentials = credentials, Method = WebMethod.Post };
var request = new RestRequest { Path = "/people/~/shares" };
StringBuilder sbAppend = new StringBuilder();
sbAppend.AppendLine("<?xml version=1.0 encoding=UTF-8?>");
sbAppend.AppendLine("<share><comment>Check out the LinkedIn Share API!</comment><content><title>LinkedIn Developers Documentation On Using the Share API</title><description>Leverage the Share API to maximize engagement on user-generated content on LinkedIn</description><submitted-url>https://developer.linkedin.com/documents/share-api</submitted-url><submitted-image-url>http://m3.licdn.com/media/p/3/000/124/1a6/089a29a.png</submitted-image-url></content><visibility><code>anyone</code></visibility></share>");
client.AddHeader("Content-Type", "text/xml");
byte[] msg = Encoding.Default.GetBytes(sbAppend.ToString());
client.AddPostContent(msg);
RestResponse response = client.Request(request);
content = response.Content;
}
catch (Exception ex)
{
throw ex;
}
return Content(content);
}
But i get a error responce.content
Edit
I use double quotes in my xml header. but always shows the same error.
Is there any thing wrong.
I didn't see the post xml values in fiddller. Please see this image
Please help.
I found error in your XML you are missing ""
Try this
sbAppend.AppendLine('<?xml version="1.0" encoding="UTF-8"?>');

How to post an image to Twitter in C#

I want to post an image to my Twitter account via C#. I can get access token code, everything is fine but I investigated a PHP code
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => OAUTH_CONSUMER_KEY,
'consumer_secret' => OAUTH_CONSUMER_SECRET,
'user_token' => $oauth_token,
'user_secret' => $oauth_token_secret,
));
$image = "{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}";
$code = $tmhOAuth->request('POST', 'https://upload.twitter.com/1/statuses/update_with_media.json',
array(
'media[]' => "#{$image}",
'status' => " " . $status, //A space is needed because twitter b0rks if first char is an #
'lat' => $lat,
'long' => $long,
),
true, // use auth
true // multipart
In PHP code, the OAuth class has a request method. In C# side, I used Twitterizer library which hasn't any request method in OAuth class. Then I used Webclient instead of request method. But I need to some Credentials to post data. But I don't know what/why I use username and password. Actually, I don't want to use any credentials. What can I use instead of credentials?
Second problem is, I always get an authorized errors (401) here is code
OAuthTokenResponse responseToken = OAuthUtility.GetAccessToken(ConsumerKey, ConsumerSecret, oauth_token, oauth_verifier);
OAuthTokens accessToken = new OAuthTokens();
accessToken.AccessToken = responseToken.Token;
accessToken.AccessTokenSecret = responseToken.TokenSecret;
accessToken.ConsumerKey = ConsumerKey;
accessToken.ConsumerSecret = ConsumerSecret;
TwitterResponse<TwitterUser> twitterResponse = TwitterAccount.VerifyCredentials(accessToken);
System.Net.ServicePointManager.Expect100Continue = false;
if (twitterResponse.Result != RequestResult.Unauthorized)
{
try
{
string URL = "https://upload.twitter.com/1/statuses/update_with_media.json";
WebClient client = new WebClient();
client.Credentials = new System.Net.NetworkCredential(uName, pass);
NameValueCollection postData = new NameValueCollection();
postData.Add("status", status);
postData.Add("media[]", Encoding.ASCII.GetString(bytesOfImage));
byte[] b = client.UploadValues(URL, "POST", postData); // 401 error.
}
catch (Exception e)
{
return e.Message;
}
So where is the problem in my code?
You can do this in LINQ to Twitter, using the TweetWithMedia method, like this:
static void TweetWithMediaDemo(TwitterContext twitterCtx)
{
string status = "Testing TweetWithMedia #Linq2Twitter " + DateTime.Now.ToString(CultureInfo.InvariantCulture);
const bool possiblySensitive = false;
const decimal latitude = StatusExtensions.NoCoordinate; //37.78215m;
const decimal longitude = StatusExtensions.NoCoordinate; // -122.40060m;
const bool displayCoordinates = false;
const string replaceThisWithYourImageLocation = #"..\..\images\200xColor_2.png";
var mediaItems =
new List<Media>
{
new Media
{
Data = Utilities.GetFileBytes(replaceThisWithYourImageLocation),
FileName = "200xColor_2.png",
ContentType = MediaContentType.Png
}
};
Status tweet = twitterCtx.TweetWithMedia(
status, possiblySensitive, latitude, longitude,
null, displayCoordinates, mediaItems, null);
Console.WriteLine("Media item sent - Tweet Text: " + tweet.Text);
}
Joe

Categories

Resources