Monday, June 18, 2018

Javascript Insights with DOM

Javascript Insights with Sudhir :


document.getElementbyId('btnResolve');

Is this a Javascript?? --> Mostly No i.e really a lot of this is DOM i.e DOM implemented in javascript

DOM is a interface that supposed to be language neutral, that allows you to manipulate HTML , listen to event handlers and things like that..
so document.getElementbyId is actually a DOM API method which javascript implements


DOM API that allows you to manipulate HTML, listen to event handler ..etc

What  happens if below html page is loaded in browser ... i.e after we enter the URL in browser and hit enter

<html>
   <head>
          <script type='text/javascript>
               alert('hello sudhiR');
          </script>
 </head>
<body>
     <h1>HELLO WORLD</h1>
 </body>
</html>

Whenever we hit enter , our browser sends an GET request for content to server and the server is going to respond with an HTTP response . In it, its going to include the html i.e string with html tags as above.
--> The browser is going to pass it off to its something like webkit , that will start processing the HTML , it'll parse it and it will start building DOM elements  up one-by-one like
<html>  --> parsed in to document element
head element to head to DOM and  when we get a script tag it goes to javascript interpreter i.e something like v8 which processes javascript and tokenize and we get a popup , untill then all browser processing totally gets freezed until user hits ok and DOM is going take over again

So until the whole DOM is loaded DOMContentLoaded or DOMContentReady will not fire/execute (i.e not fire untill the script executed) i.e untill whole html is processed

DOM creation engines --> webkit , Firefox, trident IE etc...


Doubt: If loaded or access the DOM elemnts in that script tag which is inside head , I think we get undefined.
may be that is why we load at end of body
Bottom Load your scripts..and top load CSS 

Javascript Features:
Javascript is a synonym of ECMAScript , ES is a standard and Javascript is like trademark 

Javascript is dynamic.. 
Most other Compiled languages like C .., what happens is we write our C code, we compile it and what compiler does it read that code and convert to in to ByteCode and execute that ... that bytecode is loaded in memory and computer goes instruction by instruction..reading through memory and operating something elese 

In dynamic languages like.. there is no distinction b/w the memory that's used for code and the memory that's used for data

Type travels with value and not with variable.. 2 



Anything you can do with an object can be done with a function in Javascript.. 
Create a function, can return a function with inner function, can pass functions as arguments..
The above..is which is dynamically created..

DOM is Javascript representation of HTML and a  browser.
there for you to manipulate HTML page, change whats going inside a browser , its an interface provided to javascript

DataTypes OPerators and Primitives:


Undefined: Actually going to refer to a pointer , that points hasn't been set. i.e not set this variable or defined yet.
var foo; --> undefined

null --> actually references to null pointer --> i.e its by intent i.e manually set to null. where undefined is not declared which is by mistake


assignment is we are actually taking a pointer and assigning to the address of variable in memory, i.e we have some object in our memory stack and we gonna point foo to that address

No need to use () with new operator,
Delete is deletes a property i.e it doesn't actually delete data , i.e deletes the reference to the object



Memory Stack implementation in browser:
Memory allocation of browser--> kind of very old one






That diagram is before delete.. i.e variables are just pointer to actual memory in call object or context


so delete is not actually removing data from memory, it just removes the reference, i.e we are working with pointers either reallocating , reassigning them 


So when you have name object it will have some address location and when its assigned to me i.e me.name has address "xxx" location of the object {first:"justin"}, so when me.name is copied to other varibale name then the value stored in me.name is refrence to object i.e address location of {first:"justin"}, so when we delete the property on me i.e me.name it will stop referencing the object {first:"justin"} but the other variable name still has reference or address location of object {first:"jsutin"}

What if delete me--> stille name.first work? --> yes

and important thing about delete is it delete attribute or properties of an object or variable and not variable itself.

delete will return true or false , it returns true if syntax is correct i.e dot something , and false if syntax is wrong
i.e if delete a.name --> true, if you again type same command it will return true bcz it doesnot bother wether that property exists or not 

delete a.some --> returns true

delete a --> false

 

Why Array is a object , because its stored in memory as below, keys will be integers


so typeOf will return the most base type, except for function which is  a special case in javascript








Gotcha:

when you check in browser typeof name or just type name you will get string i.e "[object Object]"

beacuse name is default property in window object which is string , if you want you can just type name in console , will return ""



When Primitive types are compared, with === then they go through the value and type





Now because they are composite types i.e objects its going to check by reference i.e its actually going to check by address of where these objects are in memory . as they are two different objects created in memory they have two different addresses , therefore false


Triple equals  in a primitive case compares value at the two addresses and a composite case we 're going to compare the addresses of left and right









Javascript doesn't have block level scope  , so i of this kind is global , its in global call object, so its gonna out the value of i at any given time


Sunday, January 29, 2017

Modular Javascript

I actually never heard much about modules until I have started developing Angular 2 applications(enterprise level). This post is more about modules in javascript which include different module formats and module loaders starting with the necessity of going modular.

Why Modules in javascript:

1.To define higher level abstractions that let you make an application of larger building blocks

2.To maintain implementation details hidden . can re-factor code and easy maintained and re-usability

3.Simplify dependency management 

So how does the modules evolve?

Earlier when javascript was developed there was no support for modules until now which led many developers groups  to invent solutions for writing modular based and then after writing too many modules for an application  by setting some standards(led to different module formats) then they found it hard to integrate all modules i,e packaging and distribution..then again.. finally meanwhile javascript evolved and started supporting MODULES(Current version ES6 mostly referred as ES2015  )

However this newer version of javascript is not supported by browsers yet which require a transpilation step using external  compilers like Babel or Typescript

lets define Module before we go ahead :

A group of code and data related to a particular piece of functionality. It encapsulates implementation details exposes a public API and is combined with other modules to build a larger application.

Module Format: 

is just a syntax used to define a module which is independent of loader , but syntax is useless without something that executes .Different Module formats are;
1)Asynchronous Module Definition Format(AMD)
2)CommonJS
3)Universal Module Definition (UMD)
4)System.register format
5)ES2015 fomat

Module Loader :

They are just javascript libraries we'll include in our project to understand the module format we decide to use  and how to load and execute.Some of the module loaders are:

1)RequireJS :-supports AMD module format
2)SystemJS :- Most popular loader which supports AMD,commonJS,UMD and system.register formats.

Before we go in detail about  module formats and loaders let us see how we used to manage javascript code without  these external libraries.

One of the familiar way was
1) IIFE (Immediately Invoked Function expressions) : Provides encapsulation and reduce the number of variables that we store in global scope (reducing global scope pollution )

(function(){

})();     which is immediately invoked that is no global storage

2)Revealing Module Pattern: Variables are scoped to functions in  js
Function scoping provides nice encapsulation of module implementation details

Unlike IIFE we need referred modules in code , so they should have name ....that means that they do add new value to the global scope

Along with encapsulation good thing about this pattern is the code is easier to read, maintain and provides clear separation b/w private implementation details and modules public api (i.e we can have all implementation and expose methods or properties we choose to )

We have 2 different types in this pattern 
1)Singleton and
2)Constructor pattern

Just quickly have syntax look

Singleton Pattern :



Constructor Pattern:



I think the name and code implementation are self explanatory 😃

So What do you think is lagging in going that way ...? yes Dependency Management we will load these js files in index.html with out missing the order i.e loading the dependent modules is trivial and is not so easy in enterprise level applications where we have 100's of js files

So lets actually get in to Module formats and load them using Module loaders

Asynchronous Module Definition Format (AMD) 

Used to define modules that will be loaded in browser . The AMD format supports loading asynchronously which is good when modules are requested from server and loaded in browser.. i.e on demand

syntax:
We define AMD modules by calling a function name define (this is not a built in Javascript but require a javascript loader) which have two parameters where the first is an Array of dependencies(mentioning relative path of module) and second is function which turns as module.
We  have to mention the module name and extension of js is not required 

employee.js

define([], function () {
    var empName = "";
    function displayName() {
        console.log('Name is ' + empName);
    }
    function setName(employeeName) {
        empName = employeeName;
    }
    function getName() {
        return empName;
    }
    return {
        //We can choose what we want to expose i.e hiding rest of
        displayName: displayName,
        setEmployeeName: setName,
        getEmployeeName: getName
    }

});

this file itself becomes a module, to have this module in other modules we need to provide this as a dependency
define (['./employee','./manager'], function (employee,manager) {
    //we can use methods and properties exposed by
    // employee and manager using the objects
});

So we have created a module , now to load the module we need a module loader i,e using requirejs module loader , we can get this from   http://requirejs.org/

Another way is through package.json with npm (node package manager), we can specify in dependencies or just install with command
npm install requirejs --save

So how to load these files?

<script data-main="js/app" src="node_modules/reuirejs/require.js"></script>

We have to mention the entry point module of the application   


What ever the dependencies are with app.js i.e app module are loaded first.

CommonJS Module Format:

Mostly used in server applications.(Node JS which have a built in loader that supports CommonJS format). However we can load with  SystemJS Loader also.

We can get dependent modules using require keyword

var employee = require('./employee.js');  //Module loader will make sure that dependent modules will be loaded 1st before executing the current module.

In order to expose functions and other properties of current module i.e as an api we need to add them as new members of special object named exports 

function testing(){

}
exports.firstfunction = testing;
Just like require, a keyword , exports object is a special object that a commonjs syntax  loader will use when creating the structure of the  module and the api that is exposed to other modules of the application. The member name on the object need not to be same as the function name you are exposing as api.

The major difference of commonJs format is that module definition is not wrapped inside a function as we do in other formats(as AMD ).

In CommonJs format by default each file is treated as module.

A little bit more about exports object 
We' usually find module.exports ,so how different it is from exports object , both are equivalent except for a few gotchas
exports.firstfunction = testing;  is same as 
module.exports.firstfunction = testing;
but we cannot export object literals by assigning them to short hand export object 

exports={ }  and also we cannot directly assign a function to short hand version of export object.
exports= function() { } 
We have to export along with module i.e like module.exports={ };

So how can we load these modules i.e commonjs module.. which is .. using SystemJs module Loader.
We can install systemJS with npm as npm install systemjs --save

So to load systemJS we need to reference it in index.html as 

<script src="node_modules/systemjs/dist/system.js"></script>

We need to add some extra javascript with a configuration object (to mention the which syntax or module format , as SystemJs supports multiple formats) provided by Systemjs loader and to put up an entry point to application we need to have a import 

<script>
       System.config({
              meta: {
                     format:'cjs'
              }
       });
       System.import('js/app.js');
</script>

Saturday, December 31, 2016

C # Interfaces



To those are working in IT may be technical or not , in their life they will come across term interface,
and almost every one know what does it mean i.e definition syntax and how to and when to use. Most of the coding guys say it  "as classes do not support multiple inheritance and it will be possible in interfaces"  and we say they don't have implementation only definition and no declaration.


So lets learn after what we know,


Interfaces are considered as a contract consisting of properties and methods  and events, when a class implementing the interface it makes a commitment i.e fulfilling contract by implementing ALL(properties also) its interface members 
By default all  members are public , we cannot specify access modifiers to interface members 

An interface is similar to PURELY abstract class i.e class containing all abstract members (i.e no implementation)



Benefits of using interface is that code can be easily Maintainable

When your GetPeople implementation changes i.e if it returns List<Person> then again you need to change your implementation in 1st case as we get compilation error
but we did not have to change the interface implemented code, thats because Person[] and List<Person> both Implement IEnumerable

so when we are coding to the abstraction we don't care about the specific class coming back.All we do is its is a class that fulfills the contract , which makes our code more resistant .As every collection in .NET implements IEnumerable our repository may be stack, queue or whatever ...everything will work exactly without any change.. SO thats thing about programming to abstraction if the underlying implementation changes our code doesn't care 

We can also strongly type the collection like IEnumerable<Person>

So when we are programming to abstraction , we're adhering to a contract , but we don't care about implementation details i.e Get the functionality you need and not bothering about the specific type.

How:

we want code that is extensible that can respond quickly to new requirements , if we come up with a contract that the core application can use then we can plug in any number of different implementations that adhere to that contract 

Improving extensibility :
 For  example say you are getting data from repository using Service...
Generally we will use repository pattern in coding i.e BL repository (May be using Services, or CSV or SQL Connection).. this may vary so what we do is.. create an interface with what is required i.e functionalities so we create an interface with CRUD operations we want and then we use it in presentation layer .. so that ur UI doesn't care about actual implementation whether using services or csv or what ever no change in using that ()

i.e what ever the class obeying the interface contract can be used

Sample service repo :


Without using interfaces: we have to create objects for each type and use them ..redundant code ... so when we care  only about operations(features provided) and don't bother about underlying implementation it really helps in extending your code with out actually disturbing the usage/Consuming in your  presentation layer


** When an interface is implemented in a class , its access specifier should be public only otherwise it'll throw error
** IF you have Interface I1 with Method M1 and Interface I2 with M2 and when you inherit I2 in your class then you have to provide implementation for both M1 and M2.

Explicit Interface Implementation 





so why explicit implementation? 

If you have 2 interfaces to be implemented you can have it with single method also but why explicity defining / implementing them as shown above?
Because when two interfaces you have inherit have same method name but different return types then this explicit implementation is mandatory

for example when you inherit IEnumerable<T> then you can see as (internally IEnumerable<T> inherits IEnumerable) then you have to provide implementation for both GetEnumerator and GetEnumerator<T>

Explicit implementation of interface member should not have Access modifier  

Program to an abstraction rather than a concrete type i.e -->Program to an interface rather than a concrete class


Actual Usage:

So as we have seen above when we use interface we actually bother about the functionality provided and not the type which is serving .. so we have minimal change in presentation layer but we have to pass the type we want to connect and get data like in prev example either csv or sql or whatever

So we have to pass from UI which type you would like to and your factory class will instantiate that class and return that object (Interface )

1.So how can we make zero impact on UI , not even passing type
2.In the example what ever may be the type either from service / csv / sql we have to load all three assemblies as wen instantiate them in factory class

Suppose if we  get new type then we have to change UI and also add reference to our repo factory class project build it and then change the repo factory ...


We can avoid all above using Dynamic Loading

i.e no need to pass type from UI or load assemblies

1.We wont pass from UI we'll pick from configuration key of web config
2.We manually put the dll in bin folder of project to pick them which will actually happen when we add a reference (we can have a post build event for that or if you dont want to give new build you can directly place them in bin folder )


like wise for others also we can enable what ever configuration you want to use
To dynamically load the dlls or assemblies



So now no need to change any code level implementation nor give any new build...
Just Change the web.config with new app settings and place the dlls of your new implementation type in bin folder... bang!! ... done with ZERO code level impact or change


Conclusion: So, on a final note what we all to remember is interface is commitment and contract :-)

Sunday, October 2, 2016

LINQ - Method Syntax

It is a technology that give you the ability to query data from C# i.e  data imply object that are in memory on heap , objects from database or xml or any data-source.

Provides almost 50+ query operators which include Sorting, Filtering , joining , grouping, partitioning, projecting , aggregating etc ..

So on what types of data we can apply querying ? 

Lowest level data type that was chosen is IEnumerable<T>

But we don't have  interesting methods to query data we only have methods to loop through ,so to define new methods to IEnumerable<T>, Microsoft took extension methods i.e by extending it.. extension method is a method that looks like a member of a given type but in reality its a STATIC method on a different type

It may Seem Why Extension methods ... when we have inheritance for example we have a class called DateTime which cannot be inherited because of its sealed property so what to do if I have to have additional functionality like some calculation or custom logic through out the code ....

What LINQ can do?

We can easily get the things like 
what is the average invoice  amount customer,list of all customers with greater than 35 or starting with A etc , all these SQL type of querying can be done on data sources.

On What DataSources we can apply this is which have LINQ Providers,
DataSouces which have Linq providers are 

SQL DataSources,Entities(EF), Objects(In Memory Data), XML

We have 2 diff types of LINQ syntax  Query Syntax and Method Syntax



This Code looks like query iterates over the list of customers and finds all the customers that matches id and uses first method to return first element of sequence. BUT it is not Happening



Linq uses something called deferred execution  i.e code defining the linq statement is doing just that i.e defining statement only ...the Linq query itself is not executed until the result is required.

Calling any operator or method on query that must iterate over the result will cause query to execute.. here above when written .First() method the result is executed which is performance level issue.

The above is linq query syntax i,e built in to language i.e C# or VB and not Dot NEt CLR , therefore the query syntax should be translated in method calls for CLR when code is compiled. Instead of using linq query syntax we can call those methods directly using Linq Method syntax , since those methods are implemented as extension methods 

Extension Methods : An extension method is a method on class that extends its functionality without modifying or recompiling th original class .
An extension method is a static method on a static class , the first parameter should be the type that should be extended and also should be prefixed with this keyword.


















Usage:













Extension methods have a small down arrow indication.

Sorting:

Ordering Operators:
 OrderBy
 OrderByDescending,
 ThenBy,
 ThenByDescending,
 Reverse.

the execution of query expression using these operators is deferred until the code requests an item from resulting sequence  

return customerList.OrderBy(c => c.LastName)
  .ThenBy(c=> c.FirstName);

If you want to order by two columns then we have to use thenby i.e if you use orderby two times then it gets sort by last orderby column only.. Such Cases we have to use ThenBy

Same if you want descending then  .. we have to use OrderByDescending 

We can handle nulls by making the datatype nullable and we can make where these null values can appear i.e either starting or at the ending i.e 


return customerList.OrderByDescending(c => c.CustomerTypeId.HasValue)   //This will make nulls to come at end
  .ThenBy(c=>c.CustomerTypeId); 

  Creating:

We may get a scenario to create enumerable sequence, creating seq of vlaues, Linq Generation operators are 
Range, -- Creates sequence of integral numbers within a specified range 
Repeat, -- Generates a sequence of one repeated value 
These Operators are static methods in Enumerable Class but not Extension Methods and Not Deferred i.e Sequence is immediately built. Using these we can create Sequential series or random series 

var seq1 = Enumerable.Range(0, 10);  // We get an integer array of size 10 with values from 0 to 9
  var seq2 = Enumerable.Range(0, 10)
  .Select(i => i * i); // We can Have some custom logic implemented inside 

We can write multiple statements inside a Lambda Expression as below
Enumerable.Range(0, 10)
  .Select(i =>
  {
  var k = 0;
  return i * i + k;
  });

var integers = Enumerable.Repeat(-1, 10);  //  Creates integer array of value '-1 ' ten times.

Random rand = new Random();
rand.Next(0,26)  creates a new Random number ranging between 0 and 25 
var strings = Enumerable.Range(0, 10)
  .Select(i => ((char)('A' + rand.Next(0, 26))).ToString());

Comparing:

comparing sequence of objects, like comparing processed list to original list  determining the difference of records or performing some data synchronization  (All are extension methods)

Intresect,  --This operator produces set intersection of two sequences ; basically defining elements seq1.Intersect(seq2)
 Except, seq1.Except(seq2)
 Concat,-- Merging  , seq1.Concat(seq2);
 Distinct , seq1.Concat(seq2).Distinct();
 Union .- By defining he unique item for merging sequences   seq1.Union(seq2);

Projection : Refers to operation of Transforming an object in to new form , i.e using SELECT or SELCTMany operators 
If we donot provide projection operators then the type returned from query will be sequence of items of type defined in original sequence 

If we provide Projection operators , the result will be a sequence that is shaped differently from sequence we have passed 

Select
SlectMany ,  projects multiple sequences based on transform function and flatens in to one sequence


Examples of Select:

public IEnumerable <string > GetNames(List<Customer> customerList)
        {
            var query = customerList.Select(c => c.LastName + ", " + c.FirstName);
            return query;
        }

Defining anonymous types in Linq using new keyword.

public dynamic GetNamesAndEmail(List<Customer> customerList)
        {
            var query = customerList.Select(c => new
                            {
                                Name = c.LastName + ", " + c.FirstName,
                                c.EmailAddress
                            });
           foreach (var item in query)
            {
                Console.WriteLine(item.Name + ":" + item.EmailAddress);
            }
            return query;
        }

Using JOINS

var query = customerList.Join(customerTypeList,
                                c => c.CustomerTypeId,
                                ct => ct.CustomerTypeId,
                                (c, ct) => new
                                {
                                    Name = c.LastName + ", " + c.FirstName,
                                    CustomerTypeName = ct.TypeName
                                });

types When a collection have fields in which one of the child is again a collection and you want to filter the Parent / Master collection using child (i.e inner filed values) we can use SelectMany

Parent Object has as collection of related or child objects

eg: A customer(Parent object )as set of invoices(which is also a collection ) or shoppping cart as items purchased
WE MAY NEED TO FIND INFORMATION ON THE PARENT OBJECT USING CHILD DATA PROPERTIES 

eg: Total price of items in the cart , customers based on invoice info(i.e not paid etc)

We can also do with select ..

For Example we have Customers and we have to find out customers with OverDue Invoice i.e not paid then we have to check the child object condition..
doing so will return an enumerable of enumerable of invoices and not customers as follows

public IEnumerable <IEnumerable <Invoice >> GetOverdueCustomers1(List<Customer> customerList)
        {
            var query = customerList
                        .Select(c => c.InvoiceList
                                    .Where(i => (i.IsPaid ?? false) == false));
            return query;
        }

but we need customers and not invoices and that too only IEnumerable , we can write above as follows

public IEnumerable <Invoice > GetOverdueCustomers1(List<Customer> customerList)
        {
            var query = customerList
                        .SelectMany(c => c.InvoiceList
                                    .Where(i => (i.IsPaid ?? false) == false));
            return query;
        }

But to get List of customers we have to use SELECT MANY so that result selector is type of customer

public IEnumerable <Customer > GetOverdueCustomers(List<Customer> customerList)
        {
            var query = customerList
                        .SelectMany(c => c.InvoiceList
                                    .Where(i => (i.IsPaid ?? false) == false),
                                    (c,i)=> c).Distinct();
            return query;
        }

Imp: As Linq is Deferred execution i.e not gets executed until we use i.e IEnumerable is Lazy Loading when we directly assign to a datasource we will not get any data , so We have to use .ToList()

CustomerGridView.DataSource = customerRepository.SortByName(customerList).ToList();

Imp: When we have anonymous type then after retrieving when we assign directly to a datasource it throws error as cannot convert object to IEnumerable so we need to convert the query itself to .ToList() before passing.

.ToList() must be used only at the time of assigning because that will cause the query to execute.


GroupBy :

public dynamic GetInvoiceTotalByIsPaid(List<Invoice> invoiceList)
        {
            var query = invoiceList.GroupBy(inv =>inv.IsPaid ?? false,
                                            inv => inv.TotalAmount,
                                            (groupKey, invTotal) => new
                                            {
                                                Key= groupKey,
                                                InvoicedAmount = invTotal.Sum()
                                            });
            foreach ( var item in query)
            {
                Console.WriteLine(item.Key + ": " + item.InvoicedAmount);
            }

            return query;
        }
Here we want to get total amount of invoices based on the invoices that got paid and not paid... i.e group invoices by IsPaid property ... so 
1st param is on which prop you would like to group by and then what result  you would like to see i.e what column aggregation you want and then the result set ...

NOT MUCH IN RESULT SET generally for join like statement you will take 1st datasource and 2nd datasource here the parameters are GROUP BY  KEY AND AGGREGATE COLUMN WE mentioned ..

If we want to group by 2 columns then the 1st parameter is the object (using new keyword)

 var query = invoiceList.GroupBy(inv => new
                            {
                                IsPaid = inv.IsPaid ?? false,
                                InvoiceMonth = inv.InvoiceDate.ToString( "MMMM")
                            },
                                            inv => inv.TotalAmount,
                                            (groupKey, invTotal) => new
                                            {
                                                Key = groupKey,
                                                InvoicedAmount = invTotal.Sum()
                                            });
            foreach ( var item in query)
            {
                Console.WriteLine(item.Key.IsPaid + "/" +
                                    item.Key.InvoiceMonth + ": " + item.InvoicedAmount);
            }


            return query;