Tuesday, August 11, 2020

What are the Differences between ASP.NET WEB API and .NET Core WEB API

 ASP.NET Core

ASP.NET Core is an open-source, cross-platform framework for building modern, cloud-based web apps on Windows, macOS, or Linux.

ASP.NET Core provides the following benefits:


The following table compares ASP.NET Core to ASP.NET 4.x.

FRAMEWORK SELECTION
ASP.NET CoreASP.NET 4.x
Build for Windows, macOS, or LinuxBuild for Windows
Razor Pages is the recommended approach to create a Web UI as of ASP.NET Core 2.x. See also MVC, Web API, and SignalR.Use Web Forms, SignalR, MVC, Web API, WebHooks, or Web Pages
Multiple versions per machineOne version per machine
Develop with Visual Studio, Visual Studio for Mac, or Visual Studio Code using C# or F#Develop with Visual Studio using C#, VB, or F#
Higher performance than ASP.NET 4.xGood performance
Use .NET Core runtimeUse .NET Framework runtime

What are the Differences between Angular and React

 Framework Vs. Library

Angular is a complete framework while React is a JavaScript Library. Angular uses a two-directional data flow process where it updates the Real DOM directly while React updates only the Virtual DOM and is concerned with the one-directional data flow. While React can be bundled with other programming libraries, Angular is a complete solution in itself. For uni-directional data flow, React needs to be augmented by Redux.

The Major Differences Between React and Angular

Data Binding

Angular allows two-way data binding while React allows one-way data binding.

Two-way data binding means that any changes you make to the model affect the view, and vice versa.

One-way data binding means any changes you make to the model affect the view, but not the other way around. This way, the data only flows in one direction.

These are also called Bidirectional and Unidirectional data flows, respectively.

DOM Usage

DOM is the Data Object Model of a web app. You can either use a regular DOM or create a virtual DOM.

Angular uses the browser's DOM, while React uses a virtual DOM.

A virtual DOM is a simplified version of the DOM. By using a virtual DOM, you can change any element very quickly and without needing to render the whole DOM. It drastically changes the performance from good to excellent.

Imagine the difference in performance in needing to render all 100 items when just a single item is changed, then just rendering a single changed item and not rendering the rest.

Using the virtual DOM is quite the buzz nowadays because it is faster, and speed is key!

Language

Angularis a JS framework by nature, but is built to use TypeScript. React, on the other hand, is a JavaScript library as well, but recommends using JSX.

The difference lies here: TypeScript is a superset of JavaScript while JSX is Javascript but with extended XML syntax.

If you want the best of Angular or React, you must learn to use TypeScript or JSX, which brings me to my next point.

The creators of JSX claim it's faster, safer, and easier than JS

Sunday, August 2, 2020

CRUD Operation in ASP.NET Core Web API with Entity Framework Core

Introduction:

This article will explain how to perform CRUD (Create, Read, Update and Delete) operations in ASP.NET Core Web API using Entity Framework Core. We will see step by step instructions about CRUD operations in ASP.NET Core Web API. In this demonstration, we will use the Database First Approach where our database will be ready before creating an actual code.

Prerequisites:

1. Visual Studio 2019.
2. Sql Server 2014.

Let's start practical demonstration, below code snippet is Employee Model class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DotNetCoreAPI.Models
{
    public class Employee
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public bool IsComplete { get; set; }
    }
}

And create context class for Employee.

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DotNetCoreAPI.Models
{
    public class EmpContext : DbContext
    {
        public EmpContext(DbContextOptions<EmpContext> options)
            :base(options)
        {
        }

        public DbSet<Employee> Employees { get; set; }
    }
}

Register database context.

In ASP.NET Core, services such as the DB context must be registered with the dependency injection (DI) container. The container provides the service to controllers.

Update Startup.cs with the following highlighted code:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNetCoreAPI.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using Microsoft.EntityFrameworkCore;

namespace DotNetCoreAPI
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string con = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=VijayDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";         
            services.AddDbContext<EmpContext>(opt =>
               opt.UseSqlServer(con));
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}


  • Right-click the Controllers folder.

  • Select Add > New Scaffolded Item.

  • Select API Controller with actions, using Entity Framework, and then select Add.

  • In the Add API Controller with actions, using Entity Framework dialog:

    • Select TodoItem (TodoApi.Models) in the Model class.
    • Select TodoContext (TodoApi.Models) in the Data context class.
    • Select Add.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DotNetCoreAPI.Models;

namespace DotNetCoreAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeesController : ControllerBase
    {
        private readonly EmpContext _context;

        public EmployeesController(EmpContext context)
        {
            _context = context;
        }

        // GET: api/Employees
        
        [HttpGet("EmployeeList")]
        public async Task<ActionResult<IEnumerable<Employee>>> GetEmployees()
        {
            return await _context.Employees.ToListAsync();
        }

        // GET: api/Employees/5
        
        [HttpGet("EmpById/{id}")]
        public async Task<ActionResult<Employee>> GetEmployee(long id)
        {
            var employee = await _context.Employees.FindAsync(id);

            if (employee == null)
            {
                return NotFound();
            }

            return employee;
        }

        // PUT: api/Employees/5
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPut("Update/{id}")]       
        public async Task<IActionResult> PutEmployee(long id, Employee employee)
        {
            if (id != employee.Id)
            {
                return BadRequest();
            }

            _context.Entry(employee).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmployeeExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Employees
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPost("Insert")]       
        public async Task<ActionResult<Employee>> PostEmployee(Employee employee)
        {
            _context.Employees.Add(employee);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetEmployee), new { id = employee.Id }, employee);
        }

        // DELETE: api/Employees/5
        [HttpDelete("RemoveEmp/{id}")]
        public async Task<ActionResult<Employee>> DeleteEmployee(long id)
        {
            var employee = await _context.Employees.FindAsync(id);
            if (employee == null)
            {
                return NotFound();
            }

            _context.Employees.Remove(employee);
            await _context.SaveChangesAsync();

            return employee;
        }

        private bool EmployeeExists(long id)
        {
            return _context.Employees.Any(e => e.Id == id);
        }
    }
}

Saturday, March 14, 2020

What is difference between Var, let and const in ES6 or javascript.


Difference between Var, let and const in ES6 or javascript.
A lot of new features came with ES6 and it's assumed that a lot of JavaScript developers have become familiar with and have started using these features.
One of the features that came with ES6 is addition of let and const which can be used for variable declaration. The question now is, what makes them different from our good of var which has been in use? If you are still not clear about this,
Here I am going to explain to you.

In this post, var, let and const will be discussed with respect to their scope, use and hoisting. As you read, take note of the differences between them.

VAR
Before the advent of ES6, var declarations ruled as King. There are issues associated with variables declared with var though. That is why it was necessary for new ways to declare variables to emerge. First though, let us get to understand var more before we discuss one of such issues.

Scope of var

Scope essentially means where these variables are available for use. var declarations are globally scoped or function/locally scoped. It is globally scoped when a var variable is declared outside a function. This means that any variable that is declared with var outside a function block is available for use in the whole window. var is function scoped when it is declared within a function. This means that it is available and can be accessed only within that function.

To understand in detail, look at below example.

var global = "hey global"; 
    function newFunction() {
        var local = "hey local";
    }

Here, global is globally scoped because it exists outside a function while local is function scoped. So we cannot access the variable local outside of a function. So if we do below code:

var global = "hey hi"; 
    function newFunction() {
        var local = "hello";
    }
    console.log(local); // error: local is not defined

We'll get an error which is as a result of local not being available outside the function.


var variables can be re-declared and updated

We can do within the same scope we won’t get any error.

   var global = "hey hi";
   var global = "say Hello instead";

and also below code.

var global = "hey hi";
 greeter = "say Hello instead";

Hoisting of var
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

  console.log (global);
    var global = "say hello";


It is interpreted as this

   var global;
    console.log(global); //global is undefined
    global = "say hello"

So var variables are hoisted to the top of its scope and initialized with a value of undefined.


Problem with var

There's a weakness that comes with var. I'll use the example below to explain this.

var global = "hey hi";
    var times = 4;
    if (times > 3) {
        var global = "say Hello instead";
    }
    console.log(global) //"say Hello instead"

So, since times > 3 returns true, global is redefined to "say Hello instead". While this is not a problem if you knowingly want global to be redefined, it becomes a problem when you do not realize that a variable global has already been defined before.

If you have use global in other parts of your code, you might be surprised at the output you might get. This might cause a lot of bugs in your code. This is why the let and const is necessary.

LET

let is preferred for variable declaration now. It's no surprise as it comes as an improvement to the var declarations. It also solves this problem that was raised in the last subheading. Let's consider why this is so.

let is block scoped

A block is chunk of code bounded by {}. A block lives in curly braces. Anything within curly braces is a block. So a variable declared in a block with the let is only available for use within that block. Let me explain this with an example.

let global = "say Hi";
   let times = 4; 
   if (times > 3) {
        let local = "say Hello instead";
        console.log(local);//"say Hello instead"
    }
   console.log(local) // local is not defined

We see that using local outside its block(the curly braces where it was defined) returns an error. This is because let variables are block scoped .

let can be updated but not re-declared.

Just like var, a variable declared with let can be updated within its scope. Unlike var, a let variable cannot be re-declared within its scope. So while this will work,
let global = "say Hi";
    global = "say Hello instead";

this will return an error.

let global = "say Hi";
    let global = "say Hello instead";//error: Identifier ‘global ‘has already been declared

However, if the same variable is defined in different scopes, there will be no error.


let global = "say Hi";

    if (true) {
        let global = "say Hello instead";
        console.log(global);//"say Hello instead"
    }
    console.log(global);//"say Hi"

Why is there no error? This is because both instances are treated as different variables since they have different scopes.
This fact makes let a better choice than var. When using let, you don't have to bother if you have used a name for a variable before as a variable exists only within its scope. Also, since a variable cannot be declared more than once within a scope, then the problem discussed earlier that occurs with var does not occur.

Hoisting of let
Just like var, let declarations are hoisted to the top. Unlike var which is initialized as undefined, the let keyword is not initialized. So if you try to use a let variable before declaration, you'll get a Reference Error.

CONST

Variables declared with the const maintain constant values. const declarations share some similarities with let declarations.
const declarations are block scoped
Like let declarations, const declarations can only be accessed within the block it was declared.
const cannot be updated or re-declared
This means that the value of a variable declared with const remains the same within its scope. It cannot be updated or re-declared. So if we declare a variable with const, we can neither do this
const global = "say Hi";
    global = "say Hello instead";//error : Assignment to constant variable.
nor this
const global= "say Hi";
    const global= "say Hello instead";//error : Identifier 'global' has already been declared

Every const declaration therefore, must be initialized at the time of declaration.
This behavior is somehow different when it comes to objects declared with const. While a const object cannot be updated, the properties of this objects can be updated. Therefore, if we declare a const object as this

  const global = {
        message : "say Hi",
        times : 4
    }

while we cannot do this

const global = {
        words : "Hello",
        number : "five"
    }//error :  Assignment to constant variable.

we can do this

global.message = "say Hello instead";

This will update the value of global.message without returning errors.

Hoisting of const

Just like let, const declarations are hoisted to the top but are not initialized.

Finally, Differences between var, let and const.

  1. var declarations are globally scoped or function scoped while let and const are block scoped.
  2. var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared.
  3. They are all hoisted to the top of their scope but while varvariables are initialized with undefined, let and const variables are not initialized.
  4. While var and let can be declared without being initialized, const must be initialized during declaration.


Wednesday, March 11, 2020

How to find most repeated character in given string using c#

The below code to  find most repeated character in given string in c#.


using System;

namespace MostRepeatedCharacter
{
    class Program
    {
        static Char GetMostRepeatedChar(string str)
        {
             // declare integer Array to count number of most repeated characters. 
            int[] count = new int[256];
            int Max = 0;
            Char result = Char.MinValue;

         // Traversing each character from left to right.
            foreach (Char c in str)
            {
               // To check if empty space and collecting repeated characters here.
                if (c !=' ' && ++count[c] > Max)
                {
                    Max = count[c];

                    result = c;
                }
            }
            return result;
        }
        static void Main(string[] args)
        {
            
            string str = "SWISS";
            Console.WriteLine("Most repeated character '{0}'", GetMostRepeatedChar(str));
            Console.ReadLine();
        }
    }
}


Out put : Most repeated character: S.