Tuesday 18 December 2012

Multi-selection options sets supports in all browser in CRM 2011 using javascript

This code will Support on IE, Chrome and FireFox....
Create Option set field which you want to convert to multi-select options.

Create Option set field
Create a Multiple lines of text field. This field only hold the user select values. So it would be invisible.

Multi line text field
After creating the above field that should be added to your form. The text field visibility mode should be invisible.

Then you need to create a new webresource file with the following code:

//Method to convert an optionset to multi select Option Set
function ConvertToMultiSelect(var_sc_optionset, var_sc_optionsetvalue, OS, OSV)
{

if (OS != null && OSV != null) {
        OS.style.display = "none";
        Xrm.Page.getControl(var_sc_optionsetvalue).setVisible(false);

        // Create a DIV container        
        var addDiv = null;
        var addInput = null;
        if (window.DOMParser) { //Chrome, Firefox and other browser
            try {                
                addDiv = document.createElement("div");
                addDiv.setAttribute("style", "overflow-y:auto; height:80px; border:1px #6699cc solid; background-color:#ffffff;");
            }
            catch (e) {
                alert(e);
            }
            OS.parentNode.appendChild(addDiv);

            // Initialise checkbox controls
            for (var i = 1; i < OS.options.length; i++) {

                var pOption = OS.options[i];
                if (!IsChecked(pOption.text, OS, OSV)) {                    
                    addInput = document.createElement("input");
                    addInput.setAttribute("type", "checkbox");
                    addInput.setAttribute("style", "border:none; width:25px; align:left;");
                } else {                   
                    addInput = document.createElement("input");
                    addInput.setAttribute("type", "checkbox");
                    addInput.setAttribute("checked", "checked");
                    addInput.setAttribute("style", "border:none; width:25px; align:left;");
                }

                var addLabel = document.createElement("label"); //("<label />");
                addLabel.innerText = pOption.text;

                var addBr = document.createElement("br"); //("<br/>"); //it's a 'br' flag            

                OS.nextSibling.appendChild(addInput);
                OS.nextSibling.appendChild(addLabel);
                OS.nextSibling.appendChild(addBr);
            }
        }
        else {  //IE Support
            try {
                var addDiv = document.createElement("<div style='overflow-y:auto; height:80px; border:1px #6699cc solid; background-color:#ffffff;' />");                
            }
            catch (e) {
                alert(e);
            }
            OS.parentNode.appendChild(addDiv);

            // Initialise checkbox controls
            for (var i = 1; i < OS.options.length; i++) {

                var pOption = OS.options[i];
                if (!IsChecked(pOption.text, OS, OSV)) {
                                    var addInput = document.createElement("<input type='checkbox' style='border:none; width:25px; align:left;' />");
                    
                } else {
                                    var addInput = document.createElement("<input type='checkbox' checked='checked' style='border:none; width:25px; align:left;' />");                    
                }

                var addLabel = document.createElement("<label />");
                addLabel.innerText = pOption.text;

                var addBr = document.createElement("<br/>");           

                OS.nextSibling.appendChild(addInput);
                OS.nextSibling.appendChild(addLabel);
                OS.nextSibling.appendChild(addBr);
            }
        }
    }
}



  // Check if it is selected
  function IsChecked( pText , OS, OSV)
  {
    if(OSV.value != "")
    {
      var OSVT = OSV.value.split(";");
      for( var i = 0; i < OSVT.length; i++ )
      {
        if( OSVT[i] == pText )
          return true;
      }
    }
    return false;
  }
  
  // Save the selected text, this field can also be used in Advanced Find
  function OnSave(OS, var_sc_optionsetvalue)
  {
    var getInput = OS.nextSibling.getElementsByTagName("input");
    var result = '';

    for( var i = 0; i < getInput.length; i++ )
    {
      if( getInput[i].checked)
      {
        result += getInput[i].nextSibling.innerText + ";";
      }
    }

    //save value
    control = Xrm.Page.getControl(var_sc_optionsetvalue);
    attribute = control.getAttribute();
    attribute.setValue(result);

  }


After adding the file to webresource you need to add on form OnLoad and OnSave event.



Then pass the parameter on OnLoad event:

OnLoad function

OnSave event:

OnSave Event parameters
After reload your form it will be displayed like this


Set lookup field while calling a Entity/Activity from ribbon button in CRM 2011


Here the look-up field is set based on another look-up field in the target entity.

function setLookupfield() {
        if (Xrm.Page.data.entity.attributes.get('targetfieldName').getValue()==null) {
            var EntityName, EntityId, LookupFieldObject;
            var Name = "";
            var resultXml;
            LookupFieldObject = Xrm.Page.data.entity.attributes.get('regardingobjectid');
            if (LookupFieldObject.getValue() != null) {
                EntityId = LookupFieldObject.getValue()[0].id;
                EntityName = LookupFieldObject.getValue()[0].entityType;
                resultXml = RetrieveEntityById(EntityName, EntityId, 'customerid');
                if (resultXml != null && resultXml.selectSingleNode('//q1:customerid') != null) {
                    var lookupValue = new Array();
                    lookupValue[0] = new Object();                  
                    lookupValue[0].id = resultXml.selectSingleNode('//q1:customerid').nodeTypedValue;
                    lookupValue[0].name = resultXml.selectSingleNode('//q1:customerid').getAttribute("name");
                    lookupValue[0].entityType = 'account';

                    Xrm.Page.data.entity.attributes.get('targetfieldname').setValue(lookupValue);
                }
            }
        }
    }
//Do not make any changes
function RetrieveEntityById(prmEntityName, prmEntityId, prmEntityColumns) {
    var resultXml, errorCount, msg, xmlHttpRequest, arrayEntityColumns, xmlEntityColumns;
    arrayEntityColumns = prmEntityColumns.split(",");
    for (var i = 0; i < arrayEntityColumns.length; i++) {
        xmlEntityColumns += "<q1:Attribute>" + arrayEntityColumns[i] + "</q1:Attribute>";
    }
    var authenticationHeader = Xrm.Page.context.getAuthenticationHeader();
    //Prepare the SOAP message.
    var xml = "<?xml version='1.0' encoding='utf-8'?>" +
    "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
    " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
    " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
    authenticationHeader +
    "<soap:Body>" +
    "<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
    "<entityName>" + prmEntityName + "</entityName>" +
    "<id>" + prmEntityId + "</id>" +
    "<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>" +
    "<q1:Attributes>" +
    xmlEntityColumns +
   "</q1:Attributes>" +
    "</columnSet>" +
    "</Retrieve></soap:Body></soap:Envelope>";
    //call function to create Soap Request to ms crm webservice
    xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);
    resultXml = xmlHttpRequest.responseXML;
    var errorCount = resultXml.selectNodes('//error').length;
    if (errorCount != 0) {
        var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
        alert("Error Message : " + msg);
    }
    else {
        return resultXml;
    }
}

After adding the javascript to webresources you need to call setLookupfield() function on page on-load event on the target entity.

Monday 17 December 2012

Enable/Disable ribbon button in CRM 2011 based on User security role using javascript


Add the following code into your webresources.

function UserHasRole(roleName) {

    var serverUrl = Xrm.Page.context.getServerUrl();
    var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
    oDataEndpointUrl += "RoleSet?$top=1&$filter=Name eq '" + roleName + "'";
    var service = GetRequestObject();
    if (service != null) {
        service.open("GET", oDataEndpointUrl, false);
        service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
        service.setRequestHeader("Accept", "application/json, text/javascript, */*");
        service.send(null);
        var requestResults = eval('(' + service.responseText + ')').d;
        if (requestResults != null && requestResults.results.length == 1) {
            var role = requestResults.results[0];
            var id = role.RoleId;
            var currentUserRoles = Xrm.Page.context.getUserRoles();
            for (var i = 0; i < currentUserRoles.length; i++) {
                var userRole = currentUserRoles[i];
                if (GuidsAreEqual(userRole, id)) {
                    return true;
                }
            }
        }
    }

    return false;
}

function GetRequestObject() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch (ex) {
            return null;
        }
    }
}
function GuidsAreEqual(guid1, guid2) {
    var isEqual = false;
    if (guid1 == null || guid2 == null) {
        isEqual = false;
    }
    else {
        isEqual = guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase();
    }

    return isEqual;
}

function callMain() {

    if (UserHasRole("Sales Manager")) {
        return true;
    }
    else {
        return false;
    }

}


  1. Open Visual Ribbon Editor tool.
  2. Select a Button which you want to Enable or Disable.
  3. Then select  a Enable Rules tab in the ribbon editor.
  4. Click Add-->Custom rule
  5. Give a webresource name in Library: here i gave $webresource:tvsi_userrole
  6. Then give a function name: callMain



Friday 14 December 2012

Trigger dialog from ribbon button in crm 2011 using javascript


function calldialog(dialogId, entityName, recordId) {
    var url = Xrm.Page.context.getServerUrl();

    recordId = recordId.replace("{", "");
    recordId = recordId.replace("}", "");
    dialogId = dialogId.replace("{", "");
    dialogId = dialogId.replace("}", "");

    url += "/cs/dialog/rundialog.aspx?DialogId=%7b" + dialogId.toUpperCase() + "%7d&EntityName=" + entityName + "&ObjectId=%7b" + recordId + '%7d';

    window.showModalDialog(url);
}

Copy your dialog process Id:


  1. Click Settings-->Solutions-->Open your Solutions-->Process-->Open your dialog process
  2. Click Actions-->Copy a Link
  3. The Link contains the Id of this dialog process.



Create a new button using visual ribbon editor tool and pass the parameter as follows






Function Name:calldialog
Library: $webresource:<webresource name>
1. String parameter Value: < Id of dialog process to be launched>
2.String parameter Value: <Name of the entity where the dialog will be launched>
3.Crm parameter: FirstPrimaryItemId // Current record Id

Thursday 13 December 2012

Set default view for Partylist or Lookup field in CRM 2011 using javascript.

function lookforuser()
{
document.getElementById("to").setAttribute("lookuptypes", "8");// set as user view
document.getElementById("to").setAttribute("defaulttype", "8");
//Copy the ID of View
Xrm.Page.getControl("to").setDefaultView("FCFB3A47-6760-E211-BACF-00155D000B45");
}

Monday 10 December 2012

Set the value of Option set field from one entity to another entity in CRM 2011 using javascript

var createContact = new XrmServiceToolkit.Soap.BusinessEntity("contact");// Target entity name

var country=Xrm.Page.data.entity.attributes.get("tvsi_countryregion").getValue();//Optionset value
if(country != null)
{
    createContact.attributes["tvsi_countryregion0"]={ value: country, type: "OptionSetValue" };
}

Call custom activity form in CRM 2011 using javascript




  1. Add this javascript into your webresources.


function OpenForm(pids) {
    var serverUrl;
    var errorMessage = "Context is not available.";
    var context;
    if (typeof GetGlobalContext != "undefined") {
        context = GetGlobalContext();
    }
    else {
        if (typeof Xrm != "undefined") {


            context = Xrm.Page.context;
        }
        else {
            alert(errorMessage);
            return;
        }
    }
    var entityId = context.getQueryStringParameters().id


    var entityEtc = context.getQueryStringParameters().etc


    var serverUrl = context.getServerUrl();
    if (serverUrl.match(/\/$/)) { serverUrl = serverUrl.substring(0, serverUrl.length - 1); }
    var recordUrl = serverUrl + "/userdefined/edit.aspx?";

//Here i used Fiddler tool to get TypeCode of my custom Activity.
    var params = "contactInfo=&etc=10004&pId="; // 10004 is type code of my custom activity.
    params += pids[0]; // Xrm.Page.data.entity.getId();
    params += "&pType=3"; // here type 3 is type code of Opportunity

    var URL = recordUrl + params;
    window.open(URL, "_blank", "width=900px,height=600px,resizable=1");
}


  1. Create a New button using visual ribbon editor.
  2. Click Action tab of Selected custom button.
  3. Then click Add link and then select JavaScriptFunction.
  4. There you have to give a function name and library path as follows:
  • Function Name: OpenForm
  • Library: $webresource:<created web resource name> //new_filename
  • Click Add link and the select CrmParameter.
  • Then select value: PrimaryItemIds


Saturday 8 December 2012

Get Guid from the PartyList in CRM 2011 using C#


Entity entity = (Entity)context.InputParameters["Target"];
var retrievedApprovalRequest = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet(true)).ToEntity<tvsi_approvalrequest>();

Guid salesmanagerId=new Guid();              
ActivityParty ap=new ActivityParty();
EntityCollection receiverIds = retrievedApprovalRequest.GetAttributeValue<EntityCollection>("to");
 for (int i = 0; i < Recipients.Entities.Count; i++)
 {
      ap = receiverIds[i].ToEntity<ActivityParty>();
      salesmanagerId = ap.PartyId.Id;                  
 }  

Share record with User/Team in CRM 2011 using c#


Share record with User / Team


GrantAccessRequest shareToUser = new GrantAccessRequest()
 {
  Target = new EntityReference("opportunity", opportunityId), //Entity Logical name and record Id
         PrincipalAccess = new PrincipalAccess
          {
                 Principal = new EntityReference(SystemUser.EntityLogicalName, userId_or_teamId),
                 AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess | AccessRights.ShareAccess
           }

};
GrantAccessResponse grantresponse = (GrantAccessResponse)service.Execute(shareToUser);

Remove record sharing from the User / Team

ModifyAccessRequest removeSharing = new ModifyAccessRequest
 {
  Target = new EntityReference("opportunity", opportunityId), //Entity Logical name and record Id
        PrincipalAccess = new PrincipalAccess
         {
                Principal = new EntityReference(SystemUser.EntityLogicalName, userId_or_teamId),
                AccessMask = AccessRights.None
          }
   };
ModifyAccessResponse modifyresponse = (ModifyAccessResponse)service.Execute(removeSharing);

Thursday 29 November 2012

Visible tab based on Optionset field value in crm 2011 using javascript


var fieldname = Xrm.Page.data.entity.attributes.get("new_fieldname").getText();
var tabvisible = Xrm.Page.ui.tabs.get("Status");
    if ( fieldname == "Qualified") {
            tabvisible.setVisible("true");
    }

Wednesday 28 November 2012

Get current user roles in CRM 2011 using javascript


// JScript source code
GetCurrentUserRoles = function () {

    var requestMain = ""

    requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    requestMain += "  <s:Body>";
    requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    requestMain += "      <request i:type=\"a:RetrieveMultipleRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\">";
    requestMain += "        <a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <b:key>Query</b:key>";
    requestMain += "            <b:value i:type=\"a:QueryExpression\">";
    requestMain += "              <a:ColumnSet>";
    requestMain += "                <a:AllColumns>false</a:AllColumns>";
    requestMain += "                <a:Columns xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">";
    requestMain += "                  <c:string>name</c:string>";
    requestMain += "                </a:Columns>";
    requestMain += "              </a:ColumnSet>";
    requestMain += "              <a:Criteria>";
    requestMain += "                <a:Conditions />";
    requestMain += "                <a:FilterOperator>And</a:FilterOperator>";
    requestMain += "                <a:Filters />";
    requestMain += "              </a:Criteria>";
    requestMain += "              <a:Distinct>false</a:Distinct>";
    requestMain += "              <a:EntityName>role</a:EntityName>";
    requestMain += "              <a:LinkEntities>";
    requestMain += "                <a:LinkEntity>";
    requestMain += "                  <a:Columns>";
    requestMain += "                    <a:AllColumns>false</a:AllColumns>";
    requestMain += "                    <a:Columns xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" />";
    requestMain += "                  </a:Columns>";
    requestMain += "                  <a:EntityAlias i:nil=\"true\" />";
    requestMain += "                  <a:JoinOperator>Inner</a:JoinOperator>";
    requestMain += "                  <a:LinkCriteria>";
    requestMain += "                    <a:Conditions>";
    requestMain += "                      <a:ConditionExpression>";
    requestMain += "                        <a:AttributeName>systemuserid</a:AttributeName>";
    requestMain += "                        <a:Operator>Equal</a:Operator>";
    requestMain += "                        <a:Values xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">";
    requestMain += "                          <c:anyType i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">" + Xrm.Page.context.getUserId() + "</c:anyType>";
    requestMain += "                        </a:Values>";
    requestMain += "                      </a:ConditionExpression>";
    requestMain += "                    </a:Conditions>";
    requestMain += "                    <a:FilterOperator>And</a:FilterOperator>";
    requestMain += "                    <a:Filters />";
    requestMain += "                  </a:LinkCriteria>";
    requestMain += "                  <a:LinkEntities />";
    requestMain += "                  <a:LinkFromAttributeName>roleid</a:LinkFromAttributeName>";
    requestMain += "                  <a:LinkFromEntityName>role</a:LinkFromEntityName>";
    requestMain += "                  <a:LinkToAttributeName>roleid</a:LinkToAttributeName>";
    requestMain += "                  <a:LinkToEntityName>systemuserroles</a:LinkToEntityName>";
    requestMain += "                </a:LinkEntity>";
    requestMain += "              </a:LinkEntities>";
    requestMain += "              <a:Orders />";
    requestMain += "              <a:PageInfo>";
    requestMain += "                <a:Count>0</a:Count>";
    requestMain += "                <a:PageNumber>0</a:PageNumber>";
    requestMain += "                <a:PagingCookie i:nil=\"true\" />";
    requestMain += "                <a:ReturnTotalRecordCount>false</a:ReturnTotalRecordCount>";
    requestMain += "              </a:PageInfo>";
    requestMain += "              <a:NoLock>false</a:NoLock>";
    requestMain += "            </b:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "        </a:Parameters>";
    requestMain += "        <a:RequestId i:nil=\"true\" />";
    requestMain += "        <a:RequestName>RetrieveMultiple</a:RequestName>";
    requestMain += "      </request>";
    requestMain += "    </Execute>";
    requestMain += "  </s:Body>";
    requestMain += "</s:Envelope>";
    var req = new XMLHttpRequest();
    req.open("POST", _getServerUrl(), false)
    // 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 () { RetrieveMultipleResponse(req, successCallback, errorCallback); };
    req.send(requestMain);  
    var resultXml = req.responseXML;
    return (resultXml);
}

function rolename() {
    var oXml = GetCurrentUserRoles();
    if (oXml != null) {
        //select the node text
        var roles = oXml.selectNodes("//a:Entities/a:Entity/a:Attributes/a:KeyValuePairOfstringanyType");
        if (roles != null) {
            for (j = 0; j < roles.length; j++) {
                   alert(roles[j].childNodes[1].text);               
            }
        }

    }
}

How to disable Form field in CRM 2011 using javascript

Xrm.Page.getControl("new_fieldname").setDisabled(true);

Hide tab or field based on User roles in CRM 2011 using javascript


function UserHasRole(roleName) {

var serverUrl = Xrm.Page.context.getServerUrl();
var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += "RoleSet?$top=1&$filter=Name eq '" + roleName + "'";
var service = GetRequestObject();

if (service != null)
{
service.open("GET",oDataEndpointUrl, false);
service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
service.setRequestHeader("Accept", "application/json,text/javascript, */*");
service.send(null);
var requestResults = eval('(' +service.responseText + ')').d;

if (requestResults != null && requestResults.results.length == 1)
{
    var role = requestResults.results[0];
    var id = role.RoleId;

//Get Current User Roles
    var currentUserRoles = Xrm.Page.context.getUserRoles();  

//Check whether current user roles has the role passed as argument
for (var i = 0; i < currentUserRoles.length;i++)
{
    var userRole = currentUserRoles[i];  
if (GuidsAreEqual(userRole, id))
{
return true;
}
}
}
}

return false;
}

function GetRequestObject()
{
if (window.XMLHttpRequest)
{
return new window.XMLHttpRequest;
}
else
{
try
{
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch (ex) {
return null;
}

}

}

function GuidsAreEqual(guid1, guid2) {

var isEqual = false;

if (guid1 == null || guid2 == null){

isEqual = false;

}

else {

isEqual = (guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase());

}
return isEqual;

}

function salesmanagerrole() {
    var field = Xrm.Page.ui.controls.get("fieldname");
    var tabvisible = Xrm.Page.ui.tabs.get("tabname");
    if (UserHasRole('Sales Manager')) {
        tabvisible.setVisible("true");
        field.setVisible("true");
    }
}

Thursday 22 November 2012

Code to Retrive the organization names in Dynamic CRM using c#


Right Click on the solutions --> Click Add service references


Right Click on the solutions --> Click Add service references


Then add the following references assemblies
  1. Microsoft.crm.sdk.proxy
  2. Microsoft.Xrm.Sdk
  3. System.ServiceModel




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Crm.Sdk;

namespace Organization
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

       ClientCredentials userCredentials = new ClientCredentials();
       private void btnSrvValidate_Click(object sender, EventArgs e)
        {
            cmbOrg.Items.Clear();
            List<string> orgNames = new List<string>();

            userCredentials.UserName.UserName = txtUser.Text.Trim();
            userCredentials.UserName.Password = txtPassword.Text.Trim();
            string serverName=txtServer.Text.Trim();        
       
            string crmURI = "http://"+ serverName +"/XRMServices/2011/Discovery.svc";
            DiscoveryServiceProxy discoveryProxy = new DiscoveryServiceProxy(new Uri(crmURI),null, userCredentials,null);
            discoveryProxy.Authenticate();
     
              try
            {
                RetrieveOrganizationsRequest retrieveOrganizationsRequest = new RetrieveOrganizationsRequest();        
                RetrieveOrganizationsResponse retrieveOrganizationsResponse = discoveryProxy.Execute(retrieveOrganizationsRequest) as RetrieveOrganizationsResponse;
                if (retrieveOrganizationsResponse.Details.Count != 0)
                {
                    foreach (OrganizationDetail orgInfo in retrieveOrganizationsResponse.Details)
                        orgNames.Add(orgInfo.FriendlyName);
                }
            }        
            catch (Exception)
            {
                throw new Exception("Please check the Dynamics CRM Server URL");
            }

           cmbOrg.Items.AddRange(orgNames.ToArray());
           cmbOrg.SelectedIndex = 0;
           cmbOrg.Focus();
     }
    }
}

Result:

Get current view part of lotus notes using java



org.eclipse.ui.IWorkbenchWindow win =  org.eclipse.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow();
org.eclipse.ui.IWorkbenchPart part=win.getPartService().getActivePart();
String viewname=part.getTitle().toString().trim();

find the deleted contact from the lotus notes using java


Database db;
Document doc;
Document tempdoc;
Vector books = session.getAddressBooks();
Enumeration e = books.elements();
    
 while (e.hasMoreElements())
{
db = (Database)e.nextElement();         
db.open();        
        
 if(db.isOpen())
 {
        DocumentCollection dc = db.getAllDocuments();
        doc = dc.getFirstDocument();         
                 
        while (doc != null)
        {                             
          if (doc.isValid())
  {
       if (doc.isDeleted())
       {
                                     JOptionPane.showMessageDialog(doc.getItemValueString("Name") + "Contact is valid but deleted", JOptionPane.INFORMATION_MESSAGE);        
        }
        else
             return doc;
    }
  }        
  tempdoc = dc.getNextDocument();           
  doc.recycle();
  doc = tempdoc;
 }
 dc.recycle();
}

Tuesday 20 November 2012

Associate account with contact while creating a Additional contact from the Lead Form.

  1. Download XrmServiceToolkit. Extract the zip file.
  2. Then you have to add the following script to crm webresources:
    •             jquery.js
    •             json.js
    •             XrmServiceToolkit.js
  3. Save the following code as javascript file. Then add it to the webresources.
function qualifyLeadRequest() {
    var requestMain = ""
xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    requestMain += "      <request i:type=\"b:QualifyLeadRequest\" 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>LeadId</c:key>";
    requestMain += "            <c:value i:type=\"a:EntityReference\">";
    requestMain += "              <a:Id>" + Xrm.Page.data.entity.getId() + "</a:Id>";
    requestMain += "              <a:LogicalName>lead</a:LogicalName>";
    requestMain += "              <a:Name i:nil=\"true\" />";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>CreateAccount</c:key>";
    requestMain += "            <c:value i:type=\"d:boolean\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">true</c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>CreateContact</c:key>";
    requestMain += "            <c:value i:type=\"d:boolean\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">true</c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>CreateOpportunity</c:key>";
    requestMain += "            <c:value i:type=\"d:boolean\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">false</c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>Status</c:key>";
    requestMain += "            <c:value i:type=\"a:OptionSetValue\">";
    requestMain += "              <a:Value>3</a:Value>";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>OpportunityCurrencyId</c:key>";
    requestMain += "            <c:value i:type=\"a:EntityReference\">";
    requestMain += "              <a:Id>89c14850-a5f3-e011-8606-1cc1dee89aa8</a:Id>";
    requestMain += "              <a:LogicalName>transactioncurrency</a:LogicalName>";
    requestMain += "              <a:Name i:nil=\"true\" />";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>OpportunityCustomerId</c:key>";
    requestMain += "            <c:value i:type=\"a:EntityReference\">";
    requestMain += "              <a:Id>e2d97648-a5f3-e011-8606-1cc1dee89aa8</a:Id>";
    requestMain += "              <a:LogicalName>account</a:LogicalName>";
    requestMain += "              <a:Name i:nil=\"true\" />";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>SourceCampaignId</c:key>";
    requestMain += "            <c:value i:type=\"a:EntityReference\">";
    requestMain += "              <a:Id>0ada7648-a5f3-e011-8606-1cc1dee89aa8</a:Id>";
    requestMain += "              <a:LogicalName>campaign</a:LogicalName>";
    requestMain += "              <a:Name i:nil=\"true\" />";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "        </a:Parameters>";
    requestMain += "        <a:RequestId i:nil=\"true\" />";
    requestMain += "        <a:RequestName>QualifyLead</a:RequestName>";
    requestMain += "      </request>";

    var resultXml = XrmServiceToolkit.Soap.Execute(requestMain);  
    var id = xmlToString(resultXml);// loadXML(resultXml);
    return id;
}

function xmlToString(resultXml) {
    if ($(resultXml).find('a\\:Id').length != 0) {
        response = $(resultXml).find('a\\:Id').eq(0);
    } else {
        response = $(resultXml).find('Id').eq(0); ; //Chrome 24.0.1312.52 could not find node by the previous code
    }
    var result = ((typeof window.CrmEncodeDecode != 'undefined') ? window.CrmEncodeDecode.CrmXmlDecode(response.text()) : crmXmlDecode(response.text()));

    return result;
}

function additionalContact(AccountId) {
 
    var createContact = new XrmServiceToolkit.Soap.BusinessEntity("contact");
    var salutation = Xrm.Page.data.entity.attributes.get("tvsi_ssalutation").getValue();      
    if(salutation != null)
    {
        createContact.attributes["tvsi_salutation"] = { value: salutation, type: "OptionSetValue" };      
    }
    createContact.attributes["firstname"] = Xrm.Page.data.entity.attributes.get("tvsi_firstname").getValue();
    createContact.attributes["lastname"] = Xrm.Page.data.entity.attributes.get("tvsi_lastname").getValue();
    createContact.attributes["jobtitle"] = Xrm.Page.data.entity.attributes.get("tvsi_jobtitle").getValue();
    createContact.attributes["emailaddress1"] = Xrm.Page.data.entity.attributes.get("tvsi_secondaryemail").getValue();
    createContact.attributes["telephone1"] = Xrm.Page.data.entity.attributes.get("tvsi_secondbusinessphone").getValue();
    createContact.attributes["mobilephone"] = Xrm.Page.data.entity.attributes.get("tvsi_mobilephone").getValue();
    createContact.attributes["address1_line1"]=Xrm.Page.data.entity.attributes.get("address1_line1").getValue();
    createContact.attributes["address1_line2"]=Xrm.Page.data.entity.attributes.get("address1_line2").getValue();
    createContact.attributes["address1_line3"]=Xrm.Page.data.entity.attributes.get("address1_line3").getValue();
    createContact.attributes["address1_city"]=Xrm.Page.data.entity.attributes.get("address1_city").getValue();
    createContact.attributes["address1_postalcode"]=Xrm.Page.data.entity.attributes.get("address1_postalcode").getValue();
    createContact.attributes["address1_stateorprovince"] = Xrm.Page.data.entity.attributes.get("address1_stateorprovince").getValue();
    var country = Xrm.Page.data.entity.attributes.get("tvsi_countryregion").getValue();//.getSelectedOption().value;    
    if(country != null)
    {
        createContact.attributes["tvsi_countryregion0"]={ value: country, type: "OptionSetValue" };
    }
     
 
    createContact.attributes["parentcustomerid"] = { id: AccountId, logicalName: "account", type: "EntityReference" };
    contactId1 = XrmServiceToolkit.Soap.Create(createContact);

}

function qualify() {   
    var id = qualifyLeadRequest();
   if(Xrm.Page.data.entity.attributes.get("tvsi_lastname").getValue()!=null)
       additionalContact(id);
    alert("Successfully Converted to Account and Contact");

    window.location.reload(true);
}


  1. Open VisualRibbonEditor Tool. Make a Connection with your CRM Server.
  2. Then Click Open. Entity Ribbon dialog will be Opened. There you have to select LEAD ribbon.
  3. Select ConverToLead button. After selected you need to click Action tab. Expand Javascript function.
  4. There you have to give a function name: qualify
  5. Library: /WebResources/new_filename



Qualify Lead automatically to Account, Contact and Opportunity using JavaScript

  1. Download XrmServiceToolkit. Extract the zip file.
  2. Then you have to add the following script to crm webresources:
  •             jquery.js
  •             json.js
  •             XrmServiceToolkit.js
Save the following code as javascript file. Then add it to the webresources.

function qualifyLeadRequest() {
    var requestMain = ""
xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    requestMain += "      <request i:type=\"b:QualifyLeadRequest\" 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>LeadId</c:key>";
    requestMain += "            <c:value i:type=\"a:EntityReference\">";
    requestMain += "              <a:Id>" + Xrm.Page.data.entity.getId() + "</a:Id>";
    requestMain += "              <a:LogicalName>lead</a:LogicalName>";
    requestMain += "              <a:Name i:nil=\"true\" />";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>CreateAccount</c:key>";
    requestMain += "            <c:value i:type=\"d:boolean\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">true</c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>CreateContact</c:key>";
    requestMain += "            <c:value i:type=\"d:boolean\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">true</c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>CreateOpportunity</c:key>";
    requestMain += "            <c:value i:type=\"d:boolean\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">true</c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>Status</c:key>";
    requestMain += "            <c:value i:type=\"a:OptionSetValue\">";
    requestMain += "              <a:Value>3</a:Value>";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>OpportunityCurrencyId</c:key>";
    requestMain += "            <c:value i:type=\"a:EntityReference\">";
    requestMain += "              <a:Id>89c14850-a5f3-e011-8606-1cc1dee89aa8</a:Id>";
    requestMain += "              <a:LogicalName>transactioncurrency</a:LogicalName>";
    requestMain += "              <a:Name i:nil=\"true\" />";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>OpportunityCustomerId</c:key>";
    requestMain += "            <c:value i:type=\"a:EntityReference\">";
    requestMain += "              <a:Id>e2d97648-a5f3-e011-8606-1cc1dee89aa8</a:Id>";
    requestMain += "              <a:LogicalName>account</a:LogicalName>";
    requestMain += "              <a:Name i:nil=\"true\" />";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>SourceCampaignId</c:key>";
    requestMain += "            <c:value i:type=\"a:EntityReference\">";
    requestMain += "              <a:Id>0ada7648-a5f3-e011-8606-1cc1dee89aa8</a:Id>";
    requestMain += "              <a:LogicalName>campaign</a:LogicalName>";
    requestMain += "              <a:Name i:nil=\"true\" />";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "        </a:Parameters>";
    requestMain += "        <a:RequestId i:nil=\"true\" />";
    requestMain += "        <a:RequestName>QualifyLead</a:RequestName>";
    requestMain += "      </request>";
//    requestMain += "    </Execute>";

    XrmServiceToolkit.Soap.Execute(requestMain);
}

function qualify() {   
    qualifyLeadRequest(); 
    window.location.reload(true);
}

  1. Open VisualRibbonEditor Tool. Make a Connection with your CRM Server.
  2. Then Click Open. Entity Ribbon dialog will be Opened. There you have to select LEAD ribbon.
  3. Select ConverToLead button. After selected you need to click Action tab. Expand Javascript function.
  4. There you have to give a function name: qualify
  5. Library: /WebResources/new_filename