Get Open Graph Data by Facebook API - facebook-graph-api

I want to get some data (title, description, image) using url to page and 'Facebook SDK for .NET' library.
I don't receive image when I use GET request:
Request implementation:
var facebookClient = new FacebookClient(GetAccessToken());
try
{
dynamic data = facebookClient.Get(url);
return new OpenGraphData
{
Id = data.og_object.id,
Title = data.og_object.title,
Description = data.og_object.description
};
}
catch (Exception e)
{
}
Is it possible to create POST request using this library?
If not please tell me another way to get this data

Request data manually
using (WebClient client = new WebClient())
{
try
{
var json =
client.UploadString(String.Format(
"https://graph.facebook.com/v2.4/?id={0}&access_token={1}", url, at), "POST");
}
catch (Exception e)
{
}
}

Related

wso2 identity server custom handler reading from properties file

public class UserRegistrationCustomEventHandler extends AbstractEventHandler {
JSONObject jsonObject = null;
private static final Log log = LogFactory.getLog(UserRegistrationCustomEventHandler.class);
#Override
public String getName() {
return "customClaimUpdate";
}
if (IdentityEventConstants.Event.POST_SET_USER_CLAIMS.equals(event.getEventName())) {
String tenantDomain = (String) event.getEventProperties()
.get(IdentityEventConstants.EventProperty.TENANT_DOMAIN);
String userName = (String) event.getEventProperties().get(IdentityEventConstants.EventProperty.USER_NAME);
Map<String, Object> eventProperties = event.getEventProperties();
String eventName = event.getEventName();
UserStoreManager userStoreManager = (UserStoreManager) eventProperties.get(IdentityEventConstants.EventProperty.USER_STORE_MANAGER);
// String userStoreDomain = UserCoreUtil.getDomainName(userStoreManager.getRealmConfiguration());
#SuppressWarnings("unchecked")
Map<String, String> claimValues = (Map<String, String>) eventProperties.get(IdentityEventConstants.EventProperty
.USER_CLAIMS);
String emailId = claimValues.get("http://wso2.org/claims/emailaddress");
userName = "USERS/"+userName;
JSONObject json = new JSONObject();
json.put("userName",userName );
json.put("emailId",emailId );
log.info("JSON:::::::"+json);
// Sample API
//String apiValue = "http://192.168.1.X:8080/SomeService/user/updateUserEmail?email=sujith#gmail.com&userName=USERS/sujith";
try {
URL url = new URL(cityAppUrl) ;
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
log.info("CONN:::::::::::::"+con);
OutputStream os = con.getOutputStream();
os.write(cityAppUrl.toString().getBytes("UTF-8"));
os.close();
InputStream in = new BufferedInputStream(con.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
jsonObject = new JSONObject(result);
log.info("JSON OBJECT:::::::::"+jsonObject);
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void init(InitConfig configuration) throws IdentityRuntimeException {
super.init(configuration);
}
#Override
public int getPriority(MessageContext messageContext) {
return 250;
}
}
I'm using wso2 identity server 5.10.0 and have to push the updated claim value to an API so I'm using a custom handler and have subscribed to POST_SET_USER_CLAIMS, i have to read the API value from deployment.toml file in jave code of the custom handler. So can any one please help here to read the value from deployment file
I can fetch the updated claim value in logs but im not able to get the API value. So can anyone help me here to read the value from deployment file.
Since the API path is required inside your custom event handler, let's define the API path value as one of the properties of the event handler.
Add the deployment.toml config as follows.
[[event_handler]]
name= "UserRegistrationCustomEventHandler"
subscriptions =["POST_SET_USER_CLAIMS"]
properties.apiPath = "http://192.168.1.X:8080/SomeService/user/updateUserEmail"
Once you restart the server identity-event.properties file populates the given configs.
In your custom event handler java code needs to read the config from identity-event.properties file. The file reading is done at the server startup and every config is loaded to the memory.
By adding this to your java code, you can load to configured value in the property.
configs.getModuleProperties().getProperty("UserRegistrationCustomEventHandler.apiPath")
NOTE: property name needs to be defined as <event_handler_name>.<property_name>
Here is a reference to such event hanlder's property loading code snippet https://github.com/wso2-extensions/identity-governance/blob/68e3f2d5e246b6a75f48e314ee1019230c662b55/components/org.wso2.carbon.identity.password.policy/src/main/java/org/wso2/carbon/identity/password/policy/handler/PasswordPolicyValidationHandler.java#L128-L133

Want to get the details of the user(member) after login successfully in xamarin forms

my question is how to pass username and password from the C# client(xamarin forms) to server's API? if details are correct then the client will get whole product list from webapi(URL).and bind all the details to a listview.I want to get the member details after the success of response code.
the client will send username password from login page to server's API. if server's webapi check whether the details matched with the database, if not, don't let it get product list.
here is the code in loginservices for login(xamarin forms)
public async Task GetData(string username,string password)
{
//string detail = new UserDetails();
UserDetails userDetails = new UserDetails();
// List<UserDetails> detail = new List<UserDetails>();
try
{
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("Username", username));
values.Add(new KeyValuePair<string, string>("Password", password));
var content = new FormUrlEncodedContent(values);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("nl-NL"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsync("http://192.168.1.50/Accounts/Authenticate", content);
return response.IsSuccessStatusCode;
};
}
catch (Exception ex)
{
throw ex;
}
}
here is the code for web api---
public async Task ValidateUser([FromBody] Credentials credentials)
{
using (DemoAPPEntities entities = new DemoAPPEntities())
{
var result = await entities.MemberDetails.Where(x => x.UserName == credentials.UserName && x.Password == credentials.Password).SingleOrDefaultAsync();
if (result == null)
{
return NotFound();
}
return Ok(entities.MemberDetails);
}
}

Accessing public information using a specific userID on facebook graph api

Someone is logged into my app. I need to display some profiles of people that might not be on this person's friends list. Is that possible, or is it a privacy issue. A person's "public profile" should be accessible right?
I tried to get the first name, profile picture and gender
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name,gender");
try {
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/" + user.getUserID(),
parameters,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
JSONObject facebookResponse = response.getJSONObject();
try {
final String first_name = facebookResponse.getString("first_name");
final String gender = facebookResponse.getString("gender");
Bundle params = new Bundle();
params.putBoolean("redirect", false);
params.putString("type", "square");
params.putInt("width", 200);
params.putInt("height", 200);
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/" + user.getUserID() + "/picture",
params,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
JSONObject facebookResponse = response.getJSONObject();
try {
JSONObject data = facebookResponse.getJSONObject("data");
String url = data.getString("url");
Name.setText(first_name);
Gender.setText(gender);
mNetworkImageView.setImageUrl(url, mImageLoader);
facebookResponseListener.updatedUserObject(first_name, url, gender, pos);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
).executeAsync();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
).executeAsync();
} catch (Exception uee) {
uee.printStackTrace();
}
all of this is inside the getView() if a listview (it's where I display the profiles). While testing, I'm getting all the information of the friends of the logged in person, but the "gender" property in the response object is missing from the non-friend. Only the name and userID is being returned.
It's all explained in the docs (https://developers.facebook.com/docs/facebook-login/permissions):
gender & locale can only be accessed if:
The person queried is the person using the app.
The person queried is using the app, and is a friend of the person
using the app.
The person queried is using the app, is not a friend of the person
using the app, but the app includes either an app access token or an
appsecret_proof argument with the call.

Post JSON Object using httpClient windows Phone 8.1

I'm trying to post a json Object to a web api project from a windows phone app but I'm still getting 404 error. For the post method, I'm using that code:
Mail mailToCheck = new Mail();
try
{
mailToCheck.MailProfil = TxtBox_mail.Text.ToString();
string json = JsonConvert.SerializeObject(mailToCheck);
var httpClient = new System.Net.Http.HttpClient(new HttpClientHandler());
System.Net.Http.HttpResponseMessage response = await httpClient.PostAsync(new Uri("http://uri/api/Profil/CheckMail"), new StringContent(json));
var responseString = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
MessageBox.Show(ex.HResult.ToString());
}
The method CheckMail on my conctroller:
[HttpPost]
[Route("api/Profil/CheckMail")]
public IHttpActionResult CheckMail([FromBody]Mail MailProfil)
{
if (MailProfil.MailProfil != null)
{
try
{
bool exists = Librairie.Profils.mailExists(MailProfil.MailProfil);
return Ok(exists);
}
catch(Exception ex)
{
return InternalServerError(ex);
}
}
else
{
return BadRequest();
}
}
The Mail object is exactly the same in the app as in the web api project. Does someone can tell me what I'm doing wrong here ?
Check some samples of HttpClient.PostAsync() here: https://monkeyweekend.wordpress.com/2014/10/23/how-to-send-text-json-or-files-using-httpclient-postasync/

web service to retrieve data from solr

how to write a rest web service to query data from solr server in java. I have the a java code to query from solr
CommonsHttpSolrServer server = null;
try
{
server = new CommonsHttpSolrServer("http://localhost:8080/solr/");
}
catch(Exception e)
{
e.printStackTrace();
}
SolrQuery query = new SolrQuery();
query.setQuery(solrquery);
query.set("rows",1000);
// query.setQueryType("dismax");
// query.setFacet(true);
// query.addFacetField("lastname");
// query.addFacetField("locality4");
// query.setFacetMinCount(2);
// query.setIncludeScore(true);
try
{
QueryResponse qr = server.query(query);
SolrDocumentList sdl = qr.getResults();
I need to get the same functionality in a web service by taking id as the query parameter.
If you just want to query the id passed as an parameter to the webservice -
String id = "100145";
String url = "http://localhost:8080/solr/core_name"; // core name needed if using multicore support
CommonsHttpSolrServer solrServer;
try {
solrServer = new CommonsHttpSolrServer(url);
ModifiableSolrParams qparams = new ModifiableSolrParams();
qparams.add("q", "id:"+id);
QueryResponse qres = solrServer.query(qparams);
SolrDocumentList results = qres.getResults();
SolrDocument doc = results.get(0);
System.out.println(doc.getFieldValue("id"));
} catch (Exception e) {
e.printStackTrace();
}