Meet The Author

I'm Ethan Jackson, An 25 years old blogger Currently living in London, United Kingdom. I'm a Skilled Blogger, Part Time web Developer And Creating new things as a web Designer.

author

ASP.NET Tutorial : Data Annotations in .NET

Leave a Comment

Data annotation is critical in modern software development for guaranteeing data integrity, readability, and clarity. Data annotations in .NET provide a standardized mechanism to transmit metadata about data objects, improving the robustness and maintainability of your code. In this article, we'll look at 25 data annotations in.NET, complete with descriptions and examples.


 What exactly are Data Annotations?

Data annotations allow developers to add metadata to data models and attributes in.NET. These annotations help to describe constraints, formatting, and validation rules, making it easier to work with data objects in a variety of scenarios, including ASP.NET applications, Entity Framework, and API validation.
'[Required]' is a required phrase.

The annotation [Required] assures that a property cannot be null. 

public class Person
{
    [Required]
    public string FirstName { get; set; }
}

2. `[StringLength]`

Defines the maximum and minimum length of a string property.

public class Product
{
    [StringLength(50, MinimumLength = 3)]
    public string Name { get; set; }
}

3. `[Range]`

Restricts a property to a specified numeric range.

public class Temperature
{
    [Range(-40, 100)]
    public int Celsius { get; set; }
}

4. `[RegularExpression]`

Validates a property against a regular expression pattern.

public class Email
{
    [RegularExpression(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$")]
    public string Address { get; set; }
}

5. `[Compare]`

Compares the values of two properties for equality.

public class User
{
    public string Password { get; set; }

    [Compare("Password")]
    public string ConfirmPassword { get; set; }
}

6. `[EmailAddress]`

Ensures that a string property contains a valid email address.

public class Contact
{
    [EmailAddress]
    public string Email { get; set; }
}

7. `[Phone]`

Validates a string property as a phone number.

public class Contact
{
    [Phone]
    public string PhoneNumber { get; set; }
}

8. `[Url]`

Check if a string property contains a valid URL.

public class Website
{
    [Url]
    public string URL { get; set; }
}

9. `[CreditCard]`

Ensures a string property contains a valid credit card number.

public class Payment
{
    [CreditCard]
    public string CardNumber { get; set; }
}

10. `[MaxLength]`

Specifies the maximum length of a string property.

public class Tweet
{
    [MaxLength(280)]
    public string Text { get; set; }
}

11. `[MinLength]`

Sets the minimum length for a string property.

public class Password
{
    [MinLength(8)]
    public string Value { get; set; }
}

12. `[DataType]`

Specifies the data type of a property.

public class Person
{
    [DataType(DataType.Date)]
    public DateTime BirthDate { get; set; }
}

13. `[Display]`

Customizes the display name for a property.

public class Product
{
    [Display(Name = "Product Name")]
    public string Name { get; set; }
}

14. `[ScaffoldColumn]`

Hides a property from a scaffolding in ASP.NET MVC.

public class Employee
{
    [ScaffoldColumn(false)]
    public int EmployeeID { get; set; }
}

15. `[ScaffoldTable]`

Specifies the table name for an Entity Framework Entity.

[ScaffoldTable("tbl_Product")]
public class Product
{
    public string Name { get; set; }
}

16. `[Editable]`

Determines whether a property is editable in MVC.

[Editable(false)]
public class UserProfile
{
    public string FirstName { get; set; }
}

17. `[Key]`

Marks a property as the primary key for an Entity Framework Entity.

public class Customer
{
    [Key]
    public int CustomerID { get; set; }
}

18. `[ForeignKey]`

Defines a foreign key relationship in Entity Framework.

public class Order
{
    public int CustomerID { get; set; }

    [ForeignKey("CustomerID")]
    public Customer Customer { get; set; }
}

19. `[Table]`

Specifies the table name for an Entity Framework entity.

[Table("Orders")]
public class Order
{
    public string OrderName { get; set; }
}

20. `[Column]`

Defines the column name for a property in Entity Framework.

public class User
{
    [Column("Full_Name")]
    public string FullName { get; set; }
}

21. `[ConcurrencyCheck]`

Indicates that a property should be included in optimistic concurrency checks.

public class Product
{
    [ConcurrencyCheck]
    public int UnitsInStock { get; set; }
}

22. `[Timestamp]`

Specifies that a property represents a database-generated timestamp.

public class Product
{
    [Timestamp]
    public byte[] RowVersion { get; set; }
}

23. `[DatabaseGenerated]`

Marks a property as database-generated.

public class Order
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int OrderID { get; set; }
}

24. `[NotMapped]`

Excludes a property from being mapped to the database.

public class User
{
    [NotMapped]
    public string FullName => $"{FirstName} {LastName}";
}

25. `[Bind]`

Specifies which properties should be included when binding data in an MVC action.

[Bind(Include = "FirstName, LastName, Email")]
public class UserProfile
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

Conclusion

Data annotations in.NET make it simple for developers to declare metadata and limitations for data models. You can improve the dependability and readability of your code by correctly applying these annotations. These annotations are useful tools in your development toolset, whether you're building online apps with ASP.NET or working with databases in Entity Framework.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/



 

Read More

SALE & Offers! WordPress 6.3 Hosting in Europe

Leave a Comment
Based on its useful features and easy to use, many developer need powerful web hosting to support their WordPress 6.3 site well. Because of that, we will inform you the Best WordPress 6.3 Hosting in Europe provider with affordable price and high quality support. After reviewed 20+ WordPress 6.3 Hosting in Europe, we had come out with the best WordPress 6.3 Hosting in Europe, control libraries, databases, technical support, and web hosting price.



SALE & Offers! WordPress 6.3 Hosting in Europe

Our Best, Cheap WordPress 6.3 Hosting in Europe Recommendation goes to HostForLIFEASP.NET, a leading web hosts who is well-known for offering high quality Windows hosting from shared hosting

About HostForLIFEASP.NET

Founded in United Kingdom, and with years’ expansion, HostForLIFEASP.NET has grown into one of top 10 WordPress 6.3 Hosting in Europe hosting providers for offers reliable and affordable web hosting services on Windows platforms. HostForLIFEASP.NET a worldwide provider of hosting support the latest release of Microsoft's widely-used WordPress 6.3 Hosting in Europe. You can take advantage of the powerful WordPress 6.3 Hosting in Europe technology in all Windows Shared Hosting, Windows Reseller Hosting and Windows Cloud Hosting Packages. 

Special Weekend SALE!

HostForLIFEASP.NET Budget Friendly Price – The service includes 4 packages called as HostForLIFE Basic, Budget, Economy and Business with the price starting at Є2.97/mo.

http://hostforlifeasp.net/ASPNET-Shared-European-Hosting-Plans.aspx
  • 30 Days Money Back Guarantee – This means webmasters are allowed to get a refund if they cancel the services because of dissatisfaction within the first 30 days.
  • Satisfactory Uptime – HostForLIFEASP.NET employs state-of-the-art data centers and advanced technologies guaranteeing 99.99% uptime shown by the following chart.

HostForLIFE WordPress 6.3 Hosting in Europe Performance

HostForLIFEASP.NET WordPress 6.3 web host reliability is absolutely outstanding compared to other comprehensive web hosting companies. HostForLIFEASP.NET is managed by a sophisticated team with lots of Windows server experts. With the correct IIS, website and file system permission configuration, the security of the hosting websites is well isolated. That means, when one website is hacked by improper code, it’s rare opportunity for other websites be affected.

http://hostforlifeasp.net/ASPNET-Shared-European-Hosting-Plans.aspxhttp://hostforlifeasp.net/European-WordPress-481-Hosting

Technical Support

As introduced above, HostForLIFEASP.NET has an experienced team on supporting ASP.NET and WordPress 6.3 Hosting in Europe. All of their technical support staffs are kindly, sophisticated and knowledgeable on either Windows platform or SQL Server 2014 databases. HostForLIFEASP.NET provides 24/7 email and ticket system support mainly. Based on our testing, the average of the first response is about 30 minutes, and it could be faster in working time. HostForLIFEASP.NET guarantees to respond each support ticket in 1 hours.

HostForLIFE is Best Option for WordPress 6.3 Hosting in Europe

Frankly speaking, HostForLIFE is best option to host your WordPress 6.3 Hosting in Europe. You just need to spend €2.97/month to host your site with them and you can install the latest WordPress via their Plesk control panel. We would highly recommend them as your WordPress 6.3 Hosting in Europe.

http://hostforlifeasp.net/ASPNET-Shared-European-Hosting-Plans
Read More

Real-time WebSocket Protocol Communication in ASP.NET Core

Leave a Comment

There are various steps involved in creating a comprehensive example of real-time communication utilizing the WebSocket protocol in ASP.NET Core. In this example, we'll build a simple chat app that allows users to send and receive messages in real time. This example assumes you are familiar with ASP.NET Core and C#.


Step 1. Create a new ASP.NET Core project

First, use Visual Studio or the command line to create a new ASP.NET Core project. You have the option of using the ASP.NET Core Web Application template and the Empty template.
Step 2: Download and install the WebSocket NuGet Package.

Microsoft.AspNetCore must be installed in your project.WebSockets is a NuGet package that adds WebSocket support.

dotnet add package Microsoft.AspNetCore.WebSockets

Step 3. Create a WebSocket Middleware
In your Startup.cs file, configure WebSocket middleware in the Configure method.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebSocketChatApp.Middleware;

Author: Peter
namespace WebSocketChatApp
{
    public class Startup
    {
        // ... other configurations ...

        public void ConfigureServices(IServiceCollection services)
        {
            // ... other services ...

            services.AddWebSocketManager();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // ... other middleware ...

            app.UseWebSockets();
            app.MapWebSocketManager("/chat", app.ApplicationServices.GetService<ChatWebSocketHandler>());

            // ... other configurations ...
        }
    }
}


Step 4. Create a WebSocket Handler
Create a WebSocket handler class to manage WebSocket connections and messages. You can name it ChatWebSocketHandler.cs.
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;

Author: Peter
namespace WebSocketChatApp.Middleware
{
    public class ChatWebSocketHandler
    {
        private readonly WebSocketConnectionManager _connectionManager;
        private readonly ILogger<ChatWebSocketHandler> _logger;

        public ChatWebSocketHandler(WebSocketConnectionManager connectionManager, ILogger<ChatWebSocketHandler> logger)
        {
            _connectionManager = connectionManager;
            _logger = logger;
        }

        public async Task HandleWebSocket(HttpContext context, WebSocket webSocket)
        {
            var socketId = _connectionManager.AddSocket(webSocket);

            _logger.LogInformation($"WebSocket connection established with ID {socketId}");

            while (webSocket.State == WebSocketState.Open)
            {
                var message = await ReceiveMessageAsync(webSocket);
                if (message != null)
                {
                    _logger.LogInformation($"Received message from ID {socketId}: {message}");
                    await BroadcastMessageAsync(message);
                }
            }

            _connectionManager.RemoveSocket(socketId);
            _logger.LogInformation($"WebSocket connection closed with ID {socketId}");
        }

        private async Task<string?> ReceiveMessageAsync(WebSocket webSocket)
        {
            var buffer = new byte[1024];
            var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

            if (result.CloseStatus.HasValue)
            {
                return null;
            }

            return System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
        }

        private async Task BroadcastMessageAsync(string message)
        {
            foreach (var socket in _connectionManager.GetAllSockets())
            {
                if (socket.Value.State == WebSocketState.Open)
                {
                    await socket.Value.SendAsync(System.Text.Encoding.UTF8.GetBytes(message), WebSocketMessageType.Text, true, CancellationToken.None);
                }
            }
        }
    }
}

Step 5. Create WebSocket Connection Manager
Create a WebSocket connection manager to keep track of connected WebSocket clients. You can name it WebSocketConnectionManager.cs.
using System;
using System.Collections.Concurrent;
using System.Net.WebSockets;

Author: Peter
namespace WebSocketChatApp.Middleware
{
    public class WebSocketConnectionManager
    {
        private readonly ConcurrentDictionary<Guid, WebSocket> _sockets = new ConcurrentDictionary<Guid, WebSocket>();

        public WebSocket AddSocket(WebSocket socket)
        {
            var socketId = Guid.NewGuid();
            _sockets.TryAdd(socketId, socket);
            return socketId;
        }

        public WebSocket? GetSocket(Guid socketId)
        {
            _sockets.TryGetValue(socketId, out var socket);
            return socket;
        }

        public ConcurrentDictionary<Guid, WebSocket>.ValueCollection GetAllSockets()
        {
            return _sockets.Values;
        }

        public Guid? GetSocketId(WebSocket socket)
        {
            foreach (var (key, value) in _sockets)
            {
                if (value == socket)
                {
                    return key;
                }
            }
            return null;
        }

        public void RemoveSocket(Guid socketId)
        {
            _sockets.TryRemove(socketId, out _);
        }
    }
}


Step 6. Create WebSocket Endpoint
Create a WebSocket endpoint in your controller to handle WebSocket connections.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.WebSockets;
using System.Threading.Tasks;
using WebSocketChatApp.Middleware;

Author: Peter
namespace WebSocketChatApp.Controllers
{
    [Route("api/[controller]")]
    public class ChatController : ControllerBase
    {
        private readonly ChatWebSocketHandler _webSocketHandler;

        public ChatController(ChatWebSocketHandler webSocketHandler)
        {
            _webSocketHandler = webSocketHandler;
        }

        [HttpGet]
        public async Task<IActionResult> Get()
        {
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
                await _webSocketHandler.HandleWebSocket(HttpContext, webSocket);
            }
            else
            {
                return BadRequest("WebSocket is not supported.");
            }

            return Ok();
        }
    }
}


Step 7. Create a Client-Side Application
Create a simple HTML page with JavaScript to connect to the WebSocket server and send/receive messages. Here's a basic example:
<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Chat By Peter</title>
</head>
<body>
    <input type="text" id="messageInput" placeholder="Enter your message" />
    <button onclick="sendMessage()">Send</button>
    <div id="chat"></div>

    <script>
        const socket = new WebSocket("ws://localhost:5000/api/chat");

        socket.onopen = (event) => {
            console.log("WebSocket connection established.");
        };

        socket.onmessage = (event) => {
            const chatDiv = document.getElementById("chat");
            chatDiv.innerHTML += `<p>${event.data}</p>`;
        };

        socket.onclose = (event) => {
            if (event.wasClean) {
                console.log(`WebSocket connection closed cleanly, code=${event.code}, reason=${event.reason}`);
            } else {
                console.error(`WebSocket connection died`);
            }
        };

        function sendMessage() {
            const messageInput = document.getElementById("messageInput");
            const message = messageInput.value;
            socket.send(message);
            messageInput.value = "";
        }
    </script>
</body>
</html>

Step 8. Run the Application
Build and run your ASP.NET Core application. Access the WebSocket chat page in your browser. You should be able to send and receive messages in real-time.

This example provides a basic implementation of a WebSocket chat application in ASP.NET Core. You can extend and customize it according.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2012 R2, SQL Server 2014, ASP.NET 7.0.4, ASP.NET MVC 6.0, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/



Read More

Best & Cheap PrestaShop 8.1.0 Hosting in Europe

Leave a Comment
HostForLIFEASP.NET are recommended as the best PrestaShop 8.1.0 hosting providers for small business owners to start a fast, reliable, secure and budget e-commerce site in Europe. HostForLIFEASP.NET offering indispensable features, 99% uptime and blazing-fast server response time at affordable prices. In fact, PrestaShop is free and open source, providing everything needed to start and manage a successful online store.
 

Best & Cheap PrestaShop 8.1.0 Hosting in Europe

PrestaShop is an open source eCommerce solution. It comes with a variety of tools necessary for building a successful online shop. To create an online store with PrestaShop you need reliable web hosting services. With hundreds of choices from every industry, the perfect store template is waiting for you. It is written in the PHP programming language with support for the MySQL database management system.

100% PrestaShop Compatibility

In order to ensure the proper installation and working of PrestaShop, you firstly need to ensure the 100% compatibility with it. After checking the documentation of its official site, in the following, we have concluded the minimum technical requirements that your selected web host needs to meet.
  • MySQL with the minimum version of 5.0.
  • PHP with the minimum version of 5.2 and the minimum PHP memory limit of 64 MB.
  • suPHP that acts as the handler of PHP language for the increased overall security.
  • Apach with the minimum version of 1.3.
  • Powerful script installer that achieves the automatic installation of PrestaShop.

HostForLIFEASP.NET is the Best PrestaShop 8.1.0 Hosting in Europe?

One of the most important things when choosing a good PrestaShop hosting in Europe is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable PrestaShop 8.1.0, their servers are optimized for PHP web applications such as PrestaShop 8.1.0 The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. Led by a team with expert who are familiar on PrestaShop technologies, HostForLIFEASP.NET offers an array of both basic and advanced PrestaShop features in the package at the same time, such as:
  • Windows 2012 as web server, ASP.NET Core 2.2.1
  • Dedicated Application Pools
  • Support the latest PHP
  • The latest ASP.NET MVC, MySQL 5.7 Databases, and SQL Server 2016 Databases
  • URL Rewrite Module, Full Trust App support, and 30+ ASP components
  • Ease-to-use Plesk Panel helps simplify setup and management
At HostForLIFEASP.NET, customers can also experience fast PrestaShop 8.1.0 Hosting in Europe. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for PrestaShop 8.1.0. And the engineers do regular maintenance and monitoring works to assure its PrestaShop 8.1.0 Hosting in Europe are security and always up.

HostForLIFEASP.NET offers four Windows and ASP.NET with PrestaShop 8.1.0 Hosting in Europe packages as you can see on the below picture:SPECIAL OFFER PrestaShop 8.1.0 Hosting in Europe

Loading Speed

HostForLIFEASP.NET builds an excellent PrestaShop 8.1.0 Hosting in Europe environment to deliver customers a fast page loading speed in the industry, which will run up to around 1.5s. With this fast speed, visitors will not waste much time in waiting for loading pages and have a better surfing the Internet experience. And there are several important factors to maintain the fast page loading speed of HostForLIFEASP.NET PrestaShop websites all the time, like powerful datacenters, rock-solid equipment, advanced servers, world-class PrestaShop engineers and more.

http://hostforlifeasp.net/European-PrestaShop-1705-Hosting.aspx

Review on Performance

HostForLIFEASP.NET guarantees to provide 99.9% uptime and fast hosting speed for all their customers to run sites stably and rapidly. To keep this promise, this company has equipped each of their state-of-the-art data center with quality servers, armed security and many cutting-edge technologies like UPS battery backup power and dual diesel generators.


Furthermore, the data center is equipped with cooling system and fire suppression including a pre-action dry pipe system. In addition, the data center, servers and network are under 24×7 monitoring carried out by a group of technicians. Therefore, any unexpected issue can be resolved immediately, ensuring customers can run sites with maximum reliability and performance. 

Review on Technical Support 

When it comes to technical support, no matter when meeting any hosting issue, customers are able to contact the support team by starting live chat, email, helpdesk or writing a ticket. Support staffs are standing by 24 hours a day and 7 days a week, so they are able to respond quickly and offer instant and effective assistance.

Cheap PrestaShop 8.1.0 Hosting in Europe

HostForLIFE.eu provides one of the Best, Cheap PrestaShop 8.1.0 Hosting in Europe Recommendation in the industry for its affordable price, rich feature, professional customer support, and high reliability. It’s highly recommended for asp.net developers, business owners and anyone who plan to build a web site based on ASP.NET. To know more about HostForLIFE.eu or its PrestaShop 8.1.0 Hosting in Europe, please visit HostForLIFE.eu, and get a PrestaShop 8.1.0 website.

PrestaShop 8.1.0 Hosting http://hostforlifeasp.net/European-PrestaShop-1712-Hostingin Europe


Read More

ASP.NET Tutorial : Implementation of NLog in.Application for the Internet Core

Leave a Comment

NLog is a free and open-source library. If you install the NLog package in your application, you are not required to perform any license-related actions.


The logging foundation for.Net or.Net Core is NLog.
NLog will assist you in troubleshooting the application error and resolving your issue.

How do you incorporate the NLog package into your application?

There are two methods for installing the NLog package.

Command
Manually launch the Nuget package manager, navigate to NLog, and install it.

Command
Install the NLog.Web.AspNetCore package.

Install the NLog manually
Open the project at the location where you wish to use NLog.
Right-click the solution and then select Manage Nuget Packages.
Enter NLog in the search box.Web.AspNetCore.

Once it is installed in your system, you can verify it on the below screenshot. 

NLog provides different logging levels. The following log levels are supported:

  • Info
  • Error
  • Debug
  • Trace
  • Fail
  • Fatal

Initialize the logger in your application.

using Microsoft.AspNetCore.Mvc;
using NLog;

namespace NLogApplication.Controllers
{
    public class ValuesController : ControllerBase
    {
        private readonly Logger _logger;

        public ValuesController()
        {
            _logger = LogManager.GetCurrentClassLogger();
        }
    }
}

Configuring the logger in your application.

You need to create the nlog.config file in your solution.

Once you have created the file, you need to right-click it and select its properties.

Change the build action to None and Copy to Output Directory to Copy always.

The below content would be required for the 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">

  <variable name="verbose" value="${longdate} | ${machinename} | ${processid} | ${processname} | ${level} | ${logger} | ${message}"/>

  <targets>
    <target xsi:type="File"
            name="file"
            layout="${verbose}"
            fileName="nlog.log"
            archiveFileName="log.{#}.log"
            archiveNumbering="Date"
            archiveEvery="Day"
            archiveDateFormat="yyyyMMdd" />
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="file" />
  </rules>
</nlog>

To demonstrate whether the logs are working or not, you need to run the application.

Try to create one dummy API for that, as below.

using Microsoft.AspNetCore.Mvc;
using NLog;

namespace NLogApplication.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly Logger _logger;

        public ValuesController()
        {
            _logger = LogManager.GetCurrentClassLogger();
        }

        [HttpGet]
        public IActionResult Get()
        {
            _logger.Info("This is the NLog Info.");
            _logger.Debug("This is the NLog Debug.");
            return Ok(DateTime.Now);
        }
    }
}

Build the solution, and if you find any solution errors, please resolve those errors. Once your solution builds successfully, please run the application. Once your application will run successfully in your browser, open Swagger or Postman and try to hit the API.


 Click on the Try it out button in the swagger documentation.


Click on the Execute button. Once the execution is done, look at the below screenshot.


For logging regarding verification, you need to follow the below steps.

  1. Right-click on your application in the solution explorer.
  2. Click on the Open Folder in file explorer.
  3. Go to the bin folder.
  4. Go to the Debug folder.
  5. Go to the .net 6.0 folder.
  6. Inside that, you have found the nlog.log file.

Open that file, and seems you see the logs inside that file as below. 


Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
 
https://hostforlifeasp.net/


Read More

Which is the Best nopCommerce 4.60.4 Hosting in Australia?

Leave a Comment
Choosing the Best nopCommerce 4.60.4 Hosting in Australia, we'll offer you with the answer.  nopCommerce is the best open-source e-commerce shopping cart. nopCommerce is available for free. Today it's the best and most popular ASP.NET ecommerce software. It has been downloaded more than 1.8 million times! nopCommerce is a fully customizable shopping cart. It's stable and highly usable. nopCommerce is an open source ecommerce solution that is ASP.NET (MVC) based with a MS SQL 2008 (or higher) backend database. Our easy-to-use shopping cart solution is uniquely suited for merchants that have outgrown existing systems, and may be hosted with your current web host or our hosting partners. It has everything you need to get started in selling physical and digital goods over the internet.

nopCommerce 4.60.4 Hosting in Australia

DiscountService.biz is a line of business under Macrodata Enterprise (ABN: 42 797 697 621), specializes in providing web hosting service to customers in Australia. DiscountService.biz is an excellent nopCommerce 4.60.4 hosting provider focusing on providing rich-featured and super fast web hosting solutions to all kinds of customers ranging from personal bloggers to enterprises. Now webmasters wonder whether this company is good for nopCommerce 4.60.4 websites, so our editors conduct a comprehensive review on the company in price, features, usability, uptime, speed and technical support.

DiscountService.biz offers a variety of cheap and affordable Australia Windows ASP.NET Shared Hosting Plans to fit any need. No matter whether you’re starting a Blog with WordPress, installing a CMS solution with Drupal, opening a Forum with PHPBB, starting an Online Store with nopCommerce 4.60.4, or any number ventures beyond those mentioned above, our Windows ASP.NET Web Hosting plans are exactly what you’ve been looking for.
 
http://discountservice.biz/Australia-Moodle-1704-Hosting

DiscountService.biz nopCommerce 4.60.4 Hosting Review on Feature, Price and Performance
Available at this low price, the Beginner plan comes with sufficient web hosting resources and the latest versions of almost all the widely-used software, such as unlimited 2 GB Disk Space storage, 20GB monthly data transfer, unlimited hosted domains, PHP 5.5, MySQL 5.5, SQL 2008/2012/2014, etc. As a leading small to mid-sized business web hosting provider, they strive to offer the most technologically advanced hosting solutions available to their customers across the world. Security, reliability, and performance are at the core of their hosting operations to ensure each site and/or application hosted on their servers is highly secured and performs at optimum level. Unlike other web hosting companies, they do not overload their servers.

http://discountservice.biz/

All DiscountService.biz servers are equipped with minimum Intel Dual Processor Multi Core, 8 GM RAM and the fastest 1,000 Mbps connection backbone. This is to ensure that all sites hosted on their server has an access to the best performance, reliability and connectivity feature.

DiscountService.biz data center is located at Sydney, NSW. Their data centers are built upon a unique pod design concept, making them functionally independent with distinct and redundant resources, and fully integrated through their revolutionary network architecture. You can have direct control over your system in any data center and full access to all of their back-end services—all fully automated and on demand.

Support Service for Customers
DiscountService.biz has been committed to providing 24/7 qualified, experienced and patient customer supports via multitudes of supporting ways, like helpdesk, support ticket and email. It is proved that any issue can be handled as soon as possible. Furthermore, nopCommerce 4.60.4 customers can solve their problems by themselves via the guidance of NopCommerceTutorial & Articles, Discussion Board and Blog.

DiscountService.biz nopCommerce 4.60.4 Hosting is the Best Hosting in Australia
In short, DiscountService.biz offer nopCommerce 4.60.4 friendly hosting solutions which are featured rich, fast, reliable, and affordable. Taking these factors into consideration, DiscountService.biz is strongly recommended for people to host their nopCommerce 4.60.4 site.
Read More

How to Convert Excel Data Into DataTable?

Leave a Comment

To deal with Microsoft Excel, the.NET Excel framework is fast and feature-rich. This framework includes an Excel creation and editing library, which enables you to create, read, and edit Microsoft Excel files in any.NET application. It includes a Spreadsheet UI control inspired by Excel for creating, editing, viewing, and formatting Excel documents. Its robust conversion APIs make it simple to convert Excel files to PDF, pictures, and other formats. We shall convert Excel data to datable in this article.


In this article, we will convert Excel data into datable.

Task 1. Create a sample ASP.NET Core Web API

In this task, you will see how to create a new sample .NET ASP.NET Core Web API using Visual Studio 2022 and the respective code of conversion from the Excel sheet to the data table.

Step 1. Open Visual Studio 2022 and click Create a new project.

Step 2. Search ASP.NET in the search bar, select ASP.NET Core Web API project template, and click Next.


 

Step 3. Enter the project name as ConvertExcelToDataTable Next.


 
Step 4. Select .NET Core as Framework. Click Create.


Step 5. Expand the Controller folder in the solution explorer, right-click WeatherForecastController.cs file, and click Delete. Right-click WeatherForecast.cs file and click Delete.

Step 6. Right-click the Controllers folder, click Add, and then click Controller.

Step 7. Select API -> API Controller with read/write actions. Click Add.


 Step 8. Leave the default name and click Add.


Task 2. Add Code in the ConvertController project
Step 1. Create a folder ‘’Model’ and add a class in it with the name of FileModel.cs file and replace the code with the following as shown below.
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace ConvertExcelToDataTable.Model

{
    public class FileModel
    {
        [JsonProperty(PropertyName = "IFormFile")]

        public IFormFile FromFile { get; set; }
    }
}

Install Nuget Package Newtonsoft.json (13.0.3)

Step 2. Create a folder ‘’Classes’ and add a class in it with the name of  ConvertCSVtoDataTable.cs file and replace the code with the following as shown below.
using ConvertExcelToDataTable.Model;
using System;
using System.Data;
using System.IO;
using System.Threading.Tasks;

namespace ConvertExcelToDataTable.Classes
{
    public class ConvertCSVtoDataTable
    {
        public async Task<DataTable> ConvertData(FileModel fileModel)
        {
            DataTable dt = new DataTable();

            try
            {
                string strFilePath = Path.Combine(Directory.GetCurrentDirectory(), "UploadedFiles", fileModel.FromFile.FileName);

                // Create file in local path to read

                using (Stream stream = new FileStream(strFilePath, FileMode.Create))
                {
                    fileModel.FromFile.CopyTo(stream);
                }

                using (StreamReader sr = new StreamReader(strFilePath))
                {
                    string[] headers = sr.ReadLine().Split(',');

                    foreach (string header in headers)

                    {
                        dt.Columns.Add(header);
                        dt.Columns[header].DataType = typeof(String);
                    }

                    if (!sr.EndOfStream)
                    {
                        while (!sr.EndOfStream)
                        {
                            string[] rows = sr.ReadLine().Split(',');
                            DataRow dr = dt.NewRow();
                            for (int i = 0; i < headers.Length; i++)
                            {
                                dr[i] = rows[i];
                            }
                            dt.Rows.Add(dr);
                        }
                    }

                    return await Task.FromResult(dt);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}


Step 3. Open controller “ConvertController” and replace the code with the following one.
using ConvertExcelToDataTable.Classes;
using ConvertExcelToDataTable.Model;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace ConvertExcelToDataTable.Controllers
{
    public class ConvertController : Controller
    {
        [HttpPost]
        [Route("api/FileUpload")]
        public async Task<JsonResult> Index(FileModel fileModel)
        {
            var obj = new ConvertCSVtoDataTable();
            var response = await obj.ConvertData(fileModel);
            return new JsonResult(fileModel.FromFile.FileName);
        }
    }
}


Step 4. Open StartUp.js for swagger configuration and replace the code with the following one.
public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "ConvertExToDt",
                    Description = "ConvertExToDt",
                });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "WHS");
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();

            });

        }


    Install Nuget Package Swashbuckle.AspNetCore.Swagger (6.5.0)
    Install Nuget Package Swashbuckle.AspNetCore.SwaggerUI (6.5.0)

Task 3. Testing
In this task, you will see how to test the API to generate the logs in the respective file.

Hit F5 to run the API locally, and Swagger will be displayed. Expand /api/values and click Try it out. Click Execute to get the response as shown below.


 Click on Choose File button and select an Excel File

The code will execute, and it will show you the expected result as below. 


In the swagger response, you can see the Excel file name.

Note. If you want to ass additional validation and conditions, then please use the data table response and use the loop conditions. Create a folder in your root project path with the name of UploadedFiles.

Task 4. Clean up resources

Once execution will be done, remove the file from the local folder.

HostForLIFE is Best Option for ASP.NET Core 8 Hosting in Europe

Frankly speaking, HostForLIFE is best option to host your ASP.NET Core 8 Hosting in Europe. You just need to spend €2.97/month to host your site with them and you can install the latest ASP.NET Core 8 via their Plesk control panel. We would highly recommend them as your ASP.NET Core 8 Hosting in Europe.

http://hostforlifeasp.net/European-ASPNET-Core-2-Hosting

 

Read More
Previous PostOlder Posts Home