Showing posts with label CRM 2011. Show all posts
Showing posts with label CRM 2011. Show all posts

Tuesday, July 28, 2015

CRM 2011/2013/2015 Javascript: Get Logged in User Full Name

CRM 2011

 function getUserFullName() {  
   var serverUrl = getCrmServerUrl();  
   var userRequest = GetRequestObject();  
   userRequest.open("GET", serverUrl + "/SystemUserSet(guid'" + Xrm.Page.context.getUserId() + "')?$select=FullName", false);  
   userRequest.setRequestHeader("Accept", "application/json");  
   userRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");  
   userRequest.send();  
   if (userRequest.status === 200) {  
     var retrievedUser = JSON.parse(userRequest.responseText).d;  
     var userFullName = retrievedUser.FullName;  
     return userFullName;  
   }  
   else {  
     return "";  
   }  
 }  
 function getCrmServerUrl() {  
   if (Xrm.Page.context.getClientUrl) // CRM 2011 UR 12+ and CRM 2013  
   {  
     serverUrl = Xrm.Page.context.getClientUrl() + "/";  
   }  
   else // CRM 2011 UR 11 or below  
   {  
     serverUrl = Xrm.Page.context.getServerUrl();  
   }  
   // Adjust URL for differences between on premise and online  
   if (serverUrl.match(/\/$/)) {  
     serverUrl = serverUrl.substring(0, serverUrl.length - 1);  
   }  
   return serverUrl + "/XRMServices/2011/OrganizationData.svc";  
 }  
 function GetRequestObject() {  
   if (window.XMLHttpRequest) {  
     return new window.XMLHttpRequest;  
   }  
   else {  
     try {  
       return new ActiveXObject("MSXML2.XMLHTTP.3.0");  
     }  
     catch (ex) {  
       return null;  
     }  
   }  
 }  


CRM 2013/2015

Xrm.Page.context.getUserName()

Thursday, June 18, 2015

CRM 2011 Quick Find Search results grid not showing header data

We have faced an issue with quick search not showing header data. fields are visible but data is not visible in the grid.

We have a Quote OOB entity and Quote Part which is a custom entity and has 1:N relationship with Quote

In the main navigation we have the quote part entity displayed under sales.

When we initially open the quote part entity grid it shows all the fields of quote and quote part with all the data visible.

Once i search with one of the quote part field it shows the NO OF RESULTS correctly but it returns the Quote related fileds empty.

After log of research and trail and error method we have found that the Quick find configuration has a problem.

No Fields were selected in Quote part quick find (Find Fields)  After we select the few fields in the FIND COLUMNS it started returning the data for the Quote attributes. Weird but true.

This is no where documented in SDK. So thought it will be helpful for anyone else who face the same issue

Here are the screenshots showing the error






Wednesday, July 10, 2013

Retrieving N:N related records using fetchxml




Using the intermediate table in the fetch xml we can easily retreive the N:N records using fetch xml

Tuesday, April 24, 2012

Using JQuery and Json in Ribbon button’s function handler(Include JS files in Ribbon Button Script)


  • In one of my CRM 2011 requirement, I had to update a record using ribbon button placed on CRM grid.
  • I had written an update script which calls OData service using Json & JQuery. (link)
  • But when I execute the function, I got “$ undefined” exception.
  • I wondered since I already had “Json.js” & “JQuery.js” web resources added to my entity.
  • After digging deeper, I came to know that, “JQuery.js” web resource is not getting loaded when my ribbon button’s function handler fired.
Fix :-
  • I fixed the problem by loading “JQuery.js” web resource dynamically, before I call my update method.
  • Below is the script to load the web resource’s


 var JScriptWebResourceUrl = “../WebResources/new_JQuery”;
var xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
xmlHttp.open(“GET”, JScriptWebResourceUrl, false);
xmlHttp.send();
eval(xmlHttp.responseText);

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;
        }

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;
}

Thursday, July 21, 2011

Page Large Result Sets with FetchXML

int fetchCount = 5000;
// Initialize the page number.
int pageNumber = 1;
string pagingCookie = null;
string fetchXml = Common.GetFetchXmlForComponentInfo(((EntityReference)entity.Attributes["neu_whatifmodelid"]).Id.ToString(), fiscalyear.ToString());
while (true)
{
string xml = Common.CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount);
componentinfocollection = service.RetrieveMultiple(new FetchExpression(xml));
foreach (var c in componentinfocollection.Entities)
{
yearlyinfo.Add(
new ComponentYearlyInformation
{
ComponentId = c.Attributes.Contains("neu_componentid") ? ((EntityReference)c.Attributes["neu_componentid"]).Id : Guid.Empty,
name = c.Attributes.Contains("neu_name") ? (string)c.Attributes["neu_name"] : string.Empty,
YearlyExpenditure = c.Attributes.Contains("neu_yearlyexpenditure") ? (decimal)c.Attributes["neu_yearlyexpenditure"] : 0,
FullyFundedAmount = c.Attributes.Contains("neu_fullyfundedamount") ? (decimal)c.Attributes["neu_fullyfundedamount"] : 0
}
);


}

if (componentinfocollection.MoreRecords)
{
// Increment the page number to retrieve the next page.
pageNumber++;
pagingCookie = componentinfocollection.PagingCookie;
}
else
{
// If no more records in the result nodes, exit the loop.
break;
}

}


public static string CreateXml(string xml, string cookie, int page, int count)
{
StringReader stringReader = new StringReader(xml);
XmlTextReader reader = new XmlTextReader(stringReader);

// Load document
XmlDocument doc = new XmlDocument();
doc.Load(reader);

return CreateXml(doc, cookie, page, count);
}

public static string CreateXml(XmlDocument doc, string cookie, int page, int count)
{
XmlAttributeCollection attrs = doc.DocumentElement.Attributes;

if (cookie != null)
{
XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");
pagingAttr.Value = cookie;
attrs.Append(pagingAttr);
}

XmlAttribute pageAttr = doc.CreateAttribute("page");
pageAttr.Value = System.Convert.ToString(page);
attrs.Append(pageAttr);

XmlAttribute countAttr = doc.CreateAttribute("count");
countAttr.Value = System.Convert.ToString(count);
attrs.Append(countAttr);

StringBuilder sb = new StringBuilder(1024);
StringWriter stringWriter = new StringWriter(sb);

XmlTextWriter writer = new XmlTextWriter(stringWriter);
doc.WriteTo(writer);
writer.Close();

return sb.ToString();
}


Reference : http://msdn.microsoft.com/en-us/library/gg309717.aspx

Thursday, June 9, 2011

Setting Attribute from javascript


Xrm.Page.getControl("neu_yearstart").setDisabled(false);
Xrm.Page.getAttribute("neu_yearstart").setValue(FiscalYearStart);
Xrm.Page.getAttribute("neu_yearstart").setSubmitMode("always");
Xrm.Page.getControl("neu_yearstart").setDisabled(true);


setSubmitMode as always will save the values to the database . if this value is not set then the value is not saved to the database but it will be visible in the front end

for example on change of one field you are setting other field then on the UI you can see the value as changed but when the user hits the save button the value is not saved to the database.


Saturday, June 4, 2011

Hide Custom Button when form is in create mode


 <RibbonDiffXml>
        <CustomActions>
          <CustomAction Id="org.button.Form.CustomAction" Location="Mscrm.Form.account.MainTab.Save.Controls._children" Sequence="1">
            <CommandUIDefinition>
              <Button Id="org.button.Form.WhatifButton" Command="org.button.Command" LabelText="What If Analysis" ToolTipTitle="Launch" ToolTipDescription="tooltip" TemplateAlias="o1" Image16by16="$webresource:neu_button16x16" Image32by32="$webresource:neu_button32x32" />
            </CommandUIDefinition>
          </CustomAction>
        </CustomActions>
        <Templates>
          <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
        </Templates>
        <CommandDefinitions>
          <CommandDefinition Id="org.button.Command">
            <EnableRules>
              <EnableRule Id="org.account.WebClient.EnableRule" />
            </EnableRules>
            <DisplayRules>
              <DisplayRule Id="org.account.WebClient.DisplayRule" />
            </DisplayRules>
            <Actions>
              <Url Address="$webresource:helloworld.html" PassParams="true" WinMode="0" WinParams="width=1100,height=760,toolbar=no,location=no,resizable =yes" />
            </Actions>
          </CommandDefinition>
        </CommandDefinitions>
        <RuleDefinitions>
          <TabDisplayRules />
          <DisplayRules>
            <DisplayRule Id="org.account.WebClient.DisplayRule">
              <FormStateRule State="Create"
                              InvertResult="true" />
            </DisplayRule>
          </DisplayRules>
          <EnableRules >
            <EnableRule Id="org.account.WebClient.EnableRule">
              <CrmClientTypeRule Type="Web" />
            </EnableRule>
          </EnableRules>
        </RuleDefinitions>
        <LocLabels />
      </RibbonDiffXml>

Add a custom button to entity ribbon



<RibbonDiffXml>
  <CustomActions>
    <CustomAction Id="org.button.Form.CustomAction" Location="Mscrm.Form.account.MainTab.Save.Controls._children" Sequence="1">
      <CommandUIDefinition>
        <Button Id="org.button.Form.WhatifButton" Command="org.button.Command" LabelText="What If Analysis" ToolTipTitle="Launch" ToolTipDescription="30 Years What If Analysis" TemplateAlias="o1" Image16by16="$webresource:neu_button16x16" Image32by32="$webresource:neu_button32x32" />
      </CommandUIDefinition>
    </CustomAction>
  </CustomActions>
  <Templates>
    <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
  </Templates>
  <CommandDefinitions>
    <CommandDefinition Id="org.button.Command">
      <EnableRules>
      </EnableRules>
      <DisplayRules>
      </DisplayRules>
      <Actions>
        <Url Address="$webresource:helloworld.html" PassParams="true" WinMode="0" WinParams="width=1100,height=760,toolbar=no,location=no,resizable =yes" />
      </Actions>
    </CommandDefinition>
  </CommandDefinitions>
  <RuleDefinitions>
    <TabDisplayRules />
    <DisplayRules/>
    <EnableRules />
  </RuleDefinitions>
  <LocLabels />
</RibbonDiffXml>

Wednesday, June 1, 2011

Get CRM 2011 CrmSvcUtil.exe and the Plugin Registration Tool to Work With WIF on Windows XP

Microsoft Dynamics CRM 2011 makes heavy use of the new Windows Identity Framework.   This been heavily integrated into most of the tools out there for development with the CRM 2011 platform.  This includes CrmSvcUtil.exe and the new plugin / plug-in registration tool.  This also presents a headache for anyone who would like to do any development for CRM 2011 with a Windows XP machine as WIF will not install on an XP machine.  You need to have Vista SP1+, Windows 7, or Windows Server.

It seems that there is an "unsupported" workaround for this.

1. If you were to happen to navigate to the following folder (C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation) on a supported machine that has the Windows Identity Framework (WIF) already installed you might find some assemblies in the directory structure and it's sub folders.

There are four assemblies in my installation:
- Microsoft.IdentityModel.dll
- Microsoft.IdentityModel.resources.dll
- Microsoft.IdentityModel.WindowsTokenService.dll
- Microsoft.IdentityModel.WindowsTokenService.resources.dll

2. If you were to happen to (accidentally of course) copy these assemblies and move them to the same folder as the CrmSvcUtil.exe file or the executable for the Plugin Registration Tool, they will function normally without needing to install the whole WIF framework package.

To build the plugin registration tool you just copy the 4 assemblies from that folder structure to the bin\debug folder and build the tool using Visual Studio.   It then functions normally.

Here is an example from the forums where someone has gotten this to work for CrmSvcUtil, and I have personally done this for the Plugin Registration Tool.  You will also notice that I was the naysayer in the thread at the time :)
http://social.microsoft.com/Forums/en/crmdevelopment/thread/8d8bd121-a34c-402d-86fd-b3c47709a0b4

I hope this helps!