I pretend to integrate my website with facebook, whant to make a automatic post (on a specific facebook account) while a user interacts with a web application.
is there any way to make this operation like a webservice way?, authenticating and calling a url that posts the information i send directly on the facebook wall?
i'm using asp.net mvc3 C# i've found a facebook developer toolkit library, is this the correct way to start or what should i do?
What is necessary is only write a post automatically on a facebook account, for example when i write a new article (news) on my website, it will be automatically posted on fb.
any idea to get me started?
I did something kind of similar, when a user clicks on a "share" button on my mvc app, it posts something on his wall. The problem using the oauth dialog, is that it will redirect the browser to a facebook site for the user to log in and accept the application permissions.
On the "share" button, I linked it to this url:
<a href=""https://www.facebook.com/dialog/oauth?client_id=[YOUR_APP_ID]&redirect_uri=[THE_REDIRECT_PAGE]/&scope=publish_stream"">
<img src='#Url.Content("~/Images/facebook_share.png")' alt="Share on Facebook!" style="height:28px" />
</a>
YOUR_APP_ID is your facebook application ID.
THE_REDIRECT_PAGE is a public page on your site that facebook will automatically redirect once the user has logged in and accepted the permissions. When facebook redirects, it appends a querystring parameter called "code" to it.
NOTE: The redirect page MUST END with a "/", it cannot end with a document, or else it doesn't work!
Once the user has accepted your request, you must ask facebook another code, called access code, used to post on the user's wall.
This code is on the redirect page:
public ActionResult Index(string code)
{
string fbAuthCode = Request["code"]; //The authorization code.
string fbAppId = "XXXXXXX"; //Your fb application id.
string fbSecretAppId = "XXXXXXXXXXXXXXXXXXXXX"; //Your fb secret app id, it is found on the fb application configuration page.
string redirectUrl = string.Format("[THE_REDIRECT_PAGE]", locationPointId, entryLocationId); //The redirect url. THIS MUST BE THE EXACT SAME REDIRECT URL USED ON THE JAVASCRIPT LINK!
string fbUrl = "https://graph.facebook.com/oauth/access_token?client_id=" + fbAppId + "&redirect_uri=" + redirectUrl + "&client_secret=" + fbSecretAppId + "&code=" + fbAuthCode; //Url used to post.
string accessToken = string.Empty;
try
{
WebClient client = new WebClient();
using (Stream stream = client.OpenRead(fbUrl))
using (StreamReader reader = new StreamReader(stream))
{
accessToken = reader.ReadToEnd().Split('&')[0].Replace("access_token=", string.Empty);
reader.Close();
}
}
catch (Exception ex)
{
throw new Exception("An error ocurred while trying to get the fb token in " + fbUrl, ex);
}
Once you have the access token, you can post to the user wall:
string postUrl = "https://graph.facebook.com/me/feed";
string postParameters;
postParameters = string.Format("message={0}&picture={1}&name={2}&caption={2}&description={3}&link={4}&access_token={5}",
"[Message]",
"[PictureUrl]",
"[Name]",
"[Caption]",
"[Link]",
accessToken);
try
{
System.Net.WebRequest req = System.Net.WebRequest.Create(postUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postParameters);
req.ContentLength = bytes.Length;
using (System.IO.Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length); //Push it out there
os.Close();
using (WebResponse resp = req.GetResponse())
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
ViewBag.PostResult = sr.ReadToEnd().Trim();
sr.Close();
}
os.Close();
}
}
catch (Exception ex)
{
throw new Exception("An error ocurred while posting data to the user's wall: " + postUrl + "?" + postParameters, ex);
}
return RedirectToAction(XXXXXXXXXXXxx....); //Then i redirect to another page.
You can see that on the exception I throw the posted url (for debugging purposes).
With that url you can usually go to the facebook Graph API Explorer or the Linter and check the real error.
I don't know if this is exactly what you want but hope it gives you a kickoff...
I've struggled a few days with this, because facebook documentation on open graph is not very good yet, at least for us that don't use curl :)
https://developers.facebook.com/docs/opengraph/tutorial/
https://developers.facebook.com/docs/opengraph/
Hope it helps.
MT.
It's easy:
Step 1:
Get a valid facebook token by requesting "*https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope="publish_stream,email*" (full list of permissions there: https://developers.facebook.com/docs/reference/api/user/)
Step 2:
Post your message to the user wall:
curl -F 'access_token=...' \
-F 'message=your message' \
https://graph.facebook.com/ID_OR_USERNAME/feed
Related
I'm trying to create an application that allows users to create preferred playlists on spotify. I am using the spotify web api and building an asp.net mvc application (c#). I am trying to make the web request to have users login to their spotify account, but for some reason my app does not redirect to the login page whenever I try to get the response.
I have tried creating a redirect link myself, but shouldn't the GetResponse() method invoke the redirect itself? I am new at this so I may be wrong but any help would be appreciated.
public IActionResult GetLogin()
{
string spotifyURL = "https://accounts.spotify.com/authorize/";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(spotifyURL);
webRequest.Method = "GET";
webRequest.Headers["client_id"] = clientID;
webRequest.Headers["response_type"] = "code";
webRequest.Headers["redirect_uri"] = "https://localhost:44383/home/login";
string json = "";
using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader rdr = new StreamReader(stream, Encoding.UTF8))
{
//should get back a string i can then turn to json and parse for accesstoken
json = rdr.ReadToEnd();
rdr.Close();
}
}
}
bool authorized = true;
if (authorized)
{
return View("Callback");// token.access_token;
}
else
{
return View("Home");
}
}
As I understand you are trying to authentificate on spotify.
I can tell you you have a few mistakes you are using a GET method tho authentificate
- The service waits a POST from you in JSON with account data like login and password, if the login and password and format will be correct it return you a JSON with access token.
How to add a Header format: Headers.Add(HttpRequestHeader.ContentType = "application/json");
After this the server will understand what content you actually sending to it.
A little about the last parts of code:
bool authorized = true;
if (authorized)
{
return View("Callback");// token.access_token;
}
else
{
return View("Home");
}
You returning like a blank Views here it is better to use
return RedirectToAction("ActionName", "CpntrollerName", new { "Here you can pass any value" });
This will allow you to redirect to another Controller and View and pass a value to it.
Summary is:
I could write a long time but better to tell the real problem you should read more on how to use API in C# applications.
Here I will provide you some links on MS documentations:
The WebRequest method: link
The HttpClient method: link
About HttpClient I recommend to use it only on desktop or mobile apps because it inherits from .NET Framework and not from .NET Core so it may cause an errors, but I didn't do a test on my ASP.NET Core applications so can't say for sure.
Little tips:
Use Newtonsoft.Json it will help you to serialize your JSON request and deserialize answer it is much easier then do it with your hands or Regex.
Use async and Task when making requests to the web, because answer can be long waited, and you don't want your app stay frozen until it waits an answer.
I'm trying to display a list of events from an Outlook calendar using the example request microsoft have here
However, I've no proper experience with using any sort of REST APIs before. Using the URL they provide I should be getting something back but I'm not. Here is the code in my controller:
string uri = "https://outlook.office365.com/api/v1.0/me/events";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "GET";
string result = "";
try
{
WebClient webClient = new WebClient();
webClient.Encoding = Encoding.UTF8;
result = webClient.DownloadString(uri);
try
{
string returnedString = result;
TempData.Add("myval", result);
ViewBag.result = "returned string " + result;
}
catch (Exception er2)
{
ViewBag.error = er2.Message;
}
ViewBag.secondresult = "first result " + result;
}
catch (Exception er)
{
}
ViewBag.firstResult = "Outside try catch " + result;
ViewBag.url = uri;
return View();
Then in my view I'm calling the ViewBags like this:
<p> here </p>
#ViewBag.url
#ViewBag.firstResult
#ViewBag.result
#ViewBag.error
#ViewBag.secondresult
<p> end </p>
But besides my here and end I get nothing. This is a project that was set up without any input from myself so I'm having to do everything across a network which is why I'm using so many try catches.
Can someone with more experience with using REST APIs tell me if I'm messing something up somewhere?
I don't see any authentication in your code, so it's likely returning a 401. You need to use OAuth2 to get an access token and use that to authenticate your calls. Since you're doing this in C#, you might want to look at the API wrappers on NuGet that implement a lot of this for you. There are some sample starter apps on http://dev.office.com/code-samples that might be helpful too (search for ASP.NET MVC).
UPDATE: I figured it out and posted the answer below.
All I'm trying to do is update any file attribute. Description, name, anything, but no matter how I format it I get a 403.
I need to be able to modify a file so it can be shared via the Box API from a cloud app. I'm updating someone else's code from V1, but they are no longer available... I've tried many things but mostly just get 403 Forbidden errors.
There are no issues with OAuth2, that works fine and I can list files and folders, but can not modify them. This question is about sharing, but I can't change a description either. The box account is mine and I authenticate with my admin credentials. Any suggestions would be appreciated.
Here is the method I am using. I pass in the fileId and token and I've left out try/catch etc. for brevity.
string uri = string.Format("https://api.box.com/2.0/files/{0}", fileId);
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.Headers.Add("Authorization: Bearer " + token);
var response = client.UploadData(uri, postArray);
var responseString = Encoding.Default.GetString(response);
}
Thanks.
Okay, My Homer Simpson moment...
UploadData is a POST, I needed to do a PUT. Here is the solution.
string uri = String.Format(UriFiles, fileId);
string response = string.Empty;
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
try
{
using (var client = new WebClient())
{
client.Headers.Add("Authorization: Bearer " + token);
client.Headers.Add("Content-Type", "application/json");
response = client.UploadString(uri, "PUT", body);
}
}
catch (Exception ex)
{
return null;
}
return response;
try changing your content type to 'multipart/form-data'?
I just looked up the api at: https://developers.box.com/docs/#files-upload-a-file
and it looks like the server is expecting a multipart post
here is stack overflow post on posting multipart data:
ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient
I'm trying to get list of torrents from uTorrent using Web API. Getting required token goes O.K.:
WebClient client = new WebClient() { Credentials = new NetworkCredential(UserName, pass) };
StreamReader Reader = new StreamReader(client.OpenRead("http://localhost:" + port + "/gui/token.html"));
string token = Reader.ReadToEnd();
token = token.Split('>')[2].Split('<')[0];
// token is now something like 3LemfrO_-A-SNBXlnQ2QcQWTYydx7qOqKb1W1S54JJW74Ly3EYGgu0xQSU4AAAAA
But when I try to use it to get list of torrents:
Reader = new StreamReader(client.OpenRead("http://localhost:" + port + "/gui/?list=1&token=" + token));
all I get is "Error 400 Bad request".
I've tried to get token manually. In browser page "http://localhost:30303/gui/?list=1&token=3LemfrO_-A-SNBXlnQ2QcQWTYydx7qOqKb1W1S54JJW74Ly3EYGgu0xQSU4AAAAA" opens as it should, but in C# with the same link without any variables I still get error 400.
The interesting part is that if switch off token authentication WebClient load page perfectly with and without
"&token=3LemfrO_-A-SNBXlnQ2QcQWTYydx7qOqKb1W1S54JJW74Ly3EYGgu0xQSU4AAAAA"
but token auth enabled by default, so my and any app should use it.
And yes, WebRequest/HttpWebRequest didn't help also.
P.S. sorry for my English, I was never able to make it work right
you have to save the cookie from the request
Classes.CookieAwareWebClient client = new Classes.CookieAwareWebClient() { Credentials = new NetworkCredential("shehab", "shehab") };
StreamReader Reader = new StreamReader(client.OpenRead("http://localhost:" + "8080" + "/gui/token.html"));
string token = HtmlRemoval.StripTagsRegexCompiled(Reader.ReadToEnd());
MessageBox.Show(token);
Reader = new StreamReader(client.OpenRead("http://localhost:" + "8080" + "/gui/?list=1&token=" + token));
MessageBox.Show(Reader.ReadToEnd());
and for the cookie aware class go to the following link(Using CookieContainer with WebClient class) as web client doesn't support cookies.
You should save cookies from request
WebRequest request = WebRequest.Create("http://localhost:" + port + "/gui/token.html");
CookieContainer cookies = new CookieContainer();
(request as HttpWebRequest).CookieContainer = cookies;
And then use it in every other request to uTorrent when using the same token:
request = WebRequest.Create("http://localhost:" + port + "/gui/?list=1&token=" + token);
(request as HttpWebRequest).CookieContainer = cookies;
I have a simple 3-step suggestion:
When you use your browser with the token, use Fiddler2 to analyze the HTTP traffic between the server and browser.
Open up your C# app and use Fiddler2 to analyze the HTTP traffic between the server and your app.
Compare the HTTP requests and responses for the browser with the requests and responses for the C# app. If you see a significant difference, there is a good chance that could be the problem.
Bounty Question
I am using c# 3.5 Window Forms Application. I am using the code mentioned in the accepted answer. and I am getting below error
The remote server returned an error: (401) Unauthorized.
Sample code to verify the UserName and Password will be really appreciated
Bounty Question Ends
I have an application with the following use-case: when the user first starts using the application, he inputs his username and password. Then, at a much later stage, the application may update his status.
Currently I'm using Twitterizer, but I believe the question is beyond the scope of the specific library I'm using. Following are the two relevant lines of code:
Twitter twitter = new Twitter("username", "password", "source");
twitter.Status.Update("update");
The construction of the Twitter object does not throw an exception if the username/password are incorrect. This is probably because nothing is sent at this point. On the other hand, the status update does throw an exception if the username/password are invalid.
My problem is that I want to validate the username/password at the point of user input, not when trying to post the update.
How can I validate the username/password without posting anything (in Twitterizer or otherwise)?
Taking a quick look at the verify_credentials API as mentioned by peSHIr, I wrote a little routine which seems to do the trick. It's late, but I was able to test it a couple of times and seems to work.
In my function, I am just returning true if I I get an HttpResponseCode.OK, and false if I get anything else or an exception is thrown. If twitter does not like the uid/password an exception will be thrown with a 401 error (not authorized.)
public bool CheckTwitterCredentials(string UserName, string Password)
{
// Assume failure
bool Result = false;
// A try except block to handle any exceptions
try {
// Encode the user name with password
string UserPass = Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes(UserName + ":" + Password));
// Create our HTTP web request object
HttpWebRequest Request =
(HttpWebRequest)WebRequest.Create("http://twitter.com/account/verify_credentials.xml");
// Set up our request flags and submit type
Request.Method = "GET";
Request.ContentType = "application/x-www-form-urlencoded";
// Add the authorization header with the encoded user name and password
Request.Headers.Add("Authorization", "Basic " + UserPass);
// Use an HttpWebResponse object to handle the response from Twitter
HttpWebResponse WebResponse = (HttpWebResponse)Request.GetResponse();
// Success if we get an OK response
Result = WebResponse.StatusCode == HttpStatusCode.OK;
} catch (Exception Ex) {
System.Diagnostics.Debug.WriteLine("Error: " + Ex.Message);
}
// Return success/failure
return Result;
}
You could try to use the API call account/verify_credentials. Hopefully the API library you use already supports this.. Twitter is notorious now for really hating third party programmers, so unless you have good reason to do something with Twitter, just stay away...
I have used other Twitter Libraries but none of them support checking the username and password for validitity. This might be because Twitter API does not have the facility to validate the username and password unless we try to do something which requires authentication.
One thing you can do is try to get friend list or any other methods that requires authentication.
Twitter API hasn't supported username/password in years. Instead, you have OAuth, which lets the user authorize your application to act on their behalf. Twitter has an account/verify_credentials endpoint you can use to verify whether the user who's tokens you have still authorizes your app. Here's an example of how you could call this endpoint with LINQ to Twitter:
var accounts =
from acct in twitterCtx.Account
where acct.Type == AccountType.VerifyCredentials
select acct;
You can visit Account/VerifyCredentials documentation for more details:
as #joe-mayo informed, you have to switch to OAuth. twitter expired v1 of their API and they documented that in following url https://dev.twitter.com/docs/faq#17750.
Here's a function i wrote that will verify twitter username and password in C# :
public bool isTwitterValid(string username, string password)
{
try
{
string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://twitter.com/statuses/verify.xml");
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
request.Headers.Add("Authorization", "Basic " + user);
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
reader.Close();
}
catch (Exception ex)
{
if (ex.Message.Contains("404")) { return true; }
}
return false;
}