I am trying to setup a simple app that consumes the Yahoo Fantasy sports API, and allows queries to be executed through YQL.
class Program
{
static void Main(string[] args)
{
string yql = "select * from fantasysports.games where game_key in ('268')";
//var xml = QueryYahoo(yql);
// Console.Write(xml.InnerText);
string consumerKey = "--my key--";
string consumerSecret = "--my secret--";
var xml = QueryYahoo(yql, consumerKey, consumerSecret);
Console.Write(xml.InnerText);
}
private static XmlDocument QueryYahoo(string yql)
{
string url = "http://query.yahooapis.com/v1/public/yql?format=xml&diagnostics=false&q=" + Uri.EscapeUriString(yql);
var req = System.Net.HttpWebRequest.Create(url);
var xml = new XmlDocument();
using (var res = req.GetResponse().GetResponseStream())
{
xml.Load(res);
}
return xml;
}
private static XmlDocument QueryYahoo(string yql, string consumerKey, string consumerSecret)
{
string url = "http://query.yahooapis.com/v1/yql?format=xml&diagnostics=true&q=" + Uri.EscapeUriString(yql);
url = OAuth.GetUrl(url, consumerKey, consumerSecret);
var req = System.Net.HttpWebRequest.Create(url);
var xml = new XmlDocument();
using (var res = req.GetResponse().GetResponseStream())
{
xml.Load(res);
}
return xml;
}
There is some hidden in here, I have a custom class to make the url ok for the Yahoo API. Here is the structure of the URL that the OAuth.GetUrl() method returns
http://query.yahooapis.com/v1/yql?diagnostics=true&format=xml&oauth_consumer_key=mykey&oauth_nonce=rlfmxniesu&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1332785286&oauth_version=1.0&q=select%20%2A%20from%20fantasysports.games%20where%20game_key%20in%20%28%27268%27%29&oauth_signature=NYKIbhjoirJwB6ADxVq5DOgLW1w%3D
With this, I always seem to get
Authentication Error. The table fantasysports.games requires a higher security level than is provided, you provided APP but at least USER is expected
I am not sure what this means, I am passing my auth information to the api, but it seems I need more permissions. Has anyone have a working example of this. If needed, I can supply code to the GetUrl method, but it is more or less a copy paste from here
http://andy.edinborough.org/Getting-Started-with-Yahoo-and-OAuth
Let me know if you have any questions. Thanks!
I couldn't make it work using the YQL, but I was able to get the players data and draft result etc, by directly using the APIs at https://fantasysports.yahooapis.com/fantasy/v2/
e.g. to get NFL player David Johnson details:
GET /fantasy/v2/players;player_keys=371.p.28474 HTTP/1.1
Host: fantasysports.yahooapis.com
Authorization: Bearer [[Base64 encoded ClientId:Secret]]
Content-Type: application/json
Related
Having a difficult time getting an HTTP POST request/response using cefsharp / ChromiumWebBrowser. I'm unable to find a working example on Stackoverflow, nor in the documentation. Looking to see if anyone has a full example? I'm stuck on if it can be done with a Navigate function (as show in one example), or needs to be a done with a handler / schema.
I'm trying a basic POST to a PHP script. If the data1/data2 match the input, it's return json status:success, otherwise failure. I see in the devtools that the html body comes back with json success, but this code returns or nothing at all. I've tried too different ways to get the response data. I want to grab the JSON response for the C# code to review. Surely there should be an easy way to accomplish this? I want to send an HTTP request and then get the body (json) to parse. If this needs the schema/handler, I cannot find a full example of using this.
namespace BrowserTest
{
public partial class MainForm : Form
{
ChromiumWebBrowser browser = null;
public Loader()
{
browser = new ChromiumWebBrowser("http://localhost/test/"); // Initialize to this page
pBrowserLogin.Controls.Add(browser);
}
private void btnTest_Click(object sender, EventArgs e)
{
byte[] request = Encoding.ASCII.GetBytes("data1=" + txtData1.Text + "&data2=" + txtData2.Text);
PostTest.Navigate(browser, "http://localhost/test/posttest.php", request, "application/x-www-form-urlencoded");
}
}
public static class PostTest
{
public static void Navigate(this IWebBrowser browser, string url, byte[] postDataBytes, string contentType)
{
IFrame frame = browser.GetMainFrame();
IRequest request = frame.CreateRequest();
request.Url = url;
request.Method = "POST";
request.InitializePostData();
var element = request.PostData.CreatePostDataElement();
element.Bytes = postDataBytes;
request.PostData.AddElement(element);
NameValueCollection headers = new NameValueCollection();
headers.Add("Content-Type", contentType);
request.Headers = headers;
frame.LoadRequest(request);
frame.GetTextAsync().ContinueWith(taskHtml =>
{
var html = taskHtml.Result;
System.Windows.Forms.MessageBox.Show(html);
});
string script = string.Format("document.documentElement.outerHTML;");
frame.EvaluateScriptAsync(script).ContinueWith(x =>
{
var response = x.Result;
if (response.Success && response.Result != null)
{
var fullhtml = response.Result;
System.Windows.Forms.MessageBox.Show(fullhtml.ToString());
}
});
}
}
}
I have been stuck in trying figure out the syntax for a particular scenario.
Scenario: When I give a JSON string as argument in the URL, I want the url to consume an API and retrieve the details from that API, as per the given input.
My project needs deserialization into c# so, I used JSON.NET for the same.
Say: input is - Profile-id : 123456789
The output should consume details pertaining to that Pid and display.
The i/p given in url:
https://www.docscores.com/widget/api/org-profile/demo-health/npi/123456789
The expected o/p:
json string
What i have been doing is :
string url = "https://www.docscores.com/widget/api/org-profile/demo-health/npi/?profile-id=ShowProfile";
string data = GET(url);
dynamic jsonDe = JsonConvert.DeserializeObject(data);
var phyRatings = Convert.ToString(jsonDe.profile.averageRating);
Console.WriteLine(phyRatings);
public string ShowProfile(string pid)
{
}
public static string GET(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string data = reader.ReadToEnd();
reader.Close();
stream.Close();
return data;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return null;
}
So, when I pass profile-id as 123456789 in the url, I want the syntax to extract other info with this Profile-id
I AM totally confused with the syntax in C#. How can I pass the argument and write inside the ShowProfile function? I searched everywhere but not able to find the correct syntax.
Can someone please tell me if this is the right way to do it?
EDIT: Sounds like you have two questions here. First is how to pass your Profile-Id in the URL, and the second is how to deserialize the JSON result into a C# object. But let me know if I'm misunderstanding.
For passing 123456789 as your profile ID, you just need to concatenate it into the URL string. So you might have
public string ShowProfile(string pid)
{
ProfileInfo info = GET(pid);
// Do what you want with the info here.
}
public static ProfileInfo GET(int profileId)
{
try
// Note this ends in "=" now.
string basePath = "/widget/api/org-profile/demo-health/npi/?profile-id=";
string path = basePath + profileId.ToString();
//...
ProfileInfo would be your custom class to match the JSON structure.
Then to deserialize the result, in your GET() method, you might instead try calling the service using HttpClient from the Microsoft.AspNet.WebApi.Client NuGet package, and then read that directly into a C# object whose structure maps to the JSON response you get (see example below). Your GET() method could then return that object, and then it'd be trivial for the ShowProfile() method to read the properties you want from that C# object.
public static ProfileInfo GET(int profileId)
{
try
{
// Note this ends in "=" now.
string basePath = "/widget/api/org-profile/demo-health/npi/?profile-id=";
string path = basePath + profileId.ToString();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://www.docscores.com");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
ProfileInfo info = await response.Content.ReadAsAsync<ProfileInfo>();
return info;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return null;
}
More code and info at MSDN: Calling a Web API From a .NET Client in ASP.NET Web API 2 (C#)
Simply put, I'm trying to create a webpage with Visual Studio 2012 wherein the user will log into a page, which, when authorized, will post a tweet, and enable them to use the rest of the features on the page. I'd like to remember said users credentials to also limit the rate at which they use a certain feature.
The problem is, I have been searching for days and I am unable to find an UP TO DATE and working example for me to follow. Everything seems to be outdated. (Twitterizer ; TweetSharp) I've switched from Java to C# & .NET and still no progress.
I am now seeking direct help.. Code snippets .. Tutorials .. Anything .. So that I can accomplish this task. I'm new to .NET but used to Java & C/C++ so I don't expect to be confused by too trivial of code..
My exact request is to be able to log in with twitter, save credentials (or the user's access token, whatever) & post a tweet.
This is a basic example of how to authenticate and retrieve a user's timeline:
// You need to set your own keys and screen name
var oAuthConsumerKey = "superSecretKey";
var oAuthConsumerSecret = "superSecretSecret";
var oAuthUrl = "https://api.twitter.com/oauth2/token";
var screenname = "aScreenName";
// Do the Authenticate
var authHeaderFormat = "Basic {0}";
var authHeader = string.Format(authHeaderFormat,
Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +
Uri.EscapeDataString((oAuthConsumerSecret)))
));
var postBody = "grant_type=client_credentials";
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (Stream stream = authRequest.GetRequestStream())
{
byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
stream.Write(content, 0, content.Length);
}
authRequest.Headers.Add("Accept-Encoding", "gzip");
WebResponse authResponse = authRequest.GetResponse();
// deserialize into an object
TwitAuthenticateResponse twitAuthResponse;
using (authResponse)
{
using (var reader = new StreamReader(authResponse.GetResponseStream())) {
JavaScriptSerializer js = new JavaScriptSerializer();
var objectText = reader.ReadToEnd();
twitAuthResponse = JsonConvert.DeserializeObject<TwitAuthenticateResponse>(objectText);
}
}
// Do the timeline
var timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=1&exclude_replies=1&count=5";
var timelineUrl = string.Format(timelineFormat, screenname);
HttpWebRequest timeLineRequest = (HttpWebRequest)WebRequest.Create(timelineUrl);
var timelineHeaderFormat = "{0} {1}";
timeLineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token));
timeLineRequest.Method = "Get";
WebResponse timeLineResponse = timeLineRequest.GetResponse();
var timeLineJson = string.Empty;
using (timeLineResponse)
{
using (var reader = new StreamReader(timeLineResponse.GetResponseStream()))
{
timeLineJson = reader.ReadToEnd();
}
}
public class TwitAuthenticateResponse {
public string token_type { get; set; }
public string access_token { get; set; }
}
Please see here (The github project has asp.net and asp.net mvc examples):
Authenticate and request a user's timeline with Twitter API 1.1 oAuth
I created an an open source project for it but unfortunately it doesn't yet include the ability to send tweets. I don't think it would be difficult but I am short on time at the moment.
If I was to implement it I would find out exactly what needs to be posted by the api, as detailed here:
https://dev.twitter.com/docs/api/1.1/post/statuses/update
For the assisting of other persons who have fallen into the same gap I did... Check out this site
It will help with authenticating & signing in & retrieving basic information.
I have written some simple code for using my Twitter developer key and secret to read tweets from a public timeline. This is so I can display a user's latest tweets in their own website. The code is below.
I now wish to do something similar with their blog on Google's Blogger. I had assumed there would be a way to use my Google API key and secret to read the public content of a blog without the user needing to authenticate. I only need blog titles and dates so I can link through to the Blogger site. But I've spent 24 hours scouring the internet and cannot find any examples for getting an access token using just the key and secret.
Using the Google API SDK I have got as far as the code below but can't find a way to get the access token without getting the user to authenticate. Any advice appreciated - feel I'm banging my head against a wall! Happy to take any approach - I just want to get some Blogger content on a website I'm building...
Authenticate with Twitter:
var oAuthConsumerKey = _key;
var oAuthConsumerSecret = _secret;
var oAuthUrl = "https://api.twitter.com/oauth2/token";
// Do the Authenticate
var authHeaderFormat = "Basic {0}";
var authHeader = string.Format(authHeaderFormat,
Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +
Uri.EscapeDataString((oAuthConsumerSecret)))
));
var postBody = "grant_type=client_credentials";
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (Stream stream = authRequest.GetRequestStream())
{
byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
stream.Write(content, 0, content.Length);
}
authRequest.Headers.Add("Accept-Encoding", "gzip");
WebResponse authResponse = authRequest.GetResponse();
// deserialize into an object
string objectText;
using (authResponse)
{
using (var reader = new StreamReader(authResponse.GetResponseStream()))
{
objectText = reader.ReadToEnd();
}
}
// objectText is JSON and contains access_token
Authenticate with Blogger??
private bloggerTest()
{
// Register the authenticator.
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = _key,
ClientSecret = _secret
};
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
// Create the service.
var service = new BloggerService(new BaseClientService.Initializer()
{
Authenticator = auth
});
var result = service.Posts.List(_blogID).Fetch();
}
private IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
var state = new AuthorizationState(new[] { BloggerService.Scopes.BloggerReadonly.GetStringValue() });
// I am stuck here!
}
For accessing a public feed it is way simpler than what you are doing. There are a bunch of classes built into the .Net framework for processing RSS feeds, you can start with SyndicationFeed. To get the feed items (blog posts) is quite simple:
XDocument feed = XDocument.Load(rssUrl); //rssUrl is the URL to the rss page that (most) blogs publish
SyndicationFeed sf = SyndicationFeed.Load(feed.CreateReader());
foreach (SyndicationItem si in sf.Items)
{
..you've now got your feed item...
}
Note that this will give you the feed items but it won't give you the full web page that they appear in. (although you will get a URL for that).
How do you get the group id in Yammer?
I am able to post a message in all of the company as well as to a specific group but i am not able to get the group id of a particular group using Yammer APIs
Find below the code for posting in a particular group where group_id is a string variable whose value I enter manually and want to automate this process.
private void Post(string address)
{
System.Uri targetUri = new System.Uri(https://www.yammer.com/api/v1/messages.json?body=HelloTest&group_id=[some_number]&access_token=" + token);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
request.Method = "POST";
request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
}
// STEP4 STEP4 STEP4
private void ReadWebRequestCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);
string results;
using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
{
results = httpwebStreamReader.ReadToEnd();
//TextBlockResults.Text = results; //-- on another thread!
SkyDriveContent test = new SkyDriveContent();
test.Name = results;
str_results = results;
}
myResponse.Close();
}
I saw the documentation but did not find any way to get the list of groups a user is a part of?
Any help would be appreciated!
You should be able to get the list of groups that a user belongs to by making a GET request to https://www.yammer.com/api/v1/groups.json?mine=1. It looks like you are using HttpWebRequest for your client code. If you haven't done so I'd suggest checking out RestSharp as it'll cut down on the amount of code you have to write.