Wednesday, July 29, 2015

Set CRM IFrame Url Dynamically to aspx page / Post data to CRM IFrame aspx page / Get Response from aspx page in CRM IFrame – CRM 2015 / CRM 2013/ 2011


Set CRM IFrame Url Dynamically to aspx page / Post data to CRM IFrame aspx page / Get Response from aspx page in CRM IFrame – CRM 2015 / CRM 2013/ 2011

 

CRM Js

// In following example on page load am binding iframe url dynamically and calling aspx page. On save, posting data to aspx page to perform some operation. On success am saving crm from data.

var dbWaiting;
 function onLoad() {
    dbWaiting = true;

    // Set IFrame URL dynamically to aspx page / service.
    var databaseRecordIDField = Xrm.Page.getAttribute('sa_databaserecordid');
    var o = document.getElementById('IFRAME_TemplateBody');

    if (o != null) {
        o.src = 'https://server.com/emailclient/template?id=' + databaseRecordIDField.getValue();
    }
    if (o != null) {
        IFrame.setSrc(o.src);
    }
    else {
        var IFrame = Xrm.Page.ui.controls.get("IFRAME_TemplateBody");
        IFrame.setSrc('https://server.com/emailclient/template?id=' + databaseRecordIDField.getValue());
    }

    // Add event listener to get response back from aspx page / service
    if (window.addEventListner) {
        window.parent.addEventListener("message", receiveMessage, false);
        window.addEventListener("message", receiveMessage, false);

    }
    else if (window.attachEvent) {
        window.parent.attachEvent("onmessage", receiveMessage);
        window.attachEvent("onmessage", receiveMessage);
    }
}

 

function onSave(ExecutionObj) {
    if (dbWaiting == true) {
        ExecutionObj.getEventArgs().preventDefault();
        var databaseRecordIDField = Xrm.Page.getAttribute('sa_databaserecordid');
        var o = document.getElementById('IFRAME_TemplateBody');

        // Data/ Json object to pass to aspx page/ service
        var pass_data = {
            'name': Xrm.Page.getAttribute('sa_name').getValue(),
            'id': Xrm.Page.getAttribute('sa_databaserecordid').getValue(),
            'action': 'saveRequestedFromCRM',
        };

         // Post data to aspx page/ service, you will get response back in receiveMessage
        if (o != null) {
            o.contentWindow.postMessage(JSON.stringify(pass_data), 'https://server.com/emailclient/template?id=' + databaseRecordIDField.getValue());
        }
        else {
            Xrm.Page.ui.controls.get("IFRAME_TemplateBody").getObject().contentWindow.postMessage(JSON.stringify(pass_data), 'https://server.com/emailclient/template?id=' + databaseRecordIDField.getValue());
        }
    }
}

 

function receiveMessage(event) {
    dbWaiting = false;
    if (event.data === 'error') {
        alert('An error occurred, could not save.  Please make sure the {{Body}} tag is included. ');
    }
    else {
        // You can read response object in to event.data
        Xrm.Page.data.entity.save();
    }
}

Disable fields on CRM Form - CRM 2015/ 2013/ 2011

function DisableForm() {
    Xrm.Page.ui.controls.forEach(
     function (control, index) {
         if (control.getControlType() != "subgrid" && control.getControlType() != "iframe" && control.getControlType() != "webresource")
             control.setDisabled(true);
     });
}

Refresh or Reload CRM IFRAME / Pass data to CRM IFRAME from CRM form – CRM 2015 / CRM 2013


Refresh or Reload CRM IFRAME / Pass data to CRM IFRAME from CRM form – CRM 2015 / CRM 2013

 
// For Posting / Passing data to IFrame, you can call following line on CRM form event. Following line will send/ post data to iframe and you can access data in receiveMessage event on html page in iframe.
 
Xrm.Page.ui.controls.get('WebResource_Dropdown').getObject().contentWindow.postMessage('refresh/data', "*")

 
Html Web Resource
<html>
<head>
    <title></title>
    <script type="text/javascript" src="sa_jQuery"></script>
    <script type="text/javascript" src="sa_JSON"></script>
    <script type="text/javascript" src="sa_XrmServiceToolkit.js"></script>
    <script src="ClientGlobalContext.js.aspx"></script>
    <script type="text/javascript">
        function receiveMessage(e) {
            // You can fetch data that you have posed in "e"
            //Refresh/ Reload data here

            LoadData();
        }

        window.attachEvent("onmessage", receiveMessage);

        function LoadData() {

        }

    </script>
    <meta charset="utf-8">
    <meta>
 </head>

<body onload="LoadData()">
</body>
</html>

Tuesday, July 28, 2015

Resize IFRAME to adjust – CRM 2015 / CRM 2013


In CRM 2015 / CRM 2013 you can resize ifram setting style by following way

Friday, July 24, 2015

Override/ Persist the Modified Date / Actual End date in entities in CRM 2015/ 2013/ 2011.


We can override or persist modifiedon date / actual end date in crm in Pre Operation.

In below sample am overriding modifiedon date on update of notes. Same way you can override actualend date in CRM 2015/ 2013/ 2011

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Client;

namespace Plugin
{
    public class NotePlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IOrganizationService service = null;

            Entity entity = null;
            ITracingService tracingService = null;

            tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            service = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                switch (context.MessageName)
                {
                    case "Update":
                        {

                            DateTime? createdon = null;
                            if (entity.Attributes.Contains("createdon"))
                            {
                                createdon = entity.GetAttributeValue("createdon");
                            }
                            else if (context.PreEntityImages.Contains("PreImage"))
                            {
                                Entity PreImage = context.PreEntityImages["PreImage"];

                                if (PreImage.Contains("createdon"))
                                {
                                    createdon = PreImage.GetAttributeValue("createdon");
                                }
                            }

                            if (createdon != null && entity.Attributes.Contains("modifiedon"))
                            {
                                entity["modifiedon"] = createdon;
                            }
                            else if (createdon != null)
                            {
                                entity.Attributes.Add("modifiedon", createdon);
                            }
                        }
                        break;
                }
            }
            catch (FaultException ex)
            {
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }



External Service call (Web access) from a CRM plug-in Post data and get respnse- CRM Dynamics 2015 / 2013 /2011


Call external web service from CRM Dynamics. Post data and get response object.

var url = "https://postdataurl";
            var pairs = new NameValueCollection()
                       {
                           { "Email", "vikram@test.com" },
                           { "FirstName", "Vikram" },
                           { "InventoryId", "1" },
                       };
            byte[] response = null;
            using (WebClient client = new WebClient())
            {
                response = client.UploadValues(url, "POST", pairs); //Adding post message as input is optional
            }
            var text = System.Text.Encoding.UTF8.GetString(response);


            /*  Equivalent to following Webrequest/ json Call */
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "{\"Email\":\"" + "vikram@test.com" + "\"," +
                    "\"FirstName\":\"" + "Vikram" + "\"," +
                    "\"InventoryId\":" + 3 + "," +
                    "\"bypassCRM\":\"true\"}";
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    text = streamReader.ReadToEnd();
                }
            }
            /* Equivalant Webrequest/ json Call */

         

External Service call (Web access) from a CRM plug-in - CRM Dynamics 2015 / 2013 /2011 (Delete Json Call Message)

Call external web service from CRM Dynamics. Delete Json call
 

Dynamics CRM 2015 / 2013 /2011 – Multi Select Option List / Pick list / Dropdown

Dynamics CRM 2015 / 2013 /2011 – Multi Select Option List / Pick list / Dropdown



1)     Create a HTML Web Resource MultiSelectPicklist.html


<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="sa_jQuery"></script>
<script type="text/javascript" src="sa_JSON"></script>
<script src="ClientGlobalContext.js.aspx"></script>
 
<script type="text/javascript">
 
var PicklistFieldName;
var TextAttributefield;
 
document.onreadystatechange = function () {
if (document.readyState == "complete") {
getDataParam();
}
}
 
function getDataParam() {
//Get the any query string parameters and load
 
var vals = new Array();
if (location.search != "") {
vals = location.search.substr(1).split("&");
for (var i in vals) {
vals[i] = vals[i].replace(/\+/g, " ").split("=");
}
//look for the parameter named 'data'
var found = false;
for (var i in vals) {
if (vals[i][0].toLowerCase() == "data") {
parseDataValue(vals[i][1]);
found = true;
break;
}
}
if (!found) {
noParams();
}
}
else {
noParams();
}
}
 
function setText(element, text) {
if (typeof element.innerText != "undefined") {
element.innerText = text;
}
else {
element.textContent = text;
}
}
 
function parseDataValue(datavalue) {
PicklistFieldName = '';
TextAttributefield = '';
if (datavalue != "") {
vals = decodeURIComponent(datavalue).split("&");
for (var i in vals) {
vals[i] = vals[i].replace(/\+/g, " ").split("=");
}
 
var temp = vals[i][0].split(';');
 
if (temp.length == 2) {
PicklistFieldName = temp[0];
TextAttributefield = temp[1];
}
else {
noParams();
}
}
else {
noParams();
}
}
 
function noParams() {
var message = document.createElement("p");
setText(message, "No data parameter was passed to this page");
 
document.body.appendChild(message);
}
 
function CreateMultiSelectPicklist() {
if (PicklistFieldName != '' && TextAttributefield != '') {
var dropdownOptions = parent.Xrm.Page.getAttribute(PicklistFieldName).getOptions();
var selectedValue = parent.Xrm.Page.getAttribute(TextAttributefield).getValue();
 
parent.Xrm.Page.getControl(PicklistFieldName).setVisible(false);
parent.Xrm.Page.getControl(TextAttributefield).setDisabled(true);
 
// Create Multi Select Picklist with values from input picklist.
$(dropdownOptions).each(function (i, e) {
var rText = $(this)[0].text;
var rvalue = $(this)[0].value;
var isChecked = false;
if (rText != '') {
 
if (selectedValue != null && selectedValue.indexOf(rText) != -1)
isChecked = true;
 
var checkbox = " input type='checkbox'  name='r'/>" + rText + ""
$(checkbox)
.attr("value", rvalue)
.attr("checked", isChecked)
.attr("id", "id" + rvalue)
.attr("style", 'border:none; width:25px; align:left;')
.click(function () {
 
//To Set Picklist Select Text
var selectedYear = parent.Xrm.Page.getAttribute(TextAttributefield).getValue();
if (this.checked) {
if (selectedYear == null)
selectedYear = rText + ";";
else
selectedYear = selectedYear + rText + ";"
}
else {
var tempSelectedtext = rText + ";";
if (selectedYear.indexOf(tempSelectedtext) != -1)
selectedYear = selectedYear.replace(tempSelectedtext, "");
else
selectedYear = selectedYear.replace(rText, "");
}
 
parent.Xrm.Page.getAttribute(TextAttributefield).setValue(selectedYear);
 
})
.appendTo(checkboxList);
}
});
}
}
 
</script>
 
<meta charset="utf-8">
</head>
<body style="border: 1px solid rgb(102, 153, 204); overflow-y: auto; background-color: rgb(255, 255, 255);" onload="CreateMultiSelectPicklist()">
<div id="checkboxList">
</div>
</body>
</html>