Friday, December 30, 2011

Using CreateRequest to Create an Entity in Microsoft Dynamics CRM 2011 Using VB .NET

This illustration shows how to use CreateRequest to create an entity in Microsoft Dynamics CRM 2011 with VB.NET

Ok, here is what the code looks like!

In VB.NET

Dim create As New CreateRequest()
Dim tstAccount As New Account()

'set attributes here
tstAccount.Name = "test account in code"
tstAccount.Address1_City = "Richfield"

create.Target = tstAccount
service.Execute(create)


Thats all there is to it!
-

Thursday, December 29, 2011

Using RetrieveMultipleRequest in Microsoft Dynamics CRM 2011 in VB .NET

RetrieveMultiple is probably the most common request I use so I figured I better add a decent VB.NET example to my example index. This illustration shows how to use the RetrieveMultipleRequest in Microsoft Dynamics CRM 2011 with VB.NET

Ok, here is what the code looks like!

In VB.NET

 Dim rmr As New RetrieveMultipleRequest()
 Dim resp As New RetrieveMultipleResponse()

 Dim qry As New QueryExpression()
 qry.EntityName = "systemuser"
 qry.ColumnSet = New ColumnSet(True)
 qry.Criteria = New FilterExpression()
 qry.Criteria.FilterOperator = LogicalOperator.And

 Dim cnd As New ConditionExpression()
 cnd.AttributeName = "organizationid"
 cnd.Operator = ConditionOperator.Equal
 cnd.Values.Add("f5d3e6d4-61b5-4739-af1b-a8ca3232a4e3")
 qry.Criteria.Conditions.Add(cnd)

 rmr.Query = qry
 resp = DirectCast(slos.Execute(rmr), RetrieveMultipleResponse)


Thats all there is to it!
-

Wednesday, December 28, 2011

Determine the User, Business Unit, and Organization Id's of a Calling User in Microsoft Dynamics CRM 2011 in VB .NET With WhoAmIRequest

Since it's the holidays we won't cover anything too difficult today. :)  BUT... this is leading up to something much greater in the near future so stay tuned.

This illustration shows how to determine the user, business unit, and organization id's of a calling user in Microsoft Dynamics CRM 2011 with WhoAmIRequest.  This example will be given in VB.NET

Ok, here is what the code looks like!

In VB.NET

Dim req As New WhoAmIRequest()
Dim resp As WhoAmIResponse = DirectCast(slos.Execute(req), WhoAmIResponse)


Thats all there is to it!
-

Monday, December 26, 2011

Add an Activity to a Queue in Microsoft Dynamics CRM 2011 Using .NET or Jscript

This illustration shows how to add an activity to a queue in Microsoft Dynamics CRM 2011 with AddToQueueRequest.  This example will be given in Jscript (SOAP) and in C# (.NET).


Ok, here is what the code looks like!

First in C#:
AddToQueueRequest req = new AddToQueueRequest();
req.Target = new EntityReference(Fax.EntityLogicalName, new Guid("52DCF6FA-1B20-E111-8E08-1CC1DEF1353B"));
//source queue is optional
 //req.SourceQueueId = new Guid();
req.DestinationQueueId = new Guid("9F361689-2730-E111-8E0C-1CC1DEF1353B");
 
AddToQueueResponse resp = (AddToQueueResponse)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;
               }, 
           AddToQueueRequest: 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:AddToQueueRequest\" 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:EntityReference\">";
               requestMain += "              <a:Id>52dcf6fa-1b20-e111-8e08-1cc1def1353b</a:Id>";
               requestMain += "              <a:LogicalName>fax</a:LogicalName>";
               requestMain += "              <a:Name i:nil=\"true\" />";
               requestMain += "            </c:value>";
               requestMain += "          </a:KeyValuePairOfstringanyType>";
               requestMain += "          <a:KeyValuePairOfstringanyType>";
               requestMain += "            <c:key>DestinationQueueId</c:key>";
               requestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">9f361689-2730-e111-8e0c-1cc1def1353b</c:value>";
               requestMain += "          </a:KeyValuePairOfstringanyType>";
               requestMain += "        </a:Parameters>";
               requestMain += "        <a:RequestId i:nil=\"true\" />";
               requestMain += "        <a:RequestName>AddToQueue</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.AddToQueueResponse(req, successCallback, errorCallback); };
               req.send(requestMain);
           },
       AddToQueueResponse: 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.AddToQueueRequest function from your form jscript handler.

Thats all there is to it!
-

Friday, December 23, 2011

Merry Christmas Everyone!!

Merry Christmas!!  I hope God blesses you this coming new year and that you are spending the holidays with family!!

Thursday, December 22, 2011

Retrieve the Dependencies to Delete a Solution Component in Microsoft Dynamics CRM 2011 Using .NET or Jscript

This illustration shows how to retrieve the dependencies to delete a solution component in Microsoft Dynamics CRM 2011 with RetrieveDependenciesForDeleteRequest.  This example will be given in Jscript (SOAP) and in C# (.NET).

Important Note: The metadata browser can be very useful in finding the MetadataId of a component to be used in this call
      Ok, here is what the code looks like!
      First in C#:

      RetrieveDependenciesForDeleteRequest req = new RetrieveDependenciesForDeleteRequest();
      req.ComponentType = (int)SolutionComponentType.Entity;
      //use the metadata browser or a retrieveentity request to get the MetadataId for the entity
      req.ObjectId = new Guid("70816501-edb9-4740-a16c-6a5efbc05d84");
      RetrieveDependenciesForDeleteResponse resp = (RetrieveDependenciesForDeleteResponse)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;
                     }, 
                 RetrieveDependenciesForDeleteRequest: 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:RetrieveDependenciesForDeleteRequest\" 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>ObjectId</c:key>";
                     requestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">70816501-edb9-4740-a16c-6a5efbc05d84</c:value>";
                     requestMain += "          </a:KeyValuePairOfstringanyType>";
                     requestMain += "          <a:KeyValuePairOfstringanyType>";
                     requestMain += "            <c:key>ComponentType</c:key>";
                     requestMain += "            <c:value i:type=\"d:int\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">1</c:value>";
                     requestMain += "          </a:KeyValuePairOfstringanyType>";
                     requestMain += "        </a:Parameters>";
                     requestMain += "        <a:RequestId i:nil=\"true\" />";
                     requestMain += "        <a:RequestName>RetrieveDependenciesForDelete</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.RetrieveDependenciesForDeleteResponse(req, successCallback, errorCallback); };
                     req.send(requestMain);
                 },
             RetrieveDependenciesForDeleteResponse: 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.RetrieveDependenciesForDeleteRequest function from your form jscript handler.


      Thats all there is to it!
      -

      Wednesday, December 21, 2011

      Lock Sales Order Product Pricing in Microsoft Dynamics CRM 2011 Using .NET or Jscript

      This illustration shows how to lock sales order product pricing in Microsoft Dynamics CRM 2011 with LockSalesOrderRequest.  This example will be given in Jscript (SOAP) and in C# (.NET).

      Important Note: This is a nifty call that allows you to lock your sales order pricing so that changes in price to the underlying products in the product catalog do not effect the  price of the items on an existing sales order.
          Ok, here is what the code looks like!
          First in C#:

          LockSalesOrderPricingRequest req = new LockSalesOrderPricingRequest();
          req.SalesOrderId = new Guid("F531AF36-E12B-E111-87E0-1CC1DEF1B5FF");
          LockSalesOrderPricingResponse resp = (LockSalesOrderPricingResponse)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;
                         }, 
                     LockSalesOrderPricingRequest: 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:LockSalesOrderPricingRequest\" 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>SalesOrderId</c:key>";
                         requestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">f531af36-e12b-e111-87e0-1cc1def1b5ff</c:value>";
                         requestMain += "          </a:KeyValuePairOfstringanyType>";
                         requestMain += "        </a:Parameters>";
                         requestMain += "        <a:RequestId i:nil=\"true\" />";
                         requestMain += "        <a:RequestName>LockSalesOrderPricing</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.LockSalesOrderPricingResponse(req, successCallback, errorCallback); };
                         req.send(requestMain);
                     },
                 LockSalesOrderPricingResponse: 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.LockSalesOrderPricingRequest function from your form jscript handler.


          Thats all there is to it!
          -

          Tuesday, December 20, 2011

          Lock Invoice Product Pricing in Microsoft Dynamics CRM 2011 Using .NET or Jscript

          This illustration shows how to lock invoice product pricing in Microsoft Dynamics CRM 2011 with LockInvoicePricingRequest.  This example will be given in Jscript (SOAP) and in C# (.NET).

          Important Note: This is a nifty call that allows you to lock your invoice pricing so that changes in price to the underlying products in the product catalog do not effect the invoice amounts for the products
              Ok, here is what the code looks like!
              First in C#:

              LockInvoicePricingRequest req = new LockInvoicePricingRequest();
              req.InvoiceId = new Guid("6EB72198-192B-E111-8E0C-1CC1DEF1353B");
              LockInvoicePricingResponse resp = (LockInvoicePricingResponse)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;
                             }, 
                         LockInvoicePricingRequest: 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:LockInvoicePricingRequest\" 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>InvoiceId</c:key>";
                             requestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">6eb72198-192b-e111-8e0c-1cc1def1353b</c:value>";
                             requestMain += "          </a:KeyValuePairOfstringanyType>";
                             requestMain += "        </a:Parameters>";
                             requestMain += "        <a:RequestId i:nil=\"true\" />";
                             requestMain += "        <a:RequestName>LockInvoicePricing</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.LockInvoicePricingResponse(req, successCallback, errorCallback); };
                             req.send(requestMain);
                         },
                     LockInvoicePricingResponse: 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.LockInvoicePricingRequest function from your form jscript handler.


              Thats all there is to it!
              -

              Monday, December 19, 2011

              Import a Translation File into Microsoft Dynamics CRM 2011 Using .NET

              This illustration shows how to import a translation file into Microsoft Dynamics CRM 2011 in code using C#  with ImportTranslationRequest.   This example will be given in C# (.NET).

              JSCRIPT NOTE: At this time I am NOT providing a Jscript example on this call because of a limit in the SOAP formatter that only allows approximately 32,000 characters to a message.  Do to encoding the file in the request, the request SOAP message was hundreds of thousands of characters. It would also be difficult to reach into a user's system to get the bytes needed anyways in a practical manner from jscript.  I am not sure there is much need to do this operation in JScript they need they can comment below and I will look into it further for them.

              Ok, here is what the code look like!
              First in C#:

              byte[] fileBytes = File.ReadAllBytes(@"C:\code\TestTranslations.zip");
              ImportTranslationRequest req = new ImportTranslationRequest();
              req.TranslationFile = fileBytes;
              ImportTranslationResponse resp = (ImportTranslationResponse)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

              I hope this helps!

              Friday, December 16, 2011

              Check the License Type for a Deployment of Microsoft Dynamics CRM 2011 Using .NET or Jscript

              This illustration shows how to check the license type for a deployment of Microsoft Dynamics CRM 2011 with RetrieveDeploymentLicenseTypeRequest.  This example will be given in Jscript (SOAP) and in C# (.NET).

              Important Note: The LicenseType property included in the response returns a guid.  After not having a lot of luck searching for how to figure out what that meant I searched for the guid itself and got one hit and found that the same guids were used for 4.0 versions also. Here are the guids I know about.  I personally checked my enterprise server and online environments and verified that they did indeed return these exact guids.

              THESE ARE NOT PRODUCT ACTIVATION KEYS, SO DON'T EVEN BOTHER TRYING :)
              • SmallBusiness 9436EA66-8262-4168-9B6C-21DF47D1D121
              • Professional 5BEEA2E8-8F82-40e8-AE0F-6D8C135E1397
              • Enterprise CB96BDD5-5F74-4ea5-8323-9D7E20079002
              • Live 66AE2919-DD58-40ca-A980-AEF7330B2745
              • SPLA (Service Provider) 722E9E15-62DC-48a7-95CF-93131BE27273
                Ok, here is what the code looks like!
                First in C#:

                RetrieveDeploymentLicenseTypeRequest req = new RetrieveDeploymentLicenseTypeRequest();
                RetrieveDeploymentLicenseTypeResponse resp = (RetrieveDeploymentLicenseTypeResponse)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;
                               }, 
                           RetrieveDeploymentLicenseTypeRequest: 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:RetrieveDeploymentLicenseTypeRequest\" 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:RequestId i:nil=\"true\" />";
                               requestMain += "        <a:RequestName>RetrieveDeploymentLicenseType</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.RetrieveDeploymentLicenseTypeResponse(req, successCallback, errorCallback); };
                               req.send(requestMain);
                           },
                       RetrieveDeploymentLicenseTypeResponse: 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.RetrieveDeploymentLicenseTypeRequest function from your form jscript handler.


                Thats all there is to it!
                -

                Thursday, December 15, 2011

                Export All Translations for a Solution in Microsoft Dynamics CRM 2011 Using .NET or Jscript

                This illustration shows how to export all translations for a solution in Microsoft Dynamics CRM 2011 with ExportTranslationRequest.  This example will be given in Jscript (SOAP) and in C# (.NET).

                Important Note:  In Jscript you can get the file but it is trickier to write it out as it is returned to the response as a base 64 encoded binary file.  Security restrictions on web applications may disallow directly saving the file to the client hard disk when performing this operation in Jscript.  So I do question how practical this particular call will be in most instances from Jscript.
                  Ok, here is what the code looks like!
                  First in C#:

                  ExportTranslationRequest req = new ExportTranslationRequest();
                  req.SolutionName = "test1";
                  ExportTranslationResponse resp = (ExportTranslationResponse)service.Execute(req);
                  
                  String outputDir = @"C:\code\";
                  byte[] exportXml = resp.ExportTranslationFile;
                  string filename = "TestTranslations" + ".zip";
                  File.WriteAllBytes(outputDir + filename, exportXml);
                  Console.WriteLine("Translations exported to {0}.", outputDir + filename);
                  
                  

                  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;
                                 }, 
                             ExportTranslationRequest: 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:ExportTranslationRequest\" 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>SolutionName</c:key>";
                                 requestMain += "            <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">test1</c:value>";
                                 requestMain += "          </a:KeyValuePairOfstringanyType>";
                                 requestMain += "        </a:Parameters>";
                                 requestMain += "        <a:RequestId i:nil=\"true\" />";
                                 requestMain += "        <a:RequestName>ExportTranslation</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.ExportTranslationResponse(req, successCallback, errorCallback); };
                                 req.send(requestMain);
                             },
                         ExportTranslationResponse: 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.ExportTranslationRequest function from your form jscript handler.


                  Thats all there is to it!
                  -

                  Wednesday, December 14, 2011

                  Chinmay Patel's Smart Soap Formatter Solution Works for CRM Online Also!

                  I covered this tool earlier here: http://mileyja.blogspot.com/2011/11/chinmay-patel-releases-crmxpress-soap.html

                  But I thought I would let everyone know that Chinmay Patel's Smart SOAP Formatter solution does work for CRM Online.  Check out the video here: http://www.crmxpress.net/blog/Blog/post/2011/12/08/Releasing-CrmXpress-SmartSoapLogger-v10.aspx

                  If you don't remember what it does it is basically what I wanted my SOAP formatter solution to turn into.  You write your web service code in .NET and it connects to your server and just magically converts it to a jscript for you and also shows you the SOAP packets if you like too.

                  Have a great day
                  -

                  Tuesday, December 13, 2011

                  Add a Component to a Solution in Microsoft Dynamics CRM 2011 Using .NET or Jscript

                  This illustration shows how to add a component to a solution in Microsoft Dynamics CRM 2011 with AddSolutionComponentRequest.  This example will be given in Jscript (SOAP) and in C# (.NET).

                  Important Note: An easy way to get the required Metadata ID for your entity or component that you want to add to the solution is to install the Metadata Browser solution that comes with the SDK.  This will allow you to browse all the attributes for the entity, relationship, etc...
                    Ok, here is what the code looks like!
                    First in C#:

                    AddSolutionComponentRequest req = new AddSolutionComponentRequest();
                    req.SolutionUniqueName = "test1";
                    //we will add account entity
                    req.ComponentId = new Guid("70816501-edb9-4740-a16c-6a5efbc05d84");
                    req.ComponentType = (int)SolutionComponentType.Entity;
                    //we will also want to copy all required dependant components
                    req.AddRequiredComponents = true;
                    AddSolutionComponentResponse resp = (AddSolutionComponentResponse)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;
                                   }, 
                               AddSolutionComponentRequest: 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:AddSolutionComponentRequest\" 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>ComponentId</c:key>";
                                   requestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">70816501-edb9-4740-a16c-6a5efbc05d84</c:value>";
                                   requestMain += "          </a:KeyValuePairOfstringanyType>";
                                   requestMain += "          <a:KeyValuePairOfstringanyType>";
                                   requestMain += "            <c:key>ComponentType</c:key>";
                                   requestMain += "            <c:value i:type=\"d:int\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">1</c:value>";
                                   requestMain += "          </a:KeyValuePairOfstringanyType>";
                                   requestMain += "          <a:KeyValuePairOfstringanyType>";
                                   requestMain += "            <c:key>SolutionUniqueName</c:key>";
                                   requestMain += "            <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">test1</c:value>";
                                   requestMain += "          </a:KeyValuePairOfstringanyType>";
                                   requestMain += "          <a:KeyValuePairOfstringanyType>";
                                   requestMain += "            <c:key>AddRequiredComponents</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:Parameters>";
                                   requestMain += "        <a:RequestId i:nil=\"true\" />";
                                   requestMain += "        <a:RequestName>AddSolutionComponent</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.AddSolutionComponentResponse(req, successCallback, errorCallback); };
                                   req.send(requestMain);
                               },
                           AddSolutionComponentResponse: 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.AddSolutionComponentRequest function from your form jscript handler.


                    Thats all there is to it!
                    -

                    Monday, December 12, 2011

                    Order Items in a Picklist / OptionSet in Microsoft Dynamics CRM 2011 Using .NET or Jscript

                    This illustration shows how to order items in a picklist / optionset in Microsoft Dynamics CRM 2011 with OrderOptionRequest.  This example will be given in Jscript (SOAP) and in C# (.NET).
                      Ok, here is what the code looks like!
                      First in C#:

                          // Use the RetrieveAttributeRequest message to retrieve  
                          // a attribute by it's logical name.
                          RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();
                          retrieveAttributeRequest.EntityLogicalName = Account.EntityLogicalName;
                          retrieveAttributeRequest.RetrieveAsIfPublished = true;
                          retrieveAttributeRequest.LogicalName = "new_picklist2";
                                 
                      
                          // Execute the request.
                          RetrieveAttributeResponse retrieveAttributeResponse =
                              (RetrieveAttributeResponse)service.Execute(
                              retrieveAttributeRequest);
                      
                          // Access the retrieved attribute.
                          PicklistAttributeMetadata retrievedPicklistAttributeMetadata =
                              (PicklistAttributeMetadata)
                              retrieveAttributeResponse.AttributeMetadata;
                      
                          // Get the current options list for the retrieved attribute.
                          OptionMetadata[] optionList =
                              retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                      
                          // Change the order of the original option's list.
                          // Use the OrderBy (OrderByDescending) linq function to sort options in  
                          // ascending (descending) order according to label text.
                          // For ascending order use this:
                          var updateOptionList =
                              optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();
                      
                          // For descending order use this:
                          // var updateOptionList =
                          //      optionList.OrderByDescending(
                          //      x => x.Label.LocalizedLabels[0].Label).ToList();
                      
                          // Create the request.
                          OrderOptionRequest orderOptionRequest = new OrderOptionRequest();
                          orderOptionRequest.AttributeLogicalName = "new_picklist2";
                          orderOptionRequest.EntityLogicalName = Account.EntityLogicalName;
                          // Set the changed order using Select linq function 
                          // to get only values in an array from the changed option list.
                          orderOptionRequest.Values = updateOptionList.Select(x => x.Value.Value).ToArray();
                              
                      
                          // Execute the request
                          service.Execute(orderOptionRequest);
                      
                      Code above adapted in part from: http://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.messages.orderoptionrequest.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 OrgServicePath = "/XRMServices/2011/Organization.svc/web";
                                     var serverUrl = "";
                                     if (typeof GetGlobalContext == "function") {
                                         var context = GetGlobalContext();
                                         serverUrl = context.getServerUrl();
                                     }
                                     else {
                                         if (typeof Xrm.Page.context == "object") {
                                               serverUrl = Xrm.Page.context.getServerUrl();
                                         }
                                         else
                                         { throw new Error("Unable to access the server URL"); }
                                         }
                                        if (serverUrl.match(/\/$/)) {
                                             serverUrl = serverUrl.substring(0, serverUrl.length - 1);
                                         } 
                                         return serverUrl + OrgServicePath;
                                     }, 
                                 OrderOptionRequest: 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:OrderOptionRequest\" 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>Values</b:key>";
                                     requestMain += "            <b:value i:type=\"c:ArrayOfint\" xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">";
                                     requestMain += "              <c:int>100000001</c:int>";
                                     requestMain += "              <c:int>100000000</c:int>";
                                     requestMain += "              <c:int>100000003</c:int>";
                                     requestMain += "              <c:int>100000002</c:int>";
                                     requestMain += "            </b:value>";
                                     requestMain += "          </a:KeyValuePairOfstringanyType>";
                                     requestMain += "          <a:KeyValuePairOfstringanyType>";
                                     requestMain += "            <b:key>AttributeLogicalName</b:key>";
                                     requestMain += "            <b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">new_picklist2</b:value>";
                                     requestMain += "          </a:KeyValuePairOfstringanyType>";
                                     requestMain += "          <a:KeyValuePairOfstringanyType>";
                                     requestMain += "            <b:key>EntityLogicalName</b:key>";
                                     requestMain += "            <b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">account</b:value>";
                                     requestMain += "          </a:KeyValuePairOfstringanyType>";
                                     requestMain += "        </a:Parameters>";
                                     requestMain += "        <a:RequestId i:nil=\"true\" />";
                                     requestMain += "        <a:RequestName>OrderOption</a:RequestName>";
                                     requestMain += "      </request>";
                                     requestMain += "    </Execute>";
                                     requestMain += "  </s:Body>";
                                     requestMain += "</s:Envelope>";
                                     var req = new XMLHttpRequest();
                                     req.open("POST", SDK.SAMPLES._getServerUrl(), true)
                                     // Responses will return XML. It isn't possible to return JSON.
                                     req.setRequestHeader("Accept", "application/xml, text/xml, */*");
                                     req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
                                     req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
                                     var successCallback = null;
                                     var errorCallback = null;
                                     req.onreadystatechange = function () { SDK.SAMPLES.OrderOptionResponse(req, successCallback, errorCallback); };
                                     req.send(requestMain);
                                 },
                             OrderOptionResponse: 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.OrderOptionRequest function from your form jscript handler.


                      Thats all there is to it!
                      -

                      Friday, December 9, 2011

                      Remove a Privilege From a Role in Microsoft Dynamics CRM 2011 Using .NET or Jscript

                      This illustration shows how to remove a privilege from a role in Microsoft Dynamics CRM 2011 with RemovePrivilegeRoleRequest.  This example will be given in Jscript (SOAP) and in C# (.NET).
                        Ok, here is what the code looks like!
                        First in C#:

                        
                        RetrieveRolePrivilegesRoleRequest reqRetrieve = new RetrieveRolePrivilegesRoleRequest();
                        //specify your role id
                        reqRetrieve.RoleId = new Guid("2ACB9A27-D621-E111-8FDE-1CC1DEF1353B");
                        RetrieveRolePrivilegesRoleResponse respRetrieve = (RetrieveRolePrivilegesRoleResponse)service.Execute(reqRetrieve);
                        
                        List<RolePrivilege> lstPrivs = respRetrieve.RolePrivileges.ToList();
                        
                        foreach(RolePrivilege r in lstPrivs)
                        {
                            RemovePrivilegeRoleRequest req = new RemovePrivilegeRoleRequest();
                            req.RoleId = new Guid("2ACB9A27-D621-E111-8FDE-1CC1DEF1353B");
                            req.PrivilegeId = r.PrivilegeId;
                            RemovePrivilegeRoleResponse resp = (RemovePrivilegeRoleResponse)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 OrgServicePath = "/XRMServices/2011/Organization.svc/web";
                                       var serverUrl = "";
                                       if (typeof GetGlobalContext == "function") {
                                           var context = GetGlobalContext();
                                           serverUrl = context.getServerUrl();
                                       }
                                       else {
                                           if (typeof Xrm.Page.context == "object") {
                                                 serverUrl = Xrm.Page.context.getServerUrl();
                                           }
                                           else
                                           { throw new Error("Unable to access the server URL"); }
                                           }
                                          if (serverUrl.match(/\/$/)) {
                                               serverUrl = serverUrl.substring(0, serverUrl.length - 1);
                                           } 
                                           return serverUrl + OrgServicePath;
                                       }, 
                                   RemovePrivilegeRoleRequest: 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:RemovePrivilegeRoleRequest\" 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>RoleId</c:key>";
                                       requestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">2acb9a27-d621-e111-8fde-1cc1def1353b</c:value>";
                                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                                       requestMain += "          <a:KeyValuePairOfstringanyType>";
                                       requestMain += "            <c:key>PrivilegeId</c:key>";
                                       requestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">886b280c-6396-4d56-a0a3-2c1b0a50ceb0</c:value>";
                                       requestMain += "          </a:KeyValuePairOfstringanyType>";
                                       requestMain += "        </a:Parameters>";
                                       requestMain += "        <a:RequestId i:nil=\"true\" />";
                                       requestMain += "        <a:RequestName>RemovePrivilegeRole</a:RequestName>";
                                       requestMain += "      </request>";
                                       requestMain += "    </Execute>";
                                       requestMain += "  </s:Body>";
                                       requestMain += "</s:Envelope>";
                                       var req = new XMLHttpRequest();
                                       req.open("POST", SDK.SAMPLES._getServerUrl(), true)
                                       // Responses will return XML. It isn't possible to return JSON.
                                       req.setRequestHeader("Accept", "application/xml, text/xml, */*");
                                       req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
                                       req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
                                       var successCallback = null;
                                       var errorCallback = null;
                                       req.onreadystatechange = function () { SDK.SAMPLES.RemovePrivilegeRoleResponse(req, successCallback, errorCallback); };
                                       req.send(requestMain);
                                   },
                               RemovePrivilegeRoleResponse: 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.RemovePrivilegeRoleRequest function from your form jscript handler.


                        Thats all there is to it!
                        -