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!!!

Part 1:Buy the Custom Top Level Domain Name from Azure.

Follow the link below to buy the Top level Domain name from Azure.

Buy Top-Level Domain from Azure.

Part 2:Configure a custom domain name in Azure App Service

First of all, I would like to talk about DNS(Domain Name System). The DNS uses data records to map domain names into IP addresses. There are several types of DNS records. For web apps, we use either an A record or a CNAME record.

  • An A (Address) record maps a domain name to an IP address.
  • A CNAME (Canonical Name) record maps a domain name to another domain name. DNS uses the second name to look up the address. Users still see the first domain name in their browser. For example, you could map “exploreitnepal.com” to “exploreitnepal.azurewebsites.net”.

If the IP address changes, a CNAME entry is still valid, whereas an A record must be updated. However, some domain registrars do not allow CNAME records for the root domain or for wildcard domains. In that case, you must use an A record.

Note:  IP address may change if you change the web app mode back to free, or if you delete and recreate your web app as well.

Part 2.1:Finding the Virtual IP address

Step 1: In your browser, open the Azure Portal.

Step 2: Click the Browse option on the left side of the page.

Step 3: Click the Web Apps blade.

Step 4: Select the name of your web app.

Step 5: In the another blade, click settings.

Step 6: Scroll down to the new opened blade, and click on Custom domains and SSL.

Step 7: In the Custom domains and SSL blade, click Bring External Domains“.

The IP address is located at the bottom of this part. Copy it and save where you want.

Part 2.2:Managing the domain name

Step 8: In the Custom domains and SSL blade, click the particular domain name that you had bought. Then you will be redirected to the Manage Domain blade.

Step 9: Then Click on Advanced Manage there, as shown below:

Step 10: You will be redirected to a page where the list of domain names that you had bought will be displayed, as shown below:

Step 11: Click on particular domain name and go to the “DNS ZONE FILE” as shown below:

Step 12: Click on Add Record there, as shown below:

Step 13: Then, carefully do the following:

  • Select record type = A (Host)
  • Enter your domain name in the HOST field.
  • Enter the IP that you had copied earlier in the POINTS TO field, then click on ADD ANOTHER button, as shown below:

Step 14: Similarly, add two more ZONE RECORD as shown below:

Step 15: After finishing, adding the ZONE RECORD, Close the entire tab in browser and go back to the Custom domains and SSL blade.
Step 16: Then, Click on Bring External Domains there. The Bring External Domains blade will opens. At the input field of the DOMAIN NAMES, add the Domain name that you had bought, as shown below: In my case the domain name is “www.exploreitnepal.com”.

Step 17: Click on Save, and Open the particular URL(In my case URL is: exploreitnepal.com) in browser, you will see the changes.

I got this view because I had uploaded my custom design. Congratulation! You have Successfully configured the custom domain name.

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

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

When you create a web app, Azure assigns it to a subdomain of azurewebsites.net. For example, if your web app is named exploreitnepal, the URL is exploreitnepal.azurewebsites.net. Azure also assigns a virtual IP address. For a production web app, you probably want users to see a custom domain name. And We can use Azure credits to buy Custom Domains and host it as well. This feature is not possible from the Dreamspark pass of Azure. This Blog explains how to buy and configure a custom domain with Web Apps.

Note: For instructions on using Traffic Manager to load balance traffic to a web app, use the selector at the top of this article to select the Traffic Manager specific steps.
Custom domain names cannot be used with Free web app. You must configure your web app for Shared, Basic, or Standard mode, which may change how much you are billed for your subscription.
If you don’t have a domain name for your web app, you can easily buy one on Azure Portal. During the purchase process you can choose to have WWW and root domain’s DNS records be mapped to your web app automatically. You also can manage your domain right inside Azure Portal.

Steps to Buy Domain Names:

Step 1: In your browser, open the Azure Portal.
Step 2: In the Web Apps tab, click the name of your web app. In my case, I am using “exploreitnepal” as shown below:

Step 3: Click on Setting there, a new blade will appears as shown below:

Step 4: Scroll down the blade and then select Custom domains and SSL as shown below:

Step 5: Then click on the Buy Domain  in “Custom domains and SSL “ blade as shown below:

Step 6: In the Buy Domains blade, use the text box to type the domain name you want to buy and hit Enter. The suggested available domains will be shown just below the text box. Select what domain you want to buy. You can also purchase multiple domains at once. Then, Click the Contact Information as shown below:

Step 7: Fill the domain’s Contact Information form and Click on OK.

Step 8: Now you can choose to,
a) “Auto renew” your domain every year

b) Opt-in for “Privacy protection” which is included in the purchase price for FREE

c) “Assign default hostnames” for WWW and root domain to the current Web App.

Step 9: Click the Select on Buy Domains blade, then you will see the purchase information on Purchase confirmation blade. If you accept the legal terms and click Buy, your order will be submitted and you can monitor the purchasing process on Notification.

Step 10: Domain purchase can take few minutes to complete. After getting the similar view as shown below, be sure that your domain has been bought.

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

Part 1: Creating a Website(Web App) 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: Making a Website in Web Matrix:

Step 1: Open Web Matrix.

Step 2: Click on New Then Empty Site to start a new project.

Step 3: Right Click on your site folder and click on New File.

Step 4: Type in the Name of the Page. (Please keep it index.html so that you won’t need to change the default settings in Azure).

Step 5: Edit your index.html Page as per your need. In my case, I have the code Shown as below:

Step 6: Click on the Run button to view the page in your browser.


Part 3: Deploying a Website in Azure Using Web Matrix:

Step 7: Click on the Publish button at the top left corner.

Step 8: Click on Import Publish Settings file.

Step 9: Then, Choose the file of extension .PublishSettings that you had downloaded by clicking the Get publish profile from Azure and click on open and then click on Save button.

Step 10: Click on Continue. Now the site you made will be checked to validate your code.

Step 11: You will the following screen. Now click on continue.

Step 12: Then, Web Matrix will check for the file to be uploaded. Then click on Continue.

Step 13: You will get a message as below after the site gets deployed.

Step 14: To check, Enter the link in the browser you will see the change. In my case, it looks as shown below:


Part 4: Deploying a Website in Azure via FTP:

Follow the Series of steps in Part 2 of the Link below to deploy the website in Azure. 

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

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

The File Transfer Protocol (FTP) is a standard network protocol used to transfer computer files from one host to another host over a TCP-based network, such as the Internet. FTP is built on a client-server architecture and uses separate control and data connections between the client and the server.

Part 1: Creating Web App in Azure:

STEP 1: Login to the management portal https://portal.azure.com

STEP 2: Click on New>> Web + Mobile >> Web App. As shown below:

STEP 3: Enter the Link you want and then Click on Create as shown below:


Part 2: Deploying Web App through FTP:

STEP 4: Wait for couple of Minute and let the web app succeed Deploy. After Deployment Succeed, open it and click on the Get publish profile as shown below:

Note: A file of extension .Publishsettings will be downloaded, keep it safe because it holds the Details required to publish Website.


STEP 5: Open the recently downloaded .Publishsettings shown file in notepad and find the publishURL, userName and userPWD as shown below:

Note: publishURL, userName and userPWD is required to upload your website to the web app you made via FTP.


STEP 6: Now, Open FTP Tool. In my case, I have Filezilla. So, I am uploading the file using it. In Filezilla, input the following:

  • publishURL to Host.
  • userName to Username.
  • userPWD to Password.

And click on Quickconnect. Then, it connects to the server and the message “Directory Listing Successful” will be displayed as shown as below:

STEP 7: Open the folder name “site” — >“ wwwroot” which is on the right side in the Filezilla, Shown as below:

STEP 8: Then, Drag and drop all your files and folders inside the folder “wwwroot” then it will automatically start uploading the files and folders and after upload completes enter the link (in my case, my URL is: http://himalmandap.azurewebsites.net/) that you made in Azure. You will see what you have uploaded.

Tags: Happy Coding!!! Enjoy Azure!!! Enjoy FTP!!!

What is the Cloud?

Cloud is a paradigm in which information is permanently stored in servers on the Internet and cached temporarily on clients (desktops, tablets, notebooks, wall computers, etc.)

Then, Azure is a cloud computing platform and infrastructure, created by Microsoft, for building, deploying, and managing applications and services through a global network. It includes a growing collection of integrated cloud services—analytics, computing, database, mobile, networking, storage, and web—for moving faster, achieving more, and saving money.

Some Awesome and Interesting feature of Using Azure are:

Use an open and flexible cloud service platform
Scale as you need, pay as you go
Protect your data
Run your apps anywhere
Make smarter decisions
Rely on a trusted cloud service
Build and deploy modern, cross-platform web and mobile applications