Tuesday, 26 May 2015

Reactivate a case using C# in CRM 2011/2013/2015

Hi,

Many times we get the requirement to reactivate a case using C# in Plugin/Workflow/Some App,

Here is the code of it.

try
{
   SetStateRequest req = new SetStateRequest();
   req.EntityMoniker = new EntityReference(entityName, entityGuid);
   req.State = new OptionSetValue(state);
   req.Status = new OptionSetValue(status);
   orgService.Execute(req);
}
catch (Exception ex)
{


}

Hope it helps.

--
Happy CRM'ing
Gopinath.

Monday, 25 May 2015

Error while trying to run project uncaught exception thrown by method called through reflection

Hi,

Today I was working with the console application got the below error while debugging the code.

"Error while trying to run project uncaught exception thrown by method called through reflection"

After some time found the solution for this.

  1. Go to the project right click and select property
  2. Select 'Debug' tab on the left
  3. Check ‘Enable Native code debugging’ (or 'Enable unmanaged code debugging', depends on version) check box.
  4. Run the project
Hope this helps.

--
Happy CRM'ing
Gopinath.

Sunday, 24 May 2015

Can we delete Personal Views in CRM? Yes, we can.

Hi,

Today, when I was talking one of my friends got an chilly doubt that can we delete the personal views in CRM.

Yes, we can delete the personal views.

  1. Open Advance Find.
  2. Click on Saved Views.
  3. Select the View and Delete.
  4. Along with Delete, we can also activate, de-activate the views.

Hope this helps.

--
Happy CRM'ing
Gopinath.

Friday, 22 May 2015

Refreshing the Web Resource in CRM 2013/2015/2016

Hi,

We are using a HTML webresource to show some the attribute values of the CRM record on the entity form.

In CRM 2011, when ever we save the record the form used to reload and webresource also refreshes and get the latest data. But in CRM 2013 and later, on the save of the record the form won't reload and as a result the values on the HTML resources were not getting refreshed.

The solution is to refresh the webresource using JavaScript on the Save Event of the form.

function refreshHTMLWebResource() {
    var webResourceControl = Xrm.Page.getControl("WebresourceName");
    var src = webResourceControl.getSrc();
    webResourceControl.setSrc(null);
    webResourceControl.setSrc(src);


}


Hope this helps.
--
Happy CRM'ing
Gopinath.

Retrieve records from CRM using Odata Synchronous Operation

Hi,
 
Here is the JavaScript code for retrieving records from CRM using OData Synchronously.
 
function retrieveContactsByAccountId(accountId) {
    // Pass 'Contact' set name since we are reading Contacts
     var oDataSetName = "AccountSet";
   // Column names of 'Contact' (Pass * to read all columns)
    var columns = "Name";
    // Prepare filter
    var filter = "AccountId eq guid'" + accountId + "'";
    var requestResults = retrieveMultipleSync(oDataSetName, columns, filter);
    var account = null;
    if (requestResults != null) {
        if (requestResults.results != null && requestResults.results.length > 0) {
            for (var indxContacts = 0; indxContacts < requestResults.results.length; indxContacts++) {
                account = requestResults.results[indxContacts];
                if (account.Name) {
                    alert(account.Name);
                }
            }
        }
    }
    else {
        alert("An error has occured. " + service.responseText);
    }
}
 
// Retrieve Multiple Synchronous Operation.
function retrieveMultipleSync(odataSetName, select, filter) {
    // Get Server URL
    var serverUrl = "";
    if (Xrm.Page.context.getClientUrl) {
        //Post UR 12
        serverUrl = Xrm.Page.context.getClientUrl();
    }
    else {
         //Pre UR 12
        serverUrl = Xrm.Page.context.getServerUrl();
    }
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    var odataUri = serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "?";
    if (select) {
        odataUri += "$select=" + select;
    }
    if (filter) {
        odataUri += "&" + "$filter=" + filter;
    }
    var service = GetRequestObject();
    if (service != null) {
        service.open("GET", odataUri, 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 GetRequestObject() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch (ex) {
            return null;
        }
    }
}
 
--
Happy CRM'ing
Gopinath
 

Thursday, 21 May 2015

Get the GUID of the Record from URL in CRM 2011/2013/2015

Hi

This might be known 99% of the CRM developers, I am writing this to help for 1% people.

How to get GUID of the record
We do this many times while working with CRM.

Follow the below steps for the getting GUID from the URL.

  • Right click on the mouse by selecting the record from the list and select Copy a Link.
  • Click Allow access on the popup if it asks.
  • Open notepad and paste.
  • You will see the complete URL of the record got pasted
  • Just take the text between "%7b" and "%7d"

That's it, you have the GUID of the record.

Hope this helps.

--
Happy CRM'ing
Gopinath.

Entities are not shown after the Solution Import in CRM

Hi All,

Here is the issue I have faced recently.

  • Created a custom entity in the Dev environment and selected Areas to Display as "Service"
  • Create a Solution in Dev env and added the new created entity to it.
  • Exported the solution and imported it in the Test environment.

After the import was successful, I have published all customizations but I was not able the newly created entity in the Service area. Opened customization and found that in Areas to Display the checkbox was unchecked.

For resolving the issue, I have added SiteMap to the solution. Exported and imported from Dev from Test.

Hope this helps.

--
Happy CRM'ing
Gopinath.
 

Wednesday, 20 May 2015

Get Language Code (LCID) of the User in CRM 2011/2013/2015

Hi,

Here is the JavaScript to get the LCID (Locale Id) of User and Organization Base Language.
 
// Current User Language ID
var currUserLcid = Xrm.Page.context.getUserLcid();
// Organization Base Language ID
var orgLcid = Xrm.Page.context.getOrgLcid();

Check this for Microsoft Locale ID Values

Hope this helps

--
Happy CRM'ing
Gopinath


 

Customize Customer Lookup to show only Accounts or Contacts

Hi,
 
In some projects we may need customize the Customer look up on Case, Opportunity etc.. for showing only Accounts or Contacts based on some conditions.
 
We can achieve this using addPreSearch and addCustomFilter in JavaScript. Let us see this now.

I have taken Case entity here.

By default, Customer Look up shows Accounts and Contacts.

Accounts


Contacts


Let us customize it by writing some JavaScript code. The method is called on the load event, you can use it based on your requirement.

Here is the JavaScript code

function OnLoad() {
    addEventHandler();
}
 
function addEventHandler() {
    Xrm.Page.getControl("customerid").addPreSearch(addFilterToShowContacts);
    //Xrm.Page.getControl("customerid").addPreSearch(addFilterToShowAccounts);
}
 
// For showing only Contacts.
function addFilterToShowContacts() {
    var account_filter = "<filter type='and'>" +
     "<condition attribute='accountid' operator='null' />" +
    "</filter>";
    Xrm.Page.getControl("customerid").addCustomFilter(account_filter, "account");
}
 
// For showing only accounts.
function addFilterToShowAccounts() {
    var account_filter = "<filter type='and'>" +
    "<condition attribute='contactid' operator='null' />" +
    "</filter>";
    Xrm.Page.getControl("customerid").addCustomFilter(account_filter, "contact");
}
Showing Only Contacts




Showing Only Accounts



The only problem I see in this approach is User has select the dropdown(Account/Contact) but this is only supported way we have. Let's hope next versions of CRM will give some other technique to solve it for us.

Hope this helps.
--
Happy CRM'ing
Gopinath.

getServerUrl is deprecated in CRM 2013

Hi,
 
We all know that getServerUrl is deprecated in CRM 2013. Even now, there are many customer who are using CRM 2011. So, while writing the JavaScript we should take some extra care for the code to work in the later versions.
 
var url = "";
if (Xrm.Page.context.getClientUrl) {
   //Post UR 12
   url = Xrm.Page.context.getClientUrl();
}
else {
   //Pre UR 12
   url = Xrm.Page.context.getServerUrl();
}

Hope this helps
 
--
Happy CRM'ing
Gopinath.
 
 

Create record using OData and JQuery in CRM 2011/2013/2015

Hi,

Here is the code for creating a record using OData and Jquery in CRM 2011/2013/2015.

Let us take the example of creating Account record.

  • Create a JS and add it in Account entity.
  • Copy and Paste the below code. I have covered the basic attributes which you can change according to your requirement.

function createAccount() {
    //Create an object to represent an Account record and set properties
    var account = new Object();
    // Set Single Line of Text field
    account.Name = "Testing Odata";
    // Set Lookup field (Contact should exists in the system)
    var primaryContact = new Object();
    primaryContact.ContactId = "B5A0F1C2-7CF5-E411-80D5-C4346BAC59E8";
    primaryContact.FullName = "Rene Valdes (sample)";
    if (primaryContact != null) {
        account.PrimaryContactId = { Id: primaryContact.ContactId, LogicalName: "contact", Name: primaryContact.FullName };
    }
    //Set a picklist value
    account.PreferredContactMethodCode = { Value: 2 };
    // Set a money value (i.e., Annual Revenue)
    account.Revenue = { Value: "2000000.00" };
    // Set a Decimal field (Here ‘new_DecimalField’ is my custom Account field)
    account.new_DecimalField = 200.00.toString();
    // Set a Boolean value
    account.DoNotPhone = true;
    // Set Date field (Here ‘new_DateField’ is my custom Account field)
    //var myDate = new Date();
    //myDate.setFullYear(1980, 12, 29);
    //account.new_Date = myDate;
    // Call create method by passing
    //(i) Entity Object (i.e.,account in this case)
    //(ii) Entity Set
    //(iii)SuccessCallback function
    //(iv) Error callback function
    createRecord(account, "AccountSet", createAccountCompleted, null);
}

// callback method which will get executed on successfull account creation
function createAccountCompleted(data, textStatus, XmlHttpRequest) {
    var account = data;
    alert("Account created; Id: " + account.AccountId.toString());
}
 
// This function creates record by making OData call
function createRecord(entityObject, odataSetName, successCallback, errorCallback) {
    //Parse the entity object into JSON
    var jsonEntity = window.JSON.stringify(entityObject);
    // Get Server URL
    var url = "";
    if (Xrm.Page.context.getClientUrl) {
        //Post UR 12
        url = Xrm.Page.context.getClientUrl();
    }
    else {
        //Pre UR 12
        url = Xrm.Page.context.getServerUrl();
    }
    //The OData end-point
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    //Asynchronous AJAX function to Create a CRM record using OData
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: url + ODATA_ENDPOINT + "/" + odataSetName,
        data: jsonEntity,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (successCallback) {
                successCallback(data.d, textStatus, XmlHttpRequest);
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (errorCallback) {
                errorCallback(XmlHttpRequest, textStatus, errorThrown);
            }
            else {
                alert("An error has occured while creating the record; Error – " + errorThrown);
            }
        }
    });
}
  • Call createAccount function on the Load of Account.
  • Create JQuery and JSON files as web resources and them on Account Form.
  • Save and Publish.

Hope this helps

--
Happy CRM'ing
Gopinath.