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 8.0.1 Hosting - HostForLIFE :: Difference Between ReadOnly and Constant in .NET C#

clock April 29, 2024 09:48 by author Peter

Values that cannot be changed at runtime in C# are declared using the readonly and const keywords. However, there are several notable distinctions between these two words.

Constant: Describe It
Const is a compile-time constant, meaning that its value can only be set at compile time and cannot be modified by runtime. Usually, it is used for declaring global constants, such as mathematical constants or other values that aren't expected to change throughout program execution. Const values are intrinsically static and always belong to the class; they are not particular to any one instance of the class. Since they are by nature public, they can also be accessed from anywhere in the code.

public class Constants
{
  public const string CLIENT_ID = "ClientId";
}

ReadOnly:  What Is It?
Conversely, readonly fields are runtime constants, which means that only the class's constructor has the ability to modify them. Their value is predetermined at runtime. Since the readonly fields are instance-level variables, a duplicate of each field exists in each class instance. Additionally, they can be marked as static, indicating that they are part of the class itself rather than a specific class instance. You have to specifically declare the access level because the readonly fields are not inherently public.

public class TestService
{
  private readonly ISomeService _someService;

  public TestService(ISomeService someService)
  {
    _someService = someService;
  }
}


Key distinctions in C# between readonly and constant:
Constants in C# are defined using the readonly and const keywords, although their applications and capabilities differ.

When their values are set is one of the biggest distinctions between readonly and const. Values defined with the const keyword must be set at compile time and will not change at runtime. It implies that const values are decided upon during code compilation rather than execution. Conversely, readonly values are set at runtime and can only have their values assigned within the class constructor.

Const values are also fundamentally different since they are always implicitly static—that is, they are part of the class and not an instance of it. On the other hand, readonly values need to specifically state the access level and can be either instance-level or static.

The following example demonstrates the distinctions between readonly and const:
public class TestClass
{
    public const double PI = 3.14;
    public readonly string Name;

    public TestClass(string name)
    {
        Name = name;
    }
}


In this case, the const value PI was set to 3.14 at compile time. However, Name is a read-only variable that is set in the class's constructor and can only be changed during runtime.

The way that const and readonly are accessible is another distinction between them. Readonly values require the access level to be explicitly specified, whereas const variables are always implicitly public.

While read-only variables are determined at runtime, const values are computed at compile time.
While read-only fields might be instance-level or static and require the access level to be explicitly specified, const values are always static and automatically public.

Readonly fields can only be modified within the class constructor, but const values cannot be altered at runtime.

ReadOnly vs Constant

ReadOnly keyword Const keyword
The readonly keyword in C# can be used to create readonly fields. The const keyword in C# is used to construct constant fields.
The runtime constant ReadOnly. A compile-time constant is called const.
It is possible to modify the readonly field's value. It is not possible to modify the value of the const field.
It can't be declared within the procedure. It may be specified within the procedure.
We can set values in the constructor and declaration sections of read-only fields. We can only assign values to the declaration part of const fields.
The use of static modifiers is possible. Static modifiers are incompatible with its use.

When should you use CONSTANTS versus READONLY?

Utilize constants when the values are absolute, fixed, and do not vary, such as DaysOfWeek, MonthsOfYear, mathematical PI value, and so on. Use readonly when the variables are obtained via user input, configuration files, or any other variable that does not have the same value, such as a database connection string, a secret key, and so on.

We learned the new technique and evolved together.



European ASP.NET Core 8.0.1 Hosting - HostForLIFE :: Extracting Values from PDFs in .NET Core 8 without ASP.NET

clock April 22, 2024 08:38 by author Peter

Within software development, data extraction from PDF files is frequently required for a number of activities, including content indexing, information retrieval, and data analysis. Although ASP.NET Core 8 provides powerful tools for working with PDFs, there are times when developers would rather have other options due to project needs or flexibility concerns. In this post, we'll look at how to use the PdfSharpCore library to extract values from PDF files inside the.NET Core 8 environment without utilizing ASP.NET. We'll present you a detailed how-to and C# examples to show you how to complete this task successfully.

  • Comprehending PdfSharpCore: PdfSharpCore is a well-liked.NET library designed for manipulating PDF documents. It offers tools for adding, editing, and removing material from PDF files. This tutorial will concentrate on using PdfSharpCore to extract text from PDF files.
  • Installing PdfSharpCore: Installing the PdfSharpCore NuGet package is necessary before we can use PdfSharpCore in our.NET Core application. The.NET CLI or the NuGet Package Manager Console can be used for this.

Using the NuGet Package Manager Console
Install-Package PdfSharpCore

Using the .NET CLI
dotnet add package PdfSharpCore

Extracting Text from PDFs in C#: Now that we have PdfSharpCore installed, let's dive into how we can extract text from PDF files using C#.
using PdfSharpCore.Pdf;
using PdfSharpCore.Pdf.IO;
using System;

public class PdfTextExtractor
{
    public static string ExtractTextFromPdf(string filePath)
    {
        using (PdfDocument document = PdfReader.Open(filePath, PdfDocumentOpenMode.Import))
        {
            string text = "";
            foreach (PdfPage page in document.Pages)
            {
                text += page.GetText();
            }
            return text;
        }
    }

    // Example usage:
    public static void Main(string[] args)
    {
        string pdfText = ExtractTextFromPdf("sample.pdf");
        Console.WriteLine(pdfText);
    }
}

The extracted text is returned by the static method ExtractTextFromPdf, which we have implemented in this example. It accepts the file path of the PDF as input and returns the retrieved text. Within the procedure, we access the PDF file using PdfSharpCore, loop through its pages, and extract text from each one. The extracted text is then concatenated and sent back.

Conclusion
By leveraging PdfSharpCore in .NET Core 8, developers have access to a powerful and efficient tool for extracting text from PDF files. Without relying on ASP.NET, PdfSharpCore provides a straightforward solution for handling PDF documents within the .NET Core ecosystem. Whether you're building data processing pipelines, content management systems, or document parsing utilities, PdfSharpCore empowers developers to accomplish PDF manipulation tasks effectively and seamlessly.



European ASP.NET Core 8.0.1 Hosting - HostForLIFE :: C# &.NET: Experimental Attribute

clock April 16, 2024 08:45 by author Peter

You can add the Experimental property to your types, methods, or assemblies to designate that a feature is experimental using the new Experimental attribute in C# 12. When someone tries to use the method or the type after you've done this, the compiler will throw an error. I describe how to use this functionality in this article.


I used Visual Studio 2022 Preview to construct a console application with.NET 8 and run it for demonstration purposes. Use of the Preview version is required until the article's date. This feature will not function otherwise.

The System.Diagnostics.CodeAnalysis namespace is where the Experimental attribute originates. You can see an example of a class with this attribute in the code below:

using System.Diagnostics.CodeAnalysis;

namespace DotNet8Examples
{
    [Experimental(diagnosticId: "Test001")]
    public class ExperimentalAttributeDemo
    {
        public void Print()
        {
            Console.WriteLine("Hello Experimental Attribute");
        }
    }
}


On line 1, there is the namespace for the Experimental attribute.
On line 5, there is the Experimental attribute, with the diagnosticId. For the diagnosticId, you can specify an Id, which will be used by the compiler, to report a usage of the API the attribute applies to.
On line 8, there is a method for this class.

Now, if you try to create an instance of this class, the compiler will complain about it:
var experimentalAttributeDemo = new ExperimentalAttributeDemo();

It should be noted that the Experimental property can be used in both the method and the class. You can use the NoWarn property in the.csproj file to use this class and ignore this error; this will work on a global level, so each time you try to use the class or method, you won't have to suppress the error; alternatively, you can suppress it directly on the code, which will require you to do so each time you need to use the class or method.

I'm directly suppressing the error Test001 in the code in the example below. In order to do it, you must add your code in between the #pragma warning disable Test001 and the #pragma warning restore Test001:



European ASP.NET Core 8.0.1 Hosting - HostForLIFE :: Using Identity for NET API Login and Registration

clock April 2, 2024 08:18 by author Peter

Creating reliable and secure online apps requires careful consideration of authentication and authorization. Microsoft Identity offers a strong foundation for implementing authorization and authentication features with ease in the.NET ecosystem. In this post, we'll look at how to use Microsoft Identity in conjunction with controllers to efficiently handle user registration and login functions in a.NET API.

Required conditions

Make sure you have installed the following prerequisites before continuing:

  • The.NET SDK (at least version 5)
  • Visual Studio Code (optional) or Visual Studio


Establishing the Project
Let's start by making a new.NET Web API project:

dotnet new webapi -n YourProjectName
cd YourProjectName


Adding Identity to the Project
To add Identity to your project, run the following commands:
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

This adds the necessary packages to your project for using Identity and Entity Framework Core with SQL Server.

Scaffold Identity

Next, scaffold Identity into your project:
dotnet aspnet-codegenerator identity -dc YourDbContext

Replace YourDbContext with the name of your application's DbContext.
Implementing Registration and Login Controllers:

Now, let's implement controllers for user registration and login.

1. Registration Controller

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using YourProjectName.Models;

namespace YourProjectName.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RegisterController : ControllerBase
    {
        private readonly UserManager<ApplicationUser> _userManager;

        public RegisterController(UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }

        [HttpPost]
        public async Task<IActionResult> Register(RegisterModel model)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                return Ok("Registration successful");
            }
            return BadRequest(result.Errors);
        }
    }
}

2. Login Controller
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using YourProjectName.Models;

namespace YourProjectName.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly SignInManager<ApplicationUser> _signInManager;

        public LoginController(SignInManager<ApplicationUser> signInManager)
        {
            _signInManager = signInManager;
        }

        [HttpPost]
        public async Task<IActionResult> Login(LoginModel model)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);
            if (result.Succeeded)
            {
                return Ok("Login successful");
            }
            return Unauthorized("Invalid email or password");
        }
    }
}

Models
Ensure you have the necessary models for registration and login:
namespace YourProjectName.Models
{
    public class RegisterModel
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }

    public class LoginModel
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }
}


Configuring Startup
Finally, add Identity services to the ConfigureServices method in Startup.cs:
services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<YourDbContext>()
    .AddDefaultTokenProviders();

Happy coding!



About HostForLIFE.eu

HostForLIFE.eu 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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in