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 !

Sample code to read XML Data from Web Resource in Plugin in CRM 2011/2013/2015


We recently had a requirement to read xml data stored in a particular web resource in plugin.

Sharing the sample code


public static Dictionary<string, string> GetMarketClusterAndMarketSegment(string webresourceName, string buildingTypeValue, IOrganizationService organizationService)
{
Dictionary<string, string> dictionaryMarket = new Dictionary<string, string>();

// tk_et_oppline_marketingfilterpicklists
// create request to retrieve Webresource
ColumnSet cols = new ColumnSet();
cols.AddColumn("content");
QueryByAttribute requestWebResource = new QueryByAttribute
{
EntityName = "webresource",
ColumnSet = cols
};
requestWebResource.Attributes.AddRange("name");
requestWebResource.Values.AddRange(webresourceName);

Entity webResourceEntity = null;
EntityCollection webResourceEntityCollection = organizationService.RetrieveMultiple(requestWebResource);

if (webResourceEntityCollection.Entities.Count > 0)
{
webResourceEntity = webResourceEntityCollection.Entities[0];
byte[] binary = Convert.FromBase64String(webResourceEntity.Attributes["content"].ToString());
string resourceContent = System.Text.Encoding.UTF8.GetString(binary);
string byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (resourceContent.StartsWith(byteOrderMarkUtf8))
{
resourceContent = resourceContent.Remove(0, byteOrderMarkUtf8.Length);
}

XDocument xmlDocument = XDocument.Parse(resourceContent);

var marketSegment = from t in xmlDocument.Descendants("ParentField").ElementAt(1).Descendants("ShowOption")
where t.Attribute("value").Value.Equals(buildingTypeValue)
select new
{
marketSegmentValue = t.Parent.Attribute("value").Value,
marketSegmentLabel = t.Parent.Attribute("label").Value
};

foreach (var v in marketSegment)
{
dictionaryMarket.Add("marketsegment", v.marketSegmentValue);
var marketCluster = from t in xmlDocument.Descendants("ParentField").ElementAt(0).Descendants("ShowOption")
where t.Attribute("value").Value.Equals(v.marketSegmentValue)
select new
{
marketClusterValue = t.Parent.Attribute("value").Value,
marketClusterLabel = t.Parent.Attribute("label").Value
};

foreach (var m in marketCluster)
{
dictionaryMarket.Add("marketcluster", m.marketClusterValue);
}
}
}

return dictionaryMarket;
}
}

Hope it helps..

Query execution time of 60 seconds exceeded the threshold of 10 seconds warning in CRM 2013.


Query execution time of 60 seconds exceeded the threshold of 10 seconds warning in CRM 2013.

We were getting the below warning in one of our test environment

On analyzing figured out that one of the plugin was using retrieve with ColumnSet(true) option i.e. retrieving all the columns of the entity which was not required in this case.

Fetching only the required columns fixed the warning.

The other option could have been indexing or increate the value for LongQueryThersholdInSeconds column in ServerSetingProperties table of MSCRM_Config.

Helpful posts

http://blog.edgewater.com/2013/01/07/microsoft-dynamics-crm-querying-data-using-late-binding-versus-early-binding/

http://www.dynamicscrmpros.com/mscrmplatform-warning-in-event-viewer-in-microsoft-dynamics-cr-event-id-17972/

Hope it helps..

 

JavaScript runtime error: Unable to get property ‘get_code’ of undefined or null reference in CRM


We can get the ‘get_code’ error if we are using Assign Step in Action/Workflow and the value is null for the field selected.

Here we need to use If condition to check if the value exist for that particular field before using Assign Step.

Sample code: Using jqGrid in ASP.NET page to show CRM data


Sample code: Using jqGrid in ASP.NET page to show CRM data

Just sharing a simple ASP.NET page that uses jqGrid to show contact records in CRM and allows user to search.

Here is the code SampleJQGrid.zip (remove .doc)

Hope it helps ..

JavaScript Reference for Microsoft Dynamics CRM 2011 / 2013


GT // CRM

Here’s a quick reference guide covering Microsoft CRM syntax for common jscript requirements.

Most of the examples are provided as functions that you can easily test in the OnLoad event of the Account form to see a working example.  These are not production hardened but they’ll help you with the CRM syntax.

(updated: 30 July 2012)

Index:

  1.   Get the GUID value of a Lookup field
  2.   Get the Text value of a Lookup field
  3.   Get the value of a Text field
  4.   Get the database value of an Option Set field
  5.   Get the text value of an Option Set field
  6.   Get the database value of a Bit field
  7.   Get the value of a Date field
  8.   Get the day, month and year parts from a Date field
  9.   Set the value of a String field
  10. Set the value of an Option Set (pick list)…

View original post 1,401 more words

Fix: Invalid ‘where’ condition. An entity member is invoking an invalid property or method while using LINQ in CRM 2013.


Hi,

We were writing a LINQ query to get the contract record information by passing in the lawyer name. The lawyer is a lookup in the contract record.

So we were using contract.lawyerid.Name field of lookup in our where condition.

However we got the below error while doing so..

 

It seems like the LINQ Implementation for CRM doesn’t correctly interpret the lookup field’s name if we are using it in the where clause.

The solution was to do a join between the entities and then use the where condition against the lawyer entity username field itself.

Hope it helps..

Debugging online plugin in CRM 2013.


Hi,

Let us take a simple plugin to understand the debugging process. We need the profile which we will use for debugging.

Register the plugin (debug version) and corresponding step using plugin registration tool.

Select Install Profiler in Plugin Registration tool and wait till the installation is complete.


Select the Step in Plugin and Click Profile in the tool

Select Ok in the dialog box

Open CRM and perform the step that will run the plugin.

Download the log file.

Open Visual Studio and attach debugger to PluginRegistrationTool.exe

Go back to Plugin Registration tool, select the step and select Debug from the tool bar.

 

Specfiy the log file in the Profile location and plugin assembly that is in debug folder.

Click on Start Execution to start debugging

Hope it helps.

Sample code to get label and value for OptionSet in CRM


Hi,

Just sharing a sample code that retrieves optionset data from CRM and also sorts it. We are using it to bind drop down in one of our custom SharePoint Application Page.


/// <summary>
/// The get global option sets.
/// </summary>
/// <param name="config">
/// The config.
/// </param>
/// <param name="globalOptionSetName">
/// The _global option set name.
/// </param>
/// <returns>
/// The <see cref="List"/>.
/// </returns>
public static List<XrmOptionSet> GetGlobalOptionSets(IOrganizationService config, string globalOptionSetName)
{
using (
XrmServiceContext context = SDKHelper.GetXrmServiceContext(
config.OrganizationServiceUrl,
config.Credentials))
{
RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest
{
Name =
globalOptionSetName
};

// Execute the request.
RetrieveOptionSetResponse retrieveOptionSetResponse =
(RetrieveOptionSetResponse)context.Execute(retrieveOptionSetRequest);

OptionSetMetadata retrievedOptionSetMetadata =
(OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray();

List<XrmOptionSet> optionSetItems = new List<XrmOptionSet>();

// Add each item in OptionMetadata array to the ListItemCollection object.
foreach (OptionMetadata o in optionList)
{
XrmOptionSet xrmOptionSet = new XrmOptionSet();
xrmOptionSet.Label = o.Label.LocalizedLabels[0].Label;
xrmOptionSet.Value = o.Value.Value.ToString(CultureInfo.InvariantCulture);
optionSetItems.Add(xrmOptionSet);
}

optionSetItems.Sort(
delegate(XrmOptionSet thisItem, XrmOptionSet otherItem)
{
return thisItem.Label.CompareTo(otherItem.Label);
});

return optionSetItems;
}
}

/// <summary>
/// The get local option sets.
/// </summary>
/// <param name="config">
/// The config.
/// </param>
/// <param name="entityName">
/// The entity name.
/// </param>
/// <param name="optionSetAttributeName">
/// The option set attribute name.
/// </param>
/// <returns>
/// The <see cref="List"/>.
/// </returns>
public static List<XrmOptionSet> GetLocalOptionSets(
IOrganizationService config,
string entityName,
string optionSetAttributeName)
{
using (
XrmServiceContext context = SDKHelper.GetXrmServiceContext(
config.OrganizationServiceUrl,
config.Credentials))
{
// Create the Attribute Request.
RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName =
entityName,
LogicalName =
optionSetAttributeName,
RetrieveAsIfPublished
= true
};

// Get the Response and MetaData. Then convert to Option MetaData Array.
RetrieveAttributeResponse retrieveAttributeResponse =
(RetrieveAttributeResponse)context.Execute(retrieveAttributeRequest);
PicklistAttributeMetadata retrievedPicklistAttributeMetadata =
(PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();

List<XrmOptionSet> optionSetItems = new List<XrmOptionSet>();

// Add each item in OptionMetadata array to the ListItemCollection object.
foreach (OptionMetadata o in optionList)
{
XrmOptionSet xrmOptionSet = new XrmOptionSet();
xrmOptionSet.Label = o.Label.LocalizedLabels[0].Label;
xrmOptionSet.Value = o.Value.Value.ToString(CultureInfo.InvariantCulture);
optionSetItems.Add(xrmOptionSet);
}

optionSetItems.Sort(
delegate(XrmOptionSet thisItem, XrmOptionSet otherItem)
{
return thisItem.Label.CompareTo(otherItem.Label);
});

return optionSetItems;
}
}
}

&nbsp;

 

Hope it helps.

Generic SQL Error – RetriveMultiple with ConditionOperator.Contains in CRM


Hi,

Was getting Generic SQL Error while using ConditionOperator.Contains in the ConditionExpression. The requirement was to get all the incident records based on the title attribute value.

condExp.AttributeName = “title”;

condExp.Operator = ConditionOperator.Contains;

condExp.Values.Add(“test”);

The correct way to perform this kind of search is by using Like operator with %.

condExp.AttributeName = “title”;

condExp.Operator = ConditionOperator.Contains;

condExp.Values.Add(“%test%”);

http://social.microsoft.com/Forums/en-US/ede5932b-5ac9-4fc9-86d9-12ef5b2b305d/crm-2011-getting-generic-sql-error-when-performing-retrievemultiple-with?forum=crmdevelopment

Hope it helps.

 

 

 

Microsoft Dynamics CRM Compatibility List


Hi,

Found this article that lists the minimum version of products compatible with Microsoft Dynamics CRM 4.0 and 2011.

Do check it out

http://support.microsoft.com/kb/2669061

Bye.

 

 

Newly Created Entity not appearing in Stunnware’s Tool (Fetch XML Wizard)


Hi,

I created two new entities in my CRM 2011 development server and thought of writing a fetch xml query using the Fetch XML Wizard tool of Stunnware.

But much to my surprise while trying to add Entities for the query, I was not able to find them in the list. This happens because of the Metadata Cache not getting refreshed. The tool maintains the cache of the metadata. This post helped me in resolving the issue.

http://luckyabhishek.blogspot.in/2011/05/stunnware-fetch-xml-doesnt-show.html

Bye.

Sample Code to Retrieve all the members of a Static Marketing List in CRM 2011


Hi,

Below is the code that we could use to retrieve the GUIDs of all the members associated to a STATIC marketing list.

 private void GetAllMembers_Click(object sender, EventArgs e)
 {
 ArrayList memberGuids = new ArrayList();
 IOrganizationService orgService = GetOrganizationService();

PagingInfo pageInfo = new PagingInfo();
 pageInfo.Count = 5000;
 pageInfo.PageNumber = 1;

QueryByAttribute query = new QueryByAttribute("listmember");
 // pass the guid of the Static marketing list
 query.AddAttributeValue("listid", new Guid("2CA7881F-3EDA-E111-B988-00155D886334"));
 query.ColumnSet = new ColumnSet(true);
 EntityCollection entityCollection = orgService.RetrieveMultiple(query);

foreach (Entity entity in entityCollection.Entities)
 {
 memberGuids.Add(((EntityReference) entity.Attributes["entityid"]).Id);
 }

// if list contains more than 5000 records
 while (entityCollection.MoreRecords)
 {
 query.PageInfo.PageNumber += 1;
 query.PageInfo.PagingCookie = entityCollection.PagingCookie;
 entityCollection = orgService.RetrieveMultiple(query);

foreach (Entity entity in entityCollection.Entities)
 {
 memberGuids.Add(((EntityReference)entity.Attributes["entityid"]).Id);
 }
 }

}

public IOrganizationService GetOrganizationService()
 {
 Uri organizationUri = new Uri("http://servername/orgname/XRMServices/2011/Organization.svc");
 Uri homeRealmUri = null;
 ClientCredentials credentials = new ClientCredentials();
 credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
 OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
 IOrganizationService _service = (IOrganizationService)orgProxy;
 return _service;
 }

Hope it helps.

Hierarchical report in SSRS to show users and their managers (CRM)


Hi,

Just created a simple SSRS report that shows the Hierarchy of the users and their manager.

This is how the report looks like

The DataSet query used

Select the row, right click and select group properties option

Select Grouping based on systemuserid

Toggle the visibility based on FullName

Select parentsystemuserid as Recursive Parent from the Advanced option

Set the Left Padding property for the fullname TextBox.

Set the expression for level as Level()

The posts from which I learned creating the hierarchical reports

http://blog.infotoad.com/post/2009/08/10/Working-with-a-Recursive-Hierarchy-Group-in-SQL-Reporting-Services-2008.aspx

http://blog.davyknuysen.be/2010/04/16/parent-child-hierarchies-in-reporting-services/

Bye.

Installing Microsoft Dynamics CRM 4.0 in Windows Server 2008 R2 machine having Microsoft SQL Server 2008 database.


Hi,

These are the steps we followed to install Microsoft Dynamics CRM 4.0 in Windows Server 2008 R2 machine (Here we had the Microsoft SQL Server 2008 installed on a different server)

Before running the setup, first we added the .NET Framework 3.5.1 Features from Server Manager.

After running the installer we got the following error in the Environment Diagnostics Wizard.

 ERROR : (provider: Named Pipes Provider, error: 40 – Could not open a connection to SQL Server) (Microsoft SQL Server, Error: )

We followed the step mentioned in this article to resolve this issue.

http://blog.sqlauthority.com/2009/05/21/sql-server-fix-error-provider-named-pipes-provider-error-40-could-not-open-a-connection-to-sql-server-microsoft-sql-server-error/

On running the installer again, we got this issue

Error : Service msftesql was not found on computer …… The specified service does not exist as an installed service.


We followed the below mentioned steps to resolve the issue

  1. Run > Regedit
  2. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
  3. Rename MSSQLFDLauncher Folder to msftesql
  4. Reboot System
  5. Administrative Tools > Services > SQL Full-text Filter Daemon Launcher (MSSQLSERVER) and Check START Status
  6. Rename back msftesql Folder to MSSQLFDLauncher

http://social.microsoft.com/Forums/eu/crm/thread/d8dda562-aae6-47b7-9c81-86f98d2b77f6

Bye.

Determining the Update Rollup Version of the CRM installed


Hi,

Just sharing two useful posts which would help us to identify the update rollup version installed in our CRM environment.

For CRM 2011

http://crmdynamo.com/2011/09/crm-2011-update-rollup-release-build-numbers-and-how-to-find-them/

For CRM 4.0

http://crmdynamo.com/2010/03/check-which-update-rollup-version-is-installed-on-your-crm-environments/

Bye.

Sample Code for adding a button for SubGrid and passing id of the selected records (CRM 2011)


Simply replace the entity schema name with your entity

  <RibbonDiffXml>
        <CustomActions>
          <CustomAction Id="MyOrg.CustomAction" Location="Mscrm.SubGrid.entitySchemaName.MainTab.Management.Controls._children" Sequence="50">
            <CommandUIDefinition>
              <Button Id="MyOrg.Button" ToolTipTitle="Upload Required Document" ToolTipDescription="Upload Required Documents for the Case" Command="MyOrg.Command" Sequence="50" LabelText="Upload Document" Alt="Upload Document To Portal" Image16by16="/_imgs/ribbon/AddEmail_16.png" Image32by32="/_imgs/ribbon/Email_32.png" TemplateAlias="o1" />
            </CommandUIDefinition>
          </CustomAction>
        </CustomActions>
        <Templates>
          <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
        </Templates>
        <CommandDefinitions>
          <CommandDefinition Id="MyOrg.Command">
            <EnableRules />
            <DisplayRules />
            <Actions>
              <JavaScriptFunction Library="$webresource:new_test" FunctionName="showvalue">
                <StringParameter Value="Guid(s) Selected" > </StringParameter>
                <CrmParameter Value="SelectedControlSelectedItemIds"></CrmParameter>
              </JavaScriptFunction>
            </Actions>
          </CommandDefinition>
        </CommandDefinitions>
        <RuleDefinitions>
          <TabDisplayRules>
          </TabDisplayRules>
          <DisplayRules />
          <EnableRules />
        </RuleDefinitions>
        <LocLabels />
      </RibbonDiffXml>

Function for the jscript web resource.

function showvalue(){

alert(value);

}

Hope it helps.

value cannot be null. parameter name value error in CRM 2011


I was getting the above error while trying to create a SharePointDocumentLocation programmatically. However I was able to create an incident record without any issue.

As it turned out, this is what I was missing


OrganizationServiceProxy orgService = new


OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);


orgService.EnableProxyTypes();

Hope it helps!

Reporting error. Report cannot be displayed. (rsProcessingAborted)


I was getting the above error while running one of the custom SSRS report inside CRM 2011.


To resolve this issue I had to follow these steps

  1. Start SQL Server Management Studio
  2. Expand Security, then expand Logins
  3. Select and right click the account under which the SQL Server Reporting Services is running.
  4. Select User Mapping and select YouOrg_MSCRM database and specify following role membership
  • CRMReaderRole,
  • db_owner
  • public.


Hope it helps.