For implementing a birthday's SharePoint 2013 app I need to get all user profiles from a site collection. For this purpose I'd like to use a (or multiple) client API(s). See http://msdn.microsoft.com/en-us/library/jj163800.aspx#bkmk_APIversions.
Unfortunately I couldn't find in the APIs description an equivalent of Microsoft.Office.Server.UserProfiles. There are in Microsoft.SharePoint.Client.UserProfiles.PeopleManager two methods, GetUserProfilePropertiesFor and GetUserProfilePropertyFor, that only get a single user profile.
So my question is: how to get with CSOM, JSOM, REST (or any client side technology) all user profiles in site collection?
Since CSOM provides methods for operations related to people per user scope, you could retrieve all site users first using SP.Web.siteUsers property. and then use
SP.UserProfiles.PeopleManager.getUserProfilePropertyFor Method to get BirthDay property as demonstrated below:
//Get Birthday User Profile Property for Site Users
function getUsersBirthdays(Success,Error) {
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var users = web.get_siteUsers();
clientContext.load(users);
clientContext.executeQueryAsync(
function() {
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
var personsProperties = [];
for(var i = 0; i < users.get_count();i++)
{
var user = users.getItemAtIndex(i);
var personBirthday = peopleManager.getUserProfilePropertyFor(user.get_loginName(),'SPS-Birthday');
personsProperties.push(personBirthday);
}
clientContext.executeQueryAsync(
function() {
Success(personsProperties);
},
Error);
},
Error);
}
//Usage
var scriptbase = _spPageContextInfo.webAbsoluteUrl + '/_layouts/15/';
$.getScript(scriptbase + 'SP.js', function () {
$.getScript(scriptbase + 'SP.UserProfiles.js', function () {
getUsersBirthdays(function(usersProperties){
for(var i = 0; i < usersProperties.length;i++)
{
console.log(usersProperties[i].get_value());
}
},
function(sender,args){
console.log(args.get_message());
});
});
});
This also should work for SP2013
function GetUsersGroups(){
ClientContext context = new Microsoft.SharePoint.Client.ClientContext("http://SPSite");
GroupCollection groupCollection = context.Web.SiteGroups;
context.Load(groupCollection,
groups = > groups.Include(group = > group.Users));
context.ExecuteQuery();
foreach (Group group in groupCollection)
{
UserCollection userCollection = group.Users;
foreach (User user in userCollection)
{
MessageBox.Show("User Name: " + user.Title + " Email: " + user.Email + " Login: " + user.LoginName);
}
}
//Iterate the owners group
Group ownerGroup = context.Web.AssociatedOwnerGroup;
context.Load(ownerGroup);
context.Load(ownerGroup.Users);
context.ExecuteQuery();
foreach (User ownerUser in ownerGroup.Users)
{
MessageBox.Show("User Name: " + ownerUser.Title + " Email: " + ownerUser.Email + " Login: " + ownerUser.LoginName);
}
context.Dispose();
}
Related
As you can imagine, stripe and authorize.net and other payment gateway services offer an api that can only be hit via server-side for safety reasons. Currently the documentation for Authorize.net allows for me to create an express node app and then run the command node charge-credit-card.js (which works and gets a 200 response from their api) My question is two parts. How do I connect my server directory (aptly named named AuthorizePaymentNode in the image below this paragraph) with my angular src app directory(aptly named named FoodOrderingApp in the image) to gather the card info on the front end so that I may process a credit card from start to finish? Secondly assuming I get it working in development how and where do I upload my AuthorizePaymentNode directory along with my FoodOrderingApp so that the two work together. Do I do it in two separate places as a friend of mine suggested or can it just be done all at once and in one place?
[https://i.stack.imgur.com/ibUDr.png][1]
charge-credit-card.js (works like a charm when running node charge-credit-card.js)
var ApiContracts = require('authorizenet').APIContracts;
var ApiControllers = require('authorizenet').APIControllers;
var SDKConstants = require('authorizenet').Constants;
var utils = require('./utils.js');
var constants = require('./constants.js');
function chargeCreditCard(callback) {
var merchantAuthenticationType = new ApiContracts.MerchantAuthenticationType();
merchantAuthenticationType.setName(constants.apiLoginKey);
merchantAuthenticationType.setTransactionKey(constants.transactionKey);
var creditCard = new ApiContracts.CreditCardType();
creditCard.setCardNumber('4242424242424242');
creditCard.setExpirationDate('0822');
creditCard.setCardCode('999');
var paymentType = new ApiContracts.PaymentType();
paymentType.setCreditCard(creditCard);
var orderDetails = new ApiContracts.OrderType();
orderDetails.setInvoiceNumber('INV-12345');
orderDetails.setDescription('Product Description');
var tax = new ApiContracts.ExtendedAmountType();
tax.setAmount('4.26');
tax.setName('level2 tax name');
tax.setDescription('level2 tax');
var duty = new ApiContracts.ExtendedAmountType();
duty.setAmount('8.55');
duty.setName('duty name');
duty.setDescription('duty description');
var shipping = new ApiContracts.ExtendedAmountType();
shipping.setAmount('8.55');
shipping.setName('shipping name');
shipping.setDescription('shipping description');
var billTo = new ApiContracts.CustomerAddressType();
billTo.setFirstName('Ellen');
billTo.setLastName('Johnson');
billTo.setCompany('Souveniropolis');
billTo.setAddress('14 Main Street');
billTo.setCity('Pecan Springs');
billTo.setState('TX');
billTo.setZip('44628');
billTo.setCountry('USA');
var shipTo = new ApiContracts.CustomerAddressType();
shipTo.setFirstName('China');
shipTo.setLastName('Bayles');
shipTo.setCompany('Thyme for Tea');
shipTo.setAddress('12 Main Street');
shipTo.setCity('Pecan Springs');
shipTo.setState('TX');
shipTo.setZip('44628');
shipTo.setCountry('USA');
var lineItem_id1 = new ApiContracts.LineItemType();
lineItem_id1.setItemId('1');
lineItem_id1.setName('vase');
lineItem_id1.setDescription('cannes logo');
lineItem_id1.setQuantity('18');
lineItem_id1.setUnitPrice(45.00);
var lineItem_id2 = new ApiContracts.LineItemType();
lineItem_id2.setItemId('2');
lineItem_id2.setName('vase2');
lineItem_id2.setDescription('cannes logo2');
lineItem_id2.setQuantity('28');
lineItem_id2.setUnitPrice('25.00');
var lineItemList = [];
lineItemList.push(lineItem_id1);
lineItemList.push(lineItem_id2);
var lineItems = new ApiContracts.ArrayOfLineItem();
lineItems.setLineItem(lineItemList);
var userField_a = new ApiContracts.UserField();
userField_a.setName('A');
userField_a.setValue('Aval');
var userField_b = new ApiContracts.UserField();
userField_b.setName('B');
userField_b.setValue('Bval');
var userFieldList = [];
userFieldList.push(userField_a);
userFieldList.push(userField_b);
var userFields = new ApiContracts.TransactionRequestType.UserFields();
userFields.setUserField(userFieldList);
var transactionSetting1 = new ApiContracts.SettingType();
transactionSetting1.setSettingName('duplicateWindow');
transactionSetting1.setSettingValue('120');
var transactionSetting2 = new ApiContracts.SettingType();
transactionSetting2.setSettingName('recurringBilling');
transactionSetting2.setSettingValue('false');
var transactionSettingList = [];
transactionSettingList.push(transactionSetting1);
transactionSettingList.push(transactionSetting2);
var transactionSettings = new ApiContracts.ArrayOfSetting();
transactionSettings.setSetting(transactionSettingList);
var transactionRequestType = new ApiContracts.TransactionRequestType();
transactionRequestType.setTransactionType(ApiContracts.TransactionTypeEnum.AUTHCAPTURETRANSACTION);
transactionRequestType.setPayment(paymentType);
transactionRequestType.setAmount(utils.getRandomAmount());
transactionRequestType.setLineItems(lineItems);
transactionRequestType.setUserFields(userFields);
transactionRequestType.setOrder(orderDetails);
transactionRequestType.setTax(tax);
transactionRequestType.setDuty(duty);
transactionRequestType.setShipping(shipping);
transactionRequestType.setBillTo(billTo);
transactionRequestType.setShipTo(shipTo);
transactionRequestType.setTransactionSettings(transactionSettings);
var createRequest = new ApiContracts.CreateTransactionRequest();
createRequest.setMerchantAuthentication(merchantAuthenticationType);
createRequest.setTransactionRequest(transactionRequestType);
//pretty print request
console.log(JSON.stringify(createRequest.getJSON(), null, 2));
var ctrl = new ApiControllers.CreateTransactionController(createRequest.getJSON());
//Defaults to sandbox
//ctrl.setEnvironment(SDKConstants.endpoint.production);
ctrl.execute(function(){
var apiResponse = ctrl.getResponse();
var response = new ApiContracts.CreateTransactionResponse(apiResponse);
//pretty print response
console.log(JSON.stringify(response, null, 2));
if(response != null){
if(response.getMessages().getResultCode() == ApiContracts.MessageTypeEnum.OK){
if(response.getTransactionResponse().getMessages() != null){
console.log('Successfully created transaction with Transaction ID: ' + response.getTransactionResponse().getTransId());
console.log('Response Code: ' + response.getTransactionResponse().getResponseCode());
console.log('Message Code: ' + response.getTransactionResponse().getMessages().getMessage()[0].getCode());
console.log('Description: ' + response.getTransactionResponse().getMessages().getMessage()[0].getDescription());
}
else {
console.log('Failed Transaction.');
if(response.getTransactionResponse().getErrors() != null){
console.log('Error Code: ' + response.getTransactionResponse().getErrors().getError()[0].getErrorCode());
console.log('Error message: ' + response.getTransactionResponse().getErrors().getError()[0].getErrorText());
}
}
}
else {
console.log('Failed Transaction. ');
if(response.getTransactionResponse() != null && response.getTransactionResponse().getErrors() != null){
console.log('Error Code: ' + response.getTransactionResponse().getErrors().getError()[0].getErrorCode());
console.log('Error message: ' + response.getTransactionResponse().getErrors().getError()[0].getErrorText());
}
else {
console.log('Error Code: ' + response.getMessages().getMessage()[0].getCode());
console.log('Error message: ' + response.getMessages().getMessage()[0].getText());
}
}
}
else {
console.log('Null Response.');
}
callback(response);
});
}
if (require.main === module) {
chargeCreditCard(function(){
console.log('chargeCreditCard call complete.');
});
}
module.exports.chargeCreditCard = chargeCreditCard;
cart.ts
let total = item.price * item.quantity;
item.options.forEach(option => (total += option.value * item.quantity));
return total;
}
get totalAmount() {
let total = 0;
this.cart.forEach(item => (total += this.getItemTotal(item)));
return total;
}```
[1]: https://i.stack.imgur.com/ibUDr.png
using the accept suite seems to be the most logical answer
I have implemented sharepoint hosted app for getting user level permissions on a list using javascript and rest api.
Here is my code,
'use strict';
var hostweburl;
var appweburl;
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
hostweburl = _spPageContextInfo.siteAbsoluteUrl;
appweburl = _spPageContextInfo.siteServerRelativeUrl;
alert(hostweburl);
alert(appweburl);
getListUserEffectivePermissions();
});
function getListUserEffectivePermissions() {
var listTitle = 'MyList_Deepa';
//var account = 'i%3A0%23.f%7Cmembership%7Cuser%40abhishek#sarasamerica.com&#target=';
var endpointUrl = "'" + appweburl + "'/_api/SP.AppContextSite(#target)/web/lists/getbytitle('" + listTitle + "')/getusereffectivepermissions(#user)?#user='i%3A0%23.f%7Cmembership%7Cuser%40abhishek#sarasamerica.com&#target='" + hostweburl + "'";
//var endpointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + MyList_Deepa + "')/getusereffectivepermissions(#u)?#u='" + encodeURIComponent(account) + "'";;
return $.ajax({
url: endpointUrl,
dataType: 'json',
headers: {
"accep": "application/json;odata=verbose",
"X-RequestDigest": $("#_REQUESTDIGEST").val()
}
});
}
function parseBasePermissions(value) {
var permissions = new SP.BasePermissions();
permissions.initPropertiesFromJson(value);
var permLevels = [];
for (var permLevelName in SP.PermissionKind.prototype) {
if (SP.PermissionKind.hasOwnProperty(permLevelName)) {
var permLevel = SP.PermissionKind.parse(permLevelName);
if (permissions.has(permLevel)) {
permLevels.push(permLevelName);
}
}
}
return permLevels;
}
getListUserEffectivePermissions().done(function (data) {
var roles = parseBasePermissions(data.d.GetUserEffectivePermissions);
console.log(roles);
});
Error: Failed to load resource: the server responded with a status of 404 (Not Found).
Please anybody can give solution to resolve the problem.
Problem: When creating the first document for a user, query takes too long
I'm creating some report, of the schema Report. I also have a UserSchema. I create a document in my UI and pass that data to a post request which is this:
exports.addSubReport = function(req,res) {
var id = req.body.masterform;
var subform = new Report();
var myDate = Date();
subform.title = req.body.title;
subform.date = req.body.date;
subform.date = myDate;
subform.owner = req.user;
subform.body = req.body.body;
subform.save();
Report.findById(id, function (err, report) {
if(err) {
res.redirect('/404NotFound');
}
else {
report.subreport.push(subform);
subform.parentReport = report;
report.save();
}
});
User.findById(req.body.id, function (err, user) {
user.forms_created.push(subform);
subform.owner = req.user;
subform.authors[0] = user.profile.firstName + " " + user.profile.lastName;
subform.author = user;
subform.save();
});
res.json(req.body);
};
this works fine and creates the object the way I want it to, however after creating the document, I set the state in my UI to 'Wait' until I can recieve the JSON with this new Report I just created. This is the GET request code:
exports.allMyReports = function(req, res) {
var id = req.user._id;
var totalproc = 0;
var dupe = [];
Report.find({"author" : id}, function (err, form) {
dupe = form;
dupe.forEach(function (person) {
User.findById(person.author, function (err, user) {
if (!err) {
person.authors[0] = user.profile.firstName + " " + user.profile.lastName;
person.save();
totalproc = totalproc + 1;
}
if (totalproc == dupe.length) {
res.json(dupe);
}
}
);
});
});
};
However the problem is that on every first report I create for a user, it takes an extremely long time. It's most likely the query of searching for it by author but than I thought well.... if the user has 15 documents already how does it even find all those documents instaneously? I have no idea why it takes so long in this case though and I haven't been able to come up with a solution yet but I think it has to do with how I'm querying.
Here is a sample of how i do it in the UI:
_onCreateReport = () => {
const title = React.findDOMNode(this.refs.title).value;
const date = React.findDOMNode(this.refs.date).value;
const body = React.findDOMNode(this.refs.body).value;
ReportsActions.addNewReport({
title: title,
date: date,
body: body
});
ReportsActions.getMyReports();
}
I perform the action of adding a new report ('post' request to API), and then getMyReport 'get' request to api for all reports belonging to me, once that returns it shows a new render of 3 buttons, one to view that document, one to view all my documents, one to create another report.
All I did, was request all the documents, and figure it out in the front-end. It reduced the time of the ajax call and I just filtered it out in my front-end which performs quick and doesn't hold the server up.
I am enumerating all terms using SP.Taxonomy.js JSOM in SharePoint.While enumerating I want to check if currentTerm has children or not.I need some property to check like children count.How can I do this with minimum round trip to server.
I am using following code get taxonomy and it is working fine.
Please help
$(document).ready(function () {
ExecuteOrDelayUntilScriptLoaded(function () {
SP.SOD.registerSod('sp.taxonomy.js', "/_layouts/15/sp.taxonomy.js");
`SP.SOD.executeFunc('sp.taxonomy.js', false, Function.createDelegate(this,`
function () {
var context = SP.ClientContext.get_current();
var taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
var termStore = taxonomySession.get_termStores().getByName("Taxonomy_qeFlDdEX32yZ3Q7EpEIeMQ==");
var termSet = termStore.getTermSet("ed6d3beb-6a49-4444-bc5d-456f747e139d");
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(Function.createDelegate(this, function (sender, args) {
var termsEnumerator = terms.getEnumerator();
var menuItems = new Array();
while (termsEnumerator.moveNext()) {
var currentTerm = termsEnumerator.get_current();
var targetGroups = document.getElementById("selectTaxonomy");
var taxoGroup = document.createElement("option");
taxoGroup.text = currentTerm.get_name();
targetGroups.add(taxoGroup);
}
}), Function.createDelegate(this, function (sender, args) {
alert('The error has occured: ' + args.get_message());
}));
}));
},"sp.js")
});
You could use SP.Taxonomy.Term.termsCount property to get the number of child Term objects, for example:
var termSetId = '--guid goes here--';
getTerms(termSetId,
function(terms){
for(var i = 0;i < terms.get_count();i++){
var term = terms.get_item(i);
var hasChildTerms = (term.get_termsCount() > 0);
//...
}
},
function(sender,args)
{
console.log(args.get_message());
});
where
function getTerms(termSetId,success,error) {
var context = SP.ClientContext.get_current();
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
var termStore = taxSession.getDefaultSiteCollectionTermStore();
var termSet = termStore.getTermSet(termSetId);
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(function () {
success(terms)
},
error);
}
Some recommendations
1) Prefer SP.SOD.loadMultiple function for loading multiple libraries, for example
SP.SOD.registerSod('SP.ClientContext', SP.Utilities.Utility.getLayoutsPageUrl('sp.js'));
SP.SOD.registerSod('SP.Taxonomy.TaxonomySession', SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js'));
SP.SOD.loadMultiple(['SP.ClientContext', 'SP.Taxonomy.TaxonomySession'], function(){
//your code goes here
});
2) Avoid any hard-coding, for example:
/_layouts/15/sp.taxonomy.js -> SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js')
Replace the line:
var termStore = taxonomySession.get_termStores().getByName("Taxonomy_qeFlDdEX32yZ3Q7EpEIeMQ==");
with this one:
var termStore = taxonomySession.getDefaultSiteCollectionTermStore();
Function.createDelegate Function could be avoided in most cases
I havent found a specific example of how to get the current user and then check if it belongs to a specific sharepoint group, as I havent found anything I cant provide a code,
help on the right direction is appreciated.
SharePoint 2013 CSOM
Prerequisites: compatible with SharePoint 2013 CSOM API only since
SP.GroupCollection.getByName Method is not available in
SharePoint 2010
How to check if current user belongs to SharePoint group via CSOM (JavaScript):
function IsCurrentUserMemberOfGroup(groupName, OnComplete) {
var currentContext = new SP.ClientContext.get_current();
var currentWeb = currentContext.get_web();
var currentUser = currentContext.get_web().get_currentUser();
currentContext.load(currentUser);
var allGroups = currentWeb.get_siteGroups();
currentContext.load(allGroups);
var group = allGroups.getByName(groupName);
currentContext.load(group);
var groupUsers = group.get_users();
currentContext.load(groupUsers);
currentContext.executeQueryAsync(OnSuccess,OnFailure);
function OnSuccess(sender, args) {
var userInGroup = false;
var groupUserEnumerator = groupUsers.getEnumerator();
while (groupUserEnumerator.moveNext()) {
var groupUser = groupUserEnumerator.get_current();
if (groupUser.get_id() == currentUser.get_id()) {
userInGroup = true;
break;
}
}
OnComplete(userInGroup);
}
function OnFailure(sender, args) {
OnComplete(false);
}
}
Usage
IsCurrentUserMemberOfGroup("Approvers", function (isCurrentUserInGroup) {
if(isCurrentUserInGroup)
{
//...
}
});
SharePoint 2010/2013 CSOM
function isUserMemberOfGroup(userId, groupId, success,error) {
var ctx = SP.ClientContext.get_current();
var allGroups = ctx.get_web().get_siteGroups();
var group = allGroups.getById(groupId);
ctx.load(group,'Users');
ctx.executeQueryAsync(
function(sender, args) {
var userInGroup = findUserById(group.get_users(),userId);
success(userInGroup);
},
error);
var findUserById = function(users,id){
var found = false;
var e = group.get_users().getEnumerator();
while (e.moveNext()) {
var user = e.get_current();
if (user.get_id() == id) {
found = true;
break;
}
}
return found;
};
}
Usage
var currentUserId = _spPageContextInfo.userId;
var groupId = 4;
isUserMemberOfGroup(currentUserId, groupId,
function (isCurrentUserInGroup) {
if(isCurrentUserInGroup)
console.log('Current user is a member of Owners group');
else
console.log('Current user is not a member of Owners group');
},
function(sender,args){
console.log(args.get_message());
});
Here's a quicker way with SharePoint 2013:
function CheckCurrentUserMembership() {
var clientContext = new SP.ClientContext.get_current();
this.currentUser = clientContext.get_web().get_currentUser();
clientContext.load(this.currentUser);
this.userGroups = this.currentUser.get_groups();
clientContext.load(this.userGroups);
clientContext.executeQueryAsync(OnQuerySucceeded);
}
function OnQuerySucceeded() {
var isMember = false;
var groupsEnumerator = this.userGroups.getEnumerator();
while (groupsEnumerator.moveNext()) {
var group= groupsEnumerator.get_current();
if(group.get_title() == "Administrator Group") {
isMember = true;
break;
}
}
OnResult(isMember);
}
function OnQueryFailed() {
OnResult(false);
}
If anyone is interested. This approach can be used when you want to check if a user is a member of a group using the group name.
var currentUserIsMemberOf = function(groupName){
var found = false;
var dfd = $.Deferred(function(){
SP.SOD.executeOrDelayUntilScriptLoaded(function(){
context = new SP.ClientContext.get_current();
allGroups = context.get_web().get_siteGroups();
context.load(allGroups);
context.load(allGroups, 'Include(Users)');
context.executeQueryAsync(
function(){
var groupsEnumerator = allGroups.getEnumerator();
while (groupsEnumerator.moveNext()) {
var group = groupsEnumerator.get_current();
if(group.get_title() == groupName) {
var usersEnumerator = group.get_users().getEnumerator();
while (usersEnumerator.moveNext()) {
var user = usersEnumerator.get_current();
if(user.get_id() == _spPageContextInfo.userId) {
found = true;
break;
}
}
}
}
dfd.resolve(found);
},
function(){
dfd.reject(args.get_message());
}
);
}, 'sp.js');
});
return dfd.promise();
}
You can use like this
currentUserIsMemberOf("Members of Demo").done(function(result){
alert(result)
});
Note this code use Promise, you can reference jQuery use your own custom Deferred object or remove Deferred object.