Sample code to retrieve more than 5000 records using FetchXML in CRM


Hi,

Sharing a sample code to retrieve more than 5000 records using the Fetch XML.

Version 1 :


private List<Entity> GetTotalRecordsfromFetch(string fetchXML, IOrganizationService orgService)
{
List<Entity> lstEntity = new List<Entity>();

int fetchCount = 5000;
int pageNumber = 1;
string pagingCookie = null;

while (true)
{
// Build fetchXml string with the placeholders.
string xml = this.CreateXml(fetchXML, pagingCookie, pageNumber, fetchCount);
RetrieveMultipleRequest fetchRequest = new RetrieveMultipleRequest
{
Query = new FetchExpression(xml)
};

var returnCollections = ((RetrieveMultipleResponse)orgService.Execute(fetchRequest)).EntityCollection;

if (returnCollections.Entities.Count >= 1)
{
lstEntity.AddRange(returnCollections.Entities);
}

if (returnCollections.MoreRecords)
{
pageNumber++;

results.pagingCookie = returnCollections.PagingCookie;
}
else
{
// If no more records in the result nodes, exit the loop.
break;
}
}

return lstEntity;
}

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

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

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

Version 2 :


private static List<Entity> GetTotalRecordsFetchXML(OrganizationServiceProxy orgProxy, string fetchXML)
{
XDocument xDocument = XDocument.Parse(fetchXML);
var fetchXmlEntity = xDocument.Root.Element("entity").ToString();

EntityCollection entityColl = new EntityCollection();
List<Entity> lstEntity = new List<Entity>();
int page = 1;
do
{

entityColl = orgProxy.RetrieveMultiple(new FetchExpression(
string.Format("<fetch version='1.0' page='{1}' paging-cookie='{0}'>" + fetchXmlEntity + "</fetch>",
SecurityElement.Escape(entityColl.PagingCookie), page++)));

lstEntity.AddRange(entityColl.Entities);
}
while (entityColl.MoreRecords);

return lstEntity;
}

Hope it helps..

System.Security.SecurityException: That assembly does not allow partially trusted callers while using HttpUtility.UrlEncode in CRM


Hi,

We got the below error in one of our Sandboxed Plugins

“System.Security.SecurityException: That assembly does not allow partially trusted callers”.

We realised it was because of using System.Web.HttpUtility class


We replaced it with EscapeDataString method and this fixed the issue.

System.Uri.EscapeDataString()

Helpful thread

https://stackoverflow.com/questions/3840762/how-do-you-urlencode-without-using-system-web

Hope it helps..

Using WebClient to call external service from CRM Online Sandboxed Plugin (HTTP POST and JSON)


Sharing a sample code that can be used to send JSON data using POST to an external service inside CRM Online Plugin. As plugin runs in sandbox mode we cannot reference Newtonsoft’s JSON.NET library http://www.newtonsoft.com/json. The other option could be to use ILMerge, which isn’t that elegant.

Here, basically we are passing some information related to lead to an external service on Post Create of it.


using Microsoft.Xrm.Sdk;
using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;

namespace MyTestPlugin
{

 public class Lead
 {
 public string Topic { get; set; }
 public string FullName { get; set; }
 public string Email { get; set; }
 }

 public class MyPluginClass : IPlugin
 {
 public void Execute(IServiceProvider serviceProvider)
 {
 try
 {
 // Obtain the execution context from the service provider.
 IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

 // The InputParameters collection contains all the data passed in the message request.
 if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
 {
 // Obtain the target entity from the input parameters.
 Entity entity = (Entity)context.InputParameters["Target"];

 using (WebClient client = new WebClient())
 {
 var myLead = new Lead();
 myLead.Topic = entity.Attributes["subject"].ToString();
 myLead.FullName = entity.Attributes["fullname"].ToString();
 myLead.Email = entity.Attributes["emailaddress1"].ToString();

 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Lead));
 MemoryStream memoryStream = new MemoryStream();
 serializer.WriteObject(memoryStream, myLead);
 var jsonObject = Encoding.Default.GetString(memoryStream.ToArray());


 var webClient = new WebClient();
 webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
 var code = "key";
 var serviceUrl = "https://xyz.azurewebsites.net/api/mylead?code=" + code;

 // upload the data using Post mehtod
 string response = webClient.UploadString(serviceUrl, jsonObject);
 }
 }
 }
 catch (Exception ex)
 {
 throw new InvalidPluginExecutionException(ex.Message);
 }
 }
 }
}

Hope it helps..


Using MediaWiki API for Showing content of Wikipedia page inside Dynamics 365 form


Hi,

Recently we had a requirement to show content of Wikipedia page and display it inside CRM in one of the entities form.

For this purpose, we can make use of “MediaWiki web service API.”

https://www.mediawiki.org/wiki/API:Main_page

To create the query, we can use the below tool

https://en.wikipedia.org/wiki/Special%3aApiSandbox

The html source code


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">

function SetWikiContent() {

// get country name from crm form
if (Xrm.Page.getAttribute("new_name") != null) {

var title = Xrm.Page.getAttribute("new_name").getValue();

// set the url
var url = "https://en.wikipedia.org/w/api.php?format=json&action=parse&page=" + title + "&prop=text&section=0&callback=?";

$.getJSON(url, function (data) {
for (text in data.parse.text) {
var text = data.parse.text[text].split("
");
var pText = "";

for (p in text) {
//Remove html comment
text[p] = text[p].split("<!--");
if (text[p].length > 1) {
text[p][0] = text[p][0].split(/\r\n|\r|\n/);
text[p][0] = text[p][0][0];
text[p][0] += "
 ";
}
text[p] = text[p][0];

//Construct a string from paragraphs
if (text[p].indexOf("
") == text[p].length - 5) {
var htmlStrip = text[p].replace(/<(?:.|\n)*?>/gm, '') //Remove HTML
var splitNewline = htmlStrip.split(/\r\n|\r|\n/); //Split on newlines
for (newline in splitNewline) {
if (splitNewline[newline].substring(0, 11) != "Cite error:") {
pText += splitNewline[newline];
pText += "\n";
}
}
}
}
pText = pText.substring(0, pText.length - 2); //Remove extra newline
pText = pText.replace(/\[\d+\]/g, ""); //Remove reference tags (e.x. [1], [4], etc)

Xrm.Page.getAttribute('new_wikiinfo').setValue(pText);
}
});
}
}

</script>
</head>
<body onload="SetWikiContent();">
</body>
</html>

The helpful article

http://stackoverflow.com/questions/8555320/is-there-a-clean-wikipedia-api-just-for-retrieve-content-summary

Hope it helps..

Simple Bing Map HTML Web Resource to show Country location in Dynamics 365


Just sharing a HTML Web resource code to show Country location inside the map using name of the country.

Source Code: –


<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>My Bing Map</title>
<script charset="UTF-8" type="text/javascript" src="https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0&s=1"></script>
<script type="text/javascript">
var map = null;

// get the bing map key https://msdn.microsoft.com/en-us/library/ff428642.aspx
var credentials = "AvYH87t36Tv3ybyYagU9HUZKjsrWO2Hcup3nu1fmNhpenHKO_xxxxx";

function GetMap() {

// countryName - name of the country from the CRM's form
var countryName = parent.Xrm.Page.getAttribute("new_name").getValue();

// calling virtual earth api
var geocodeRequest = "https://dev.virtualearth.net/REST/v1/Locations?countryRegion=" + countryName + "&key=" + credentials + "&jsonp=GeocodeCallback";

CallRestService(geocodeRequest);
}

function GeocodeCallback(result) {

if (result && result.resourceSets && result.resourceSets.length > 0 && result.resourceSets[0].resources && result.resourceSets[0].resources.length > 0) {

var coordinates = result.resourceSets[0].resources[0].point.coordinates;
var centerPoint = new Microsoft.Maps.Location(coordinates[0], coordinates[1]);

map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),
{
credentials: credentials,
center: centerPoint,
mapTypeId: Microsoft.Maps.MapTypeId.road,
zoom: 5
});

var pushpin = new Microsoft.Maps.Pushpin(map.getCenter());
map.entities.push(pushpin);
}
}

function CallRestService(request) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
document.body.appendChild(script);
}
</script>
</head>
<body onload="GetMap();">
<div id='mapDiv' style="position: relative; width: 600px; height: 300px;"></div>
</body>
</html>

Check this helpful post as well

https://blogs.bing.com/maps/2015/03/05/accessing-the-bing-maps-rest-services-from-various-javascript-frameworks/

Hope it helps..

Deployment Manager – To create a new organization, the wizard must remove the current organization in Dynamics 365 message.


While creating a new organization using Deployment Manager we got the below message

It was because we had entered the Workgroup Product key which restricts it to only organization.

https://technet.microsoft.com/en-us/library/hh699677.aspx

Changing the product key to the server one, allowed creating the new organizations.

Hope it helps..

SSRS Fetch XML based CRM Online Report performance in Dynamics 365


Hi,

Recently we were analyzing the performance of a fetch xml based online report.

The report was running against opportunity, and had 4 data set in it. Custom entity A and custom entity B were n – 1 related to opportunity.

Data Set Opportunity 13000 records
Data Set for Custom Entity A used for Lookup 100 records
Data Set for Custom Entity B used for Lookup 8000
Data Set for Tasks Activity used for Lookup 130000 records

More on Lookup Function in SSRS

Running without filter 107 seconds
Filter Last 6 months 94 seconds

We then updated the report’s design, to include only one Dataset by using link entities in the main dataset’s fetch xml. We got the below result

Running without filter 280 seconds
Filter Last 6 months 10 seconds

Another variation we tried was having two Dataset, one for opportunity and another one for tasks to be used for lookup.

Running without filter 50 seconds
Filter Last 6 months 50 seconds

The last variation we tried was using only one Dataset for Opportunity in the main report and the drill down report for Tasks

Running without filter 34 seconds
Filter Last 6 months 7 seconds

It clearly shows that the most efficient way of implementing is through the usage of drill down report, only glitch here is user needs to click on the main report to get the details.

Using single dataset is efficient for subset of records, however it can take long time if it runs on huge number of records in which case lookup performs better.

Basically,

g

Hope it helps..

Using Lookup, LookupSet and Multilookup function in SSRS (Dynamics 365)


Using the Lookup, LookupSet and Multilookup functions we can basically combine values from 2 different data set.

The definition of them are

Lookup/LookupSet/Multilookup(source_expression, destination_expression, result_expression, dataset)

source expression – the field from the source data set (for e.g. primary key)

destination expression – the field to be matched from the destination dataset (sort of foreign key)

result expression – the field whose value has to be returned from the destination dataset

dataset – destination dataset name.

For e.g. we have custom entity Team and Team Members (1 à n)

We have following two DataSet one for Team and one for Team Members.

  1. DSTeam

  1. DSPlayer

The sample report has the Tablix which is bound to DSTeam and has two columns one which is bound new_name field of DSTeam dataset and the second column which gets the player name from DSPlayer dataset.

Output:

Lookup function picks the “first matching value” from the second dataset DSPlayer.

To get all the matching we need to use the LookupSet function (along with Join)

Output:

To understand Multilookup, let us create one more entity Tournament that will have a text attribute which stores comma separated team name.

Let us create one more dataset DSTournament and bound it to a new table. Which have one column which lists the Tournament name and the other column that does the multilookup to DSPlayer to get the player name.

It brings the first matching value, by searching (doing lookup) on multiple value i.e. India and South Africa

Hope it helps..

The ‘distinct’ attribute is not declared error while trying to import solution in CRM 2016 (and earlier)


Hi,

Got this error while trying to import a managed solution in CRM 2016 Online.

During analysis we figured out that it was pointing to one of the charts created for System User Entity. It seemed like chart’s xml was modified after export and then imported. The xml definition of the chart contained distinct keyword.

Removing the distinct keyword from the Chart definition and importing it back and then importing the managed solution with this updated chart got imported without any error.

Hope it helps..

IPluginExecutionContext Depth is 2 in Create Plugin during Import of records in CRM 2015 (and earlier)


We had one of our plugins on Create of Opportunity however during the import of the Opportunity record it was not working properly. We had the Depth check in our plugin code to check for infinite loop as the same plugin was being used for Update also.

After some debugging we realized that Depth value is 2 instead of 1 during import.

To test this, we created a sample plugin for create of Test entity record and then imported the Test entity records.

As expected the import failed and we got our custom exception in it.

Hope this helps..

Sample code to update Access Mode of System User in C# (CRM 2016 or earlier)


Recently had a requirement to set Access Mode of around 500 users to Administrative from Read – Write. We wrote an on demand workflow for that. However, running that workflow on those 500 records in a batch of 100 records was causing them to stuck in waiting stage and we had to then manually resume those workflow instance. So we ended up writing a Console Application for that.


   QueryExpression queryExpression = new QueryExpression();
            queryExpression.EntityName = "systemuser";
            queryExpression.ColumnSet = new ColumnSet();
            queryExpression.ColumnSet.AddColumn("fullname");

            ConditionExpression conditionExpression1 = new ConditionExpression();
            conditionExpression1.AttributeName = "tk_businessarea";
            conditionExpression1.Values.Add("EE286698-AF08-E311-B55E-1CC1DE6DAA0B");
            conditionExpression1.Operator = ConditionOperator.Equal;

            ConditionExpression conditionExpression2 = new ConditionExpression();
            conditionExpression2.AttributeName = "isdisabled";
            conditionExpression2.Values.Add(false);
            conditionExpression2.Operator = ConditionOperator.Equal;

            // access mode ==> 0 --> Read Write and 1 --> Adminstrative
            ConditionExpression conditionExpression3 = new ConditionExpression();
            conditionExpression3.AttributeName = "accessmode";
            conditionExpression3.Values.Add(1);
            conditionExpression3.Operator = ConditionOperator.Equal;
            
            queryExpression.Criteria.AddCondition(conditionExpression1);
            queryExpression.Criteria.AddCondition(conditionExpression2);
            queryExpression.Criteria.AddCondition(conditionExpression3);

            queryExpression.Criteria.FilterOperator = LogicalOperator.And;

            EntityCollection entityColl = organizationProxy.RetrieveMultiple(queryExpression);
            foreach(var entity in entityColl.Entities)
            {
                Entity userEntity = new Entity("systemuser");
                userEntity.Id = entity.Id;
                userEntity.Attributes["accessmode"] = new OptionSetValue(0);
                organizationProxy.Update(userEntity);
            }

Hope it helps !!

Generic SQL error in CRM 2015 Online (and earlier)


Recently we were getting the Generic SQL Error in one of our Plugin which was registered in Create of Opportunity Line.

The scenario was that on qualifying the lead, opportunity was getting created and we had Async Plugin on Create of Opportunity that will create an Opportunity Line and had Sync Plugin on Create of Opportunity Line that was updating the parent Opportunity. This issue was occurring randomly.

We observed the following, that if both the Plugin are registered as Sync or Async the issue doesn’t occur. It also doesn’t occur if we have Opportunity Plugin on Create as Sync and the one on Opp. Line as Async.

The other way of solving the issue was to introduce delay before updating the Parent Opportunity from the child opportunity line create Plugin.

Hope this helps..

SandboxFault.ThrowIfGuidEmpty: entityId in CRM 2015.


Hi,

We had one of our Plugins registered in RetrieveMultiple of an entity. And one of the JavaScript was using FetchXML to retrieve that particular entity records. This JavaScript was throwing the following exception

Putting the Guid.Empty check for the OutputParameter EntityCollection fixed the issue.

Hope it helps..

“The content of the import file is not valid. You must select a text file” – Error on Solution Import in CRM 2015 (and earlier)


Hi,

We got this issue while importing (managed) solution from dev to test organization. We had recently deleted one of our existing 1 – n relationship and had created a new n – n relationship between those entities. The issue was that the new relationship had exactly the same schema name as the old relationship which we deleted.

The solution was to delete the newly created n – n relationship in Dev and create a new one with different schema name. After this change we were able to import the solution successfully.

Hope it helps..

Sample code to close a quote as won using WinQuoteRequest in CRM 2016 (and earlier)


Just sharing a sample code to close quote as won through C#


WinQuoteRequest winQuoteRequest = new WinQuoteRequest();
Entity quoteClose = new Entity("quoteclose");
quoteClose.Attributes["quoteid"] = new EntityReference("quote", new Guid("015816C2-2F10-E611-8112-3863BB353ED0"));
quoteClose.Attributes["subject"] = "Quote Close" + DateTime.Now.ToString();
winQuoteRequest.QuoteClose = quoteClose;
winQuoteRequest.Status = new OptionSetValue(-1);
organizationProxy.Execute(winQuoteRequest);

Hope it helps..

Set PartyList field To in Email in CRM 2015 (and earlier)


Sample code to set the PartyList field for Email Activity.


function setContact() {

var partlistData = new Array();
partlistData[0] = new Object();

// guid of the record
partlistData[0].id = "8B2AD82B-30D6-E511-811F-3863BB356F90";

// name of the record
partlistData[0].name = "Hugh Grant";

// entity schema name
partlistData[0].entityType = "contact";
Xrm.Page.getAttribute("to").setValue(partlistData)

}

Hope it helps..

The selected translations file is either invalid or does not conform to the required translations file schema error while importing translations in CRM 2015 (and earlier)


Hi,

While importing translations we got the below error

On opening the CrmTranslations.xml we saw the translations missing for that row.

On specifying the values for those fields and importing it back fixed the issue.

Hope it helps..

Unit Testing (Microsoft Fakes) RetrieveSharedPrincipalsAndAccessResponse in Plugin in CRM 2016 (and earlier)


Hi,

While trying to write Fakes for RetrieveSharedPrincipalsAndAccessResponse we’d realize that PrincipalAccess is read only property and the class itself is sealed.

So to unit test it we need to write a wrapper class as suggested here

http://alexanderdevelopment.net/post/2013/10/17/unit-testing-custom-microsoft-dynamics-crm-code-part-4/

The wrapper class


/// <summary>
/// Wrapper class for retrieve response
/// </summary>
[DataContract(Namespace = "http://schemas.microsoft.com/xrm/2011/Contracts")]
public class RetrieveSharedPrincipalsAndAccessResponseWrapper : OrganizationResponse
{
/// <summary>
/// The _entity
/// </summary>
private PrincipalAccess[] _principalaccess;

/// <summary>
/// Initializes a new instance of the <see cref="RetrieveResponseWrapper"/> class.
/// </summary>
/// <param name="response">The response.</param>
public RetrieveSharedPrincipalsAndAccessResponseWrapper(OrganizationResponse response)
{
try
{
this.PrincipalAccesses = ((RetrieveSharedPrincipalsAndAccessResponseWrapper)response).PrincipalAccesses;
}
catch
{
this.PrincipalAccesses = ((RetrieveSharedPrincipalsAndAccessResponse)response).PrincipalAccesses;
}
}

/// <summary>
/// Gets or sets the PrincipalAccesses.
/// </summary>
/// <value>
/// The entity.
/// </value>
public PrincipalAccess[] PrincipalAccesses
{
get
{
return _principalaccess;
}

set
{
_principalaccess = value;
}
}
}

The unit test


 organizationService.ExecuteOrganizationRequest = request =>
 { 
 RetrieveSharedPrincipalsAndAccessResponseWrapper retrieveResponseWrapper = new RetrieveSharedPrincipalsAndAccessResponseWrapper(new RetrieveSharedPrincipalsAndAccessResponse());
 PrincipalAccess[] principalAccess = new PrincipalAccess[1]; 
 PrincipalAccess pAccess = new PrincipalAccess();
 pAccess.AccessMask = AccessRights.CreateAccess;
 pAccess.Principal = new EntityReference("team", new Guid("9A69533A-2306-4DFC-9662-65ABFAB41348"));
 principalAccess[0] = pAccess;
 retrieveResponseWrapper.PrincipalAccesses = principalAccess; 
 return retrieveResponseWrapper;
 };

 

Change in the Plugin code using Wrapper instead of original class



 IOrganizationService orgService = serviceFactory.CreateOrganizationService(context.UserId);

 var accessRequest = new RetrieveSharedPrincipalsAndAccessRequest
 {
 Target = new EntityReference("projectsite", new Guid("CDF30DD5-C64E-4EF5-ABA6-C9715C10A07D"))
 };

 RetrieveSharedPrincipalsAndAccessResponseWrapper accessResponse = (new RetrieveSharedPrincipalsAndAccessResponseWrapper(orgService.Execute(accessRequest)));

Hope it helps

The type or namespace name ‘RSASignaturePadding’ does not exist in the namespace ‘System.Security.Cryptography’ (are you missing an assembly reference?) in Unit Test Project.


Was getting the below error while trying to build a unit test project (framework version 4.5.2) in VS 2012.

Delete the .messages file as suggested in some forums, but that didn’t help.

Just tried building the project by changing the Target Framework to 4.6.

That worked and after that on switching back the target version to 4.5.2 also worked.

Helpful post

https://social.msdn.microsoft.com/Forums/vstudio/en-US/2de45cd4-2744-4a91-91a2-785f305c1ef7/errors-on-trying-to-add-fakes-assembly-on-system?forum=vsunittest

Hope it helps..

Xrm.Utility.openEntityForm with Regarding field in CRM 2015.


Hi

We recently had a requirement to open new Task form on click of a ribbon button with Regarding field prefilled.

And as mentioned in the SDK, we can’t set the values for regarding lookups.

https://msdn.microsoft.com/en-us/library/gg334375.aspx#BKMK_SetLookupFieldValues

The workaround is to create custom parameters, set its value in JavaScript and use these values on the onLoad of the Form.

http://www.crmnerd.com/customizations/using-xrm.utility.openentityform-with-custom-parameters/

http://butenko.pro/2013/01/ms-crm-2011-open-new-activity-form-with-regarding-field-prefilled/#comment-134

Hope it helps..

Administration Mode Enabled. Only system administrators and system customizers can sign in at this time in CRM 2015 Online.


Hi,

After we copied our Dev instance to another Sandbox instance we got this message on opening CRM.

To disable it.

Go to Office 365 Administration Section

Select your sandbox instance.

Select Admin

Uncheck Enable Administration Mode

Hope it helps.

DateTime fields in CRM 2015


Hi,

We recently had a requirement wherein we were working with DateTime fields in a Plugin. It was related to Time Zone.

These articles were of extreme help.

http://develop1.net/public/post/Dynamics-CRM-DateTimes-the-last-word.aspx

http://inogic.com/blog/2015/06/handling-datetime-fields-in-microsoft-dynamics-crm-update-1/

http://ttidbit.blogspot.com/2013/01/crm-timezone-codes.html

Sample Code to use LocalTimeFromUtcTimeRequest


var currentUserSettings = organizationProxy.RetrieveMultiple(
new QueryExpression("usersettings")
{
ColumnSet = new ColumnSet("timezonecode"),
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression("systemuserid", ConditionOperator.EqualUserId)
}
}
}).Entities[0];

var timeZoneCode = currentUserSettings.Attributes["timezonecode"].ToString();

DateTime time1 = DateTime.UtcNow;

LocalTimeFromUtcTimeRequest convert = new LocalTimeFromUtcTimeRequest();
convert.UtcTime = time1.ToUniversalTime();
convert.TimeZoneCode = Convert.ToInt32(timeZoneCode);
LocalTimeFromUtcTimeResponse response = (LocalTimeFromUtcTimeResponse)organizationProxy.Execute(convert);
MessageBox.Show(response.LocalTime.ToString());

 

The interesting part was that our plugin was running under the context of System account, so to get the logged in user from UI, we added an additional field and populated the value of time zone in it on on load using current logged in user’s information, and used the same field in plugin.

Hope it helps..

Plugin on Retrieve Multiple in CRM 2015.


Recently we had a requirement to filter sub grid on one of the forms. We thought of using Plugin on Retrieve Multiple for this.

Here we were showing Opportunity Sub Grid on Account form.

So we created a view for Opportunity that will be used as Sub Grid. Used it as Related Record Sub Grid so that we can have the GUID of the Account record being passed to the plugin.

The problem we faced à Sorting and Paging stopped working for the Sub Grid.

http://crmtipoftheday.com/2015/10/05/limitations-of-retrieve-plugins/v


void IPlugin.Execute(IServiceProvider serviceProvider)
{
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));

// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Query") && context.InputParameters["Query"] is QueryExpression && context.MessageName == "RetrieveMultiple")
{
QueryExpression qe = (QueryExpression)context.InputParameters["Query"];
if (qe.EntityName == "opportunity")
{
string currentCustomerId = string.Empty;
ConditionExpression[] filters = qe.Criteria.Conditions.ToArray();
foreach (var filter in filters)
{
currentCustomerId = filter.Values[0].ToString();
}

FetchXmlToQueryExpressionRequest req = new FetchXmlToQueryExpressionRequest();
req.FetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
"<entity name='opportunity'>" +
" <attribute name='name' />" +
"<attribute name='customerid' />" +
"<attribute name='estimatedvalue' />" +
"<attribute name='statuscode' />" +
"<attribute name='opportunityid' />" +
"<order attribute='name' descending='false' />" +
"<link-entity name='account' from='accountid' to='parentaccountid' alias='ad'>" +
" <filter type='and'>" +
" <filter type='or'>" +
" <condition attribute='accountid' operator='eq' uiname='aaass' uitype='account' value=' " + currentCustomerId + "' />" +
" <condition attribute='accountid' operator='under' uiname='aaass' uitype='account' value='" + currentCustomerId + "' />" +
"</filter>" +
"</filter>" +
"</link-entity>" +
"</entity>" +
"</fetch>";
FetchXmlToQueryExpressionResponse resp = (FetchXmlToQueryExpressionResponse)service.Execute(req);
context.InputParameters["Query"] = resp.Query;

}
}

Hope it helps..

The records were not updated because the following Microsoft Dynamics CRM fields were not found during Import in CRM 2015.


Hi,
Was getting the below error while trying to import few records

The reason being there were two field in the entity having same Display Name. Renaming one of the fields fixed the issue and import ran successfully.

Hope it helps ..

Add Find Columns to Lookup View in CRM.


Hi,

Recently we had a requirement to search based on a particular attribute within the lookup view. The initial thought was to add a Find Columns to the lookup view. But then realized we do not have option of adding Find Columns to the lookup view.

The next thought was if I add that particular field to the list of Find Columns in Quick Find view will it work in Lookup View also? And it worked, basically adding any fields in the Find Column will make it Searchable.

The search works properly in the Lookup View as well as Lookup Inline View.

Hope it helps..

Sample Fetch XML Report using Multivalued Parameter (in Operator) in CRM


Hi,

Sharing a sample report which shows the usage of Multi Value parameter in filter.

Replace the Condition generated in the Fetch xml query using Advanced Find

As following

Create another DataSet to provide value for @gendercodevalue parameter.

Set @gendercodevalue parameter as following ( internal – if we do not want user to select or specify value for it in report)

Preview:

Hope it helps..

Using RetrievePrincipalAccessRequest in CRM


Hi,

Recently had a requirement to show\hide a ribbon button based on the condition i.e. if a user has Write access to that record show it else hide it.

Here either the user can have Write access to the record through the one of the security roles assigned to him or through the team which has that rights.

In this case we can use RetrievePrincipalAccessRequest which returns as response all the right user had on that particular record either through his own security roles or teams he is part of.

For e.g. we give following rights on a particular record to a team (which the user is part of)

If we check the rights user has on the record using RetrievePrincipalAccessRequest we get the following response (combination of all the rights either through sharing or his own security roles)

[


RetrievePrincipalAccessRequest request = new RetrievePrincipalAccessRequest();

// system user or team
request.Principal = new EntityReference("systemuser", new Guid("EBEECB5F-2D60-E511-80F8-3863BB357FC0"));

// record for which we want to check the access
request.Target = new EntityReference("is_productionsite", new Guid("15734DF9-31DD-E511-810E-3863BB353ED0"));

RetrievePrincipalAccessResponse resp = (RetrievePrincipalAccessResponse)orgService.Execute(request);

 

Hope it helps.

Only Secure Content is displayed notification while using Bing Map API version 7.0 in CRM Online.


Hi,

We recently developed a web resource using Bing Map API to show address as push pin for Custom Entities.

However, we were getting the following notification

The reason being we were using Http version of the API and CRM is on HTTPS. We changed it to use HTTPS version and it fixed the issue.

Else we would have to do the following settings in the browsers

http://du.screenstepslive.com/s/docs/m/7107/l/219447-allow-mixed-content-in-browsers

Helpful post

http://blog.devdave.com/2011/01/removing-mixed-content-warning-when.html

Hope it helps..