Async and Await in C#

Async and Await are the two keywords that help us to program asynchronously. An async keyword is a method that performs asynchronous tasks such as fetching data from a database, reading a file, etc can be marked as “async”. Whereas await keyword making  “await” to a statement means suspending the execution of the async method it is residing in until the asynchronous task completes. After suspension, the control goes back to the caller method. Once the task completes, the control comes back to the states where await is mentioned and executes the remaining statements in the enclosing method.

When we are dealing with UI on button click, we use a long-running method like reading a large file or something else which will take a long time, in that case, the entire application must wait to complete the whole task. In other words, if any process is blocked in a synchronous application, the whole application gets blocked, and our application stops responding until the whole task completes. By using Asynchronous programming, the Application can continue with the other work that does not depend on the completion of the entire task.

We can run all the methods parallelly by using simple thread programming, but it will block UI and wait to complete all the tasks. To come out of this problem, we have to write too many codes in traditional programming, but if we use the async and await keywords, we will get the solutions in much less code.

Principles and Methods of Rest API

Principles of Rest API 

1. Client-Server decoupling

In a REST API design, client and server programs must be independent. The client software should only know the URI of the requested resource; it should have no additional interaction with the server application. 


2. Uniform Interface

All API queries for the same resource should look the same regardless of where they come from. The REST API should ensure that similar data, such as a user's name or email address, is assigned to just one uniform resource identifier (URI). 


3. Statelessness

REST APIs are stateless, meaning each request must contain all the information needed to process it. 


4. Layered System architecture

REST API requests and responses are routed through many tiers. REST APIs must be designed so neither the client nor the server can tell whether they communicate with the final application or an intermediary.  


5. Cacheable

Wherever feasible, resources should be cacheable on the client or server side. Server responses must additionally indicate if caching is authorized for the offered assistance. The objective is to boost client-side speed while enhancing server-side scalability.  


6. Code on Demand

REST APIs typically provide static resources, but in rare cases, responses may include executable code (such as Java applets). In these cases, perform the code when necessary.

___________________________________________________________________________________


Methods of Rest API

1. GET

The most popular HTTP method, GET, returns a representative view of the information and data contained in a resource. For data security and resource idempotence, the Use of GET should only be in read-only mode. If another client hasn't changed this technique in the interim, you should always obtain the same results regardless of how many times you use it. 


2. POST

POST is the sole HTTP method for RESTful APIs that focuses on resource collections. Applying POST to the parent resource causes it to build a new resource, add it to the correct hierarchy, and return a specific URL for future use for establishing a subordinate resource in a collection. However, remember that POST is not idempotent; you cannot repeatedly employ this technique and anticipate a consistent result.


3. PUT 

The PUT command modifies a resource by completely replacing its content, making it the single-resource counterpart of POST. As a result, PUT is the most popular technique for updating resource data in a RESTful API. 


4. PATCH

Another HTTP method for updating resources is PATCH. PATCH alters resource contents instead of replacing resources, like the PUT method. These updates should often be conveyed using a common format, such as JSON or XML. 


5. DELETE 

DELETE is the final HTTP method to look at. Targeting a single resource with a DELETE method results in the complete deletion of that resource.

Jwt Token Manager

 public string CreateToken(int branchID, string employeeID)

{

var tokenString = "";

try

{

var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("myEncryptionKey@143#"));


var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

var claims = new List<Claim>

{

new Claim(ClaimTypes.Name,  branchID + "," + employeeID)

};

var tokeOptions = new JwtSecurityToken(

issuer: "http://localhost:5000",

audience: "http://localhost:5000",

claims: claims,

notBefore: DateTime.Now,

signingCredentials: signinCredentials

);

tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);

}

catch (Exception e) { }


return tokenString;

}



public string CreatePaymentToken(string policyId, string CustomerID)

{

var tokenString = "";

try

{

//var symmetricKey = Convert.FromBase64String("bXlFbmNyeXB0aW9uS2V5QDE0MyM=");

//var SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature);

//var claims = new List<Claim>

// {

// new Claim(ClaimTypes.Name, policyId +","+ CustomerID )

//     };

//var tokeOptions = new JwtSecurityToken(

//issuer: "http://localhost:5000",

//audience: "http://localhost:5000",

//claims: claims,

//notBefore: DateTime.Now,

//signingCredentials: SigningCredentials

//);

//tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);

string Key =("bXlFbmNyeXB0aW9uS2V5QDE0MyM=");

tokenString = Base64Encode(policyId + "-" + Key+"-"+ CustomerID);

}

catch (Exception e) { }


return tokenString;

}

public  string Base64Encode(string plainText)

{

var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);

return System.Convert.ToBase64String(plainTextBytes);

}

public  string Base64Decode(string base64EncodedData)

{

var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);

return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);

}

Azure DevOps

Azure DevOps Server is a Microsoft product that provides version control, reporting, requirements management, project management, automated builds, testing and release management capabilities.

Azure DevOps Services, cloud service for software development.

Some benefits of DevOps include: Faster, better product delivery. Faster issue resolution and reduced complexity. Greater scalability and availability.

Azure DevOps supports a collaborative culture and set of processes that bring together developers, project managers, and contributors to develop software. It allows organizations to create and improve products at a faster pace than they can with traditional software development approaches.

What are the main tools in Azure DevOps ?

Azure Boards.

Azure Repos.

Azure Pipelines.

Azure Test plans.

Azure Artifacts.

Azure DevOps Server.

All services.

A DevOps pipeline is a set of automated processes and tools that allows developers and operations professionals to collaborate on building and deploying code to a production environment.

Azure is a cloud computing platform and an online portal that allows you to access and manage cloud services and resources provided by Microsoft. These services and resources include storing your data and transforming it, depending on your requirements.

What are the Key Components of DevOps?

Continuous Development.

Continuous Integration.

Continuous Testing.

Continuous Feedback.

DevOps pipeline typically has eight stages. In the Development phase, they are: plan, code, build, and test. In the Operations phase, the stages are: release, deploy, operate, and monitor.

Top DevOps Tools List  /  How many software used in DevOps?

# DevOps_Tools  DevOps_Stage

1. Git                 Code, Build

2. Gradle         Build

3. Selenium                 Test

4. Jenkins         Build, Test, Deploy

What are the Features of Azure DevOps?

1) Dashboard Control.

2) Enhanced Source Control. 

3) Track and Plan Your Work.

4) Continuous Integration and Deployment (CI/CD) 

5) Assistance with Exploratory and Manual Testing.

6) Services for Integrated Collaboration.

7) Azure Cloud Hosted Services.

zure DevOps supports a collaborative culture and set of processes that bring together developers, project managers, and contributors to develop software. It allows organizations to create and improve products at a faster pace than they can with traditional software development approaches.


Using scripts in ASP.Net Core

 In Layout page :-

    <div>

        @RenderBody()

        @RenderSection("scripts")

    </div>

_____________________________________________________________________________________

In View page :-

@section Scripts {

    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

}


C# - Anonymous Method

 An anonymous method is a method without a name. 

-- 

Anonymous methods in C# can be defined using the delegate keyword and can be assigned to a variable of delegate type.

public delegate void Print(int value);

static void Main(string[] args)

{

    Print print = delegate(int val) 

    {         

      Console.WriteLine("Inside Anonymous method. Value: {0}", val); 

    };

    print(100);

}

-- 

Anonymous methods can access variables defined in an outer function.

Example: Anonymous Method

public delegate void Print(int value);

static void Main(string[] args)

{

    int i = 10;

    Print prnt = delegate(int val) 

    {

        val += i;

        Console.WriteLine("Anonymous method: {0}", val); 

    };

    prnt(100);

}

--

Anonymous methods can also be passed to a method that accepts the delegate as a parameter.

In the following example, PrintHelperMethod() takes the first parameters of the Print delegate:

Example: Anonymous Method as Parameter

public delegate void Print(int value);

class Program

{

    public static void PrintHelperMethod(Print printDel,int val)

    { 

        val += 10;

        printDel(val);

    }

    static void Main(string[] args)

    {

      PrintHelperMethod(delegate(int val) { Console.WriteLine("Anonymous method: {0}", val); }, 100);

    }

}

--

Anonymous methods can be used as event handlers:

Example: Anonymous Method as Event Handler

saveButton.Click += delegate(Object o, EventArgs e)

    System.Windows.Forms.MessageBox.Show("Save Successfully!"); 

};

Difference Between dispose() and finalize() in C#

Definition of dispose()

The dispose() method releases the unmanaged resources that are held by an object of the class. The unmanaged resources are files, data connections, etc. The method dispose() is declared in the interface IDisposeable.

Definition of finalize()

The finalize() method is defined in the object class. It is used for cleanup activities. This method is called by the garbage collector when the reference of an object is not used for a long time. 

Key Differences Between dispose() and finalize()

- The method dispose() is defined in an interface IDisposable. On the other hand, the method finalize()     is defined in the class object.

- The method dispose() has to be manually invoked inside the code by a programmer, while the method     finalize is automatically invoked by the garbage collector before it destroys the object.

- The method dispose could be invoked anytime, whereas the method finalize is invoked by the             garbage  collector when it finds that that object has not been referenced for a long time.

- The method dispose() is implemented in a class after implementing the interface IDisposable. The     method finalize() has to be implemented only for unmanaged resources because the managed     resources  are automatically freed by the garbage collector.

- The access specifier of the method dispose() is public as it is defined in the interface IDisposable and    it would be implemented by the class that implements this interface hence, it should be public. On the    other hand, the method finalize() has protected access specifier so that it should not be accessible to     any member outside the class.

- The method dispose() is fast and frees the object instantly hence, it does not affects the performance     cost. The method finalize() is slower and does not free the resources held by the object instantly.

BASIS FOR COMPARISONDISPOSE( )FINALIZE( )
DefinedThe method dispose( ) is defined in the interface IDisposable interface.The method finalize( ) id defined in java.lang.object class.
Syntaxpublic void Dispose( ){
// Dispose code here
}
protected void finalize( ){
// finalization code here
}
InvokedThe method dispose( ) is invoked by the user.The method finalize( ) is invoked by the garbage collector.
PurposeMethod dispose( ) is used to free unmanaged resources whenever it is invoked.Method finalize( ) is used to free unmanaged resources before the object is destroyed.
ImplementationThe method dispose( ) is to be implemented whenever there is a close( ) method.The method finalize( ) is to be implemented for unmanaged resources.
Access specifierThe method dispose( ) is declared as public.The method finalize( ) is declared as private.
ActionThe method dispose( ) is faster and instantly disposes an object.The method finalize is slower as compared to dispose
PerformanceThe method disposes( ) performs the instantaneous action hence, does not effect the performance of websites.The method finalize( ) being slower affects the performance of the websites.

Get difference between 2 dates in JavaScript

 <script>

    function dateDiffInDays() {

        const date1 = new Date(document.getElementById("AgeFrom").value);

        const date2 = new Date(document.getElementById("AgeTo").value);

        const diffTime = Math.abs(date2 - date1);

        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

        alert(diffDays + " days");

    }

</script>

Middleware Components in ASP.NET Core

Middleware are software components that are assembled into an application pipeline to handle requests and responses. Each component chooses whether to pass the request on to the next component in the pipeline and can perform certain actions before and after the next component is invoked in the pipeline.

What are the ASP.NET Core Middleware Components?

The ASP.NET Core Middleware Components are the software components (technically components are nothing but the C# Classes) that are assembled into the application pipeline to handle the HTTP Requests and Responses. Each middleware component in ASP.NET Core Application performs the following tasks.

1.Chooses whether to pass the HTTP Request to the next component in the pipeline. This can be achieved by calling the next() method within the middleware.

2.Can perform work before and after the next component in the pipeline.


In ASP.NET Core there are so many built-in Middleware components that are already made available that you can use directly. If you want then you can also create your own Middleware components in asp.net core applications. The most important point that you need to keep in mind is, in ASP.NET Core a given Middleware component should only have a specific purpose i.e. single responsibility.

The Middleware components are the components that we generally use to set up the request processing pipeline in the ASP.NET Core application. 

Where we use Middleware Components in the ASP.NET Core application?

Some of the examples of using Middleware components in the ASP.NET Core application are as follows :-

We may have a Middleware component for authenticating the user

Another Middleware component may be used to log the request and response

Similarly, we may have a Middleware component that is used to handle the errors

We may have a Middleware component that is used to handle the static files such as images, Javascript or CSS files, etc.

Another Middleware component may be used to Authorize the users while accessing a specific resource


How to Configure Middleware Components in ASP.NET Core application?

In the ASP.NET Core application, we need to configure the Middleware components within the Configure() method of the Startup class which is present inside the Startup.cs file. 

So, whenever you want to configure any middleware components in any type of .net core applications, then you need to configure it within the Configure() method of the Startup class by calling the Use* methods on the IApplicationBuilder object.


Understanding Middleware Components in ASP.NET Core:

In the ASP.NET Core application, the Middleware component can have access to both the incoming HTTP Request and outgoing HTTP Response. So, a Middleware component in ASP.NET Core can

Handle the incoming HTTP request by generating an HTTP response.

Process the incoming HTTP request, modify it, and then pass it to the next middleware component

Process the outgoing HTTP response, modify it, and then pass it on to either the next middleware component or to the ASP.NET Core web server.

A middleware component in ASP.NET Core may also handle the HTTP Request by generating an HTTP Response. The ASP.NET Core Middleware component may also decide not to call the next middleware component in the request pipeline.

For example, we have a static file middleware component. And if the incoming HTTP request comes for some static files such as images, CSS files, JavaScript, etc. then this Static Files Middleware component can handle the request and then short-circuit the request pipeline by not calling to the next component in the pipeline i.e. the MVC Middleware component.

As we already discussed the ASP.NET Core middleware components can have access to both the HTTP request and response in the pipeline. So, a middleware component can also process the outgoing response. For example, the logging middleware component in our case may log the time when the response is sent back to the client.

It is very important to understand the execution order of Middleware components. The ASP.NET Core middleware components are executed in the same order as they are added to the pipeline.

As per your application’s business requirements, you may add any number of Middleware components. For example, if you are developing a static web application with some static HTML pages and images, then you may require only “StaticFiles” middleware components in the request processing pipeline.

But, if you are developing a secure dynamic data-driven web application then you may require several middleware components such as Logging Middleware, Authentication middleware, Authorization middleware, MVC middleware, etc.

In ASP.NET Core, you can use the “Use” and “Run” extension methods to register the Inline Middleware component into the Request processing pipeline. The “Run” extension method allows us to add the terminating middleware. On the other hand, the “Use” extension method allows us to add the middleware components which may call the next middleware component in the request processing pipeline.


What is the difference between MapGet and Map method?

The MapGet method is going to handle the GET HTTP Requests whereas the Map method is going to handle all types of HTTP requests such as GET, POST, PUT, & DELETE, etc.

Types of Inheritance In C#

 Acquiring (taking) the properties of one class into another is called inheritance. Code reusability is one of the key features of OOPs and it is achieved via inheritance. Using inheritance, one or more classes can derive from an existing class. The existing class is called a base class, and the inherited class is called a derived or inherited class. 




Single inheritance in C#

It is the type of inheritance in which there is one base class and one derived class. 


Hierarchical inheritance in C#

This is the type of inheritance in which there are multiple classes derived from one base class. This type of inheritance is used when there is a requirement of one class feature that is needed in multiple classes.


Multilevel inheritance in C#

When one class is derived from another, this type of inheritance is called multilevel inheritance.


Multiple inheritances using Interfaces

C# does not support multiple inheritances of classes. To overcome this problem, we can use interfaces. We will see more about interfaces in my next article in detail.

Difference between Managed and Unmanaged code in .NET

Managed code is the code which is managed by the CLR(Common Language Runtime) in .NET Framework. Whereas the Unmanaged code is the code which is directly executed by the operating system.


Managed Code

Unmanaged Code

It is executed by managed runtime environment or managed by the CLR.It is executed directly by the operating system.
It provides security to the application written in .NET Framework.It does not provide any security to the application.
Memory buffer overflow does not occur.Memory buffer overflow may occur.
It provide runtime services like Garbage Collection, exception handling, etc.It does not provide runtime services like Garbage Collection, exception handling, etc.
The source code is compiled in the intermediate language known as IL or MSIL or CIL.The source code directly compiles into native languages.
It does not provide low-level access to the programmer.It provide low-level access to the programmer.

How to give serial numbers in list view pages

  @{int index = 1;}

    @foreach (var item in Model)

    {

        <tr>

            <td>

                @index

            </td>              

        </tr>

        index++;

    }