Wednesday, July 27, 2016

jQuery Selectors

jQuery Selectors:

In this section, you will learn about jQuery selectors and how to find DOM element(s) using selectors.
Reference -
The jQuery selector enables you to find DOM elements in your web page. Most of the times you will start with selector function $() in the jQuery.
Syntax:
$(selector expression, context)
            
jQuery(selector expression, context)
The selector expression parameter specifies a pattern to match the elements. The jQuery usesCSS selector patterns as well as its own pattern to match the elements.
The context parameter is optional. It specifies elements in a DOM hierarchy from where jQuery starts searching for matching elements.
Let's see commonly used selectors in jQuery.

Select elements by name:

The most common selector pattern is element name. Specifing an element name as string e.g. $('p') will return an array of all the <p> elements in a webpage.
The following figure shows which DOM elements will be returned from $('p') & $'(div').
jQuery Selectors Demo
jQuery Selectors Demo
As you can see in the above figure, $('div') will return all the <div> elements including its child elements.
Example: Select elements by name

$('p').append('This is paragraph.'); // appends text to all p elements 

$('div').append('This is div.); // appends text to all div elements 

<div>
    <p></p>
    <p></p>
</div>

<p></p>

<div></div>

Select elements by id:

jQuery append() method inserts text at the end in the element.
You can get a particular element by using id selector pattern. Specify an id of an element for which you want to get the reference, starting with # symbol.
The following figure shows which DOM elements will be returned from $('#myDiv1') & $'(#prg2').
jQuery Selectors Demo
jQuery Id Selector Demo
Example: Select element by #Id

$('#impPrg').append('This element\'s id is "impPrg"');

$('#myDiv2').append('This element\'s id is "myDiv2"');

<div id="myDiv1">
    <p></p>
</div>

<p id="impPrg"></p>

<div id="myDiv2">
</div>

Select elements by attribute:

jQuery also allows you to find an element based on attributes set on it. Specifing an attribute name in square brackets in $ function e.g. $('[class]') will return all the elements that have class attribute irrespective of value.
In the following example, jQuery returns all the elements that have class or contenteditable attribute irrespective of any value.
jQuery Selectors Demo
jQuery Attribute Selector
Example: Select elements by attribute

$('[class]').append('This element has class attribute');

<div id="myDiv1">
    <p></p>
</div>

<p id="impPrg" class="boldPrg"></p>

<div id="myDiv2" class="yellowDiv">
</div>
You can also specify a specific value of an attribute in attribute selector. For example, $('[class="myCls"]') will return all the elements which have class attribute with myCls as a value.
jQuery Selectors Demo
jQuery Selector by Attribute Value
Example: Select element by attribute value
 
$('[class="impDiv"]').append('This element includes class="yellowDiv" attribute');
      
<div id="myDiv1">
    <p></p>
</div>

<p id="impPrg" class="boldPrg">This is paragraph.</p>

<div id="myDiv2" class="yellowDiv">
</div>

jQuery Selector Patterns:

jQuery provides number of ways to select a specific DOM element(s). The following table lists the most important selector patterns.
CategorySelectorDescription
Find by Element$('p')Find all <p> elements
$('p, div, code')Find <p>,<div> and <code> elements
Find Descendant Elements$('div p')Find all <p> elements which are descendants of <div>
$('div > p')Find <p> which is child of <div>
$(*)Find all elements
Find by Id$('#myDiv')Find element whose id is myDiv
$('p#myPrg')Find <p> element whose Id ismyPrg
$('#myDiv1, #myDiv2')Find multiple elements by id separated by comma.
Find by CSS Class$('.myCSSClass')Find all the elements withclass=myCSSClass.
$('.myCSSClass1, .myCSSClass2 ')Finds all elements whose class attribute is set to myCSSClass1 ormyCSSClass2
$('div.myCSSClass')Finds all <div> elements withclass=myCSSClass
$('p:first-child')Find all <p> elements, which is the first child of its parent element. (parent element can be anything)
Find by Attributes$('[class]')Find all the elements with the classattribute(whatever the value).
$('div[class]')Find all the <div> elements that have a class attribute(whatever the value).
Find by containing value of attribute$('div[class=myCls]')Find all the <div> elements whose class attributes are equal to myCls.
$('div[class|=myCls]')Find all the <div> elements whose class attributes are either equal tomyCls or starting with myCls string followed by a hyphen (-).
$('div[class *="myCls"]')Selects <div> elements whose class attributes contain myCls.
$('div[class~=myCls]')Selects div elements whose class attributes contain myCls, delimited by spaces.
$('div[class$=myCls]')Selects <div> elements whose class attributes value ends withmyCls. The comparison is case sensitive.
$('div[class!=myCls]')Selects <div> elements which does not have class attribute or value does not equal to myCls.
$('div[class^=myCls]')Selects <div> elements whoseclass attribute value starts with myCls.
$('div:contains("tutorialsteacher")'Find all <div> elements that contains the text 'tutorialsteacher'
Find by Input type$(":button")Find all input whose type is button.
$(':input[type="radio"]')Find all radio input types.
Even-Odd rows$('tr:odd')Find all odd rows. (1,3,5,7..)
$('tr:even')Find all even rows.(0,2,4,6..)

Points to Remember :

  1. jQuery selectors enables you to find DOM elements in the web page.
  2. jQuery uses css selector expression patterns along with its own patterns.
  3. Syntax: $('selector expression','context'). context is an optional parameter.
  4. jQuery includes various selector patterns e.g element name, #id, attributes, descendant elements, css class, input types etc.

Lambda Expression

Anatomy of the Lambda Expression

C# 3.0(.NET 3.5) introduced the lambda expression along with LINQ. The lambda expression is a shorter way of representing anonymous methods using some special syntax.

For example, following anonymous method checks if student is teenager or not:
Anonymous method in C#:
    
delegate(Student s) { return s.Age > 12 && s.Age < 20; };
        
Anonymous method in VB.Net:
    
Dim isStudentTeenAger = Function(s As Student) As Boolean
                                    Return s.Age > 12 And s.Age < 20
                        End Function
        
The above anonymous method can be represented using a Lambda Expression in C# and VB.Net as below:
Lambda Expression in C#:

s => s.Age > 12 && s.Age < 20

Lambda Expression in VB.Net:

Function(s) s.Age  > 12 And s.Age < 20

Let's see how the lambda expression evolved from the following anonymous method.
Anonymous method in C#:

delegate(Student s) { return s.Age > 12 && s.Age < 20; };

The Lambda expression evolves from anonymous method by first removing the delegate keyword and parameter type and adding a lambda operator:
Lambda Expression from Anonymous Method
The above lambda expression is absolutely valid, but we don't need the curly braces, return and semicolon if we have only one statement that returns a value. So we can eliminate it.
Also, we can remove parenthesis (), if we have only one parameter.
Lambda Expression from Anonymous Method
Thus, we got the lambda expression: s => s.Age > 12 && s.Age < 20 where s is a parameter,=> is the lambda operator and s.Age > 12 && s.Age < 20 is the body expression:
Lambda Expression Structure in C#
Same way we got lambda expression in VB.Net can be written as below:
Lambda Expression Structure in VB.Net
Note :VB.Net doesn't support lambda operator =>

Lambda Expression with Multiple parameters:

You can wrap the parameters in parenthesis if you need to pass more than one parameter, as below:
Example: Specify multiple parameters in lambda expression C#
            
(s, youngAge) => s.Age >= youngage;

You can also give type of each parameters if parameters are confusing:
Example: Specify parameter type in lambda expression C#
            
(Student s,int youngAge) => s.Age >= youngage;

Example: Specify multiple parameters in lambda expression VB.Net
            
Function(s, youngAge) s.Age >= youngAge 

Lambd expression without any parameter:

It is not necessary to have atleast one parameter in a lambda expression. The lambda expression can be specify without any parameter also.
Example: Lambda expression with zero parameter.
            
() => Console.WriteLine("Parameter less lambda expression")

Multiple statements in body expression:

You can wrap expressions in curly braces if you want to have more than one statement in the body:
Example: Lambda expression C#

(s, youngAge) =>
{
  Console.WriteLine("Lambda expression with multiple statements in the body");
    
  Return s.Age >= youngAge;
}

Example: Lambda expression VB.Net

Function(s , youngAge)
    
    Console.WriteLine("Lambda expression with multiple statements in the body")
    Return s.Age >= youngAge

End Function 

Local variable in Lambda Expression body:

You can declare a variable in the expression body to use it anywhere in the expression body, as below:
Example: Lambda expression C#

s =>
{
   int youngAge = 18;

    Console.WriteLine("Lambda expression with multiple statements in the body");

    return s.Age >= youngAge;
}
Example: Lambda expression VB.Net

 Function(s) 
                                      
        Dim youngAge As Integer = 18
            
        Console.WriteLine("Lambda expression with multiple statements in the body")
            
        Return s.Age >= youngAge
            
End Function
You can invoke lambda expression as you invoke delegates. Learn how to invoke lambda expression in the next section.

Points to Remember:

  1. Lambda Expression is a shorter way of representing anonymous method.
  2. Lambda Expression syntax: parameters => body expression
  3. Lambda Expression can have zero parameter.
  4. Lambda Expression can have multiple parameters in parenthesis ().
  5. Lambda Expression can have multiple statements in body expression in curly brackets {}.

Thursday, July 21, 2016

Using Parallel ForEach and ExecutionTransactionRequest in CRM 2015 for bulk creation of records.

Reference -
Recently we had a requirement to read each account record and create 4 related child records for each of them. First we wrote a console app that will loop through each of the account records and will create corresponding records. The tool was working fine however it’s execution was very slow. It was talking around 5 hours to process 10000 Account records and create corresponding 40000 child records.
To fine tune the performance, we implemented the Parallel.ForEach.
We got the performance improvement, however we were getting the following error
The communication object, System.ServiceModel.Security.TransportSecurityProtocol, cannot be used for communication because it has been Aborted.
And because of this we had few Account records which had one, two or three records instead of total 4 related records as required. (as the child records might be getting created by separate thread).
For e.g. we can see that for Account Number 98208 we have four records created one at 8:33, then another one at 8:36, 8:38 and 8:41. (gap of minimum 2 minutes). So if there was an exception we had account records created with less than 4 child records.
We solved this issue by using ExecuteTransactionRequestand creating all the child records as part of transaction, so that we either have all the 4 records created or none.
All the child records were getting created at the same time
We also got huge performance improvement, the code that was initially taking 5 hours to process 10000 records, were not taking only 1 hour to process them.
Hope it helps..