I am using the latest SDK of Facebook C# SDK i.e. 5.0.9 Beta
I had one Text box in page in button which suppose to post the text in the users Wall.
But the problem is when I am clicking on Button the page get redirected to
something like
http://localhost:5000/facebookredirect.axd?code=JU1q_vSj13WRn1wIjHjCZRF5iDy_xvkFUppxADeS0F0.eyJpdiI6InJwejVVWXpJY1RqV0VaY1JjTl92ZGcifQ.KSa0B1ax1qCZZ-K_oXLmAZR8lyknWDRY9ieWxuLIZqXedUzb1WQH_FrcMF98VO6U1Dk5KIo4dz4AMdBxtfrUUH0ucgOoPC6_7Zb03WsIgY2fF84L-0s3A7m3f971sJUS4nQyRGDZ_-8oPuO0K0dTPg&state=eyJyIjoiaHR0cDovL2FwcHMuZmFjZWJvb2suY29tL3Rlc3RhcHBfdGVzdGluZy9Ib21lL0Fib3V0P0xlbmd0aD0zIn0
and then again redirected to my apps URL in between I am not getting any data in my controller the values are showing as null.
After analyzing HTTP call I found the content is
<html><head><script type="text/javascript">
top.location = "http://www.facebook.com/dialog/oauth/?scope=user_about_me,friends_about_me,publish_stream&state=eyJyIjoiaHR0cDovL2FwcHMuZmFjZWJvb2suY29tL3Rlc3RhcHBfdGVzdGluZy9ob21lL0Fib3V0In0&client_id=218380811509677&redirect_uri=http://localhost:5000/facebookredirect.axd";
</script></head><body></body></html>
I am using Ajax but the Behavior is same for normal as well.
It Seems like Authorizing on every Call.
Do I need to implement Oauth 2.0.
I am Using sample APP for the MVC3.
Can anyone tell me whats going wrong?
That´s a typical occurrence , when you use FacebookAuthorizeAttribute from Facebook.Web.Mvc. At least, your response-code let me assume that the oauth-handshake didn´t work properly (although you got the "code", you forgot to get your "access_token" with it)
In case you´re using FacebookAuthorizeAttribute, check if you´re app-settings in the facebook-developer-app AND your web.config have the right canvas-url/ canvas-page inserted. (In your case, for testing, "http://localhost/" / "http://apps.facebook.com/yourappname")
Recently I read a post, which said you mustn´t use the Facebook.Mvc classes, because they provide example-code.
see 1. Answer on this link
Try this code
public ActionResult Index()
{
var url = "http://www.facebook.com/v2.2/dialog/oauth/?scope=user_friends,read_friendlists,publish_actions,read_stream,read_insights,manage_pages,user_checkins,user_photos,read_mailbox,manage_notifications,read_page_mailboxes,email,user_videos,user_groups,offline_access,publish_actions,manage_pages&client_id=" + ConfigurationManager.AppSettings["ClientId"] + "&redirect_uri=" + ConfigurationManager.AppSettings["RedirectUrl"] + "&response_type=code";
return Redirect(url);
}
Call Back Url
public string AddFacebookAccount(string code)
{
string ret = string.Empty;
string client_id = ConfigurationManager.AppSettings["ClientId"];
string redirect_uri = ConfigurationManager.AppSettings["RedirectUrl"];
string client_secret = ConfigurationManager.AppSettings["ClientSecretKey"];
long friendscount = 0;
try
{
FacebookClient fb = new FacebookClient();
string profileId = string.Empty;
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("client_id", client_id);
parameters.Add("redirect_uri", redirect_uri);
parameters.Add("client_secret", client_secret);
parameters.Add("code", code);
JsonObject fbaccess_token = null;
try
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
fbaccess_token = (JsonObject)fb.Get("/oauth/access_token", parameters);
}
catch (Exception ex)
{
try
{
fbaccess_token = (JsonObject)fb.Get("/oauth/access_token", parameters);
}
catch (Exception ex1)
{
return "issue_access_token";
}
}
string accessToken = fbaccess_token["access_token"].ToString();
Session["AccessToken"] = accessToken;
if (accessToken != null)
{
fb.AccessToken = accessToken;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
dynamic profile = fb.Get("v2.2/me");
dynamic friends = fb.Get("v2.2/me/friends");
try
{
Session["uid"] = profile.id;
friendscount = Convert.ToInt16(friends["summary"]["total_count"].ToString());
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
//return new JavaScriptSerializer().Serialize(ret);
return ret;
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
return "Something Went Wrong";
}
}
Post Text and Image Code
public ActionResult ComposeMessageSend(string message)
{
System.Net.ServicePointManager.Expect100Continue = false;
string file = Server.MapPath("~/Images/11.jpg");
message = "This is Photoshop's version of Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin, lorem quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit. Duis sed odio sit amet nibh vulputate cursus a sit amet mauris. Morbi accumsan ipsum velit. Nam nec tellus a odio tincidunt auctor a ornare odio. Sed non mauris vitae erat consequat auctor eu in elit. Class aptent" ;
string tokenid = string.Empty;
string userid = string.Empty;
//Arvind Itact
tokenid = "CAAK1OqZAcaoMBAHxFQXf78orU2KkZCijtr5MT14VBQsB9QB4YkL6Ua3FUHcSEpss7f0dwIPofpDI0oOSH94iaOQx9tbsS7zbZAu3To6R5dKo4jQ2HGXoiiiVBIEfEoVKwieOLzT6IvZAwlqMxK8x8gqR0RG9Dgd60NwCM3XRPDHZAeoUVYpSELoQdPJS1uDbNQFBK4mgtaSVPcbkjmD1VYhpC";
userid = "1383854058392012107";
string result = FacebookComposeMessage(tokenid, userid, message, file);
return View();
}
public string FacebookComposeMessage(string tokenid,string userid ,String message,string imagepath)
{
FacebookClient fb = new FacebookClient();
string ret = "";
fb.AccessToken = tokenid;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
var args = new Dictionary<string, object>();
args["message"] = message;
if (!string.IsNullOrEmpty(imagepath))
{
var media = new FacebookMediaObject
{
FileName = "filename",
ContentType = "image/jpeg"
};
byte[] img = System.IO.File.ReadAllBytes(imagepath);
media.SetValue(img);
args["source"] = media;
ret = fb.Post("v2.0/" + userid + "/photos", args).ToString();
}
else
{
ret = fb.Post("v2.0/" + userid + "/feed", args).ToString();
// ret = fb.Post("/" + objFacebookAccount.FbUserId + "/photos", args).ToString();
// var data = fb.Get("v2.2" + ret);
}
return ret;
}
Related
welcome everybody
I moved from xamarin to Flutter
I encountered some problems
Including encryption and decryption
How can I convert this function to Dart/Flutter?
This function is required to communicate with the api
Thank you everyone
public static string encryp(string x, string encrypt)//function
{
try
{
string y = x;
byte[] etext = UTF8Encoding.UTF8.GetBytes(y);
string Code = encrypt;
MD5CryptoServiceProvider mdhash = new MD5CryptoServiceProvider();
byte[] keyarray = mdhash.ComputeHash(UTF8Encoding.UTF8.GetBytes(Code));
TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider();
tds.Key = keyarray;
tds.Mode = CipherMode.ECB;
tds.Padding = PaddingMode.PKCS7;
ICryptoTransform itransform = tds.CreateEncryptor();
byte[] result = itransform.TransformFinalBlock(etext, 0, etext.Length);
string encryptresult = Convert.ToBase64String(result);
return encryptresult.ToString();
}
catch (Exception ex)
{
return (ex.Message==null ?"": ex.Message);
}
}
public static string decrypt(string x, string keyai)
{
try
{
string y = x.Replace("\0", null);
byte[] etext = Convert.FromBase64String(y);
string key = keyai;
MD5CryptoServiceProvider mdhash = new MD5CryptoServiceProvider();
byte[] keyarray = mdhash.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider();
tds.Key = keyarray;
tds.Mode = CipherMode.ECB;
tds.Padding = PaddingMode.PKCS7;
ICryptoTransform itransform = tds.CreateDecryptor();
byte[] result = itransform.TransformFinalBlock(etext, 0, etext.Length);
string dencryptresult = UTF8Encoding.UTF8.GetString(result);
return dencryptresult.ToString();
}
catch (Exception ex)
{
return (ex.Message==null ?"": ex.Message);
}
}
update
I wrote this code on Flutter
import 'package:dart_des/dart_des.dart' as des3;
String encryptDataE(String _plainText, String _key) {
var bytes = new List<int>.from(utf8.encode(_plainText));
var key = md5.convert(utf8.encode(_key)).bytes; //The key is any letters
des3.DES3 mDes3CBC = des3.DES3(
key: key,
mode: des3.DESMode.ECB,
paddingType: des3.DESPaddingType.PKCS7,
);
final encrypted = mDes3CBC.encrypt(bytes);
String value = base64Encode(encrypted);
return value;
}
String decryptDataD(String _plainText, String _key) {
String plainText = _plainText.replaceAll("\0", null);
var bytes = base64.decode(plainText);
var key = md5.convert(utf8.encode(_key)).bytes; //The key is any letters
des3.DES3 mDes3CBC = des3.DES3(
key: key,
mode: des3.DESMode.ECB,
paddingType: des3.DESPaddingType.PKCS7,
);
final decrypt= mDes3CBC.decrypt(bytes);
String value = utf8.decode(decrypt);
return value;
}
After experimenting with encryption and decoding, this works now
One point left, how can this be achieved?
//string y = x.Replace("\0", null);//c#
String plainText = _plainText.replaceAll("\0", null); //I tried with this and it gets an error
Consider using this tool: "Use the tool e.g. for porting your Xamarin/UWP project to Flutter"
Otherwise, there is a pretty easy Flutter Encrypt package here
//Package example
import 'package:encrypt/encrypt.dart';
void main() {
final plainText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit';
final key = Key.fromUtf8('my 32 length key................');
final iv = IV.fromLength(16);
final encrypter = Encrypter(AES(key));
final encrypted = encrypter.encrypt(plainText, iv: iv);
final decrypted = encrypter.decrypt(encrypted, iv: iv);
print(decrypted); // Lorem ipsum dolor sit amet, consectetur adipiscing elit
print(encrypted.base64); // R4PxiU3h8YoIRqVowBXm36ZcCeNeZ4s1OvVBTfFlZRdmohQqOpPQqD1YecJeZMAop/hZ4OxqgC1WtwvX/hP9mw==
}
I want use rsa in flutter
I have the following code for flutter
But I do not know about the part test/private.pem and test/public.pem how it is made in flutter
Of course, I have private and public keys that are made in Java with a length of 1024
Can I put them here? Or not, and must the PEM file be created? How do I generate a PEM file?
Thank you for your help
Future<void> main () async {
final publicKey = await parseKeyFromFile<RSAPublicKey>('test/public.pem');
final privKey = await parseKeyFromFile<RSAPrivateKey>('test/private.pem');
final plainText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit';
final encrypter = Encrypter(RSA(publicKey: publicKey, privateKey: privKey));
final encrypted = encrypter.encrypt(plainText);
final decrypted = encrypter.decrypt(encrypted);
print(decrypted); // Lorem ipsum dolor sit amet, consectetur adipiscing elit
print(encrypted.base64); // kO9EbgbrSwiq0EYz0aBdljHSC/rci2854Qa+nugbhKjidlezNplsEqOxR+pr1RtICZGAtv0YGevJBaRaHS17eHuj7GXo1CM3PR6pjGxrorcwR5Q7/bVEePESsimMbhHWF+AkDIX4v0CwKx9lgaTBgC8/yJKiLmQkyDCj64J3JSE=
}
there are 2 ways to set publicKey and privateKey.
from your project :
create a folder named as test/
inside it
like this
inside private.pem and public.pem paste your private and public key
respectively .
and get it using
final publicKey = await parseKeyFromFile<RSAPublicKey>('test/public.pem');
final privKey = await parseKeyFromFile<RSAPrivateKey>('test/private.pem');
above approach works good when public and private keys are constant
from string :
import 'package:encrypt/encrypt.dart';
import 'package:pointycastle/asymmetric/api.dart';
String privateKeyString="key goes here";
String publicKeyString="key goes here";
//create a instance of RSA key praser
RSAKeyParser keyParser = RSAKeyParser();
//and parse those string keys
RSAAsymmetricKey privateKeyParser = keyParser.parse(privateKeyString);
RSAAsymmetricKey publicKeyParser =keyParser.parse(publicKeyString);
final publicKey = RSAPublicKey(publicKeyParser.modulus!, publicKeyParser.exponent!);
final privKey;
if (privateKeyParser is RSAPrivateKey) {
privKey = RSAPrivateKey(privateKeyParser.modulus!,privateKeyParser.exponent!, privateKeyParser.p,privateKeyParser.q);
final plainText = 'hello world';
final encrypter = Encrypter(RSA(publicKey: publicKey, privateKey:privKey));
final encrypted = encrypter.encrypt(plainText);
final decrypted = encrypter.decrypt(encrypted);
}
it worked for me!!
You can use pointy castle package to do that: https://pub.dev/packages/pointycastle
Just generate a key pair (code below) and use it in your app. Good luck!
import 'package:pointycastle/export.dart';
import 'dart:math';
import 'dart:typed_data';
AsymmetricKeyPair<RSAPublicKey, RSAPrivateKey> generateRSAkeyPair(
SecureRandom secureRandom,
{int bitLength = 2048}) {
// Create an RSA key generator and initialize it
final keyGen = RSAKeyGenerator()
..init(ParametersWithRandom(
RSAKeyGeneratorParameters(BigInt.parse('65537'), bitLength, 64),
secureRandom));
// Use the generator
final pair = keyGen.generateKeyPair();
// Cast the generated key pair into the RSA key types
final myPublic = pair.publicKey as RSAPublicKey;
final myPrivate = pair.privateKey as RSAPrivateKey;
return AsymmetricKeyPair<RSAPublicKey, RSAPrivateKey>(myPublic, myPrivate);
}
SecureRandom exampleSecureRandom() {
final secureRandom = FortunaRandom();
final seedSource = Random.secure();
final seeds = <int>[];
for (int i = 0; i < 32; i++) {
seeds.add(seedSource.nextInt(255));
}
secureRandom.seed(KeyParameter(Uint8List.fromList(seeds)));
return secureRandom;
}
// here is how you generate key pair
final pair = generateRSAkeyPair(exampleSecureRandom());
final public = pair.publicKey; // to get public
final private = pair.privateKey; // i know, you get it :D
Issue happens on Win10. Eclipse 4.13.0.
I got a JFace TableViewer above a Text widget in a GridLayout. Whenever I fill the Table with content, the Text widget disappears. If I configure the shell as FillLayout it works, but that's not what I want because I've got some widgets not wanting to grab any space (like the search field, the separator, etc.).
I can't seem to find the problem, any advice?
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
public class TestDialog {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setBounds(10, 10, 800, 600);
shell.setLayout(new GridLayout());
Label separator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
separator.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Link link = new Link(shell, SWT.NONE);
link.setText("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore");
link.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
Text txtSearch = new Text(shell, SWT.BORDER | SWT.SEARCH | SWT.ICON_SEARCH | SWT.CANCEL);
txtSearch.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
txtSearch.setMessage("Enter search phrase here");
TableViewer tableViewer = new TableViewer(shell, SWT.BORDER | SWT.FULL_SELECTION);
tableViewer.setContentProvider(ArrayContentProvider.getInstance());
Table table = tableViewer.getTable();
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
Group grp = new Group(shell, SWT.NONE);
grp.setText("MyGroup:");
grp.setLayout(new FillLayout(SWT.HORIZONTAL));
grp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
Text txt = new Text(grp, SWT.WRAP);
List<String> entries = new ArrayList<String>();
for (int i = 0; i < 100; i++) {
entries.add("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore");
}
tableViewer.setInput(entries);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
The table is being expanded to show all of the lines and this is pushing everything below the table out of the window.
You need to specify a height hint for the table:
Table table = tableViewer.getTable();
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
data.heightHint = 200;
table.setLayoutData(data);
In Android app I have integrated Facebook login in android studio. I want to display username, user email id and a user profile photo after login. How will I get it?
Use this for user information. Its work successfully.
loginButton = (LoginButton) findViewById(R.id.login_button);
List < String > permissionNeeds = Arrays.asList("user_photos", "email",
"user_birthday", "public_profile", "AccessToken");
loginButton.registerCallback(callbackManager,
new FacebookCallback < LoginResult > () {#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("onSuccess");
String accessToken = loginResult.getAccessToken()
.getToken();
Log.i("accessToken", accessToken);
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
Log.i("LoginActivity", response.toString());
try {
id = object.getString("id");
try {
URL profile_pic = new URL(
"http://graph.facebook.com/" + id + "/picture?type=large");
Log.i("profile_pic",
profile_pic + "");
} catch (MalformedURLException e) {
e.printStackTrace();
}
name = object.getString("name");
email = object.getString("email");
gender = object.getString("gender");
birthday = object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields",
"id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
System.out.println("onCancel");
}
#Override
public void onError(FacebookException exception) {
System.out.println("onError");
Log.v("LoginActivity", exception.getCause().toString());
}
});
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent data) {
super.onActivityResult(requestCode, responseCode, data);
callbackManager.onActivityResult(requestCode, responseCode, data);
}
I am stuck into a problem for which I have not found any solution or documentation.
I am building an app using Facebook API in which user will create an app and will give their APP ID & APP SECRET to the application in order to create pages or post to pages.
Now the problem is they will only login into my application not in facebook nor login using FB.
I am getting APP ACCESS TOKEN from APP ID & APP SECRET.
Using https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=APP_SECRET&grant_type=client_credentials
But how could i use it to get pages for that account or generate USER ACCESS TOKEN from it?
Please help me with your expert guidance.
Thanks.
You cannot create Apps nor Pages by using the Graph API! See https://developers.facebook.com/docs/graph-api/reference/v2.0/page
If you want to publish to a Page the logged-in User administrers, you can request the respective Page Access Token (with publish_actions and manage_pages permissions!) via
GET /me/accounts
See
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/accounts/
https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens
first of create developer apps and get token give some permission
public ActionResult Index()
{
var url = "http://www.facebook.com/v2.0/dialog/oauth/?scope=user_friends,read_friendlists,read_stream,read_insights,manage_pages,user_checkins,user_photos,read_mailbox,manage_notifications,read_page_mailboxes,email,user_videos,user_groups,offline_access,publish_actions,manage_pages&client_id=" + ConfigurationManager.AppSettings["ClientId"] + "&redirect_uri=" + ConfigurationManager.AppSettings["RedirectUrl"] + "&response_type=code";
return Redirect(url);
}
that automatic redirect call back url for example
public ActionResult AddFacebookAccount(string code)
{
string ret = string.Empty;
string client_id = ConfigurationManager.AppSettings["ClientId"];
string redirect_uri = ConfigurationManager.AppSettings["RedirectUrl"];
string client_secret = ConfigurationManager.AppSettings["ClientSecretKey"];
long friendscount = 0;
try
{
FacebookClient fb = new FacebookClient();
string profileId = string.Empty;
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("client_id", client_id);
parameters.Add("redirect_uri", redirect_uri);
parameters.Add("client_secret", client_secret);
parameters.Add("code", code);
JsonObject fbaccess_token = null;
try
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
fbaccess_token = (JsonObject)fb.Get("/oauth/access_token", parameters);
}
catch (Exception ex)
{
try
{
fbaccess_token = (JsonObject)fb.Get("/oauth/access_token", parameters);
}
catch (Exception ex1)
{
ViewBag.acc_tkn= "issue_access_token";
}
}
string accessToken = fbaccess_token["access_token"].ToString();
Session["AccessToken"] = accessToken;
if (accessToken != null)
{
fb.AccessToken = accessToken;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
dynamic profile = fb.Get("v2.2/me");
dynamic friends = fb.Get("v2.2/me/friends");
try
{
Session["uid"] = profile.id;
friendscount = Convert.ToInt16(friends["summary"]["total_count"].ToString());
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
ViewBag.acc_tkn = accessToken;
ViewBag.Uid = profile.id;
}
return View();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
ViewBag.acc_tkn= "Something Went Wrong";
return View();
}
}
you will get access Token when post data on page refer Bellow Code
public void FacebookPostonPage(string file, string message, string tokenid)
{
JsonObject fbaccess_token = null;
FacebookClient fb = new FacebookClient();
fb.AccessToken = tokenid;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
fbaccess_token = (JsonObject)fb.Get("v2.0/me/accounts");
dynamic Result = fbaccess_token["data"];
foreach (var obj in Result)
{
string result = FacebookComposeMessage(obj.access_token, obj.id, message, file);
}
}
public string FacebookComposeMessage(string tokenid,string userid ,String message,string imagepath)
{
FacebookClient fb = new FacebookClient();
string ret = "";
fb.AccessToken = tokenid;
fb.AppId = ConfigurationManager.AppSettings["ClientId"];
fb.AppSecret = ConfigurationManager.AppSettings["ClientSecretKey"];
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
var args = new Dictionary<string, object>();
args["message"] = message;
if (!string.IsNullOrEmpty(imagepath))
{
var media = new FacebookMediaObject
{
FileName = "filename",
ContentType = "image/jpeg"
};
byte[] img = System.IO.File.ReadAllBytes(imagepath);
media.SetValue(img);
args["source"] = media;
ret = fb.Post("v2.0/" + userid + "/photos", args).ToString();
}
else
{
ret = fb.Post("v2.0/" + userid + "/feed", args).ToString();
// ret = fb.Post("/" + objFacebookAccount.FbUserId + "/photos", args).ToString();
// var data = fb.Get("v2.2" + ret);
}
return ret;
}
You will post Successfully try now