Start a project with Me today!

Contact Me

When working with ASP.NET Core, you may want to build lightweight services, i.e without templates or controller classes, to reduce resource consumption and improve performance. You can create these lightweight services and APIs in the Startup or Program classes. Let’s see how you can build such lightweight services in ASP.NET Core 6

First of all, create an ASP.NET Core project.
Following these steps will create a new ASP.NET Core Web API 6 project in Visual Studio 2022:

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create new project” and select “ASP.NET Core Web API” from the list of templates displayed.
  3. Click Next, and “Configure your new project” window, specify the name and location for the new project.
  4. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  5. Click Next and in the “Additional Information” window shown next, select .NET 6.0 (Preview) as the target framework from the drop-down list at the top. Leave the “Authentication Type” as “None” (default).

To building lightweight services that don’t require a controller, you should now delete the Controllers solution folder and any model classes that are created by default.

Next, open the launchSettings.json file under the Properties solution folder and remove or comment out the launchUrl key-value pair as shown in the code snippet given below.

The launchUrl refers to the host of your application. When the application is started, the URL specified in launchURL is used to start the application. If the URL is wrong or does not exist, the application will throw an error at startup. By removing launchUrl or commenting it out, we ensure that the application doesn’t use the default launchUrl to launch the application and thus we avoid any errors. Once the launchUrl is removed, the application will fall back to port 5000.

We’ll now take advantage of some of the extension methods of the IEndpointConventionBuilder interface to map requests. Here is the list of these extension methods:

  • MapGet
  • MapPost
  • MapDelete
  • MapPut
  • MapRazorPages
  • MapControllers
  • MapHub
  • MapGrpcServices

The MapGet, MapPost, MapDelete, and MapPut methods are used to connect the request delegate to the routing system. MapRazorPages is used for RazorPages, MapControllers for Controllers, MapHub for SignalR, and MapGrpcService for gRPC.

The following code snippet illustrates how you can use MapGet to create an HTTP Get endpoint.

endpoints.MapGet("/", async context =>
{
     await context.Response.WriteAsync("Hello World!");
});

Now create a new C# file named Person and enter the following code:

public class Person
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

Create a read-only list of Person and populate it with some data as shown in the code snippet given below.

private readonly List<Person> _persons;
        public Startup(IConfiguration configuration)
        {
            _authors = new List<Person>
            {
                new Person
                {
                    Id = 1,
                    FirstName = "Ravi",
                    LastName = "Kandel"
                },
                new Person
                {
                    Id = 2,
                    FirstName = "David",
                    LastName = "Warner"
                },
                new Person
                {
                    Id = 3,
                    FirstName = "John",
                    LastName = "Doe"
                }
            };
            Configuration = configuration;
        }

You can use the following code to create another endpoint and return the list of Person in JSON format.

endpoints.MapGet("/persons", async context =>
{
      var persons = _persons == null ? new List<Person>() : _persons;
      var response = JsonSerializer.Serialize(persons);
      await context.Response.WriteAsync(response);
});

To retrieve a particular record based on the Id, you can write the following code:

endpoints.MapGet("/persons/{id:int}", async context =>
{
   var id = int.Parse((string)context.Request.RouteValues["id"]);
   var person = _persons.Find(x=> x.Id == id);
   var response = JsonSerializer.Serialize(person);
   await context.Response.WriteAsync(response);
});

To add data using an HTTP Post endpoint, you can take advantage of the MapPost extension method as shown below.

endpoints.MapPost("/", async context =>
{
    var person = await context.Request.ReadFromJsonAsync<Person>();
    _persons.Add(person);
    var response = JsonSerializer.Serialize(person);
    await context.Response.WriteAsync(response);
});

To delete data, you can take advantage of the MapDelete extension method as shown below.

endpoints.MapDelete("/persons/{id:int}", async context =>
{
    var id = int.Parse((string)context.Request.RouteValues["id"]);
    var person = _persons.Find(x => x.Id == id);
    _persons.Remove(person);
    var response = JsonSerializer.Serialize(_persons);
    await context.Response.WriteAsync(response);
});

Finally, The complete source code of the Configure method of the Startup class:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
   if (env.IsDevelopment())
   {
        app.UseDeveloperExceptionPage();
   }
   app.UseRouting();
   app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
   await context.Response.WriteAsync("Hello World!");
});
endpoints.MapGet("/persons", async context =>
{
    var persons = _persons == null ? new List<Person>() : _persons;
    var response = JsonSerializer.Serialize(persons);
    await context.Response.WriteAsync(response);
});
endpoints.MapGet("/persons/{id:int}", async context =>
{
    var id = int.Parse((string)context.Request.RouteValues["id"]);
    var person = _persons.Find(x=> x.Id == id);
    var response = JsonSerializer.Serialize(person);
    await context.Response.WriteAsync(response);
});
endpoints.MapPost("/", async context =>
{
    var person = await context.Request.ReadFromJsonAsync<Person>();
    _persons.Add(person);
    var response = JsonSerializer.Serialize(person);
    await context.Response.WriteAsync(response);
});
endpoints.MapDelete("/persons/{id:int}", async context =>
{
    var id = int.Parse((string)context.Request.RouteValues["id"]);
    var person = _persons.Find(x => x.Id == id);
    _persons.Remove(person);
    var response = JsonSerializer.Serialize(_persons);
    await context.Response.WriteAsync(response);
});
   });
}

Lightweight services or APIs don’t have a template and don’t need a controller class to create them in. You can create such services in the Startup or the Program class.

If you want to implement authorization in the lightweight services demonstrated in this post, you should take advantage of the RequireAuthorization extension method of the IEndpointConventionBuilder interface.

Happy Coding…!!! 😉

Today in this article, I will explain how we can encrypt and secure our connection string in web config file. This post provides a basic reference on how basic protection can be achieved using the aspnet_regiis.exe tool, by default installed with .Net Framework.
So, it is always recommended to encrypt the connection string of your application because the data we have here is highly sensitive. It must be secured. Follow these instructions in order to implement “Encrypt and Decrypt Connection Strings in Web.config Using aspnet_regiis.exe

Lets have a look of plain Connection String in Web.config file before encryption. The Screenshot below shows the plain connection string before Encryption:

Step1: Open Developer Command Prompt.
You will need to open Developer Command Prompt from Start Menu > Microsoft Visual Studio 2013 > Common7 > Tools > Shortcuts
Note:  You must be log in as Administrator and right click Developer command prompt Prompt and select Run as Administrator

Note: In this Article, I explaining the process using Microsoft Visual Studio 2013. This process is same for the other versions. The only difference will be that you need to open Visual Studio Command Prompt from the folder of their respective version of Visual Studio installed on your computer.

Encrypting the Connection String in Web.Config using aspnet_regiis.exe tool. 
For encrypt the connection string in the Web.config file, you will need to use the aspnet_regiis.exe tool.
Syntax:  aspnet_regiis.exe -pef “connectionStrings” “<Path of the Folder containing the Web.Config file>”

This command requires 3 arguments:
–pef: It represents the action to be performed. In order to perform Encryption, the parameter value is -pef.
connectionStrings: It represents section of the Web.Config file to be encrypted. For this case, the value will be connectionStrings.
Path of Folder: Here we need to provide the path of folder that containing the Web.config file.

Example: aspnet_regiis.exe -pef  “connectionStrings” “D:\My Project\Testwebsite”

Above command will encrypt the all the Connection Strings in the ConnectionStrings section of Web.Config file.
 
Connection String in Web.config file after Encryption

 Access the Encrypted Connection String in Code behind
Asp.net will automatically decrypt the connection string when it is fetched in code behind, so you need to access the connection string in same way as you would be in a general way.

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Decrypt the Connection String in Web.Config using aspnet_regiis.exe

For decrypting the ConnectionString section in the Web.Config file, we will need to use the aspnet_regiis.exe tool that was used for encryption.
Syntax: aspnet_regiis.exe -pdf “connectionStrings” “<Path of the Folder containing the Web.Config file>”

 This command requires 3 arguments:
–pdf: It represents the action to be performed. In order to perform Decryption, the parameter value is -pdf.
connectionStrings: It represents section of the Web.Config file to be decrypted. For this case, the value will be connectionStrings.
Path of Folder: Here we need to provide the path of folder that containing the Web.config file.
Example: aspnet_regiis.exe -pdf  “connectionStrings” “D:\My Project\Testwebsite”

Above command will decrypt the all the Connection Strings in the connectionStrings section of Web.Config file.
Note: This decryption process is machine specific means, connectionStrings can be decrypted on the same machine where we perform encryption.

What’s The Difference Between a Coder, Programmer, Developer, and Engineer?

Software engineers, programmers, coder, developer and computer scientist all of these job titles can get complicated. Here we will describe each title and will let you know what is the exact difference between a Programmer, Coder, Developer, and Software Engineer.

What’s The Difference Between a Coder, Programmer, Developer, and Engineer?

Software engineers, programmers, coder, developer and computer scientist all of these job titles can get complicated. Well, if you are working in the technology industry, you might know the meaning of all these job titles. However, if you have to distinguish them then you will have to face a tough time.

Some of you might say that all these titles depend on the education. Well, it might be true, but there are also few peoples who claim that the company decides if you are a programmer, developer, coder or other.

Here we will describe each title and will let you know what is the exact difference between a Programmer, Coder, Developer, and Software Engineer.

Coders

If you thought that coder is someone who writes codes, then you are right. But, coders are considered the least qualified. You can also name coders a beginner in the field, who are basically skilled in one coding language.

Coders sometimes can’t do all the phases required in making of any app like the designing part or testing. They basically write pieces-of-code that can easily be assigned by the developers.

Developers And Programmers

These two titles are often used in a way that can be exchanged. Developers and Programmers are more experienced than coders or anyone who write codes. Programmers and developers are those peoples who understand at least two or three programming languages and write clean & error free codes.

As we already said, they are more experienced code writers, so they can utilize their skills to create more advanced levels of software coding. Developers, on the other hand, are considered as true professionals that can take care of all the generals like a development of a software, to check the design of the application etc.

Software Engineers

Software engineers are considered as expert coders. They are highly-experienced and are well skilled in 3 to 4 programming languages. Software Engineers uses their skills to design and implement the overall architecture of an application.

Software engineers do everything from analyzing what the particular needs of the users, going through the design, maintenance, testing and the final evaluation of the software. Not only these, software engineers often have college degrees and can demonstrate things theoretically.

So, these are the difference between a Programmer, Coder, Developer, and Software engineer. This gives a clear idea on what they do and who should you approach, in case of any problem. Hope you like the article, share it with your friends too.

Managing and Configuring custom domains in the Azure.

In Azure, we can host 10 ASP.Net websites for free. But to configure a custom domain we need the website to be scaled to either SHARED, BASIC or STANDARD mode.

First of all, purchase a domain from Go Daddy or Big Rock. Or Also from any other domain Name provider. Now, open Azure Portal and login with your Microsoft account, and create a Web App(website) there.

Part 1:   To Creating a Website in Azure:

Follow the Series of steps in Part 1 of the Link below to create the website in Azure.

Deploying a Website in Azure via FTP (File Transfer Protocol).

Part 2:   Configure your Azure Web App as:​

Step 1: Login to portal with your Microsoft Account.
Step 2: Select the Web App that you have created. In my case, I am using “hariharadhikari” as example, and is shown below:

Step 3: Then, Go to the Scale Menu there.

Step 4: Now, change “app service plan pricing tier” to either SHARED, BASIC or STANDARD mode and “Save”. This requires an active subscription. In my case, I am changing it to “BASIC” mode as shown below:

Step 5: Then, Select the Web App that you have Created and click on “Manage Domains” at the bottom of the page as shown below:

Step 6: Then, Copy the “IP Address” available at the end of the Popup Page Appeared, and keep it safe because it is needed to point your Custom Domain to Azure Web App.

Step 7: Leave it as it is and go to your domain dashboard and Update/change the “Name Server” of your domain to:

  • Primary Name Server: NS1.AFRAID.ORG
  • Secondary Name Server: NS2.AFRAID.ORG
  • Tertiary Name Server: NS3.AFRAID.ORG

Note: It may take certain time to point to the Server.

Part 3:   To Link your custom domain to Azure App:​

Step 8: Sign up at afraid. Go to Domain Menu there and click on “Add a Domain into Free DNS” there as shown below:

Step 9: Enter your “Domain Name” in Domain Input field and select “Private” from shared state and submit as shown below:

Step 10: Again, go to the domain and configure your domain similar to the domain that I have configured and remember that you must have to point the copied “IP Address” there as shown below:

Step 11: Go to Manage Domain of the Particular Web App in Azure and Configure your domain there as similar to that I have shown below:

Step 12: Then, go to the browser and enter your domain name there you will be redirected to the Web page. Now, you are done Successfully. In my case, the domain name is “hariharadhikari.com.np”. You can check it from your browser.

Note: If any problem occurred then feel free to comment your problem, I will help you.

Tags: Happy Using AZURE!!!  Happy Coding!!!