Wednesday, December 21, 2011

Add Multiple Entities (Members) to a Marketing List in Microsoft Dynamics CRM 2011 Using .NET or Jscript

This illustration shows how to add a list of entities (members) to a marketing list in Microsoft Dynamics CRM 2011 with AddListMembersListRequest. This example will be given in Jscript (SOAP) and in C# (.NET).

Note: The entity type you add to your marketing list must be consistent with the entity type for the list and must be either an account, contact, or a lead.
Ok, here is what the code looks like!
First in C#:

AddListMembersListRequest req = new AddListMembersListRequest();
req.ListId = new Guid("6CAC04FC-930F-E111-8DB2-1CC1DEF1B5FF");
//add the new list of marketing list memnbers
req.MemberIds = new System.Guid[2];
req.MemberIds[0] = new Guid("DCB265C9-5F0C-E111-BF0B-1CC1DEE89AA8");
req.MemberIds[1] = new Guid("E4B265C9-5F0C-E111-BF0B-1CC1DEE89AA8");
AddListMembersListResponse resp = (AddListMembersListResponse)service.Execute(req);


Now here is the Jscript nicely formatted by the CRM 2011 SOAP formatter. Available at: http://crm2011soap.codeplex.com/

Now in Jscript



if (typeof (SDK) == "undefined")    { SDK = { __namespace: true }; }        //This will establish a more unique namespace for functions in this library. This will reduce the         // potential for functions to be overwritten due to a duplicate name when the library is loaded.        SDK.SAMPLES = {            _getServerUrl: function () {                ///                /// Returns the URL for the SOAP endpoint using the context information available in the form                /// or HTML Web resource.                ///                var OrgServicePath = "/XRMServices/2011/Organization.svc/web";                var serverUrl = "";                if (typeof GetGlobalContext == "function") {                    var context = GetGlobalContext();                    serverUrl = context.getServerUrl();                }                else {                    if (typeof Xrm.Page.context == "object") {                          serverUrl = Xrm.Page.context.getServerUrl();                    }                    else                    { throw new Error("Unable to access the server URL"); }                    }                   if (serverUrl.match(/\/$/)) {                        serverUrl = serverUrl.substring(0, serverUrl.length - 1);                    }                     return serverUrl + OrgServicePath;                },             AddListMembersListRequest: function () {                var requestMain = ""                requestMain += "";                requestMain += "  ";                requestMain += "    ";                requestMain += "      ";                requestMain += "        ";                requestMain += "          ";                requestMain += "            ListId";                requestMain += "            6cac04fc-930f-e111-8db2-1cc1def1b5ff";                requestMain += "          ";                requestMain += "          ";                requestMain += "            MemberIds";                requestMain += "            ";                requestMain += "              dcb265c9-5f0c-e111-bf0b-1cc1dee89aa8";                requestMain += "              e4b265c9-5f0c-e111-bf0b-1cc1dee89aa8";                requestMain += "            ";                requestMain += "          ";                requestMain += "        ";                requestMain += "        ";                requestMain += "        AddListMembersList";                requestMain += "      ";                requestMain += "    ";                requestMain += "  ";                requestMain += "";                var req = new XMLHttpRequest();                req.open("POST", SDK.SAMPLES._getServerUrl(), true)                // Responses will return XML. It isn't possible to return JSON.                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");                var successCallback = null;                var errorCallback = null;                req.onreadystatechange = function () { SDK.SAMPLES.AddListMembersListResponse(req, successCallback, errorCallback); };                req.send(requestMain);            },        AddListMembersListResponse: function (req, successCallback, errorCallback) {                ///                /// Recieves the assign response                ///                ///                /// The XMLHttpRequest response                ///                ///                /// 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.                ///                ///                /// The function to perform when an error is returned.                /// This function accepts a JScript error returned by the _getError function                ///                if (req.readyState == 4) {                if (req.status == 200) {                if (successCallback != null)                { successCallback(); }                }                else {                    errorCallback(SDK.SAMPLES._getError(req.responseXML));                }            }        },        _getError: function (faultXml) {            ///            /// Parses the WCF fault returned in the event of an error.            ///            ///            /// The responseXML property of the XMLHttpRequest response.            ///            var errorMessage = "Unknown Error (Unable to parse the fault)";            if (typeof faultXml == "object") {                try {                    var bodyNode = faultXml.firstChild.firstChild;                    //Retrieve the fault node                    for (var i = 0; i < bodyNode.childNodes.length; i++) {                        var node = bodyNode.childNodes[i];                        //NOTE: This comparison does not handle the case where the XML namespace changes                        if ("s:Fault" == node.nodeName) {                        for (var j = 0; j < node.childNodes.length; j++) {                            var faultStringNode = node.childNodes[j];                            if ("faultstring" == faultStringNode.nodeName) {                                errorMessage = faultStringNode.text;                                break;                            }                        }                        break;                    }                }            }            catch (e) { };         }         return new Error(errorMessage);      },  __namespace: true };  

Now you can call the SDK.SAMPLES.AddListMembersListRequest function from your form jscript handler.


Thats all there is to it!
-