Facebook - posting with facebook dialog - c#

I manage get access token from FB.
I can post on wall. But I need to display popup window (dialog?) to allow user add comment and see what he posting (sharing).
Im confused with Open graph which I believe I use and graph API. Is the same thing?
Bellow is my code:
private string CheckAuthorization()
{
string app_id = "xxxxxxxxxxxxxxxx";
string app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string scope = "publish_stream,email,user_location,user_birthday";
if (Request["code"] == null)
{
Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
return tokens["access_token"];
}
}
Above code working fine Im getting access token (login popup when Im not logged and popup with information about what info will be shared).
Then I post on FB wall:
var client = new FacebookClient(access_token);
client.Post("/me/feed", new { message = "some text to post" });
My question is how to get popup window before post with description what Im posting and option to add user own comment.

Related

Send post to Facebook page

I have a c# asp.net web application.
I am using the facebook login through their javascript sdk and it does the login.
Now I have a Simple WYSIWYG Editor in which whatever is added should be posted on the facebook page of that logged in user.
Following is the code:
string FacebookApiId = "952214336368241";
string FacebookApiSecret = "fb2213d66523c8cb0bc99306f46ee457";
string accessToken = GetAccessToken(FacebookApiId, FacebookApiSecret);
PostMessage(accessToken, "My message");
private string GetAccessToken(string apiId, string apiSecret)
{
string AuthenticationUrlFormat = "https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials&scope=manage_pages,offline_access,publish_stream";
string accessToken = string.Empty;
string url = string.Format(AuthenticationUrlFormat, apiId, apiSecret);
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
String responseString = reader.ReadToEnd(); // this gives me {"access_token":"952214336368241|McqSGYIMU1eYBZ1zGydWj9hu6Bt","token_type":"bearer"}
NameValueCollection query = HttpUtility.ParseQueryString(responseString);
accessToken = query["access_token"]; // This line throws error
}
//if (accessToken.Trim().Length == 0)
//throw new Exception("There is no Access Token");
return "952214336368241|McqSGYIMU1eYBZ1zGydWj9hu6B"; // hard-coded to get it working;
}
private void PostMessage(string accessToken, string v)
{
try
{
FacebookClient facebookClient = new FacebookClient(accessToken);
dynamic messagePost = new ExpandoObject();
messagePost.access_token = accessToken;
messagePost.message = v;
var result = facebookClient.Post("/[user id]/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
//handle something
}
catch (Exception ex)
{
//handle something else
}
}
This throws error:
{"(OAuthException - #803) (#803) Some of the aliases you requested do not exist: [user id]"}
I even wrote my facebook emailid instead of [user id] but it still does not work and gives me error:
Message: "(OAuthException - #2500) An active access token must be used to query information about the current user."
Can anyone please advise how can I remove this error.
The code is VERY old, offline_access and publish_stream do not exist anymore since many years.
You have to use a Page Token with the publish_pages permission in order to post to your Page with the API.
You can use "me/feed" or "page-id/feed", but not an Email.
Information about Tokens and how to generate them:
https://developers.facebook.com/docs/facebook-login/access-tokens/
https://www.devils-heaven.com/facebook-access-tokens/
Try stuff in the API Explorer before programming: https://developers.facebook.com/tools/explorer/

Trying to build a Twitter Thread programmatically

I've built a Twitter application that works in C#. It's a WPF or Windows-like application that makes a web request to the Twitter API endpoint. Now, I have a business case to create a Twitter thread when it's sending a series of 280-character tweets. Because of all the business rules we have, there's no way I can use an existing Twitter app on the market.
The issue is that I'm always getting a 401 unauthorized whenever I try to send a tweet with the in_reply_to_status_id_str. In fact it does this whenever I try to add ANY OPTIONAL PARAMETERS besides the required STATUS parameter. I'm using OAuth 1.0A.
I'm trying to create a series of Tweets that will display Show This Thread at the bottom and can be viewed together.
The method I've provided would be called in a loop for each 280-character segment.
NOTE: I NOW HAVE THIS WORKING. I REALIZED YOU HAVE TO ORDER THE PARAMETERS BEFORE SIGNING THEM
public async Task<string> TwitterWebRequest(string status, string resource_url, string authHeader, int counter)
{
string id = "";
using (var request = new HttpRequestMessage(HttpMethod.Post, resource_url))
{
request.Headers.TryAddWithoutValidation("Authorization", authHeader);
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var data = new Dictionary<string, string>();
if (counter == 0)
{
data = new Dictionary<string, string>
{
["status"] = status
};
}
else
{
data = new Dictionary<string, string>
{
["in_reply_to_status_id"] = "1169662308278292480",
["status"] = status
};
}
request.Content = new FormUrlEncodedContent(data);
using (HttpResponseMessage response = await client.Value.SendAsync(request))
{
JavaScriptSerializer json = new JavaScriptSerializer();
string responseStream = await response.Content.ReadAsStringAsync();
Dictionary<string, object> jsonObj = json.DeserializeObject(responseStream) as Dictionary<string, object>;
if (counter == 0) { id = jsonObj["id_str"].ToString(); }
if (response.StatusCode == HttpStatusCode.OK) {
return "OK";
}
else { return ""; }
}
}
This is what I'm doing so far for the signature:
This is what I did to make it work. I had to put the parameters in order. This is a requirement for OAuth, otherwise you'll get a 401 Unauthorized.
private static string CreateBaseString(string oauth_nonce, string oauth_timestamp, string status)
{
string baseFormat = "in_reply_to_status_id=1169662308278292480&oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}"
+ "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}";
string baseString = String.Format(baseFormat, oauth.OAuth_Consumer_Key, oauth_nonce, oauth.OAuth_Signature_Method,
oauth_timestamp, oauth.OAuth_Token, oauth.OAuth_Version, EncodingUtils.UrlEncode(status));
return String.Concat("POST&", EncodingUtils.UrlEncode(oauth.Resource_Url), "&", EncodingUtils.UrlEncode(baseString));
}

How to authorize the application in facebook

I am developing an asp.net website and I want to post to facebook from my website so I created an application in facebook and I used below code but wher I run my website I get error
code :
private void Authorization()
{
string AppId = "1138658742823914";
string AppSecret = "87471caa78f52e3919e43c3dc72b542a";
string scope = "‎public_profile‎,user_friends";
if (Request["code"]==null)
{
Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect uri={1}&scope={2}",AppId,Request.Url.AbsoluteUri,scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client id={0}&redirect uri={1}&scope={2}&code={3}&client_secret={4}",AppId,Request.Url.AbsoluteUri,scope,Request["code"].ToString(),AppSecret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response=request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
// meh.aspx?token1=steve&token2=jack&....
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("/me/feed",new { message="Atefeh Ahmadi Hello every One"});
}
error :
Facebook.FacebookOAuthException: (OAuthException - #200) (#200) The user hasn't authorized the application to perform this action
See Picture
It looks like you have not configured your app properly in facebook or you have not mentioned your website url correctly while creating an app on facebook.

Fetch Facebook user profile details with profile picture and Logout properties using Facebook C# SDK

i want to fetch user details with profile picture using Facebook c# SDK.I have done some coding and able to login using Facebook in my app.I am explaining my code below.
immediateHelp.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Params["code"] != null)
{
//Facebook.FacebookAPI api = new Facebook.FacebookAPI();
FacebookClient client = new Facebook.FacebookClient(GetAccessToken());
object me = client.Get("/me");
lblTextImage.ImageUrl="need picture here" ;
lblTextEmail.Text="need email here";
// JSONObject meFriends = client.Get("/me/friends");
}
}
}
private string GetAccessToken()
{
if (HttpRuntime.Cache["access_token"] == null)
{
Dictionary<string, string> args = GetOauthTokens(Request.Params["code"]);
HttpRuntime.Cache.Insert("access_token", args["access_token"], null, DateTime.Now.AddMinutes(Convert.ToDouble(args["expires"])), TimeSpan.Zero);
}
return HttpRuntime.Cache["access_token"].ToString();
}
private Dictionary<string, string> GetOauthTokens(string code)
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string clientId = "*************";
string redirectUrl = "http://localhost:3440/immediateHelp.aspx";
string clientSecret = "************************";
string scope = "user_photos,email";
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&scope={4}",
clientId, redirectUrl, clientSecret, code, scope);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string retVal = reader.ReadToEnd();
foreach (string token in retVal.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
return tokens;
}
I need to attach image in image field and email in text Box after login.I need also logout properties with destroy session using Facebook c# SDK.Please help me to resolve this.
The following code will help you get email and profile picture. The code client.Get("/me?fields=picture")) return picture in format of Json so that we need to extract the url as the code show :
FacebookClient client = new FacebookClient(access_token);
dynamic myInfo = fb.Get("/me?fields=email");
var picture = (((JsonObject)(JsonObject)client.Get("/me?fields=picture"))["picture"]);
var url = (string)(((JsonObject)(((JsonObject)picture)["data"]))["url"]);
lblTextImage.ImageUrl=url;
lblTextEmail.Text=myInfo.email;
Hop this work for you.

C# facebook SDK dont work

I have a website write (.net 4) and i am tring to create some facebook login.
After i download Facebook sdk for c#, i am tring to get user info using the access token.
It seems to me that i am doing something wrong, all the examples i examined, were little bit diffrent from mine. instead of getting me paramethers by :
me["id"] // mine
me.id // examples
when i try to get values like the examples i got errors.
also i am having problem with get the email address of user, already add email to scope:
This method responsible for get the access token:
public string GetAccessToken()
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
strAppId, Request.Url.AbsoluteUri, strScope, Request["code"].ToString(), strAppSecret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
return access_token;
}
This method responsible for get user information:
public string GetUserInfo(string strToken)
{
var client = new FacebookClient(strToken);
dynamic me = client.Get("me");
User user = new User();
try
{
string user_id = me["id"];
string user_first_name = me["first_name"];
string user_last_name = me["last_name"];
string user_name = me["username"];
string user_location = me["location"]["name"];
string user_city = me["hometown"]["name"];
//user_mail = me.email; }
catch(Exception ex)
{
}
return string.Empty;
}
when try to run on me.email or me["email"] i get this error:
'me.email' threw an exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' dynamic {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException}
I suggest you to use Microsoft.AspNet.Mvc.Facebook. It's easy to use and has all these properties already done.
http://www.asp.net/mvc/tutorials/mvc-4/aspnet-mvc-facebook-birthday-app

Categories

Resources