Get firstname, lastname and email address from Facebook using ASP.NET - c#

I have the below code in my Startup.Auth.cs file but I can't find a way to get the firstname and lastname from Facebook:
var facebookOptions = new FacebookAuthenticationOptions()
{
AppId = "",
AppSecret = "",
BackchannelHttpHandler = new FacebookBackChannelHandler(),
UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,email"
};
facebookOptions.Scope.Add("email");
facebookOptions.Scope.Add("public_profile");
app.UseFacebookAuthentication(facebookOptions);

Here is a quick example of how you can get the user information from Facebook in asp.net winforms. This example uses the Facebook SDK for .Net.
This snippet logs in the user with Facebook and then gets the extra user info, but can also be used for just getting the extra profile data.
static string Facebook_Key = "yourAppID";
static string Facebook_Secret = "yourAppSecret";
protected void Page_Load(object sender, EventArgs e)
{
//check if the user is returning from Facebook
if (Request.QueryString["code"] != null)
{
FacebookClient fbc = new FacebookClient();
//retreive the access token
dynamic result = fbc.Post("oauth/access_token", new
{
client_id = Facebook_Key,
client_secret = Facebook_Secret,
redirect_uri = Request.Url.AbsoluteUri,
code = Request.QueryString["code"].ToString()
});
fbc.AccessToken = result.access_token;
//get the extra profile data
dynamic user = fbc.Get("me?fields=first_name,last_name,id,email");
//display the results
FacebookLoginLabel.Text += user.id + "<br>";
FacebookLoginLabel.Text += user.first_name + "<br>";
FacebookLoginLabel.Text += user.last_name + "<br>";
FacebookLoginLabel.Text += user.email + "<br>";
//start the actual aspnet registration or login
LoginOrRegisterUser();
}
}
protected void FacebookLoginButton_Click(object sender, EventArgs e)
{
FacebookClient fbc = new FacebookClient();
//start the Facebook login request
var loginUrl = fbc.GetLoginUrl(new
{
client_id = Facebook_Key,
redirect_uri = Request.Url.AbsoluteUri,
response_type = "code",
scope = "email"
});
//redirect the user to Facebook for authentication
Response.Redirect(loginUrl.AbsoluteUri);
}
ASPX
<asp:Button ID="FacebookLoginButton" runat="server" Text="Log in with Facebook" OnClick="FacebookLoginButton_Click" />
<asp:Label ID="FacebookLoginLabel" runat="server" Text=""></asp:Label>

Related

Twitter Integration In windows Phone 7

I want to get the user information from the twitter and show in windows phone 7. I found some examples for twitter integration.
Link 1
Link 2
But in this examples i can only login to the twitter. I can not post or can not get the user information. Can any one provide a sample application or links for windows phone 7 twitter integration.
After getting login i try like this:
private void btntest_Click(object sender, RoutedEventArgs e)
{
string newURL = string.Format("https://api.twitter.com/1.1/users/show.json?screen_name={0}", userScreenName);
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webBrowser_Navigated);
webClient.DownloadStringAsync(new Uri(newURL));
}
void webBrowser_Navigated(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
Console.WriteLine("Error ");
return;
}
Console.WriteLine("Result==> " + e.Result);
//List<Tweet> tweets = JsonConvert.DeserializeObject<List<Tweet>>(e.Result);
//this.lbTweets.ItemsSource = tweets;
}
But here i can not get the user information. Please help me to get the user infoemation.
Thanks in advance.
Did you try using the Tweetinvi API from Codeplex, where you could grab the user details as well you could post tweets.
Tweetinvi a friendly Twitter C# API
Have a look at this one too:
Windows Phone 8 - Twitter API
Finally i found the Solution..!!! :-)
public void GetTwitterDetail(string _userScreenName)
{
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
};
var restClient = new RestClient
{
Authority = "https://api.twitter.com/1.1",
HasElevatedPermissions = true
};
var restRequest = new RestRequest
{
Credentials = credentials,
Path = string.Format("/users/show.json?screen_name={0}&include_entities=true", _userScreenName),
Method = WebMethod.Get
};
restClient.BeginRequest(restRequest, new RestCallback(test));
}
private void test(RestRequest request, RestResponse response, object obj)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
Console.WriteLine("Content==> " + response.Content.ToString());
Console.WriteLine("StatusCode==> " + response.StatusCode);
});
}
Now i got the User's In formations..!!! 5 days struggling comes to end..!! Thanks to all..!!

getting security warning in facebook authentication

I am getting security warning while using authentication in facebook app.My code is as shown with screenShot with security warning
private void imageFacebook_Tap(object sender, GestureEventArgs e)
{
FaceBookBlocker.Visibility = Visibility.Visible;
pop_up.IsOpen = true;
//Get this from the facebook
string appId = "My Facebook App Id";
var parameters = new Dictionary<string, object>();
parameters["client_id"] = appId;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
string extendedPermissions = "user_about_me,read_stream,publish_stream";
// add the 'scope' only if we have extendedPermissions.
if (!string.IsNullOrEmpty(extendedPermissions))
{
// A comma-delimited list of permissions
parameters["scope"] = extendedPermissions;
}
var oauth = new FacebookOAuthClient();
//Create the login url
var loginUrl = oauth.GetLoginUrl(parameters);
////Open the facebook login page into the browser
_webBrowser.Navigate(loginUrl);
}
I do have resolved.Check my answer here. Escape from Facebook security Warning
Also replace http: with https: in the Facebook GraphAPI.
There is going to be your code,where you connect to Facebook.Best guess would be Facebook has rolled out a security change to their API and the code being used by you has not been updated to work with the new API
Alternatively
You need to delete this bit of code
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "// connect . facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
Looks like it is in your footer?
I just hide BrowserControl if navigating to the success page
private void BrowserControl_Navigating(object sender, NavigatingEventArgs e)
{
if (e.Uri.AbsolutePath.ToString() == "/connect/login_success.html")
{
BrowserControl.Visibility = Visibility.Collapsed;
}
if (NavigatingCallback != null)
{
NavigatingCallback();
}
}

How to update status on twitter using C# and LINQ to Twitter library

I am writing an Metrol Style App to update status on my Twitter. I use LINQ to Twitter library. But I don't understand why my app throws exception 401 Unauthorized. Here is my code:
private void UpdateStatus()
{
// configure the OAuth object
var auth = new SingleUserAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = "ConsumerKey",
ConsumerSecret = "ConsumerSecret",
OAuthToken = "TwitterAccessToken",
AccessToken = "TwitterAccessTokenSecret"
}
};
using (var twitterCtx = new TwitterContext(auth, "https://api.twitter.com/1/", "https://search.twitter.com/"))
{
var tweet = twitterCtx.UpdateStatus("Hi everybody!"); // error here
viewTextBlock.Text = String.Empty;
viewTextBlock.Text = viewTextBlock.Text + "Status returned: " +
"(" + tweet.StatusID + ")" +
tweet.User.Name + ", " +
tweet.Text + "\n";
}
}
I just posted a blog entry on using OAuth in Windows 8 with LINQ to Twitter:
http://geekswithblogs.net/WinAZ/archive/2012/07/02/using-linq-to-twitter-oauth-with-windows-8.aspx
I also included a 401 FAQ in the LINQ to Twitter docs here:
http://linqtotwitter.codeplex.com/wikipage?title=LINQ%20to%20Twitter%20FAQ&referringTitle=Documentation
You can implement it using the Twitterizer assembly.
Firstly you can create a token which can be used to access Twitter and then using that particular token you can update TwitterStatus (Twitterizer.Core.TwitterObject.TwitterStatus).
Sample code is as follows.
public void CreateCachedAccessToken(string requestToken)
{
string ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"];
string ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"];
OAuthTokenResponse responseToken = OAuthUtility.GetAccessToken(ConsumerKey, ConsumerSecret, requestToken);
//Cache the UserId
Session["GetCachedUserId"] = responseToken.UserId;
OAuthTokens accessToken = new OAuthTokens();
accessToken.AccessToken = responseToken.Token;
accessToken.AccessTokenSecret = responseToken.TokenSecret;
accessToken.ConsumerKey = ConsumerKey;
accessToken.ConsumerSecret = ConsumerSecret;
Session["AccessToken"] = accessToken;
}
To update the TwitterStatus you can do as follows.
public OAuthTokens GetCachedAccessToken()
{
if (Session["AccessToken"] != null)
{
return (OAuthTokens)(Session["AccessToken"]);
}
else
{
return null;
}
}
TwitterStatus.Update(GetCachedAccessToken(), txtTweet.Trim());
The below mentioned method can be used to implement sign in.
protected string GetTwitterAuthorizationUrl()
{
string ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"];
string ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"];
OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(ConsumerKey, ConsumerSecret);
return "https://twitter.com/oauth/authorize?oauth_token=" + reqToken.Token;
}
Hope this helps.
If there are any clarifications please raise. Thanks

how to update twitter status from my asp.net web page

I have created an asp.net web page and I am using twitterizer.framework.dll.
Below is my c# code.
protected void btnTwitt_Click(object sender, EventArgs e)
{
//OAuthTokens tokens = new OAuthTokens();
//tokens.AccessToken = "--REDACTED--";
//tokens.AccessTokenSecret = "--REDACTED--";
//tokens.ConsumerKey = "--REDACTED--";
//tokens.ConsumerSecret = "--REDACTED--";
/////
//TwitterResponse<TwitterUser> showUserResponse = TwitterUser.Show(tokens, "twit_er_izer");
string TwitterUserName = "My twitter username";
string TwitterPassword = "my password";
// string TwitterMessage = txtShout.Text;
if (TwitterUserName != string.Empty && TwitterPassword != string.Empty)
{
try
{
//Twitter
// TwitterAccount twitter = new TwitterAccount(TwitterUserName, TwitterPassword);
//Twitter tw
Twitter twitter = new Twitter(TwitterUserName, TwitterPassword);
string TwitterMsg = txtShout.Text;
if (txtShout.Text.Length > 120)
{
TwitterMsg = TwitterMsg.Substring(0, 130) + "... For more update logon to DailyFreeCode.com";
}
else
{
TwitterMsg = TwitterMsg + "... For more update logon to DailyFreeCode.com";
}
twitter.Status.Update(TwitterMsg);
//Twitterizer.TwitterStatus.Update(tokens,TwitterMsg);
lblTwitMsg.Text = "Your have shout successfully on http://twitter.com/" + TwitterUserName;
}
catch (Exception ex)
{
Response.Write("<b>" + ex.Message + "</b><br>" + ex.StackTrace);
}
}
}
Now, I am getting error authorization failed.
On this line
twitter.Status.Update(TwitterMsg);
Plz help me, thanks!
It appears as though you're using Twitterizer version 1.x, but trying to copy code examples from Twitterizer version 2.x. Twitter twitter = new Twitter(TwitterUserName, TwitterPassword); is a dead giveaway. 2.x no longer uses that syntax.
Twitter no longer allows access to the API by supplying username and password. The tokens ARE your username and password, in a manner of speaking.
If you use the twitterizer framework you shouldn't be passing the username/password. You need to fill:
OAuthTokens tokens = new OAuthTokens();
tokens.AccessToken = "XXX";
tokens.AccessTokenSecret = "XXX";
tokens.ConsumerKey = "XXX";
tokens.ConsumerSecret = "XXX";
you can do this by using the following three methods from the framework:
1:
public static Uri BuildAuthorizationUri(
string requestToken
)
2:
public static OAuthTokenResponse GetRequestToken(
string consumerKey,
string consumerSecret,
string callbackAddress
)
3:
OAuthTokenResponse accessToken = OAuthUtility.GetAccessToken(consumerKey, consumerSecret, requestToken, verifier);
look it up here

Facebook login MVC 5

I have to do a log in button in MVC, i searched for alot of tutorials on how to do and i found one i think is good but everytime i run de program i keep getting an exception
`public ActionResult FacebookCallBack(string code)
{
var fb = new FacebookClient();
dynamic result = fb.Post("oauth/acces_token", new
{
client_id = "",
client_secret = "",
redirect_uri = RedirectedUri.AbsoluteUri,
code = code
});
var accesToken = result.acces_token;
Session["AccesToken"] = accesToken;
fb.AccessToken = accesToken;
dynamic me = fb.Get("me?field=link,first_name,currency,last_name,email,gender,locale,timezone,verified,picture,age_range");
string email = me.email;
string lastname = me.last_name;
string picture = me.picture.data.url;
FormsAuthentication.SetAuthCookie(email, false);
return RedirectToAction("Index", "Home");
}
`
this is the exception
Facebook.FacebookOAuthException: '(OAuthException - #1) client_secret should not be passed to /oauth/acces_token'
also this is the Facebook Action
public ActionResult Facebook()
{
var fb = new FacebookClient();
var loginUrl = fb.GetLoginUrl(new
{
client_id = "",
client_secret = "",
redirect_uri = RedirectedUri.AbsoluteUri,
response_type = "code",
scope = "email"
});
return Redirect(loginUrl.AbsoluteUri);

Categories

Resources