I know these facebook api stuffs are really became a pain in the ass, after from my longer searches on internet, I could only find a message post API to facebook. I just want to modify it for both message and image posting. Here is relevant code which posts a message to facebook.(Windows Phone 7)
private void PostToWall_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(txtMessage.Text))
{
MessageBox.Show("Enter message.");
return;
}
var fb = new FacebookClient(_accessToken);
fb.PostCompleted += (o, args) =>
{
if (args.Error != null)
{
Dispatcher.BeginInvoke(() => MessageBox.Show(args.Error.Message));
return;
}
var result = (IDictionary<string, object>)args.GetResultData();
_lastMessageId = (string)result["id"];
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Message Posted successfully");
txtMessage.Text = string.Empty;
btnDeleteLastMessage.IsEnabled = true;
});
};
var parameters = new Dictionary<string, object>();
parameters["message"] = txtMessage.Text;
fb.PostAsync("me/feed", parameters);
}
and I have also found a image post code, but I could not integrate it into my code. I think methods are not appropriate with each other.
Here is image post code;
var photo = new WriteableBitmap(0, 0).FromResource("Background200x200.jpg");
FacebookClient app = new FacebookClient();
IDictionary<string, object> parameters = new Dictionary<string, object>();
parameters["access_token"] = _facebookAccessToken; //set in another method where I authenticate...
parameters["name"] = "my picture";
parameters["message"] = "this is a picture uploaded from my the facebook sdk";
var mediaObject = new FacebookMediaObject {
FileName = "Background200x200.jpg",
ContentType = "image/jpeg",
};
mediaObject.SetValue(photo.ToByteArray());
parameters["source"] = mediaObject;
app.ApiAsync(
UploadComplete,
null,
"https://graph.facebook.com/me/feed",
parameters,
HttpMethod.Post);
I just want to post an image with a message. And If you can give me a sample link which posts an image to facebook (I ve been seeking for a ready-coded image post application,that is, Visual studio solution file which I can compile it and XAP it, and run on my phone)
or If you can help me to evolve my message poster to image poster, I would be really pleasured.
THANKS
Related
I have a problem with getting profile image from Delve account. Here is the example of link which returns me photo when i put it into browser: https://orgname.sharepoint.com/_vti_bin/DelveApi.ashx/people/profileimage?userId=alias#org.com&size=L
Now I need to get this photo from code. I tried such way, that works perfect for external images not in Office365:
var credentials = new NetworkCredential("myemail", "password");
using (var handler = new HttpClientHandler { Credentials = credentials })
using (var client = new HttpClient(handler))
{
var bytes = await client.GetByteArrayAsync(url);
return Convert.ToBase64String(bytes);
}
But as responce I get html page with text like:
<H1>We can't sign you in</H1><p>Your browser is currently set to block cookies. You need to allow cookies to use this service.</p><p>Cookies are small text files stored on your computer that tell us when you're signed in. To learn how to allow cookies, check the online help in your web browser.</p>
I think it is related with Office365 Authorization, but I don`t know how to perform REST request to this url with my credentials...
Problem Solved, first we need to initialize SharePoint Context:
public ClientContext SetupSpContext()
{
// This builds the connection to the SP Online Server
var clientContext = new ClientContext(_sharePointCrmDocumentsSiteName);
var secureString = new SecureString();
foreach (var c in _sharePointCrmDocumentsPwd.ToCharArray()) secureString.AppendChar(c);
{
clientContext.Credentials = new SharePointOnlineCredentials(_sharePointCrmDocumentsLoginName, secureString);
}
var web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
return clientContext;
}
Then we can Get profile picture from Shrepoint using User email:
public string DownloadProfilePictureAsBase64(string email)
{
try
{
var pictureUrl = GetPictureUrl(email);
var fileInfo = File.OpenBinaryDirect(_sharePointContext, pictureUrl);
using (var memory = new MemoryStream())
{
var buffer = new byte[1000000];
int nread;
while ((nread = fileInfo.Stream.Read(buffer, 0, buffer.Length)) > 0)
{
memory.Write(buffer, 0, nread);
}
memory.Seek(0, SeekOrigin.Begin);
var buffer2 = new byte[memory.Length];
memory.Read(buffer2, 0, buffer2.Length);
return Convert.ToBase64String(buffer2);
}
}
catch (Exception ex)
{
Console.WriteLine($"Picture for user {email} can not be downloaded");
Console.WriteLine(ex.Message);
}
return null;
}
private string GetPictureUrl(string email)
{
string targetUser = $"i:0#.f|membership|{email}";
var peopleManager = new PeopleManager(_sharePointContext);
var personProperties = peopleManager.GetPropertiesFor(targetUser);
_sharePointContext.Load(personProperties, p => p.PictureUrl);
_sharePointContext.ExecuteQuery();
var pictureUri = new Uri(personProperties.PictureUrl);
var localPath = pictureUri.LocalPath.Replace("MThumb", "LThumb"); //Change size of the picture
return localPath;
}
You should Microsoft Graph to get a user's picture. https://graph.microsoft.com/v1.0/me/photo gets your metadata about the profile picture, and https://graph.microsoft.com/v1.0/me/photo/$value gets you the image. You need to use OAuth. See https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/profilephoto_get for more details.
On using Android Facebook SDK, I'm able to successfully post a message to the me/feed (so I guess the problem isn't with the session status or the permissions) but posting a link (with it's additional parameters) fails with error:
{Response: responseCode: 500, graphObject: null, error: {HttpStatus: 500, errorCode: 100, errorType: FacebookApiException, errorMessage: Invalid parameter}, isFromCache:false}
I use hardcoded parameters that are confirmed to work in a different app.
What could this error mean?
I had the same problem and i was looping between it and require upload file permission error while trying to fix it.
I was sharing 2 types of posts : status and photos through using the link
https://www.facebook.com/permalink.php?story_fbid={POST-ID}&id={PAGE-ID}
or
https://www.facebook.com/{PAGE-ID}/posts/{POST-ID}
but recently i found out the facebook seems to have made some changes and this way stopped working for photos, the only way to get it to work was through using the graph api to get the post link that exists with the post object and use it for posting.
example for getting the link from a post:
Request request = new Request(Session.getActiveSession(), mPageID+ "/posts", null, HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
GraphMultiResult list = response.getGraphObjectAs(GraphMultiResult.class);
if (list != null) {
GraphObjectList<GraphObject> graphOList = list.getData();
for (int i = 0; i < graphOList.size(); i++) {
GraphObject graphObjectItem = graphOList.get(i);
if (graphObjectItem != null) {
Post p = new Post();
if (graphObjectItem.getProperty("link") != null)
p.setURL(graphObjectItem.getProperty("link").toString());
if (graphObjectItem.getProperty("id") != null) {
p.setPostID(graphObjectItem.getProperty("id").toString());
}
}
}
}
}
});
// i use execute and wait because i'm calling the function inside a background task
Request.executeAndWait(request);
function that i used to share the link :
public static void sharePost(String message, String link){
Bundle b = new Bundle();
b.putString("message", message);
b.putString("link", link);
b.putString("access_token", Session.getActiveSession().getAccessToken());
Request postRequest = new Request(Session.getActiveSession(),
"/me/feed", b, HttpMethod.POST, new Request.Callback() {
#Override
public void onCompleted(Response response) {
responseMessage = response.toString();
}
});
Request.executeAndWait(postRequest);
}
I am using FB SDK in .net, and on my website there are multiple Facebook emails configured by the user.
Whenever the user wants to post any message on FB, he can pick any email and should be able to login on FB.
The problem is that if the user already logged-in in to FB but wants to post message on some other FB account we are not able to show him the login screen and the message gets posted on the already logged-in account.
Even though we have users auth_type=reauthenticate but this also didn't help to show login screen each time. I need a mechanism like on twitter to force login on FB.
Can anyone please provide help?
A Facebook App – Take note of your App ID and App Secret
Json.NET Installed in your Bin. Download Here: http://json.codeplex.com
The following references need to be added to the page your app will be set up on:
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
using System.Security.Cryptography;
This is the HTML content:
<div id="fb-root"></div>
function runLogin() {
FB.init({
appId : 'ENTERYOURAPPIDHERE',
status : true,
cookie : true,
xfbml : true,
channelURL: 'ENTERTHEPAGEYOURAPPURLPOINTSTOHERE', // channel.html file
oauth : true
});
<div id="dontLike">
PAGE IS <b>NOT</b> Liked
</div>
</form>
Open up your code-behind for the page. We validated the code signed request.
public bool ValidateSignedRequest()
{
var VALID_SIGNED_REQUEST = Request.Form["signed_request"];
string applicationSecret = "YOURAPPSECRET";
string[] signedRequest = VALID_SIGNED_REQUEST.Split('.');
string expectedSignature = signedRequest[0];
string payload = signedRequest[1];
// Attempt to get same hash
var Hmac = SignWithHmac(UTF8Encoding.UTF8.GetBytes(payload), UTF8Encoding.UTF8.GetBytes(applicationSecret));
var HmacBase64 = ToUrlBase64String(Hmac);
return (HmacBase64 == expectedSignature);
}
private string ToUrlBase64String(byte[] Input)
{
return Convert.ToBase64String(Input).Replace("=", String.Empty)
.Replace('+', '-')
.Replace('/', '_');
}
private byte[] SignWithHmac(byte[] dataToSign, byte[] keyBody)
{
using (var hmacAlgorithm = new HMACSHA256(keyBody))
{
hmacAlgorithm.ComputeHash(dataToSign);
return hmacAlgorithm.Hash;
}
}
public Dictionary<string, string> DecodePayload(string payload)
{
//Remove the bad part of signed_request
//Begin
string[] sB64String = payload.Split('.');
payload = payload.Replace((sB64String[0] + "."), string.Empty);
//End
var encoding = new UTF8Encoding();
var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
var json = encoding.GetString(base64JsonArray);
var jObject = JObject.Parse(json);
var parameters = new Dictionary<string, string>();
parameters.Add("page", ((bool)jObject["page"]["liked"]).ToString());
parameters.Add("admin", ((bool)jObject["page"]["admin"]).ToString());
return parameters;
}
protected void pageLike()
{
string pageLiked = string.Empty;
var signed_request = Request.Form["signed_request"];
var json = DecodePayload(signed_request);
foreach (KeyValuePair<string, string> objKVP in json)
{
//Note You can also see if a user is an admin by replacing the objKVP.Key with admin
if (objKVP.Key == "page" && objKVP.Value == "True")
{
Response.Redirect("https://www.YOURSITE.com/facebook/app/pageLiked.aspx");
litJson.Text += objKVP.Key + " - " + objKVP.Value + "<br />";
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
pageLike();
}
You can see this example at this link: http://blog.daniellecopp.com/2012/03/19/detect-if-facebook-user-likes-your-page-with-asp-net-2/#comment-52
I have a problem logging out of Facebook on Windows Phone. I have the code to login, but I can't log out of it. Can someone show me how to log out of Facebook on a Windows Phone?
Here's the login code:
private FacebookClient _asyncFbClient;
private string _appID = "";
private string _appSecret = "";
private void StartFacebookLogin(object sender, RoutedEventArgs e)
{
string[] extendedPermissions = new[] { "user_about_me", "publish_stream", "email" };
FacebookClient fb = new FacebookClient();
var oauth = new FacebookOAuthClient { AppId = _appID, AppSecret = _appSecret };
var logout = new FacebookUser();
var parameters = new Dictionary<string, object>
{
{"response_type", "token"},
{"display", "touch"}
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
var loginUrl = oauth.GetLoginUrl(parameters);
webBrowser.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(CheckForAuth);
webBrowser.Navigate(loginUrl);
}
private void CheckForAuth(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Uri, out result))
{
if (result.IsSuccess)
{
IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
MessageBox.Show(result.AccessToken);
access = result.AccessToken;
if (Settings.Contains("MyFacebookAccessToken1"))
Settings["MyFacebookAccessToken1"] = result.AccessToken;
else
Settings.Add("MyFacebookAccessToken1", result.AccessToken);
Settings.Save();
_asyncFbClient = new FacebookClient(result.AccessToken);
_asyncFbClient.GetCompleted += new EventHandler<FacebookApiEventArgs>(_asyncFbClient_GetCompleted);
_asyncFbClient.GetAsync("/me");
}
}
}
Here's the logout code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(linkUrl);
request.Method = "GET";
request.BeginGetResponse(new AsyncCallback(LogoutResponse), request);
private void LogoutResponse(IAsyncResult result)
{
string responseData = "";
try
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse;
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
responseData = reader.ReadToEnd();
//responseData = true
}
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() => { MessageBox.Show(ex.Message); });
}
}
I have tried to use Facebook's logout API and get a successful result, but the next time I open the web browser it's already automatically logged in to Facebook again. How can I get it to log out?
I tried quite a few hacks to get this to work... and then Facebook finally updated their documentation with a good answer:
Logout
You can log a user out of their Facebook session by directing them to
the following URL:
https://www.facebook.com/logout.php?next=YOUR_URL&access_token=ACCESS_TOKEN
YOUR_URL must be a URL in your site domain, as defined in the
Developer App.
From http://developers.facebook.com/docs/authentication/
there is no FB Logout, it has been removed.
your best bet is to forget your credentials.
Facebook PHP SDK uses a function like this:
public function getLogoutUrl($params=array()) {
return $this->getUrl(
'www',
'logout.php',
array_merge(array(
'next' => $this->getCurrentUrl(),
'access_token' => $this->getAccessToken(),
), $params)
);
}
Which creates a URL like:
https://www.facebook.com/logout.php?next={YOUR_ENCODED_URL}&access_token={YOUR_ACCESS_TOKEN}
I believe the encoded URL must be owned by the application to whom the access_token belongs.
If you get that URL right, it'll work (just tried for one of my applications).
I'm not 100% sure if it works on windows-phone, but you can give it a try.
Hello i have a problem when i try to post something on users wall. here is my code
protected void Page_Load(object sender, EventArgs e)
{
app = new FacebookApp();
auth = new CanvasAuthorizer(app);
auth.Perms += "user_about_me,publish_stream,create_event,offline_access";
if (auth.IsAuthorized())
{
Response.Write("authorized " + app.Session.UserId.ToString()+" "+app.Session.AccessToken + "<br/>");
dynamic rez = app.Get("me");
Response.Write(rez.first_name + " "+rez.last_name);
}
else
Response.Write("not authorized ");
}
protected void btnPost_Click(object sender, EventArgs e)
{
dynamic parameters = new ExpandoObject();
parameters.message = "Check out this funny article";
parameters.link = "http://www.example.com/article.html";
parameters.picture = "http://www.example.com/article-thumbnail.jpg";
parameters.name = "Article Title";
parameters.caption = "Caption for the link";
parameters.description = "Longer description of the link";
parameters.actions = new
{
name = "View on Zombo",
link = "http://www.zombo.com",
};
parameters.privacy = new
{
value = "ALL_FRIENDS",
};
parameters.targeting = new
{
countries = "US",
regions = "6,53",
locales = "6",
};
dynamic result = app.Api("/me/feed",parameters);
}
when i try to post i get the :
(OAuthException) An active access token must be used to query information about the current user.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Facebook.FacebookOAuthException: (OAuthException) An active access token must be used to query information about the current user.
P.S.
dynamic rez = app.Get("me");
Response.Write(rez.first_name + " "+rez.last_name);
is working with no problems!
Thanks in advance.
That is because you have not given it access token try putting
FacebookApp app = new FacebookApp("my_access_token");
at top of post button event and replace
dynamic result = app.Api("/me/feed",parameters);
with
dynamic result = app.Post("me/feed", parameters);