Archive for the ‘JScript’ Category


Calling EXE or Executing command from CRM 2011 Ribbon button

I had a requirement to execute command or call exe file from CRM Ribbon button which open SAP GUI shortcut based on some parameter which we need to pass as  parameter  from CRM Entity Form. We had written the following function which was called from CRM button.

function CallSAPGUI(l_SAPID)
 {
    var l_c_ConvertToCharCode = String.fromCharCode(34);
var obj_ActiveX = new ActiveXObject(‘WScript.Shell’);

l_s_CommendText = ‘start sapshcut.exe’ + ‘ -user=’ + l_c_ConvertToCharCode + l_SAPID + l_c_ConvertToCharCode + ‘ -client=017’ + ‘ -language=EN’ + ‘ -system=ABC’ + ‘ -gui=/M/vhdh08.ct056.tss.loc/S/3600/G/ct_01’ + ‘ -command=*/TTC/ZZ_PP_RAT_TA3/CLA/ZZ_PP_TARHD-NUM=1000-34;’ + ‘ –maxgui’;

 if (obj_ActiveX)
{
obj_ActiveX.Run(‘cmd.exe /c ‘ + l_c_ConvertToCharCode + l_s_CommendText + l_c_ConvertToCharCode);
}
}

We were using this code in CRM 2011 outlook client. Once I deployed this code , I thought this code will work but I got the below error.

Automation server can’t create object

I visited various blog and found that we need to do the following setting in IE. We need to do the below setting for both “Local Intranet ” and” Trusted Sites ” of Security Tab. Once i did the browser setting SAP GUI was working fine on button click.

IE_Settings

Hope it will help you !!

 

Advertisements

Silverlight application can get a reference to the Xrm.Page Object instance using either of following approaches.

1. Using HTML bridge feature of Silverlight

ScriptObject  xrm = (ScriptObject)HtmlPage.Window.GetProperty(“Xrm”);

ScriptObject  page= (ScriptObject)xrm.GetProperty(“Page”);

2. Using Dynamic Language Runtime

Using DLR you can utilize the dynamic language keywords which allow resolving method calls at runtime.

dynamic  xrm = (ScriptObject)HtmlPage.Window.GetProperty(“Xrm”);

 

Below is some important methods/property which is useful for Silverlight Application.

1. Getting the current Theme: This is useful if you are trying to style your Silverlight content in a similar way the user will see the web client. Valid Values are Default, Office12Blue, and Office14Silver.

var theme= xrm.Page.context.getCurrentTheme();

2.      Getting Org Name:

var orgName= xrm.Page.context.getOrgUniqueName();

3.      Getting the Server URL:

var serverUrl = xrm.Page.context.getServerUrl();

4.      Getting the User ID:

Knowing the user id that is working with the current page can be helpful when you need to do things like retrieve all the records that are owned by that person to present on the page.

 

var  userID = xrm.Page.context.getUserId();

5.      Getting the user’s Role:

var roles = xrm.Page.context.getUserRoles();

6.      Getting the entity logical Name:

String entityname =xrm.Page.data.entity.getEntityName();

7.      Getting the Entity Id:
Guid entityID = xrm.Page.data.entity.getId();

8.      Checking if Entity is Dirty:

By checking the dirty flag at the entity level you can quickly determine if there have been any changes to any of the fields. This doesn’t give you field level granularity you have to check each attribute if you need that.

bool isDirty = xrm.Page.data.entity.getIsDirty();

9.      Getting the Data as XML:

Using this feature you can get a string that represents the XML that would be sent to the server when the record is saved. The XML contains only the fields which have been modified.

String dataXml = xrm.Page.data.entity.getDataXml();

10.  Saving Data to the Server:

The save function allows you to simulate saving data to the CRM server just like if the user hit the save button in the ribbon.

Xrm.Page.data.entity.save()
or
Xrm.Page.data.entity.save(“saveandclose”)
or
Xrm.Page.data.entity.save(“saveandnew”)

11.  Working with the Entity Attributes

You can get to the attributes on an entity via the Attributes collection. The different attribute types can have special methods that are only for their specific type.The following shows which methods each type of attribute currently has.

All Attribute have these methods:

addOnChange,fireOnChange, getAttributeType,getFormat,getInitialValue, getIsDirty, getName, getParent,getRequiredLevel, getSubmitMode, getUserPrivelege, getValue, removeOnChange, setRequiredLevel, setSubmitMode, and setValue

Money,decimal,integer and double have these methods too:

getMax, getMin, and getPrecision

Boolean and Optioset attributes have these methods:

getInitalValue

Optionset attributes have these methods:

getOption, getOptions, getSelectedOption, and getText

 

12.  UI Methods:

The UI methods are high level methods located at Xrm.page.ui and are the starting point for working with the UI controls. This is also the starting point for looking for Controls and Tabs.

Refreshing the Ribbon:

This method is beyond helpful if you are doing any enable/display rules that depends on values on the form. After the value is changed on the form you can use this method to force the ribbon to re-evaluate the data in the form so the ribbon is updated.

refreshRibbon();

13.  Working with Form Controls:

The following methods are on all controls:

getControlType, getDisabled, getLabel, getName, getParent, setDisabled(all except web resources), setFocus, setLabel, and setVisible

The following methods are specific to Lookups;

addCustomeView, getDefaultView, and setDefaultView

The following methods are specific to Option Sets

adoption,clearOptions, and removeOption

The following methods are specific to Web Resources:

getData, getObject, setData, keep in mind the get/setData can only be used with Silverlight Web resources

The Following methods are specific to IFrames:

getSrc, setSrc, and getInitalUrl

The following methods are specific to Subgrids:

refresh


Below code shows how to get Security Roles of current User Using JScript which uses a RetrieveMultiple query …

function GetCurrentUserRoles()
{
var xml = “” +

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

“<soap:Envelope xmlns:soap=\”” +

http://schemas.xmlsoap.org/soap/envelope/&#8221; +

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

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

GenerateAuthenticationHeader() +

” <soap:Body>” +

” <RetrieveMultiple xmlns=\”” +

http://schemas.microsoft.com/crm/2007/WebServices\”>” +

” <query xmlns:q1=\”” +

http://schemas.microsoft.com/crm/2006/Query&#8221; +

“\” xsi:type=\”q1:QueryExpression\”>” +

” <q1:EntityName>role</q1:EntityName>” +

” <q1:ColumnSet xsi:type=\”q1:ColumnSet\”>” +

” <q1:Attributes>” +

” <q1:Attribute>name</q1:Attribute>” +

” </q1:Attributes>” +

” </q1:ColumnSet>” +

” <q1:Distinct>false</q1:Distinct>” +

” <q1:LinkEntities>” +

” <q1:LinkEntity>” +

” <q1:LinkFromAttributeName>roleid</q1:LinkFromAttributeName>” +

” <q1:LinkFromEntityName>role</q1:LinkFromEntityName>” +

” <q1:LinkToEntityName>systemuserroles</q1:LinkToEntityName>” +

” <q1:LinkToAttributeName>roleid</q1:LinkToAttributeName>” +

” <q1:JoinOperator>Inner</q1:JoinOperator>” +

” <q1:LinkEntities>” +

” <q1:LinkEntity>” +

” <q1:LinkFromAttributeName>systemuserid</q1:LinkFromAttributeName>” +

” <q1:LinkFromEntityName>systemuserroles</q1:LinkFromEntityName>” +

” <q1:LinkToEntityName>systemuser</q1:LinkToEntityName>” +

” <q1:LinkToAttributeName>systemuserid</q1:LinkToAttributeName>” +

” <q1:JoinOperator>Inner</q1:JoinOperator>” +

” <q1:LinkCriteria>” +

” <q1:FilterOperator>And</q1:FilterOperator>” +

” <q1:Conditions>” +

” <q1:Condition>” +

” <q1:AttributeName>systemuserid</q1:AttributeName>” +

” <q1:Operator>EqualUserId</q1:Operator>” +

” </q1:Condition>” +

” </q1:Conditions>” +

” </q1:LinkCriteria>” +

” </q1:LinkEntity>” +

” </q1:LinkEntities>” +

” </q1:LinkEntity>” +

” </q1:LinkEntities>” +

” </query>” +

” </RetrieveMultiple>” +

” </soap:Body>” +

“</soap:Envelope>” +

“”;

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

xmlHttpRequest.Open(“POST”, “/mscrmservices/2007/CrmService.asmx”, false);

xmlHttpRequest.setRequestHeader(“SOAPAction”,

http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple&#8221;);

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

xmlHttpRequest.setRequestHeader(“Content-Length”, xml.length);

xmlHttpRequest.send(xml);

var resultXml = xmlHttpRequest.responseXML;

return(resultXml);

}

For Complete Source Code for hiding tab/field based on Security Role Please Visit.

Jimmy Wang’s version.


I had client requirement that on the selection of City (lookup), Region and Sub Region should be populated automatically which is read only field. To achieve this we mapped the city with region (lookup) and sub region (lookup) on the city entity. After writing below code I was getting following error.

There was an error with this field’s customized event.

Field:new_cityid

Event:onchange

Error:’ new_subregionid.value ‘ is null or not an object

I solved the issue with help of this link and answer posted by Adi Katz .

“The keyValues are only available when you use the lookup dialog. The form assistant does not contain the columns that are retrieved by the lookup and this is why the items array is empty.”

For details please visit below link.

http://social.microsoft.com/Forums/en-US/crmdevelopment/thread/ad9b5b22-da6b-4f20-9fd4-b7e46d9a7556

After this solution I added Sub Region field to lookup dialog (lookup view) and this solve my issue.

Put below code on OnChange of City Lookup field.

/*****Auto Populate SubRegion on Selection of City field******************/

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

{
crmForm.all.new_subregionid.DataValue = null;
}

else

{

var lookup_guid;

var lookup_name;

var lookup_type;

var lookup_typename;

var lookupItem = new Array;

lookupItem = crmForm.all.new_cityid.DataValue;

lookup_guid=lookupItem[0].id;

lookup_name=lookupItem[0].name;

lookup_type=lookupItem[0].type;

lookup_typename=lookupItem[0].typename;

var subRegionName;

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

{
var lookupValues = crmForm.all.new_cityid.items[0].keyValues;
subRegionName = lookupValues.new_subregionid.value? lookupValues.new_subregionid.value : null;

}
else
{
subRegionName = null;

}

var subregionidvalue = GetAttributeValueFromID(lookup_typename, lookup_guid, ‘new_subregionid’);

if(subregionidvalue != null)

{
var subregionlookupData = new Array();

//Create an Object add to the array.

var subregionlookupItem = new Object();

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

subregionlookupItem.id = subregionidvalue;

regionlookupItem.typename = ‘new_subregion’;

regionlookupItem.name = subRegionName ;

// Add the object to the array.

subregionlookupData[0] = subregionlookupItem;

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

crmForm.all.new_subregionid.DataValue = subregionlookupData;

crmForm.all.new_subregionid.ForceSubmit = true;

}

function GetAttributeValueFromID(sEntityName, sGUID, sAttributeName)

{

var sXml = “”;

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

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

// retrieve the given attribute name in any XML namespace

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

if (result == null)

{

return “”;

}

else

{

return result.text;

}

}

}


Let me explain the scenario..

We have a Model lookup and a variant Lookup on Lead form. Every variant is associated with a particular model. i.e One model have multiple Variant.

Eg.
Model          Varient
Alto             Alto LX
Alto             Alto Xcite
Alto             Alto LXI
SX4               SX4 VXI
SX4               SX4 ZXI Leather
SX4               SX4 ZXI
—————————-

Now Requirement is that when user select a model from Model lookup then only variant corresponding to selected model should be displayed to user when user click on variant lookup and disable the search in Variant lookup.

Write below code on Model OnChange event.

if(crmForm.all.new_modelid.DataValue != null )
{
var modelLookup=crmForm.all.new_modelid.DataValue;
var modelID=modelLookup[0].id;
var modelName=modelLookup[0].name;
var field=crmForm.all.new_variantid;

// Pass fetch xml through search value parameter
field.lookupbrowse = 1;
field.AddParam(“search”,”<fetch mapping=’logical’ distinct=’false’>”
+”<entity name=’new_varientmaster’>”
+”<attribute name=’new_varientmasterid’/>”
+”<attribute name=’new_name’/><attribute name=’createdon’/>”
+”<order attribute=’new_name’ descending=’false’/><filter type=’and’>”
+”<condition attribute=’new_modelnameid’ operator=’eq’ uiname='”+ modelName
+”‘ uitype=’new_modelmaster’ ”
+”value='”+ modelID +”‘ />”
+”</filter></entity></fetch>”

);
}

Note: Put below code if not already exist

The following code needs to be inserted anywhere in the <CRM site folder>\_controls\lookup\lookupsingle.aspx file if not already exist (if you have already code for filtering lookup)..

<script runat=”server”>
protected override void OnLoad( EventArgs e )
{
base.OnLoad(e);
crmGrid.PreRender += new EventHandler( crmgrid_PreRender );
}

void crmgrid_PreRender( object sender , EventArgs e )
{
// As we don’t want to break any other lookups, ensure that we use workaround only if
// search parameter set to fetch xml.
if (crmGrid.Parameters[“search”] != null && crmGrid.Parameters[“search”].StartsWith(“<fetch”))
{
crmGrid.Parameters.Add(“fetchxml”, crmGrid.Parameters[“search”]);

// searchvalue needs to be removed as it’s typically set to a wildcard ‘*’
crmGrid.Parameters.Remove(“searchvalue”);

// and then select it.
this._showNewButton = false;
}
}

</script>

For details  about lookupsingle.aspx code visit below link.

http://crm.georged.id.au/post/2008/02/16/Filtering-lookup-data-in-CRM-4.aspx

For Reference: Model is custom entity (new_modelmaster) which contains name attribute (i.e Model Name) and Variant is custom entity (new_variantmaster) which contain name attribute( variant Name ) and Model lookup(new_modelnameid) to map model with variant.

For building FetchXml Query find below link.

https://arvindcsit.wordpress.com/2010/09/08/using-the-advanced-find-for-fetchxml-builder/

Enjoy J


You can just open the Advanced find page and build the query as you like. Then run the query to see if it returns the data as you wish it should. If you are satisfied with the results and you want to know what query was sent into the CRM Framework, then press F11 to get the address bar and enter this script and press enter.

javascript:alert(resultRender.FetchXml.value);

If you get a warning about leaving the page, just press ‘ok’ and then the query which is sent to the framework opens up in a popup. Unfortunately you cannot select the text to copy and paste. But with Windows XP and Windows Server 2003 you can copy all text on the popup by clicking somewhere on the popup (not on the button “OK” ofcourse) and pressing ctrl+c. Now in notepad you can paste the text of the FetchXML.

Good luck!

You can also try this instead of the alert:

javascript:prompt(“my query:”, resultRender.FetchXml.value);


Create record using JScript

This sample shows how to use the CrmService.Create method using the same example provided in the Server Programming Guide: CrmService.Create method.

To test this sample:

  1. Paste the following code into any Event Detail Properties dialog box.
  2. Save the form and then click Create Form on the Preview menu.

When the event occurs, the code will run. This code creates and opens a new contact record.

// Prepare values for the new contact.

var firstname = “Jesper”;

var lastname = “Aaberg”;

var donotbulkemail = “true”;

var address1_stateorprovince = “MT”;

var address1_postalcode = “99999”;

var address1_line1 = “23 Market St.”;

var address1_city = “Sammamish”;

var authenticationHeader = GenerateAuthenticationHeader();

// 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>”+

“<Create xmlns=’http://schemas.microsoft.com/crm/2007/WebServices‘>”+

“<entity xsi:type=’contact’>”+

“<address1_city>”+address1_city+”</address1_city>”+

“<address1_line1>”+address1_line1+”</address1_line1>”+

“<address1_postalcode>”+address1_postalcode+”</address1_postalcode>”+

“<address1_stateorprovince>”+address1_stateorprovince+”</address1_stateorprovince>”+

“<donotbulkemail>”+donotbulkemail+”</donotbulkemail>”+

“<firstname>”+firstname+”</firstname>”+

“<lastname>”+lastname+”</lastname>”+

“</entity>”+

“</Create>”+

“</soap:Body>”+

“</soap:Envelope>”;

// Prepare the xmlHttpObject and send the request.

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

xHReq.Open(“POST”, “/mscrmservices/2007/CrmService.asmx”, false);

xHReq.setRequestHeader(“SOAPAction”,”http://schemas.microsoft.com/crm/2007/WebServices/Create”);

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

xHReq.setRequestHeader(“Content-Length”, xml.length);

xHReq.send(xml);

// Capture the result

var resultXml = xHReq.responseXML;

// Check for errors.

var errorCount = resultXml.selectNodes(‘//error’).length;

if (errorCount != 0)

{

var msg = resultXml.selectSingleNode(‘//description’).nodeTypedValue;

alert(msg);

}

// Open new contact record if no errors.

else

{

var contactid = resultXml.selectSingleNode(“//CreateResult”);

window.open(“/sfa/conts/edit.aspx?id={“+contactid.nodeTypedValue+”}”);

}

A successful response includes XML with a CreateResponse element that returns the ID for the record created. The following is an example of a successful response:

<?xml version=”1.0″ encoding=”utf-8″?>
<soap:Envelope xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns:xsd=”http://www.w3.org/2001/XMLSchema”&gt;
<soap:Body>
<CreateResponse xmlns=”http://schemas.microsoft.com/crm/2007/WebServices”&gt;
<CreateResult>368c8b1b-851c-dd11-ad3a-0003ff9ee217</CreateResult>
</CreateResponse>
</soap:Body>
</soap:Envelope>