Tuesday, 13 October 2020

New Features in C# 6.0

 List of All New Features in C# 6.0

Microsoft has announced some new keywords and some new behavior of C# 6.0 in Visual Studio 2015.
  1. using Static.
  2. Auto property initializer.
  3. Dictionary Initializer.
  4. nameof Expression.
  5. New way for Exception filters.
  6. await in catch and finally block.
  7. Null – Conditional Operator.
  8. Expression – Bodied Methods
  9. Easily format strings – String interpolation
1. using Static
This is a new concept in C# 6.0 that allows us to use any class that is static as a namespace that is very useful for every developer in that code file where we need to call the static methods from a static class like in a number of times we need to call many methods from Convert.ToInt32() or Console.Write(),Console.WriteLine() so we need to write the class name first then the method name every time in C# 5.0. In C# 6.0 however Microsoft announced a new behavior to our cs compiler that allows me to call all the static methods from the static class without the name of the classes because now we need to first use our static class name in starting with all the namespaces.

using System;  
using static System.Convert;  
using static System.Console;  
namespace Project1  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            WriteLine("Enter first value ");  
            int val1 = ToInt32(ReadLine());  
            WriteLine("Value is : {0}", (val1));  
            ReadLine();  
        }  
    }  
}


2. Auto property initializer
Auto property initializer is a new concept to set the value of a property during of property declaration. We can set the default value of a read=only property, it means a property that only has a {get;} attribute. 

class Emp  
{  
    public string Name { getset; }="nitin";  
    public int Age { getset; }=25;  
    public int Salary { get; }=999;  

4. nameof Expression
nameof is new keyword in C# 6.0 and it's very useful from a developer's point of view because when we need to use a property, function or a data member name into a message as a string so we need to use the name as hard-coded in “name” in the string and in the future my property or method's name will be changed so it must change all the messages in every form or every page so it's very complicated to remember that how many number of times you already use the name of them in your project code files and this avoids having hardcoded strings to be specified in our code as well as avoids explicit use of reflection to get the names. Let's have an example.

nameof Returns the name of property in below code.
class Program  
    {  
        static void Main(string[] args)  
        {  
            Employee emp = new Employee();  
            WriteLine("{0} : {1}"nameof(Employee.Id), emp.Id);  
            WriteLine("{0} : {1}"nameof(Employee.Name), emp.Name);  
            WriteLine("{0} : {1}"nameof(Employee.Salary), emp.Salary);  
            ReadLine();  
        }  
    }  
    class Employee  
    {  
        public int Id { getset; } = 101;  
        public string Name { getset; } = "Nitin";  
        public int Salary { getset; } = 9999;  
    }  

5. Exception filters
Exception filters are a new concept for C#. In C# 6.0 they are already supported by the VB compiler but now they are coming into C#. Exception filters allow us to specify a condition with a catch block so if the condition will return true then the catch block is executed only if the condition is satisfied. This is also the best attribute of new C# 6.0 that makes it easy to do exception filtrations in also that type of code contains a large amount of source code. Let's have an example.

class Program  
    {  
        static void Main(string[] args)  
        {  
            int val1 = 0;  
            int val2 = 0;  
            try  
            {  
                WriteLine("Enter first value :");  
                val1 = int.Parse(ReadLine());  
                WriteLine("Enter Next value :");  
                val2 = int.Parse(ReadLine());  
                WriteLine("Div : {0}", (val1 / val2));  
            }  
            catch (Exception exif (val2 == 0)  
            {  
                WriteLine("Can't be Division by zero ☺");  
            }  
            catch (Exception ex)  
            {  
                WriteLine(ex.Message);  
            }  
            ReadLine();  
        }  
    }  

If the user enters an invalid value for division, like 0, then it will throw the exception that will be handled by Exception filtration where you mentioned an if() with catch{} block and the output will be something.

6. Await in catch and finally block
This is a new behavior of C# 6.0 that now we are able to call async methods from catch and also from finally. Using async methods are very useful because we can call then asynchronously and while working with async and await, you may have experienced that you want to put some of the result awaiting either in a catch or finally block or in both. 

public class MyMath  
{  
    public async void Div(int value1int value2)  
    {  
        try  
        {  
            int res = value1 / value2;  
            WriteLine("Div : {0}"res);  
        }  
        catch (Exception ex)  
        {  
            await asyncMethodForCatch();  
        }  
        finally  
        {  
            await asyncMethodForFinally();  
        }  
    }  
    private async Task asyncMethodForFinally()  
    {  
        WriteLine("Method from async finally Method !!");  
    }  

    private async Task asyncMethodForCatch()  
    {  
        WriteLine("Method from async Catch Method !!");  
    }  

7. Null-Conditional Operator
The Null-Conditional operator is a new concept in C# 6.0 that is very beneficial for a developer in a source code file that we want to compare an object or a reference data type with null. So we need to write multiple lines of code to compare the objects in previous versions of C# 5.0 but in C# 6.0 we can write an in-line null-conditional with the ? and ?? operators

class Program  
{  
   static void Main()  
    {  
        Employee emp = new Employee();  
        emp.Name = "Rahul Kumar";  
        emp.EmployeeAddress = new Address()  
        {  
            HomeAddress = "Lucknow",  
            OfficeAddress = "Kanpur"  
        };  
   WriteLine((emp?.Name) + "  " + (emp?.EmployeeAddress?.HomeAddress??"No Address"));  
      ReadLine();  
    }  
}

8. Expression–Bodied Methods
An Expression–Bodied Method is a very useful way to write a function in a new way and also very useful for those methods that can return their value by a single line so we can write those methods by using the “=>“ lamda Operator in C# 6.0

class Program  
    {  
        static void Main(string[] args)  
        {  
            WriteLine(GetTime());  
            ReadLine();  
        }  
static string GetTime()=> "Current Time - " + DateTime.Now.ToString("hh:mm:ss");  
               public int Compare(int aint b=> a == b ? 100 : 200;  

         // Method that call another method  
         public void called() => Display();   
    }  


9. Easily format strings using String interpolation
To easily format a string value in C# 6.0 without any string.Format() method we can write a format for a string using interpolation

    class Program  
    {  
        static void Main()  
        {  
            string FirstName = "Dotnet";  
            string LastName = "Guru";  
  
            // With String Interpolation in C# 6.0  
            string  output"\{FirstName}-\{LastName}";  
            WriteLine(output);   // Dotnet-Guru
            ReadLine();  
        }  



Continue Reading →

Local Storage vs Session Storage vs Cookie

With Advent of Html5 , we have got various option to cache or store info on client browser. Previously we were having only cookies , which were very restrictive and size of cookies was very small. but now we local storage and session storage as well. and cookies has been talk of past , though it is getting used for various purposes. let's talk about all these

LocalStorage
localStorage is a way to store data on the client’s computer. It allows the saving of key/value pairs in a web browser and it stores data with no expiration date. localStorage can only be accessed via JavaScript, and HTML5. However, the user has the ability to clear the browser data/cache to erase all localStorage data.

//Set the value in a local storage object
localStorage.setItem('name'myName);

//Get the value from storage object
localStorage.getItem('name');

//Delete the value from local storage object
localStorage.removeItem(name);//Delete specifice obeject from local storege
localStorage.clear();//Delete all from local storege

Pros:
  1. stores data with no expiration date
  2. storage limit is about 5MB
  3. data is never transferred to the server
Cons:
  1. plaintext, hence not secure by design
  2. limited to string data, hence need to be serialized
  3. can only be read on client-side
Session storage
  1. Stores data only for a session, meaning that the data is stored until the browser (or tab) is closed
  2. data is never transferred to the server
  3. can only be read on client-side
  4. storage limit is about 5-10MB
  5. opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window
sessionStorage.setItem('key''value');
var data = sessionStorage.getItem('key');

Cookie
  1. Stores data that has to be sent back to the server with subsequent XHR requests. Its expiration varies based on the type and the expiration duration can be set from either server-side or client-side .
  2. Cookies are primarily for server-side reading (can also be read on client-side), localStorage and sessionStorage can only be read on client-side.
  3. Size must be less than 4KB.
  4. Cookies can be made secure by setting the httpOnly flag as true for that cookie. This prevents client-side access to that cookie.
Cookies can be updated , set using document.cookie object from browser window object.
document.cookie = "yummy_cookie=choco"
document.cookie = "tasty_cookie=strawberry"
console.log(document.cookie); 
// logs "yummy_cookie=choco; tasty_cookie=strawberry"



Reference: https://medium.com
Continue Reading →

call() , apply() and bind() in JavaScript

In this post, we will be discussing the difference between call(), apply(), and bind() methods of JavaScript functions with simple examples. As functions are also Objects in JavaScript, these 3 methods are used to control the invocation of the function. call() and apply() were introduced in ECMAScript 3 while bind() was added as part of ECMAScript 5.

  Bind( ) 
The bind method creates a new function and sets the this keyword to the specified object.
For example: Let’s suppose we have two person objects.
const john = {
    name: 'John',
    age: 24,
  };
  const jane = {
    name: 'Jane',
    age: 22,
  };

Let’s add a greeting function:
function greeting() {
    console.log(`Hi, I am ${this.name} and I am ${this.age} years old`);
  }

We can use the bind method on the greeting function to bind the this keyword to john and jane objects.
For example:
const greetingJohn = greeting.bind(john);
// Hi, I am John and I am 24 years old
greetingJohn();
const greetingJane = greeting.bind(jane);
// Hi, I am Jane and I am 22 years old
greetingJane();

Here greeting.bind(john) creates a new function with this set to john object, which we then assign to greetingJohn variable. Similarly for greetingJane.

Bind() can also accept arguments: We can also pass extra arguments to the bind method. 
function greeting(lang) {
    console.log(`${lang}: I am ${this.name}`);
  }
  const john = {
    name: 'John'
  };
  const jane = {
    name: 'Jane'
  };
  const greetingJohn = greeting.bind(john'en');
  greetingJohn();
  const greetingJane = greeting.bind(jane'es');
  greetingJane();

In the above example, the bind method creates a new function with certain parameters predefined (lang in this case) and this keyword set to the john and jane objects.

 Call ( ) 
The call method sets the this inside the function and immediately executes that function.

The difference between call() and bind() is that the call() sets the this keyword and executes the function immediately and it does not create a new copy of the function, while the bind() creates a copy of that function and sets the this keyword.

function greeting() {
    console.log(`Hi, I am ${this.name} and I am ${this.age} years old`);
  }
  const john = {
    name: 'John',
    age: 24,
  };
  const jane = {
    name: 'Jane',
    age: 22,
  };
  // Hi, I am John and I am 24 years old
  greeting.call(john);
  // Hi, I am Jane and I am 22 years old
  greeting.call(jane);


Above example is similar to the bind() example except that call() does not create a new function. We are directly setting the this keyword using call().

Call () can also accept arguments: Call() also accepts a comma-separated list of arguments. 

function greet(greeting) {
    console.log(`${greeting}, I am ${this.name} and I am ${this.age} years old`);
  }
  const john = {
    name: 'John',
    age: 24,
  };
  const jane = {
    name: 'Jane',
    age: 22,
  };
  // Hi, I am John and I am 24 years old
  greet.call(john'Hi');
  // Hi, I am Jane and I am 22 years old
  greet.call(jane'Hello');


 Apply ( ) 
The apply() method is similar to call(). The difference is that the apply() method accepts an array of arguments instead of comma separated values.

function greet(greetinglang) {
    console.log(lang);
    console.log(`${greeting}, I am ${this.name} and I am ${this.age} years old`);
  }
  const john = {
    name: 'John',
    age: 24,
  };
  const jane = {
    name: 'Jane',
    age: 22,
  };
  // Hi, I am John and I am 24 years old
  greet.apply(john, ['Hi''en']);
  // Hi, I am Jane and I am 22 years old
  greet.apply(jane, ['Hola''es']);

  1. bind: It binds the function with provided value and context but it does not executes the function. To execute function you need to call the function.
  2. call: It executes the function with provided context and parameter.
  3. apply: It executes the function with provided context and parameter as array.
Conclusion
We have learned that how this keyword behaves differently in JavaScript than in other object-oriented languages. The call, bind and apply methods can be used to set the this keyword independent of how a function is called.
 The bind method creates a copy of the function and sets the this keyword, while the call and apply methods sets the this keyword and calls the function immediately.
Reference: https://blog.bitsrc.io/https://www.codementor.io


Continue Reading →

Monday, 12 October 2020

HTTP Methods

REST APIs enable you to develop any kind of web application having all possible CRUD (create, retrieve, update, delete) operations. REST guidelines suggest using a specific HTTP method on a particular type of call made to the server (though technically it is possible to violate this guideline, yet it is highly discouraged).

Use below-given information to find a suitable HTTP method for the action performed by API.

  1. HTTP GET
  2. HTTP POST
  3. HTTP PUT
  4. HTTP DELETE
  5. HTTP PATCH

GET: GET method is used to retrieve data from a server at the specified resource. For example, say you have an API with a /users endpoint. Making a GET request to that endpoint should return a list of all available users.

For any given HTTP GET API, if the resource is found on the server, then it must return HTTP response code 200 (OK) – along with the response body, which is usually either XML or JSON content (due to their platform-independent nature).

Since a GET request is only requesting data and not modifying any resources, it's considered a safe and idempotent method.

Idempotence means that applying an operation once or applying it multiple times has the same effect. Examples: Multiplication by zero. No matter how many times you do it, the result is still zero.

POST: In web api, POST requests are used to send data to the API server to create or update a resource. The data sent to the server is stored in the request body of the HTTP request.

The simplest example is a contact form on a website. When you fill out the inputs in a form and hit Send, that data is put in the response body of the request and sent to the server. This may be JSON, XML, or query parameters.

Ideally, if a resource has been created on the origin server, the response SHOULD be HTTP response code 201 (Created) and contain an entity which describes the status of the request and refers to the new resource.

It's worth noting that a POST request is non-idempotent. It mutates data on the backend server (by creating or updating a resource), as opposed to a GET request which does not change any data.

PUT: Similar to POST, PUT requests are used to send data to the API to update or create a resource. The difference is that PUT requests are idempotent. So if you send a request multiple times, that should be equivalent to single request modification. In contrast, calling a POST request repeatedly make have side effects of creating the same resource multiple times.

Generally, when a PUT request creates a resource the server will respond with a 201 (Created), and if the request modifies existing resource the server will return a 200 (OK) or 204 (No Content).

The difference between the POST and PUT APIs can be observed in request URIs. POST requests are made on resource collections, whereas PUT requests are made on a single resource.

PATCH: HTTP PATCH requests are to make partial update on a resource. If you see PUT requests also modify a resource entity, so to make more clear – PATCH method is the correct choice for partially updating an existing resource, and PUT should only be used if you’re replacing a resource in its entirety.

DELETE: As the name applies, DELETE APIs are used to delete resources.

A successful response of DELETE requests should be HTTP response code 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has been queued, or 204 (No Content) if the action has been performed but the response does not include an entity.

DELETE operations are idempotent. If you DELETE a resource, it’s removed from the collection of resources. Repeatedly calling DELETE API on that resource will not change the outcome – however, calling DELETE on a resource a second time will return a 404 (NOT FOUND) since it was already removed. Some may argue that it makes the DELETE method non-idempotent. It’s a matter of discussion and personal opinion.

PUT VS PATCH:

When a client needs to replace an existing Resource entirely, they can use PUT. When they’re doing a partial update, they can use HTTP PATCH.

For instance, when updating a single field of the Resource, sending the complete Resource representation can be cumbersome and uses a lot of unnecessary bandwidth. In such cases, the semantics of PATCH make a lot more sense.

Glossary:- 

Safe Methods

As per HTTP specification, the GET and HEAD methods should be used only for retrieval of resource representations – and they do not update/delete the resource on the server. Both methods are said to be considered “safe“.

This allows user agents to represent other methods, such as POST, PUT and DELETE, in a unique way so that the user is made aware of the fact that a possibly unsafe action is being requested – and they can update/delete the resource on server and so should be used carefully.

Idempotent Methods

The term idempotent is used more comprehensively to describe an operation that will produce the same results if executed once or multiple times. Idempotence is a handy property in many situations, as it means that an operation can be repeated or retried as often as necessary without causing unintended effects. With non-idempotent operations, the algorithm may have to keep track of whether the operation was already performed or not.

In HTTP specification, The methods GET, HEAD, PUT and DELETE are declared idempotent methods.

https://restfulapi.net/idempotent-rest-apis/


Continue Reading →

Sunday, 11 October 2020

Angular: ViewChild and ContentChild

 Essentially ViewChild and ContentChild are used for component communication in Angular. Therefore, if a parent component wants access of child component then it uses ViewChild or ContentChild.

Any component, directive, or element which is part of a template is ViewChild and any component or element which is projected in the template is ContentChild.

ViewChild
If you want to access following inside the Parent Component, use @ViewChild decorator of Angular.
  1. Child Component
  2. Directive
  3. DOM Element
ViewChild returns the first element that matches the selector. 

Let us assume that we have a component MessageComponent as shown in the below listing:
import { ComponentInput } from '@angular/core';
@Component({
    selector: 'app-message',
    template: `
<h2>{{message}}</h2>
 
`
})
export class MessageComponent {
    @Input() messagestring;
  
}

We are using MessageComponent inside AppComponent as shown in below listing:

import { ComponentOnInit } from '@angular/core';
@Component({
  selector: 'app-root',
template:'<div><h1>Messages</h1><app-message [message]='message'></app-message></div>'
})
export class AppComponent implements OnInit {
    messageany;
    ngOnInit() {
        this.message = 'Hello World !';
    }
}

In application, you will get the output as below:

Messages
Hello World!

Here, MessageComponent has become child of AppComponent. Therefore, we can access it as a ViewChild. Definition of ViewChild is:

“The Child Element which is located inside the component template”,

Here MessageComponent is located inside template of AppComponent, so it can be accessed as ViewChild.

export class AppComponent implements OnInitAfterViewInit {
    messageany;
    @ViewChild(MessageComponentmessageViewChildMessageComponent;
  
    ngAfterViewInit() {
        console.log(this.messageViewChild);
    }
  
    ngOnInit() {
        this.message = 'Hello World !';
    }
}

We need to do following tasks:
  1. Import ViewChild and AfterViewInit from @angular/core
  2. Implement AfterViewInit life cycle hook to component class
  3. Create a variable with decorator @ViewChild
  4. Access that inside ngAfterViewInit life cycle hook
ContentChild
Let us start with understanding about ContnetChild. Any element which is located inside the template, is ContnetChild.

To understand it let us consider MessageContainerComponent.

import { Component } from '@angular/core';
@Component({
    selector: 'app-messagecontainer',
    template: `<div> 
    <h3>{{greetMessage}}</h3>
     <ng-content select="app-message"></ng-content>
    </div>`
})
export class MessageContainerComponent {
    greetMessage = 'Ignite UI Rocks!';
}

In this component, we are using Angular Content Projection.

Any element or component projected inside becomes a ContentChild. If you want to access and communicate with MessageComponent projected inside MessageContainerComponent, you need to read it as ContnetChild.

Before we go ahead and learn to use ContentChild, first see how MessageContainerComponent is used and MessageComponent is projected.

import { ComponentOnInit } from '@angular/core';
@Component({
    selector: 'app-root',
    template: `<div>
  <app-messagecontainer>
  <app-message [message]='message'></app-message>
  </app-messagecontainer>
  </div>`
})
export class AppComponent implements OnInit {
    messageany;
    ngOnInit() {
        this.message = 'Hello World !';
    }
}

As you see in the above listing that in the AppComponent, we are using MessageContainerComponent and passing MessageComponent to be projected inside it. Since MessageComponent is used in MessageContainerComponent using content projection, it becomes ContentChild.

Since, MessageComponnet is projected and being used inside template of MessageContainerComponent, it can be used as ContentChild as shown in the below listing:

import { ComponentContentChildAfterContentInit } from '@angular/core';
import { MessageComponent } from './message.component';
  
@Component({
    selector: 'app-messagecontainer',
    template: `<div> 
<h3>{{greetMessage}}</h3>
    <ng-content select="app-message"></ng-content>
    </div>  `
})
export class MessageContainerComponent implements AfterContentInit {
    greetMessage = 'Ignite UI Rocks!';
    @ContentChild(MessageComponentMessageComponnetContentChildMessageComponent;
    ngAfterContentInit() {
        console.log(this.MessageComponnetContentChild);
    }
}

We need to do the following tasks:
  • Import ContnetChild and AfterContnetInit from @angular/core
  • Implement AfterContnetInit life cycle hook to component class
  • Create a variable with decorator @ContnetChild
  • Access that inside ngAfterContnetInit life cycle hook
In the output console you will find a reference of MessageComponent, also if you can notice that __proto__ of MessageComponent is set to Object.

You can modify the ContentChild property inside ngAfterContentInit life cycle hook of the component. 

ViewChildren: Returns the specified elements or directives from the view DOM as QueryList.
The return type of ViewChildren is QueryList.
    QueryList is just a fancy name for an object that stores a list of items. What is special about this object is when the state of the application changes Angular will automatically update the object items for you.

ContentChildren: Returns the specified elements or directives from the content DOM as QueryList

ViewChildren vs ContentChildren —
  • ViewChildren don’t include elements that exist within the ng-content tag.
  • ContentChildren includes only elements that exists within the ng-content tag.


Continue Reading →

Typescript: Iterators (for..in and for..of)

 for..of statements

for..of loops over an iterable object. Here is a simple for..of loop on an array:

let someArray = [1"string"false];

for (let entry of someArray) {
  console.log(entry); // 1, "string", false
}


for..of vs. for..in statements

Both for..of and for..in statements iterate over lists; the values iterated on are different though, for..in returns a list of keys on the object being iterated, whereas for..of returns a list of values of the numeric properties of the object being iterated.

Here is an example that demonstrates this distinction:

let list = [456];

for (let i in list) {
  console.log(i); // "0", "1", "2",
}

for (let i of list) {
  console.log(i); // "4", "5", "6"
}


Another distinction is that for..in operates on any object; it serves as a way to inspect properties on this object. for..of on the other hand, is mainly interested in values of iterable objects. Built-in objects like Map and Set implement Symbol.iterator property allowing access to stored values.

let pets = new Set(["Cat""Dog""Hamster"]);
pets["species"] = "mammals";

for (let pet in pets) {
  console.log(pet); // "species"
}

for (let pet of pets) {
  console.log(pet); // "Cat", "Dog", "Hamster"
}


Continue Reading →

Saturday, 10 October 2020

Javascript: Map and Set

Now we’ve learned about the following complex data structures:

  • Objects for storing keyed collections.
  • Arrays for storing ordered collections.

But that’s not enough for real life. That’s why Map and Set also exist.

 Map 

Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

Methods and properties are:

  1. new Map() – creates the map.
  2. map.set(key, value) – stores the value by the key.
  3. map.get(key) – returns the value by the key, undefined if key doesn’t exist in map.
  4. map.has(key) – returns true if the key exists, false otherwise.
  5. map.delete(key) – removes the value by the key.
  6. map.clear() – removes everything from the map.
  7. map.size – returns the current element count.

For instance:

let map = new Map();

map.set('1''str1');   // a string key
map.set(1'num1');     // a numeric key
map.set(true'bool1'); // a boolean key


Map can also use objects as keys.

let john = { name: "John" };
let map = new Map();

map.set(john'str1');   // a string key


Every map.set call returns the map itself, so we can “chain” the calls:

map.set('1''str1')
  .set(1'num1')
  .set(true'bool1');


Iteration over Map

For looping over a map, there are 3 methods:

  • map.keys() – returns an iterable for keys,
  • map.values() – returns an iterable for values,
  • map.entries() – returns an iterable for entries [key, value],

let recipeMap = new Map([
    ['cucumber'500],
    ['tomatoes'350],
    ['onion',    50]
  ]);
  
  // iterate over keys (vegetables)
  for (let vegetable of recipeMap.keys()) {
    alert(vegetable); // cucumber, tomatoes, onion
  }
  
  // iterate over values (amounts)
  for (let amount of recipeMap.values()) {
    alert(amount); // 500, 350, 50
  }
  
  // iterate over [key, value] entries
  for (let entry of recipeMap) { // the same as of recipeMap.entries()
    alert(entry); // cucumber,500 (and so on)
  }

// iterate with foreach
recipeMap.forEach(function(valuekey) {
    console.log(key + ' -> ' + value);
  });


Set 

A Set is a special type collection – “set of values” (without keys), where each value may occur only once.

Its main methods are:

  1. new Set(iterable) – creates the set, and if an iterable object is provided (usually an array), copies values from it into the set.
  2. set.add(value) – adds a value, returns the set itself.
  3. set.delete(value) – removes the value, returns true if value existed at the moment of the call, otherwise false.
  4. set.has(value) – returns true if the value exists in the set, otherwise false.
  5. set.clear() – removes everything from the set.
  6. set.size – is the elements count.

The main feature is that repeated calls of set.add(value) with the same value don’t do anything. That’s the reason each value appears in a Set only once.

For example, we have visitors coming, and we’d like to remember everyone. But repeated visits should not lead to duplicates. A visitor must be “counted” only once.

Set is just the right thing for that:

let set = new Set();

let john = { name: "John" };
let pete = { name: "Pete" };
let mary = { name: "Mary" };

// visits, some users come multiple times
set.add(john);
set.add(pete);
set.add(mary);
set.add(john);
set.add(mary);

// set keeps only unique values
alertset.size ); // 3

for (let user of set) {
  alert(user.name); // John (then Pete and Mary)
}

The alternative to Set could be an array of users, and the code to check for duplicates on every insertion using arr.find. But the performance would be much worse, because this method walks through the whole array checking every element. Set is much better optimized internally for uniqueness checks.








Continue Reading →

Monday, 5 October 2020

ASP.NET Core Dependency Injection

How can we inject the service dependency into the controller?

There are three easy steps to add custom service as a dependency on the controller.

Step 1: Create the service

 public interface IHelloWorldService
 {
  string SaysHello();
 }
 
 public class HelloWorldServiceIHelloWorldService
 {
  public string SaysHello()
  { 
   return "Hello ";
  }
 }

Step 2: Add this service to Service container (service can either added by singleton, transient or scoped)

public void ConfigureServices(IServiceCollection services)
{
    ….
    …
    services.AddTransient<IHelloWorldServiceHelloWorldService>();
}

Step 3: Use this service as a dependency in the controller

public class HomeControllerController
{
    IHelloWorldService _helloWorldService;
    public HomeController(IHelloWorldService helloWorldService)
    {
    _helloWorldService = helloWorldService;
    }
}


Service lifetimes

Services can be registered with one of the following lifetimes:

  1. Transient
  2. Scoped
  3. Singleton

Singleton

ASP.NET Core will create and share a single instance of the service through the application life. The service can be added as a singleton using AddSingleton method of IServiceCollection. ASP.NET Core creates service instance at the time of registration and subsequence request use this service instance. Here, we do not require to implement Singleton design pattern and single instance maintained by the ASP.NET Core itself.

services.AddSingleton<IHelloWorldServiceHelloWorldService>();


Transient

Transient lifetime services are created each time they're requested from the service container. This lifetime works best for lightweight, stateless services. Register transient services with AddTransient.

In apps that process requests, transient services are disposed at the end of the request.

services.AddTransient<IHelloWorldServiceHelloWorldService>();


Scoped

Scoped lifetime services are created once per client request (connection). Register scoped services with AddScoped.

In apps that process requests, scoped services are disposed at the end of the request.

When using Entity Framework Core, the AddDbContext extension method registers DbContext types with a scoped lifetime by default.

services.AddScoped<IHelloWorldServiceHelloWorldService>();


Reference: https://docs.microsoft.com

Continue Reading →

Topics

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

Dotnet Guru Archives