Populate Lookup value on selection of another Lookup


 Step 1.


Step 2.

Step 3.

Let me explain the scenario…

Suppose we have City Lookup on Lead entity and we want to populate Region (Lookup), State (Lookup) and Zone (Lookup) on selection of particular City from City Lookup. You need to write below code on OnChange event of City Lookup field.

if(crmForm.all.new_cityid.DataValue !=null)

{

    var citylookupValues = crmForm.all.new_cityid.DataValue;

    if(citylookupValues[0] !=null)

    {

        var cityID = citylookupValues[0].id;

        var regionID = GetAttributeValueFromID(“new_city”, cityID , “new_regionid”);

        var stateID = GetAttributeValueFromID(“new_city”, cityID , “new_stateid”);

        var zoneID = GetAttributeValueFromID(“new_region”, regionID , “new_zoneid”);   

        if(regionID != null)

        {

            //Create an array to set as the DataValue for the lookup control.

            var regionlookupData = new Array();

            //Create an Object add to the array.

            var regionlookupItem= new Object();

            //Set the id, typename, and name properties to the object.

            regionlookupItem.id = regionID;

            regionlookupItem.typename = ‘new_region’;

            regionlookupItem.name = regionName;

            // Add the object to the array.

            regionlookupData[0] = regionlookupItem;

            // Set the value of the lookup field to the value of the array.

            crmForm.all.new_regionid.DataValue = regionlookupData;

            crmForm.all.new_regionid.ForceSubmit = true;

 

        }

        if(stateID != null)

        {

            //Create an array to set as the DataValue for the lookup control.

            var statelookupData = new Array();

            //Create an Object add to the array.

            var statelookupItem = new Object();

            //Set the id, typename, and name properties to the object.

            statelookupItem.id = stateID;

            statelookupItem.typename = ‘new_state’;

            statelookupItem.name = stateName;

            // Add the object to the array.

            statelookupData[0] = statelookupItem;

            // Set the value of the lookup field to the value of the array.

            crmForm.all.new_stateid.DataValue = statelookupData;

            crmForm.all.new_stateid.ForceSubmit = true;

        }

        if(zoneID != null)

        {

            var zoneName = GetAttributeValueFromID(“new_zone”, zoneID, “new_name”);

            //Create an array to set as the DataValue for the lookup control.

            var zonelookupData = new Array();

            //Create an Object add to the array.

            var zonelookupItem = new Object();

            //Set the id, typename, and name properties to the object.

            zonelookupItem.id = zoneID;

            zonelookupItem.typename = ‘new_zone’;

            zonelookupItem.name = zoneName;

            // Add the object to the array.

            zonelookupData[0] = zonelookupItem;

            // Set the value of the lookup field to the value of the array.

            crmForm.all.new_zoneid.DataValue = zonelookupData;

            crmForm.all.new_zoneid.ForceSubmit = true;

        }

     }

}

else

{

     crmForm.all.new_regionid.DataValue = null;

    crmForm.all.new_stateid.DataValue = null;

    crmForm.all.new_zoneid.DataValue = null;

}

 

function  GetAttributeValueFromID(sEntityName, sGUID, sAttributeName)

{

    /*

    * sEntityName: the name of the CRM entity (account, etc.)

    * whose attribute value wish to look up

    * sGUID: string representation of the unique identifier of the specific object whose attrbuite value we wish to look up

    * sAttributeName – the schema name of the attribute whose value we wish returned

    */

 

    var sXml = “”;

    //var oXmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);

    var oXmlHttp = new ActiveXObject(“Msxml2.XMLHTTP.6.0”);

 

    //var serverurl = “http://10.10.40.50:5555”;

    var serverurl = “”;

 

    //set up the SOAP message

    sXml += “<?xml version=\”1.0\” encoding=\”utf-8\” ?>”;

    sXml += “<soap:Envelope xmlns:soap=\”http://schemas.xmlsoap.org/soap/envelope/\””

    sXml += ” xmlns:xsi=\”http://www.w3.org/2001/XMLSchema-instance\””

    sXml += ” xmlns:xsd=\”http://www.w3.org/2001/XMLSchema\”>”;

    sXml += “<soap:Body>”;

    sXml += “<entityName xmlns=\”http://schemas.microsoft.com/crm/2006/WebServices\”>” +

    sEntityName + “</entityName>”;

    sXml += “<id xmlns=\”http://schemas.microsoft.com/crm/2006/WebServices\”>” +

    sGUID + “</id>”;

    sXml += “<columnSet xmlns=\”http://schemas.microsoft.com/crm/2006/WebServices\””

    sXml += ” xmlns:q=\”http://schemas.microsoft.com/crm/2006/Query\””

    sXml += ” xsi:type=\”q:ColumnSet\”><q:Attributes><q:Attribute>” +

    sAttributeName + “</q:Attribute></q:Attributes></columnSet>”;

    sXml += “</soap:Body>”;

    sXml += “</soap:Envelope>”;

 

    // send the message to the CRM Web service

    oXmlHttp.Open(“POST”, serverurl +

    “/MsCrmServices/2006/CrmService.asmx”,false);

    oXmlHttp.setRequestHeader(“SOAPAction”,

    “http://schemas.microsoft.com/crm/2006/WebServices/Retrieve&#8221;);

    oXmlHttp.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”);

    oXmlHttp.setRequestHeader(“Content-Length”, sXml.length);

    oXmlHttp.send(sXml);

 

    // retrieve response and find attribute value

    //var result = oXmlHttp.responseXML.selectSingleNode(“//” + sAttributeName);

    var result = oXmlHttp.responseXML.selectSingleNode(“//*[local-name()=\””+  sAttributeName +”\”]”);

    if (result == null)

    {

    return “”;

    }

    else

    return result.text;

}

Replace a field to a button or Create a button on Form, and attach the onclick() event


This is an example on how to create a button on the form, using java script. First of all we need to create a nvarchar attribute and put it on the form where we want our button.
In this example my attribute’s schema name is new_test.

Here is the code

/*———————————-*/

someFunction = function()

{

alert(“button clicked!”);

}

// This is how we call the button, what we see

crmForm.all.new_test.DataValue = “Button”;

// We could align it a bit

crmForm.all.new_test.style.textAlign = “center”;

crmForm.all.new_test.vAlign = “middle”;

//we make the mouse look as a hand when we’re moving over

crmForm.all.new_test.style.cursor = “hand”;

crmForm.all.new_test.style.backgroundColor = “#CADFFC”;

crmForm.all.new_test.style.color = “#FF0000”;

crmForm.all.new_test.style.borderColor = “#330066”;

crmForm.all.new_test.style.fontWeight = “bold”;

crmForm.all.new_test.contentEditable = false;

//we attach some events in order to make it look nice 🙂

crmForm.all.new_test.attachEvent(“onmousedown”,color1);

crmForm.all.new_test.attachEvent(“onmouseup”,color2);

crmForm.all.new_test.attachEvent(“onmouseover”,color3);

crmForm.all.new_test.attachEvent(“onmouseleave”,color4);

function color3() {

crmForm.all.new_test.style.backgroundColor = “#6699FF”;

}

function color4() {

crmForm.all.new_test.style.backgroundColor = “CADFFC”;

}

function color1() {

crmForm.all.new_test.style.color = “000099”;

}

function color2() {

crmForm.all.new_test.style.color = “FF0000”;

}

//here we attach what we want our button do

crmForm.all.new_test.attachEvent(“onclick”,someFunction);
Replace a field to a label (use replaceNode())
/* replace new_field_d to a label */
if (crmForm.all.new_field != null)
{
var html = document.createElement( “”);
html.innerText = “this is a lable”;
crmForm.all.new_field_d.replaceNode(buttonText);
}

Append text under a field (you don’t need to create an attribute for that)
/* append text under new_field */
if(crmForm.all.new_field != null)
{
var html= document.createElement( “”);
html.innerText = “this is a text field”;
crmForm.all.new_field.parentNode.appendChild(html);
}

Revoke Access To Entity


private bool RevokeAccessToEntity(ICrmService service, Guid guidValue, Guid entityID, string EntityName)
{
bool isSuccess = false;
// Create the SecurityPrincipal object.
SecurityPrincipal principal = new SecurityPrincipal();

// PrincipalId is the GUID of the team whose access is being revoked.
principal.Type = SecurityPrincipalType.Team;

principal.PrincipalId = guidValue;

// Create the target for the request.
TargetOwnedDynamic target = new TargetOwnedDynamic();
// EntityId is the GUID of the Opportunity to which
// access is being revoked.
target.EntityId = entityID;
target.EntityName = EntityName;

// Create the request object.
RevokeAccessRequest revoke = new RevokeAccessRequest();
// Set the properties of the request object.
revoke.Revokee = principal;
revoke.Target = target;
// Execute the request.

try
{
RevokeAccessResponse revoked = (RevokeAccessResponse)service.Execute(revoke);
isSuccess = true;
}
catch (Exception ex)
{
isSuccess = false;
throw ex;
}
return isSuccess;

}

AutoNumber Plug-In for Custom Entity In CRM 4.0


using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.Crm.Sdk;

using Microsoft.Crm.SdkTypeProxy;

using Microsoft.Crm.Sdk.Query;

using System.Web.Services.Protocols;

namespace CRM.Customization.AutoNumber

{

public class AutoNumberPlugIns:IPlugin

{

DynamicEntity entity = null;

int startNumber;

string prefix = string.Empty;

string seperator = string.Empty;

int nextMaxNumber;

string uniqueId = string.Empty;

#region IPlugin Members

public void Execute(IPluginExecutionContext context)

{

if (context.InputParameters.Properties.Contains(“Target”) &&

context.InputParameters.Properties[“Target”] is DynamicEntity)

{

entity = (DynamicEntity)context.InputParameters.Properties[“target”];

ICrmService service = context.CreateCrmService(true);

if (entity.Name ==“new_testentity”)

{

// Find maximum number

int maxNumber = FindMaxNumber(service);

nextMaxNumber=maxNumber + 1;

if (nextMaxNumber > 0)

{

bool isRetrivePrefixSuccess = RetrievePrefixSufixAndStartNumber(service);

if (isRetrivePrefixSuccess)

{

if (nextMaxNumber >= startNumber)

{

string buildAutoNumber = prefix + seperator + nextMaxNumber.ToString();

uniqueId = buildAutoNumber;

StringProperty uId = new StringProperty(“new_uniqueid”, uniqueId);

entity.Properties.Add(uId);

CrmNumber nextNumber = new CrmNumber();

nextNumber.Value = nextMaxNumber;

CrmNumberProperty uniqueNo = new CrmNumberProperty(“new_uniqueno”, nextNumber);

entity.Properties.Add(uniqueNo);

}

}

}

}

}

}

private int FindMaxNumber(ICrmService service)

{

int maxNo=0;

QueryExpression query = new QueryExpression();

query.EntityName = “new_testentity”;

ColumnSet cols = new ColumnSet();

cols.AddColumn(“new_uniqueno”);

query.ColumnSet = cols;

query.AddOrder(“new_uniqueno”, OrderType.Descending);

PagingInfo pageInfo = new PagingInfo();

pageInfo.Count = 1;

pageInfo.PageNumber = 1;

query.PageInfo = pageInfo;

RetrieveMultipleRequest request = new RetrieveMultipleRequest();

request.Query = query;

request.ReturnDynamicEntities = true;

RetrieveMultipleResponse response = (RetrieveMultipleResponse)service.Execute(request);

DynamicEntity testEntity = (DynamicEntity)response.BusinessEntityCollection.BusinessEntities[0];

for (int i = 0; i < testEntity.Properties.Count; i++)

{

if (testEntity.Properties.Contains(“new_uniqueno”))

{

CrmNumber uniqueNumber = (CrmNumber)testEntity.Properties[“new_uniqueno”];

maxNo = uniqueNumber.Value;

}

}

return maxNo;

}

private bool RetrievePrefixSufixAndStartNumber(ICrmService service)

{

try

{

QueryByAttribute query = new QueryByAttribute();

query.EntityName = “new_autonumber”;

ColumnSet cols = new ColumnSet();

cols.AddColumn(“new_startnumber”);

cols.AddColumn(“new_prefix”);

cols.AddColumn(“new_currentnumber”);

cols.AddColumn(“new_separator”);

query.ColumnSet = cols;

query.Attributes = new string[] { “new_entityname” };

query.Values = new object[] { “new_testentity” };

RetrieveMultipleRequest request = new RetrieveMultipleRequest();

request.Query = query;

request.ReturnDynamicEntities = true;

RetrieveMultipleResponse response = (RetrieveMultipleResponse)service.Execute(request);

DynamicEntity dynamicsEntity = (DynamicEntity)response.BusinessEntityCollection.BusinessEntities[0];

if (dynamicsEntity.Properties.Count > 0)

{

// DynamicEntity autoNumberEntity = (DynamicEntity)dynamicsEntity.BusinessEntities[0];

// Extract the fullname from the dynamic entity string fullname;

for (int i = 0; i < dynamicsEntity.Properties.Count; i++)

{

if (dynamicsEntity.Properties.Contains(“new_startnumber”))

{

CrmNumber startNo = (CrmNumber)dynamicsEntity.Properties[“new_startnumber”];

startNumber = startNo.Value;

}

if (dynamicsEntity.Properties.Contains(“new_prefix”))

{

String prefixId = (String)dynamicsEntity.Properties[“new_prefix”];

prefix = prefixId.ToString();

}

if (dynamicsEntity.Properties.Contains(“new_separator”))

{

String seperaterId = (String)dynamicsEntity.Properties[“new_separator”];

seperator = seperaterId.ToString();

}

}

}

return true;

}

catch (SoapException ex)

{

throw ex;

}

}

}

#endregion

}

Sharing Record with a Team


using  System;

using System.Collections.Generic;

using System.Text;

using Microsoft.Crm.Sdk;

using Microsoft.Crm.SdkTypeProxy;

using Microsoft.Crm.Sdk.Query;

namespace CRM.Customization.Sharing
{

public class SharingRecord:IPlugin

{

string teamId = string.Empty;

#region IPlugin Members

public void Execute(IPluginExecutionContext context)
{
DynamicEntity entity=null ;

if (context.InputParameters.Properties.Contains(“Target” )
&& context.InputParameters.Properties[“Target”] is DynamicEntity )
{
entity = (DynamicEntity)context.InputParameters.Properties[“Target” ];
Guid recordId=(Guid)context.OutputParameters.Properties[“id” ];

ICrmService service = context.CreateCrmService(true );

// Query express to find out team id to share the rescord

QueryByAttribute query = new QueryByAttribute ();
query.EntityName =EntityName .team.ToString();

ColumnSet cols = new ColumnSet ();
cols.AddColumn(“teamid” );

query.ColumnSet = cols;
query.Attributes =new string[] { “name”

};
query.Values =new string[] { “MUL” };

BusinessEntityCollection retrieved = (BusinessEntityCollection) service.RetrieveMultiple(query);
if (retrieved.BusinessEntities.Count > 0 )
{
team newTeam = (team )retrieved.BusinessEntities[0];
Key teamGuid = (Key )newTeam.teamid;
teamId = teamGuid.Value.ToString();
}

// Create the SecurityPrincipal Object
SecurityPrincipal principal = new SecurityPrincipal ();
principal.Type =SecurityPrincipalType .Team;

// PrincipalId is the Guid of the user to whom access is being granted
principal.PrincipalId =new Guid (teamId);

// Create the PrincipalAccess Object
PrincipalAccess principalAccess = new PrincipalAccess ();

// Set the PrincipalAccess Object’s Properties
principalAccess.Principal = principal;

// Gives the principal access to read
principalAccess.AccessMask =AccessRights .ReadAccess;

// Create the Target Object for the Request
TargetOwnedOpportunity target = new TargetOwnedOpportunity ();

// EntityId is the Guid of the account access is being granted to
target.EntityId = recordId;

// Create the Request Object
GrantAccessRequest grant = new GrantAccessRequest ();

// Set the Request Object’s properties
grant.PrincipalAccess = principalAccess;
grant.Target = target;

// Execute the Request
GrantAccessResponse granted = (GrantAccessResponse )service.Execute(grant);
}

}

#endregion

}

}

Blank.aspx issue with Internet Explorer 6 in CRM 4.0


If you are getting a dialog box asking to download Blank.aspx in every pop-up window in the CRM then this article is for u.

Recently, a KB cumulative hotfix (KB953838)from windows update has apparently damaged the aspx association link within Internet Explorer 6.

http://support.microsoft.com/kb/953838

If you’re seeing this issue, you can resolve the problem in either the following ways:

1) Try to first save Blank.aspx as a file to your desktop.  Right-click on it, and choose to open with ‘Internet Explorer’.  Make sure to check on ‘always use this…’  Failing this try either of the following:
2) Uninstall the KB patch from the user’s Add/Remove Programs
3) Install Internet Explorer 7 overtop of IE 6
4) Remote into the CRM server, and open Blank.aspx in notepad.  (note: Blank.aspx can be found in: My Computer -> Program Files -> Microsoft Dynamic CRM -> CRMWeb -> _root -> Blank.aspx
On the header of Blank.aspx, add the word test and save Blank.aspx.  Restart IIS, and then clear the temporary internet files of the user with the issue.

Try any of above which suits u most.

Using Update Method of CrmService WebService


// Set up the CRM Service.

CrmAuthenticationToken token = new

CrmAuthenticationToken();

// You can use enums.cs from the SDK\Helpers folder to get

the enumeration for AD Authentication.

token.AuthenticationType = 0;

token.OrganizationName =”AdventureWorksCycle”;

CrmService service = new CrmService();

service.Url

=”http://<servername&gt;:<port>/mscrmservices/2007/crmservice.

asmx”;

service.CrmAuthenticationTokenValue = token;

service.Credentials =

System.Net.CredentialCache.DefaultCredentials;

// Create the contact object.

contact contact = new contact();

// Set the contact object properties to be updated.

contact.address1_line1 =”34 Market St.”;

// The contactid is a key that references the ID of the

contact to be updated.

contact.contactid = new Key();

// The contactid.Value is the GUID of the record to be

changed.

contact.contactid.Value = new Guid(“4D507FFE-ED25-447B-

80DE-00AE3EB18B84″);

// Update the contact.

service.Update(contact);