Category Archives: MS CRM 4.0

Get Max value using Javascript

 If you want to fetch Max value from CRM entity record using Javascript, you can use below code, remember to change entity and field name accordingly

var authenticationHeader = GenerateAuthenticationHeader();

// Prepare the SOAP message.

var xml = “<?xml version=’1.0′ encoding=’utf-8′?>”+

“<soap:Envelope xmlns:soap=’'”+

” xmlns:xsi=’'”+

” xmlns:xsd=’’>”+



“<RetrieveMultiple xmlns=’’>”+

“<query xmlns:q1=’'”+

” xsi:type=’q1:QueryExpression’>”+

“<q1:EntityName>EntityName</q1:EntityName>”+ //change entity name

“<q1:ColumnSet xsi:type=’q1:ColumnSet’>”+


“<q1:Attribute>FieldName</q1:Attribute>”+ //change field name



“<q1:Orders>” +

“<q1:Order>” +

“<q1:AttributeName>FieldName</q1:AttributeName>” + //change field name

“<q1:OrderType>Descending</q1:OrderType>” +

“</q1:Order>” +

“</q1:Orders>” +





// Prepare the xmlHttpObject and send the request.

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

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


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

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


// 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;





var results = resultXml.getElementsByTagName(‘BusinessEntity’);

var msg = “”;

if (results.length == 0)









var MaxValue = results[0].selectSingleNode(‘./q1:FieldName’).nodeTypedValue;   //change name of the field to get Max value





Leave a comment

Filed under JS Script, MS CRM & Javascript

Using CompoundUpdateRequest in Dynamics CRM 4.0

Sometime when we are integrating ms crm with another application we need to send CRM data to another application and also need to keep track if data is already sent or not. For example if you are sending sales order and sales order line items and you need to update sales order and line item after sending, you can use  compoundupdaterequest message to update sales order and order line items in one go.


private BusinessEntityCollection ReadAllOrderLineItems(Guid _ID, ICrmService _iService)


            RetrieveMultipleResponse retrieved = null;



                ConditionExpression _Condition = new ConditionExpression();

                _Condition.Operator = ConditionOperator.Equal;

                _Condition.AttributeName = “salesorderid”;

                _Condition.Values = new object[] { _ID };

                 FilterExpression _Filter = new FilterExpression();

                _Filter.FilterOperator = LogicalOperator.And;

                _Filter.Conditions.AddRange(new ConditionExpression[] { _Condition });

                 QueryExpression query = new QueryExpression();

                query.ColumnSet = new AllColumns();

                query.Criteria = _Filter;

                query.EntityName = “salesorderdetail”;

                RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();

                retrieve.Query = query;

                retrieve.ReturnDynamicEntities = true;

                retrieved = (RetrieveMultipleResponse)_iService.Execute(retrieve);


            catch (SoapException Ex)


                throw Ex;


            catch (Exception Excep)


                throw Excep;


            return retrieved.BusinessEntityCollection;


//Get all orderline items for particular salesorderid
BusinessEntityCollection _OrderLineItems = ReadAllOrderLineItems(_SalesorderID,_iCrmService); //I have written this function to fetch all order line items based on salesorder id.
 //Create Dynamic entity array to store salesorderdetails
 DynamicEntity[] _SalesorderDetailArr=new DynamicEntity[_OrderLineItems.BusinessEntities.Count];
 for(int i=0; i<_OrderLineItems.BusinessEntities.Count; i++)
               //get salesorder key
                DynamicEntity _ExistingSalesorderItem = (DynamicEntity)_OrderLineItems.BusinessEntities[i];
 // create properties for sales order detail, in my example I have created a bit field in sales order and sales order detail

                DynamicEntity _Salesorderitem=new DynamicEntity();
                _Salesorderitem.Name = “salesorderdetail”;
                 //Add property to set created flag
                 CrmBooleanProperty _Created = new CrmBooleanProperty();
                _Created.Name = “new_created”;
                _Created.Value = new CrmBoolean();
                _Created.Value.Value = true;
                 //set key property
                KeyProperty _SalesorderDetailKey = new KeyProperty();
                _SalesorderDetailKey.Name = “salesorderdetailid”;
                _SalesorderDetailKey.Value = new Key();
                _SalesorderDetailKey.Value.Value = ((Key)_ExistingSalesorderItem.Properties[“salesorderdetailid”]).Value;
                _SalesorderDetailArr[i] = _Salesorderitem;

            DynamicEntity _Salesorder = new DynamicEntity();
            _Salesorder.Name = “salesorder”;
            _Salesorder.Properties.Add(new KeyProperty(“salesorderid”, new Key(_ID)));
            CrmBooleanProperty _Created = new CrmBooleanProperty();
            _Created.Name = “new_created”;
            _Created.Value = new CrmBoolean();
            _Created.Value.Value = true;
            TargetCompoundDynamic _TargetUpdate = new TargetCompoundDynamic();
            _TargetUpdate.ChildEntities = _SalesorderDetailArr;
            _TargetUpdate.Entity = _Salesorder;
            CompoundUpdateRequest _Request = new CompoundUpdateRequest();
            _Request.Target = _TargetUpdate;
            CompoundUpdateResponse _Response = (CompoundUpdateResponse)_iService.Execute(_Request);


Filed under MS CRM 4.0, Workflow & Plugin Development

Customization Import from CRM online to Onpremise

Today I tried to import my customization.xml from CRM online to onpremise and I got error

 “Either the file could not be uploaded, or this is not a valid Customization file.”

I was surprised. I tried to import the same file to my CRM online environment again and it imported successfully. So my first thought was to enable trace and check for log files, I got one log file. I check that log file using CRM 4.0 Trace Log Viewer and I found an exception message

“The element ‘savedquery’ has invalid child element ‘visualizations’. List of possible elements expected:’Description,columnsetxml’.”

So “Visualization” was the main culprit here. In CRM online visualization represents to Charts, so a visualization tags is added under savedquery node. So I modified my customization xml file in visual studio and deleted all visualization tags and then imported my customization file and it worked like a charm.


Leave a comment

Filed under MS CRM 4.0

Close Activity based on Due Date using workflow


I got one requirement from my client where we need to complete Email activity based on it’s Due date. so I have to check if current date is equal to email’s due date then close email activity. So I created a workflow to implement this. Here are the steps to create workflow

1.       Create new workflow select Entity as Email, Give some name to workflow like “Close Email”, Select new Blank workflow.

2.       Select Run when record is created.

3.       Select “Wait Condition”


Timeout until Email:Due Date

5.       Select Row under and add new step “Change record status” and set email status as completed.

6.       It should look like as below.



7.       Publish your workflow and create Email record and set due date. workflow will close email activity based on it’s due date.


Cheer !!!

Leave a comment

Filed under MS CRM 4.0, Workflow & Plugin Development

Create Opportunity Relationship record

Sometime we need to create “Opportunity Relationship” record through code. We can use below code to create Opportunity relationship record. Basically we need to set three values while creating opportunity relationship record customerid, opportunityid and opportunityroleid.

//I have used Dynamic entity to create opportunity relationship record

DynamicEntity  _OpportunityRelationship = new DynamicEntity();

//Set entity name as “customeropportunityrole”         

 _OpportunityRelationship.Name = “customeropportunityrole”;

//Create property to set customer 

CustomerProperty _OpportunityCustomer=new CustomerProperty();

  _ OpportunityCustomer.Name=”customerid”;

 _ OpportunityCustomer.Value=new Customer();

 _ OpportunityCustomer.Value.type = “account”; //Set customer type (I am using account here)

 _ OpportunityCustomer.Value.Value=CustomerGUID;  //replace CustomerGUID with customer GUID


//set Opportunity ID 

LookupProperty _OpportunityID=new LookupProperty();

 _ OpportunityID.Name=”opportunityid”;

 _ OpportunityID.Value=new Lookup();

 _ OpportunityID.Value.Value=OpportunityID; //replace OpportunityID with opportunity GUID


 //Set Opportunity Role

//you can create Relationship Roles from Setting->Business Management->Relationship Roles        

 LookupProperty _OpportunityRole = new LookupProperty();

 _OpportunityRole.Name = “opportunityroleid”;

 _OpportunityRole.Value = new Lookup();

   _OpportunityRole.Value.Value =GUIDofRelationshipRole; //Replace GUIDofRelationshipRole with Relationship role Guid.


  TargetCreateDynamic targetCreate = new TargetCreateDynamic();

  targetCreate.Entity = _OpportunityRelationship;

// Create the request object.

 CreateRequest create = new CreateRequest();

  // Set the properties of the request object.

  create.Target = targetCreate;

 // Execute the request.

 CreateResponse created = (CreateResponse)_Service.Execute(create);

 Hope it will help somebody.

Cheer 🙂

Leave a comment

Filed under MS CRM 4.0, Workflow & Plugin Development

Microsoft Dynamics CRM MVP

Just want to share with you all that I won Dynamics CRM MVP award. It is great honor to me and I would like to thank Microsoft and Dynamics CRM community for this recognition. Special thanks to Jim to submit my nomination for this great honor.

I would like to thank all my friends,my family members,my colleagues for their cooperation and help to achieve this award.


Filed under MS CRM 4.0

Run exe from MS CRM 4.0

If you are looking to run .exe from MS CRM 4.0, then you can do this easily. You can create a ISV button on MS CRM form and create on global function on formonload can call it in ISV button JS.. you can write below code to run .exe

var _Object=new ActiveXObject( “WScript.Shell” ) ;
_Object.Run(“C:\\WINDOWS\\system32\\calc.exe” );

 you can also pass parameters with Run command.

Enjoy !!!


Filed under JS Script, MS CRM 4.0

Easy way to avoid Infinite loop in Update plugin

I have seen many developers facing issue of infinite loop while using update method inside update plugin. I know it could be requirement specific, to use update method inside update plugin. But sometime we can void infinite issue, there is no need of calling update method. You could play with inputparmeter propertybag. For example sometime we have requirement to calculate values based on the input values scenarios like this we don’t need to use update method. So the question is how to update record without using update method in update plugin. For scenarios like these we can register our plugin on pre state and can catch our inputs from inputpropertybag and after calculating our values we can add our new property of resultant value in inputpropertybag, so no need of using update method to save value in database.

We need to follow below steps

  1. Register preupdate plugin.
  2. Read required input values from inputparameter propertybag.
  3. Calculate your resultant value.
  4. Create new property of your resultant value.
  5. Add new property to input propertybag.

Enjoy !!!

Leave a comment

Filed under MS CRM 4.0, Workflow & Plugin Development

Close Activity Event in MS CRM

sometime we need to perform some action when activity is closed in MS CRM.In that case you have to capture close activity event, you can do this using event.Mode property in onsave event. you just have to write below code.

if(event.Mode==5) //Close activity event


//you code to implement your logic


Enjoy !!!

Leave a comment

Filed under JS Script, MS CRM & Javascript, MS CRM 4.0

Attach onclick event with MS CRM CRM checkbox

As you know that we can set control formatting of bit field to use it as checkbox. But only changing formatting does not make it to behave like a checkbox because of onchange event. Let take an example for this, like we have one field “Calculate Value” and we want to calculate some value on the selection of this bit field. We can set control formatting for the bit field to display like a checkbox.

 So if we will write some code onchange event of this bit field


You will not get this alert until you will move focus from this field. so make it to behave like real checkbox you have to attach onclick event with this field. You can do this using below code on form onload





after that you can simple check DataValue for bit ,if it is true or false to work accordingly


1 Comment

Filed under JS Script, MS CRM 4.0