I'm using the facebook sdk api, in a class to return a public facebook pages posts. But it returns blank, it doesn't throw an error.
var client = new FacebookClient();
dynamic result = client.Get("oauth/access_token", new
{
client_id = facebook_AppID, //App Id
client_secret = facebook_AppSecret, //App Secret
grant_type = "client_credentials" //client_credentials
});
var AccessToken = result.access_token;
var facebookClient = new FacebookClient(AccessToken);
JsonObject pagePost = facebookClient.Get("/thepagename/posts") as JsonObject;
string html = "";
foreach (var account in (JsonArray)pagePost["data"])
{
html += (string)(((JsonObject)account)["message"]);
}
What am I missing?
Related
HI I am trying to use Microsoft graph api to send messages.
Previously, I was sending messages/emails with the graph api without attachment. Now I need to attach 10 attachment each.
So I looked for examples and got to the Microsoft document and it shows the following code
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var attachment = new FileAttachment
{
Name = "smile",
ContentBytes = Convert.FromBase64String("R0lGODdhEAYEAA7")
};
await graphClient.Me.Messages["{message-id}"].Attachments
.Request()
.AddAsync(attachment);
Link:
https://learn.microsoft.com/en-us/graph/api/message-post-attachments?view=graph-rest-1.0&tabs=csharp
My question is what it is showing is not clear I am not sure I would I use message-id. Also I dont see if the Message is created and how the attachment is created.
Can someone help please.
You may refer to this document to learn the example about how to send email with attachments. And the below is my test code, it worked for me, I used client credential flow to provide authentication..
using Azure.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Graph;
public class HomeController : Controller
{
private readonly IWebHostEnvironment _appEnvironment;
public HomeController(IWebHostEnvironment appEnvironment)
{
_appEnvironment = appEnvironment;
}
public async Task<string> sendMailAsync() {
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "azure_ad_clientid";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var a = _appEnvironment.WebRootPath;//I have a file stored in my project
var file = a + "\\hellow.txt";
byte[] fileArray = System.IO.File.ReadAllBytes(#file);
//string base64string = Convert.ToBase64String(fileArray);
var message = new Message
{
Subject = "Meet for lunch?",
Body = new ItemBody
{
ContentType = BodyType.Text,
Content = "The new cafeteria is open."
},
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "xxx#outlook.com"
}
}
},
Attachments = new MessageAttachmentsCollectionPage()
{
new FileAttachment
{
Name = "attachment.txt",
ContentType = "text/plain",
ContentBytes = fileArray
}
}
};
await graphClient.Users["user_id"]
.SendMail(message, null)
.Request()
.PostAsync();
return "success";
}
}
I am trying to post the JSON data to Pardot. I have used the info from here to call the Pardot API and currently using Pardot form handler to post the data. I want to know if i could the data via Pardot API call by using CREATE or UPSERT instead of using a form handler.
Below is my code
class SendingDataToPardot
{
public string Login()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var url = "https://pi.pardot.com/api/login/version/3";
string apiKey = null;
var loginInfo = new Dictionary<string, string>
{
{"email", "xx"},
{"password", "xxx"},
{"user_key", "xxx"}
};
var httpContent = new FormUrlEncodedContent(loginInfo);
using (var client = new HttpClient())
{
HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string resultValue = response.Content.ReadAsStringAsync().Result;
apiKey = XDocument.Parse(resultValue).Element("rsp").Element("api_key").Value;
return apiKey;
}
else
{
return null;
}
}
}
public string POST()
{
string Api_Key = Login();
var url = "form handler url";
var contactFormData = new Dictionary<string, string>
{
{"email", "test#test.com"},
{"FirstName", "xxx"},
{"LastName", "xxxxx"},
{"Comments", "this is a test"}
};
var data= new FormUrlEncodedContent(contactFormData);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Api_Key);
HttpResponseMessage response = client.PostAsync(url, data).Result;
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
}
}
}
For most of the APIs Pardot exposes, you need to do XML work with it.
Looks like you are using Java, so you might have luck using a public library, even if just for understanding communication patterns (we had to rewrite it for our purposes, but it did serve as a great blueprint).
Have a look at the https://github.com/Crim/pardot-java-client project and see if it helps you out.
not sure if I am doing this right , passing a Token value and then get some info from a webservice.
I edited this question , it is passing authentication. I will leave it for future searches.
private async void Data(string AUTH)
{
using (HttpClient client = new HttpClient())
{
var Tokens = Storage.access.AUTH;
var json = JsonConvert.SerializeObject(AUTH);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AUTH);
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
var response = client.GetAsync("https://any adrees.com").Result;
string content = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
var content2 = await response.Content.ReadAsStringAsync();
var Items = JsonConvert.DeserializeObject<Mensajes>(content2);
}
Debug.WriteLine(content);
}
}
Not sure what type of token you are refer to, my answer will be based on OAuth access token.
You will need to create a AuthenticationHeaderValue and set it into HttpClient's headers.
var authHeader = new AuthenticationHeaderValue("bearer", Storage.accessToken.Token);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = authHeader;
I'm trying out the facebook api. I'm getting this error that i'm not authorized to perform this action. I have accepted all the pop-ups that came when i run the program. Anyone got a quick soulution for this?
sing Facebook;
public void CheckAutorization()
{
string app_Id = "xxxxxxxxxxxxxxx";
string app_secret = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
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('&'))
{
//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);
client.Post("/me/feed", new { message = "Is there anyone out there? :) Can i get a whoop whoop" });
}
}
}
}
Had to change the scope string scope = "publish_stream, manage_pages" to string scope = "publish_stream, publish_actions";
I'm building an application that allows users to post message to their facebook from the application. To problem I'm having that I don't know how to get the user access_token for the publish_stream permission.
This is what I've got so far:
var fb = new FacebookClient();
dynamic result = fb.GetLoginUrl(new
{
client_id = AppID,
client_secret = AppSecret,
grant_type = "client_credentials",
scope = "publish_stream",
state = "http://localhost:17578/Facebook.aspx",
redirect_uri = "http://localhost:17578/Facebook.aspx"
});
That works fine and it returns a 'code' in the querystring. However, I'm not sure what to do with that code.
The 'old' Facebook C# sdk contained the FacebookOAuthClient class which had the ExchangeCodeForAccessToken() method, but I don't know what the replacement of this static method is in the new SDK.
So the question really is: How to exchange the code that is returned for an access_token?
After you get the code query string parameter you must make a call to the Facebook Graph API to get the access token.
https://developers.facebook.com/docs/howtos/login/server-side-login/
FacebookClient client = new FacebookClient();
dynamic result = client.Get("oauth/access_token", new { client_id = Settings.Social_Facebook_App_Id, client_secret = Settings.Social_Facebook_Secret_Key, code = Request.QueryString["code"], redirect_uri = Settings.Social_Facebook_Login_Redirect_URI });
if (result.error == null)
{
Session["AccessToken"] = client.AccessToken = result.access_token;
dynamic user = client.Get("me", new { fields = "name,username,email" });
string userName = user.username;
mu = Membership.GetUser(userName);
if (mu == null) // Register
{
RegisterModel rm = new RegisterModel();
rm.Email = user.email;
rm.UserName = userName;
return View("Register", rm);
}
else
{
FormsAuthentication.SetAuthCookie(userName, true);
return RedirectToAction(MVC.Home.Index());
}
}