I have tried to find answers on following questions for at least one hour but with no success.
I have WPF project (C#) and I have webBrowser control to navigate to my Facebook page http://www.facebook.com/TennisHelper and I want to do next few things:
I want to avoid login by creating user settings in my application which will contain email and password, but I don't know how to do that with C# Facebook SDK,
I want to make able for my user to post textual posts on that page via textBox control,
I want to make able for my user to post photos from his computer directly to that page, but with not creating new albums. Just to post image on page wall.
I was searching Google for all those problems but with no success
Let me know actually what is your requirement.I think your first requirement is to add a facebook login(or register with facebook page) button in your Website login page.
step1:You need to register a new facebook application on facebook.
step 2:install facebook c# sdk .You can either download the zip file manually or install it using nuget.I recommend the second option.I am using c# sdk 5.4.1 What is nuget? How to install a package using nuget?
step 3:Now you can add name space facebook to the page
step 4:Insert a login button(simply a button with text login) in login page(say login.aspx).Let it be button1
step 5:On click button redire to another page (let login1.aspx)
here is a sample code for login 1
using Facebook;//
FacebookOAuthClient fb = new FacebookOAuthClient();
UriBuilder red = new UriBuilder("www.example.com/Login1.aspx");
protected void Page_Load(object sender, EventArgs e)
{
string appid = "{your app id}";
string appsecret = "{your app secret}";
string permissions = "publish_stream";
if(Request.QueryString["code"] == null)
{
try
{
Response.Redirect("https://www.facebook.com/dialog/oauth?client_id=" + appid + "&redirect_uri=" + red.Uri.ToString() + "&scope=" + permissions +"&state=djfjfdjj");
}
catch (Exception b)
{
Label1.Text = b.ToString();
}
}
else
{
try
{
FacebookOAuthClient cl = new FacebookOAuthClient();
cl.RedirectUri = red.Uri;
cl.AppId = appid;
cl.AppSecret = appsecret;
dynamic result = cl.ExchangeCodeForAccessToken(Request.QueryString["code"]);
Label1.Text = Convert.ToString(result);
if (result["access_token"] != null)
{
Session["access_token"] = result["access_token"].ToString();//Now you have access token
Response.Redirect("Welcome.aspx");//replace welcome.aspx
}
else
{
Label1.Text = "Unable to authenticate\n Please try again later";
}
}
catch(Exception b)
{
Label1.Text = b.ToString();
}
}
}
Now you have access token saved in session.
for getting basic information of the client
dynamic me=fb.Get("\me");
it in cludes first name, last name ,email address,location,image url etc. of the current user.Now you can use this e-mail or name to verify your user or register new user etc.(its up to you ).
posting on that page is possible but diffiult How can I use the Facebook C# SDK to post on Facebook Pages
You should register an application on Facebook in order to use Facebook log in.navigate to
http://developers.facebook.com
create an appllication.You will get an application id and application secret.Use it as appid,appsecret
Related
Ok. So this question might be a bit stupid but as I've searched and searched and haven't found a working solution I thought I might ask here.
I've put up a simple PHP page that gets 2 parameters from the url myusername and mypassword. Then gets 3 int values from a database according to the username and password given.
(tested it By typing the url in with the parameters and the PHP script itself works. Even made it to echo the 3 integers on the page to make sure)
Now to the problematic part. I'm using Visual Studio 2013 and making an Universal App for Windows 8.1. And I just can't seem to get the httpClient to get me any data from there. Through browsing the forums I haven't been able to find anything that works. Couldn't have tested all either as most use GetResponse() which doesn't work in VS 2013. As I'm fairly new to the C# coding it could be as simple as to a little mistake in the dozens of tests I've done.
Made a login screen with 2 text fields. And I can build the url in form of "www.something.com/something/somephp?myusername=UserNameGiven&mypassword=PasswordGiven"
If anyone could give a simple solution on how I might be able to get the results from the page that address opens (only shows the 3 integers through echo... can remove those too if those arent required for the C# code to work. String format would probably be ideal if not too much to ask...
Ok made a new GetScores async method for the code you gave SnyderCoder. Throwing that Task on login button would have required coding beyond my knowhow for the moment atleast.
Still Results.Text field remains at the default status and shows no change.
Changed the LoginButton back to async without task.
the state of my code from the c# is atm is
private async void LoginButton_Click(object sender, RoutedEventArgs e)
{
string UserName, Password;
UserName = UserNameFeedField.Text.ToString();
Password = PasswordFeedField.Text.ToString();
string url = "something.com/something/GetScores.php?myusername=" + UserName + "&mypassword=" + Password;
URL.Text = url;
// GetScores(url);
using (Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient())
{
string contentOFPage = await client.GetStringAsync(new Uri(url));
Results.Text = contentOFPage;
}
}
incase it matters here is the PHP code portion
<?php
$host="db_host"; // Host name
$username="db_user"; // Mysql username
$password="db_pswd"; // Mysql password
$db_name="db_name"; // Database name
$tbl_name="db_table"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_GET["myusername"];
$mypassword=$_GET["mypassword"];
// To protect MySQL injection (more detail about MySQL injection )
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT field1 as LowB, field2 as LongB, field3 as Bs FROM $tbl_name WHERE UserID='$myusername' and UserPSWD='$mypassword'";
$result=mysql_query($sql);
// this part only shows the variables gotten from the query and echoes those on the page
// was only made to test that the PHP works.
while ($row = mysql_fetch_assoc($result)) {
echo ($row["LowB"] . " " . $row["LongB"] . " " . $row["Bs"]);
}
?>
First a async method always needs to return a task. For the rest:
private async void LoginButton_Click(object sender, RoutedEventArgs e)
{
string UserName = UserNameFeedField.Text.ToString();
string Password = PasswordFeedField.Text.ToString();
string url = "www.something.com/something/some.php?myusername=" + UserName + "&mypassword=" + Password;
using (Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient())
{
string contentOfPage = await client.GetStringAsync(new Uri(url));
//Do something with the contentOfPage
}
}
I am having issues with Authentication in my Windows Phone 7 app using Facebook SDK .net
here is the authentication part
var facebookClient = new FacebookClient();
facebookClient.AppId = FacebookAppId;
facebookClient.AppSecret = FacebookSecret;
var authUrl = facebookClient.GetLoginUrl(new
{
client_id = FacebookAppId,
client_secret = FacebookSecret,
scope = "publish_stream",
response_type = "token",
display = "touch",
redirect_uri = "https://www.facebook.com/connect/login_success.html"
});
browser.Navigate(authUrl);
So the browser screens seem to work fine, login screen shows and then the permissions screens show. When I press OK on the last permission screen I just get a white screen. In fact I have been staring at this white screen for 10mins now.
Any ideas?
Here is the Browser.Navigated event handler. I have commented where I have put breakpoints
async void browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
var facebookClient = new FacebookClient(); // Put break point here to make sure the event is handled
if(facebookClient.TryParseOAuthCallbackUrl(e.Uri, out result))
{
if (result.IsSuccess) // Put break point here to check result but its never reached
{
Logging.WriteLine("Authentication was a success!");
Classes.Facebook.Instance.AccessToken = result.AccessToken;
CreateFacebookPost();
}
else
{
MessageBox.Show(string.Format("Error: {0}\nReason:{1}", result.ErrorDescription, result.ErrorReason), "Authentication Error", MessageBoxButton.OK);
Logging.WriteLine("Authentication Failed");
Logging.WriteLine(string.Format("Error: {0}\nReason:{1}", result.ErrorDescription, result.ErrorReason));
}
browser.Visibility = System.Windows.Visibility.Collapsed;
browser.Navigated -= browser_Navigated;
}
}
EDIT 1:
Just some more info. I know the authentication (from Facebooks view) is a success as I can now see the app on my Facebook. Also, if I push back on the phone to go to previous screen of the app and then go back into the facebook section it shows everything is ok and I can make posts.
EDIT 2:
Using very similar code, this works fine in a Windows Phone 8 app. I have compared the 2 and can't seen any difference.
Looks like I have found the solution. You have to set IsScriptedEnabled=True on the WebBrowser control. By default it is false.
I have pages that I admin in the Facebook and I want to share a link(not post) from that page using Facebook C# SDK. How can I do that? For clarify question, Facebook pages has link button that you can share link with page's picture.
Simply facebookclient.Post("me/feed",parameters);
For the parameters see https://developers.facebook.com/docs/reference/api/post/
messagePost["message"] = message;
messagePost["caption"] = caption;
messagePost["description"] = descr;
messagePost["link"] = "http://xxx";
FacebookClient fbClient = new FacebookClient(FacebookAdminToken); //users have to accept your app
dynamic fbAccounts = fbClient.Get("/" + FacebookAdminId + "/accounts");
if (pageID != null)
{
foreach (dynamic account in fbAccounts.data)
{
if (account.id == pageID)
{
messagePost["access_token"] = account.access_token;
break;
}
}
dynamic publishedResponse = fbClient.Post("/" + pageID + "/links", messagePost);
message.Success = true;
}
Hope his helps.
there is two majour problems with my solution:
1) my FacebookAdmintoken was created using the soon to be deprecated offline_status. there currently is no way for the access_token to stay alive otherwise. Facebook claims it does, but it just doesn't work.
2) there is a bug in the facebook API. when you use post('/id/LINKS') you cannot specify the picture (FB chooses a random pic from the site) and using post('/id/FEED') people can see the result, but they cannot SHARE it.
Seriously FB, get your act together!!!!!
I am writing a test app which will simply ask the user to login to facebook via a webbrowser control. Then on the Navigated event a message box will appear relaying the user name of the user. The example I have been following uses a a FacebookClient.Get() method and so do many other examples on the net. My problem is that the FacebookClient doesn't even contain a Get().
I am using C#4.0, and I referenced the Facebook C# SDK from NuGet.
private void wb_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Uri, out result))
{
if (result.IsSuccess)
{
var accesstoken = result.AccessToken;
var fb = new FacebookClient(accesstoken);
var _result = (IDictionary<string, object>)fb.Get("/me");
var name = (string)_result["name"];
MessageBox.Show("Hi " + name);
}
else
{
var errorDescription = result.ErrorDescription;
var errorReason = result.ErrorReason;
}
}
}
The Facebook C# SDK isn't really optimised for WP7, I recommend using the facebook API without going through the sdk c#
I have been attempting to code a windows form application that interacts with facebook to retrieve the access token that has permissions to get some of the user's information. I have been trying to get the birthday of myself using the following code but it keeps giving me the 400 bad request error. Basically after running this code, and logging in at the authentication it is suppose to show a messagebox containing the user's birthday. In this case, I am using my own user id in the api.GET method. It seems to be the access token issue as when I don't pass in any tokens, i can view public available information such as id using the same code but I print out the access token to check and it seems to be alright. Any help would be much appreciated. First time posting here
public partial class AccessTokenRetrieval : Form
{
private string accessToken=null;
public AccessTokenRetrieval()
{
InitializeComponent();
}
private void accessTokenButton_Click(object sender, EventArgs e)
{
string getAccessTokenURL = #"https://graph.facebook.com/oauth/authorize?client_id=223055627757352&redirect_uri=http://www.facebook.com/connect/login_success.html&type=user_agent&display=popup&grant_type=client_credentials&scope=user_photos,offline_access";
getAccessTokenWebBrowser.Navigate(getAccessTokenURL);
}
private void getAccessTokenWebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string successUrl = #"http://www.facebook.com/connect/login_success.html";
string urlContainingUserAuthKey = e.Url.ToString();
MessageBox.Show(urlContainingUserAuthKey);
int searchInt = urlContainingUserAuthKey.IndexOf(successUrl);
MessageBox.Show(searchInt.ToString());
if (urlContainingUserAuthKey.IndexOf(successUrl) == -1)
{
string accessTokenString;
accessTokenString = Regex.Match(urlContainingUserAuthKey, "access_token=.*&").ToString();
this.accessToken = accessTokenString.Substring(13, accessTokenString.Length - 14);
//100001067570373
//MessageBox.Show(accessToken);
accessTokenTextBox.Text = this.accessToken;
Facebook.FacebookAPI api = new Facebook.FacebookAPI(this.accessToken);
JSONObject me = api.Get("/100001067570373");
MessageBox.Show(me.Dictionary["user_birthday"].String);
}
}
#
I would request you to try http://facebooksdk.codeplex.com and checkout the samples folder.
It includes sample for WinForms authentication and also making various request to Facebook.
Here are other useful links that I would recommend you to read.
http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-first-Facebook-Application.aspx
http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx