European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core Hosting :: Upload Files using ASP.NET Core API

clock June 26, 2023 10:55 by author Peter

In contemporary web applications, it is frequently necessary to upload files. Whether it involves uploading images, documents, or any other file format, ensuring a seamless user experience when dealing with uploads is crucial. This article will delve into the process of incorporating file upload functionality into an ASP.NET Core Web API.

Setting up the Project

To begin, we will set up a new ASP.NET Core Web API project. We'll also install the necessary NuGet packages required for file handling, such as
    Microsoft.EntityFrameworkCore.SqlServer
    Microsoft.EntityFrameworkCore
    Microsoft.EntityFrameworkCore.Tools


The tools which have been leveraged for this tutorial are.
    Visual Studio Community Edition 16.4.5
    .NET 6.0
    Entity Framework Core
    Web API

The entire source code can be downloaded from GitHub.

Creating the Model and Database Context
In this section, we'll define the model class representing the uploaded files and the corresponding database context for storing the file data. We'll use Entity Framework Core to interact with the database and store the file information as byte arrays.

Create a model class to represent the image entity. In this example, let's call it ImageEntity.cs:
public class ImageEntity
{
    [Key]
    public int Id { get; set; }

    public string FileName { get; set; }

    public byte[] Data { get; set; }
}

Then, create a database context class, AppDbContext.cs, that inherits from DbContext and includes a DbSet for the ImageEntity:
public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    public DbSet<ImageEntity> Images { get; set; }
}


Handling Multiple File Uploads in the Controller
In this segment, we will develop a controller action that receives an IFormFile object to manage file uploads. We will extract the file data and store it in the database utilizing the database context.

Create a controller, ImagesController.cs, with two actions: one for uploading the file and another for retrieving the file:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace FileUploadsPOC.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ImagesController : ControllerBase
    {
        private readonly AppDbContext _dbContext;


        public ImagesController(AppDbContext dbContext)
        {
            _dbContext = dbContext;

        }

        [HttpPost("upload")]
        public async Task<IActionResult> Upload(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return BadRequest("No file uploaded.");

            var imageEntity = new ImageEntity
            {
                FileName = file.FileName
            };

            using (var memoryStream = new MemoryStream())
            {
                await file.CopyToAsync(memoryStream);
                imageEntity.Data = memoryStream.ToArray();
            }

            await _dbContext.Images.AddAsync(imageEntity);
            await _dbContext.SaveChangesAsync();

            return Ok(imageEntity.Id);
        }

        [HttpGet("download/{id}")]
        public async Task<IActionResult> Download(int id)
        {
            var imageEntity = await _dbContext.Images.FirstOrDefaultAsync(image => image.Id == id);

            if (imageEntity == null)
                return NotFound();

            var fileContentResult = new FileContentResult(imageEntity.Data, "application/octet-stream")
            {
                FileDownloadName = imageEntity.FileName
            };

            return fileContentResult;
        }
    }
}

Setup the configuration
Make sure to configure your database connection string in the appsettings.json file:
"ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=FileUploadPOC;Trusted_Connection=SSPI;Encrypt=false;TrustServerCertificate=true"
  }

Configure your database connection and add the required services to Program.cs
builder.Services.AddDbContext<AppDbContext>(options =>
            options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

Create the Database Migration and Update Database
Open the Package Manager Console and execute the below commands.

Add-Migration FileUpload (FileUpload is the name of the migration, you can provide any name at your convenience)

Once the build succeeds, execute the below command.
Update-database

Testing the Upload and Download Functionality
To ensure our file upload functionality works as expected, we'll test it using a tool like Postma. I will leave this to you.

Following the steps outlined in this blog post, you can easily enable this feature in your web applications. Happy coding!



European ASP.NET Core Hosting :: Understanding Bitwise Enums in C# What is Bitwise Enums

clock June 19, 2023 08:13 by author Peter

A bitwise enum is an enum type that combines multiple enum values into a singular value using bitwise operations. Each enum value has its own bit indicator, which is represented by a power of 2. By designating these flags, we can represent multiple enum values using bitwise operators to combine or mask them.
How do we define Bitwise Enums?

To define a bitwise enum, the [Flags] attribute must be added to indicate that the enum values can be combined using bitwise operations. Here's an instance:
[Flags] enum DaysOfWeek {
  None = 0, Monday = 1, Tuesday = 2, Wednesday = 4, Thursday = 8, Friday = 16,
    Saturday = 32, Sunday = 64
};

In the above code, we define a DaysOfWeek enum where each day of the week is assigned a unique power of 2. The None value is assigned 0, indicating no days are selected.

Combining Bitwise Enums

To combine multiple enum values, we use the bitwise OR (|) operator. Here's an example,

DaysOfWeek selectedDays = DaysOfWeek.Monday | DaysOfWeek.Wednesday | DaysOfWeek.Friday;

The above code combines the Monday, Wednesday, and Friday enum values using the bitwise OR operator.

Checking for Enum Values

To check if a specific enum value is set in a bitwise enum, we use the bitwise AND (&) operator. Here's an example:

Console.WriteLine("selected Days", selectedDays);

if ((selectedDays & DaysOfWeek.Monday) != 0) {
  Console.WriteLine("Monday is selected.");
}

selectedDays ^= DaysOfWeek.Wednesday;

In the above code, we check if the Monday value is set in the selectedDays variable using the bitwise AND operator.

Removing Enum Values
To remove a specific enum value from a bitwise enum, we use the bitwise XOR (^) operator. Here's an example:
selectedDays ^= DaysOfWeek.Wednesday;

Console.WriteLine(selectedDays);


In the above code, we remove the Wednesday value from the selectedDays variable using the bitwise XOR operator.

In C#, bitwise enums offer a potent method for effectively encoding and modifying flag-based enumerations. We can mix, check, and remove particular enum values within a compact representation by giving them distinctive bit flags and using bitwise operations. Bitwise enums provide ease and flexibility for expressing flag-based situations such as days of the week, permissions, or other flag-based circumstances. If you have a firm grasp of bitwise enums, you can use this functionality in your C# projects to deal with challenging flag-based scenarios.



European ASP.NET Core Hosting :: HostedService in .Net Core

clock June 13, 2023 10:22 by author Peter

In the. NETCore, a HostedService, is a type of class that embodies a background task or service running asynchronously within an application. Its purpose is to initiate when the application starts and conclude when the application ceases. HostedService is an integral component of the generic host in .NET Core, enabling various functionalities like executing background processes, managing job schedules, and monitoring system resources.

The tools which I have leveraged for this tutorial are below.
    VS 2022 Community Edition (64-bit)
    .Net 7.0
    Console App

The entire source code can be downloaded from GitHub.
Here's an example of creating a HostedService in .NET Core.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

public class MyHostedService : IHostedService, IDisposable
{
    private readonly ILogger<MyHostedService> _logger;
    private Timer _timer;

    public MyHostedService(ILogger<MyHostedService> logger)
    {
        _logger = logger;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("MyHostedService is starting.");

        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));

        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        _logger.LogInformation("Doing some work...");
        // Perform your background processing or task here
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("MyHostedService is stopping.");

        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}

In this instance, the class MyHostedService is implemented with the IHostedService interface, which necessitates the implementation of the StartAsync and StopAsync methods. The ILogger is injected into the service's constructor for the purpose of logging.

The StartAsync method is invoked upon application startup. Within this method, you can initialize and commence any background tasks or processing. In this example, a Timer is instantiated to simulate a recurring task occurring every 5 seconds.

The StopAsync method is called when the application is shut down. Its purpose is to gracefully halt any ongoing work and perform resource cleanup. In the provided example, the Timer is stopped.

The Dispose method is implemented to properly release any resources utilized by the service.

To utilize the MyHostedService, it is necessary to register it within the dependency injection container of your application. Here's an illustration of how to configure and execute the HostedService in a console application.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

var host = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
    services.AddHostedService<MyHostedService>();
})
.ConfigureLogging(logging =>
{
    logging.ClearProviders();
    logging.AddConsole();
})
.Build();

await host.RunAsync();


In this scenario, the AddHostedService method is employed to enlist MyHostedService as a hosted service within the dependency injection container.

Upon executing the console application, MyHostedService will initiate and operate in the background until the application is halted.

Conclusion
Please take note that this example relies on Microsoft.Extensions.Hosting and Microsoft.Extensions.Logging namespaces, which are frequently utilized in .NET Core applications. Ensure you include the necessary NuGet packages (Microsoft.Extensions.Hosting and Microsoft.Extensions.Logging.Console) in your project.

This sample serves as a fundamental illustration of a HostedService in .NET Core. It can be customized and expanded to cater to your specific requirements.



European ASP.NET Core Hosting - HostForLIFE :: Utilizing NLog for logging in ASP.NET Core WebAPI

clock June 5, 2023 10:36 by author Peter

Logging is an integral element of the development process for all applications, including web APIs. It assists developers in monitoring and analyzing the flow of their applications, identifying issues, and resolving issues. NLog is a prominent logging framework in the ASP.NET Core ecosystem, providing a robust and flexible logging solution. This article examines how to implement monitoring in an ASP.NET Core WebAPI with NLog.

What exactly is NLog?

NLog is an adaptable and extensible platform for logging in.NET applications. It supports multiple logging destinations, including files, databases, and email. NLog is extremely configurable, enabling developers to configure logging behavior based on their particular needs.

Configuring NLog for ASP.NET Core WebAPI
Follow the steps below to get started with NLog in an ASP.NET Core WebAPI project:

Step 1. Add NLog dependencies
Add the required NLog dependencies to your project to get started. The NuGet Package Manager in Visual Studio can be used to search for and install the following packages:
NLog NLog.Web.AspNetCore

These packages provide the essential monitoring functionality and ASP.NET Core integration.

Step 2. Configure NLog

Create a nlog.config file in the project's root directory. This file defines NLog's configuration, including log targets and rules. Here is an example of a simple nlog.config file:

<?xml version="1.0" encoding="utf-8"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    autoReload="true" internalLogLevel="Trace" internalLogFile="${basedir}\logs\internallog.log" throwConfigExceptions="true">
    <!-- enable asp.net core layout renderers -->
    <extensions>
        <add assembly="NLog.Extended"/>
    </extensions>

    <targets>
        <!-- File Target for all log messages with basic details -->
        <target xsi:type="File" name="logfile" fileName="${basedir}/logs/nlog-${date:format=yyyy-MM-dd}.log"
            layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />
        <!-- Other targets like console, database, etc. can be added here -->
    </targets>
    <rules>
        <logger name="*" minlevel="Trace" writeTo="logfile" />
        <!-- Other rules can be added here -->
    </rules>
</nlog>

In this example, we define a file target called "logfile" that writes log messages to a file named nlog-YYYY-MM-DD.log within your application's logs subdirectory. You can add more targets such as console, database, or email as per your requirements. The minlevel attribute specifies the minimum log level to be captured, whereas the writeTo attribute specifies the destination(s) to which log messages should be written.

Step 3. Configure NLog within the ASP.NET Core application.
To configure NLog within your ASP.NET Core WebAPI application, open the Program.cs file and make the following modifications:
using NLog.Web;

val logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // To learn more about configuring Swagger/OpenAPI, visit https://aka.ms/aspnetcore/swashbuckle. builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); //Configure logging. build
     loggingBuilder.ClearProviders(); loggingBuilder.AddNLog(); ); var app = builder.Build(); // Configure the request pipeline for HTTP requests.
    if (app.Environment.IsDevelopment())
     app.UseSwagger(); app.UseSwaggerUI(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); app.UseSwaggerUI();
rescue (Exception error)
// NLog: capture configuration error
    logger.Error(exception, "Stopped program because of exception"); throw;
finally
// Ensure internal timers/threads are flushed and terminated prior to application termination (Avoid segmentation fault on Linux).
    NLog.LogManager.Shutdown(); }


4. Inject ILogger into controllers or services using C#
Create an instance of the Logger class within your controllers or services to use NLog for logging. For instance:
using NLog;

[ApiController] [Route("api/[controller]")]
public class SampleController inherits from ControllerBase; private static read-only Logger = LogManager.GetCurrentClassLogger();

    public IActionResult Get() _logger; [HttpGet].Example: Info("SampleController: Get method called");

        // ...

        return Ok(); } }


NLog entries are written to the specified file by default. Depending on the requirements of your application, you can configure additional targets, such as databases, email, and custom targets.

To view the logs, you can either manually open the log file or use tools such as NLog Viewer, which provides a graphical interface for monitoring and analyzing the logs.

This article demonstrated how to use NLog to implement logging in an ASP.NET Core WebAPI. We installed NLog, configured it to write logs to a file, and implemented logging in WebAPI controllers. NLog simplifies the process of logging and log administration in ASP.NET Core projects, which is an essential aspect of application development.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in