In AIML, I started with Python.
Differences between MD5 and SHA1
|
MD5 |
SHA1 |
|
MD5
stands for Message Digest. |
While
SHA1 stands for Secure Hash Algorithm. |
|
MD5 can
have 128 bits length of message digest. |
Whereas
SHA1 can have 160 bits length of message digest. |
|
The
speed of MD5 is fast in comparison of SHA1’s speed. |
While
the speed of SHA1 is slow in comparison of MD5’s speed. |
|
To make
out the initial message the aggressor would want 2^128 operations whereas
exploitation the MD5 algorithmic program. |
On the
opposite hand, in SHA1 it’ll be 2^160 that makes it quite troublesome to seek
out. |
|
MD5 is
simple than SHA1. |
While
SHA1 is more complex than MD5. |
|
MD5
provides indigent or poor security. |
While
it provides balanced or tolerable security. |
|
In MD5,
if the assailant needs to seek out the 2 messages having identical message
digest then assailant would need to perform 2^64 operations. |
Whereas
in SHA1, assailant would need to perform 2^80 operations which is greater
than MD5. |
|
MD5 was
presented in the year 1992. |
While
SHA1 was presented in the year 1995. |
Code Refactoring in C#
Code refactoring allows you to change the code structure without changing or affecting what the code itself actually does. Code refactoring is the practice of taking previously written code and rewriting it to make it more efficient.
Using code refactorings:
On a symbol in the text editor.
On a code selection in the text editor.
On a file or a selection of files in the Solution Explorer tool window.
On a type member or a selection of type members in File Structure or another ReSharper tool window.
Change Signature
This refactoring allows you to modify a method signature in the following ways:
Add, remove, rename, or reorder parameter(s)
Change return type
Change parameter type(s)
Rename method
Refactoring can be explained as the process of improving your code after it has been written by changing:
The internal structure of the code.
External behavior of the code.
Methods
There are 5 methods of applying effective refactoring over your code, these methods are already available in Visual studio:
Extract Method
Extract interface
Rename
Promote variable to the parameter
Encapsulate Field
Generate method stub
Multiple inheritance using interfaces
C# does not support multiple class inheritance. To overcome this problem we use interfaces to achieve multiple class inheritance. With the help of the interface, class C( as shown in the above diagram) can get the features of class A and B.
ACID Properties in DBMS
Atomicity:
By this, we mean that either the entire transaction takes place at once or doesn’t happen at all. There is no midway i.e. transactions do not occur partially. Each transaction is considered as one unit and either runs to completion or is not executed at all. It involves the following two operations.
—Abort: If a transaction aborts, changes made to the database are not visible.
—Commit: If a transaction commits, changes made are visible.
Atomicity is also known as the ‘All or nothing rule’.
Consistency:
This means that integrity constraints must be maintained so that the database is consistent before and after the transaction. It refers to the correctness of a database.
Isolation:
This property ensures that multiple transactions can occur concurrently without leading to the inconsistency of the database state. Transactions occur independently without interference. Changes occurring in a particular transaction will not be visible to any other transaction until that particular change in that transaction is written to memory or has been committed. This property ensures that the execution of transactions concurrently will result in a state that is equivalent to a state achieved these were executed serially in some order.
Durability:
This property ensures that once the transaction has completed execution, the updates and modifications to the database are stored in and written to disk and they persist even if a system failure occurs. These updates now become permanent and are stored in non-volatile memory. The effects of the transaction, thus, are never lost.
Setting session in Asp.Net Core 7.0 MVC project
I am using Visual Studio 2022
To Set the session in Asp.Net Core 7.0 MVC project, do the following changes :- ___________________________________________________________________________________
In Program.cs file:-
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Razor.Language.Intermediate;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddSession();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseSession();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=HR}/{action=HRLogin}/{id?}");
app.Run();
____________________________________________
In Controller:-
HttpContext.Session.SetString("username", login.Username.ToString());
then call the session value
string SessionName = HttpContext.Session.GetString("username");
Cross-Origin Requests (CORS) in ASP.NET Core
How to Find Nth Highest Salary in SQL
SELECT * FROM(
SELECT emp_name, salary, DENSE_RANK()
over(ORDER BY salary DESC) AS ranking FROM employee) AS k
WHERE ranking=2;
SELECT * FROM(
SELECT emp_name, salary, ROW_NUMBER()
over(ORDER BY salary DESC) AS ranking FROM employee) AS k
WHERE ranking=2;
SELECT * FROM(
SELECT emp_name, salary, RANK()
over(ORDER BY salary DESC) AS ranking FROM employee) AS k
WHERE ranking=2;
Web API vs Rest API
1) Web API vs REST API: Protocol
Web API supports protocol for HTTP/s protocol and URL requests/responses headers that enable services to reach various clients through the web. On the other hand, all communication in the REST API is supported only through HTTP protocol.
2) Web API vs REST API: Formats
Although APIs perform identical tasks, a Web API provides flexibility to any style of communication. Whereas a REST API can take advantage of using REST, SOAP, and XML-RPC for communication.
3) Web API vs REST API: Design
As Web APIs are lightweight architecture, they are designed for gadgets constrained to devices like smartphones. In contrast, REST APIs send and receive data over systems making it a complex architecture.
4) Web API vs REST API: Support
Web API can be hosted only on an Internet Information Service (IIS) or self that supports XML and JSON requests. In contrast, REST API can be hosted only on IIS that supports standardized XML requests.
Difference Between Code First Approach And Database First Approach
Code First Approach
In code first approach, we will first create entity classes with properties defined in it. Entity framework will create the database and tables based on the entity classes defined. So database is generated from the code. When the dot net code is run database will get created.
Advantages
1. You can create the database and tables from your business objects.
2. You can specify which related collections are to be eager loaded or not be serialized at all.
3. Database version control.
4. Good for small applications.
Disadvantages
1. You have to write everything related to database in the visual studio code.
2. For stored procedures you have to map stored procedure using Fluent API and write Stored Procedure inside the code.
3. If you want to change anything in the database tables you to make changes in the entity classes in the code file and run the update-database from the package manager console.
4. Not preferred for Data intensive applications.
Database First Approach
In this approach Database and tables are created first. Then you create entity Data Model using the created database.
Advantages
1. Simple to create the data model
2. Graphical user interface.
3. Mapping and creation of keys and relationships are easy as you need not have to write any code .
4. Preferred for data intense and large applications
Disadvantages
1. Using an existing database to generate a .edmx model file and the associated code models results in a giant pile of auto generated code.
2. When you need to add any functionality to generated model you have to extend the model class generated.
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 COMPARISON | DISPOSE( ) | FINALIZE( ) |
|---|---|---|
| Defined | The method dispose( ) is defined in the interface IDisposable interface. | The method finalize( ) id defined in java.lang.object class. |
| Syntax | public void Dispose( ){ // Dispose code here } | protected void finalize( ){ // finalization code here } |
| Invoked | The method dispose( ) is invoked by the user. | The method finalize( ) is invoked by the garbage collector. |
| Purpose | Method dispose( ) is used to free unmanaged resources whenever it is invoked. | Method finalize( ) is used to free unmanaged resources before the object is destroyed. |
| Implementation | The method dispose( ) is to be implemented whenever there is a close( ) method. | The method finalize( ) is to be implemented for unmanaged resources. |
| Access specifier | The method dispose( ) is declared as public. | The method finalize( ) is declared as private. |
| Action | The method dispose( ) is faster and instantly disposes an object. | The method finalize is slower as compared to dispose |
| Performance | The 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.

