Thursday, January 15, 2015

Crm 2011 Soap Examples

RetrieveUserPrivilegesRequest = function (userId, successCallback, errorCallback) {
var requestMain = "";
requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
requestMain += "  <s:Body>";
requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
requestMain += "      <request i:type=\"b:RetrieveUserPrivilegesRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
requestMain += "        <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
requestMain += "          <a:KeyValuePairOfstringanyType>";
requestMain += "            <c:key>UserId</c:key>";
requestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + userId + "</c:value>";
requestMain += "          </a:KeyValuePairOfstringanyType>";
requestMain += "        </a:Parameters>";
requestMain += "        <a:RequestId i:nil=\"true\" />";
requestMain += "        <a:RequestName>RetrieveUserPrivileges</a:RequestName>";
requestMain += "      </request>";
requestMain += "    </Execute>";
requestMain += "  </s:Body>";
requestMain += "</s:Envelope>";

var req = new XMLHttpRequest();
req.open("POST", JCL._getServerUrl(), true);

req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");

req.onreadystatechange = function () {
RetrieveUserPrivilegesResponse(req, successCallback, errorCallback);
};
req.send(requestMain);
};

RetrieveUserPrivilegesResponse = function (req, successCallback, errorCallback) {
///<summary>
/// Recieves the user privileges response
///</summary>
///<param name="req" Type="XMLHttpRequest">
/// The XMLHttpRequest response
///</param>
///<param name="successCallback" Type="Function">
/// The function to perform when an successfult response is returned.
/// For this message no data is returned so a success callback is not really necessary.
///</param>
///<param name="errorCallback" Type="Function">
/// The function to perform when an error is returned.
/// This function accepts a JScript error returned by the _getError function
///</param>
if (req.readyState == 4) {
if (req.status == 200) {
alert(req.responseXML.xml);
if (successCallback !== null) {
successCallback();
}
} else {
errorCallback(JCL._getError(req.responseXML));
}
}
};

getXhr = function () {
///<summary>
/// Get an instance of XMLHttpRequest for all browsers
///</summary>
if (XMLHttpRequest) {
// Chrome, Firefox, IE7+, Opera, Safari
// ReSharper disable InconsistentNaming
return new XMLHttpRequest();
// ReSharper restore InconsistentNaming
}
// IE6
try {
// The latest stable version. It has the best security, performance,
// reliability, and W3C conformance. Ships with Vista, and available
// with other OS's via downloads and updates.
return new ActiveXObject('MSXML2.XMLHTTP.6.0');
} catch (e) {
try {
// The fallback.
return new ActiveXObject('MSXML2.XMLHTTP.3.0');
} catch (e2) {
alert('This browser is not AJAX enabled.');
return null;
}
}
};

errorHandler = function (req) {
///<summary>
/// Private function return an Error object to the errorCallback
///</summary>
///<param name="req" type="XMLHttpRequest">
/// The XMLHttpRequest response that returned an error.
///</param>
///<returns>Error</returns>

var errorMessage = '';
if (req.responseText !== "") {
errorMessage = JSON.parse(req.responseText).error.message.value;
}

return new Error("Error : " + req.status + ": " + req.statusText + ": " + errorMessage);
};

CRM 2011 Rest Query Syntax with example


  1.  SDK.REST.retrieveMultipleRecords("vaccinationprogram", "$select=vaccinationprogramId,VaccinationPeriod, &$filter=VaccinationPeriod/Value  eq  " + obj , results, errorHandler, oncomplete);

   2    var oDataSetName = "distsalesSet";

        // Column names (Pass * to read all columns)
        var columns = "mtdnetsales";
        // Prepare filter
        var filter = "accountid/Id eq guid'" + clinic + "' and Year eq '" + salesyear_py + "'";


 RetrieveMultiple(oDataSetName, columns, filter);

Reference javascript file from HTMLin CRM 2011

When you reference a web resource you should always use the appropriate mechanism to do so. Again, the SDK contains the details but in summary:

Referencing web resources from one of our designers is straight forward and the designer will take care of doing the right thing when referencing the web resource
Referencing web resources from CRM component that don’t have a designer (e.g. Ribbon, Sitemap) should always use the $webresource directive
Referencing web resources from other web resources (e.g. an html page referencing a js library) should always use RELATIVE paths.
All the above boils down to one important fact; depending on the deployment type (and other configuration such as domain name, caching, etc) that CRM is running the absolute URL of a web resource will be different.  Simple example, a web resource whose unique name is “myprefix_/mypage.html” will translate into the following URLs:

CRM Online: https://myorg.crm.dynamics.com/Webresources/myprefix_/mypage.html
CRM On-premises: http://myserver/myorg/Webresources/myprefix_/mypage.html
So now you see why is so important to reference web resources appropriately. Both the CRM designers and the $webresource directive will take care of constructing the correct URL (and will also provide buil-in caching capabilities). As for referencing one web resource from another as long as you use relative references you should be fine. Just remember that any directory below /Webresources is out of your control.  In the example if myprefix_/mypage.html wants to reference a js file under the custom scripts directory (e.g. the web resource unique name of the js file is ”myprefix_/scripts/myscript.js” the code would look like this

<html>
<head>
<script src=”scripts/myscript.js”
</head>

</html>


Notice how I referenced the script file using relative URLs, this would cause the browser to traverse forward and find the correct js file on the scripts directory (simulated using the name of the script file). The above will work for all CRM deployments without having to change a single line of code.

Update parent record based on multiple fields

Here’s an extremely simplified example of a plug-in. We have parent record with a field for total, and a single child with unit and rate. When either unit or rate changes, we want to multiply these and update to the total of the parent.
Design Notes
  • Because user may only update units and not update rate, we cannot use target which would only include the attributes that were actually updated. Therefore, we use image to make sure we get the necessary attributes, without having to do additional data retrieve.
  • The plug-in is post-update, so we will have access to post-image, showing all values like they are after update.
  • When registering the plugin, we set filtering attributes to include only rate and units. Therefore, plugin will not trigger needlessly if something unrelated updates.
  • When setting up the Image, we only need rate, units and parent ID.
Plug-in Code
using System;
using Microsoft.Xrm.Sdk;

namespace CRM
{
    public class Update : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context =
                (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            // Get a reference to the Organization service.
            IOrganizationServiceFactory factory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);

            if (context.InputParameters != null)
            {
                //entity = (Entity)context.InputParameters["Target"];
                //Instead of getting entity from Target, we use the Image
                Entity entity = context.PostEntityImages["PostImage"];

                Money rate = (Money)entity.Attributes["po_rate"];
                int units = (int)entity.Attributes["po_units"];
                EntityReference parent = (EntityReference)entity.Attributes["po_parentid"];

                //Multiply
                Money total = new Money(rate.Value * units);

                //Set the update entity
                Entity parententity = new Entity("po_parententity");
                parententity.Id = parent.Id;
                parententity.Attributes["po_total"] = total;

                //Update
                service.Update(parententity);

            }

        }

    }
}

Update same record based on multiple fields

This example is similar to the one above, but let’s assume our total is on same entity.
  • In order to change the total on the fly, the plug-in needs to be pre-update
  • This means we do not have access to post image, and have to use the pre-image instead. Therefore, we need to get all the changed values from the target, and unchanged values from the image.
Plug-in Code
if (context.InputParameters != null)
            {
                //Get Target - includes everything changed
                Entity entity = (Entity)context.InputParameters["Target"];

                //Get Pre Image
                Entity image = context.PreEntityImages["PreImage"];

                //If value was changed, get it from target.
                //Else, get the value from preImage
                Money rate = null;
                if(entity.Attributes.Contains("po_rate"))
                    rate = (Money)entity.Attributes["po_rate"];
                else
                    rate =  (Money)image.Attributes["po_rate"];
                int units = 0;
                if (entity.Attributes.Contains("po_units"))
                    units = (int)entity.Attributes["po_units"];
                else
                    units = (int)image.Attributes["po_units"];

                //Multiply
                Money total = new Money(rate.Value * units);

                //Set the value to target
                entity.Attributes.Add("po_total",total);

                //No need to issue additional update
            }
There is no need to use service.update here.

Field security Profile is system administrator


select * from SystemUser
where SystemUserId in
(
    select SystemUserId from SystemUserProfiles
    where FieldSecurityProfileId in
    (
        select FieldSecurityProfileId from FieldSecurityProfile
        where Description = 'System Administrator'
    )
)

Custom WorkFlow to Send Email with PDF formatted Report as Attachment

Introduction

In some cases, we have to send Email to customers with a Report in Pdf format as an attachment.

Background

Once I had the same requirement. To do this, we have to follow three steps.

First to retrieve the Report,
Second to convert the Report to Pdf format and
Last to send an Email with the Pdf as attachment.

below is the Url where it's already done

https://mscrmmindfire.wordpress.com/2013/11/20/custom-workflow-to-send-email-with-pdf-formatted-report-as-attachment/