Thursday, July 13, 2017

Call Action from JavaScript


function Callcustomaction(actionName, param1Value) {
    var result2 = null;
    var result = {};
    result.Output1 = {};
    result.Output2 = {};
    var data = {
        "Param1Name": param1Value,
        "Param2Name": ""
    };

    var req = new XMLHttpRequest();
    var uri = Xrm.Page.context.getClientUrl() + "/api/data/v8.0/";
    try {
        req.open("POST", encodeURI(uri + actionName), false);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.onreadystatechange = function () {
            if (this.readyState == 4) {
                req.onreadystatechange = null;
                if (this.status == 200) {
                    result2 = JSON.parse(this.response);
                } else {
                    var err = JSON.parse(this.response).error;
                    alert(err.message);
                }
            }
        };
        req.send(JSON.stringify(data));
        result.Output1 = result2.Output1;
        result.Output2 = result2.Output2;
        return result;

    } catch (err) {
        alert(err.message);
    }
    return result;
}

Wednesday, March 23, 2016

Sample WebAPI Methods for MSCRM 2016

function InitiateAPICalls() {
    var resp = ExecuteAPIRequest("accounts"); //Ajax Request
    var resp1 = ExecuteXmlRequestToAPI("accounts"); //XMLHttpRequest

}


function result(resultArray, error) {
    this.results = resultArray;
    this.error = error;
}
function ExecuteAPIRequest(query) {
    var resultArray = null;
    var errorMessage = null;
    $.ajax(
    {
        type: "GET",
        url: Xrm.Page.context.getClientUrl() + "/api/data/v8.0/" +query,
        async: false,
        headers: { "Accept": "application/json", "Content-Type": "application/json;charset=utf-8", "OData-MaxVersion": "4.0", "OData-Version": "4.0" }
    })
    .done(function (Httpresponse) {
        resultArray = Httpresponse.value;
    })
    .fail(function (Httpresponse) {
        var errors = JSON.parse(Httpresponse.responseText);
        if (errors.error)
            errorMessage = "There was an error executing the request. " + Httpresponse.status + " " + Httpresponse.statusText +". " + errors.error.message;
    })
    .always(function (Httpresponse) {
    });
    return new result(resultArray,errorMessage);
}

function ExecuteXmlRequestToAPI(query) {
    var resultArray = null;
    var errorMessage = null;
    var req = new XMLHttpRequest()
    var resultArray = null;
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/"+ query, false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onerror = function (error) {
        throw new Error("There was an error executing the request. " + req.status + " " + error.message);
    }
    var response = req.send();
    if (req.status == 200) {
        var results = JSON.parse(req.response);
        resultArray = results.value;
    }
    else {
        var errors = JSON.parse(req.response);
        if (errors.error)
            errorMessage = "There was an error executing the request. " + req.status + " " +req.statusText+ ". "+ errors.error.message;
    }
    return new result(resultArray,errorMessage);
}

Friday, April 3, 2015

Knockout


Knockout Click Binding:

<td>
<a data-bind="text:title,click:$parent.openRecord"/>
</td>

if you use href in "a" tag, the function wont be called.

Inside your view model,

var self = this;
self.openRecord = function (record) { // Write your code here for click operation };


Knockout Dirty flag:


Create new ko object :
ko.dirtyFlag = function (root, isInitiallyDirty) { var result = function () { }, _initialState = ko.observable(ko.toJSON(root)), _isInitiallyDirty = ko.observable(isInitiallyDirty); result.isDirty = ko.computed(function () { return _isInitiallyDirty() || _initialState() !== ko.toJSON(root); }); result.reset = function () { _initialState(ko.toJSON(root)); _isInitiallyDirty(false); }; return result; };


In your view model, you can use the flag like this:
var isDirty = false; //set to true to load your item as Dirty.
  self.dirtyFlag = new ko.dirtyFlag(this, isDirty);

To check for a specific item in your Model as dirty or not,
        self.quantitydirtyFlag = new ko.dirtyFlag(self.quantity, isDirty);

        self.dirtyItems = ko.computed(function () {
        self.isDirty = ko.computed(function () {

            return ko.utils.arrayFilter(self.items(), function (item) {
                return item.dirtyFlag.isDirty();
            });
        }, self);

            return self.dirtyItems().length > 0;

        }, self);


you can check for whether the item is dirty or not by,

record.dirtyFlag.isDirty()
for the specific item,
record.quantitydirtyFlag.isDirty()

Dirty flag original reference here.




Wednesday, August 13, 2014

Parse Json Date to Date Object

Parse jsondate in JavaScript to a Date Object:
Below are two methods I use  
Method 1:
var jsonDate = "/Date(1224043200000)/"
var value = new Date(parseInt(jsonDate.substr(6)));

Method 2:
var jsonDate = "/Date(1224043200000)/"
var value = new Date(parseInt(jsonDate.replace(/(^.*\()|([+-].*$)/g, '')));
if you want in "mm/dd/yyyy" format, use this along with the above script
var dat = value.getMonth()+ 1 + "/" + value.getDate()+ "/" +value.getFullYear();

Thursday, July 10, 2014

Site works in chrome but not in IE/Unable to browse CRM in IE


For a long time, i had trouble browsing my CRM running in Hyper-V in my machine's IE. But it works fine with Chrome/firefox. Then i tried this:

IE is using Kerberos and not falling back on NTLM like Chrome and Firefox. You must force NTLM authentication in IIS7.5 by following these steps: 1. Select your site. 2. Double click authentication. 3. Select "Windows Authentication" (ensuring that it is enabled). 4. Click "Providers..." in the right hand column. 5. Select NTLM and click "Move Up".





Wednesday, June 25, 2014

Unable to see any forms or grids in CRM

If a user  is unable to see the forms or grids even with proper privilege to the entity, then you probably need to set another privilege as below:

Open the security role. 
Under Customizations tab--> Select Read Privilege for System Form.


Monday, May 19, 2014

Training & Adoption Kit for MSCRM 2013



Training & User Adoption Kit for MSCRM 2013




http://www.microsoft.com/en-us/dynamics/crm-customer-center/training-adoption-kit-for-microsoft-dynamics-crm.aspx


Tuesday, April 29, 2014

System dashboard throws error. ConfigSettings Modify CRM.

Sometimes, I've faced scenarios where even clicking on Dashboards, threw CRM error. especially, when the VM is cloned.

In such cases, the solution was to verify HelpServerUrl in the config settings and modify the same. 

select * from configsettings
---HelpServerUrl value would be' http://<originalservername>'


update ConfigSettings
set Helpserverurl ='http://<servername>/'
where Id='43E2CF02-D524-4E0E-955-6211701D462D'

Note: This is strictly unsupported by Microsoft.

Friday, April 11, 2014

Business Rules not firing CRM2013

Recently,  i was facing a bizarre issue of Business Rules not firing for Customer Records even though the rule was active for the entity. This was because one of the fields being validated, was not present on the form. Once i added that, the business rule started working again :)

Thursday, March 27, 2014

Create Feeds for Custom Entities


Many a times we will come across the scenario where in the clientwould like to see the feeds for custom entities.
Unfortunately, MS prevents us from creating an Activity Feed rule for custom entities. So we cannot configure this directly.
But, there is a perfectly safe workaround for this.

1.       Create a Workflow. i.e. if you want the feeds for creation of a custom entity then create a workflow to fire on create of the record.
2.       The workflow should create a post. Set the attributes as desired.








That is all there is to creating a post for a custom entity :)




Wednesday, March 19, 2014

Create New Business Processes / Modify existing processes




There are 3 steps involved in creating or modifying the existing business process flows.

In this case, I’ll be adding a sample process flow to the contact entity.

  1. First step in the process is Adding the sales stage category values you need. i.e. the stage names. In the default solution, you will find an option set “processstage_category”. Add necessary values in the option set.
  2. Creating a Business Process Flow. Go to SettingsàProcessesàBusiness Process Flows. Create New. 
  3. Add the necessary stages and checks required for them.

The same can be done for OTB entities like Opportunity, Account etc. These Process flows can be controlled through security roles just like Forms.

Wednesday, February 19, 2014

Enable Proxy Types in Plugins

If you need to use Linq Queries in plugins/workflows, you have to enable proxy types before instantiating the service object from service provider.


factory.GetType().GetProperty("ProxyTypesAssembly").SetValue(factory,typeof(YourCrmContext).Assembly, null);



Friday, January 31, 2014

Ajax request from HTML to CRM2011/ CRM2013

var requestmain = fetchxml;

 $.ajax(
            {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: serverurl + "/XRMServices/2011/Organization.svc/web",
                async: false,
                data: requestMain,
                headers: { "Accept": "application/xml, text/xml, */*", "Content-Type": "text/xml; charset=utf-8", "SOAPAction": "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/RetrieveMultiple" }

            })
            .done(function (XMLHttpRequest) {
                var strResponse = GetXmlValue(XMLHttpRequest.childNodes[0]);
                xmlDoc = $.parseXML(strResponse);
            })
            .fail(function (XMLHttpRequest) {
                alert("Error retrieving accounts using fetch xml");
            })
            .always(function (XMLHttpRequest) {
            });

function GetXmlValue(value) {
    if (value.xml == undefined) {
        return (new XMLSerializer()).serializeToString(value);
    }
    return value.xml;
}
 

Friday, August 24, 2012

FormEntityContextRule Example



 CustomActions:

        <CustomActions>
          <CustomAction Id="Mscrm.SubGrid.new_test.AddExistingAssocCustom" Location="Mscrm.SubGrid.new_test.AddExistingStandard" Sequence="30" >
            <CommandUIDefinition>
              <Button Id="Mscrm.SubGrid.new_test.AddExistingStandard" Command="Mscrm.AddExistingRecordFromSubGridStandardCustom" Sequence="30" LabelText="CustomAddExistingStd" Alt="$Resources(EntityDisplayName):Ribbon.SubGrid.AddExisting" Image16by16="/_imgs/ribbon/AddExistingStandard_16.png" Image32by32="/_imgs/ribbon/AddExistingStandard_32.png" TemplateAlias="o1" ToolTipTitle="$Resources(EntityDisplayName):Mscrm_SubGrid_EntityLogicalName_MainTab_Management_AddExistingStandard_ToolTipTitle" ToolTipDescription="$Resources(EntityDisplayName):Mscrm_SubGrid_EntityLogicalName_MainTab_Management_AddExistingStandard_ToolTipDescription" />
            </CommandUIDefinition>
          </CustomAction>

          <CustomAction Id="Mscrm.SubGrid.new_test.AddNewStandardCustom" Location="Mscrm.SubGrid.new_test.AddNewStandard" Sequence="20" >
            <CommandUIDefinition>
              <Button Id="Mscrm.SubGrid.new_test.AddNewStandard" Command="Mscrm.AddNewRecordFromSubGridStandardCustom" Sequence="20" LabelText="CustomAddNewStd" Alt="$Resources(EntityDisplayName):Ribbon.SubGrid.AddNew" Image16by16="/_imgs/ribbon/NewRecord_16.png" Image32by32="/_imgs/ribbon/newrecord32.png" TemplateAlias="o1" ToolTipTitle="$Resources(EntityDisplayName):Mscrm_SubGrid_EntityLogicalName_MainTab_Management_AddNewStandard_ToolTipTitle" ToolTipDescription="$Resources(EntityDisplayName):Mscrm_SubGrid_EntityLogicalName_MainTab_Management_AddNewStandard_ToolTipDescription" />
            </CommandUIDefinition>
          </CustomAction>
        </CustomActions>



CommandDefinitions:

        <CommandDefinitions>
          <CommandDefinition Id="Mscrm.AddExistingRecordFromSubGridStandardCustom">
            <EnableRules>
              <EnableRule Id="Mscrm.AppendToPrimary" />
              <EnableRule Id="Mscrm.EntityFormIsEnabled" />
            </EnableRules>
            <DisplayRules>
              <DisplayRule Id="Mscrm.AddExisting" />
              <DisplayRule Id="Mscrm.ShowForOneToManyGrids" />
              <DisplayRule Id="Mscrm.AppendToPrimary" />
              <DisplayRule Id="Mscrm.AppendSelected" />
              <DisplayRule Id="Mscrm.CanWriteSelected" />
              <DisplayRule Id="Mscrm.CustomShow" />
            </DisplayRules>
            <Actions>
              <JavaScriptFunction FunctionName="Mscrm.GridRibbonActions.addExistingFromSubGridStandard" Library="/_static/_common/scripts/RibbonActions.js">
                <CrmParameter Value="SelectedEntityTypeCode" />
                <CrmParameter Value="SelectedControl" />
              </JavaScriptFunction>
            </Actions>
          </CommandDefinition>
          <CommandDefinition Id="Mscrm.AddNewRecordFromSubGridStandardCustom">
            <EnableRules>
              <EnableRule Id="Mscrm.AppendToPrimary" />
              <EnableRule Id="Mscrm.EntityFormIsEnabled" />
            </EnableRules>
            <DisplayRules>
              <DisplayRule Id="Mscrm.ShowForOneToManyGrids" />
              <DisplayRule Id="Mscrm.AppendToPrimary" />
              <DisplayRule Id="Mscrm.CreateSelectedEntityPermission" />
              <DisplayRule Id="Mscrm.AppendSelected" />
              <DisplayRule Id="Mscrm.HideAddNewForChildEntities" />
              <DisplayRule Id="Mscrm.CustomShow" />
            </DisplayRules>
            <Actions>
              <JavaScriptFunction FunctionName="Mscrm.GridRibbonActions.addNewFromSubGridStandard" Library="/_static/_common/scripts/RibbonActions.js">
                <CrmParameter Value="SelectedEntityTypeCode" />
                <CrmParameter Value="PrimaryEntityTypeCode" />
                <CrmParameter Value="FirstPrimaryItemId" />
                <CrmParameter Value="PrimaryControl" />
              </JavaScriptFunction>
            </Actions>
          </CommandDefinition>
        </CommandDefinitions>


RuleDefinition:
        <RuleDefinitions>
          <TabDisplayRules />
          <DisplayRules>
            <DisplayRule Id="Mscrm.CustomShow" >
              <FormEntityContextRule EntityName="account" InvertResult="true" />
            </DisplayRule>
          </DisplayRules>
          <EnableRules />
        </RuleDefinitions>

open link url inside a div/iframe

<html>
<head>
<script type="text/javascript">

function  showPage (which) {
    document.getElementById('xrmforms').innerHTML = '<' + 'iframe id="crmpage" src="' + which + '"width="100%" height="600px;" scrolling="auto"></iframe>';

}

</script>

</head>
<body>
<a href="http://www.google.com" onclick="showPage(this.href);return false;">Click here</a>


<div id="xforms">
</div>

</body>
</html>








Replace certain character JavaScript

To replace certain characters in javascript:

In this example, i'm replacing '&' with '&amp;' in the entire string.


function formatTexts(linkText) {
    var patt1 = /&/g;
    var patt1replStr = "&amp;";

    var matchPatt = linkText.match(patt1);

    var pattformat = /&amp;/g;
    var matchformatted = "";
    if (matchPatt != null && matchPatt.length > 0) {
        while (matchformatted.length < matchPatt.length) {
            linkText = linkText.replace(linkText.match(patt1)[0], patt1replStr);
            matchformatted = linkText.match(pattformat);
        }
    }
    return linkText;
}