Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, September 11, 2015

CRM Quick Connect from .NET Example App is Out on CodePlex

I wish when I was first learning to code in .NET for Dynamics CRM that I had a really quick example of how to make a connection.  I created this example in CodePlex.  It does little more than pops open a connection to CRM and gives your User ID guid back to you but it will show you how to get that far quickly.  The example applies to Dynamics CRM versions 2011 through 2015.

Download it here:  https://dynamicscrmquickconnect.codeplex.com/


I hope this helps!  Have a great weekend!

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

    -

    Friday, July 27, 2012

    Getting the Text Value of an OptionSetValue Using LINQ in Microsoft Dynamics CRM 2011

    I have seen some interesting things historically when trying to get at the text value of an OptionSetValue in code.  Many times this means making a metadata RetrieveAttributeRequest or something of that nature to get the metadata for the OptionSet.  This is pretty cumbersome in many instances, but the other day I saw an interesting way of doing this put out in a forum question here.

    The basics are as follows.

    1. Use CrmSvcUtil.exe (comes with the SDK) to get a context that you can use with the CRM LINQ provider.

    2. Use LINQ to pull the entity attribute FormattedValues for a specific attribute of type OptionSetValue.  The example below is pulling based on a specific entity ID so it pulls the specific text value of the optionset in this instance.


    var strstringvalue = (from ca in context.CreateQuery<CampaignActivity>()
            where ca.ActivityId == campaignResponse.new_CampaignActivityId.Id
            select ca.FormattedValues["new_campaignactivitytype"]);
    
    


    This should help somebody out. :) - Happy Friday!

    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!
        -

        Tuesday, March 13, 2012

        Disassociate an Entity Record From Another Entity Record in Microsoft Dynamics CRM 2011 Using C# in Silverlight

        This tutorial will show you how to disassociate an entity record from another entity record in Microsoft Dynamics CRM 2011 using C# in Silverlight.

        First things first.  You have to set up your Silverlight app to make a web services connection to CRM.   The best tutorial I have found for this is located here in the MSDN:
        http://msdn.microsoft.com/en-us/library/gg594452.aspx

        Here is the call in C#:

        OrganizationRequest request = new OrganizationRequest() { RequestName = "Disassociate" };
        
        //Target is the entity that you are associating your entities to.
        EntityReference entrefTarget = new EntityReference();
        entrefTarget.Id = new Guid("06AA44B1-336B-E111-B3CA-1CC1DEF1B5FF");
        entrefTarget.LogicalName = "account";
        request["Target"] = entrefTarget;
        
        //RelatedEntities are the entities you are associating to your target (can be more than 1)
        EntityReferenceCollection entrefcolCollection = new EntityReferenceCollection();
        EntityReference entrefRelatedEntity1 = new EntityReference();
        entrefRelatedEntity1.Id = new Guid("32B365C9-5F0C-E111-BF0B-1CC1DEE89AA8");
        entrefRelatedEntity1.LogicalName = "contact";
        entrefcolCollection.Add(entrefRelatedEntity1);
        request["RelatedEntities"] = entrefcolCollection;
        
        
        //The relationship schema name in CRM you are using to associate the entities. 
        //found in settings - customization - entity - relationships
        Relationship relRelationship = new Relationship();
        relRelationship.SchemaName = "contact_customer_accounts";
        request["Relationship"] = relRelationship;
        
        //execute the request
        IOrganizationService service = SilverlightUtility.GetSoapService();
        
        //depending on how you do things your calls will most likely be asynchronous
        service.BeginExecute(request, new AsyncCallback(Associate_Callback), service);
        
        

        You will notice that the biggest change in thinking and syntax will be that you have to specify your request and response properties as strings explicitly in code.

        Really though once you understand the differences in working with the two concepts it really isn't a tough nut to crack.

        -

        Monday, March 12, 2012

        Associate an Entity Record with Another in Microsoft Dynamics CRM 2011 Using C# in Silverlight

        This tutorial will show you how to associate an entity record to another entity record in Microsoft Dynamics CRM 2011 using C# in Silverlight.

        First things first.  You have to set up your Silverlight app to make a web services connection to CRM.   The best tutorial I have found for this is located here in the MSDN:
        http://msdn.microsoft.com/en-us/library/gg594452.aspx

        Here is the call in C#:

        private void AssociateAccount(Guid guidResult)
        {
            OrganizationRequest request = new OrganizationRequest() { RequestName = "Associate" };
        
            //Target is the entity that you are associating your entities to.
            EntityReference entrefTarget = new EntityReference();
            entrefTarget.Id = guidResult;
            entrefTarget.LogicalName = "account";
            request["Target"] = entrefTarget;
             
            //RelatedEntities are the entities you are associating to your target (can be more than 1)
            EntityReferenceCollection entrefcolCollection = new EntityReferenceCollection();
            EntityReference entrefRelatedEntity1 = new EntityReference();
            entrefRelatedEntity1.Id = new Guid("32B365C9-5F0C-E111-BF0B-1CC1DEE89AA8");
            entrefRelatedEntity1.LogicalName = "contact";
            entrefcolCollection.Add(entrefRelatedEntity1);
            request["RelatedEntities"] = entrefcolCollection;
            
        
            //The relationship schema name in CRM you are using to associate the entities. 
            //found in settings - customization - entity - relationships
            Relationship relRelationship = new Relationship();
            relRelationship.SchemaName = "contact_customer_accounts";
            request["Relationship"] = relRelationship;
        
            //execute the request
            IOrganizationService service = SilverlightUtility.GetSoapService();
        
            //depending on how you do things your calls will most likely be asynchronous
            service.BeginExecute(request, new AsyncCallback(Associate_Callback), service);
        }
        
         private void Associate_Callback(IAsyncResult result)
        {
            try
            {
                OrganizationResponse response = ((IOrganizationService)result.AsyncState).EndExecute(result);
                
        
                
        
            }
            catch (Exception ex)
            {
                ReportError(ex);
            }
        }
        

        You will notice that the biggest change in thinking and syntax will be that you have to specify your request and response properties as strings explicitly in code.

        Really though once you understand the differences in working with the two concepts it really isn't a tough nut to crack.

        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!
        -