Add group to list using SharePoint 2010 JSOM - sharepoint

Can someone give me an example of adding a SharePoint group to a list using the javascript client object model. I was able to create groups and add them to the site but I haven't seen any documentation on adding the groups to a list? I know how to do this via c# but not javascript.

How to grant permissions for Group in List via CSOM (JavaScript) in SharePoint 2013
The following example demonstrates how to grant Contribute permissions for group Approvers in list:
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var group = web.get_siteGroups().getByName("Approvers");
var roleDef = web.get_roleDefinitions().getByType(SP.RoleType.contributor);
var roleDefBindings = SP.RoleDefinitionBindingCollection.newObject(context);
roleDefBindings.add(roleDef);
list.get_roleAssignments().add(group,roleDefBindings);
list.update();
context.load(group);
context.load(list);
context.load(roleDef);
context.executeQueryAsync(
function () {
console.log('For group ' + group.get_title() + ' has been granted ' + roleDef.get_name() + ' permissons in List ' + list.get_title());
},
function (sender, args) {
console.log("Error: " + args.get_message());
}
);
Since SP.GroupCollection does not contain the method getByName in SharePoint 2010, use the method SP.GroupCollection.getById(id) instead to return Group client object:
var group = web.get_siteGroups().getById(16); //get Approvers group by Id

function getGroupByName(groupName, completeFunction) {
if (groupName == null) {
throw new Error("Group Name cannot be null");
}
var rv = null;
var currentContext = SP.ClientContext.get_current();
var currentWeb = currentWeb = currentContext.get_web();
var allGroups = currentWeb.get_siteGroups();
currentContext.load(allGroups);
currentContext.executeQueryAsync(getGroupByName_Success, getGroupByName_Failed);
function getGroupByName_Success() {
var groupEnumerator = allGroups.getEnumerator();
while (groupEnumerator.moveNext()) {
rv = groupEnumerator.get_current();
var groupTitle = rv.get_title();
if (groupTitle == groupName) {
groupFound = true;
break;
}
}
if (groupFound == false) {
rv = null;
}
completeFunction(rv);
}
function getGroupByName_Failed(sender, args) {
alert("Error Occurred: " + args.get_message() + "\n" + args.get_stackTrace());
}
}

Related

How to change the default values when add link Sharepoint 2013

In Add Link page, is it possible to change the default values like title, address, show these links to, by using URL parameters?
According to this, it seems possible in sharepoint2010. Does anyone know whether it works in 2013??
If not, is it possible to add a link by post REST API??
This problem can be solved by the steps below.
Add a custom action. Just follow the steps here.
In my case code is as below
SP.SOD.executeFunc("callout.js", "Callout", function() {
var itemCtx = {};
itemCtx.Templates = {};
itemCtx.BaseViewID = 'Callout';
// Define the list template type
itemCtx.ListTemplateType = 101;
itemCtx.Templates.Footer = function(itemCtx) {
// context, custom action function, show the ECB menu (boolean)
return CalloutRenderFooterTemplate(itemCtx, AddCustomAction, true);
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
});
function AddCustomAction(renderCtx, calloutActionMenu) {
// Add your custom action
calloutActionMenu.addAction(new CalloutAction({
text: "FAVORITE",
// tooltip: 'This is your custom action',
onClickCallback: function() {
CreateCustomNewQuickLink(renderCtx.CurrentItem.FileLeafRef, renderCtx.CurrentItem.FileRef);
}
}));
// Show the default document library actions
CalloutOnPostRenderTemplate(renderCtx, calloutActionMenu);
}
function CreateCustomNewQuickLink(title, url) {
var urlAddress = $(location).attr('protocol') + "//" + $(location).attr('host') + '/_Layouts/quicklinksdialogformTEST.aspx?Mode=Link' +
'&title=' + encodeURIComponent(title) +
'&url=' + encodeURIComponent(url);
ShowNewQuicklinkPopup(urlAddress, PageRefreshOnDialogClose);
}
Create a new add link page which is copied from "quicklinksdialogform.aspx". I add some javascript as below.
$(init)
function init() {
var args = new Object();
args = GetUrlParms();
if (args["title"] != undefined) {
$(".ms-long")[0].value = decodeURIComponent(args["title"]);
}
if (args["url"] != undefined) {
$(".ms-long")[1].value = decodeURIComponent(args["url"]);
}
}
function GetUrlParms() {
var args = new Object();
var query = location.search.substring(1);
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
var pos = pairs[i].indexOf('=');
if (pos == -1) continue;
var argname = pairs[i].substring(0, pos);
var value = pairs[i].substring(pos + 1);
args[argname] = unescape(value);
}
return args;
}
It works like below

Check if specified user belongs to specific group or not

I posted this question on SharePoint exchange but it did not get any attention. Any help will be appreciated.
I have implemented a site and have added a SharePoint group called "SG_Uploader".
In this group, I ONLY have one Active Directory group called "AD_L6" and there are many users in AD_L6.
If a user comes to site and I want to check if he can upload a document, I use below code which is very simple:
SPWeb web = // ...
SPGroup group = web.SiteGroups["SG_Uploader"];
if (group.ContainsCurrentUser)
{
// allow user to upload
}
Now, I want to do the same thing, not for current user but for a specific user that I have his username. By that mean I want to write a code like
SPWeb web = // ...
SPGroup group = web.SiteGroups["SG_Uploader"];
if (group.ContainsUser(username))
{
// allow user to upload
}
I could not figure out who I can do that. Please advise.
The following code for your reference.
var username = "user1";
var spGroupName = "SG_Uploader";
var adGroupName = "AD_L6";
using (SPSite spSite = new SPSite("http://sp2013/sites/team/"))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
SPUser user = spWeb.EnsureUser(adGroupName);
if (user.Groups.Cast<SPGroup>().Any(g => g.Name.Equals(spGroupName)))
{
var principalContext = new PrincipalContext(ContextType.Domain);
var group = GroupPrincipal.FindByIdentity(principalContext, adGroupName);
var isGroupMember = group.Members.Any(x => x.Name == username);
if (isGroupMember)
{
Console.WriteLine("User " + username + " is a member of group " + spGroupName);
}
else
{
Console.WriteLine("User " + username + " is not a member of group "+spGroupName);
}
}
}
}
You can do that.
string userName = "PERSEUS\\dmitry.kaloshin";
string groupName = "Home Members";
using (SPSite spSite = new SPSite("http://perseus"))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
SPUser user = spWeb.EnsureUser(userName);
if (user.Groups.Cast<SPGroup>().Any(g => g.Name.Equals(groupName)))
{
Console.WriteLine("User " + userName + " is a member of group " + groupName);
}
else
{
Console.WriteLine("User " + userName + " is NOT a member of group " + groupName);
}
}
}
Visit https://social.msdn.microsoft.com/Forums/office/en-US/65066c08-9924-4935-9bba-f715b75d3fac/how-to-check-if-user-exists-in-a-particular-sharepoint-group-or-not-programatically?forum=sharepointdevelopmentprevious

Why am I unable to list all my accounts with this code?

This is my first foray into Google Analytics. I created a service account and downloaded the p12 file from the developer console.
This code works, but in an incomplete way.
I have two accounts, but the code below just returns one account from the list.
How do I get all my accounts listed?
private static ServiceAccountCredential Run2()
{
const string keyfilePath = "file.p12";
const string serviceAccountMail = "notarealemailaddress#developer.gserviceaccount.com";
var certificate = new X509Certificate2(keyfilePath, "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountMail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics, AnalyticsService.Scope.AnalyticsReadonly, AnalyticsService.Scope.AnalyticsProvision }
}.FromCertificate(certificate));
return credential;
}
static void Main()
{
var cr = Run2();
var service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = cr,
ApplicationName = "Analytics API Sample"
});
var request = service.Management.Accounts.List();
request.MaxResults = 20;
var result = request.Execute();
foreach (var item in result.Items)
{
Console.WriteLine("Account Name: {0} {1} {2}", item.Name, item.Kind, item.Id);
}
}
This is what I ended up doing. The service account that Google creates needs to be added to every account that you need to access. I figured this from reading the documentation.
https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/service-py
Try this out
ManagementResource.AccountSummariesResource.ListRequest list = service.Management.AccountSummaries.List();
list.MaxResults = 1000; // Maximum number of Account Summaries to return per request.
AccountSummaries feed = list.Execute();
List allRows = new List();
//// Loop through until we arrive at an empty page
while (feed.Items != null)
{
allRows.AddRange(feed.Items);
// We will know we are on the last page when the next page token is
// null.
// If this is the case, break.
if (feed.NextLink == null)
{
break;
}
// Prepare the next page of results
list.StartIndex = feed.StartIndex + list.MaxResults;
// Execute and process the next page request
feed = list.Execute();
}
feed.Items = allRows;
//Get account summary and display them.
foreach (AccountSummary account in feed.Items)
{
// Account
Console.WriteLine("Account: " + account.Name + "(" + account.Id + ")");
foreach (WebPropertySummary wp in account.WebProperties)
{
// Web Properties within that account
Console.WriteLine("\tWeb Property: " + wp.Name + "(" + wp.Id + ")");
//Don't forget to check its not null. Believe it or not it could be.
if (wp.Profiles != null)
{
foreach (ProfileSummary profile in wp.Profiles)
{
// Profiles with in that web property.
Console.WriteLine("\t\tProfile: " + profile.Name + "(" + profile.Id + ")");
}
}
}
}
Reference: http://www.daimto.com/googleanalytics-management-csharp/
http://www.daimto.com/googleAnalytics-authentication-csharp/

Need Help: Account Name on Contact Phone Call

I am new to CRM and have been able to figure out everything up to now. I have read so many post and internet post and tried them. I have watched some many videos. It seems it should be easy. The contact record has the ParentCustomerID, and ParentCustomerName that holds the account if there is one associated. Now I am just totally confused on the required steps.
Requirement: - I need Account Name to be displayed on the contact level phone call form and saved in phone call table so that it can be visible in the phone call view.
I have in Phone Call N:1 Relationship field str_companyid (lookup) primary Entity is Account with Referential behavior.
I tried a Phone Call N:1 Relationship field new_companystring (lookup) primary Entity is Contact with Referential behavior. I came to the conclusion that this is not a valid approach. Let me know if incorrect.
Do I need a N:N instead?
I have added the str_companyid field to the form. I went to the "Create a phone call for a contact" workflow process. On the "Create PhoneCall" step I have added the dynamic field {Company(Contact)}. After save and publishes; I created a phone call and it isn't populated.
I have tried different Web Resource JS. I have added the JS in the onload of the form properties.
Why doesn't something as easy as this work? I can't seem to get the retrieveRecord to work. I have also tried the xmlHttpObject object but it returns 0.
Can someone help assist me on what I am missing? What are the complete steps to accomplish this?
![I have screenshots below and the code I was running][1]
function PopulateCompanyName()
{
//get group GUID
if (Xrm.Page.getAttribute("to").getValue()[0].id != null) {
var lookup = Xrm.Page.getAttribute("to").getValue();
alert(lookup[0].id);
alert(lookup[0].typename);
alert(lookup[0].name);
alert(lookup);
SDK.JQuery.retrieveRecord(lookup[0].id,
lookup[0].typename,
"ParentCustomerID",
null,
function (lookup) {
Xrm.Page.getAttribute("Company").setValue(lookup[0].str_companyid);
});
}
else {
Xrm.Page.getAttribute("str_companyid").setValue(null);
}
}
function GetCompany()
///Get lookup ID
{
alert("I am Here");
var lookupfield = Xrm.Page.getAttribute("to").getValue();
if (lookupfield != null && lookupfield [0] != null)
{
var householdlookupvalue = lookupfield [0].id;
}
else
{
var householdlookupvalue = " ";
}
alert("I am here2");
alert(householdlookupvalue);
}
// Prepare variables for a contact to retrieve.
var authenticationHeader = Xrm.Page.context.getAuthenticationHeader();
// Prepare the SOAP message.
var xml = ""+
""+
authenticationHeader+
""+
""+
"contact"+
""+lookupfield [0].id+""+
""+
""+
"parentcustomerid"+
""+
""+
""+
""+
"";
alert(xml );
// Prepare the xmlHttpObject and send the request.
var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xHReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xHReq.setRequestHeader("Content-Length", xml.length);
xHReq.send(xml);
// Capture the result.
var resultXml = xHReq.responseXML;
alert("at results");
var errorCount = resultXml.selectNodes('//error').length;
alert("errorCount " + errorCount); ////////////////////////////////////returns 0; it shouldn't
alert("After the result XML "+resultXml .toString() + " ::::");
// Check for errors.
var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0)
{
}
// Display the retrieved value.
else
{
//Create an array to set as the DataValue for the lookup control.
var lookupData = new Array();
//Create an Object add to the array.
var lookupItem= new Object();
//Set the id, typename, and name properties to the object.
lookupItem.id = resultXml.selectSingleNode("//q1:parentcustomerid").nodeTypedValue;
lookupItem.entityType = 'account';
lookupItem.name = resultXml.selectSingleNode("//q1:parentcustomerid").getAttribute("name");
// Add the object to the array.
lookupData[0] = lookupItem;
alert(lookupitem.name)
// Set the value of the lookup field to the value of the array.
Xrm.Page.getAttribute("str_companyid").setValue(lookupData);
}
var contact = new Array();
contact = Xrm.Page.getAttribute("to").getValue();
alert("I am here");
alert(contact);
if (contact == null || contact[0].entityType != "contact" || contact.length > 1) {
return;
}
alert("inside if")
var serverUrl = Xrm.Page.context.getClientUrl();
var oDataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc/ContactSet?$select=ParentCustomerId&$filter=ContactId eq guid'" + contact[0].id + "'";
var retrieveReq = new XMLHttpRequest();
retrieveReq.open("GET", oDataSelect, false);
retrieveReq.setRequestHeader("Accept", "application/json");
retrieveReq.setRequestHeader("Content-Type", "application/json;charset=utf-8");
retrieveReq.onreadystatechange = function () {
GetContactData(this);
};
retrieveReq.send();
}
I replied in the other forum but I post here as reference and with more technical details.
The to attribute of phonecall entity is a partylist type, this means that it can handle several records from different entities. In your case you want to get the Parent Account (field parentcustomerid) if a contact is inside the to field.
Your first code contains same typo and use the msdn Retrieve example, the second code uses CRM 4.0 endpoints, they are still supported inside CRM 2011, but it's better to avoid them so you can use the REST endpoint instead of the SOAP one.
a working code in your case can be:
function setToParentAccount() {
// set only if to Field (Recipient) has 1 record and is a contact
if (Xrm.Page.getAttribute("to").getValue() != null) {
var recipient = Xrm.Page.getAttribute("to").getValue();
if (recipient.length == 1 && recipient[0].entityType == "contact") {
var contactId = recipient[0].id;
var serverUrl;
if (Xrm.Page.context.getClientUrl !== undefined) {
serverUrl = Xrm.Page.context.getClientUrl();
} else {
serverUrl = Xrm.Page.context.getServerUrl();
}
var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
var contactRequest = new XMLHttpRequest();
contactRequest.open("GET", ODataPath + "/ContactSet(guid'" + contactId + "')", false);
contactRequest.setRequestHeader("Accept", "application/json");
contactRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
contactRequest.send();
if (contactRequest.status === 200) {
var retrievedContact = JSON.parse(contactRequest.responseText).d;
var parentAccount = retrievedContact.ParentCustomerId;
if (parentAccount.Id != null && parentAccount.LogicalName == "account") {
var newParentAccount = new Array();
newParentAccount[0] = new Object();
newParentAccount[0].id = parentAccount.Id;
newParentAccount[0].name = parentAccount.Name;
newParentAccount[0].entityType = parentAccount.LogicalName;
Xrm.Page.getAttribute("str_companyid").setValue(newParentAccount);
} else {
Xrm.Page.getAttribute("str_companyid").setValue(null);
}
} else {
alert("error");
}
} else {
Xrm.Page.getAttribute("str_companyid").setValue(null);
}
}
}
to be called inside OnLoad event and OnChange event of the to field.

SP list item - disable "Edit" for all users except for the item creator but still leave a single column editable for all users

Is it possible to use Item-level Permissions in SP 2013 to disable other users modifying items not created by them but still allow them to modify a single field (column) from that item?
I want everyone to be able to input information in that column after clicking "Edit" item button but yet not able to modify any other field if the item is not created by him.
Only the item creator should be able to modify all the fields.
Any ideas how to achieve that are more than welcome :)
You could use client object model for the same as follows:
$(document).ready(function () {
if(CheckCreatedBy() != GetCurrentUser())
{
$("input[Title='EditableByAllUsers']").prop("disabled", true);
}
});
function CheckCreatedBy()
{
var clientContext = new SP.ClientContext.get_current();
var siteColl = clientContext.get_site();
var oList = siteColl.get_rootWeb().get_lists().getByTitle('ChangeEditForm');
var itemId = _spGetQueryParam('id') ;
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ID\'/>' +
'<Value Type=\'Number\'>'+ itemId +'</Value></Eq></Where></Query></View>');
this.collListItem= oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this,this.onCheckCreatedBySuccessMethod), Function.createDelegate(this, this.onCheckCreatedByFailureMethod));
return this.value;
}
function onCheckCreatedBySuccessMethod(sender, args)
{
var CreatedBy = '';
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
CreatedBy = oListItem.get_item('Author').get_lookupValue();
alert(CreatedBy);
return CreatedBy ;
}
}
function onCheckCreatedByFailureMethod(sender, args)
{
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
function GetCurrentUser()
{
var ClientContext = new SP.ClientContext.get_current();
this.CurrentWeb = ClientContext.get_web();
ClientContext.load(this.CurrentWeb.get_currentUser());
ClientContext.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod));
return this.value;
}
function onSuccessMethod(sender, args)
{
var userObject =this.CurrentWeb.get_currentUser().get_title();
return userObject;
}
function onFailureMethod(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
It can also be done using XSL. This will help you with the same.
I hope this helps.

Resources