OpenNTF XSnippets - Code Snippets for IBM XPages Development: "myObjectArray.sortByField("name");"
'via Blog this'
Wednesday, February 29, 2012
Tuesday, February 28, 2012
Get User Security Roles in Jscript
function GetAllSystemRoles() {
var serverUrl = Xrm.Page.context.getServerUrl();
var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += "RoleSet";
var service = GetRequestObject();
if (service != null) {
service.open("GET", oDataEndpointUrl, false);
service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
service.setRequestHeader("Accept", "application/json, text/javascript, */*");
service.send(null);
var requestResults = eval('(' + service.responseText + ')').d;
return requestResults;
}
}
function GetRoleIdByName(allsecurityRoles,rolename) {
if (allsecurityRoles != null && allsecurityRoles.results.length > 0) {
for (var i = 0; i < allsecurityRoles.results.length; i++) {
var role = allsecurityRoles.results[i];
if (role.Name == rolename) {
id = role.RoleId;
return id;
}
}
}
return null;
}
function UserHasRole(allsecurityRoles) {
debugger;
var nsrApprovedPrivilage = new Array("Pricing Analyst", "TSC", "Pricing Team manager", "TSC Manager", "Sales Manager - Direct", "Sales Manager - Telesales", "Sales Manager - Winback", "General Manager - Direct", "TSM");
for (var j = 0; j < nsrApprovedPrivilage.length; j++) {
var id = GetRoleIdByName(allsecurityRoles, nsrApprovedPrivilage[j]);
var currentUserRoles = Xrm.Page.context.getUserRoles();
for (var i = 0; i < currentUserRoles.length; i++) {
var userRole = currentUserRoles[i];
if (GuidsAreEqual(userRole, id)) {
return true;
}
}
}
return false;
}
function GetRequestObject() {
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
}
else {
try {
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch (ex) {
return null;
}
}
}
function GuidsAreEqual(guid1, guid2) {
var isEqual = false;
if (guid1 == null || guid2 == null) {
isEqual = false;
}
else {
isEqual = guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase();
}
return isEqual;
}
function CheckIfUserCanApprove() {
debugger;
var hasPrivilagesToApprove = UserHasRole(GetAllSystemRoles());
if (hasPrivilagesToApprove) {
alert("hasPrivilagesToApprove");
}
else {
alert("does not have hasPrivilagesToApprove");
}
}
Add the list of security roles in nsrApprovedPrivilage array to check if user has that particular role
Monday, February 20, 2012
CRM 2011 Convert EntityCollection to DataTable
public DataTable convertEntityCollectionToDataTable(EntityCollection BEC)
{
DataTable dt = new DataTable();
int total = BEC.Entities.Count;
for (int i = 0; i < total; i++)
{
DataRow row = dt.NewRow();
Entity myEntity = (Entity)BEC.Entities[i];
var keys= myEntity.Attributes.Keys;
foreach (var item in keys)
{
string columnName = item;
string value = getValuefromAttribute(myEntity.Attributes[item]);
if (dt.Columns.IndexOf(columnName) == -1)
{
dt.Columns.Add(item, Type.GetType("System.String"));
}
row[columnName] = value;
}
dt.Rows.Add(row);
}
return dt;
}
private string getValuefromAttribute(object p)
{
if (p.ToString() == "Microsoft.Xrm.Sdk.EntityReference")
{
return ((EntityReference)p).Name;
}
if (p.ToString() == "Microsoft.Xrm.Sdk.OptionSetValue")
{
return ((OptionSetValue)p).Value.ToString();
}
if (p.ToString() == "Microsoft.Xrm.Sdk.Money")
{
return ((Money)p).Value.ToString();
}
if (p.ToString() == "Microsoft.Xrm.Sdk.AliasedValue")
{
return ((Microsoft.Xrm.Sdk.AliasedValue)p).Value.ToString();
}
else
{
return p.ToString();
}
}
Tuesday, February 7, 2012
code that can retrieve total number of your desired entity
code that can retrieve total number of your desired entity and return this as int
///
/// Gets the supplied entity count from CRM 2011.
///
/// "Service">The CRM 2011 service.
/// "EntityName">Name of the entity we need get count of.
/// "ServicePageSize">Size of the page (optional).
///
private int GetEntityCount(IOrganizationService Service, string EntityName, int ServicePageSize = 5000)
{
RetrieveMultipleResponse retrieved;
int PageNumber = 1;
string PagingCookie = string.Empty;
int PageSize = ServicePageSize;
do {
QueryExpression query = new QueryExpression() {
EntityName = EntityName,
//ColumnSet = new ColumnSet(Columns),
PageInfo = new PagingInfo() {
PageNumber = 1,
Count = PageSize
}
};
if (PageNumber != 1) {
query.PageInfo.PageNumber = PageNumber;
query.PageInfo.PagingCookie = PagingCookie;
}
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
retrieved = (RetrieveMultipleResponse)Service.Execute(retrieve);
if (retrieved.EntityCollection.MoreRecords) {
PageNumber++;
PagingCookie = retrieved.EntityCollection.PagingCookie;
}
} while (retrieved.EntityCollection.MoreRecords);
return ((PageNumber - 1) * PageSize) + retrieved.EntityCollection.Entities.Count;
}
Monday, February 6, 2012
Get User Security Roles
private EntityCollection GetUserSecurityRole(Guid userGuid, IOrganizationService service)
{
var query = new QueryExpression
{
LinkEntities =
{
new LinkEntity
{
LinkFromEntityName = "role",
LinkFromAttributeName = "roleid",
LinkToEntityName = "systemuserroles",
LinkToAttributeName = "roleid",
LinkCriteria = new FilterExpression
{
FilterOperator =LogicalOperator.And,
Conditions =
{
new ConditionExpression
{
AttributeName = "systemuserid",
Operator = ConditionOperator.Equal,
Values =
{
userGuid
}
}
}
}
}
},
ColumnSet = new ColumnSet(true),
EntityName = "role"
};
var userRoles = service.RetrieveMultiple(query);
return userRoles;
}
Monday, January 23, 2012
How to get access privilages for a user on a particular record
RetrievePrincipalAccessRequest req = new RetrievePrincipalAccessRequest();
//specify team or systemuser you want to get privileges for
req.Principal = new EntityReference("team", teamId);
//specify the CRM record you want to check principal permissions for (can be any entity type)
req.Target = new EntityReference("account", accountid);
RetrievePrincipalAccessResponse resp = (RetrievePrincipalAccessResponse)service.Execute(req);
return resp.AccessRights.ToString();
//specify team or systemuser you want to get privileges for
req.Principal = new EntityReference("team", teamId);
//specify the CRM record you want to check principal permissions for (can be any entity type)
req.Target = new EntityReference("account", accountid);
RetrievePrincipalAccessResponse resp = (RetrievePrincipalAccessResponse)service.Execute(req);
return resp.AccessRights.ToString();
Tuesday, October 18, 2011
CRM 2011 Get OptionSetValue Label Text
In CRM 2011, when you try to get the value of an OptionSet, you will always get an Integer value instead of the label value.
Below is the Helper method which is used to retrieve the label of the selected option set
public static string GetOptionSetValueLabel(IOrganizationService service, Entity entity, string attribute, OptionSetValue option)
{
string optionLabel = String.Empty;
RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = entity.LogicalName,
LogicalName = attribute,
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest);
AttributeMetadata attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata;
PicklistAttributeMetadata picklistMetadata = (PicklistAttributeMetadata)attrMetadata;
// For every status code value within all of our status codes values
// (all of the values in the drop down list)
foreach (OptionMetadata optionMeta in
picklistMetadata.OptionSet.Options)
{
// Check to see if our current value matches
if (optionMeta.Value == option.Value)
{
// If our numeric value matches, set the string to our status code
// label
optionLabel = optionMeta.Label.UserLocalizedLabel.Label;
}
}
return optionLabel;
}
Below is the Helper method which is used to retrieve the label of the selected option set
public static string GetOptionSetValueLabel(IOrganizationService service, Entity entity, string attribute, OptionSetValue option)
{
string optionLabel = String.Empty;
RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = entity.LogicalName,
LogicalName = attribute,
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest);
AttributeMetadata attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata;
PicklistAttributeMetadata picklistMetadata = (PicklistAttributeMetadata)attrMetadata;
// For every status code value within all of our status codes values
// (all of the values in the drop down list)
foreach (OptionMetadata optionMeta in
picklistMetadata.OptionSet.Options)
{
// Check to see if our current value matches
if (optionMeta.Value == option.Value)
{
// If our numeric value matches, set the string to our status code
// label
optionLabel = optionMeta.Label.UserLocalizedLabel.Label;
}
}
return optionLabel;
}
Subscribe to:
Posts (Atom)