Sep 21, 2015

Determine if Owner (SystemUser /Team) and assign to a record

In Dynamics CRM Owner can be either a user or a team. This can be little tricky when reading Owner from a record and set to another one.

Please check below screen shot of Account. You can simply check this with OwnerIdType, yet you can’t retrieve that field for some reason.

 
Still we can check two different fields that holds Either User Id or team Id.

In fact, I tried below approach which worked for me.

String OwningEntityType = String.Empty;
if (_account.OwningTeam != null)
{
    OwningEntityType = "team";
}
else
{
    OwningEntityType = "systemuser";
}

AssignRequest assignAcc = new AssignRequest
{
     Assignee = new EntityReference(OwningEntityType, _account.OwnerId.Id),
     Target = new EntityReference(<Target Entity Name>, <Target Entity Name ID>)
};
organizationService.Execute(assignAcc);

Jun 11, 2015

Exception handling – Process failed status in Asynchronous process

We discussed about handling of exception of plug-ins in few occasions. We also discussed and   recommended the usage of tracing mechanism and you can check it here.

It could be important to show a formal message to the user if a process is failed, especially in Asynchronous processes because it doesn’t throw any exception as in synchronous processors. User may not have sufficient permission to check system jobs either. Tracing information is not for end users, but for developers. In this case, we can use a custom status field with one value as process failed.

Please check the code snippet and notice how that status change happened just before exception is thrown.

try
{
  //Any information you need to trace
  // ex;
  //tracer.Trace("Account:{0} and Guid:{1}", _account.Name, _account.accountid);
}
catch (Exception ex)
{
  // ***status change to Failed status ****
  throw new InvalidPluginExecutionException("[" + ex.Message + "]" + ex.StackTrace, ex);
}
finally
{
}

Now, this worked fine for lengthy processes for me. Yet, there is one exception: if issue occur with SQL time out/ DB connection this will become a problem. Why? Simply this update won’t happen and system will stuck in that point… bitter truth is we are not getting any trace information either, because it come after this step.

So you need to decide depending on your scenario. If the SQL time out is a possible culprit, just forget about this status change.

Mar 31, 2015

Many–to-Many Associate, Disassociate and Retrieve

This is how you associate many-to-many relationships programmatically. One good thing about this approach is you can associate more than one record in one call. Disassociate too takes same parameters.

AssociateRequest request = new AssociateRequest();

EntityReference _ref1 = new EntityReference(<entity A - logical name>, <entity A - Guid>);
request.Target = _ref1;

EntityReferenceCollection _entRefColl = new EntityReferenceCollection();
_entRefColl.Add(new EntityReference(<entity B - logical name>, <entity B - Guid 1>));
_entRefColl.Add(new EntityReference(<entity B - logical name>, <entity B - Guid 2>));
request.RelatedEntities = _entRefColl;

request.Relationship = new Relationship("<relationship name>"); 
//relationship name ex: new_account_office

crmService.Execute(request);

Now one important fact;

Intermediate table of the many-to-many table is having the name of the relationship. For ex: new_account_office. This table got two Guids which are the primary key values of the two respective records to be associated which is obvious.

You are allowed to query this intermediate table as you wish. One thing to keep in mind is two Guids coming out of this table are purely Guids and NOT Entity References.

Probably, this is the only occasion you retrieve Guid from a table which are not the Primary key in CRM.  All other entity retrievals, if not a primary key we are retrieving Entity Reference type.  Clear?

Feb 26, 2015

Issue with datetime formats in OData retrievals

We now use OData Service for client side data retrievals. Yet, there is a bit of complexity when dealing with date time fields.  I usually use REST methods of XrmServiceToolkit library. When I try to retrieve datetime field and populate in some form field, I simply couldn’t do since what I retrieved was something different. Something like “/Date(1420588331000)/”. What is this?

This is a time encoded to a single integer which increases every second. This is UNIX timestamp. Though this is a logical representation of time which can be very helpful when dealing with complex time calculations, in our operation this can be frustrating.

We need to transfer this to date time which can be identified by JavaScript. So below code snippet can be helpful.

//Method

dateFormatUnixStamp: function (_uString) {
    var _date = null;
    if (_uString != null) {
        _date = new Date(parseInt(_uString.slice(_uString.indexOf("(") + 1, _uString.indexOf(")"))));
        _date.setDate(_date.getDate());
    }
    return _date;
}

//Calling

//Suppose _Ent is a entity we retrived through the service
//and we are assigning it to new_startdate of current form

var _startDate = dateFormatUnixStamp(_Ent.new_StartDate);
Xrm.Page.getAttribute(new_startdate).setValue(_startDate);

These two blogs also provides much helpful code samples in this regards;

https://rajeevpentyala.wordpress.com/2011/08/21/read-odata-service-date-field-in-crm-2011/
http://blogs.catapultsystems.com/rhutton/archive/2014/01/30/crm-2013-handling-odata-date-field-value.aspx

Thank you Deepak Mehta for the help.

Feb 12, 2015

Console Application skeleton for Dynamics CRM

Sometimes we need to do some operation in CRM through console applications, though not very common. Still we need to use CRM web services within the console application. CrmConnetion class can be used for that.

This code snippet can be useful in building your application.

Configuration file that keep the connection attributes;

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
<appSettings>
  <add key="connectionStr" value="Url=http://SERVERNAME/TENANTNAME; Domain=xxxxx; Username=xxxxx; Password=xxxxx;"/>
</appSettings>
</configuration>

Program code with CrmConnection;

using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System;
using System.Configuration;
using System.ServiceModel;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace ConsoleApplication1
{
 class Program
 {
   static void Main(string[] args)
   {
     CrmConnection _crmConnection = CrmConnection.Parse(ConfigurationManager.AppSettings.Get("connectionStr"));
     OrganizationService _orgService = new OrganizationService(_crmConnection);

     try
     {
        //Logic here
     }
     catch (Exception e)
     {
         Console.WriteLine("Process failed : " + e.Message);
     }
     finally
     {
         Console.WriteLine("Process successful.");
         Console.ReadLine();
     }
   }
 }
}

Feb 3, 2015

SQL to Fetchxml converter

This is a cool tool.

As we all are from on-premise CRM arena, one of the obvious challenges we have now is doing the same complex SSRS reports in online CRMs. In fact, challenge is writing fetchxml queries in the same way we did in t-sql queries. This is a cool free online tool by Kingswaysoft. This converts your t-sql queries to fetch.

 
Note: Please read the help page before using it.

Jan 18, 2015

Reading the record Id from CRM 2013 front end

This is just small tip. How developers grab the GUID of a record from the front end of CRM.

What I do is using frames[0].Xrm.Page.data.entity.getId() script in developer’s tool console. (by pressing F12)

Now does it work in CRM 2013?

Yep, but need to be quite careful. Since we don’t get new window for every record in CRM 2013, if you try this as it is, it would give you a wrong ID. (yes, WRONG!) As an alternative, always make your record popped out as a new window before applying this script.

Below Icon will pop-out your record.