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..

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 !!

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..

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

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..

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.

Get Total Count of records in CRM. (more than 5000)

For version 9.0 please check the below post

RetrieveTotalRecordCountRequest

https://dreamingincrm.com/2019/07/22/getting-entity-record-counts/

https://docs.microsoft.com/en-us/dotnet/api/microsoft.crm.sdk.messages.retrievetotalrecordcountrequest?view=dynamics-general-ce-9

Just sharing a sample code to get the total number of records (e.g. account here)

 IOrganizationService orgService = GetOrganizationService();

 int totalCount = 0;

 QueryExpression query = new QueryExpression("account");
 query.ColumnSet = new ColumnSet();
 query.Distinct = true;
 query.ColumnSet.AddColumn("accountid");
 query.PageInfo = new PagingInfo();
 query.PageInfo.Count = 5000;
 query.PageInfo.PageNumber = 1;
 query.PageInfo.ReturnTotalRecordCount = true;

 EntityCollection entityCollection = orgService.RetrieveMultiple(query);
 totalCount = entityCollection.Entities.Count;

 while (entityCollection.MoreRecords)
 {
 query.PageInfo.PageNumber += 1;
 query.PageInfo.PagingCookie = entityCollection.PagingCookie;
 entityCollection = orgService.RetrieveMultiple(query);
 totalCount = totalCount + entityCollection.Entities.Count;
 } 

 MessageBox.Show(totalCount.ToString());

 

Hope it helps

Business Process Error while trying to open records in CRM 2015

Hi we were getting the below error while trying to open any record in CRM 2015

G

Turned out that by mistake one wrong extra step had got registered on RetrieveMultiple

ActivityFeeds.Plugins: ActivityFeeds.Plugins.ActivityClose]

[c824b80a-d392-e511-8114-3863bb356f90: ActivityFeeds.Plugins.ActivityClose: RetrieveMultiple of any Entity]

Removing this step fixed the issue.

Hope it helps.

Fixed – Microsoft Dynamics CRM Reporting Authoring Extension Setup – Setup cannot continue because there is a pending restart required error in CRM 2015

Hi,

Got the below error while trying to install the Report Authoring Extension for CRM 2015.

To fix the issue, open the log file, check for the registry path and delete it

Hope it helps !