Image Upload CRUD Operations in .NET Core WebAPIs

how to upload images in .net core web api

Upload images in .net core apis

In this article, we will learn how to upload/update/delete/read images in .net core APIs. I hate to give long and unnecessary intros, So let’s come to the point’s.

💻 You can get the code from this github repo.

What is the logic behind it? 🤔

When you upload the image (or any file), we will generate the unique image name with it’s extension (eg. uniquename.png). Save the image name in the database and save the file with the same name inside the project. In production apps, you can not simply upload files to the server, you have to give permission to that folder. Or you can use other file storage service, where you will save your files.

[Read More]

Separating the DI Setup From Program.cs file

Separating the DI Setup From Program.cs file

Let’s take a look at the program.cs file below.

using InventoryMgt.Api.Middlewares;
using InventoryMgt.Data.Repositories;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<ICategoryRepository, CategoryRepository>();
builder.Services.AddTransient<IProductRepository, ProductRepository>();
builder.Services.AddTransient<IPurchaseRepository, PurchaseRepository>();
builder.Services.AddTransient<IStockRepository, StockRepository>();
builder.Services.AddTransient<ISaleRepository, SaleRepository>();
builder.Services.AddTransient<ExceptionMiddleware>();
builder.Services.AddCors(options =>
{
 options.AddDefaultPolicy(policy =>
 {
 policy.WithOrigins("*").AllowAnyHeader().AllowAnyMethod().WithExposedHeaders("X-Pagination");
 });
});
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
 app.UseSwagger();
 app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseCors();
app.UseAuthorization();
app.ConfigureExceptionMiddleware();
app.MapControllers();

app.Run();

It is a regular program.cs file. Since we use the dependency injection in our application, we have to register lots of service in our program.cs file. For example:

[Read More]

Private Constructor in C#

private constructor in c#

In C#, a private constructor is a constructor method declared with the private access modifier (or without mentioning any modifier). If a class have only a private constructor and does not have any public constructor, then you are not able to create the instance of a class. Example 👇

public class Student
{
 Student() { } // private constructor
}

public class Program
{
 static void Main()
 {
 Student stu = new(); //Error CS0122 'Student.Student()'
 // is inaccessible due to its protection level

    }

}

When you try to create the instance of stu, you will the following error.

[Read More]

Generic Delegates (Action, Func & Predicates) in C#

Generic delegate c#, action func predicate in c#

In C#, delegates are used to refer to methods with a specific signature. Generic delegates extend this concept by allowing you to create delegates that can work with any method signature, rather than being tied to a specific signature.

Here’s a basic example of a generic delegate:

delegate T MyGenericDelegate<T>(T arg);

You can use this generic delegate as follows.

MyGenericDelegate<int> handler1 = CustomSquare;
int square=handler1(4);
Console.WriteLine(square); //16

MyGenericDelegate<string\> handler2 = CustomToUpper;
Console.WriteLine(CustomToUpper("helLo")); //HELLO

In-built Generic delegates

C# comes with inbuilt generic delegates like Action, Func and Predicate.

[Read More]

Delegates, Anonymous Method and Lambda Expression

Delegates, anonymous method and lambda expression in c#

  • Delegates in C# are essentially type-safe function pointers.
  • They allow you to treat methods as objects, enabling you to pass methods as parameters, store them in variables, and invoke them dynamically.
  • Delegates are particularly useful for implementing callback mechanisms and event handling in C#.

delegate void MyDelegate(string message);

You can point this delegate to any method with similar signature.

namespace BasicsOfCSharp;

// Declare a delegate type
delegate void MyDelegate(string message);

class Program
{
 // Method that matches the delegate signature
 static void DisplayMessage(string message)
 {
 Console.WriteLine("Message: " + message);
 }
 static void Main()
 {
        // Instantiate the delegate.
        MyDelegate handler = DisplayMessage;

        // calling the handler
        handler("Hello..");

    }

}

👉Multicast Delegate:

[Read More]

Abstract Class in C#

In c#, Abstract class is a class that can not be instantiated on its own

abstract class in c#

  • In c#, Abstract class is a class that can not be instantiated on its own
  • It is typically used as a base class for other class.
  • Abstract class provides a way to achieve abstraction, because there you can just declare the methods (abstract methods) and implement them later.
  • It can contain both abstract methods (methods without implementation details) and non-abstract methods (method with implementation details).
  • Similar goal can be achieved with interface, but in abstract class you can also define non-abstract method. These methods are needed when you need to share some common functionality.
public abstract class Shape
{
 // it is the basic syntax of abstract class
}

Example:

[Read More]

Polymorphism in depth with C#

polymorphism in csharp

Polymorphism is one of the core concept of object oriented programming. Word polymorphism = poly (many) + morphism (forms). As its name suggesting polymorphism means, an entity can have multiple forms.

📢 Updated and refinded at : 21-feb-2025

Other oops core concepts :

Let’s learn polymorphism through mistakes.

Jim requires an entry system for his pet shop, which exclusively houses various breeds of dogs. This system will manage the entry and records of all dogs entering and exiting the premises.

[Read More]

Inheritance in C#

inheritance csharp

📢 Updated and refinded at : 21-feb-2025

Inheritance is a fundamental concept in OOPs that allows a class to inherit properties and behaviors of another class. We have two key terms are here base class/superclass and derived class/subclass.

  • Base class / super-class: Whose members and functionality are inherited (Giver).
  • Derived class / sub-class: Who is inheriting the members (Taker)

📺Other oops concepts:

Syntax of inheritance:

[Read More]

Encapsulation in C#

encapsulation in c#

📢 Updated and refinded at : 21-feb-2025

Bundling the data member and member function into a single unit is called encapsulation. Remember the term “capsule”. We put all the medicine inside a wrapper and call it capsule. Similarly, wrap the data members and member functions together is called encapsulation.

Now we need to understand few terms.

  • Data members : Attributes or properties (eg. name, age)
  • Member functions: Methods (PrintDetails)

👉 We wrap up the data members (attributes or properties) and member functions (methods) into a single unit (class).

[Read More]

Abstraction in C#

abstraction in oops c#

📢 Updated and refinded at : 21-feb-2025

Abstraction allows you to focus on the relevant details of an object while ignoring unnecessary complexities.
This is achieved by defining a simplified representation of an object that hides the implementation details and exposes only the necessary features.
In practical terms, abstraction is implemented through abstract classes and interfaces in languages like C#.

📺Other OOPs related articles :

Let’s implement abstraction by using interface. In the real world projects, we use interfaces more often.

[Read More]