Post on facebook page using c# as page using graph api - c#

private void CheckAuthorization()
{
string app_id = "*****";
string app_secret = "******";
string scope = "manage_pages,publish_pages";
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
//tokens["access_token"];
var client = new FacebookClient(access_token);
Dictionary<string, string> data = new Dictionary<string, string>();
client.Post("/1038145769594318/feed", new
{
message = " test page post",
picture = "http://service.extrabucks.in/EmailTemplateCss/7/images/bottom-background2.png",
name = "Nikunj Patel",
link = "www.extrabucks.in",
description = "Test Description",
type = "links"
});
}
}
Hey i am using this code for post on Facebook using c# but the problem is that it's not post as a page it's post as a user. I want to post as a Page in my Fan page. please give me a solution using the above code. and one more thing i want life-time Working access_token what should i do ?
thanks in advance

public static string GetPageAccessToken(string userAccessToken)
{
FacebookClient fbClient = new FacebookClient();
fbClient.AppId = "*****";
fbClient.AppSecret = "**************";
fbClient.AccessToken = userAccessToken;
Dictionary<string, object> fbParams = new Dictionary<string, object>();
JsonObject publishedResponse = fbClient.Get("/me/accounts", fbParams) as JsonObject;
JArray data = JArray.Parse(publishedResponse["data"].ToString());
foreach (var account in data)
{
if (account["name"].ToString().ToLower().Equals("opening shortly"))
{
return account["access_token"].ToString();
}
}
return String.Empty;
}
this code is working for me for refreshing page access tokens every time
just add
client.Post("/1038145769594318/feed", new
{
message = " test page post",
picture = "",
name = "Nikunj Patel",
link = "www.extrabucks.in",
description = "Test Description",
type = "photo",
access_token = GetPageAccessToken(access_token)
});

Related

I want to implement sharepoint document search using C# api

I want to search sharepoint document using C# api call.
I am trying below code:
string URL = "http://server/_api/search/query?query_parameter=value&query_parameter=value";
System.Net.Http.HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "XXXXX", "XXXXXX"))));
using (client)
{
HttpResponseMessage httpResponseMessage = await client.GetAsync(URL);
HttpResponseMessage responsemMsgx = httpResponseMessage;
if (responsemMsgx.IsSuccessStatusCode)
{
}
}
But,i am have a doubt regarding URL below:
string URL = "http://server/_api/search/query?query_parameter=value&query_parameter=value";
Please help me with the sharepoint server and constructing the URL.
My expected output is something like JSON .
If you want to search documents, we can use the Search REST API below to achieve it.
/_api/search/query?querytext='IsDocument:True'
C# example:
string siteUrl = "http://sp2013/sites/team";
string searchQuery = "/_api/search/query?querytext='IsDocument:True'";//search all documents
var credential = new System.Net.NetworkCredential("username", "password", "domainname");
HttpClientHandler handler = new HttpClientHandler() { Credentials = credential };
HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json;odata=verbose");
var result = client.GetAsync(siteUrl+searchQuery).Result;
var content = result.Content.ReadAsStringAsync().Result;
JObject jobj = JObject.Parse(content);
JArray jarr = (JArray)jobj["d"]["query"]["PrimaryQueryResult"]["RelevantResults"]["Table"]["Rows"]["results"];
foreach (JObject j in jarr)
{
JArray results = (JArray)j["Cells"]["results"];
var title = "";
var path = "";
foreach (JObject r in results)
{
if (r["Key"] != null)
{
if (r["Key"].ToString() == "Title")
{
title = r["Value"].ToString();
}
if (r["Key"].ToString() == "Path")
{
path = r["Value"].ToString();
}
}
}
Console.WriteLine(title + "|" + path);
}

Authenticate SharePoint online REST API without user name and password

I am trying to build a console app that reads the data from SharePoint list.
But i dont want to pass the user credentials in order to authenticate, instead use the token. Is this possible?
I tried using the following code but i get forbidden error while trying to GetFormDigest
static void Main(string[] args)
{
string sConnStr = "https://sab/sites/DevT";
Uri oUri = null;
oUri = new Uri(sConnStr + "/_api/web/lists/getbytitle('sd')/GetItems");
string sResult = string.Empty;
string stringData = "{'query' : {'__metadata': { 'type': 'SP.CamlQuery' }, 'ViewXml':'<View><Query><Where><Eq><FieldRef Name =\"Title\"/><Value Type=\"Text\">HR</Value></Eq></Where></Query></View>'}}";
HttpWebRequest oWebRequest = (HttpWebRequest)WebRequest.Create(oUri);
oWebRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
oWebRequest.Method = "POST";
oWebRequest.Accept = "application/json;odata=verbose";
oWebRequest.ContentType = "application/json;odata=verbose";
oWebRequest.Headers.Add("X-RequestDigest", GetFormDigest());
oWebRequest.ContentLength = stringData.Length;
StreamWriter writer = new StreamWriter(oWebRequest.GetRequestStream());
writer.Write(stringData);
writer.Flush();
WebResponse wresp = oWebRequest.GetResponse();
using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))
{
sResult = sr.ReadToEnd();
}
}
public static string GetFormDigest()
{
string sFormDigest = null;
string sConnStr = "https://sab/sites/DevT";
Uri oUri = null;
oUri = new Uri(sConnStr + "/_api/contextinfo");
HttpWebRequest oWebRequest = HttpWebRequest.Create(oUri) as HttpWebRequest;
oWebRequest.UseDefaultCredentials = true;
oWebRequest.Method = "POST";
oWebRequest.Accept = "application/json;odata=verbose";
oWebRequest.ContentLength = 0;
oWebRequest.ContentType = "application/json";
string sResult;
WebResponse sWebReponse = oWebRequest.GetResponse();
using (StreamReader sr = new StreamReader(sWebReponse.GetResponseStream()))
{
sResult = sr.ReadToEnd();
}
var jss = new JavaScriptSerializer();
var val = jss.Deserialize<Dictionary<string, object>>(sResult);
var d = val["d"] as Dictionary<string, object>;
var wi = d["GetContextWebInformation"] as Dictionary<string, object>;
sFormDigest = wi["FormDigestValue"].ToString();
return sFormDigest;
}
You could use Add-in authentication to access SharePoint data.
You could check my test demo below.
https://social.msdn.microsoft.com/Forums/office/en-US/d33f5818-f112-42fb-becf-3cf14ac5f940/app-only-token-issue-unauthorized-access?forum=appsforsharepoint

Post to Facebook Page as page

After quite searching i was able to post on Facebook Page as myself. but my target was to post on the Page i manage as the page. I did some more research and i was able to get the access token of the page i manage. when i tried to POST on it, sdk gave me the error that
The user hasn't authorized the application to perform this action
here is my code for your reference :
string app_id = "xxxxx";
string app_secret = "yyyyyyy";
string scope = "publish_actions,manage_pages";
if (Request["code"] == null)
{
string url = string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope);
Response.Redirect(url, false);
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = System.Net.WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
dynamic parameters = new ExpandoObject();
parameters.message = "Check out this funny article";
parameters.link = "http://www.natiska.com/article.html";
parameters.picture = "http://www.natiska.com/dav.png";
parameters.name = "Article Title";
parameters.caption = "Caption for the link";
//zzzzzzz is my fan page
string pageAccessToken = "";
JsonObject jsonResponse = client.Get("me/accounts") as JsonObject;
foreach (var account in (JsonArray)jsonResponse["data"])
{
string accountName = (string)(((JsonObject)account)["name"]);
if (accountName == MY_PAGE_NAME)
{
pageAccessToken = (string)(((JsonObject)account)["access_token"]);
break;
}
}
client = new FacebookClient(pageAccessToken);
client.Post("/zzzzzzz/feed", parameters);
You need the publish_pages permission to post as pages.
https://developers.facebook.com/docs/graph-api/reference/v2.3/page/feed#publish
Your Facebook App Dosn't have manage_page & publish_page permission, instead of this you can create test application and from that u can create test users for your testing .
From there u can manage all the pages posts and data.

using HttpWebRequest two or more times via c#

I have one problem. I have two methods which use HttpWebRequest. One of them post a message to my facebook wall. Another take count number of likes.
Thare is code:
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url =
string.Format(
"https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
//get wall data
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
//post message to my wall or image
dynamic messagePost = new ExpandoObject();
messagePost.message = "I need to get an id of this post";
try
{
var postId = client.Post("me/feed", messagePost);
id_mypost = postId["id"];
}
catch (FacebookOAuthException ex)
{
//handle oauth exception
}
catch (FacebookApiException ex)
{
//handle facebook exception
}
}
This method post message to my wall. Thare is the second method:
if (Response.BufferOutput == true)
{
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url =
string.Format(
"https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
try
{
string str = client.Get("/me/feed").ToString();
JObject obj = JObject.Parse(str);
JToken jUser = obj["data"];
int numb = jUser.Count();
int id_post = 0;
for (int i = 0; i < numb; i++)
{
if (obj["data"][i]["id"].ToString() == id_mypost)
{
id_post = i;
}
}
string strr = obj["data"][id_post]["likes"].ToString();
string pattern = #"id";
int count_like = 0;
Regex newReg = new Regex(pattern);
MatchCollection matches = newReg.Matches(strr);
foreach (Match mat in matches)
{
count_like++;
}
}
catch (Exception)
{
}
}
So thare is the problem. I use two times HttpWebRequest. So , when I bild my app i got next error: Cannot redirect after HTTP headers have been sent.
Can somebody help me ?
Cannot redirect after HTTP headers have been sent.
This is the error of asynchronous operation. For example if you are using any thread operation and in that thread you try Response.redirect it will give this error.
The response is already sent to client before the statement executes.
Can you please tell me where exactly the error is occurring ?

How to post to the profile of other people using following code

I have the following code:
public void CheckAuthorization()
{
string app_id = "";//Your id here
string app_secret = "";//your secret key
string scope = "publish_stream, manage_pages";
if (Request["code"] == null)
{
Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")), token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=")-1));
}
}
string access_token=tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("me/feed", new { message="Hi"});
}
}
Using this code , I can post to my profile using the line
client.Post("me/feed", new { message="Hi"});
How can I go about posting on other profiles?
Try this:
client.Post("/PROFILE_ID/feed", new { message="Hi"});
More info: https://developers.facebook.com/docs/reference/api/#publishing

Categories