Showing posts with label jscript. Show all posts
Showing posts with label jscript. Show all posts

Saturday, November 12, 2016

Giving Up My MVP!!

Yes, I am giving up my MVP award at the end of the year.  I am retiring it to go work or Microsoft as a Premier Field Engineer.  I am shocked at how much I have to learn and am so excited for where this adventure takes me in the future.  I will try to keep you all updated.   I am so thrilled to have helped so many people over the years.  I know that I have made web requests over JScript and .NET much easier for some people and I continue to get a quarter of a million page views a year.

Thanks!!

Tuesday, November 12, 2013

CRM 4.0 Event.mode Syntax Killed at Some Point in CRM 2011

Don't know why (or with what Update Rollup) event.Mode was removed, but in UR-15, event.Mode does not work as documented here:

http://msdn.microsoft.com/en-us/library/cc150868.aspx

It's alright though, in CRM 2011 they have a new construct documented here you can change your code to utilize.

http://msdn.microsoft.com/en-us/library/gg509060.aspx

Just  a quick tip for your Tuesday in case you install UR-15 and bump into this!

UPDATE:  It helps to understand how to pass the context as the first parameter as shown in the blogpost below, if you are having trouble after reading the documentation below, check this out:
http://rajeevpentyala.wordpress.com/2011/12/13/jscript-validation-on-activationdeactivation-of-record-in-crm-2011/

UPDATE 2:  It seems that this might only be a problem if using IE 10.  There are other CRM 4.0 syntax items that won't work properly for IE 10 that I bumped into also yesterday, but most things still work.


-

Tuesday, June 11, 2013

Format of Jscript SOAP Responses in Microsoft Dynamics CRM 2011 Organization Service has Changed in UR 12!

You used to be able to pass in your response.responseXML.xml into a function like the one below to parse out a response and pull individual attributes.

function parseResponse(responseXML, attributename) {

    debugger;
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.loadXML(responseXML);
    x=xmlDoc.getElementsByTagName("a:KeyValuePairOfstringanyType");
    for (i=0;i<x.length;i++)
   {
      if (x[i].childNodes[0].text == attributename)
      {
         //we decode the base 64 contents and alert the HTML of the Iframe
          alert(x[i].childNodes[1].text);
      }
      
   } 
}

PROBLEM:  With UR 12 and above you can still use this type of function but the responseXML property no longer exists on the response object.

SOLUTION: now instead of passing in your myresponse.responseXML.xml property of your response, now the property of your reponse is just in a  new response property, so the new syntax would just be myresponse.response

I hope this helps!!

-

Tuesday, February 19, 2013

CRM 4 Client Side SDK Will Not Work In Orion Release

Heads up, if you still use the 4.0 client-side SDK you won't be able to in Orion.  It's not supported and it won't work.   You might want to start migrating those customizations over if you are going to be planning an upgrade to the Orion release.

-Happy Tuesday!


Monday, August 20, 2012

Query a User's Schedule for Open Time Blocks Using .NET and Jscript in Microsoft Dynamics CRM 2011

This illustration shows how to query a user's schedule for open time blocks using C# or Jscript in Microsoft Dynamics CRM 2011 with QueryScheduleRequest.
    Ok, here is what the code looks like!
    First in C#:

     WhoAmIRequest reqWAI = new WhoAmIRequest();
     WhoAmIResponse respWAI = (WhoAmIResponse)_serviceProxy.Execute(reqWAI);
    
                                                  
     QueryScheduleRequest reqSchedule = new QueryScheduleRequest();
     reqSchedule.ResourceId = respWAI.UserId;
     reqSchedule.Start = DateTime.Now;
     reqSchedule.End = DateTime.Today.AddDays(3);
     reqSchedule.TimeCodes = new TimeCode[] { TimeCode.Available };
    
     QueryScheduleResponse respSchedule = (QueryScheduleResponse)service.Execute(reqSchedule);
    
     
     if (respSchedule.TimeInfos.Length > 0)
     {
         //act on time slots
     }
    

    If you need help instantiating a service object in .NET within a plugin check out this post:
    http://mileyja.blogspot.com/2011/04/instantiating-service-object-within.html

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

    Now in Jscript


    This example is asynchronous, if you want to learn how to make JScript SOAP calls synchronously please visit this posthttp://mileyja.blogspot.com/2011/07/using-jscript-to-access-soap-web.html

    
    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 () {
                   ///<summary>
                   /// Returns the URL for the SOAP endpoint using the context information available in the form
                   /// or HTML Web resource.
                   ///</summary>
                   var ServicePath = "/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 + ServicePath;
                   }, 
               QueryScheduleRequest: function () {
                   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:QueryScheduleRequest\" 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>ResourceId</c:key>";
                   requestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">6e219f51-0310-4c4d-8c60-1c524e2ba7b3</c:value>";
                   requestMain += "          </a:KeyValuePairOfstringanyType>";
                   requestMain += "          <a:KeyValuePairOfstringanyType>";
                   requestMain += "            <c:key>Start</c:key>";
                   requestMain += "            <c:value i:type=\"d:dateTime\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">2012-08-20T10:10:38.910063-05:00</c:value>";
                   requestMain += "          </a:KeyValuePairOfstringanyType>";
                   requestMain += "          <a:KeyValuePairOfstringanyType>";
                   requestMain += "            <c:key>End</c:key>";
                   requestMain += "            <c:value i:type=\"d:dateTime\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">2012-08-23T00:00:00-05:00</c:value>";
                   requestMain += "          </a:KeyValuePairOfstringanyType>";
                   requestMain += "          <a:KeyValuePairOfstringanyType>";
                   requestMain += "            <c:key>TimeCodes</c:key>";
                   requestMain += "            <c:value i:type=\"b:ArrayOfTimeCode\">";
                   requestMain += "              <b:TimeCode>Available</b:TimeCode>";
                   requestMain += "            </c:value>";
                   requestMain += "          </a:KeyValuePairOfstringanyType>";
                   requestMain += "        </a:Parameters>";
                   requestMain += "        <a:RequestId i:nil=\"true\" />";
                   requestMain += "        <a:RequestName>QuerySchedule</a:RequestName>";
                   requestMain += "      </request>";
                   requestMain += "    </Execute>";
                   requestMain += "  </s:Body>";
                   requestMain += "</s:Envelope>";
                   var req = new XMLHttpRequest();
                   req.open("POST", SDK.SAMPLES._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");
                   var successCallback = null;
                   var errorCallback = null;
                   req.onreadystatechange = function () { SDK.SAMPLES.QueryScheduleResponse(req, successCallback, errorCallback); };
                   req.send(requestMain);
               },
           QueryScheduleResponse: function (req, successCallback, errorCallback) {
                   ///<summary>
                   /// Recieves the assign 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) {
                   if (successCallback != null)
                   { successCallback(); }
                   }
                   else {
                       errorCallback(SDK.SAMPLES._getError(req.responseXML));
                   }
               }
           },
           _getError: function (faultXml) {
               ///<summary>
               /// Parses the WCF fault returned in the event of an error.
               ///</summary>
               ///<param name="faultXml" Type="XML">
               /// The responseXML property of the XMLHttpRequest response.
               ///</param>
               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
    };
    
    


    To understand how to parse the response please review my post on using the DOM parser.
    Now you can call the SDK.SAMPLES.QueryScheduleRequest function from your form jscript handler.


    Thats all there is to it!
    -

    Wednesday, August 8, 2012

    Query Audit Data in Microsoft Dynamics CRM 2011 to Determine When A User Last Logged In

    This example will show you how to Query audit data in .NET (C#) and Jscript to determine when a user last logged in to the system.

    Important Notes: The way access auditing currently works in CRM it will only record access to the system every 4 hours for someone.  So you can tell when someone logged in, but you won't be able to tell when they logged in again unless the subsequent login was more than four hours later.  Also, access auditing wasn't added to CRM 2011 until Update Rollup 5.  So you need to have CRM Online or On-Premise with at least Update Rollup 5 installed to use access auditing.

    C# Example: 


    RetrieveMultipleRequest rmr = new RetrieveMultipleRequest();
    RetrieveMultipleResponse resp = new RetrieveMultipleResponse();
    SystemUser wr = new SystemUser();
    
    QueryExpression query = new QueryExpression()
    {
        EntityName = "audit",
        ColumnSet = new ColumnSet(true),
        Criteria = new FilterExpression
        {
            FilterOperator = LogicalOperator.And,
            Conditions = 
              {
                  new ConditionExpression
                  {
                      AttributeName = "operation",
                      Operator = ConditionOperator.Equal,
                      Values = { 4 }  //access
                  },
                  new ConditionExpression
                  {
                      AttributeName = "objectid",
                      Operator = ConditionOperator.Equal,
                      Values = { "6e219f51-0310-4c4d-8c60-1c524e2ba7b3" }  //my user id
                  }
              
              //
              }
    
    
        },
        Orders = 
        {
            new OrderExpression
            {
                AttributeName = "createdon",
                OrderType = OrderType.Descending
            }
        }
    };
    
    rmr.Query = query;
    resp = (RetrieveMultipleResponse)slos.Execute(rmr);
    
    

    Now in J-SCRIPT :

    
    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 () {
                   ///<summary>
                   /// Returns the URL for the SOAP endpoint using the context information available in the form
                   /// or HTML Web resource.
                   ///</summary>
                   var ServicePath = "/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 + ServicePath;
                   }, 
               GetUserLastLoggedInRequest: function () {
                   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=\"a:RetrieveMultipleRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\">";
                   requestMain += "        <a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
                   requestMain += "          <a:KeyValuePairOfstringanyType>";
                   requestMain += "            <b:key>Query</b:key>";
                   requestMain += "            <b:value i:type=\"a:QueryExpression\">";
                   requestMain += "              <a:ColumnSet>";
                   requestMain += "                <a:AllColumns>true</a:AllColumns>";
                   requestMain += "                <a:Columns xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" />";
                   requestMain += "              </a:ColumnSet>";
                   requestMain += "              <a:Criteria>";
                   requestMain += "                <a:Conditions>";
                   requestMain += "                  <a:ConditionExpression>";
                   requestMain += "                    <a:AttributeName>operation</a:AttributeName>";
                   requestMain += "                    <a:Operator>Equal</a:Operator>";
                   requestMain += "                    <a:Values xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">";
                   requestMain += "                      <c:anyType i:type=\"d:int\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">4</c:anyType>";
                   requestMain += "                    </a:Values>";
                   requestMain += "                  </a:ConditionExpression>";
                   requestMain += "                  <a:ConditionExpression>";
                   requestMain += "                    <a:AttributeName>objectid</a:AttributeName>";
                   requestMain += "                    <a:Operator>Equal</a:Operator>";
                   requestMain += "                    <a:Values xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">";
                   requestMain += "                      <c:anyType i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">6e219f51-0310-4c4d-8c60-1c524e2ba7b3</c:anyType>";
                   requestMain += "                    </a:Values>";
                   requestMain += "                  </a:ConditionExpression>";
                   requestMain += "                </a:Conditions>";
                   requestMain += "                <a:FilterOperator>And</a:FilterOperator>";
                   requestMain += "                <a:Filters />";
                   requestMain += "              </a:Criteria>";
                   requestMain += "              <a:Distinct>false</a:Distinct>";
                   requestMain += "              <a:EntityName>audit</a:EntityName>";
                   requestMain += "              <a:LinkEntities />";
                   requestMain += "              <a:Orders>";
                   requestMain += "                <a:OrderExpression>";
                   requestMain += "                  <a:AttributeName>createdon</a:AttributeName>";
                   requestMain += "                  <a:OrderType>Descending</a:OrderType>";
                   requestMain += "                </a:OrderExpression>";
                   requestMain += "              </a:Orders>";
                   requestMain += "              <a:PageInfo>";
                   requestMain += "                <a:Count>0</a:Count>";
                   requestMain += "                <a:PageNumber>0</a:PageNumber>";
                   requestMain += "                <a:PagingCookie i:nil=\"true\" />";
                   requestMain += "                <a:ReturnTotalRecordCount>false</a:ReturnTotalRecordCount>";
                   requestMain += "              </a:PageInfo>";
                   requestMain += "              <a:NoLock>false</a:NoLock>";
                   requestMain += "            </b:value>";
                   requestMain += "          </a:KeyValuePairOfstringanyType>";
                   requestMain += "        </a:Parameters>";
                   requestMain += "        <a:RequestId i:nil=\"true\" />";
                   requestMain += "        <a:RequestName>RetrieveMultiple</a:RequestName>";
                   requestMain += "      </request>";
                   requestMain += "    </Execute>";
                   requestMain += "  </s:Body>";
                   requestMain += "</s:Envelope>";
                   var req = new XMLHttpRequest();
                   req.open("POST", SDK.SAMPLES._getServerUrl(), false)
                   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.send(requestMain);
                   //work with the response here
                   //var strResponse = req.responseXML.xml;
                   //alert(strResponse.toString());
               },
     __namespace: true
    };
    
    

    Now you can call this jscript from a webresource by calling SDK.SAMPLES.GetUserLastLoggedIn()  All you should need to change (pass in) with this particular call would be the guid of the user you want to get the last access record for.

    - I hope this helps

    -

    Thursday, July 12, 2012

    How to Build an HTML/JScript Configuration Web Resource for Microsoft Dynamics CRM 2011


    Web Resources can be used to create an interface to allow end-users to easily configure your solution after it's been installed.  This is ideal for storing keys and other sorts of registration or configuration information related to the solution.

    Download the Sample here: http://code.msdn.microsoft.com/Sample-HTMLJScript-172cd74e

    For step-by-step instructions on how to install a configuration page (this one is already installed) and work with it from an end-user standpoint you can visit Mahender Pal's blog here:
    http://mahenderpal.wordpress.com/2011/07/26/step-by-step-adding-configuration-page-in-solution-ms-crm-2011/

    Building the Sample

    1. First you must unzip the download file and install the included zip file SampleConfiguredSolution_1_0.zip
    2. Next you must Import and Publish the  SampleConfiguredSolution_1_0.zip into your Microsoft Dynamics CRM 2011 instance.  Your instance can be On-Premise or Online.


    Description

    After you install the solution there are only two main components worth noting.  
    1. A custom entity used to store configuration data.  I chose to use a custom entity instead of an XML file or other mechanism due to the ease of securing and manipulating the data.  The data is easy to secure because, as a custom entity, it uses the standard role-based security already included in CRM and by default will only be available to administrators.  The data is also easier to manipulate because if stored as an XML web resource it is stored in the content attribute of the webresource entity.  This means that you have to follow these steps to work with the data.
    - un-encode the content attribute (it is stored as a base-64 encoded string)
    - parse the XML 
    - update the values
    - re-encode the attribute data in base-64
    - make an update call
    It's just more complicated.

    2. An HTML webresource that includes jscript that contains the GUI for working with the configuration data and also has jscript web service calls wired up inside that facilitate saving and retrieving the data.
    The logic is easy:
    When page loads it checks for a configuration record with a specific name.  If it finds the record it will load the data into the GUI.  
    When the update button is pressed it checks if the record existed or not and creates it if it didn't exist otherwise it will update the record.


    Source Code Files

    • SampleConfiguredSolution.zip - Download Zip File
    • SampleConfiguredSolution_1_0.zip - CRM 2011 Unmanaged Solution File

    Tuesday, July 10, 2012

    Using the Dynamic Type in Silverlight to Easily Access The Client-Side API in Microsoft Dynamics CRM 2011

    This is a neat little trick to be able to easily work with the client-side API in CRM 2011 from within Silverlight using the "Dynamic" type.

    1. Add a reference to Microsoft.CSharp from the .NET tab in your project.

    2. Now you are ready to go.  The Dynamic type is one that allows you to write your code but allow it to not be evaluated until runtime.  This means that the compiler won't throw an error if your syntax is bad though so you will want to be precise.

    The example given below illustrates getting the form type and verifying it is an update form and then if it is we are calling a function from a jscript webresource attached to the form (that is part of a namespace).  I also embedded a little call to get the entity ID in there also.  It makes it hard to remember that you are working in C# sometimes.

    dynamic xrm = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");
    var formType = xrm.Page.ui.getFormType();
    string strFormID = xrm.Page.data.entity.getId();
    if (formType == 2)
    {
        dynamic sdk = (ScriptObject)HtmlPage.Window.GetProperty("SDK");
        sdk.SAMPLES.TriggerActionsRequest();
    }
    


    - I hope this helps!

    Tuesday, June 12, 2012

    Export a Saved Import Map in Microsoft Dynamics CRM 2011 Using C# or JScript

    This illustration shows how to export a saved import map in Microsoft Dynamics CRM 2011 with ExportMappingsImportMapRequest.  This example will be given in Jscript (SOAP) and in C# (.NET).
      Ok, here is what the code looks like!
      First in C#:

      ExportMappingsImportMapRequest req = new ExportMappingsImportMapRequest();
      req.ExportIds = false;
      req.ImportMapId = new Guid("455B72E2-9863-4984-AEF2-A26C16AFBAD6");
      ExportMappingsImportMapResponse resp = (ExportMappingsImportMapResponse)service.Execute(req);
      

      If you need help instantiating a service object in .NET within a plugin check out this post:
      http://mileyja.blogspot.com/2011/04/instantiating-service-object-within.html

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

      Now in Jscript


      This example is asynchronous, if you want to learn how to make JScript SOAP calls synchronously please visit this posthttp://mileyja.blogspot.com/2011/07/using-jscript-to-access-soap-web.html

      
      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 () {
                     ///<summary>
                     /// Returns the URL for the SOAP endpoint using the context information available in the form
                     /// or HTML Web resource.
                     ///</summary>
                     var ServicePath = "/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 + ServicePath;
                     }, 
                 ExportMappingsImportMapRequest: function () {
                     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:ExportMappingsImportMapRequest\" 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>ImportMapId</c:key>";
                     requestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">455b72e2-9863-4984-aef2-a26c16afbad6</c:value>";
                     requestMain += "          </a:KeyValuePairOfstringanyType>";
                     requestMain += "          <a:KeyValuePairOfstringanyType>";
                     requestMain += "            <c:key>ExportIds</c:key>";
                     requestMain += "            <c:value i:type=\"d:boolean\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">false</c:value>";
                     requestMain += "          </a:KeyValuePairOfstringanyType>";
                     requestMain += "        </a:Parameters>";
                     requestMain += "        <a:RequestId i:nil=\"true\" />";
                     requestMain += "        <a:RequestName>ExportMappingsImportMap</a:RequestName>";
                     requestMain += "      </request>";
                     requestMain += "    </Execute>";
                     requestMain += "  </s:Body>";
                     requestMain += "</s:Envelope>";
                     var req = new XMLHttpRequest();
                     req.open("POST", SDK.SAMPLES._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");
                     var successCallback = null;
                     var errorCallback = null;
                     req.onreadystatechange = function () { SDK.SAMPLES.ExportMappingsImportMapResponse(req, successCallback, errorCallback); };
                     req.send(requestMain);
                 },
             ExportMappingsImportMapResponse: function (req, successCallback, errorCallback) {
                     ///<summary>
                     /// Recieves the assign 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) {
                     if (successCallback != null)
                     { successCallback(); }
                     }
                     else {
                         errorCallback(SDK.SAMPLES._getError(req.responseXML));
                     }
                 }
             },
             _getError: function (faultXml) {
                 ///<summary>
                 /// Parses the WCF fault returned in the event of an error.
                 ///</summary>
                 ///<param name="faultXml" Type="XML">
                 /// The responseXML property of the XMLHttpRequest response.
                 ///</param>
                 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
      };
      


      To understand how to parse the response please review my post on using the DOM parser.
      Now you can call the SDK.SAMPLES.ExportMappingsImportMapRequest function from your form jscript handler.


      Thats all there is to it!
      -

      Friday, June 8, 2012

      Book an Appointment in Microsoft Dynamics CRM 2011 Using C# or Jscript

      This illustration shows how to book an appointment in Microsoft Dynamics CRM 2011 with BookRequest.  This example will be given in Jscript (SOAP) and in C# (.NET).
        Ok, here is what the code looks like!
        First in C#:

        WhoAmIRequest userRequest = new WhoAmIRequest();
        WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);
        
        // Create the ActivityParty instance.
        ActivityParty party = new ActivityParty
        {
            PartyId = new EntityReference(SystemUser.EntityLogicalName, userResponse.UserId)
        };
        
        // Create the appointment instance.
        Appointment appointment = new Appointment
        {
            Subject = "Test Appointment",
            Description = "Test Appointment created using the BookRequest Message.",
            ScheduledStart = DateTime.Now.AddHours(1),
            ScheduledEnd = DateTime.Now.AddHours(2),
            Location = "Office",
            RequiredAttendees = new ActivityParty[] { party },
            Organizer = new ActivityParty[] { party }
        };
        
        // Use the Book request message.
        BookRequest req = new BookRequest
        {
            Target = appointment
        };
        BookResponse resp = (BookResponse)service.Execute(req);
        Guid _appointmentId = resp.ValidationResult.ActivityId;
        
        
        This C# code was adapted from MSDN examples located at http://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.bookrequest.aspx

        If you need help instantiating a service object in .NET within a plugin check out this post:
        http://mileyja.blogspot.com/2011/04/instantiating-service-object-within.html

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

        Now in Jscript


        This example is asynchronous, if you want to learn how to make JScript SOAP calls synchronously please visit this posthttp://mileyja.blogspot.com/2011/07/using-jscript-to-access-soap-web.html

        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 () {
                       ///<summary>
                       /// Returns the URL for the SOAP endpoint using the context information available in the form
                       /// or HTML Web resource.
                       ///</summary>
                       var ServicePath = "/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 + ServicePath;
                       }, 
                   BookRequest: function () {
                       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:BookRequest\" 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>Target</c:key>";
                       requestMain += "            <c:value i:type=\"a:Entity\">";
                       requestMain += "              <a:Attributes>";
                       requestMain += "                <a:KeyValuePairOfstringanyType>";
                       requestMain += "                  <c:key>subject</c:key>";
                       requestMain += "                  <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">Test Appointment</c:value>";
                       requestMain += "                </a:KeyValuePairOfstringanyType>";
                       requestMain += "                <a:KeyValuePairOfstringanyType>";
                       requestMain += "                  <c:key>description</c:key>";
                       requestMain += "                  <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">Test Appointment created using the BookRequest Message.</c:value>";
                       requestMain += "                </a:KeyValuePairOfstringanyType>";
                       requestMain += "                <a:KeyValuePairOfstringanyType>";
                       requestMain += "                  <c:key>scheduledstart</c:key>";
                       requestMain += "                  <c:value i:type=\"d:dateTime\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">2012-06-08T09:42:45.8655676-05:00</c:value>";
                       requestMain += "                </a:KeyValuePairOfstringanyType>";
                       requestMain += "                <a:KeyValuePairOfstringanyType>";
                       requestMain += "                  <c:key>scheduledend</c:key>";
                       requestMain += "                  <c:value i:type=\"d:dateTime\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">2012-06-08T10:42:45.8655676-05:00</c:value>";
                       requestMain += "                </a:KeyValuePairOfstringanyType>";
                       requestMain += "                <a:KeyValuePairOfstringanyType>";
                       requestMain += "                  <c:key>location</c:key>";
                       requestMain += "                  <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">Office</c:value>";
                       requestMain += "                </a:KeyValuePairOfstringanyType>";
                       requestMain += "                <a:KeyValuePairOfstringanyType>";
                       requestMain += "                  <c:key>requiredattendees</c:key>";
                       requestMain += "                  <c:value i:type=\"a:EntityCollection\">";
                       requestMain += "                    <a:Entities>";
                       requestMain += "                      <a:Entity>";
                       requestMain += "                        <a:Attributes>";
                       requestMain += "                          <a:KeyValuePairOfstringanyType>";
                       requestMain += "                            <c:key>partyid</c:key>";
                       requestMain += "                            <c:value i:type=\"a:EntityReference\">";
                       requestMain += "                              <a:Id>6e219f51-0310-4c4d-8c60-1c524e2ba7b3</a:Id>";
                       requestMain += "                              <a:LogicalName>systemuser</a:LogicalName>";
                       requestMain += "                              <a:Name i:nil=\"true\" />";
                       requestMain += "                            </c:value>";
                       requestMain += "                          </a:KeyValuePairOfstringanyType>";
                       requestMain += "                        </a:Attributes>";
                       requestMain += "                        <a:EntityState i:nil=\"true\" />";
                       requestMain += "                        <a:FormattedValues />";
                       requestMain += "                        <a:Id>00000000-0000-0000-0000-000000000000</a:Id>";
                       requestMain += "                        <a:LogicalName>activityparty</a:LogicalName>";
                       requestMain += "                        <a:RelatedEntities />";
                       requestMain += "                      </a:Entity>";
                       requestMain += "                    </a:Entities>";
                       requestMain += "                    <a:EntityName i:nil=\"true\" />";
                       requestMain += "                    <a:MinActiveRowVersion i:nil=\"true\" />";
                       requestMain += "                    <a:MoreRecords>false</a:MoreRecords>";
                       requestMain += "                    <a:PagingCookie i:nil=\"true\" />";
                       requestMain += "                    <a:TotalRecordCount>0</a:TotalRecordCount>";
                       requestMain += "                    <a:TotalRecordCountLimitExceeded>false</a:TotalRecordCountLimitExceeded>";
                       requestMain += "                  </c:value>";
                       requestMain += "                </a:KeyValuePairOfstringanyType>";
                       requestMain += "                <a:KeyValuePairOfstringanyType>";
                       requestMain += "                  <c:key>organizer</c:key>";
                       requestMain += "                  <c:value i:type=\"a:EntityCollection\">";
                       requestMain += "                    <a:Entities>";
                       requestMain += "                      <a:Entity>";
                       requestMain += "                        <a:Attributes>";
                       requestMain += "                          <a:KeyValuePairOfstringanyType>";
                       requestMain += "                            <c:key>partyid</c:key>";
                       requestMain += "                            <c:value i:type=\"a:EntityReference\">";
                       requestMain += "                              <a:Id>6e219f51-0310-4c4d-8c60-1c524e2ba7b3</a:Id>";
                       requestMain += "                              <a:LogicalName>systemuser</a:LogicalName>";
                       requestMain += "                              <a:Name i:nil=\"true\" />";
                       requestMain += "                            </c:value>";
                       requestMain += "                          </a:KeyValuePairOfstringanyType>";
                       requestMain += "                        </a:Attributes>";
                       requestMain += "                        <a:EntityState i:nil=\"true\" />";
                       requestMain += "                        <a:FormattedValues />";
                       requestMain += "                        <a:Id>00000000-0000-0000-0000-000000000000</a:Id>";
                       requestMain += "                        <a:LogicalName>activityparty</a:LogicalName>";
                       requestMain += "                        <a:RelatedEntities />";
                       requestMain += "                      </a:Entity>";
                       requestMain += "                    </a:Entities>";
                       requestMain += "                    <a:EntityName i:nil=\"true\" />";
                       requestMain += "                    <a:MinActiveRowVersion i:nil=\"true\" />";
                       requestMain += "                    <a:MoreRecords>false</a:MoreRecords>";
                       requestMain += "                    <a:PagingCookie i:nil=\"true\" />";
                       requestMain += "                    <a:TotalRecordCount>0</a:TotalRecordCount>";
                       requestMain += "                    <a:TotalRecordCountLimitExceeded>false</a:TotalRecordCountLimitExceeded>";
                       requestMain += "                  </c:value>";
                       requestMain += "                </a:KeyValuePairOfstringanyType>";
                       requestMain += "              </a:Attributes>";
                       requestMain += "              <a:EntityState i:nil=\"true\" />";
                       requestMain += "              <a:FormattedValues />";
                       requestMain += "              <a:Id>00000000-0000-0000-0000-000000000000</a:Id>";
                       requestMain += "              <a:LogicalName>appointment</a:LogicalName>";
                       requestMain += "              <a:RelatedEntities />";
                       requestMain += "            </c:value>";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "        </a:Parameters>";
                       requestMain += "        <a:RequestId i:nil=\"true\" />";
                       requestMain += "        <a:RequestName>Book</a:RequestName>";
                       requestMain += "      </request>";
                       requestMain += "    </Execute>";
                       requestMain += "  </s:Body>";
                       requestMain += "</s:Envelope>";
                       var req = new XMLHttpRequest();
                       req.open("POST", SDK.SAMPLES._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");
                       var successCallback = null;
                       var errorCallback = null;
                       req.onreadystatechange = function () { SDK.SAMPLES.BookResponse(req, successCallback, errorCallback); };
                       req.send(requestMain);
                   },
               BookResponse: function (req, successCallback, errorCallback) {
                       ///<summary>
                       /// Recieves the assign 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) {
                       if (successCallback != null)
                       { successCallback(); }
                       }
                       else {
                           errorCallback(SDK.SAMPLES._getError(req.responseXML));
                       }
                   }
               },
               _getError: function (faultXml) {
                   ///<summary>
                   /// Parses the WCF fault returned in the event of an error.
                   ///</summary>
                   ///<param name="faultXml" Type="XML">
                   /// The responseXML property of the XMLHttpRequest response.
                   ///</param>
                   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
        };
        
        


        To understand how to parse the response please review my post on using the DOM parser.
        Now you can call the SDK.SAMPLES.BookRequest function from your form jscript handler.


        Thats all there is to it!
        -

        Thursday, March 1, 2012

        Validate the Constraints of an Appointment are Met in Microsoft Dynamics CRM 2011 in Jscript or .NET

        This illustration shows how to validate the constraints of an appointment are met in Microsoft Dynamics CRM 2011 with ValidateRequest.  This example will be given in Jscript (SOAP) and in C# (.NET).

        Ok, here is what the code looks like!
        First in C#:
        
        Entity appointment = null;
        appointment = slos.Retrieve("appointment", new Guid("7A1C29A5-3363-E111-B314-1CC1DEF1353B"), new ColumnSet("activityid", "scheduledstart", "scheduledend"));
        ValidateRequest req = new ValidateRequest();
        req.Activities = new EntityCollection();
        req.Activities.Entities.Add(appointment);
        ValidateResponse resp = (ValidateResponse)service.Execute(req);
        
        

        If you need help instantiating a service object in .NET within a plugin check out this post:
        http://mileyja.blogspot.com/2011/04/instantiating-service-object-within.html


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

        Now in Jscript

        This example is asynchronous, if you want to learn how to make JScript SOAP calls synchronously please visit this posthttp://mileyja.blogspot.com/2011/07/using-jscript-to-access-soap-web.html

        
        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 () {
                       ///<summary>
                       /// Returns the URL for the SOAP endpoint using the context information available in the form
                       /// or HTML Web resource.
                       ///</summary>
                       var ServicePath = "/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 + ServicePath;
                       }, 
                   ValidateRequest: function () {
                       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:ValidateRequest\" 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>Activities</c:key>";
                       requestMain += "            <c:value i:type=\"a:EntityCollection\">";
                       requestMain += "              <a:Entities>";
                       requestMain += "                <a:Entity>";
                       requestMain += "                  <a:Attributes>";
                       requestMain += "                    <a:KeyValuePairOfstringanyType>";
                       requestMain += "                      <c:key>activityid</c:key>";
                       requestMain += "                      <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">7a1c29a5-3363-e111-b314-1cc1def1353b</c:value>";
                       requestMain += "                    </a:KeyValuePairOfstringanyType>";
                       requestMain += "                    <a:KeyValuePairOfstringanyType>";
                       requestMain += "                      <c:key>scheduledstart</c:key>";
                       requestMain += "                      <c:value i:type=\"d:dateTime\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">2012-03-01T00:30:00Z</c:value>";
                       requestMain += "                    </a:KeyValuePairOfstringanyType>";
                       requestMain += "                    <a:KeyValuePairOfstringanyType>";
                       requestMain += "                      <c:key>scheduledend</c:key>";
                       requestMain += "                      <c:value i:type=\"d:dateTime\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">2012-03-01T01:00:00Z</c:value>";
                       requestMain += "                    </a:KeyValuePairOfstringanyType>";
                       requestMain += "                  </a:Attributes>";
                       requestMain += "                  <a:EntityState i:nil=\"true\" />";
                       requestMain += "                  <a:FormattedValues>";
                       requestMain += "                    <a:KeyValuePairOfstringstring>";
                       requestMain += "                      <c:key>scheduledstart</c:key>";
                       requestMain += "                      <c:value>3/1/2012 12:30 AM</c:value>";
                       requestMain += "                    </a:KeyValuePairOfstringstring>";
                       requestMain += "                    <a:KeyValuePairOfstringstring>";
                       requestMain += "                      <c:key>scheduledend</c:key>";
                       requestMain += "                      <c:value>3/1/2012 1:00 AM</c:value>";
                       requestMain += "                    </a:KeyValuePairOfstringstring>";
                       requestMain += "                  </a:FormattedValues>";
                       requestMain += "                  <a:Id>7a1c29a5-3363-e111-b314-1cc1def1353b</a:Id>";
                       requestMain += "                  <a:LogicalName>appointment</a:LogicalName>";
                       requestMain += "                  <a:RelatedEntities />";
                       requestMain += "                </a:Entity>";
                       requestMain += "              </a:Entities>";
                       requestMain += "              <a:EntityName i:nil=\"true\" />";
                       requestMain += "              <a:MinActiveRowVersion i:nil=\"true\" />";
                       requestMain += "              <a:MoreRecords>false</a:MoreRecords>";
                       requestMain += "              <a:PagingCookie i:nil=\"true\" />";
                       requestMain += "              <a:TotalRecordCount>0</a:TotalRecordCount>";
                       requestMain += "              <a:TotalRecordCountLimitExceeded>false</a:TotalRecordCountLimitExceeded>";
                       requestMain += "            </c:value>";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "        </a:Parameters>";
                       requestMain += "        <a:RequestId i:nil=\"true\" />";
                       requestMain += "        <a:RequestName>Validate</a:RequestName>";
                       requestMain += "      </request>";
                       requestMain += "    </Execute>";
                       requestMain += "  </s:Body>";
                       requestMain += "</s:Envelope>";
                       var req = new XMLHttpRequest();
                       req.open("POST", SDK.SAMPLES._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");
                       var successCallback = null;
                       var errorCallback = null;
                       req.onreadystatechange = function () { SDK.SAMPLES.ValidateResponse(req, successCallback, errorCallback); };
                       req.send(requestMain);
                   },
               ValidateResponse: function (req, successCallback, errorCallback) {
                       ///<summary>
                       /// Recieves the assign 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) {
                       if (successCallback != null)
                       { successCallback(); }
                       }
                       else {
                           errorCallback(SDK.SAMPLES._getError(req.responseXML));
                       }
                   }
               },
               _getError: function (faultXml) {
                   ///<summary>
                   /// Parses the WCF fault returned in the event of an error.
                   ///</summary>
                   ///<param name="faultXml" Type="XML">
                   /// The responseXML property of the XMLHttpRequest response.
                   ///</param>
                   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
        };
        
        



        To understand how to parse the response please review my post on using the DOM parser.
        Now you can call the SDK.SAMPLES.ValidateRequest function from your form jscript handler.

        Thats all there is to it!
        -

        Tuesday, February 14, 2012

        Submit a Bulk Duplicate Detection Job in Microsoft Dynamics CRM 2011 using C# or Jscript

        This illustration shows how to submit a bulk duplicate detection job in Microsoft Dynamics CRM 2011 with BulkDetectDuplicatesRequest.  This example will be given in Jscript (SOAP) and in C# (.NET).


        NOTES: 

        - You can schedule the job at regular intervals if desired using this request.  See the following link for details. http://msdn.microsoft.com/en-us/library/cc189846.aspx


        Ok, here is what the code looks like!
        First in C#:
        
        BulkDetectDuplicatesRequest req = new BulkDetectDuplicatesRequest();
        //send email to these receipients after job completes
        req.ToRecipients = new Guid[] { new Guid("6E219F51-0310-4C4D-8C60-1C524E2BA7B3") };
        //add cc recipients to the email here if desired
        req.CCRecipients = new Guid[0];
        req.JobName = "testbulkdeletejob";
        req.SendEmailNotification = true;
        
        req.RecurrencePattern = "";
        //example of recurrence pattern 
        //int interval = 30;
        //string pattern = String.Format(System.Globalization.CultureInfo.InvariantCulture, "FREQ=DAILY;INTERVAL={0};", interval);
        //req.RecurrencePattern = pattern;
        req.Query = new QueryExpression()
        {
            EntityName = "account",
            ColumnSet = new ColumnSet(true),
            Criteria = new FilterExpression
            {
                FilterOperator = LogicalOperator.And,
                Conditions = 
                {
              
                    new ConditionExpression
                    {
                        AttributeName = "name",
                        Operator = ConditionOperator.Equal,
                        Values = { "test account in code" }
                    }
                }
            }
        };
         //Guid of email template for email that will be sent (must be a system job email template)
        req.TemplateId = new Guid("D1F0639F-2057-E111-B314-1CC1DEF1353B");
        
        BulkDetectDuplicatesResponse resp = (BulkDetectDuplicatesResponse)service.Execute(req);
        
        

        If you need help instantiating a service object in .NET within a plugin check out this post:
        http://mileyja.blogspot.com/2011/04/instantiating-service-object-within.html


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

        Now in Jscript

        This example is asynchronous, if you want to learn how to make JScript SOAP calls synchronously please visit this posthttp://mileyja.blogspot.com/2011/07/using-jscript-to-access-soap-web.html

        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 () {
                       ///<summary>
                       /// Returns the URL for the SOAP endpoint using the context information available in the form
                       /// or HTML Web resource.
                       ///</summary>
                       var ServicePath = "/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 + ServicePath;
                       }, 
                   BulkDetectDuplicatesRequest: function () {
                       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:BulkDetectDuplicatesRequest\" 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>Query</c:key>";
                       requestMain += "            <c:value i:type=\"a:QueryExpression\">";
                       requestMain += "              <a:ColumnSet>";
                       requestMain += "                <a:AllColumns>true</a:AllColumns>";
                       requestMain += "                <a:Columns xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" />";
                       requestMain += "              </a:ColumnSet>";
                       requestMain += "              <a:Criteria>";
                       requestMain += "                <a:Conditions>";
                       requestMain += "                  <a:ConditionExpression>";
                       requestMain += "                    <a:AttributeName>name</a:AttributeName>";
                       requestMain += "                    <a:Operator>Equal</a:Operator>";
                       requestMain += "                    <a:Values xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">";
                       requestMain += "                      <d:anyType i:type=\"e:string\" xmlns:e=\"http://www.w3.org/2001/XMLSchema\">test account in code</d:anyType>";
                       requestMain += "                    </a:Values>";
                       requestMain += "                  </a:ConditionExpression>";
                       requestMain += "                </a:Conditions>";
                       requestMain += "                <a:FilterOperator>And</a:FilterOperator>";
                       requestMain += "                <a:Filters />";
                       requestMain += "              </a:Criteria>";
                       requestMain += "              <a:Distinct>false</a:Distinct>";
                       requestMain += "              <a:EntityName>account</a:EntityName>";
                       requestMain += "              <a:LinkEntities />";
                       requestMain += "              <a:Orders />";
                       requestMain += "              <a:PageInfo>";
                       requestMain += "                <a:Count>0</a:Count>";
                       requestMain += "                <a:PageNumber>0</a:PageNumber>";
                       requestMain += "                <a:PagingCookie i:nil=\"true\" />";
                       requestMain += "                <a:ReturnTotalRecordCount>false</a:ReturnTotalRecordCount>";
                       requestMain += "              </a:PageInfo>";
                       requestMain += "              <a:NoLock>false</a:NoLock>";
                       requestMain += "            </c:value>";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "          <a:KeyValuePairOfstringanyType>";
                       requestMain += "            <c:key>JobName</c:key>";
                       requestMain += "            <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">testbulkdeletejob</c:value>";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "          <a:KeyValuePairOfstringanyType>";
                       requestMain += "            <c:key>SendEmailNotification</c:key>";
                       requestMain += "            <c:value i:type=\"d:boolean\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">true</c:value>";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "          <a:KeyValuePairOfstringanyType>";
                       requestMain += "            <c:key>TemplateId</c:key>";
                       requestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">d1f0639f-2057-e111-b314-1cc1def1353b</c:value>";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "          <a:KeyValuePairOfstringanyType>";
                       requestMain += "            <c:key>ToRecipients</c:key>";
                       requestMain += "            <c:value i:type=\"d:ArrayOfguid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">";
                       requestMain += "              <d:guid>6e219f51-0310-4c4d-8c60-1c524e2ba7b3</d:guid>";
                       requestMain += "            </c:value>";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "          <a:KeyValuePairOfstringanyType>";
                       requestMain += "            <c:key>CCRecipients</c:key>";
                       requestMain += "            <c:value i:type=\"d:ArrayOfguid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" />";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "          <a:KeyValuePairOfstringanyType>";
                       requestMain += "            <c:key>RecurrencePattern</c:key>";
                       requestMain += "            <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\" />";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "          <a:KeyValuePairOfstringanyType>";
                       requestMain += "            <c:key>RecurrenceStartTime</c:key>";
                       requestMain += "            <c:value i:type=\"d:dateTime\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">0001-01-01T00:00:00</c:value>";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "        </a:Parameters>";
                       requestMain += "        <a:RequestId i:nil=\"true\" />";
                       requestMain += "        <a:RequestName>BulkDetectDuplicates</a:RequestName>";
                       requestMain += "      </request>";
                       requestMain += "    </Execute>";
                       requestMain += "  </s:Body>";
                       requestMain += "</s:Envelope>";
                       var req = new XMLHttpRequest();
                       req.open("POST", SDK.SAMPLES._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");
                       var successCallback = null;
                       var errorCallback = null;
                       req.onreadystatechange = function () { SDK.SAMPLES.BulkDetectDuplicatesResponse(req, successCallback, errorCallback); };
                       req.send(requestMain);
                   },
               BulkDetectDuplicatesResponse: function (req, successCallback, errorCallback) {
                       ///<summary>
                       /// Recieves the assign 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) {
                       if (successCallback != null)
                       { successCallback(); }
                       }
                       else {
                           errorCallback(SDK.SAMPLES._getError(req.responseXML));
                       }
                   }
               },
               _getError: function (faultXml) {
                   ///<summary>
                   /// Parses the WCF fault returned in the event of an error.
                   ///</summary>
                   ///<param name="faultXml" Type="XML">
                   /// The responseXML property of the XMLHttpRequest response.
                   ///</param>
                   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
        };
        
        



        To understand how to parse the response please review my post on using the DOM parser.
        Now you can call the SDK.SAMPLES.BulkDetectDuplicatesRequest function from your form jscript handler.

        Thats all there is to it!
        -

        Monday, February 13, 2012

        Submit a Bulk Delete Job in Microsoft Dynamics CRM 2011 using C# or Jscript

        This illustration shows how to submit a bulk delete job in Microsoft Dynamics CRM 2011 with BulkDeleteRequest.  This example will be given in Jscript (SOAP) and in C# (.NET).

        NOTES: 

        - You can schedule the job at regular intervals if desired using this request.  See the following link for details. http://msdn.microsoft.com/en-us/library/cc189846.aspx

        - You can also define a start date and time for the job to occur.

        - Lastly, this does not really act as a bulk delete request in the same sense as a bulk insert in SQL.  It submits an asynchronous job to the server that runs in the background but deletes the records one by one.  You will not really gain performance by this call versus a normal mass delete, but at least you won't have to babysit it.

        Ok, here is what the code looks like!
        First in C#:
        BulkDeleteRequest req = new BulkDeleteRequest();
        //send email to these receipients after job completes
        req.ToRecipients = new Guid[] { new Guid("6E219F51-0310-4C4D-8C60-1C524E2BA7B3") };
        //add cc recipients to the email here if desired
        req.CCRecipients = new Guid[0];
        req.JobName = "testbulkdeletejob";
        req.SendEmailNotification = true;
        
        req.RecurrencePattern = "";
        //example of recurrence pattern 
           //int interval = 30;
           //string pattern = String.Format(System.Globalization.CultureInfo.InvariantCulture, "FREQ=DAILY;INTERVAL={0};", interval);
           //req.RecurrencePattern = pattern;
        req.QuerySet = new QueryExpression[]
        {
           new QueryExpression()
           {
               EntityName = "account",
               ColumnSet = new ColumnSet(true),
               Criteria = new FilterExpression
               {
                   FilterOperator = LogicalOperator.And,
                   Conditions = 
                  {
                      
                      new ConditionExpression
                      {
                          AttributeName = "name",
                          Operator = ConditionOperator.Equal,
                          Values = { "test account in code" }
                      }
                  }
               }
           }
        };
        BulkDeleteResponse resp = (BulkDeleteResponse)service.Execute(req);
        
        

        If you need help instantiating a service object in .NET within a plugin check out this post:
        http://mileyja.blogspot.com/2011/04/instantiating-service-object-within.html

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

        Now in Jscript


        This example is asynchronous, if you want to learn how to make JScript SOAP calls synchronously please visit this posthttp://mileyja.blogspot.com/2011/07/using-jscript-to-access-soap-web.html

        
        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 () {
                       ///<summary>
                       /// Returns the URL for the SOAP endpoint using the context information available in the form
                       /// or HTML Web resource.
                       ///</summary>
                       var ServicePath = "/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 + ServicePath;
                       }, 
                   BulkDeleteRequest: function () {
                       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:BulkDeleteRequest\" 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>QuerySet</c:key>";
                       requestMain += "            <c:value i:type=\"a:ArrayOfQueryExpression\">";
                       requestMain += "              <a:QueryExpression>";
                       requestMain += "                <a:ColumnSet>";
                       requestMain += "                  <a:AllColumns>true</a:AllColumns>";
                       requestMain += "                  <a:Columns xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" />";
                       requestMain += "                </a:ColumnSet>";
                       requestMain += "                <a:Criteria>";
                       requestMain += "                  <a:Conditions>";
                       requestMain += "                    <a:ConditionExpression>";
                       requestMain += "                      <a:AttributeName>name</a:AttributeName>";
                       requestMain += "                      <a:Operator>Equal</a:Operator>";
                       requestMain += "                      <a:Values xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">";
                       requestMain += "                        <d:anyType i:type=\"e:string\" xmlns:e=\"http://www.w3.org/2001/XMLSchema\">test account in code</d:anyType>";
                       requestMain += "                      </a:Values>";
                       requestMain += "                    </a:ConditionExpression>";
                       requestMain += "                  </a:Conditions>";
                       requestMain += "                  <a:FilterOperator>And</a:FilterOperator>";
                       requestMain += "                  <a:Filters />";
                       requestMain += "                </a:Criteria>";
                       requestMain += "                <a:Distinct>false</a:Distinct>";
                       requestMain += "                <a:EntityName>account</a:EntityName>";
                       requestMain += "                <a:LinkEntities />";
                       requestMain += "                <a:Orders />";
                       requestMain += "                <a:PageInfo>";
                       requestMain += "                  <a:Count>0</a:Count>";
                       requestMain += "                  <a:PageNumber>0</a:PageNumber>";
                       requestMain += "                  <a:PagingCookie i:nil=\"true\" />";
                       requestMain += "                  <a:ReturnTotalRecordCount>false</a:ReturnTotalRecordCount>";
                       requestMain += "                </a:PageInfo>";
                       requestMain += "                <a:NoLock>false</a:NoLock>";
                       requestMain += "              </a:QueryExpression>";
                       requestMain += "            </c:value>";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "          <a:KeyValuePairOfstringanyType>";
                       requestMain += "            <c:key>JobName</c:key>";
                       requestMain += "            <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">testbulkdeletejob</c:value>";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "          <a:KeyValuePairOfstringanyType>";
                       requestMain += "            <c:key>SendEmailNotification</c:key>";
                       requestMain += "            <c:value i:type=\"d:boolean\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">true</c:value>";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "          <a:KeyValuePairOfstringanyType>";
                       requestMain += "            <c:key>ToRecipients</c:key>";
                       requestMain += "            <c:value i:type=\"d:ArrayOfguid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">";
                       requestMain += "              <d:guid>6e219f51-0310-4c4d-8c60-1c524e2ba7b3</d:guid>";
                       requestMain += "            </c:value>";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "          <a:KeyValuePairOfstringanyType>";
                       requestMain += "            <c:key>CCRecipients</c:key>";
                       requestMain += "            <c:value i:type=\"d:ArrayOfguid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" />";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "          <a:KeyValuePairOfstringanyType>";
                       requestMain += "            <c:key>RecurrencePattern</c:key>";
                       requestMain += "            <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\" />";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "          <a:KeyValuePairOfstringanyType>";
                       requestMain += "            <c:key>StartDateTime</c:key>";
                       requestMain += "            <c:value i:type=\"d:dateTime\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">0001-01-01T00:00:00</c:value>";
                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                       requestMain += "        </a:Parameters>";
                       requestMain += "        <a:RequestId i:nil=\"true\" />";
                       requestMain += "        <a:RequestName>BulkDelete</a:RequestName>";
                       requestMain += "      </request>";
                       requestMain += "    </Execute>";
                       requestMain += "  </s:Body>";
                       requestMain += "</s:Envelope>";
                       var req = new XMLHttpRequest();
                       req.open("POST", SDK.SAMPLES._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");
                       var successCallback = null;
                       var errorCallback = null;
                       req.onreadystatechange = function () { SDK.SAMPLES.BulkDeleteResponse(req, successCallback, errorCallback); };
                       req.send(requestMain);
                   },
               BulkDeleteResponse: function (req, successCallback, errorCallback) {
                       ///<summary>
                       /// Recieves the assign 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) {
                       if (successCallback != null)
                       { successCallback(); }
                       }
                       else {
                           errorCallback(SDK.SAMPLES._getError(req.responseXML));
                       }
                   }
               },
               _getError: function (faultXml) {
                   ///<summary>
                   /// Parses the WCF fault returned in the event of an error.
                   ///</summary>
                   ///<param name="faultXml" Type="XML">
                   /// The responseXML property of the XMLHttpRequest response.
                   ///</param>
                   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
        };
        
        



        To understand how to parse the response please review my post on using the DOM parser.
        Now you can call the SDK.SAMPLES.BulkDeleteRequest function from your form jscript handler.

        Thats all there is to it!
        -