Pages

Tuesday 19 November 2013

Send SMS to contact in Dynamics CRM


I have developed a plugin for send a text message to contact when a contact is created in crm.

Iam using site2sms api. We need to have a site2sms account and pass those credentials in web request. Using this, we can send unlimited text messages.

But we cannot send messages to contact who are registered their mobile number with DND activation.


Plugin code:


publicclass SendSms:IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
string emailobj = string.Empty;
Guid Conid = Guid.Empty;
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = (IOrganizationService)serviceFactory.CreateOrganizationService(context.UserId);
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity Cont = context.InputParameters["Target"] as Entity;
string to = Cont.Attributes["mobilephone"].ToString();
string customer = Cont.Attributes["fullname"].ToString();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(@"https://site2sms.p.mashape.com/index.php?uid=xxxxxxxxxx&pwd=xxxxx&phone=" + to + "&msg=type message here");
request.Headers.Add(
"X-Mashape-Authorization", "xxxxxxxxxxxxxx");
request.ContentType =
"application/json";
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
request.AllowAutoRedirect =
true;
request.KeepAlive =
true;
request.Method =
"GET";
request.Timeout = 50000;
request.Credentials =
CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
}
}

Tuesday 23 July 2013

Assign contacts

Retrieve Contacts.html:

<HTML xmlns="http://www.w3.org/1999/xhtml"><HEAD><TITLE>Untitled Page</TITLE>
<META charset=utf-8></HEAD>
<BODY spellcheck="true">
<SCRIPT type=text/javascript src="sample_/Scripts/SDK.REST.js"></SCRIPT>
<SCRIPT type=text/javascript src="ClientGlobalContext.js.aspx"></SCRIPT>
<SCRIPT type=text/javascript src="sample_/Scripts/json2.js"></SCRIPT>
<SCRIPT type=text/javascript src="my_RetrieveContacts"></SCRIPT>
<BUTTON id=btnRetrieveAccounts onclick=retrieveContacts();>Retrieve contacts</BUTTON><BUTTON id=btnGetUsers onclick="assignContacts('contactsTable');">Get Users</BUTTON>
<TABLE id=tableHeadings border=1 summary="This table provides the headings for the list of accounts displayed in a grid.">
<THEAD></THEAD>
<TBODY></TBODY></TABLE>
<TABLE id=contactsTable border=1>
<TBODY></TBODY></TABLE></BODY></HTML>


RetrieveContacs.js

     var contactsGrid;
     var ContactsCol;
    var totalcontactsCount = 0;
    function retrieveContacts() {
        var options = "$select=FullName,ContactId&$filter=Telephone1 eq '555-0109'";
        SDK.REST.retrieveMultipleRecords("Contact", options, retrieveContactsCallBack, function (error) { alert(error.message); }, contactsRetrieveComplete);
    }
    function retrieveContactsCallBack(retrievedContacts) {
        contactsGrid = document.getElementById('contactsTable');
        deleteAllRows("contactsTable");
        totalcontactsCount = retrievedContacts.length;
        ContactsCol=retrievedContacts;
        for (var i = 0; i < retrievedContacts.length; i++) {
            var contact = retrievedContacts[i];
            var rowCount = contactsGrid.rows.length;
            var row = contactsGrid.insertRow(rowCount);
            var cell1 = row.insertCell(0);
            var element1 = document.createElement("input");
            element1.type = "checkbox";
            element1.name = "chkbox[]";
            cell1.appendChild(element1);
            var cell2 = row.insertCell(1);
            var element2 = document.createElement();
            cell2.innerHTML = contact.FullName;
            cell2.appendChild(element2);
        }
    }
    function contactsRetrieveComplete() {

    }
    function clearaccountsGrid() {
        totalcontactsCount = 0;
        for (var i = contactsGrid.rows.length - 1; i >= 0; i--) {
            contactsGrid.deleteRow(i);
        }
    }
    function deleteAllRows(tableID) {
        try {
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;
            for (var i = 0; i < rowCount; i++) {
                var row = table.rows[i];
                table.deleteRow(i); rowCount--; i--;
            }
        }
        catch (e) {
            alert(e);
        }
    }
    function assignContacts(tableID){
      var obj =new Array();
        var ids="";
        var table = document.getElementById(tableID);
                var rowCount = table.rows.length;
                for (var i = 0; i < rowCount; i++) {
                    var row = table.rows[i];
                    var chkbox = row.cells[0].childNodes[0];
                    if (null != chkbox && true == chkbox.checked) {
                         obj[i]=new Object();
                         obj[i]= ContactsCol[i].ContactId;
                          ids=ids+obj[i]+" ";
                    }
                }
        window.open("https://crmtrail2011.crm5.dynamics.com//WebResources/my_usersList?orglcid=1033&orgname=crmtrail2011&userlcid=1033&data="+ids);
  }


Userslist.htm:


<HTML xmlns="http://www.w3.org/1999/xhtml"><HEAD><TITLE>Untitled Page</TITLE>
<META charset=utf-8></HEAD>
<BODY onload=getUsers(); spellcheck="true">
<SCRIPT type=text/javascript src="sample_/Scripts/SDK.REST.js"></SCRIPT>
<SCRIPT type=text/javascript src="ClientGlobalContext.js.aspx"></SCRIPT>
<SCRIPT type=text/javascript src="sample_/Scripts/json2.js"></SCRIPT>
<SCRIPT type=text/javascript src="sample_/Scripts/SDK.SOAPSample.Assign.js"></SCRIPT>
<SCRIPT type=text/javascript>
 
var UsersGrid;
var UsersCol;
var totalUsersCount = 0;
function getUsers() {
   var options = "$select=FullName,CALType,SystemUserId&$filter=AccessMode/Value ne 3 and IsDisabled eq false";
    SDK.REST.retrieveMultipleRecords("SystemUser", options, retrieveUsersCallBack, function (error) { alert(error.message); }, UsersRetrieveComplete);
}
function retrieveUsersCallBack(retrievedUsers) {
    UsersGrid = document.getElementById('UsersTable');
    totalUsersCount = totalUsersCount + retrievedUsers.length;
    UsersCol=retrievedUsers;
    for (var i = 0; i < retrievedUsers.length; i++) {
        var user= retrievedUsers[i];
        var rowCount = UsersGrid.rows.length;
        var row = UsersGrid.insertRow(rowCount);
        var cell1 = row.insertCell(0);
        var element1 = document.createElement("input");
        element1.type = "radio";
        element1.name = "chkbox[]";
        cell1.appendChild(element1);
        var cell2 = row.insertCell(1);
        var element2 = document.createElement();
        cell2.innerHTML = user.FullName;
        cell2.appendChild(element2);
        var lt=user.CALType;
       
        alert(lt.getText());
    }
}
function UsersRetrieveComplete() {

}
function assign(tableID){
       var uid;
        var table = document.getElementById(tableID);
                var rowCount = table.rows.length;
                for (var i = 0; i < rowCount; i++) {
                    var row = table.rows[i];
                    var chkbox = row.cells[0].childNodes[0];
                    if (null != chkbox && true == chkbox.checked) {
                         uid=new Object();
                         uid= UsersCol[i].SystemUserId;
                    }
               }
   var vals = new Array();
   if (location.search != "") {
    vals = location.search.substr(1).split("&");
    for (var i in vals) {
     vals[i] = vals[i].replace(/\+/g, " ").split("=");
    }
    //look for the parameter named 'data'
    for (var i in vals) {
     if (vals[i][0].toLowerCase() == "data") {
       var split=vals[i][1].split(" ");
     for(var count=0;count<split.length;count++){
       var contactid  = split[count];
       SDK.SOAPSamples.assignRequest(uid,contactid ,"contact",scb,ecb);
     }
     }
    }
 }
 }
 function scb(){
   alert("success");
 }
function ecb(){
 alert("error");
}
</SCRIPT>
<BUTTON id=btnAssign onclick="assign('usersTable');">Assign</BUTTON>
<TABLE id=tableHeadings border=1 summary="This table provides the headings for the list of users displayed in a grid.">
<THEAD></THEAD>
<TBODY></TBODY></TABLE>
<TABLE id=usersTable border=1>
<TBODY></TBODY></TABLE></BODY></HTML>

Tuesday 9 July 2013

Create multi select option set in dynamics crm 2011

The following function is used to add multi select optionset in CRM 2011.

For this,we need to create two fields.
 1. new_optionset (type : Optionset)
 2. new_text (type : multi line text) - This is hidden field.

Here , we have to pass 5 parameters in MultiPickList function.

param1- Optionset field Name (new_optionset)
param2 - Multiline text field (new_text)
param3 - empty string ("")
param4 - selected color ( I used green).



function MultiPickList(param1, param2, param3, param4, param5) {
    try {
        var fn = arguments.callee.toString().match(/function\s+([^\s\(]+)/);
        if (param1 == null || param2 == null) {
            alert("Error: Parameter missing. \n Format: <optionset fieldsname> ,  <option value text field> ,  [<option header>], [<select color>]   , [<deselect color>] ,  \n [" + "Function=" + fn[1] + "]");
            return true;
        }
        var tparamtype = Xrm.Page.data.entity.attributes.get(param1).getAttributeType();
        if (tparamtype != "optionset") {
            alert(param1 + "(first parameter) should be of type optionset \n" + "[function=" + fn[1] + "]");
            return true;
        }
        var tparamtype = Xrm.Page.data.entity.attributes.get(param2).getAttributeType();
        if (tparamtype != "memo") {
            alert(param2 + "(second parameter) should be of type memo (text with mutiline) \n[function=" + fn[1] + "]");
            return true;
        }
        var plOptions = param1;
        var plText = param2;
        var plMenuItem = "View Selected List";
        var SelectedList_orig = crmForm.all[plText];
        var FullList = crmForm.all[plOptions];
        var SelCtr = -1;
        var new_selColor = "orange";
        var new_deSelColor = "white";
        if (param4 != null)
            new_selColor = param4;
        if (param5 != null)
            new_deSelColor = param5;
        var SelectedList = SelectedList_orig.value.split("\r\n");
       
        crmForm.all[plText].style.display = "none";
        if (FullList != null && SelectedList != null) {
            initColor();
            if (param3 != null && param3 != "") {
                plMenuItem = param3;
            }
            else {
                plMenuItem = FullList.options[0].text;
                changeColor("grey", 0);
            }
           
            for (var ctr = 0; ctr < SelectedList.length; ctr++) {
                selCtr = SelectedIndex(SelectedList[ctr]);
                if (selCtr > -1) {
                    changeColor(new_selColor, selCtr);
                }
            }
        }
        function SelectedIndex(selectedText) {
            var FullListValue;
            for (var ctr1 = 0; ctr1 < FullList.options.length; ctr1++) {
                FullListValue = FullList.options[ctr1].index;
                if (FullListValue == selectedText) {
                    return ctr1;
                }
            }
            return -2;
        }
        crmForm.all[plOptions].attachEvent('onchange', OnChangePL);
        function OnChangePL() {
            var SelCtr = -1;
            var optionSetCntrl = document.getElementById(plOptions);
            var sel = optionSetCntrl.value;
            if (sel == plMenuItem)
                return;
            SelCtr = SelectedIndex(sel);
            var SelColor = "grey";
            SelColor = crmForm.all[plOptions][SelCtr].style.backgroundColor;
            if (SelColor == new_selColor) {
                changeColor(new_deSelColor, SelCtr);
                saveChanges(sel, selCtr, "del");
            }
            else {
                changeColor(new_selColor, SelCtr);
                saveChanges(sel, selCtr, "add");
            }
        }
        function saveChanges(p_selText, p_SelCtr, p_mode) {
            switch (p_mode) {
                case "add":
                    SelectedList.push(p_selText);
                    break;
                case "del":
                    for (var ctr2 = 0; ctr2 < SelectedList.length; ctr2++) {
                        if (SelectedList[ctr2] == p_selText) {
                            SelectedList.splice(ctr2, 1);
                            break;
                        }
                    }
                    break;
            }
            Xrm.Page.getAttribute(plText).setValue(SelectedList.join("\r\n"));
        }
        function initColor() {
            for (var ctr3 = 0; ctr3 < FullList.options.length; ctr3++)
            { changeColor(new_deSelColor, ctr3); }
        }
        function changeColor(newColor, newCtr) {
            crmForm.all[plOptions][newCtr].style.backgroundColor = newColor;
        }
    }
    catch (e)
         { alert(e.description); }
}

Sunday 7 July 2013

Show or Hide a tab in the form onload using javascript

This function is used for hiding a tab in onload event.
Using Javascript, we can easily show or hide a tab on a form.
The following functionality works as hide a tab in new form and show that tab again in existing form.

function tabHide()
{
  var formType=Xrm.Page.ui.getFormType();
  if(formType==1)
  {
     Xrm.Page.ui.tabs.get("tab_details", "collapsed", false).setVisible(false);
  }
  else
  {
     Xrm.Page.ui.tabs.get("tab_details", "collapsed", false).setVisible(true);
  }
}

                                          (OR)


function tabHide()
{
  var formType=Xrm.Page.ui.getFormType();
  if(formType==1)
  {

//Here 1 is mentioned that this is a second tab("Details" tab in my contact page) in a form
     Xrm.Page.ui.tabs.get(1).setVisible(false);  
  }
  else
  {
     Xrm.Page.ui.tabs.get(1).setVisible(true);
  }
}

Friday 5 July 2013

How to integrate CRM contact data based on phone number to HTML Page Web resource

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Add/Remove dynamic rows in HTML table </title>
    <script src="../ClientGlobalContext.js.aspx" type="text/javascript"></script>
    <script src="utils/FetchUtil.js" type="text/javascript"></script>
    <script type="text/javascript" language="javascript">
        function addRow(tableID) {
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
            var cell1 = row.insertCell(0);
            var element1 = document.createElement("input");
            element1.type = "checkbox";
            element1.name = "chkbox[]";
            cell1.appendChild(element1);
            var cell2 = row.insertCell(1);
            cell2.innerHTML = rowCount + 1;
            var cell3 = row.insertCell(2);
            var element2 = document.createElement();
            cell3.innerHTML = rowCount;
            cell3.appendChild(element2);
        }
        function deleteRow(tableID) {
            try {
                var table = document.getElementById(tableID);
                var rowCount = table.rows.length;
                for (var i = 0; i < rowCount; i++) {
                    var row = table.rows[i];
                    var chkbox = row.cells[0].childNodes[0];
                    if (null != chkbox && true == chkbox.checked) {
                        table.deleteRow(i); rowCount--; i--;
                    }
                }
            }
            catch (e) {
                alert(e);
            }
        }
        function deleteAllRows(tableID) {
            try {
                var table = document.getElementById(tableID);
                var rowCount = table.rows.length;
                for (var i = 0; i < rowCount; i++) {
                    var row = table.rows[i];
                    table.deleteRow(i); rowCount--; i--;
                }
            }
            catch (e) {
                alert(e);
            }
        }
        function getData(tableID) {
            var table = document.getElementById(tableID);
            var pn = "123456";
            deleteAllRows(tableID);
            var _oService;
            var _sOrgName = "";
            var _sServerUrl = Xrm.Page.context.getServerUrl();
            alert(_sServerUrl);
            var sFetch = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
  "<entity name='contact'>" +
    "<attribute name='fullname' />" +
    "<attribute name='parentcustomerid' />" +
    "<attribute name='telephone1' />" +
    "<attribute name='address1_city' />" +
    "<attribute name='emailaddress1' />" +
    "<attribute name='adx_username' />" +
    "<attribute name='createdon' />" +
    "<attribute name='contactid' />" +
    "<order attribute='createdon' descending='true' />" +
    "<filter type='and'>" +
      "<condition attribute='statecode' operator='eq' value='0' />" +
      "<condition attribute='telephone1' operator='eq' value='" + pn + "'/>" +
    "</filter>" +
  "</entity>" +
"</fetch>";
            _oService = new FetchUtil(_sOrgName, _sServerUrl);
            var res = _oService.Fetch(sFetch);
            for (var i = 0; i < res.length; i++) {
                var fn = res[i].attributes["fullname"].value;
                bindData(tableID, fn);
            }
        }
        function bindData(tableID, ContactName) {
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
            var cell1 = row.insertCell(0);
            var element1 = document.createElement("input");
            element1.type = "checkbox";
            element1.name = "chkbox[]";
            cell1.appendChild(element1);
            var cell2 = row.insertCell(1);
            cell2.innerHTML = rowCount + 1;
            var cell3 = row.insertCell(2);
            var element2 = document.createElement();
            cell3.innerHTML = ContactName;
            cell3.appendChild(element2);
        }
    </script>
</head>
<body>
    <input type="button" value="Get Data" onclick="getData('dataTable')" />
    <input type="button" value="Add Row" onclick="addRow('dataTable')" />
    <input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
    <table id="dataTable" width="350px" border="1">
        <tr>
            <td>
                <input type="checkbox" name="chk" />
            </td>
            <td>
                1
            </td>
            <td>
                &nbsp;
            </td>
        </tr>
    </table>
</body>
</html>


Thursday 27 June 2013

Copy Email description to case description when email convert to case

How to copy Email description to case description when email convert to case.

For this i have created a small workflow to get this result.

Please see below screenshot.




I have take this workflow on email entity and it will be fired if regarding field change in email. Because when we convert email to case, regarding filed will update automatically in email. so i took like this.

Just Update regarding case of email.

How to create custom entity in CRM 2011

Please follow below steps for create a custom entity in CRM 2011
1.       Navigate to Settings à Solutions. From here, select the appropriate solution you want to add your entity to. You can also create a new solution for your entity if you prefer.
2.       Inside of the selected solution, make sure you have selected components in the Navigation menu, click the New button, and the select Entity. You are presented with the information form for entering general entity settings.
3.       The first thing you need to do when creating an entity is to enter some general settings. Many of these settings can be changed later, but some can only be made when you initially create the entity, and others can be set after the initial entity creation but cannot be changed again after that. Before creating an entity, you should understand these limitations so you can plan an entity that will meet your long term needs.
4.       When you have completed entering your settings, click the save button. You can continue to customize the entity. Then publish all customizations.






Entity definition

The entity definition area includes a number of different important settings as follows:

·         Display Name / Plural Name: These two fields represent the name of the entity as it will appear in Dynamics CRM. In some contexts the plural name will be used, and in others the display name will be used. These values can be changed later if desired.
·         Name: This field is the name that the entity will be referred to if it is referenced within custom code including custom reports, JScript, or other programming code. This field cannot be changed after the entity has been saved for the first time.
·         Description: This field is an optional field with more information on how the entity will be used within Dynamics CRM. It is a best practice to enter text into description fields that documents how the entity will be used. By entering this documentation, you will make it easier to support your instance of Dynamics CRM in the future.
·         Ownership: This field determines who will own each record in the entity. Another way to think about ownership is to ask, “Who will be responsible for maintaining this record in Dynamics CRM?” This field plays an important part in defining security roles and in establishing views and charts of data. After you select a value for this setting and save the entity, you cannot change it. Options for this field are as follows:
·         User or Team: Select this option if every record in this entity will be “owned” by a user or by a team of users. For example, if you create an entity to track projects, then you will most likely want to use this setting because your projects will be assigned to an owner who is responsible for making sure that his or her projects are managed properly.
·         Organization: Select this option if records won’t be owned by any particular individual or team. For example, if you create an entity to track customer inventory, then you will most likely want to use this setting because this inventory will not be owned by a particular user (or team) in your business.

Wednesday 26 June 2013

how to trigger a plug-in from jscript

I can tell you that the question of how to trigger a plug-in from jscript comes up pretty frequently.  Usually someone wants to just trigger the plug-in from a form event, but also sometimes people want to trigger the plug-in from a ribbon button.  Unfortunately, a lot of the replies usually say that it's not supported or not possible. I am happy to say that it is possible and that I have regularly used this workaround to achieve this and it even uses supported methodology.

The code examples I link to today will be for CRM 2011 but the basic methodology is the same for 4.0 also.


Description
Here is how this works:

1. First you need to create a new custom entity to act as a trigger entity, I'll often times even name this new custom entity "new_trigger{plugin name}"


2. Now you must register your plug-in (or several plug-ins) on the create or update messages for this new entity. (I usually prefer the create message for my registrations because a new record will be created which keeps a record or audit-trail of who manually executed your plug-in and when in the created by and created time-stamp attributes on the entity)


3.  You must create a jscript web resource that contains a function that performs a soap update or create call on the entity depending on which message you registered your plug-in on.


4.  Lastly you must add your web resource to your form and call your update or create jscript function on one of the exposed form events (OnLoad, OnSave, etc...).  You can also call your jscript function from ribbon button if you want.

I hope this helps!