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

}

Wednesday, April 29, 2015

What's New In C# 6.0?

Microsoft has released the preview version of Visual Studio 2015 and .NET 4.6 for developers to try and provide feedback on usage or issues. .NET 4.6 preview comes withC# 6.0 which includes the new additional features expected by developers to improve the coding productivity.
In this article I am going to describe the new features introduced in C# 6.0. If you haven’t download the Visual Studio 2015 please get it from below download button.
Download Visual Studio 2015
Property Initialization with default value
In C# 6.0 we can initialize the default value to property right from the place we create it. With the help of this we can avoid the chances of null errors while accessing property when no value assigned.
Old Style:
        public int Id { getset; }
        public string FirstName { getset; }
New Style:
        public int Id { getset; } = 1001;
        public string FirstName { getset; } = "Srinivas";

String Interpolation
The most common thing we use in our daily coding is String concatenation. For this we use either ‘+’ symbol or string.Format. Sometimes when we use String.Format(), the numbered placeholders like {0}, {1}, {2}, etc. caused the problem (especially when you use more placeholders) due to arguments to be supply in the same order.
This usage is very much simplified in C# 6.0 by adding expression which replaces the numbered placeholders.
Old Style:
name = string.Format("Employee name is {0}, located at {1}", emp.FirstName, emp.Location);
New Style:
name = "Employee name is \{emp.FirstName}, located at \{emp.Location}";
We can even use the expressions in the content placeholder area as below:
name = "Employee name is \{emp.FirstName}, located at \{emp.Location}. Age of employee is \{(emp.Age > 0) ? emp.Age.ToString() : "N/A"}";
Note: The above syntax works well in preview, however Microsoft has decided to change the syntax even in much better way as below:
name = $"Employee name is {emp.FirstName}, located at {emp.Location}";

Expression Bodied Functions
C# 6.0 allows properties, methods and other members to have bodies as lambda expressions instead of statement blocks. This will reduces the little lines of codes and gives clear view.
Old Style:
        public string[] GetCountryList()
        {
            return new string[] { "India""USA""UK" };
        }
New Style:
        public string[] GetCountryList() => new string[] { "India""USA""UK" };

Import Static Classes
We know that static members can only be accessed by only class name and can’t be instantiate for static classes. If your class is having more static members and you need to repeat the class name all the times whenever you are calling static member. It is redundant, which is not necessary.
C# 6.0 allows us to import the Static classes and use the static members directly without class name. For instance, Math is a core static class from .NET library. Before C# 6.0 we must call its methods with class name. But now things makes simpler by importing Math class with using statement and call mathematical functions directly as shown below:
Old Style:
            double powerValue = Math.Pow(2, 3);
            double roundedValue = Math.Round(10.6);
New Style:
            using System.Math;
            double powerValue = Pow(2, 3);
            double roundedValue = Round(10.6);
Same implementation can be used for calling extension methods as shown below: (assume you have a list object for employee collection)
Old Style:
            var employees = listEmployees.Where(i => i.Location == "Bangalore");
New Style:
            using System.Linq.Enumerable;
            var employees = Where(listEmployees, i => i.Location == "Bangalore");

Null-conditional operators
C# 6.0 introduces Null-conditional (?.) operator which works on top of conditional (?:) operator to provide the much easier access to check the NULL values.
It returns null value, if any of the object in the series of reference objects provided is null. The new style will also reduce the code when you use nested conditions.
            var emp = new Employee()
            {
                Id = 1,
                Age = 30,
                Location = "Bangalore",
                Department = new Department()
                {
                    Id = 1,
                    Name = "IT"
                }
            };
Old Style:
            string location = emp == null ? null : emp.Location;
            string departmentName = emp == null ? null : emp.Department == null ? null : emp.Department.Name;
New Style:
            string location = emp?.Location;
            string departmentName = emp?.Department?.Name;

nameof Expressions
In C# 6.0, nameof operator will be used to avoid the hardcoded string laterals which may causes spell mistakes especially when we work with PropertyChanged() in XAML. It accepts an element as parameter and returns the string lateral for the same element. The parameter can be any member like property, method, class, etc.
            var emp = new Employee()
            {
                Id = 1,
                Age = 30,
                Location = "Bangalore",
                Department = new Department()
                {
                    Id = 1,
                    Name = "IT"
                }
            }; 
            Response.Write(emp.Location); //result: Bangalore
            Response.Write(nameof(Employee.Location)); //result: Location

Await in catch and finally blocks
Most of the times we use catch and finally blocks to log exceptions, sending exception notifications and cleaning up the resources. Before C# 6.0, these catch and finally blocks wouldn’t allow the await for async operations due to compiler limitations. Developers has to found their own workaround solutions on this
Now C# 6.0 allows us to use await statement in catch and finally blocks for asyc operations.
        public async Task StartAnalyzingData()
        {
            try
            {
                // collect and analyze the data               
            }
            catch
            {
                await LogExceptionDetailsAsync();
            }
            finally
            {
                await CloseResourcesAsync();
            }
        }

Exception Filters
Exception Filters (conditional exceptions) are the CLR capability which is already available in Visual Basic, but not in C# till now.
In order to use it, you must be declare the condition on the same line where the Catch block was defined like catch (Exception ex) if (filterCondition). If the filter condition is true, then only the Catch block will execute else it will skip from the execution.
            try
            {               
                //throw some exception here for test
            }
            catch (ArgumentNullException ex) if (ex.Source == "EmployeeCreation")
            {
                //notify null exception
            }
            catch (InvalidOperationException ex) if (ex.InnerException != null)
            {
                //notify and log exception
            }
            catch (Exception ex) if (ex.InnerException != null)
            {
                //log general exception
            }

Dictionary Initializer
C# 6.0 adds the ability to add values of the dictionary to its keys/indexes directly while initializing itself. The common use of this is, creating a Json object at one time instead creating an object first and assigning the values later on.
            var country = new Dictionary<intstring>
            {
                [0] = "India",
                [1] = "USA",
                [2] = "UK",
                [3] = "Japan"
            };

C# 6.0 with code name Roslyn, made with many syntactical changes and along with that introduced other new features. Also Microsoft has improved the C# compiler with new core and performance level technologies.
Happy coding!!! J

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...