Monday, 30 October 2023

Arrays in C#

In C#, an array is a collection of elements of the same type that are stored in contiguous memory locations and can be accessed using an index. Arrays provide an efficient way of storing and accessing a fixed number of elements.

 Create an array 

There are multiple ways to create an array in C#. Here are a few examples.

Using the new keyword

  int[] numbers = new int[5];

The above code snippet creates an array called "intArray" to hold five integers. However, the elements of the Array are not yet initialized, and their values are undefined.

Using the new keyword with an array initializer

Arrays can also be initialized when they are declared by providing a list of comma-separated values enclosed in curly braces {}

  int[] intArray = new int[] {1, 2, 3, 4, 5};

  // or Simply
 
  int[] intArray = {1, 2, 3, 4, 5};

This creates an array called "intArray" with five elements and assigns the values 1, 2, 3, 4, and 5 to the elements of the Array.

Using the var keyword

  var myArray = new int[] {1, 2, 3, 4, 5};

This creates an array; the array type is inferred from the initializer, and the Array's name is myArray.

How To Sort Array In C#

The simplest way to sort an array in C# is using Array.Sort method. The Array.Sort method takes a one-dimensional array as an input and sorts the array elements in the ascending order.

The following code snippet creates an array of integers.

  int[] intArray = new int[] { 9, 2, 4, 3, 1, 5 };

The Array.Sort method takes array as an input and sorts the array in ascending order.

  Array.Sort(intArray);

To sort an array in descending order, we can use Sort.Reverse method. This method also takes an array as an input and sorts its elements in descending order. The following code snippet reverses an array.

  Array.Reverse(intArray);

Sort an Array of Int in C#

Here is the complete code that creates an array of integers and sorts in ascending and descending orders using Array.Sort and Array.Reverse methods.

static void Main(string[] args) {
    // Array of integers
    int[] intArray = new int[] {
        9,
        2,
        4,
        3,
        1,
        5
    };
    Console.WriteLine("Original array");
    foreach(int i in intArray) {
        Console.Write(i + " ");
    }
    Console.WriteLine();
    // Sort array in ASC order
    Console.WriteLine("Sorted array in ASC order");
    Array.Sort(intArray);
    foreach(int i in intArray) {
        Console.Write(i + " ");
    }
    Console.WriteLine();
    Console.WriteLine("Sorted array in DESC order");
    // Sort Array in DESC order
    Array.Reverse(intArray);
    foreach(int i in intArray) {
        Console.Write(i + " ");
    }
    Console.WriteLine();

The output of the above code is below where first it prints the original array, followed by the sorted array in ASC and DESC order respectively.


Sort an Array of Strings in C#

Now let’s sort an array of strings in C#. Sorting an array of strings is like sorting an array of int. The Array.Sort method takes an input value of an array of strings. The following code example shows how to sort an array of strings in ascending and descending orders using C#.

  // Array of strings
string[] strArray = new string[] { "Mahesh", "David", "Allen", "Joe", "Monica" };
Console.WriteLine();
Console.WriteLine("Original array");
foreach (string str in strArray)
{
    Console.Write(str + " ");
}
Console.WriteLine();
// Sort array
Array.Sort(strArray);
// Read array items using foreach loop
foreach (string str in strArray)
{
    Console.Write(str + " ");
}
Console.WriteLine();
Array.Reverse(strArray);
foreach (string str in strArray)
{
    Console.Write(str + " ");
}
Console.WriteLine();

The output of the above code displays original array, sorted array in the ascending order, and sorted array in the descending order.


Sort a Range of Elements In An Array

The Sort.Array method allows you to sort a range of elements within an array. For example, if an array has 11 elements but what if you want to sort only 1st to next 6 elements in the array? You can use that by passing the first starting index of the element followed by the number of elements to be sorted.

// Array of integers
int[] intArray = new int[] { 9, 2, 4, 3, 1, 5, 6, 9, 5, 7, 1, 0};
// Sort array from 1st element to 6th element. Skip 0th element.
Array.Sort(intArray, 1, 6);
foreach (int i in intArray)
{
    Console.Write(i + " ");
}

The output looks like the following where you can see only 6 elements are sorted after skipping the first element of the array.

9 1 2 3 4 5 6 9 5 7 1 0

Note that this sorting applies to all types of arrays not just integers.


Continue Reading →

Sunday, 8 October 2023

HTML5 Features

 Top HTML5 Features are:

HTML stands for Hyper Text markup language, and HTML 5 is the 5th version of it. A lot of dynamic parameters were missing in the HTML for which we have to depend on third-party libraries, however, in the latest version of HTML it has become a lot easier for building a dynamic website.

Browser support for HTML5

All modern browsers, including Google Chrome, Mozilla Firefox, Opera Mini, Microsoft Edge, and Apple Safari, support HTML 5 in all of their features. Because HTML 5 capabilities are not adequately supported by earlier browser versions, developers must create alternative content to ensure cross-browser compatibility. 

below are the list of Top HTML5 Features, which are described in detail below:

  1. Semantic Elements
  2. Audio and Video Support
  3. Canvas Elements
  4. Geolocation API
  5. Local Storage
  6. Responsive Images
  7. Web Workers
  8. Drag and Drop API
  9. Form Enhancements
  10. Web Sockets
  11. Micro Data
  12. Cross Document Messaging
For details, visit website

Continue Reading →

Saturday, 30 September 2023

Web API Versioning

What Is API Versioning?

API versioning is the process of iterating different versions of your API.

Why Is API Versioning Required?

While working on an existing application or creating a new one, we may create multiple APIs that may be consumed by many clients. When the business has started to grow and expand, new requirements arise. Due to this, we may need to provide more functionality in the existing APIs. However, existing Web API can be consumed by many clients so how to implement the new feature without impacting the existing consumers? We can solve this problem by versioning our API.

There are some common ways to version a REST API.

1. Versioning through URI

The most commonly used versioning is in which we can add a version to the API base URL.

Example:

http://api-demo.example.com/api/1/employee

This approach is easy to implement and understand, as clients can simply request the desired version of the API by specifying the corresponding URL. Here are the steps to implement URL-based versioning in ASP.NET Core:

Install the Microsoft.AspNetCore.Mvc.Versioning NuGet package in your ASP.NET Core project. You can do this using the Package Manager Console or the NuGet Package Manager in Visual Studio.

In the ConfigureServices method of your Startup.cs file, configure the API versioning options by adding the following code:

  services.AddApiVersioning(options =>
    {
        options.DefaultApiVersion = new ApiVersion(1, 0);
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.ReportApiVersions = true;
        options.ApiVersionReader = new UrlSegmentApiVersionReader();
    });

This code configures the default API version to be 1.0, assumes the default version when not specified in the URL, reports the API versions in the response headers, and uses the URL segment as the versioning source.

In your controller, add the ApiVersion attribute to specify the supported API versions for each action method. For example:

  [ApiController]
  [Route("api/v{version:apiVersion}/[controller]")]
  [ApiVersion("1.0")]
  public class MyController : ControllerBase
  {
      [HttpGet]
      public IActionResult Get()
      {
          return Ok("Version 1.0");
      }
     
      [HttpGet, MapToApiVersion("2.0")]
      public IActionResult GetV2()
      {
          return Ok("Version 2.0");
      }
  }

This code specifies that the controller supports version 1.0 of the API, and that the GetV2 action method supports version 2.0. The [MapToApiVersion] attribute maps the action method to version 2.0.

Test the API by sending requests to the corresponding URLs. For example:

http://localhost:5000/api/v1.0/my -> returns "Version 1.0"

http://localhost:5000/api/v2.0/my -> returns "Version 2.0"

By using URL-based versioning in ASP.NET Core, you can easily manage different versions of your API and provide backward compatibility to existing clients.

2. Query String

Another option for versioning a REST API is to include the version number as a query parameter.

This is a straightforward way to version an API from an implementation point of view.

Example:

https://api-demo.example.com/api/employee/?api-version=2

Follow the same steps and code as mentioned above. change code for AddApiVersioning method. in this only  ApiVersionReader  property is changed.

  services.AddApiVersioning(options =>
    {
        options.DefaultApiVersion = new ApiVersion(1, 0);
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.ReportApiVersions = true;
        options.ApiVersionReader = new QueryStringApiVersionReader("version");
    });

Test the API by sending requests with the "version" query parameter. For example:

http://localhost:5000/api/my?version=1.0 -> returns "Version 1.0"

http://localhost:5000/api/my?version=2.0 -> returns "Version 2.0"

By using query string-based versioning in ASP.NET Core, you can provide a flexible and convenient way for clients to specify the desired version of your API.

3. Custom headers

Define a new header that contains the version number in the request as part of the request header itself.

Example:

GET https://api-demo.example.com/api/employee
Accept-Version: 3

Follow the same steps and code as mentioned above. change code for AddApiVersioning method. in this only  ApiVersionReader  property is changed.

  services.AddApiVersioning(options =>
    {
        options.DefaultApiVersion = new ApiVersion(1, 0);
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.ReportApiVersions = true;
        options.ApiVersionReader = new HeaderApiVersionReader("X-Version");
    });

This code configures the default API version to be 1.0, assumes the default version when not specified in the header, reports the API versions in the response headers, and uses the "X-Version" header as the versioning source.

Test the API by sending requests with the "X-Version" header. For example:

http://localhost:5000/api/my

X-Version: 1.0 -> returns "Version 1.0"

X-Version: 2.0 -> returns "Version 2.0"

By using header-based versioning in ASP.NET Core, you can provide a flexible and non-intrusive way for clients to specify the desired version of your API.

Learn More: https://codelikeadev.com/https://www.c-sharpcorner.com/
                        https://www.dotnettricks.com/https://blog.devart.com/


Continue Reading →

Wednesday, 2 August 2023

Dotnet Core Versions

.NET Core is a cross-platform, open-source framework developed by Microsoft for building modern, scalable, and high-performance applications. It has since been unified with .NET Framework into a single product under the name ".NET" (starting with version 5), which is a continuation of .NET Core.

Here’s a summary of the evolution and versions of .NET Core:

  1. .NET Core 1.0 - Released in June 2016.
  2. .NET Core 1.1 - Released in November 2016.
  3. .NET Core 2.0 - Released in August 2017.
  4. .NET Core 2.1 - Released in May 2018 (LTS).
  5. .NET Core 2.2 - Released in December 2018.
  6. .NET Core 3.0 - Released in September 2019.
  7. .NET Core 3.1 - Released in December 2019 (LTS).

After .NET Core 3.1, the versioning transitioned to .NET 5:

  1. .NET 5 - Released in November 2020 (marks the unification of .NET Core and .NET Framework).
  2. .NET 6 - Released in November 2021 (LTS).
  3. .NET 7 - Released in November 2022.
  4. .NET 8 - Released in November 2023 (LTS).

The versioning structure now focuses on just ".NET", where .NET Core versions are no longer distinct, and the term ".NET Core" has been replaced by ".NET". .NET 5 and onwards represent the unified platform that evolved from .NET Core.

To check the version of .NET (whether .NET Core or the latest .NET versions), you can use the command:

dotnet --version

Continue Reading →

Monday, 10 July 2023

Use of Dynamic in C#

 Dynamic type has been added to C# since C# 4.0 (.NET 4.5) and its main purpose is to bypass the static type checks and add more flexibility to the language. 

Static vs Dynamic Languages

As you might be aware, the software development languages are divided into two major categories: static languages and dynamic languages. The main difference between a static and a dynamic language is how it handles its types (or doesn’t).

in the static languages variables are resolved during “compile time” and in the dynamic in the “runtime”.

What does this really mean though?

In a static language, a variable is assigned its type when the project is compiled.
In a dynamic language, a variable can change it’s type several times while the application is already running.

Some examples of static and dynamic languages:

Static: C , C# , F# , C++ , Java , Go

Dynamic: Javascript , Python , Ruby , PHP , Perl , Objective-C

Advantages of Static and Dynamic Languages

Static languages are generally considered to be faster because they resolve their types during the compilation phase. This helps improve the application performance and optimization. Excluding machine language and Assembly, fastest high-level languages are probably C and C++. No other languages can still match the speed of these two because of their memory management capabilities.

Besides being fast, static languages are also being fast to fail. You’ll find a lot of bugs even before the application has started because of the compiler checks. This means fewer bugs once the application is up and running.

On the other hand dynamic languages, while being slower, are much easier to write. And you can write them faster without having to think about which type to use or how to initialize it.

What is Dynamic Type in C#

So we already mentioned that C# is a statically typed language. So what does a dynamic type has to do with C#?

The dynamic type has been added to C# since version 4 as because of the need to improve interoperability with COM (Component Object Model) and other dynamic languages. While that can be achieved with reflection, dynamic provides a natural and more intuitive way to implement the same code.

Dynamic type in C# is instantiated by using the dynamic keyword and it can be assigned any other type.

Why Should We Use the Dynamic Type

By now, you probably have some ideas on where you can use dynamic type. But let’s go through some common scenarios in which dynamic could potentially improve our applications and make our lives as developers a bit easier.

First of all, let’s make it clear that dynamic is not a silver bullet. We shouldn’t use it just because we can.

While it has its benefits, dynamic objects are harder to work with while writing code, since we don’t have and Intelligence for them due to the nature of dynamic type. On the other hand, if have a need to implement dynamic type everywhere, we are probably using a wrong type of language. Dynamic languages are better suited for those kinds of cases.

So what are the common cases to apply dynamic to:

  1. Communicating with other dynamic languages
  2. Simplifying responses from API calls when we don’t know what type of object to expect (or we don’t care)
  3. Creating libraries that can be used between languages
  4. Making generic solutions when speed isn’t the main concern
  5. Replacing and simplifying reflection code

Why we shouldn’t use dynamic all the time because:

  1. It’s slower than statically typed code
  2. Increases a chance to get runtime exceptions
  3. Decreases code readability in some cases, and working with it is a bit harder due to the lack of IntelliSense

Reference: https://www.linkedin.com

Continue Reading →

Friday, 24 February 2023

View encapsulation in Angular

 In Angular, a component's styles can be encapsulated within the component's host element so that they don't affect the rest of the application.

The Component decorator provides the encapsulation option which can be used to control how the encapsulation is applied on a per component basis.

Choose from the following modes:

ViewEncapsulation.ShadowDom: Angular uses the browser's built-in Shadow DOM API to enclose the component's view inside a ShadowRoot, used as the component's host element, and apply the provided styles in an isolated manner.

ViewEncapsulation.ShadowDom only works on browsers that have built-in support for the shadow DOM (see Can I use - Shadow DOM v1). Not all browsers support it, which is why the ViewEncapsulation.Emulated is the recommended and default mode.                             

ViewEncapsulation.Emulated: Angular modifies the component's CSS selectors so that they are only applied to the component's view and do not affect other elements in the application, emulating Shadow DOM behavior. For more details, see Inspecting generated CSS.

ViewEncapsulation.None: Angular does not apply any sort of view encapsulation meaning that any styles specified for the component are actually globally applied and can affect any HTML element present within the application. This mode is essentially the same as including the styles into the HTML itself.

Reference: https://angular.io/

Continue Reading →

Monday, 20 February 2023

Building Microservices with ASP.NET Core

 This tutorials only for beginner level developers. In this I will let you know a simple Asp.net Core WebApi Project interacting with OCELOT opensource API Gateway.

Microservices, also known as Microservices Architecture, is basically an SDLC approach in which large applications are built as a collection of small functional modules. It is one of the most widely adopted architectural concepts within software development. In addition to helping in easy maintenance, this architecture also makes development faster.



See the above picture of a Simple Microservice Architecture.

Now We will learn Microservice By creating a simple application.

 Create a Asp.net core WebApi Project in Visual studio 2019.

Delete pre defined WeatherForecast Controller and model and Create UserController and User Model as per below screenshot.

Code are given below.
namespace UserService.Database.Entities
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Contact { get; set; }
    }
}

We need to install Microsoft.EntityFrameworkCore, Microsoft.EntityFrameworkCore.SQLServer, Microsoft.EntityFrameworkCore.Tools. version should be as per DotnetCore version. here I am using 3.1 version.

using Microsoft.EntityFrameworkCore;
using UserService.Database.Entities;

namespace UserService.Database
{
    public class DatabaseContext : DbContext
    {
        public DbSet<User> Users { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"data source=SURAJKUMAR-PC/SKM;
                    initial catalog=EntityFrameworkCoreDB;persist security info=True;
                    user id=sa;password=1234;");
        }
    }
}


using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using UserService.Database;
using UserService.Database.Entities;

namespace UserService.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        DatabaseContext db;
        public UserController()
        {
            db = new DatabaseContext();
        }
        // GET: api/<UserController>
        [HttpGet]
        public IEnumerable<User> Get()
        {
            return db.Users.ToList();
        }

        // GET api/<UserController>/5
        [HttpGet("{id}")]
        public User Get(int id)
        {
            return db.Users.Find(id);
        }

        // POST api/<UserController>
        [HttpPost]
        public IActionResult Post([FromBody] User user)
        {
            try
            {
                db.Users.Add(user);
                db.SaveChanges();
                return StatusCode(StatusCodes.Status201Created);
            }
            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }
    }
}

Now Save everything and lets create database table. Open Package manager Console in Visual Studio and execute the below highlighted command for migration.

This will genrate migration script and update the things in Sql server. Now lets checkout our SQL server DB.

See, Users table has been created. Now lets add one record in table for API testing.

Id Name Address Contact
1 suraj delhi 987643222

Run the application and execute below API url. You will see the response. 

Our API is ready now.

Creating OCELOT API Gateway.

Now Add one more project (ASP.NET Core WebApp blank project) inside same solution named APIGateway.
- Add Ocelot Package from Nuget pckg manager.
- Add ocelot.json file.


Add Routes data inside ocelot.json file as per below code.

{
    "Routes": [
      {
        "DownstreamPathTemplate": "/api/user",
        "DownstreamScheme": "http",
        "DownstreamHostAndPorts": [
          {
            "Host": "localhost",
            "Port": "30935"
          }
        ],
        "UpstreamHttpMethod": [ "GET" ],
        "UpstreamPathTemplate": "/user"
      },
      {
        "DownstreamPathTemplate": "/api/user/{id}",
        "DownstreamScheme": "http",
        "DownstreamHostAndPorts": [
          {
            "Host": "localhost",
            "Port": "30935"
          }
        ],
        "UpstreamHttpMethod": [ "GET" ],
        "UpstreamPathTemplate": "/user/{id}"
      }
    ]
  }

Add the above json file in Program.cs class as per below screenshot.

Add Ocelot service and middleware in StartUp class as pr below screenshot.



Now Run Both the application and see results.


Use the url as per below screenshot for testing.


From Ocelot API Gateway, we are able to access microservice.

Reference: https://www.youtube.com/

Microservice Interview Questions and Answers : https://www.guru99.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# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) 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