Pages

Sunday, 13 September 2015

Dynamically Generating Ribbon Buttons

Dynamically Generating Ribbon Buttons


Hello Folks,
I had a requirement in which the Buttons in a ribbon to be shown dynamically, so for doing this we require a little bit of scripting and ribbon customization. For doing this I am using Ribbon Workbench tool and creating a Flyout button which I've read from Scott durow blog.
  • Create a solution and add desired entitiy and Jscript file having script shown in last.
  • In my scenario I wanted to have a button on Home Page, so using Ribbon Workbench I dragged a Flyout button on to the home section, once u dragged this button then by default a menu will be added as shown in below screenshot, so u need to remove it

  • Now create two commands, one for dynamically generating Menu and another for calling when any of the menu is clicked.
  • For dynamically generating Menu command,you need to add an action where you need to call a  Jscript function “populateDynamicMenu” and also you need to pass CRM Parameter CommandProperties as shown below and I’ve named this command as ct.contact.PopulateMenu.Command



  •          For another command, you need to add an action where you need to call a Jscript function itemClicked and also you need to pass CRM Parameter CommandProperties as shown above screenshot. I’ve given this command name as ct.contact.ItemClicked.Command


  • ·         Now Both your commands are ready so now you just need to hook those commands, so now open the your button(I’ve named it as FlyOut) properties as shown in screenshot



  • ·         Now hook the commands created as shown in below screenshot

  • ·         That’s it you are done, now publish the changes and got to desired entity and check it

  •  Once you click the button it will call the action hooked to it, in my case I am alerting Button's Id as shown in below screenshot

Jscript
In the populateDynamicMenu function u need to add the button actions in <button> tag by giving the command which you have created for Action to triggered when a button is clicked, in my case it is ct.contact.ItemClicked.Command, so for each button give a unique Id, In my case I’ve given GUID.
And also Change the LabelText to show the label of the button, in my case it is Custom Report and Committee. you can make this a bit more generic by generating the <button> tags dynamically.

function populateDynamicMenu(commandProperties)
{
// Dynamically return the menu to show - this can be built at run time
commandProperties["PopulationXML"]='<Menu Id="demo.CustomReportMenu"><MenuSection Id="demo.CustomReportSection" Sequence="10"><Controls Id="demo.CustomReportControls"><Button Id="C2F4EFC4-3155-E511-80E1-3863BB341AF0" Command="ct.contact.ItemClicked.Command" Sequence="30" LabelText="Custom Report" /><Button Id="4431d3ca-d377-4b7d-b547-4e89806b18d5" Command="ct.contact.ItemClicked.Command" Sequence="30" LabelText="Committee" /></Controls></MenuSection></Menu>';
}

Function itemClicked is called when you click on any of the buttons, here you can get the Id of the button as shown in the below code.


function itemClicked(commandProperties)
{
debugger;
// Determine which button was clicked in the menu
alert(commandProperties.SourceControlId+ ' clicked');
}

Friday, 24 October 2014

Connecting MSD CRM 2013 to Gmail through Email Router

Hello Folks,

In this post I am connecting CRM to Gmail for sending mails and receiving mails.

1) Download the Email Router from Microsoft website and install it.
2) Open the Email Router Configuration Manager,
            a) For Connecting Email Router we need to create Incoming and Outgoing profiles, each of these profiles we need to hook to the CRM Org. Create these profiles in “Configuration Profile” Tab of Email Router,

             b) For Incoming set according to following screen shot, The Username in Incoming Profile will be taken from the User/Queue, no not require to mention here.



            c) Now go to “Advanced” tab set the network port to “995” for Gmail.

              
 Note: For other email Id’s use “110” as port number and Uncheck “use SSL” in General                  Tab.
             Use Port 110 for regular Connection.
 Use Port 995 for SSL Connection.


d)        Now create the Outgoing Profile as per the below screen shot and set the Port no.

    3) Now Add your desired CRM Org connecting using Org Unique name, Once added, this CRM Org shows all the users, Now you need to add these profiles to the corresponding users.



Tuesday, 22 April 2014

Retrieve SubGrid Records MS CRM 2013 using JavaScript

function RetrieveSubGridRecords() {
    if (document.getElementById("Sub Grid Name")) {
        var grid = document.getElementById("Sub Grid Name").control;
        for (var rowNo = 0; rowNo < grid.GetRecordsFromInnerGrid().length; rowNo++)
            for (var cellNo = 0; cellNo < grid.GetRecordsFromInnerGrid()[rowNo][3].cells.length; cellNo++)
                alert(grid.GetRecordsFromInnerGrid()[rowNo][3].cells[cellNo].outerText);    }    else {
        setTimeout("RetrieveSubGridRecords();", 2500);
    }}


Hope it Helps

Wednesday, 2 April 2014

Restrict Partylist Lookup of Phone Entity only to Contacts in CRM 2013

Hi,
In CRM 2013, by default the when we open a form it looks different, so when we hover mouse over the attribute then we can get to know whether it is Lookup or normal field.
Since in the above figure Regarding,Call to are Lookup fields so once we hover the mouse over it then we can understand it.

now in "Regarding" field I have to select "Account" records, once I select Account record in "Regarding" attribute. The "Call to" attribute should be filtered to corresponding Contacts.

So in my code I am Initiating my page, so that i can get the lookup fields,
the Snippet is given below,
------------------------->
function setfilterforlookup(econtext)
{
debugger;
var test=Xrm.Page.getControl("to");  //this line is to initiate my form

test.addPreSearch(addFilter);

document.getElementById("to_i").setAttribute("defaulttype","2");  //to_i is id name of my  lookup in crm 2013 which we can get from debugging page, from HTML format go to the desired lookup
document.getElementById("to_i").setAttribute("lookuptypes","2");
document.getElementById("to_i").setAttribute("lookuptypenames","contact:2:Contact");

}


function addFilter() {
    //check if the city is not empty
    
var lookupObject = Xrm.Page.getAttribute("regardingobjectid").getValue();
var id = lookupObject[0].id;
        //create a filter xml
        var filter ="<filter type='and'>" +
                     "<condition attribute='parentcustomerid' operator='eq' value='" + id + "'/>" +
                     "</filter>";
        //add filter
        Xrm.Page.getControl("to").addCustomFilter(filter,"contact");

    }
-------------------------->

Tuesday, 11 March 2014

Connecting CRM to Dot NET Application

Here I am Creating  a WindowsForm Application which is conneced to CRM.
So I'll Create a new Solution in Visual Studio of Windows Application Type. Now Right click on that solution and Click on the properties. Change the Version of .Net Framework as 4.0

now In my Scenario I am Creating a Record using this Solution. Sor in my form I've added one Text Field and One Button. On clicking of button the record must be created using the textfield value from textbox.

so double click on button in form Design and paste the following code

---------------->
 try
            {
                ClientCredentials cre = new ClientCredentials();
                cre.UserName.UserName = "User Name";
                cre.UserName.Password = "Password";
               var a = "https://<org name>.crm5.dynamics.com";  //for online crm
                Uri serviceUri = new Uri(a+"/xrmservices/2011/Organization.svc");

                OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, cre, null);
                proxy.EnableProxyTypes();
                IOrganizationService service = (IOrganizationService)proxy;

                Entity ent = new Entity("entity name");
                ent.Attributes["Field attribute name"] = textBox1.Text;
                service.Create(ent);
            }
            catch (SoapException ex)
            {

            }
            catch (Exception ex)
            {

            }
---------------->

Monday, 10 March 2014

Delete a Record in CRM using OData Query

Hi Folks,

To Delete a record in CRM, we require JQuery min 1.4 &  JSON2 script file which we can get from SDK from this specific path
SampleCode\JS\RESTEndpoint\JavaScriptRESTDataOperations\JavaScriptRESTDataOperations\Scripts

Now add the following code to your webresource,
Also add JSon.js and Jquery1.4min.js to the Library 
--------------------------->
 function update()
{
    var lookupObject = Xrm.Page.getAttribute("new_lookup").getValue();  //Getting id throug lookup
    var id = lookupObject[0].id;
    var set="new_entity5Set";
    updateRecord(id, set);
}
    function updateRecord(id, odataSetName) {
    var serverUrl = Xrm.Page.context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'"+id+"')",
    beforeSend: function (XMLHttpRequest) {
    XMLHttpRequest.setRequestHeader("Accept", "application/json");
    XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
    },
    success: function (data, textStatus, XmlHttpRequest) {
    alert("Deleted successfully");
    },
    error: function (XmlHttpRequest, textStatus, errorThrown) {
    alert("Error while deletion " + errorThrown);
  
    }
    });
    }

--------------------------->

Update a Record in CRM using OData Query

Hi Folks,

To Update a record in CRM, we require JQuery min 1.4 &  JSON2 script file which we can get from SDK from this specific path
SampleCode\JS\RESTEndpoint\JavaScriptRESTDataOperations\JavaScriptRESTDataOperations\Scripts

Now add the following code to your webresource,
Also add JSon.js and Jquery1.4min.js to the Library
------------------>
function update()
{
    var lookupObject = Xrm.Page.getAttribute("new_lookup").getValue();        //getting the id through lookup
    var id = lookupObject[0].id;
    var entity = new Object();
    entity.new_name="Hello";
    var set="your entity schema nameSet";              //entity name with Set
    updateRecord(id, entity, set);
}
    function updateRecord(id, entityObject, odataSetName) {
    var jsonEntity = window.JSON.stringify(entityObject);
    var serverUrl = Xrm.Page.context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    data: jsonEntity,
    url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'"+id+"')",
    beforeSend: function (XMLHttpRequest) {
    XMLHttpRequest.setRequestHeader("Accept", "application/json");
    XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
    },
    success: function (data, textStatus, XmlHttpRequest) {
    alert("Updated successfully");
    },
    error: function (XmlHttpRequest, textStatus, errorThrown) {
    if (XmlHttpRequest && XmlHttpRequest.responseText) {
    alert("Error while updating " + odataSetName+ " ; Error – " + XmlHttpRequest.responseText);
    }
    }
    });
    }

----------------------->

Wednesday, 5 March 2014

Connecting CRM to Custom Web Page

Here a Custom Web Page is connected to CRM. Now for doing so we require SDK and Visual Studio.

the following Steps can be used to do so

a)  Open Visual Studio create a new Web Site of type ASP.NET Empty Web Site give a desired name and click on Ok. I have my form name as "crmsample".


 
b) now In Solution Explorer, right click on Project(crmsample), go to Add and click on New Item. this new Item is the actual web page in which the fields are displayed. Now select the Web Form type of template.

 

c) Within the Solution Explorer, right Click on References and Click on Add Reference, now a pop-up will be displayed select the following Assemblies or browse it to the SDK/Bin folder there you can get these Assemblies.
  • System.ServiceModel.Description
  • Microsoft.Xrm.Sdk.Client
  • System.Net
  • Microsoft.Xrm.Sdk

d) Now go to Solution Explorer, right click on the form name(I had given name as Default) and click on View Designer.
 
e)  Now add corresponding labels and text boxes and button with the help of toolbox{here I am creating a contact record on clicking of a button}. The below screen shot explains it.

 
f) I've changed the Id's of text boxes,  by right clicking on text boxes go to properties, In properties toolbox you can change its ID.
for First Name - txtFirstName
for Last Name - txtLastName
for Email Address - txtEmailAddress
for Phone Number - txtPhoneNumber

g)  Now on click of Submit button the record must be created, so for doing thse we must give an action to the button so double click on button, then a snippet for the action of button on clicking will be displayed. add the following gode within the on click event of Submit button.
------------------>
protected void Button1_Click(object sender, EventArgs e)
        {
            ClientCredentials Credentials = new ClientCredentials();
            Credentials.UserName.UserName = "your User Name";
            Credentials.UserName.Password = "your Password";
            //Uncomment th below lines to use the default username and password for the browser in which CRM is currently opened
            //Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            //This URL needs to be updated to match the servername and Organization for the environment.
            Uri OrganizationUri = new Uri("Organization svc URL");
            Uri HomeRealmUri = null;
      
            using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))
            {
                IOrganizationService service = (IOrganizationService)serviceProxy;

                //Instantiate the contact object and populate the attributes.
                Entity contact = new Entity("contact");
                contact["firstname"] = txtFirstName.Text.ToString();
                contact["lastname"] = txtLastName.Text.ToString();
                contact["emailaddress1"] = txtEmailAddress.Text.ToString();
                contact["telephone1"] = txtPhoneNumber.Text.ToString();
                Guid newContactId = service.Create(contact);

                //This code will clear the textboxes after the contact is created.
                txtFirstName.Text = "";
                txtLastName.Text = "";
                txtEmailAddress.Text = "";
                txtPhoneNumber.Text = "";
            }
        }
----------------->
also add the included references to this file at top of the code.

h) Now click Complie and Run the code. The webpage will be opened in default web browser. the following screen shot shows it
 
i) Now fill the fields and click on Submit Button. Now go to your CRM and see the contact entity, a record will be created.
Note:- The Mandatory Fields in CRM should be filled or else the record will not be created and instead it will throw an error.