asp.net (C#) Facebook GetInfo() - c#

I am struggling to get off with ground with some Facebook dev work. All I want to do is retireve some user info for the logged in user. This is the code I got from another site & it looks fine to me, however is always returns IsConnected() to be false.
I am running this code within an iframe on my facebook app (in sandbox mode)
private const string APPLICATION_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxx";
private const string SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
public Facebook.Rest.Api Api;
private Facebook.Session.ConnectSession _connectSession;
protected void Page_Load(object sender, EventArgs e)
{
_connectSession = new Facebook.Session.ConnectSession(APPLICATION_KEY,SECRET_KEY);
if (!_connectSession.IsConnected())
{
lit.Text = "Please sign-in with Facebook.";
}
else
{
try
{
Api = new Facebook.Rest.Api(_connectSession);
Facebook.Schema.user u = Api.Users.GetInfo();
img.ImageUrl = u.pic_square;
lit.Text = string.Format("Welcome, " + u.name);
}
catch (Exception ex)
{
lit.Text = ex.Message;
}
}
}

See this other SO question about a similar problem. The poster apparently found what he was looking for, but didn't know how to implement it. You may be able to do so, since there's a lot of information in the question body.

Related

How do i make an else or if statement creating text into usrNameLabel when it does not find the website url i specified at the top

So i want to display [NOT FOUND] if the web request doesnt find the url specified with strings above.
What I have done is a HWID system to identify the current user. it combines 2 strings to find my github repository and in that repository a file titled with their hwid and it displays their user name inside.
I want to make it so that if it does not find that file/website url/git repository that it displays Not Found.
Everything was defined before hand / everything works how it should but if it does not find the
url it will just crash.
or if it gets removed.
also this will happen if it does not find a connection to the internet.
but i have a fix for that which will switch the text to Not Connected when the check for Online/Offline status comes back as Offline.
i have read some on else statements and as far as i know it needs an if statement above.
i dont have one there because my code did not require one before.
Can someone please help me rewrite it?
code:
private void Form1_Load(object sender, EventArgs e)
{
HWID = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;
textBox1.Text = HWID;
//downloads the username of the user
WebClient client = new WebClient();
string GithubRepository = "INSERT GITHUB LINK";
string GithubRepositoryImg = "INSERT OTHER GITHUB LINK";
string urlEndInPNG = ".png";
String strPageCode = client.DownloadString(GithubRepository+=HWID);
string strProfPicUrl = GithubRepositoryImg += HWID += urlEndInPNG;
usrNameLabel.Text = strPageCode;
// Insert else or if statement that says it to display "[NOT FOUND]" when it doesnt find it.
//my try
else{
usrNameLabel.Text = "Not Found";
}
What it displays when it finds the url
Image of what it displays
I have googled how to create one but it does not work pls help.
thank you
I think you need a try-catch more than an if/else statement.
Try as following:
private void Form1_Load(object sender, EventArgs e)
{
HWID = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;
textBox1.Text = HWID;
//downloads the username of the user
WebClient client = new WebClient();
string GithubRepository = "INSERT GITHUB LINK";
string GithubRepositoryImg = "INSERT OTHER GITHUB LINK";
string urlEndInPNG = ".png";
string strPageCode = string.Empty;
try
{
strPageCode = client.DownloadString(GithubRepository += HWID);
}
catch (Exception ex)
{
usrNameLabel.Text = "Not Found";
}
string strProfPicUrl = GithubRepositoryImg += HWID += urlEndInPNG;
usrNameLabel.Text = string.IsNullOrEmpty(strPageCode) ? usrNameLabel.Text : strPageCode;
}
When the code throws the exception, label's text will be set to "Not Found", in case it doesn't find the repository you're searching for.

Grabbing Dropbox access token on Windows Form using Dropbox API

I have done a class which already works with the Dropbox API uploading files, downloading, deleting and so on. It has been working quite well since I was just using my own access token, but I need to register other users and a single but "big" problem appeared: retrieving the access token.
1.- Redirect URI? I'm starting to doubt why do I need this. I finally used this URI (https://www.dropbox.com/1/oauth2/redirect_receiver) because "The redirect URI you use doesn't really matter" Of course I included this one on my app config on Dropbox.
2.- I reach the user's account (I can see the user's count increased and I see the app has access to the user's account.
3.- I have a breakpoint on my code to inspect the variables in order to apply the DropboxOAuth2Helper.ParseTokenFragment but I have no success on there.
This is my code, but on the if before the try catch is where it gets stuck:
string AccessToken;
const string AppKey = "theOneAtmyAppConfigOnDropbox";
const string redirectUrl = "https://www.dropbox.com/1/oauth2/redirect_receiver";
string oauthUrl =
$#"https://www.dropbox.com/1/oauth2/authorize?response_type=token&redirect_uri={redirectUrl}&client_id={AppKey}";
private string oauth2State;
private bool Result;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Start(AppKey, webBrowser1);
webBrowser1.Navigating += Browser_Navigating;
}
private void Start(string appKey, WebBrowser w)
{
this.oauth2State = Guid.NewGuid().ToString("N");
Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OauthResponseType.Token, appKey, redirectUrl, state: oauth2State);
w.Navigate(authorizeUri);
}
private void Browser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
if (!e.Url.ToString().StartsWith(redirectUrl, StringComparison.InvariantCultureIgnoreCase))
{
// we need to ignore all navigation that isn't to the redirect uri.
return;
}
try
{
OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Url);
if (result.State != this.oauth2State)
{
// The state in the response doesn't match the state in the request.
return;
}
this.AccessToken = result.AccessToken;
this.Result = true;
}
catch (ArgumentException)
{
// There was an error in the URI passed to ParseTokenFragment
}
finally
{
e.Cancel = true;
this.Close();
}
}
I've been fighting against this for hours and I'm starting to see the things a little cloudy at this point.
This is the tutorial I used, but I'm not moving forward. I would really appreciate any help!
EDIT: I finally made some steps forward. I changed the line which contains
Uri authorizeUri2 = DropboxOAuth2Helper.GetAuthorizeUri(appKey);
Now I'm showing the generated access token on the WebClient! Bad part comes when trying to get it (it gets inside the if) and it gets generated every time I ask the user for permission, so it gets overwrited.
EDIT 2: I noted the token I get generated on the browser is somehow malformed. I try to manually change it hardcored when I'm debugging and I get an exception when an AuthException when creating the DropboxClient object :( What the hell!
As Greg stated, the solution was using the event Browser_Navigated. Looks like the version of the embedded IE my Visual Studio (2015) uses didn't notice that if it's a redirect, it won't launch the event BrowserNavigating.

Facebook Extended Permission in C#

I'm developping a Facebook Application (using ASP.NET C# and Nathan Totten's Facebook C# SDK) and trying to access to extended permissions.
I tried on localhost (with an existing app in facebook), and everybody works. But when I try to use it directly in facebook, I obtain a blank page (i'm still connected on facebook).
Here is my code :
Page/aspx :
protected void btn_ask_question_Click(object sender, EventArgs e)
{
if (ControllerAccess.testUserConnected())
{
if (txt_ask_question.InnerText != "")
{
Dictionary<string, object> action = new Dictionary<string,object>();
action.Add("action", "askQuestion");
action.Add("message", txt_ask_question.InnerText);
action.Add("idTheme", ddl_choose_question_category.SelectedValue);
HttpContext.Current.Session["ActionToDo"] = action;
String s = Controller.GetExtendedPermission2(this, ControllerAccess.getScopeByAction("askQuestion"));
try{
Response.Redirect(s, false);
} catch(Exception ex)
{
}
}
}
}
In my Page_Load() :
if (HttpContext.Current.Session["ActionToDo"] != null)
{
Dictionary<string, object> action = HttpContext.Current.Session["ActionToDo"] as Dictionary<string, object>;
String s = action["action"].ToString();
switch (s)
{
case "askQuestion":
Guid idTheme;
Boolean themeExists = Guid.TryParse(action["idTheme"].ToString(), out idTheme);
if(themeExists)
{
askQuestion(action["message"].ToString(), idTheme);
lbl_errors.Text = "Votre question a bien été posée";
}
break;
default:
break;
}
HttpContext.Current.Session["ActionToDo"] = null;
}
In Control.cs :
public static string GetCustomOAuthDialogParameters(string AppID, string RedirectURI, string Scope, string State)
{
string CustomParameters = "?client_id=" + AppID + "&redirect_uri=" + RedirectURI + "&scope=" + Scope + "&state=" + State;
return CustomParameters;
}
public static void GetExtendedPermission(Page page, String scope)
{
ecritureFichier("GetExtendedPermission");
Label lbl_errors = page.Form.FindControl("lbl_errors") as Label;
string OAuthDialogAbsoluteURL = "";
try
{
string OAuthDialogURL = "https://www.facebook.com/dialog/oauth";
string PageLocation = GetCurrentPageFacebookPublishedPath(page.Request); //The redirect page (eg: https://apps.facebook.com/democsharpsdk/TestsExtendedPermission.aspx)
string UniqueReferenceCode = Guid.NewGuid().ToString();
OAuthDialogAbsoluteURL = OAuthDialogURL + GetCustomOAuthDialogParameters(AppID, PageLocation, scope, UniqueReferenceCode);
page.Response.Redirect(OAuthDialogAbsoluteURL, false);
}
catch (Exception exp)
{
lbl_errors.Text += "Erreur Catchée via ASP.NET : " + exp.Message;
}
}
The blank page appears when I use this line : page.Response.Redirect(OAuthDialogAbsoluteURL, false);
But I log all my steps and my OAuthDialogAbsoluteURL is correct :
https://www.facebook.com/dialog/oauth?client_id=XXXXXXXXXXXXXXXXX&redirect_uri=https://apps.facebook.com/name_of_my_app&scope=email&state=0443030f-dddd-4fe6-9d6c-9454409d01b3
When I type it into the adress bar manually, everything works correctly.
Do you have any idea about the difference between local version and published version or why the redirect doesn't work? Maybe facebook block some requests?
Thanks.
Make sure you settings point to the hosted version if you want to use the app to test different environments. Facebook doesn't let you authorise a user from a site that isn't connect to your app for security reasons.
Normally, you would see an error like "URL isn't owned by Application" or similar.
I finally resolved my problem usingChrome Debugger. The error was :
Refused to display document because display forbidden by X-Frame-Options
I used Javascript to fix it, and did my redirection like this :
Response.Write("<script>");
Response.Write("window.open('"+redirect+"','_top')");
Response.Write("</script>");
Hope it'll help some people.

Web Browsers Showing Error Page

I never used fiddler core before. But after first time using it into my application, a weird problem is happening. Whenever my application is running web browsers are working fine. But other time those all showing error page. I know I did something wrong with fiddler core. I am sending my codes here. Codes are working perfectly. But there is something into my code so that I getting this problem. Please see the code and let me know what am I doing wrong.
static bool bUpdateTitle = true;
static Proxy oSecureEndpoint;
static string sSecureEndpointHostname = "localhost";
static int iSecureEndpointPort = 1106;
private void button1_Click(object senderr, EventArgs e)
{
List<Fiddler.Session> oAllSessions = new List<Fiddler.Session>();
Fiddler.FiddlerApplication.OnNotification += delegate(object sender, NotificationEventArgs oNEA) { MessageBox.Show("** NotifyUser: " + oNEA.NotifyString); };
Fiddler.FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS)
{
oS.bBufferResponse = false;
Monitor.Enter(oAllSessions);
oAllSessions.Add(oS);
Monitor.Exit(oAllSessions);
if (oS.hostname=="localhost")
{
oS.utilCreateResponseAndBypassServer();
oS.oResponse.headers.HTTPResponseStatus = "200 Ok";
oS.oResponse["Content-Type"] = "text/html; charset=UTF-8";
oS.oResponse["Cache-Control"] = "private, max-age=0";
oS.utilSetResponseBody("<html><body><font size=10>Restricted</font></body></html>");
}
};
Fiddler.CONFIG.IgnoreServerCertErrors = false;
FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true);
FiddlerCoreStartupFlags oFCSF = FiddlerCoreStartupFlags.Default;
Fiddler.FiddlerApplication.Startup(0, oFCSF);
oSecureEndpoint = FiddlerApplication.CreateProxyEndpoint(iSecureEndpointPort, true, sSecureEndpointHostname);
}
public static void DoQuit()
{
if (null != oSecureEndpoint) oSecureEndpoint.Dispose();
Fiddler.FiddlerApplication.Shutdown();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DoQuit();
}
As mentioned in the response to your same message left in the Fiddler discussion group, this means that you ran your program at least once without properly calling Shutdown() (e.g. because it crashed). Clear the incorrect proxy settings from Tools > Internet Options > Connections > LAN Settings when your program isn't running.

Finding out if a Facebook page is liked by a user. Using the Facebook C# SDK

I'm trying to build a Facebook 'fangate' tab or 'reveal' tab for a Facebook page.
You know how it goes - when a user visits the page, they are shown one bit of content if they haven't yet clicked 'Like' and another once they have.
I'm not a PHP guy so I'm attempting to do this with the Facebook C# SDK (http://facebooksdk.codeplex.com) in Visual Studio 2010. I'm fairly new to .NET too so I'm not doing so well with this!
I have to admit I've been cutting and pasting code from all over the place to get this to work and I think I'm almost there but I'm not getting this error:
Invalid signed request.
Line 82: var DecodedSignedRequest = FacebookSignedRequest.Parse(current, FacebookWebContext.Current.SignedRequest.Data.ToString());
Here's my code:
var settings = ConfigurationManager.GetSection("facebookSettings");
var current = settings as IFacebookApplication;
var DecodedSignedRequest = FacebookSignedRequest.Parse(current, FacebookWebContext.Current.SignedRequest.Data.ToString());
dynamic SignedRequestData = DecodedSignedRequest.Data;
var RawRequestData = (IDictionary<string, object>)SignedRequestData;
string currentFacebookPageID = current.AppId;
bool currentFacebookPageLiked = false;
if (RawRequestData.ContainsKey("page") == true)
{
Facebook.JsonObject RawPageData = (Facebook.JsonObject)RawRequestData["page"];
if (RawPageData.ContainsKey("id") == true)
currentFacebookPageID = (string)RawPageData["id"];
if (RawPageData.ContainsKey("liked") == true)
currentFacebookPageLiked = (bool)RawPageData["liked"];
}
if (currentFacebookPageLiked)
{
//Do some stuff for fans
}
else
{
//Do some stuff for non-fans
}
All the Facebook settings are in my web.config file and I have checked that the AppID and AppSecret are correct.
Can anyone offer me any insight into this issue please? Is there a better way of doing this that I've not yet found?
Many thanks in advance for any help.
OK, I've sorted it out - but I'm not sure why. I have a feeling that the Facebook C# SDK screws around with the signed request in some way. If I get the signed request using Request.Forms["signed_request"] it all seems to work.
I'll share my working code in the hope that it will help others with the same problem.
//Pull in the facebook app settings from the web.config file
var settings = ConfigurationManager.GetSection("facebookSettings");
var current = settings as IFacebookApplication;
//Set up some stuff for later
string currentFacebookPageID = current.AppId;
bool currentFacebookPageLiked = false;
//Get the signed request
FacebookSignedRequest SignedRequest = FacebookSignedRequest.Parse(current, Request.Form["signed_request"]);
dynamic SignedRequestData = SignedRequest.Data;
//extract what we need from the request
var RawRequestData = (IDictionary<string, object>)SignedRequestData;
//Check to see if we've got the data we need
if (RawRequestData.ContainsKey("page") == true)
{
//We do, lets examine it and set the boolean as appropriate
Facebook.JsonObject RawPageData = (Facebook.JsonObject)RawRequestData["page"];
if (RawPageData.ContainsKey("id") == true)
currentFacebookPageID = (string)RawPageData["id"];
if (RawPageData.ContainsKey("liked") == true)
currentFacebookPageLiked = (bool)RawPageData["liked"];
}
if (currentFacebookPageLiked)
{
//Do some stuff for fans
lblName.Text = "Hi " + result.first_name + " - You are a fan";
}
else
{
//Do some stuff for non-fans
lblName.Text = "Hi " + result.first_name + " - please click the like button";
}
This is the code i used and it worked great for me.
protected bool IsPageLiked()
{
var current = ConfigurationManager.GetSection("facebookSettings")
as IFacebookApplication;
dynamic signedRequest = FacebookSignedRequest.Parse(current, Request);
try
{
return signedRequest.Data.page.liked;
}
catch (Exception)
{
return false;
}
}

Categories

Resources