Wednesday 31 October 2018

RXJS Operators

Operators By Category

1- Creating Observables

Operators that originate new Observables.
  • Create — create an Observable from scratch by calling observer methods programmatically
  • Defer — do not create the Observable until the observer subscribes, and create a fresh Observable for each observer
  • Empty/Never/Throw — create Observables that have very precise and limited behavior
  • From — convert some other object or data structure into an Observable
  • Interval — create an Observable that emits a sequence of integers spaced by a particular time interval
  • Just — convert an object or a set of objects into an Observable that emits that or those objects
  • Range — create an Observable that emits a range of sequential integers
  • Repeat — create an Observable that emits a particular item or sequence of items repeatedly
  • Start — create an Observable that emits the return value of a function
  • Timer — create an Observable that emits a single item after a given delay

2- Transforming Observables

Operators that transform items that are emitted by an Observable.
  • Buffer — periodically gather items from an Observable into bundles and emit these bundles rather than emitting the items one at a time
  • FlatMap — transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable
  • GroupBy — divide an Observable into a set of Observables that each emit a different group of items from the original Observable, organized by key
  • Map — transform the items emitted by an Observable by applying a function to each item
  • Scan — apply a function to each item emitted by an Observable, sequentially, and emit each successive value
  • Window — periodically subdivide items from an Observable into Observable windows and emit these windows rather than emitting the items one at a time

3- Filtering Observables

Operators that selectively emit items from a source Observable.
  • Debounce — only emit an item from an Observable if a particular timespan has passed without it emitting another item
  • Distinct — suppress duplicate items emitted by an Observable
  • ElementAt — emit only item n emitted by an Observable
  • Filter — emit only those items from an Observable that pass a predicate test
  • First — emit only the first item, or the first item that meets a condition, from an Observable
  • IgnoreElements — do not emit any items from an Observable but mirror its termination notification
  • Last — emit only the last item emitted by an Observable
  • Sample — emit the most recent item emitted by an Observable within periodic time intervals
  • Skip — suppress the first n items emitted by an Observable
  • SkipLast — suppress the last n items emitted by an Observable
  • Take — emit only the first n items emitted by an Observable
  • TakeLast — emit only the last n items emitted by an Observable

4- Combining Observables

Operators that work with multiple source Observables to create a single Observable
  • And/Then/When — combine sets of items emitted by two or more Observables by means of Patternand Plan intermediaries
  • CombineLatest — when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function
  • Join — combine items emitted by two Observables whenever an item from one Observable is emitted during a time window defined according to an item emitted by the other Observable
  • Merge — combine multiple Observables into one by merging their emissions
  • StartWith — emit a specified sequence of items before beginning to emit the items from the source Observable
  • Switch — convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently-emitted of those Observables
  • Zip — combine the emissions of multiple Observables together via a specified function and emit single items for each combination based on the results of this function

5- Error Handling Operators

Operators that help to recover from error notifications from an Observable
  • Catch — recover from an onError notification by continuing the sequence without error
  • Retry — if a source Observable sends an onError notification, resubscribe to it in the hopes that it will complete without error

6- Observable Utility Operators

A toolbox of useful Operators for working with Observables
  • Delay — shift the emissions from an Observable forward in time by a particular amount
  • Do — register an action to take upon a variety of Observable lifecycle events
  • Materialize/Dematerialize — represent both the items emitted and the notifications sent as emitted items, or reverse this process
  • ObserveOn — specify the scheduler on which an observer will observe this Observable
  • Serialize — force an Observable to make serialized calls and to be well-behaved
  • Subscribe — operate upon the emissions and notifications from an Observable
  • SubscribeOn — specify the scheduler an Observable should use when it is subscribed to
  • TimeInterval — convert an Observable that emits items into one that emits indications of the amount of time elapsed between those emissions
  • Timeout — mirror the source Observable, but issue an error notification if a particular period of time elapses without any emitted items
  • Timestamp — attach a timestamp to each item emitted by an Observable
  • Using — create a disposable resource that has the same lifespan as the Observable

7- Conditional and Boolean Operators

Operators that evaluate one or more Observables or items emitted by Observables
  • All — determine whether all items emitted by an Observable meet some criteria
  • Amb — given two or more source Observables, emit all of the items from only the first of these Observables to emit an item
  • Contains — determine whether an Observable emits a particular item or not
  • DefaultIfEmpty — emit items from the source Observable, or a default item if the source Observable emits nothing
  • SequenceEqual — determine whether two Observables emit the same sequence of items
  • SkipUntil — discard items emitted by an Observable until a second Observable emits an item
  • SkipWhile — discard items emitted by an Observable until a specified condition becomes false
  • TakeUntil — discard items emitted by an Observable after a second Observable emits an item or terminates
  • TakeWhile — discard items emitted by an Observable after a specified condition becomes false

8- Mathematical and Aggregate Operators

Operators that operate on the entire sequence of items emitted by an Observable
  • Average — calculates the average of numbers emitted by an Observable and emits this average
  • Concat — emit the emissions from two or more Observables without interleaving them
  • Count — count the number of items emitted by the source Observable and emit only this value
  • Max — determine, and emit, the maximum-valued item emitted by an Observable
  • Min — determine, and emit, the minimum-valued item emitted by an Observable
  • Reduce — apply a function to each item emitted by an Observable, sequentially, and emit the final value
  • Sum — calculate the sum of numbers emitted by an Observable and emit this sum

9- Backpressure Operators

  • backpressure operators — strategies for coping with Observables that produce items more rapidly than their observers consume them

10- Connectable Observable Operators

Specialty Observables that have more precisely-controlled subscription dynamics
  • Connect — instruct a connectable Observable to begin emitting items to its subscribers
  • Publish — convert an ordinary Observable into a connectable Observable
  • RefCount — make a Connectable Observable behave like an ordinary Observable
  • Replay — ensure that all observers see the same sequence of emitted items, even if they subscribe after the Observable has begun emitting items

11- Operators to Convert Observables

  • To — convert an Observable into another object or data structure

To read more about http://reactivex.io/




Continue Reading →

Tuesday 23 October 2018

UI Framework Questions

What is React JS?
ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications. It’s used for handling view layer for web and mobile apps. React also allows us to create reusable UI components.

React allows developers to create large web applications which can change data, without reloading the page. The main purpose of React is to be fast, scalable, and simple. It works only on user interfaces in application. This corresponds to view in the MVC template. It can be used with a combination of other JavaScript libraries or frameworks, such as Angular JS in MVC.

What is Redux
Redux is a predictable state container for JavaScript apps.
Redux makes it easy to manage the state of your application. Another way of looking at this – it helps you manage the data you display and how you respond to user actions.

What is Webpack
Webpack is an open-source JavaScript module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset. Webpack takes modules with dependencies and generates static assets representing those modules.

What is Babel
Babel is a JavaScript compiler.

Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Here are the main things Babel can do for you:

What is the difference between CSS and SASS?
Sass is a preprocessor for CSS, which makes it essentially the same thing as CSS. Being a preprocessor, you code in Sass and later the code is compiled into CSS. It functions as a (amazing) power-up for CSS, enabling features that are yet to exist in CSS. Sass’ main goal is to improve maintainability as your stylesheets getting larger and more complex. Some handy features Sass provided are:
  1. Variables, you can store reusable values with variables, this can be handy to store values like color hex code or a font stack.
  2. Nesting, you can write hierarchical CSS selectors simpler with Sass, just write it in nests just like what we do with HTML elements.
  3. Partials, you can write your stylesheet in a modular way using partials and import statements, improving your code maintainability and readability.
  4.  Mixins, they are like functions which you can define and reuse throughout your stylesheets. For example, sometimes we have to write one declaration for each rendering engine, like border-radius that should be accompanied by -webkit-border-radius, -moz-border-radius and so on. You can group all those border-radius statements into one mixin and just use the mixin whenever you need to define the border-radius for your element. Neat, isn’t it?
  5. Extension and Inheritance, which lets you share a set of CSS properties across your stylesheets.
  6. Mathematical Operators, like +, -, *, /, and % to aid you in determining various numbers throughout your stylesheets.


Continue Reading →

Select and where in Lamda

Where: Filters a sequence of values based on a predicate.
Select: Projects each element of a sequence into a new form.

//Output: 1,2,3,4,5,6,7,8,9,10
var numbers = Enumerable.Range(110);
          
//Output:  2,4,6,8,10
var even = numbers.Where(n => (n % 2) == 0).ToList();

//Output: false,true,false,true,false,....true
var evens = numbers.Select(n => (n % 2) == 0).ToList();

//Output: 1,2,3,4,5,6,...10
var lineNumbers = numbers.Select(i => i).ToList();


Continue Reading →

Monday 22 October 2018

MVC and WebApi


  1. Asp.Net MVC is used to create web applications that returns both views and data but Asp.Net Web API is used to create full blown HTTP services with easy and simple way that returns only data not view.
  2. Web API helps to build REST-ful services over the .NET Framework and it also support content-negotiation(it's about deciding the best response format data that could be acceptable by the client. it could be JSON,XML,ATOM or other formatted data), self hosting which are not in MVC.
  3. Web API also takes care of returning data in particular format like JSON,XML or any other based upon the Accept header in the request and you don't worry about that. MVC only return data in JSON format using JsonResult.
  4. In Web API the request are mapped to the actions based on HTTP verbs but in MVC it is mapped to actions name.
  5. Asp.Net Web API is new framework and part of the core ASP.NET framework. The model binding, filters, routing and others MVC features exist in Web API are different from MVC and exists in the new System.Web.Http assembly. In MVC, these featues exist with in System.Web.Mvc. Hence Web API can also be used with Asp.Net and as a stand alone service layer.


Continue Reading →

Saturday 20 October 2018

Understanding Rxjs Observable

What is Reactive Programming?
Reactive programming is programming with asynchronous data streams.

Reactive Extensions for JavaScript (RxJS) is a reactive streams library that allows you to work with asynchronous data streams. RxJS can be used both in the browser or in the server-side using Node.js.

When version 2 of Angular came out, it introduced us to observables. The Observable isn’t an Angular specific feature, but a new standard for managing async data that will be included in the ES7 release. Angular uses observables extensively in the event system and the HTTP service.

What is Observable:
Observables can be defined as a streams of data whose items arrive asynchronously over time.
To use observables, Angular uses a third-party library called Reactive Extensions (RxJS). Observables are a proposed feature for ES 2016, the next version of JavaScript.


You can think of an observable as an array whose items arrive asynchronously over time. Observables help you manage asynchronous data, such as data coming from a backend service. Observables are used within Angular itself, including Angular’s event system and its http client service. To use observables, Angular uses a third-party library called Reactive Extensions (RxJS). 

An Observable by default is unicast. Unicasting means that each subscribed observer owns an independent execution of the Observable. To demonstrate this:

const observable = Rx.Observable.create((observer=> {
    observer.next(Math.random());
    });
    
    // subscription 1
    observable.subscribe((data=> {
      console.log(data); // 0.24957144215097515 (random number)
    });
    
    // subscription 2
    observable.subscribe((data=> {
       console.log(data); // 0.004617340049055896 (random number)
    });

Subject:
While Observables are unicast by design, this can be pretty annoying if you expect that each subscriber receives the same values. Subjects can help us overcome this issue.
Subjects can multicast. Multicasting basically means that one Observable execution is shared among multiple subscribers.

Subjects are like Event Emitters, they maintain a registry of many listeners. When calling subscribe on a Subject it does not invoke a new execution that delivers data. It simply registers the given Observer in a list of Observers.

So how to use Subjects to multicast
Multicasting is a characteristic of a Subject. You don’t have to do anything special to achieve this behavior's. This is a small multicast demonstration:

const subject = new Rx.Subject();

// subscriber 1
subject.subscribe((data) => {
    console.log(data); // 0.24957144215097515 (random number)
});

// subscriber 2
subject.subscribe((data) => {
    console.log(data); // 0.24957144215097515 (random number)
});

subject.next(Math.random());

Nice! Now I got two subscriptions getting the same data. This however is not all that Subjects can do.

Whereas Observables are solely data producers, Subjects can both be used as a data producer and a data consumer. By using Subjects as a data consumer you can use them to convert Observables from unicast to multicast. Here’s a demonstration of that:

const observable = Rx.Observable.create((observer) => {
    observer.next(Math.random());
});

const subject = new Rx.Subject();

// subscriber 1
subject.subscribe((data) => {
    console.log(data); // 0.24957144215097515 (random number)
});

// subscriber 2
subject.subscribe((data) => {
    console.log(data); // 0.24957144215097515 (random number)
});

observable.subscribe(subject);

We pass our Subject to the subscribe function and let it take the values that come out of the Observable (data consuming). All the subscribers to that Subject will then all immediately receive that value.

merge: Turn multiple observables into a single observable.
var source1 = Rx.Observable.interval(100)
    .timeInterval()
    .pluck('interval');
var source2 = Rx.Observable.interval(150)
    .timeInterval()
    .pluck('interval');

var source = Rx.Observable.merge(
    source1,
    source2)
    .take(5);

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });

// => Next: 100
// => Next: 150
// => Next: 100
// => Next: 150
// => Next: 100
// => Completed

When do we apply forkJoin?
We use it when API requests are independent. It means that they do not depend on each other to complete and can execute in parallel. 
When all observables complete, emit the last emitted value from each. This operator is best used when you have a group of observables and only care about the final emitted value of each. Example link

When do we apply mergeMap/flatMap?
flatMap is an alias for mergeMap. When we need data from the first API request to make requests to the second API. Example link

concat: Concatenates all of the specified observable sequences, as long as the previous observable sequence terminated successfully.

/* Using Observable sequences */
var source1 = Rx.Observable.return(42);
var source2 = Rx.Observable.return(56);

var source = Rx.Observable.concat(source1, source2);

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });

// => Next: 42
// => Next: 56
// => Completed

empty: Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.

var source = Rx.Observable.empty();

var subscription = source.subscribe(
  function (x) {
    console.log('Next: %s', x);
  },
  function (err) {
    console.log('Error: %s', err);
  },
  function () {
    console.log('Completed');
  });
  
// => Completed

catch: Continues an observable sequence that is terminated by an exception with the next observable sequence.

var obs1 = Rx.Observable.throw(new Error('error'));
var obs2 = Rx.Observable.return(42);

var source = Rx.Observable.catch(obs1, obs2);

var subscription = source.subscribe(
  function (x) {
    console.log('Next: %s', x);
  },
  function (err) {
    console.log('Error: %s', err);
  },
  function () {
    console.log('Completed');
  });

// => Next: 42
// => Completed

zipMerges the specified observable sequences or Promises into one observable sequence by using the selector function, when all observable emit then only emit result as an array. The data emitted by the combined Observable is mapped one by one in order.

/* Without a result selector */
var range = Rx.Observable.range(0, 5);

var source = Rx.Observable.zip(
  range,
  range.skip(1),
  range.skip(2)
);

var subscription = source.subscribe(
  function (x) {
    console.log('Next: %s', x);
  },
  function (err) {
    console.log('Error: %s', err);
  },
  function () {
    console.log('Completed');
  });

// => Next: 0,1,2
// => Next: 1,2,3
// => Next: 2,3,4
// => Completed

map: Apply projection with each value from source. map is an operator that transforms data by applying a function.
// RxJS v6+
import { from } from 'rxjs';
import { map } from 'rxjs/operators';

//emit (1,2,3,4,5)
const source = from([1, 2, 3, 4, 5]);
//add 10 to each value
const example = source.pipe(map(val => val + 10));
//output: 11,12,13,14,15
const subscribe = example.subscribe(val => console.log(val));
pipe:
A Pipeable Operator is a function that takes an Observable as its input and returns another Observable. the previous Observable stays unmodified.
   You can use pipes to link operators together. Pipes let you combine multiple functions into a single function. The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
pipe was introduced to RxJS in v5.5 to take code that looked like this:

of(1,2,3).map(x => x + 1).filter(x => x > 2);

and turn it into this
of(1,2,3).pipe(
    map(x => x + 1),
    filter(x => x > 2)
  );

Example :
import { filtermap } from 'rxjs/operators';
const nums = of(12345);

// Create a function that accepts an Observable.
const squareOddVals = pipe(
  filter((nnumber=> n % 2 !== 0),
  map(n => n * n)
);

// Create an Observable that will run the filter and map functions
const squareOdd = squareOddVals(nums);

// Suscribe to run the combined functions
squareOdd.subscribe(x => console.log(x));

filter: Emit values that pass the provided condition
// RxJS v6+
import { from } from 'rxjs';
import { filter } from 'rxjs/operators';

//emit (1,2,3,4,5)
const source = from([1, 2, 3, 4, 5]);
//filter out non-even numbers
const example = source.pipe(filter(num => num % 2 === 0));
//output: "Even number: 2", "Even number: 4"
const subscribe = example.subscribe(val => console.log(`Even number: ${val}`));

takeWhile: Emit values until provided expression is false.
// RxJS v6+
import { of } from 'rxjs';
import { takeWhile } from 'rxjs/operators';

//emit 1,2,3,4,5
const source = of(1, 2, 3, 4, 5);
//allow values until value from source is greater than 4, then complete
const example = source.pipe(takeWhile(val => val <= 4));
//output: 1,2,3,4
const subscribe = example.subscribe(val => console.log(val));
Difference between takeWhile() and filter()
// RxJS v6+
import { of } from 'rxjs';
import { takeWhile, filter } from 'rxjs/operators';

// emit 3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3
const source = of(3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3);

// allow values until value from source equals 3, then complete
// output: [3, 3, 3]
source
  .pipe(takeWhile(it => it === 3))
  .subscribe(val => console.log('takeWhile', val));

// output: [3, 3, 3, 3, 3, 3, 3]
source
  .pipe(filter(it => it === 3))
  .subscribe(val => console.log('filter', val));

From: convert various other objects and data types into Observables
// RxJS v6+
import { from } from 'rxjs';

//emit array as a sequence of values
const arraySource = from([1, 2, 3, 4, 5]);
//output: 1,2,3,4,5
const subscribe = arraySource.subscribe(val => console.log(val));

of: Converts the arguments to an observable sequence. link
// RxJS v6+
import { of } from 'rxjs';
//emits any number of provided values in sequence
const source = of(1, 2, 3, 4, 5);
//output: 1,2,3,4,5
const subscribe = source.subscribe(val => console.log(val));

switchMap
switchMap is very similar to flatMap, but with a very important distinction.

in short, every time an event comes down the stream, flatMap will subscribe to (and invoke) a new observable without unsubscribing from any other observable created by a previous event. switchMap on the other hand will automatically unsubscribe from any previous observable when a new event comes down the stream.
https://angular-2-training-book.rangle.io/

catchError: Gracefully handle errors in an observable sequence.

combineLatest: combineLatest combines the values from all the Observables passed as arguments. This happens by subscribing to each Observable in order and, whenever any Observable emits, collecting an array of the most recent values from each Observable. So if we pass an observable to the combineLatest operator, the returned Observable will always emit an array of ‘n’ values. Click here for more

dispatchEvent:

Read more https://github.com/Reactive-Extensions/operators




Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives