Microsoft Dynamics CRM 2011

Microsoft Dynamics CRM 2011

Tuesday, April 16, 2019

Dynamics 365 - How to Update Entity attributes using Web API and Javascript in 5 minutes

In this article we describe Step by step How to Update Entity attributes using Web API and Javascript in 5 minutes.
In this example, we send an HTTP PATCH request to the Dynamics 365 Web Api, in order to update several attributes, and also a MANY-TO-ONE relationship reference between Phonecall and Contact.
We use the HTTP PATCH verb since we are updating more than ONE attribute. Elsewhere, we should use the HTTP PUT OData REST method.


How to Update Entity attributes using Web API and Javascript in 5 minutes  



The following code sends an HTTP PATCH request to the Dynamics 365 Web Api, in order to update several attributes, and also a MANY-TO-ONE relationship reference between Phonecall and Contact:



 var fnPATCHEntity = (newEntityId) => {
            //debugger;
            var entity = {};
            entity.phonenumber = document.getElementById("Phone").value;            
            entity.description = document.getElementById("Description").value;
            entity["regardingobjectid_contact@odata.bind"] = "/contacts(" + newEntityId + ")";
            let id = parent.Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');


            $.ajax({
                type: "PATCH",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: Xrm.Page.context.getClientUrl() + "/api/data/v8.2/phonecalls(" + id + ")",
                data: JSON.stringify(entity),
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
                    XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
                    XMLHttpRequest.setRequestHeader("Accept", "application/json");
                },
                async: true,
                success: function (data, textStatus, xhr) {
                    Xrm.Utility.alertDialog('Phonecall Updated with MANY-TO-ONE relationship!!');
                },
                error: function (xhr, textStatus, errorThrown) {
                    Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
                }
            });

        }




That's all...
In this article we've seen Step by step How to Update Entity attributes using Web API and Javascript in 5 minutes.
Enjoy Microsoft Dynamics 365 CRM!

by Carmel Schvartzman

כתב: כרמל שוורצמן

Dynamics 365 - How to Create a MANY-TO-ONE related Entity record using Web API and Javascript in 5 minutes

In this article we describe Step by step How to Create a MANY-TO-ONE related Entity record using Web API and Javascript in 5 minutes.
This Web Resource uses Bootstrap and JQuery , to issue HTTP POST and HTTP PATCH requests to a Dynamics 365 Organization, using the Web Api, in order to Create a new Contact record, related to a current Phonecall. 

The UI looks like this :










How to Create a MANY-TO-ONE related Entity record using Web API and Javascript in 5 minutes  



There will be 2 functions, one for creating a new Contact record with HTTP POST , like this :





And the second function, in order to UPDATE the current Phonecall record, setting its Contact reference regardingobjectid_contact to the guid of the newly created Contact :






The following is the whole Web Resource, to be copied as a building block to your Dynamics Organization :


<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script>

        // Create a MANY-TO-ONE relationship :  Créer une relation plusieurs-à-un phonecalls-contact :
        var fnPATCHRelatedEntity = (newEntityId) => {
            //debugger;
            var entity = {};
            entity["regardingobjectid_contact@odata.bind"] = "/contacts(" + newEntityId + ")";
            let id = parent.Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');
            // In case you want to modify another attribute :  Au cas ou tu veux modifier un autre attribut :
            // entity.phonenumber = "0546589251";

            parent.$.ajax({     //  We can use HTTP PUT whenever we need to modify only ONE attribute
                type: "PATCH",  //  on peut utiliser le verbe HTTP PUT , dans le cas de modification de 1 seul attribut
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: parent.Xrm.Page.context.getClientUrl() + "/api/data/v8.2/phonecalls(" + id + ")",
                data: JSON.stringify(entity),
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
                    XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
                    XMLHttpRequest.setRequestHeader("Accept", "application/json");
                },
                async: true,
                success: function (data, textStatus, xhr) {
                    parent.Xrm.Utility.alertDialog('Phonecall Updated with MANY-TO-ONE relationship!!');
                },
                error: function (xhr, textStatus, errorThrown) {
                    parent.Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
                }
            });

        }

        var fnCreateContact = () => {
            //debugger;
            var entity = {};
            entity.address1_telephone1 = document.getElementById("Phone").value;
            entity.emailaddress1 = document.getElementById("Email").value;
            entity.firstname = document.getElementById("FirstName").value;
            entity.lastname = document.getElementById("LastName").value;

            parent.$.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: parent.Xrm.Page.context.getClientUrl() + "/api/data/v8.2/contacts",
                data: JSON.stringify(entity),
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
                    XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
                    XMLHttpRequest.setRequestHeader("Accept", "application/json");
                },
                async: true,
                success: function (data, textStatus, xhr) {
                    let uri = xhr.getResponseHeader("OData-EntityId");
                    let regExp = /\(([^)]+)\)/;
                    let matches = regExp.exec(uri);
                    let newEntityId = matches[1];
                    if (newEntityId != null) {
                        // Créer une relation plusieurs-à-un phonecalls-contact :
                        fnPATCHRelatedEntity(newEntityId);
                    }


                    document.getElementById('btnCreateContact').classList.add('disabled');
                },
                error: function (xhr, textStatus, errorThrown) {
                    parent.Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
                }
            });
        }


    </script>

</head>
<body style="direction: rtl; overflow-wrap: break-word;">

    <div class="container">
        <div class="jumbotron">
            <h3>Create Contact</h3>
            <p></p><h5>This function creates a new Contact related to the current Phonecall through a One-To-Many relationship</h5><p></p>
            <table style="font:12px;border-spacing:3px;margin:5px;">
                <tbody>
                    <tr>
                        <td>First Name: </td>
                        <td><input type="text" id="FirstName" value="Bender"></td>
                    </tr>
                    <tr>
                        <td>Last Name: </td>
                        <td><input type="text" id="LastName" name="LastName" value="Rodriguez"></td>
                    </tr>
                    <tr><td>Email: </td><td><input type="text" id="Email" value="www.bender.com"></td></tr>
                    <tr>
                        <td>Phone: </td>
                        <td><input type="text" id="Phone" name="Phone" value="123456789"></td>
                    </tr>
                </tbody>
            </table>

            <button id="btnCreateContact" onclick="fnCreateContact()" type="button" class="btn btn-primary">Create Contact</button>

        </div>
    </div>
</body>
</html>










That's all...
In this article we've seen Step by step How to Create a MANY-TO-ONE related Entity record using Web API and Javascript in 5 minutes.
Enjoy Microsoft Dynamics 365 CRM!

by Carmel Schvartzman

כתב: כרמל שוורצמן

SOLVED ERROR - Cannot find assembly "Microsoft.SqlServer.ManagedDTS" when calling an SSIS agent job from C# code


In this article we describe how to find the assembly "Microsoft.SqlServer.ManagedDTS"  when calling an SSIS agent job from C# code.

When calling an Sql Server Integration Services agent job SSIS programmatically from C# .Net code, in order to use the method  Execute , there is a need for using in the application the reference to the assembly  Microsoft.SqlServer.ManagedDTS .

The problem resides in finding that DLL . It should be installed in the pc, together with the rest of SQL SERVER DLLs.



How to find the assembly "Microsoft.SqlServer.ManagedDTS"  when calling an SSIS agent job from C# code



The first try will be to add the assembly via the assemblies list box in visual studio , only to find that it was not available there:




Then, we could go to the  SQL SERVER assemblies  folder : C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies
Again, it will not be possible to get the assembly that way:





SOLUTION: 
Press WIN KEY + R to open the Run window , and run the GAC command : 


    C:\Windows\assembly\gac_msil


The GAC will open, and then make a search for the ManagedDTS assembly :

Copy it to the BIN folder of your VISUAL STUDIO project, then open the reference manager and BROWSE for it in the BIN folder :






Add the "Using" reference to your Project .
That's all...
In this article we've seen Step by step how to find the assembly "Microsoft.SqlServer.ManagedDTS" when calling an SSIS agent job from C# code.
Enjoy Microsoft Dynamics 365 CRM!

by Carmel Schvartzman

כתב: כרמל שוורצמן










    Dynamics 365 - How to Create a new Entity record using Web API and Javascript in 5 minutes

    In this article we describe Step by step  How to Create a new Entity record  using Web API and Javascript in 5 minutes. We'll use the JQuery already loaded by Dynamics 365 on the form.

    For this example, we'll create a Contact record, when clicking a button, using a Web Resource locally inside the Form.


    How to Create a new Entity record  using Web API and Javascript in 5 minutes



    This is the function to Create a Record , using an HTTP POST request: 


    var entity = {};
    entity.address1_telephone1 = "";
    entity.emailaddress1 = "";
    entity.lastname = "";

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: Xrm.Page.context.getClientUrl() + "/api/data/v8.2/contacts",
        data: JSON.stringify(entity),
        beforeSend: function(XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
            XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        async: true,
        success: function(data, textStatus, xhr) {
            var uri = xhr.getResponseHeader("OData-EntityId");
            var regExp = /\(([^)]+)\)/;
            var matches = regExp.exec(uri);
            var newEntityId = matches[1];
        },
        error: function(xhr, textStatus, errorThrown) {
            Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
        }
    });



    And this is the Web Resource EMBEDDED in the Form (that's why we wrote "parent" before calls to JQuery ) :
    1) Open the Form
    2) Add > Section > Web Resource
    3) Paste inside it the following HTML - JS code:



    <html><head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script>

    var fnCreateContact = () => {
    var entity = {};
    entity.address1_telephone1 = "123123123";
    entity.emailaddress1 = "www.bender.com";
    entity.lastname = "Contact Name";

    parent.$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: parent.Xrm.Page.context.getClientUrl() + "/api/data/v8.2/contacts",
        data: JSON.stringify(entity),
        beforeSend: function(XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
            XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        async: true,
        success: function(data, textStatus, xhr) {
            var uri = xhr.getResponseHeader("OData-EntityId");
            var regExp = /\(([^)]+)\)/;
            var matches = regExp.exec(uri);
            var newEntityId = matches[1];

    document.getElementById('btnCreateContact').classList.add('disabled');
        },
        error: function(xhr, textStatus, errorThrown) {
            parent.Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
        }
    });
    }
    </script>
    <meta></head><body style="direction: rtl; overflow-wrap: break-word;">

    <div class="container">
      <div class="jumbotron">
        <h3>Create Contact</h3>   
        <p>This function creates a new Contact</p>
         <button id="btnCreateContact" onclick="fnCreateContact()" type="button" class="btn btn-primary">Create Contact</button>
      </div>
    </div>

    </body></html>






    That's all...
    In this article we've seen Step by step  How to Create a new Entity record  using Web API and Javascript in 5 minutes.
    Enjoy Microsoft Dynamics 365 CRM!

    by Carmel Schvartzman

    כתב: כרמל שוורצמן

    Step by step How to Install the CRM REST Builder in your Dynamics CRM 365 in 5 minutes

    In this article we describe Step by step How to Install the CRM REST Builder in your Dynamics CRM 365 in 5 minutes.
    The CRM REST Builder is an open source creation by  Jason Lattimer. It will give you the chance of getting the REST OData code that you need, both using JQuery or XMLHttpRequest, automatically and avoiding to fall on errors. The Builder enables you to perform WEB API OData REST request to create One to Many , Many to One and Many to Many relationships, asynchronously:



    How to Install the CRM REST Builder in your Dynamics CRM 365 in 5 minutes

    1) Download the REST BUILDER:
    Browse to the Jason Lattimer's Github , and download the Builder , according to your Dynamics CRM version: https://github.com/jlattimer/CRMRESTBuilder/releases



    2) Import the Managed Solution to your Dynamics 365:
    Open your solutions screen, and import the REST Builder solution:



    3) Open the REST BUILDER:
    After refreshing the Solutions form, you will see a button on the top of the form. Open it to see the Builder:





    4) Create your REST request:

    Create your request, and copy it to the web resource that will be called from your entity form:








    That's all...
    In this article we've seen Step by step How to Install the CRM REST Builder in your Dynamics CRM 365 in 5 minutes.
    Enjoy Microsoft Dynamics 365 CRM!

    by Carmel Schvartzman

    כתב: כרמל שוורצמן










      Wednesday, April 10, 2019

      Dynamics 365 - How to Retrieve Many-To-One related Entity attributes using Web API and Javascript

      In this article we describe Step by step  How to Retrieve Many-To-One related Entity attributes using Web API and Javascript in 5 minutes. We use the JQuery included in the Dynamics form.
      This is our example :  we want to get attributes from a Contact related to a Phonecall :
      This is a MANY-TO-ONE relationship, therefore :
      Primary Entity = Contact
      Related Entity = Phonecall
      Link Entity = regardingobjectid_phonecall_contact 
       (this logical name can be inferred from the N:1 link as seen in the Customizations : see this snapshot : )





      How to Retrieve Many-To-One related Entity attributes using Web API and Javascript 



      This approach works by creating only one web resource embedded into the Form HTML page of the entity :
      1) Open the Form - Add a new Region
      2) Add a Web Resource to the Region
      3) Click on Create New Web Resource 
      4) Add the following Building Block code to the Web Resource :

      This code:
      - loads Bootstrap
      - uses JQuery form the Parent Form
      - Gets Attributes from both the current Entity (Phonecall) + the related MANY-TO-ONE Entity (Contact) :


      <html><head>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
      <script> 
         
          function fnGetContactDetails() {

            debugger;
            let gPrimaryEntityId = parent.Xrm.Page.data.entity.getId();

            if (gPrimaryEntityId) {

              gPrimaryEntityId = gPrimaryEntityId.replace("{", "").replace("}", "");

              parent.$.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: encodeURI(parent.Xrm.Page.context.getClientUrl() + "/api/data/v8.2/phonecalls(" + gPrimaryEntityId + ")?$select=activityid,phonenumber&$expand=regardingobjectid_contact_phonecall($select=contactid,fullname,accountrolecode,emailaddress1,telephone1,mobilephone,company)"),
                beforeSend: function (XMLHttpRequest) {
                  XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
                  XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
                  XMLHttpRequest.setRequestHeader("Accept", "application/json");
                  XMLHttpRequest.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
                },
                async: true,
                success: function (data, textStatus, xhr) {
                  var result = data;
                  var activityid = result["activityid"];
                  var phonenumber = result["phonenumber"];
                  if (result.hasOwnProperty("regardingobjectid_contact_phonecall")) {
                    var contactid = result["regardingobjectid_contact_phonecall"]["contactid"];
                    var fullname = result["regardingobjectid_contact_phonecall"]["fullname"];
                    let accountrolecode = result["regardingobjectid_contact_phonecall"]["accountrolecode"];
                    let emailaddress1 = result["regardingobjectid_contact_phonecall"]["emailaddress1"];
                    let telephone1 = result["regardingobjectid_contact_phonecall"]["telephone1"];
                    let company = result["regardingobjectid_contact_phonecall"]["company"];
                    let mobilephone = result["regardingobjectid_contact_phonecall"]["mobilephone"];


                    document.getElementById("msg").innerHTML = fullname + "<br>" + // accountrolecode + "<br>" + 
                               emailaddress1 + "<br>" + telephone1 + "<br>" + company + "<br>" + mobilephone;

                  document.getElementById("btnGetContact").style.display = "none";
                    // parent.Xrm.Utility.alertDialog(fullname);
                  }
                },
                error: function (xhr, textStatus, errorThrown) {
                  parent.Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
                }
              });
            }
            else {
              parent.Xrm.Page.ui.alert("No ID for Primary Entity");
            }
          }

      </script>
      <meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta></head><body style="direction: rtl; overflow-wrap: break-word;">


      <div class="container">
        <div class="jumbotron">
          <h3>Contact Details</h3> 
          <button id="btnGetContact" class="btn btn-secondary" onclick="fnGetContactDetails()">Get Contact Details </button> 
          <b><div id="msg"></div></b> 
      </div>

      </div></body></html> 
          
      }







      That's all...
      In this article we've seen Step by step  How to Retrieve Many-To-One related Entity attributes using Web API and Javascript in 5 minutes.
      Enjoy Microsoft Dynamics 365 CRM!

      by Carmel Schvartzman

      כתב: כרמל שוורצמן