Monday, June 29, 2015

How to convert textbox to hyperlink in MS CRM

function ConvertToLink(fieldName,urlFieldName) {
    var itemText = Xrm.Page.getAttribute(fieldName).getValue();
    if (itemText != null && itemText != '' && itemText != 'null') {
        var url = Xrm.Page.getAttribute(urlFieldName).getValue();
        var btn = "<a href='javascript: void(0);' onclick=\"window.open(\'" + url + "\', \'windowname1\');  return false;\" style='color:blue;text-decoration:underline !important'>" + itemText + "</a>";
        var ctrl = Xrm.Page.ui.controls.get(fieldName)._control;
        // Add the new button
        ctrl.get_element().innerHTML += btn;
        // Hide the textbox
        ctrl.get_element().firstChild.style.display = 'none';
    }
}

Early Binding and Late Binding In MS CRM 2015

Late Binding

In Microsoft Dynamics CRM 2015 and Microsoft Dynamics CRM Online 2015 Update, you can use the Entity class when you work with entities. 
When initialized, the Entity class contains the logical name of an entity and a property-bag array of the entity’s attributes. 
This lets you use late binding so that you can work with types such as custom entities and custom attributes that weren’t available when your application was compiled. 
The key difference between early and late binding involves type conversion. While early binding provides compile-time checking of all types so that no implicit casts occur, late binding checks types only when the object is created or an action is performed on the type. 
The Entity class requires types to be explicitly specified to prevent implicit casts.

//Get the Value from optionset.

int val = ((OptionSetValue)account.Attributes["schemaname"].Value;

// Get the Text from OptionSet

String optiontext=account.FormattedValue["schemaname"].ToString();

// Set Value to the optionset

account.Attributes["schemaname"] = new OptionSetValue(1000);

// Get the lookup value

Guid ID = (EntityReference)account.Attributes["schemaname"].Id;

// Set lookup value

account.Attributes["schemaname"] = new EntityReference("contact",Guid);


Early Binding

The examples shown previously used late binding. When using late binding, accessing and using the Organization Service is difficult and you need to explicitly type both the entity and attribute’s names.
This makes the code cumbersome to write, and sometimes prone to errors.
Instead of using late binding, you can use early binding which provides IntelliSense support and better code development and use of .NET technologies such as the .NET Framework Language-Integrated Query (LinQ). 
To use early binding, you must generate the entity classes by using the code
generation tool called CrmSvcUtil.exe, a console application that you can find in the SDK\bin folder of the CRM 2013 SDK.
Here is an example of calling this tool:
Click here to view code image
CrmSvcUtil.exe /url:http://columbuscrm/demo1/XRMServices/2011...
/out:GeneratedCode.cs /username:bill /password:p@ssword!


Saturday, June 27, 2015

When to use Abstract class and what is the benefit of using Abstract class in real time application development.

It is a very common interview question when to use Abstract class and what is the benefit of using Abstract class in real time application development. The common properties of Abstract class are it cannot be initiated, functions and implementation can be partially implemented.

Consider an application that calculates salary of full time and contract based employees. There are few common properties of both employees, e.g., both employees have name, address, ID, but different way of calculating salaries. So we can declare one master class named as BaseEmployee and place common properties and Virtual Salary Calculator function with no implementation. Two child classes, FullTimeEmployee and ContractEmployee can inherit from BaseEmployee class and override Salary Calculator virtual function and our problem can be solved, then why Abstract Class should be used?

The problem with this inheritance approach is more like logical and business issue, in inheritance we can simply create BaseEmployee object and nothing can stop us which is wrong, usually any normal company does not have any BaseEmployee type employee, so if we want to stop user from accidentally creating a BaseEmployee class object we should declare this class and Salary Calculator as Abstract so that it can only be inherited but not initiated.

namespace AbstractClassExample
{
    class Program
    {
        static void Main(string[] args)
        {
            /*BaseEmployee Object can not be created since this is declared as Abstract
            Following LOCs will return compilation error if uncommented.*/

            //BaseEmployee baseEmployee = new BaseEmployee();
            //baseEmployee.EmployeeID = "EMP001";
            //baseEmployee.EmployeeAddress = "3400 Lee Highway, VA 22031";
            //baseEmployee.EmployeeName = "John Doe";

            //Base Employee Calculate Salary can be called that shouldn't be accessible
            //var baseSalary = baseEmployee.CalculateSalary(34);

            //Full Time and Contract Employees objects are successfully created.
            BaseEmployee fullTimeEmployee = new FullTimeEmployee();
            var fteSalary = fullTimeEmployee.CalculateSalary(40);

            BaseEmployee contractEmployee = new ContractEmployee();
            var CteSalary = contractEmployee.CalculateSalary(40);
        }
    }

    public abstract class BaseEmployee
    {
        public string EmployeeID { get; set; }
        public string EmployeeName { get; set; }
        public string EmployeeAddress { get; set; }

        public abstract double CalculateSalary(int hoursWorked);
    }

    public class FullTimeEmployee : BaseEmployee
    {
        public override double CalculateSalary(int hoursWorked)
        {
            return hoursWorked * 60.00+3700;
        }
    }

    public class ContractEmployee : BaseEmployee
    {
        public override double CalculateSalary(int hoursWorked)
        {
            return hoursWorked * 65.00;
        }
    }
}

Tuesday, June 2, 2015

MODIFYING AUTO-SAVE FEATURE INTERVAL TRIGGER TIME IN MICROSOFT DYNAMICS CRM 2013/2015


By default, the Auto-save feature interval trigger time in Microsoft Dynamics CRM 2013 is set to 30 seconds. However, there might be a case where you have to decrease or increase this interval trigger time value to meet a specific requirement. You will then have to modify the “AutoSaveInterval” value in the “DeploymentProperties” table in the “MSCRM_CONFIG” SQL Server database. The value is in second(s) unit.

Retrieving Auto-save feature interval trigger time


SELECT IntColumn FROM DeploymentProperties
WHERE ColumnName = 'AutoSaveInterval'
Modifying Auto-save feature interval trigger time


UPDATE DeploymentProperties
SET IntColumn = 100
WHERE ColumnName = 'AutoSaveInterval'

Saturday, May 30, 2015

Filtering on opportunity products lookup ("Existing Product" lookup inside Opportunity Product entity)

function AddNewView2() {

 try {
 $("#productid").attr("disableViewPicker", "0");
 // Parameters
 var customViewId = "FD140AAF-4DF4-11DD-BD17-0019B9312238"; // new id
 var customViewName = "Sales Products";
 var lookupFieldName = "productid";
 var entityName = "product";
 var primaryKeyName = "productid";
 var primaryFieldName = "productid";
 // Create Dynamics View
 AdvancedFilteredLookup2(lookupFieldName, customViewId, entityName, primaryKeyName, primaryFieldName, customViewName);
 $("#productid").attr("disableViewPicker", "1");
 }
 catch (err) {
 }
}

// Advanced Filtered Lookup
function AdvancedFilteredLookup2(lookupSchemaName, viewId, entityName, primaryKeyName, primaryFieldName, viewDisplayName) {
 var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical'>" +
"<entity name='" + entityName + "'>" +
"<attribute name='name' />" +
"<attribute name='producttypecode' />" +
"<attribute name='productnumber' />" +
"<attribute name='" + primaryFieldName + "' />" +
"<order attribute='name' descending='false' />"+
"<filter type='and'>" +                      
    "<condition attribute='ti_salesproduct' operator='eq' value='1' />" +
    "</filter>" +
    "</entity>" +
    "</fetch>";

 var layoutXml = "<grid name='resultset' " +
"object='1024' " +
"jump='name' " +
"select='1' " +
"icon='1' " +
"preview='1'>" +
"<row name='result' " +
"id='" + primaryKeyName + "'>";

 layoutXml += "<cell name='name' width='300' />";
 layoutXml += "<cell name='productnumber' width='100' />";
 layoutXml += "<cell name='producttypecode' width='150' />";
 layoutXml += "</row></grid>";

 try {
 var lookupControl = Xrm.Page.ui.controls.get("productid");
 lookupControl.addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
 }
 catch (err) {
 }
}


Thursday, May 28, 2015

CRM Developer Tools in Visual Studio 2015


It seems CRM Developer Tools are not getting much love from Microsoft lately.

The versions available for CRM 2013 where only for VS2013 and V2012 It’s not been release as part in CRM 2015 SDK yet.

…and VS 2015 is just around the corner…

But there is always a way, ;)…













There are known work around (e.g.: Microsoft Dynamics CRM 2013 Toolkit with Visual Studio 2013) to make this work on VS2013 but I found none so far to deal with VS2015.

After looking around and doing some tests I found a MVW (Minimum Viable Workaround, ;)) to make this work. Two simple steps should do it, as per below:

Add the below to devenv.exe.config

<dependentAssembly>

<assemblyIdentity name="Microsoft.Windows.Design.Host" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />

<bindingRedirect oldVersion="4.0.0.0-4.1.0.0" newVersion="4.2.0.0" />

</dependentAssembly>

Install Microsoft.CrmDeveloperToolsVS2015.vsix (my own version with just a view tweaks considering the workaround for VS2013, as per blog linked above)

Tuesday, May 5, 2015

How to update the value of parent entity field while updating child entity in ms crm 2011 using javascript

Parent Entity  to open the child entity in popup windows with selected records

function addPriceEndDate(selecteditemsid)
{
var parameters = {};
parameters["selecteditemsid_0"] = selecteditemsid;
  Xrm.Utility.openEntityForm("cel_priceenddate", null, parameters);    
}

Add the Below parameters in ribbon workbench.



From child entity we updating the parent entity fields in my case I am updating End date. Below is script.

function onPriceEndDateSave()
{
if (getQuerystring('selecteditemsid_0') != null)
{
var accountid = getQuerystring('selecteditemsid_0');
accountid = ReplaceString(accountid ,"%7b","{");
accountid = ReplaceString(accountid ,"%7d","}");
accountid = ReplaceString(accountid ,"%2c",",");
var priceids= new Array();
priceids= accountid.split(",");
for (price in priceids) {
updateRecord(priceids[price]);
}
}
}


function updateRecord(id)
{
debugger;
try
{
var price = {};
price.cel_EndDate = Xrm.Page.getAttribute("cel_priceenddate").getValue();

SDK.REST.updateRecord(
id,
price ,
"cel_price",
function () {
writeMessage("The Price record changes were saved");
},
errorHandler
);

}
catch(e)
{
alert("Failed to Execute");
}
}
function errorHandler(error) {
alert(error.message);
}
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[[]/,"[").replace(/[]]/,"]");
var regex = new RegExp("[?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
function ReplaceString(strString, strReplace, strReplaceWith){
if (strString != "" && strReplace != "") {
var re = new RegExp(strReplace, "gi");
var s = strString.replace(re, strReplaceWith);
return s;
}
else{
return strString;
}

}

Get files of last hour in Azure Data Factory

  Case I have a Data Factory pipeline that should run each hour and collect all new files added to the data lake since the last run. What is...