Advertisements

Archive

Archive for the ‘JScript’ Category

Get the view name of main grid using JScript

January 29, 2014 Leave a comment

We got a requirement to Enable\disable ribbon button based on selected view.

View name

View name

We used JScript to disable the button by getting the selected view name.

Below is the script to get the selected view name of  Main Grid

var viewName = “”;

if (crmGrid && crmGrid.control) {

viewName = crmGrid.control.get_viewTitle();

}

🙂

Advertisements
Categories: CRM, JScript Tags: , ,

Xrm.Utility is undefined error – CRM 2011

Other day when I deployed my solution on a new CRM server, I was getting “Xrm.Utility is undefined” script error.

I refered“Xrm.Utility” JScriptin my code to open forms which was causing script issue.

Reason & Fix

  • The CRM server is not having UR 8
  • Since Xrm.Utility object was added in CRM 2011 Update Rollup 8, installing UR 8 on server solved the issue

🙂

event.returnValue is not working after UR 12 – Fix

July 15, 2013 2 comments

We use event.returnValue=false statement, to stop the event execution. (i.e., I can stop my crm form’s save action, if I write event.returnValue=false statement on my onsave() event).

After I upgraded to UR12, I was getting script error, if I use the event.returnValue statement.

Reason

  • Update Rollup 12 and December 2012 Service Update support additional browsers by generating HTML that supports W3C standards.
  • This requires removing dependencies on HTML components (HTC) that are specific to Internet Explorer.
  • Hence event.returnValue statement has been deprecated

Fix

  • Use context.getEventArgs().preventDefault() function to cancel the event execution

How do I use this

  • First to get “context”, enable the OnSave event handler to pass the execution context as the first parameter to the OnSave event handler.
  • Open customization form -> Form Properties and in “Handler Properties” window, select the “Pass execution ….” checkbox
  • Pass execution context

    Pass execution context

  • Next in your Jscript , read the context as first parameter

function onsave(context) {

// Prevent the event execution

context.getEventArgs().preventDefault();

}

Get more details on latest CRM JScript changes from this link

🙂

Retrieve records with Fetchxml using Jscript – CRM 2011

June 20, 2013 1 comment

Retrieve the records using FetchXML is a convenient way as we can form the FetchXML easily using the ‘Advanced Find’ .

Download Fetch XML

Download Fetch XML

Once you have the FetchXML ready, below is the JScript to execute and read the result set.

  • In this sample, I am fetching records from custom entity “Bikes” which has relationship with ‘Contact’ entity. (i.e., Fetch all the bikes of a Contact whose full name contains ‘Raj’)
  • Note – I am using “xrmservicetoolkit” helper Jscript which is available in CodePlex. You just need to download the Jscript and refer to your CRM form.

function getBikesByContactName() {

var fetchXml =

“<fetch mapping=’logical’>” +

“<entity name=’raj_bike’>” +

“<attribute name=’raj_name’ />” +

“<attribute name=’createdon’ />” +

“<link-entity name=’contact’ from=’contactid’ to=’raj_customerid’ alias=’ad‘>” +

“<attribute name=’fullname’ />” +

“<filter type=’and’>” +

“<condition attribute=’fullname’ operator=’like’ value=’%raj%’ />” +

“</filter>” +

“</link-entity>” +

“</entity>” +

“</fetch>”;

// Execute the fetch

var bikes = XrmServiceToolkit.Soap.Fetch(fetchXml);

// Get the results by loop through ‘bikes’

for (var indxBikes = 0; indxBikes < bikes.length; indxBikes++) {

alert(“Bike Name – “+bikes[indxBikes].attributes.raj_name.value);

alert(“Created On – “+bikes[indxBikes].attributes.createdon.value);

// Get the related entity (i.e., Contact) attributes using LinkEntity alias)

alert(“Related entity attribute (Contact Name) – ” + bikes[indxBikes].attributes.ad.fullname.value);

}

}

🙂

Filtering Lookup view based on custom logic CRM 2011

June 17, 2013 1 comment

In one of my requirement, I have to filter my lookup view results based on another lookup field value.

I have 2 Lookup fields on my form

  • Product
  • Product Category

When I click on “Product” lookup, I have to show only Products with category as “Product Category” field value.

Filter Lookup View

Filter Lookup View

We can achieve this requirement using Jscript by following below steps

  • Create a new view with our filter
  • Use the SDK method addCustomView, to add newly created view for the lookup dialog box
  • Set this view as default view
  • Disable the view selector to avoid user to select other views from Lookup dialog
  • Put above logic in a function register it on “onchange” event of “Product Category” field

Below is the Jscript function

function createAndSetLookupView() {

// Some GUID but only needs to be unique among the other available views for the lookup

var viewId = “{CB6F8184-D7C2-4664-9FAB-18FD9DCDB22A}”;

// Name of the view

var viewDisplayName = “My filtered view”;

// Prepare the xml with columns to display and filter

// Tip : Use Advanced Find to prepare th FetchXML

var fetchXml = “<fetch version=’1.0′ ” +

“output-format=’xml-platform’ ” +

“mapping=’logical’>” +

“<entity name=’new_product’>” +

“<attribute name=’new_productid’ />” +

“<attribute name=’new_name’ />” +

“<attribute name=’new_categoryid’ />” +

“<attribute name=’createdon’ />” +

“<order attribute=’new_name’ ” +

“descending=’false’ />” +

“<filter type=’and’>” +

“<condition attribute=’new_categoryid’ ” +

“operator=’eq’ ” +

“uiname='” + {categoryName} + “‘ ” +

“uitype=’new_category’ ” +

“value='” + {categoryGUID} + “‘ />” +

“</filter>” +

“</entity>” +

“</fetch>”;

var layoutXml = “<grid name=’resultset’ ” +

“object=’1′ ” +

“jump=’new_name’ ” +

“select=’1′ ” +

“icon=’1′ ” +

“preview=’2′>” +

“<row name=’result’ ” +

“id=’new_productid’>” +

“<cell name=’new_name’ ” +

“width=’150′ />” +

“<cell name=’new_categoryid’ ” +

“width=’150′ />” +

“<cell name=’createdon’ ” +

“width=’100′ />” +

“</row>” +

“</grid>”;

try {

// Lookup field which you want to add new view

var lookupControl = Xrm.Page.ui.controls.get(“new_productid”);

// Add the created view to Product lookup and set this view as default

lookupControl.addCustomView(viewId, “new_product”, viewDisplayName, fetchXml, layoutXml, true);

//Disable “View Selection” dropdown of “Product” lookup dialog

document.getElementById(“new_productid”).setAttribute(“disableViewPicker”, “1”);

}

catch (e) {

alert(“Error in createAndSetLookupView() – ” + e.description);

}

}

🙂

Associate Campaign with related items using Jscript – CRM 2011

We can associate 2 entity records having N:N relationship using “AssociateRequest” SDK message. (How to associate)

But you get below error when you try to associate a Campaign record with Campaign related items such as Marketing List, Product, or Salesliterature using “AssociateRequest” SDK message.

Associate is not supported for CampaignItem Platform

To associate a Campaign, we have an exclusive SDK message “AddItemCampaignRequest”.

Below is the Jscript to associate Campaign with related records

function associateCampaignItem (campaignId, associateRecordId, associateRecordSchemaName) {

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=\”b:AddItemCampaignRequest\” 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>CampaignId</c:key>”;

requestMain += ” <c:value i:type=\”d:guid\” xmlns:d=\”http://schemas.microsoft.com/2003/10/Serialization/\”>” + campaignId + “</c:value>”;

requestMain += ” </a:KeyValuePairOfstringanyType>”;

requestMain += ” <a:KeyValuePairOfstringanyType>”;

requestMain += ” <c:key>EntityId</c:key>”;

requestMain += ” <c:value i:type=\”d:guid\” xmlns:d=\”http://schemas.microsoft.com/2003/10/Serialization/\”>” + associateRecordId + “</c:value>”;

requestMain += ” </a:KeyValuePairOfstringanyType>”;

requestMain += ” <a:KeyValuePairOfstringanyType>”;

requestMain += ” <c:key>EntityName</c:key>”;

requestMain += ” <c:value i:type=\”d:string\” xmlns:d=\”http://www.w3.org/2001/XMLSchema\”>” + associateRecordSchemaName + “</c:value>”;

requestMain += ” </a:KeyValuePairOfstringanyType>”;

requestMain += ” </a:Parameters>”;

requestMain += ” <a:RequestId i:nil=\”true\” />”;

requestMain += ” <a:RequestName>AddItemCampaign</a:RequestName>”;

requestMain += ” </request>”;

requestMain += ” </Execute>”;

requestMain += ” </s:Body>”;

requestMain += “</s:Envelope>”;

var req = new XMLHttpRequest();

 

var OrgServicePath = “/XRMServices/2011/Organization.svc/web”;

var serverUrl = Xrm.Page.context.getServerUrl() + OrgServicePath;

req.open(“POST”, serverUrl, true)

// 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&#8221;);

var successCallback = null;

var errorCallback = null;

req.onreadystatechange = function () { AddItemCampaignResponse(req); };

req.send(requestMain);

}

function AddItemCampaignResponse(req) {

if (req.readyState == 4) {

if (req.status == 200) {

alert(“Success”);

}

else {

alert(“Error – ” + req.responseXML);

}

}

}

How do I use

  • Lets try to associate ‘Campaign’ with ‘Marketing List’ item using above script
  • Pass the required arguments as specified below

    var campaignId = “”; //Campaign GUID

var marketinglistId = “”; //Marketinglist GUID

var schemaName = “”; // Marketinglist entity Schema Name

associateCampaignItem(campaignId, marketinglistId, schemaName);

🙂

Consuming WCF service from Jscript using JQuery

I recently got a requirement to host a WCF service in Azure and consume it client side using Jscript.

In this article, I am providing details on how to consume WCF service from Jscript with the help of JQuery.

In below example, service is a simple “Products.svc” contain 1 method “GetProducts()” and returns List<Product> (“Product” is custom class)

WCF Service

  • Service Contract (IProductService.cs)

[ServiceContract(Namespace = “http://ABCproducts&#8221;,

Name = “IProductService”,

SessionMode = SessionMode.NotAllowed,

ProtectionLevel = ProtectionLevel.None)]

public interface IProductService{

[OperationContract]

[WebInvoke(

Method = “POST”,

BodyStyle = WebMessageBodyStyle.Wrapped,

RequestFormat = WebMessageFormat.Json,

ResponseFormat = WebMessageFormat.Json)]

List<Product> GetProducts();

}

[DataContract]

public class Product{

string id = string.Empty;

string name = string.Empty;

[DataMember]

public string ProductId{

get { return id; }

set { id = value; }

}

[DataMember]

public string ProductName{

get { return name; }

set { name = value; }

}

}

  • Service (ProductService.svc)

public List<Product> GetProducts(){

List<Product> products = new List<Product>();

Product P1 = new Product();

P1.Id = “1”;

P1.Name = “Mango”;

Product P2 = new Product();

P2.Id = “2”;

P2.Name = “Apple”;

products.Add(P1);

products.Add(P2);

return products;

}

  • Service Binding (Web.config)
    • Very important note is, the service endpoint has to be “webHttpBinding”; otherwise we get “Cannot process the message because the content type application\json was not the expected…” error.
    • webHttpBinding is the REST-style binding, where you can hit a service URL and get back a result in either XML or JSON from the service.
    webHttp Binding

    webHttp Binding

    • Add a “EndPointBehavior” with “webHttp” stack element.
webHttp Behavior

webHttp Behavior

    • Below is the service configuration mentioned in my web.config file

<services>

<service name=”ProductService”>

<endpoint address=”” behaviorConfiguration=”endPtBehaviorJSon

binding=”webHttpBinding” bindingConfiguration=”bindingWebHttp”

name=”wsBindingBFS” contract=”IProductService” />

</service>

</services>

<behaviors>

<endpointBehaviors>

<behavior name=”endPtBehaviorJSon“>

<webHttp />

</behavior>

</endpointBehaviors>

</behaviors>

Jscript

  • Since we are using JQuery, refer “JQuery.1.4.1.min.js” file
  • In this example we are getting output in json format. (Observe “dataType property mentioned as “json”)
  • getProducts” is the function which communicate to service and gets “Product” collection as response in JSon format.
  • The response comes in special format (i.e., WCF Service method name+Result)  (i.e, GetProductsResult)

function getProducts() {

var serviceURL = “http://{Server Name}/ProductService.svc/GetProducts“;

$.ajax({

type: “POST”,

contentType: “application/json; charset=utf-8”,

url: serviceURL,

processData: false,

dataType: “json”,

//If the call succeeds

success:

function (response) {

retrieveProducts(response)

},

//If the call fails

error: function (XMLHttpRequest, textStatus, errorThrown) {

alert(“Error while retrieval – ” + XMLHttpRequest.responseText);

}

});

}

function retrieveProducts(response) {

// Result collection come as Response.{MethodName}+”Result”

if (response && response.GetProductsResult) {

$.each(response.GetProductsResult, function (i) {

alert(

“Product ID: ” + this.ProductId +

” Product Name: ” + this.ProductName);

});

}

}