How to get Display name of user profile manager property - sharepoint-2013

When I was writing custom display template for SharePoint people search, I wanted to display the manager of the searched user. When I display the manager value returned from SharePoint people search, it displays as follows:
i:0#.f|membership|lpalmer#xyz.com
I want to show the display instead of the account name in my SharePoint display template. Let me know if this can be done either using JavaScript or just by doing some configurations on SharePoint user profile property change.

This cannot be done using just configurations. You will need to query the User Profile Service and get the Display Name using the login name the search service returns.
For obtaining any property you can use something like this:
function getProfilePropertyValueFromLoginName(loginName, propertyName, success, error) {
// Get the current client context and PeopleManager instance.
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
var personProperties = peopleManager.getPropertiesFor(loginName);
// Load the PersonProperties object and send the request.
clientContext.load(personProperties);
clientContext.executeQueryAsync(
function () {
if (success) {
success(loginName, personProperties.get_userProfileProperties()[propertyName]);
}
}, function (sender, args) {
if (error) {
error(sender, args);
}
});
}
-Hope it helps

Related

How to get the ID of the snapshot in cloud functions?

I am using cloud functions to trig when a new document is added to the firestore but I couldn't find online how to get the ID of this document.
this is my code :
exports.sendWelcomeEmail = functions.firestore
.document(`users/{user}`)
.onCreate(async (snap, context) => {
const email = snap.data().userEmail; // The email of the user.
const displayName = snap.data().userName; // The display name of the user.
return sendWelcomeEmail(email, displayName);
});
I need to get the Id from "snap" how can I do that?
You can access particular fields as you would with any JS property, here's the link to the documentation.

Facebook Matching API - Returns empty data for any other user

I have a problem when I use the Facebook Checkbox Plugin in order to connect my users to a Facebook chatbot. When they click and the checkbox is checked, I get their user reference, and sending him/her a message, I get the user page-scoped id.
Using this user page-scoped id, I should be able to get the user app-scoped id, that I need to get more information from this user.
In order to to this, I use the facebook Matching API, and it works great for my administrator user, but as soon as I login using any other user, even if it is registered as a developer, the data that I get from the matching API is empty.
[https://developers.facebook.com/docs/messenger-platform/identity/id-matching]
Anybody has an idea about what could be happening here? My app is live (not approved), and I believe the permissions and tokens are right... If there is a problem, it should be about tokens, but I'm not sure about this.
Here, some of my code:
const accessToken = config.facebook.unlimitedPageAccessToken;
const clientSecret = config.facebook.clientSecret;
const appsecretProof = CryptoJS.HmacSHA256(accessToken, clientSecret).toString(CryptoJS.enc.Hex);
request({
url: 'https://graph.facebook.com/v2.10/'+ recipientId +'/ids_for_apps',
qs: { access_token: accessToken, appsecret_proof: appsecretProof }
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
body = JSON.parse(body);
console.log("data --> " + JSON.stringify(body, null, 4));
const userAppId = body.data[0].id;
return userAppId;
} else {
console.error("Error trying to translate ID's.");
}
});
As I said, when I log in with any other user than the administrator, I get this:
{
"data": []
}
For every Facebook page, a user has a different psid. So until you get that page scoped id, you won't be able to send them a message. So may be what you can do is link the users to the page first to initialize the conversation.

Setting user's email on Facebook signup with Parse.com

I'm using Parse.com and trying to set up user sign up with Facebook.
Upon authentication with Facebook for the first time a beforeSave is called on _User to fetch additional user details:
function UserBeforeSave(request, response){
var user = request.object,
auth = user.get('authData');
// check if user is newly registered
if (!user.existed()) {
// Check if a user signs up with facebook
if (Parse.FacebookUtils.isLinked(request.object)) {
// Query Graph API for user details
Parse.Cloud.httpRequest({
url:'https://graph.facebook.com/v2.2/me?access_token=' + auth.facebook.access_token,
success:function(httpResponse){
// Map facebook data to user object
if (httpResponse.data.first_name) request.object.set('first_name', httpResponse.data.first_name);
if (httpResponse.data.last_name) request.object.set('last_name', httpResponse.data.last_name);
if (httpResponse.data.email) request.object.set('email', httpResponse.data.email);
response.success();
},
error:function(httpResponse){
console.error(httpResponse);
response.error();
}
});
} else {
response.success();
}
} else {
response.success();
}
}
Problem is that that email line is actually breaking the operation with error:
Can't modify email in the before save trigger
I tried moving this code to the afterSave but the authdata is not available there making it difficult to call the FB API. The email is therefore left blank at the moment.
I'm assuming this is a very common use case of integrating Parse with the Facebook API, am I missing something in the integration process that automatically fetches the email?
I just do the graph query client-side and set email there. This works fine.
Is there a reason you want to do it in the before/afterSave on the User?

Retrieving scores with Application Token

So I have an app set up, and I'm trying to send scores via a server rather than from the application. This allows me to keep scores longer term, whilst also having the social advantages of Facebook.
Now, the problem I have comes in retrieving the scores using the Application Token. I can post absolutely fine using either the Application Token or a User Token, but when retrieving the scores with the Application Token I receive the following:
{
"data": [
]
}
If it was flat out not working or a permissions issue I'd expect to receive an error returned, but the fact it returns an empty array is puzzling. More puzzling is that using a User Access Token retrieves the score absolutely fine, so it's clearly arriving correctly into the Facebook backend.
Is this just a problem with using an App Access Token in this situation? The documentation says that I should be able to use one, but maybe it's mistaken?
I'd also like to clarify that I've run this both in code and via the Graph Explorer, always with no success.
Make sure that you have granted user_games_activity and friends_games_activity permissions
on developers.facebook.com/tools/explorer
from above link you will get an application access_token and add it in your code like this
public void sendDataToFacebookGraphServer()
{
// TODO Auto-generated method stub
final Session session = Session.getActiveSession();
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(UnityPlayer.currentActivity, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://graph.facebook.com/user_id/scores");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("score", "3000"));
// add this line and try
pairs.add(new BasicNameValuePair("access_token", "add_app_access_token_here"));
try{
post.setEntity(new UrlEncodedFormEntity(pairs));
}
catch(UnsupportedEncodingException e)
{
}
try{
response = client.execute(post);
Log.i("*********Response*******************************************************", response.toString());
UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(UnityPlayer.currentActivity,""+response.toString(),Toast.LENGTH_LONG).show();
}
});
}
catch (IOException e1)
{
}
}
Is this supposed to work with the app access token? I don't think it is.
According to the Scores Documentation you can
Retrieve a user's score with the user or app access token (/USER_ID/scores)
Retrieve a user's friends' scores for your app with the user access token (/APP_ID/scores)
Retrieve a user's friends' scores in any app with the user access token (/USER_ID/scores) - though this one respects those users' privacy settings so you won't get an answer for users whose game/app activity is private

Call Profile Provider By Name in Profile config

I have a legacy system (sitecore 6.1) which is already have one profile provider in plave as default profile for admin section.
Now, i need to impelement another customised SQL profile provider (in a different table) for normal user.
But my question is How dose system know which profile provider to use in code?
Is there any thing I can do similar as :
System.Web.Security.Membership.Providers[providerString];
So that I can call customised profile provider in my code accordingly.
Or what would be the best practice in this case.
I've wasted like 1 hour try to go through sitecore docs, but not much available there.
Here's some code that I recently did to set up some custom profile stuff for a client using the Email Campaign Manager. Granted this code uses some classes specific to ECM, it creates a new user, initializes a profile class and then assigns that profile to the new user. Then it sets some custom properties for the user that was just created. It shows you how to call the profile based on the user as well as assigning a profile to use for that user. This might help or maybe help someone else.
public static void Process(List<Subscriber> userItems, Item targetAudienceDefinitionItem)
{
foreach (Subscriber user in userItems)
{
// you can also just pass it the id of the target audience as a string
Sitecore.Modules.EmailCampaign.TargetAudienceBase target = Sitecore.Modules.EmailCampaign.TargetAudience.FromItem(targetAudienceDefinitionItem);
string campaignname = target.ManagerRoot.Settings.CommonDomain;
string realUsername = campaignname + "\\" + user.UserName;
using (new SecurityDisabler())
{
User newUser;
if (!Sitecore.Security.Accounts.User.Exists(realUsername))
{
// create a new user and assign it to the email domain specified in the manager root item
newUser = Sitecore.Security.Accounts.User.Create(campaignname + "\\" + user.UserName, System.Web.Security.Membership.GeneratePassword(8,1));
}
else
// get back the existing user
newUser = User.FromName(realUsername, false);
// get back the current user profile
UserProfile subscriber = newUser.Profile;
// reset the profile to be the profile specified in the manager root
subscriber.ProfileItemId = target.ManagerRoot.Settings.SubscriberProfile;
subscriber.Save();
// built in properties are set like this
subscriber.Email = user.Email;
// set custom property value
subscriber["Address"] = user.Address;
// or long method
subscriber.SetCustomProperty("Address", user.Address);
subscriber.Save();
// now subscribe the user to the target audience subscriber list
target.Subscribe(Contact.FromName(newUser.Name));
}
}
}