Quantcast
Channel: All About ASP.NET and ASP.NET Core 2 Hosting BLOG
Viewing all 427 articles
Browse latest View live

ASP.NET Core - ASPHostPortal.com :: Centralized ASP.NET Core Logging in One Line of Code

$
0
0

Centralized ASP.NET Core Logging in One Line of Code

ASP.NET Core comes with some great built-in logging. Framework components such as Routing, MVC and EntityFramework have been updated to support structured logging throughout - for example, when MVC selects a controller and action it includes ActionName in a log event so that later, you can drill down easily to requests hitting a specific action. The framework also adds convenient properties like RequestId to log events by default, making it trivial to zoom in on just the events raised during handling of a particular HTTP request. Setting up truly great application logging in an ASP.NET app has never been easier.

Seq has had first-class support for ASP.NET Core apps through Serilog since the early beta releases.
Just recently, we've taken this a step further. On File > New Project precious time spent configuring libraries can really add up. We want Seq to be so simple to include that there's no reason to put it off until later. That's why we've created a new package, Seq.Extensions.Logging, that gets centralized logging configuration down to just one line of code.

Seq.Extensions.Logging

Here's all it takes to get a new ASP.NET Core app hooked up to Seq. First, add the package:

"dependencies": {
  "Seq.Extensions.Logging": "1.0.1"
}

Then in your Startup class's Configure() method, call AddSeq():

public void Configure(IApplicationBuilder app, 
                      IHostingEnvironment env,
                      ILoggerFactory loggerFactory)
{
    loggerFactory.AddSeq("http://localhost:5341");

The AddSeq() method supports a few more parameters including the logging level and API key if one is needed. It can also pull configuration from appsettings.json for simple deployment-time configuration.
Once the logger is configured, you will immediately see some events from the framework on each request. You can add logging to your own code by taking a dependency on Microsoft.Extensions.Logging's ILogger<T>:

class HomeController : Controller 
{
    readonly ILogger<HomeController> _log;

    public HomeController(ILogger<HomeController> log)
    {
        _log = log;
    }

    public IActionResult Index()
    {
        var secret = 42;
        _log.LogInformation("The secret number is {Secret}");
    }
}

Notice that ASP.NET Core logging has full support for message templates, meaning tokens like {Secret} in the log message will be translated into fully-searchable properties in Seq.

Under the hood

The API of Seq.Extensions.Logging is complete: you can comfortably use it all the way through to production without thinking about how any of it works under the hood. But, if you find you need more control over how log events are collected, or if you'd like to use more advanced Serilog features to enrich or filter events, it's easy to migrate over to Serilog.
Under the hood, the package wraps Serilog, the Serilog provider for Microsoft.Extensions.Logging, and the other bits and pieces of plumbing that make Seq and Serilog work together. Replacing AddSeq() with AddSerilog() is straightforward and mechanical, and all of your logging will continue working in exactly the same way.

Levelling up

There's a whole host of interesting details on ASP.NET Core's logging in the official documentation. Taking some time to learn how to use the API can make your application much easier to debug once it's out there in production.
Don't forget to Install-Package Seq.Extensions.Logging and AddSeq() next time you're starting out on ASP.NET Core!


ASP.NET Hosting - ASPHostPortal.com :: Using Microsoft Enterprise Library in ASP.NET

$
0
0

In this tutorial we will show you how to using Microsoft Enterprise Library is a collection of reusable software components used for  logging, validation, data access, exception handling etc.

Here I am describing how to use Microsoft Enterprise Library for data access.

Step 1: First download the project from
http://entlib.codeplex.com/ URL.
Step 2: Now extract the project to get

Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Configuration.Design.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.ObjectBuilder.dll


And give reference in the Bin directory by Right click on Bin -> Add Reference -> then give the path of these 4 dlls. Then

Step 3: Modification in the web.config for Connection String.

<add name="ASPHostPortalConnection" providerName="System.Data.SqlClient" connectionString="DataSource=ASPHostPortalSQLEXPRESS;Initial Catalog=ASPHostPortal;User ID=sa;Password=admintest;Min Pool Size=10;Max Pool Size=100;Connect Timeout=100"/>


Give the connection string as above where Datasource is your data source name, Initial Catalog is your database name and User ID and Password as in your sql server.

Step 4:

Now it is time to write the code.

Write the below 2 lines in the using block.

using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

Here I am writting some examples how to work on:

public DataTable Read()
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
            DbCommand dbCommand = db.GetStoredProcCommand("[Topics_Return]");
            DataSet dataSet = db.ExecuteDataSet(dbCommand);
            return dataSet.Tables[0];
        }
        catch
        {
            return null;
        }
    }


The above code is a sample that will return a dataset. Here Fewlines4bijuConnection is the connection name and Topics_Return is the stored procedure name that is nothing but a Select statement.
But if the stored procedure is taking parameter then the code will be like:

 public int Save()
    {
        Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
        DbCommand dbCommand = db.GetStoredProcCommand("Topics_Save");

        db.AddInParameter(dbCommand, "@Subject", DbType.AnsiString, "Here is the subject");
        db.AddInParameter(dbCommand, "@Description", DbType.AnsiString, "Here is the Descriptiont");      
        db.AddInParameter(dbCommand, "@PostedBy", DbType.Int32, 4);       
        db.AddOutParameter(dbCommand, "@Status", DbType.AnsiString, 255);
        try
        {
            db.ExecuteNonQuery(dbCommand);
            return Convert.ToInt32(db.GetParameterValue(dbCommand, "Status"));
        }
        catch
        {
            return 0;
        }
    }

As the code explained above ASPHostPortalConnection is the connection name and Topics_Save is the stored procedure name that is taking 3 (Subject,Description,PostedBy) input parameters and 1(Status) output parameter.

You may give values from textbox, I am here provideing sample values like  "Here is the subject", "Here is the Descriptiont" or you may give the UserID from session, I am here giving 4. The output parameter will give you a string as defined and the code to get the value is

int returnValue=Convert.ToInt32(db.GetParameterValue(dbCommand, "Status"));

you can pass input parameter as below

db.AddInParameter(dbCommand, "@Subject", DbType.AnsiString, "Here is the subject");

DbType.AnsiString since Subject is of string time, you can select different values like AnsiString, DateTime from the Enum as be the parameter type.

The above code describes if you are using any stored procedure.
Below is an example that shows how to use inline SQL statements.

public DataSet GetID(string title)
    {
       DataSet ds=new DataSet();

        try
        {
            Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
            DbCommand dbCommand = db.GetSqlStringCommand("Select * FROM Topics where UserID=1 and
IsDeleted=0");          
            ds= db.ExecuteDataSet(dbCommand);
           return ds;         
        }
        catch
        {
            return ds;
        }
         return ds;
    }


Happy coding!!

 

Best ASP.NET Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

ASP.NET Hosting - ASPHostPortal.com :: Creating Default User Roles in ASP.NET MVC

$
0
0

ASP.NET MVC 5 is the latest update to Microsoft's popular MVC (Model-View-Controller) technology - an established web application framework. MVC enables developers to build dynamic, data-driven web sites. MVC 5 adds sophisticated features like single page applications, mobile optimization, adaptive rendering, and more.


In this article, We'll look into how to create default user roles in ASP.NET MVC 5.Let's begin by establishing where the user role is assigned, and that is the registration stage. In the default template, you have the AccountController that contains a Register action. The default implementation looks like this:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        try
        {
            WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
            WebSecurity.Login(model.UserName, model.Password);
            return RedirectToAction("Index", "Home");
        }
        catch (MembershipCreateUserException e)
        {
            ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}


What's missing here is the role assignment, so let's add that. Right after the CreateUserAndAccount call, we can check whether a specific role exists, and if it is - add the registered user to it. In case the role is new, create it.

if (!Roles.RoleExists("Standard"))
    Roles.CreateRole("Standard");
Roles.AddUserToRole(model.UserName, "Standard");


Here I am working with a role called Standard, but obviously you can use another identifier for it. If you open the database that is carrying the app data, you will notice that there are two new tables introduced in the existing context - Roles and UsersInRoles.

As the data skeleton is established, you can now limit content access based on roles. In views, you could use the Authorize attribute:

[Authorize(Roles = "Admin")]

Or you could check for the role directly:


@if (Roles.GetRolesForUser().Contains("Admin"))
{
}

That's the tutorial How to create Default User Roles in ASP.NET MVC 5, for more information about ASP.NET MVC 5 Hosting please feel free to visit ASPHostPortal.com.

Best ASP.NET Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

ASP.NET Hosting - ASPHostPortal.com :: Improve Performance of an ASP.NET Website

$
0
0

Improve Performance of an ASP.NET Website

In this tip, we will look at various aspects of improving the performance of ASP.NET web applications.
Performance is an important aspect of the modern day web application development. Here are some tips that you can consider while making a better performing website.

1. Upgrade Your ASP.NET Framework

Check your .NET framework. If you can upgrade your site to use .NET 4.5, then it has some great performance optimizations. .NET 4.5 has a new Garbage Collector which can handle large heap sizes (i.e., tens of gigabytes). Some other improvements are Multi-core JIT compilation improvements, and ASP.NET App Suspension. These optimizations do not require code changes.

2. Caching

Use output caching – Use output caching for regularly used views or pages which have no dynamic updates. The easiest way to implement cache on MVC view is to add an [OutputCache] attribute to either an individual controller action or an entire controller class. Here is a controller action Index() that will be cached for 15 seconds.

[OutputCache(Duration = 15, VaryByParam = "None")]
public ActionResult Index(string Id)
{
}

Use Data caching - Reduces the database or the disk I/O by caching the regularly used data to in-memory cache. This avoids repeated queries for data, and it can improve performance and scalability. In addition, caching makes data available when the data source is temporarily unavailable. The .NET Framework provides classes that enable you to use caching facilities in ASP.NET applications. These classes are defined in the System.Runtime.Caching namespace.

3. Always keep CSS and JavaScript External

Never add any JavaScript or inline style information within the views. That would regenerate the view each time and you would miss out on the benefits of the Caching. Hence always keep JS and CSS as separate files and add them as links in the view.

4. File Compression

There are often requests to the web server with lot of static content. These contents can be compressed thereby reducing the bandwidth on requests. The following setting is only available in II7 and later.

configuration> 
    <system.webServer>   
        <urlCompression doStaticCompression="true" doDynamicCompression="true" /> 
    </system.webServer>

The urlCompression name sounds strange but it is not really the compressing of URLs. It means compressing or gzipping the content that is sent to the browser. By setting to true/enabling, you can gzip content sent to the browser while saving lots of bandwidth.

5. Bundling and Minification

The custom CSS files and the JavaScript files should be bundled into a single large file (reduces the number of HTTP requests) and also minified (reduces the size of the data transferred over the wire).

6. CDN (Content Delivery Network)

All the 3rd party JavaScript files such as JQuery, Knockout should always use the CDN instead of the web application server. CDN Servers are dedicated to deliver the static content and is always faster than your own host. There is a very high probability that the client (browser) would have already cached the JavaScript as part of other web application since most of them use the same CDN URL.

7. Control Image Requests

There are couple of ways to do this. 

Image sprite - With image sprite, you can combine multiple different images into a single large image. Then use CSS to reposition those images within the site.
Base64 Data URIs - With this option, you would never make any requests to the server to obtain any images.

8. Script Rendering Order

Move the script tags <script> to the very bottom of the page. The reason this is important is because during the rendering, when the browser comes across a <script> tag, it stops to process the script and then moves ahead. If you put the script tags at the bottom of the page, the page/HTML will render faster and the scripts can execute after the DOM elements have loaded. Sometimes moving the script to the bottom of the page is not possible as some DOM elements or CSS may depend on these scripts, so they can be rendered. In such cases, you could move those scripts further up the page.

There are some other ways:

  • 1.defer attribute

Hide Copy Code

<script src="some.js" defer>
</script>

Using the defer attribute, you can specify the script not to run until the page has been fully loaded.

  • 2.async attribute

<script src="some.js" async>
</script>

Using the async tag, the scripts will be run asynchronously, as soon as it is available.

9. Removing Default HTTP Modules in ASP.NET

ASP.NET has many http modules waiting for request to be processed and would go through the entire pipeline even if it’s not configured for your application.
All the default modules will be added in the machine.config place in“$WINDOWS$\Microsoft.NET\Framework\$VERSION$\CONFIG” directory. One could improve the performance by removing those modules which you wouldn’t require.

10. Compile in Release Mode

Always set the build configuration to release mode for the website.

In this tip, we looked at some of the approaches that you can take to make optimized and better performing web sites. This included, reducing number of requests to the server, changes to the .NET framework, and compressing techniques.

Best ASP.NET Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

ASP.NET Hosting - ASPHostPortal.com :: How To Using DataAnnotations and Localization in ASP.NET Core MVC

$
0
0

Using DataAnnotations and Localization in ASP.NET Core MVC

This article shows how ASP.NET Core localization can be used together with data annotations. The data annotations are used to decorate the data model, and when HTTP POST/PUT (also PATCH) Requests are sent with model errors, the error message is returned localized in the request culture.

Localization Setup

In the Startup class, the AddDataAnnotationsLocalization is added in the ConfigureServices method.   

services.AddMvc()
   AddViewLocalization()
   AddDataAnnotationsLocalization();

Now a model class can be created and the data annotations can be used. The Length property in this example has a range attribute, with an ErrorMessageResourceName and an ErrorMessageResourceType property set. The ErrorMessageResourceType is used to define the resource itself using the type and the ErrorMessageResourceName is used to define the resource identifier. Only the Length property has localized error messages implemented.

using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Globalization;
using AspNet5Localization.Controllers;
using Microsoft.Extensions.Localization;  
namespace AspNet5Localization.Model
{
    public class Box
    {
        public long Id { get; set;
        public double Height { get; set;
        public double Width { get; set; }
        [Required(ErrorMessage = "BoxLengthRequired")]
        [Range(1.0, 100.0, ErrorMessage = "BoxLengthRange")]
        public double Length { get; set; }
    }
}

Now a MVC 6 controller can be created which uses the model class. This controller implements POST and PUT action methods, which uses the ModelState to validate the request. If the model is invalid, the error message is returned with a localized value.

using AspNet5Localization.Model;
using Microsoft.AspNetCore.Mvc;
namespace AspNet5Localization.Controllers
{
    [Route("api/[controller]")]
    public class BoxesController : Controller
    {
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            if (id == 0)
            {
                return NotFound(id);
            }
            return Ok(new Box() { Id = id, Height = 10, Length = 10, Width=10 });
        }
 
        /// <summary>
        /// http://localhost:5000/api/boxes?culture=it-CH
        /// Content-Type: application/json
        ///
        /// { "Id":7,"Height":10,"Width":10,"Length":1000}
        /// </summary>
        /// <param name="box"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Post([FromBody]Box box)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            else
            {          
                string url = Url.RouteUrl("api/boxes", new { id = 11111 },
                    Request.Scheme, Request.Host.ToUriComponent());
 
                return Created(url, box);
            }
        }
 
        [HttpPut("{id}")]
        public IActionResult Put(int id, [FromBody]Box box)
        {
            if(id == 0)
            {
                return NotFound(box);
            }
 
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            else
            {
                return Ok(box);
            }
        }
 
        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            if (id == 0)
            {
                return NotFound(id);
            }
 
            return new NoContentResult();
        }
    }
}

Now the POST method can be called in Fiddler or Postman. Underneath is an example of a HTTP POST Request using the it-CH culture. The length property is outside the range and will return an model state error.

http://localhost:5000/api/boxes?culture=it-CH
User-Agent: Fiddler
Host: localhost:5000
Content-Length: 46
Content-Type: application/json
{ "Id":7,"Height":10,"Width":10,"Length":1000}
HTTP Response with a it-CH localized error message:
HTTP/1.1 400 Bad Request
Date: Sat, 24 Oct 2015 17:15:28 GMT
Content-Type: application/json; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked
{"Length":["The box length should be between 1 and a 100 it-CH"]}

Localization can be used in data annotations like previous versions of MVC or Web API and provides a simple way of validating your data inputs.

Best ASP.NET Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

ASP.NET Core 2 Hosting - How to Publish ASP.NET Core 2

$
0
0

This tutorial will show you how to publish ASP.NET Core on IIS. The following is steps by steps to deploy .net Core.

Program class in asp.net core 2.0 contains a method that is called “CreateDefaultBuilder”. It is responsible for setting up everything for your application related to hosting, manage server, IIS integration, create directory etc.

public class Program {  
    public static void Main(string[] args) {  
        BuildWebHost(args).Run();  
    }  
    public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args).UseStartup < Startup > ().Build();  
}

Just go through with CreateDefaultBuilder method's actual definition using F12 in Visual Studio, you can read the comment which specifies its tasks.

The deployment is not the same as Asp.Net, there are a few more components required to host your asp.net core 2.0 application on IIS. Before deploying, you have to install a bundle which is required to host Asp.Net Core 2.0 application on IIS and that is .Net Core Windows Server Hosting. This bundle will install .Net Core Runtime which provides all the required libraries on runtime, .Net Core Library and Asp.Net Core Module.

If you are still using Asp.Net Core 1.x then you can find out the “.Net Core Windows Server Hosting” bundle using the following link and install it.

Here we are using Asp.Net Core 2.0 application to deploy it on IIS, so we are going to download .Net Core Windows Server Hosting bundle from following link and install it with our system.

When it is in progress, you can see it is installing three main components: .Net Core Runtime, .Net Core Library and Asp.Net Core Module. As you can see in the following image, Microsoft .Net Core Runtime is being installed.

Warning

Please make sure you have restarted your system before moving to the next step after the installation of “Microsoft .Net Core Windows Server Hosting” bundles.

For this demonstration, we are using the same Asp.Net Core 2.0 application which we have created in previous article. To learn how to create First application in Asp.Net Core 2, please refer to following article.

First Application In ASP.NET Core MVC 2.0

Let’s move to Visual Studio 2017 version 15.3 which provides .Net Core 2 features.  Open the Asp.Net Core 2.0 application which we have created in last article. Open the solution explorer and right click to project and choose Publish option for publishing this web application.

It will open a new windows as following, which provide us three different options to publish our web application and these options are “Azure”, “IIS,FTP” and “Folder”. So, here are choosing “Folder” to publish our web content”. You have to provide the destination path where you would like to publish web application and then click to “Publish”.

It will start publishing content on selected folder as following image shown. Once everything will fine, it will show Publish Successes message.

Now it’s time to create a new website inside the IIS Manager, to open IIS Manager, just type “inetmgr” in “Search Program and files” in start menu. It will open IIS Manager for you as following image shown where you can manage you application.

Just right click to “Sites” and choose “Add Web Site..”.

In next window, you have to define you “Site Name”, physical path where you have published you application earlier and host name to find on web browser as below image. Don’t change Port and anything else and just click to OK.

Now we are almost done but need to change the “Application Pools” for this site. Click to application pools from the left panel and choose you pools as “asp.netcore2.com” and double click on that. Now you can edit you “Application Pool” for this website. From this window, you have to changes “.Net Framework  version” or “.Net CLR version” with “No Managed Code” and OK. 

Last thing, what you need to do, just make one entry about your application inside the host file, which is located on the following location. You have to add one more entry as we have done for asp.netcore2.com which directly points to localhost IP address.

C:\Windows\System32\drivers\etc

The time has come to run the application on the browser, so open any browser and just type asp.netcore2.com and press enter. Wow… you will get the following screen, which means the application has successfully hosted on IIS.

ASP.NET Core 2 Hosting - Prepare Your Machine and Get to Know Visual Studio Code for Angular 2 and ASP.NET Core Project

$
0
0

Why so many posts? The idea is to take you from nothing and not only build the application but to detail why it's built in this manner. There are numerous options when it comes to web development and for many readers this tutorial will walk you through two new frameworks and a new code editor so breaking up the content allows for sufficient explanation. In this particular post, you install the tools used throughout the remaining posts. The post also provides a tour of the main Visual Studio Code features used to create the application.

Prepare Your Machine

These are the frameworks and tools to install before writing any code: Node.js and npm; .NET Core (Includes ASP.NET Core); Visual Studio Code; C# Visual Studio Code Extension (Installed from Visual Studio Code)

Node.js and npm

No you aren't writing a Node.js application. However, the framework has become the defacto tooling standard for pre-processing your HTML, JavaScript, and CSS before it hits the browser. For instance, the Angular 2 application is built in TypeScript which requires compilation into JavaScript. Node.js fills this role in the application. As important as Node.js is its package manager, npm. This tool has also become the defacto standard for obtaining web development libraries and tooling. Node.js and npm are included in the same installer available in both a current and LTS (long-term support) version. The LTS version is recommended for most users. Make sure to have node version 4.x.x or higher and npm version 3.x.x or higher. You will check them later while touring Visual Studio Code.

.NET Core

To be clear, this is not the .NET Framework of old. The .NET Core framework is built from the ground up to be cross-platform and fast. This download includes the .NET Core and ASP.NET Core Frameworks as well as the terminal/command line tools used to create the backend in this tutorial. While higher-order features such as Routing, Views, Controllers are similar to their ASP.NET 4.6 counterparts, setting up and configuring an ASP.NET Core application is noticeably different and you will even start it from the terminal/command line. For this tutorial, use the .NET Core Preview 3 SDK. Later in this post, you will check which version is installed. It should be 1.0.0-preview3-x or higher.

Visual Studio Code

Visual Studio Code is one of the newer additions to the Visual Studio family. Forget anything you knew about traditional Visual Studio, this is a different animal entirely. During installation, you can add Visual Studio Code to your PATH variable. This enables the ability to type code . in the terminal/command window and open the current directory in Visual Studio Code.

Get to Know Visual Studio Code

This application is built entirely in Visual Studio Code. While this is not an exhaustive tour, it points out the main features of the editor relevant to building the application and continues setting up the editor for your project.

Explorer Pane

Put simply, this is where your files are listed. You point Visual Studio Code to a directory and this pane lists all the files and folders in that directory, including those that are currently open in the editor. You can create new files or folders directly in the explorer pane and to edit a file, simply click on it and it opens in the editor.

Integrated Terminal

The integreated terminal in Visual Studio Code is exactly that. Instead of switching between your editor and a seperate instance of your terminal/command window, you run commands directly in the editor. This walkthrough exclusively uses the integrated terminal, but of course using a separate terminal/command window works fine as well. Go head and try it out:

Press Ctrl + ` to open the Integrated Terminal
Type node -v then Enter to get the Node.js version. It should be 4.x.xor higher.
Type npm -v then Enter to get the npm version. It should be 3.x.x or higher.
Type dotnet --version then Enter to get the .NET Core SDK verion. It should be 1.0.0-preview3-x or higher.
Press Ctrl + ` to close the Integrated Terminal

If at any point these commands fail, it most likely means that either the framework is not installed or isn't added to your PATH. On windows at least, try restarting to refresh your PATH variable.

Command Palette

If you only remember one keyboard shortcut in Visual Studio Code, it should be Ctrl + Shift + P to open the command palette. The command palette contains almost every operation you want to complete in Visual Studio Code. Just start typing and it filters the list of operations for you. You're fingers never have to leave the keyboard. You still need to install the C# extension (from Microsoft) in Visual Studio Code before you start coding. Try to install it using the command palette. If you get stuck, you can also find it here. These are the key features in Visual Studio Code used during the walkthrough. There are so many other great features, so please read more about them in the Visual Studio Code documentation.

Best ASP.NET Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

ASP.NET Core 2 Hosting - Creating A GraphQL Endpoint in ASP.NET Core

$
0
0

The Graph Query Language

The GraphQL was invented by Facebook in 2012 and released to the public in 2015. It is a query language to tell the API exactly about the data you wanna have. This is the difference between REST, where you need to query different resources/URIs to get different data. In GrapgQL there is one single point of access about the data you want to retrieve.

That also makes the planning about the API a little more complex. You need to think about what data you wanna provide and you need to think about how you wanna provide that data.

While playing around with it, I created a small book database. The idea is to provide data about books and authors.

Let's have a look into few examples. The query to get the book number and the name of a specific book looks like this.

{
book(isbn: "822-5-315140-65-3"){
isbn,
name
}
}

This look similar to JSON but it isn't. The property names are not set in quotes, which means it is not really a JavaScript Object Notation. This query need to be sent inside the body of an POST request to the server.

The Query gets parsed and executed against a data source on the server and the server should send the result back to the client:

{
"data": {
"book": {
"isbn": "822-5-315140-65-3",
"name": "ultrices enim mauris parturient a"
}
}
}

If we want to know something about the author, we need to ask about it:

{
book(isbn: "822-5-315140-65-3"){
isbn,
name,
author{
id,
name,
birthdate
}
}
}

This is the possible result:

{
"data": {
"book": {
"isbn": "822-5-315140-65-3",
"name": "ultrices enim mauris parturient a",
"author": {
"id": 71,
"name": "Henderson",
"birthdate": "1937-03-20T06:58:44Z"
}
}
}
}

You need a list of books, including the authors? Just ask for it:

{
books{
isbn,
name,
author{
id,
name,
birthdate
}
}
}

The list is too large? Just limit the result, to get only 20 items:

{
books(limit: 20) {
isbn,
name,
author{
id,
name,
birthdate
}
}
}

The Book Database

The book database is just fake. I love to use GenFu to generate dummy data. So I did the same for the books and the authors and created a BookRepository:

public class BookRepository : IBookRepository
{
private IEnumerable<Book> _books = new List<Book>();
private IEnumerable<Author> _authors = new List<Author>();
public BookRepository()
{
GenFu.GenFu.Configure<Author>()
.Fill(_ => _.Name).AsLastName()
.Fill(_=>_.Birthdate).AsPastDate();
_authors = A.ListOf<Author>(40);
GenFu.GenFu.Configure<Book>()
.Fill(p => p.Isbn).AsISBN()
.Fill(p => p.Name).AsLoremIpsumWords(5)
.Fill(p => p.Author).WithRandom(_authors);
_books = A.ListOf<Book>(100);
}
public IEnumerable<Author> AllAuthors()
{
return _authors;
}
public IEnumerable<Book> AllBooks()
{
return _books;
}
public Author AuthorById(int id)
{
return _authors.First(_ => _.Id == id);
}
public Book BookByIsbn(string isbn)
{
return _books.First(_ => _.Isbn == isbn);
}
}
public static class StringFillerExtensions
{
public static GenFuConfigurator<T> AsISBN<T>(
this GenFuStringConfigurator<T> configurator) where T : new()
{
var filler = new CustomFiller<string>(
configurator.PropertyInfo.Name, 
typeof(T), 
() =>
{
return MakeIsbn();
});
configurator.Maggie.RegisterFiller(filler);
return configurator;
}
public static string MakeIsbn()
{
// 978-1-933988-27-6
var a = A.Random.Next(100, 999);
var b = A.Random.Next(1, 9);
var c = A.Random.Next(100000, 999999);
var d = A.Random.Next(10, 99);
var e = A.Random.Next(1, 9);
return $"{a}-{b}-{c}-{d}-{e}";
}
}

GenFu provides a useful set of so called fillers to generate data randomly. There are fillers to generate URLs, emails, names, last names, states of US and Canada and so on. I also need a ISBN generator, so I created one by extending the generic GenFuStringConfigurator.

The BookRepository is registered as a singleton in the Dependency Injection container, to work with the same set of data while the application is running. You are able to add some more information to that repository, like publishers and so on.

GraphQL in ASP.NET Core

Fortunately there is a .NET Standard compatible implementation of the GraphQL on GitHub. So there's no need to parse the Queries by yourself. This library is also available as a NuGet package:

<PackageReference Include="GraphQL" Version="0.15.1.678" />

The examples provided on GitHub, are pretty easy. They directly write the result to the output, which means the entire ASP.NET Applications is a GraphQL server. But I want to add GraphQL as a ASP.NET Core MiddleWare, to add the GraphQL implementation as a different part of the Application. Like this you are able to use REST based POST and PUT request to add or update the data and to use the GraphQL to query the data.

I also want that the middleware is listening to the sub path "/graph"

public class GraphQlMiddleware
{
private readonly RequestDelegate _next;
private readonly IBookRepository _bookRepository;
public GraphQlMiddleware(RequestDelegate next, IBookRepository bookRepository)
{
_next = next;
_bookRepository = bookRepository;
}
public async Task Invoke(HttpContext httpContext)
{
var sent = false;
if (httpContext.Request.Path.StartsWithSegments("/graph"))
{
using (var sr = new StreamReader(httpContext.Request.Body))
{
var query = await sr.ReadToEndAsync();
if (!String.IsNullOrWhiteSpace(query))
{
var schema = new Schema { Query = new BooksQuery(_bookRepository) };
var result = await new DocumentExecuter()
.ExecuteAsync(options =>
{
options.Schema = schema;
options.Query = query;
}).ConfigureAwait(false);
CheckForErrors(result);
await WriteResult(httpContext, result);
sent = true;
}
}
}
if (!sent)
{
await _next(httpContext);
}
}
private async Task WriteResult(HttpContext httpContext, ExecutionResult result)
{
var json = new DocumentWriter(indent: true).Write(result);
httpContext.Response.StatusCode = 200;
httpContext.Response.ContentType = "application/json";
await httpContext.Response.WriteAsync(json);
}
private void CheckForErrors(ExecutionResult result)
{
if (result.Errors?.Count > 0)
{
var errors = new List<Exception>();
foreach (var error in result.Errors)
{
var ex = new Exception(error.Message);
if (error.InnerException != null)
{
ex = new Exception(error.Message, error.InnerException);
}
errors.Add(ex);
}
throw new AggregateException(errors);
}
}
}
public static class GraphQlMiddlewareExtensions
{
public static IApplicationBuilder UseGraphQL(this IApplicationBuilder builder)
{
return builder.UseMiddleware<GraphQlMiddleware>();
}
}

With this kind of MiddleWare, I can extend my applications Startup.cs with GraphQL:

app.UseGraphQL();

As you can see, the BookRepository gets passed into this Middleware via constructor injection. The most important part is that line:

var schema = new Schema { Query = new BooksQuery(_bookRepository) };

This is where we create a schema, which is used by the GraphQL engine to provide the data. The schema defines the structure of the data you wanna provide. This is all done in a root type called BooksQuery. This type gets the BookRepostory.

This Query is a GryphType, provided by the GraphQL library. You need to derive from a ObjectGraphType and to configure the schema in the constructor:

public class BooksQuery : ObjectGraphType
{
public BooksQuery(IBookRepository bookRepository)
{
Field<BookType>("book",
arguments: new QueryArguments(
new QueryArgument<StringGraphType>() { Name = "isbn" }),
resolve: context =>
{
var id = context.GetArgument<string>("isbn");
return bookRepository.BookByIsbn(id);
});
Field<ListGraphType<BookType>>("books",
resolve: context =>
{
return bookRepository.AllBooks();
});
}
}

Using the GraphQL library all types used in the Query to define the schema are any kind of GraphTypes, even the BookType:

public class BookType : ObjectGraphType<Book>
{
public BookType()
{
Field(x => x.Isbn).Description("The isbn of the book.");
Field(x => x.Name).Description("The name of the book.");
Field<AuthorType>("author");
}
}

The difference is just the generic ObjectGraphType which is also used for the AuthorType. The properties of the Book, which are simple types like the name or the ISBN are mapped directly with the lambda. The complex typed properties like the Author are mapped via another generic ObjectGraphType, which is ObjectGraphType in that case.

Best ASP.NET Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.


ASP.NET Core 2 Hosting - The Differences Between ASP.NET MVC and ASP.NET WebForms

$
0
0

Terminology

Before we proceed to talk about the differences between WebForms and MVC, we need to know the difference between certain terms on the Microsoft stack of technologies. In the past, I've heard a couple of developers mixing and matching certain terms that weren't related to each other at all.

.NET Framework - A technology introduced in 2002 which includes the ability to create executables, web applications, and services using C# (pronounced see-sharp), Visual Basic, and F# (wikipedia)

ASP.NET - An open source, server-side web application framework which is a subset of the .NET Framework that focuses specifically on building web application, web sites, and web services.

ASP.NET Web Forms - (2002 - current) A proprietary technique developed by Microsoft to manage state and form data across multiple pages. The innate ability of the web are state-less pages where Microsoft created stateful pages by creating the Web Forms technique.

ASP.NET MVC - (2008 - current) An open source web application framework that implements a Model-View-Controller design pattern.
With that cleared up, let's go over the differences between ASP.NET Web Forms and MVC.

Differences Between ASP.NET Web Forms and ASP.NET MVC

Even though these technologies have been around for 5+ years, they each have their advantages and disadvantages.

Web Forms has ViewState, MVC does not

This has become the bane of my existence. As I mentioned above, ViewState is a page-level state management mechanism. If you have a number of server-side web controls on a page, your ViewState will become extremely large.

Let me tell you a story of how ViewState can be so...unnatural.

I worked at one company where I wasn't getting any data back from a submitted form. After talking to the security specialists and the networking team, I found out that my requests were being blocked by the company firewall.

The reason? The firewall was blocking the request because there was a form trying to perform a 2MB+ postback and the firewall thought it was blocking an attack from a hacker.

Another reason is that your HTML SHOULD be small to send back to the client, not bloated with a huge 1MB+ ViewState variable. Let's see that pass the mobile-friendly test. :-)

MVC does not have a ViewState. It uses model/ViewModels to pass back and forth between the Views.

Web Forms has a Code-Behind Model where MVC just has models

Code-Behind is a way to attach C# or VB code to a web page and act on their specific actions when they occur on the page. When you compile a Web Form that contains code-behind, it becomes part of the assembly (or DLL) to make the site functional.

With MVC, you pass in data that was already processed and is being delivered to the View which should have no logic or processing included in it as well.

Web Forms has Web Controls where MVC does not

There are a lot of developers who were complaining that MVC didn't have any server-side controls. This is because they became spoiled with the Web Forms way of doing things on a page. Controls were already available to them and they used them. Eventually, they started building their own custom server controls.

While Web Forms had a large number of server-controls, MVC kept the lean-and-mean approach to granular HTML. After the dust settled, developers started to understand the direction with MVC and leveraged JavaScript where they could build their own custom controls or even use a third-party library like Bootstrap for their UI.

Web Forms has State-aware components where MVC uses more of a template approach

This is why it's hard to convert a Web Forms application over to an MVC application.

In Web Forms, developers place controls on a web page and are able to manipulate those controls on the server in the code-behind. The server-side controls are even aware of their state when ViewState is turned on.

With MVC, you aren't working with controls, you are passing data to be used in a dumb View. The Razor syntax in a View is extremely powerful. If you want an objects property dropped into the HTML HEAD tag, you place a @model.Title right in the header and you're done.

Where Web Forms doesn't have the separation of concerns, MVC is adamant about it!

I can't tell you how many times I've seen developers create a Web Form, attach code to a control, and then place the business logic inside the code-behind instead of being handled or processed by a business object. How is that business logic going to be used in another application when it's attached to a UI control?

MVC's philosophy with business logic is "Thin Controllers, Fat Models" (Hence, my article about the skinniest controller) meaning that the models will contain all of your business logic while your controllers should return a model to the view.

This forces you to think about how your models should already have "processed data" and how the ViewModel will strictly be a car to transport your processed models to your destination which is the View.

Web Forms and MVC can use Sessions, but I would recommend against it

Along with ViewState, sessions are another bane of my existence. Sessions provide state in a state-less web. What happens when that state is out of sync? Don't tell me it won't be because it will. Been there, done that!

Developers placing state (or worse, user controls) inside of a session is just asking for trouble.

In MVC, there are a number of ways of passing data back and forth to the View. I mention a couple in a post called ASP.NET MVC Views: How to Pass Data To Views.

As I mentioned before, I'm glad I'm not the only one who feels this way about Sessions.

Web Forms has IsPostBack where MVC has a GET and...well...a POST

New Web Form developers (and some seasoned) sometimes forget to include an "if (IsPostBack) return;" statement in their Page_Load event of their page. This may look strange to some veteran web developers coming over from PHP or other web language.

The whole idea of Web Forms is when you are requesting a page, it's considered a GET (visiting the page for the first time) and the page initializes.

The term IsPostback is coined when a form is submitted, or POST-ed. So if I visit a page, the IsPostBack lets me through and performs the initialization of the page. When you submit a form, the Page_Load detects that it's a Postback and kicks you out of the Page_Load immediately because it should defer to the event that triggered the submit.

MVC has the standard HTTP Protocol standards of GET, POST, DELETE, and redirects. When you click a submit button, that form (and data) gets submitted to the controller and the controller handles the processing of it.

Again, the MVC way feels more natural.

Web Forms is not testable-friendly, MVC was built around tests

Out of the box, web form developers have a problem.

Unless they were disciplined with their business objects and code-behind forms, it may take a rewrite to get most of the business logic into a testable state.

With MVC, you can build tests against the controller, routes, action results...against just about any hooks in the ASP.NET MVC Framework.
Web Forms has One. Big. Form. MVC can have multiple forms on a page.

Speaking of unnatural, you can imagine how hard it is to go to a website that has a JavaScript service that contains an HTML form and they suggest you copy-and-paste this sample code into your ASP.NET Web Forms page.

Won't work. Why?

If you do a View Source on a Web Forms web site, you'll notice that right after the BODY tag in your HTML, there is a Form tag that encompasses the entire page...INSIDE A FORM!

This is where the gears in my head locked up the first time I experienced this. How kooky is this?

MVC allows you to have multiple forms on a page.

End of story.

Best ASP.NET Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

ASP.NET Core 2 Hosting - How to Use Bootstrap 4 in ASP.NET Core

$
0
0

 So although you can still use it right now, Bootstrap has also announced to drop support for it. As a result, the built-in ASP.NET Core templates are slowly being edited to move away from it too.

Unfortunately, there is no clear path forward. This is mostly due to the fact that web applications are continuously moving further into the client-side, requiring complex client-side build systems and many dependencies. So if you are building something like that, you might already know how to solve this then, and you can expand your existing build process to simply also include Bootstrap and jQuery there.

But there are still many web applications out there that are not that heavy on the client-side, where the application still runs mainly on the server and the server serves static views as a result. Bower previously filled this by making it easy to just publish client-side dependencies without that much of a process.

In the .NET world we also have NuGet and with previous ASP.NET versions, we could use NuGet as well to add dependencies to some client-side dependencies since NuGet would just place the content into our project correctly. Unfortunately, with the new .csproj format and the new NuGet, installed packages are located outside of our project, so we cannot simply reference those.

This leaves us with a few options how to add our dependencies:

One-time installation

This is what the ASP.NET Core templates, that are not single-page applications, are currently doing. When you use those to create a new application, the wwwroot folder simply contains a folder lib that contains the dependencies:

If you look closely at the files currently, you can see that they were originally placed there with Bower to create the template, but that is likely to change soon. The basic idea is that the files are copied once to the wwwroot folder so you can depend on them.

To do this, we can simply follow Bootstrap’s introduction and download the compiled files directly. As mentioned on the download site, this does not include jQuery, so we need to download that separately too; it does contain Popper.js though if we choose to use the bootstrap.bundle file later—which we will do. For jQuery, we can simply get a single "compressed, production" file from the download site.

This leaves us with a few files which will simply extract and copy into the wwwroot folder. We can also make a lib folder to make it clearer that these are external dependencies:

That’s all we need, so now we just need to adjust our _Layout.cshtml file to include those dependencies. For that, we add the following block to the <head>:

<environment include="Development">
<link rel="stylesheet" href="~/lib/css/bootstrap.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="~/lib/css/bootstrap.min.css" />
</environment>

And the following block at the very end of the <body>:

<environment include="Development">
<script src="~/lib/js/jquery-3.3.1.js"></script>
<script src="~/lib/js/bootstrap.bundle.js"></script>
</environment>
<environment exclude="Development">
<script src="~/lib/js/jquery-3.3.1.min.js"></script>
<script src="~/lib/js/bootstrap.bundle.min.js"></script>
</environment>

You can also just include the minified versions and skip the <environment> tag helpers here to make it a bit simpler. But that’s all you need to do to keep you starting.

Dependencies from NPM

The more modern way, also if you want to keep your dependencies updated, would be to get the dependencies from the NPM package repository. You can use either NPM or Yarn for this; in my example, I’ll use NPM.

To start off, we need to create a package.json file for our project, so we can specify our dependencies. To do this, we simply do that from the "Add New Item" dialog:

Once we have that, we need to edit it to include our dependencies. It should something look like this:

{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"bootstrap": "4.0.0",
"jquery": "3.3.1",
"popper.js": "1.12.9"
}
}

By saving, Visual Studio will already run NPM to install the dependencies for us. They will be installed into the node_modules folder. So what is left to do is to get the files from there into our wwwroot folder. There are a few options to do that:

bundleconfig.json for bundling and minification

We can use one of the various ways to consume a bundleconfig.json for bundling and minification, as explained in the documentation. A very easy way is to simply use the BuildBundlerMinifier NuGet package which automatically sets up a build task for this.

After installing that package, we need to create a bundleconfig.json at the root of the project with the following contents:

[
{
"outputFileName": "wwwroot/vendor.min.css",
"inputFiles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"minify": { "enabled": false }
},
{
"outputFileName": "wwwroot/vendor.min.js",
"inputFiles": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
],
"minify": { "enabled": false }
}
]

This basically configures which files to combine into what. And when we build, we can see that the vendor.min.css and vendor.js.css are created correctly. So all we need to do is to adjust our _Layouts.html again to include those files:

<!-- inside <head> -->
<link rel="stylesheet" href="~/vendor.min.css" />
<!-- at the end of <body> -->
<script src="~/vendor.min.js"></script>

Using a task manager like Gulp

If we want to move a bit more into client-side development, we can also start to use tools that we would use there. For example Webpack which is a very commonly used build tool for really everything. But we can also start with a simpler task manager like Gulp and do the few necessary steps ourselves.

For that, we add a gulpfile.js into our project root, with the following contents:

const gulp = require('gulp');
const concat = require('gulp-concat');
const vendorStyles = [
"node_modules/bootstrap/dist/css/bootstrap.min.css"
];
const vendorScripts = [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js",
];
gulp.task('default', ['build-vendor']);
gulp.task('build-vendor', ['build-vendor-css', 'build-vendor-js']);
gulp.task('build-vendor-css', () => {
return gulp.src(vendorStyles)
.pipe(concat('vendor.min.css'))
.pipe(gulp.dest('wwwroot'));
});
gulp.task('build-vendor-js', () => {
return gulp.src(vendorScripts)
.pipe(concat('vendor.min.js'))
.pipe(gulp.dest('wwwroot'));
});

Now, we also need to adjust our package.json to have dependencies on gulp and gulp-concat:

{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"bootstrap": "4.0.0",
"gulp": "^3.9.1",
"gulp-concat": "^2.6.1",
"jquery": "3.3.1",
"popper.js": "1.12.9"
}
}

Finally, we edit our .csproj to add the following task which makes sure that our Gulp task runs when we build the project:

<Target Name="RunGulp" BeforeTargets="Build">
<Exec Command="node_modules\.bin\gulp.cmd" />
</Target>

Now, when we build, the default Gulp task runs, which runs the build-vendor tasks, which then builds our vendor.min.css and vendor.min.js just like we did before. So after adjusting our _Layout.cshtml just like above, we can make use of jQuery and Bootstrap.

While the initial setup of Gulp is a bit more complicated than the bundleconfig.json one above, we have now have entered the Node-world and can start to make use of all the other cool tools there. So it might be worth to start with this.

Best ASP.NET Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

ASP.NET Core 2 Hosting - How to Secure Your .NET Core 2.0 Web App

$
0
0

Configuring ASP.NET Core to require authentication

Imagine we’re starting with an ASP.NET Core 2.0 MVC application (with no authentication mechanism configured).

You can grab the code we’re about to go through and take a look for yourself using the next link.

Get the code: Simple Authentication using ASP.NET Core 2.0
The first step is to enable authentication for our site, which we can do by modifying startup.cs.

We can start by adding the relevant Authentication services to our application.

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
            options =>
            {
                options.LoginPath = new PathString("/auth/login");
                options.AccessDeniedPath = new PathString("/auth/denied");
            });
     // ---------------
     // rest of configureServices code goes here...
}

We’re going to stick with cookies for now. This means our logged in users will get a cookie in their browser, which gets passed to our app on every request, indicating that they are authenticated.

Notice how we’ve configured two paths, the path to the login page (where we can send unauthenticated people when they try to access a restricted area) and the path to an access denied page (useful for when they inevitably enter incorrect credentials).

We also need to tell our app to go ahead and actually enable authentication. Happily, this is very very simple in .NET Core 2…

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication();
    // ---------------
    // rest of configure code goes here...
}

Just another Login form

So now our app knows we’re going to be using authentication, but there’s more work to be done.

We need a way to identify our users, the common way being to ask them for a username and password.

Login forms are straightforward enough, here’s one to get us started.

<h2>Hmm, looks like you need to log in</h2>
<form asp-controller="Auth" asp-action="Login" method="post">
    <label for="username">Username</label>
    <input id="username" name="username" type="text"/>
    <label for="password">Password</label>
    <input id="password" name="password" type="password" />
    <button type="submit">Log me in</button>
</form>

If we’re using the default routing for MVC, you’ll want to create an AuthController with a Login action that returns this view.

If you’re not familiar with them, the asp- attributes are tag helpers, new to ASP.NET core, which make it easier to link your html to your ASP.NET MVC controllers. Read more about tag helpers here.

In this example, the form contents will be posted to the Login action on an Auth controller.

A word to the wise, if you start with an empty web app project you’ll find that Tag Helpers don’t work automatically.

The easiest way to get them working is to create a _ViewImports.cshtml file and add this line to it…

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

If you start with one of the other starter templates you’ll probably find this file is created for you.

The logging in bit

To keep this super, super simple, we’ll opt to hard-code a username and password for now.

If our users enter the correct combination, they’ll be logged in, with full access to “locked down” parts of the application.

Now let’s be honest, hardcoded usernames and passwords are somewhat limiting (and not at all secure if your code ends up in a public Github repo) but they do tackle our urgent requirement to provide a mechanism for users to log in, and gain access to parts of the site that will be unavailable to Joe Public.

This falls into the camp of “doing the simplest possible thing first”, so you can start to build up momentum with your new app, rather than getting bogged down in building your own user management system from day one.

The login form will post to this controller action…

[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Login(string returnUrl, string username, string password)
{
    if (username == "Jon" && password == "ABitSimplisticForProductionUseThis...")
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, "jon", ClaimValueTypes.String, "
https://yourdomain.com")
        };
        var userIdentity = new ClaimsIdentity(claims, "SecureLogin");
        var userPrincipal = new ClaimsPrincipal(userIdentity);
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
            userPrincipal,
            new AuthenticationProperties
            {
                ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                IsPersistent = false,
                AllowRefresh = false
            });
        return GoToReturnUrl(returnUrl);
    }
    return RedirectToAction(nameof(Denied));
}

There’s our super insecure hardcoded username/password check (as discussed).

We’ve opted to use claims-based security.

In the most basic sense, you can think of Claims as pieces of information about your user. In this case we’re simply storing the user’s name in a claim, which we then attach to an identity for the user.

This identity is the representation of your user that ASP.NET core can interrogate, to find out anything it needs to know.

You can assign many claims to one identity, but ASP.NET Core requires the name claim as a minimum requirement (it will error if you don’t assign one).

Next up we create a user principal. If this is your first foray into ASP.NET Core authentication then this can be a little confusing, but it’s worth noting you could have more than one identity and attach them all to the same principal.

We’ve no need to handle multiple identities for the same user yet, so we can move along to the SignInAsync method on the HTTPContext, which logs our user in.

In practice, this creates an encrypted cookie holding the user’s information (the Claims Principal). From here on (until they exit the browser) your user is authenticated.

Because we’ve set IsPersistent to false, the cookie will be lost when our user exits their browser, and will have to log in again next time they come to the site.

If you want to see what that cookie looks like, check out the Application > Cookies window in Chrome (you’ll find a similar view in other browsers) and you’ll find it there, called .AspNetCore.Cookies.
Once they’re logged in, the user is redirected to the original page they requested, or the home page. You can do this with a simple helper method.

private IActionResult GoToReturnUrl(string returnUrl)
{
    if (Url.IsLocalUrl(returnUrl))
    {
        return Redirect(returnUrl);
    }
    return RedirectToAction("Index", "Home");
}

No access for you

This is all well and good, but currently there’s no reason for anyone to log in to the site, because nothing is locked down.

Let’s remedy that by restricting access to the main homepage for the app.

[Authorize]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

The [Authorize] attribute will trigger ASP.NET Core to redirect any users who aren’t logged in (don’t have an auth cookie) to the login page (that we configured in startup.cs).

It’s all about you

So that’s almost the entire process. But it would be nice to greet the user by name.

We’ll do this on our main index view…

<h1>Hi @User.Identity.Name, you're in the club.</h1>    

Let me out of here

Finally, we should probably let them log out, if they so wish.

All this needs is a simple form.

<form asp-controller="Auth" asp-action="Logout">
    <button type="submit">Log out</button>
</form>
And controller action.
public async Task<IActionResult> Logout()
{
    await HttpContext.SignOutAsync();
    return RedirectToAction(nameof(Login));
}

Best ASP.NET Hosting Recommendation
 

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

ASP.NET Core 2 Hosting - Create ASP.NET Chart Control from Database using C#

$
0
0

In this article I will explain with an example, how you can display charts in ASP.Net using new Chart Control.

Web.Config Modifications

You will need to modify the Web.Config file as following shown in order to use the ASP.Net 4.0 Chart control.

<configuration>
    <appSettings>
        <add key="ChartImageHandler" value="storage=file;timeout=20;" />
    </appSettings>
    <connectionStrings>
        <add name="conString"
        connectionString="Data Source=.\SQL2005;database=Northwind;Integrated Security=true"/>
    </connectionStrings>
 
    <system.web>
        <compilation debug="true" targetFramework="4.0">
            <assemblies>
                <add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            </assemblies>
        </compilation>
        <httpHandlers>
            <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
        </httpHandlers>
        <pages>
            <controls>
                <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
            </controls>
        </pages>
    </system.web>
    <system.webServer>
        <handlers>
            <remove name="ChartImageHandler"/>
            <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        </handlers>
    </system.webServer>
</configuration>

HTML Markup

Below is the HTML Markup of the page. It has an ASP.Net DropDownList and an ASP.Net Chart Control. The DropDownList is populated with countries and when a country is selected, the chart is populated with the statistics of orders of different cities in the selected country.

<asp:DropDownList ID="ddlCountries" runat="server" OnSelectedIndexChanged="ddlCountries_SelectedIndexChanged"
    AutoPostBack = "true">
</asp:DropDownList><hr />
<asp:Chart ID="Chart1" runat="server" Height="300px" Width="400px" Visible = "false">
    <Titles>
        <asp:Title ShadowOffset="3" Name="Items" />
    </Titles>
    <Legends>
        <asp:Legend Alignment="Center" Docking="Bottom" IsTextAutoFit="False" Name="Default" LegendStyle="Row" />
    </Legends>
    <Series>
        <asp:Series Name="Default" />
    </Series>
    <ChartAreas>
        <asp:ChartArea Name="ChartArea1" BorderWidth="0" />
    </ChartAreas>
</asp:Chart>

Namespaces

You will need to import the following Namespaces.

C#

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

Populating the DropDownList and Chart

Inside the Page Load event, the DropDownList is populated with Countries from the Orders table of the Northwind database. When a Country is selected in the DropDownList, the statistical records of Ship Cities and their Total Orders are fetched from the Orders table. The Ship City values are assigned to the X point values of the Chart while the Total Orders value for the Ship Cities are assigned to the Y point values of the Chart. Finally using these values the Chart is populated and displayed.

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string query = "select distinct shipcountry from orders";
        DataTable dt = GetData(query);
        ddlCountries.DataSource = dt;
        ddlCountries.DataTextField = "shipcountry";
        ddlCountries.DataValueField = "shipcountry";
        ddlCountries.DataBind();
        ddlCountries.Items.Insert(0, new ListItem("Select", ""));
    }
}
  
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
    Chart1.Visible = ddlCountries.SelectedValue != "";
    string query = string.Format("select shipcity, count(orderid) from orders where shipcountry = '{0}' group by shipcity", ddlCountries.SelectedValue);
    DataTable dt = GetData(query);
    string[] x = new string[dt.Rows.Count];
    int[] y = new int[dt.Rows.Count];
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        x[i] = dt.Rows[i][0].ToString();
        y[i] = Convert.ToInt32(dt.Rows[i][1]);
    }
    Chart1.Series[0].Points.DataBindXY(x, y);
    Chart1.Series[0].ChartType = SeriesChartType.Pie;
    Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
    Chart1.Legends[0].Enabled = true;
}
 
private static DataTable GetData(string query)
{
    DataTable dt = new DataTable();
    SqlCommand cmd = new SqlCommand(query);
    String constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    sda.SelectCommand = cmd;
    sda.Fill(dt);
    return dt;
}

Best ASP.NET Hosting Recommendation
 

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

ASP.NET Core 2 Hosting - Create an Application With Angular 6 and .NET Core

$
0
0

Angular 6 recently launched and has introduced some pretty awesome features.

Let's look at how to create and Angular 6 application with and without using .NET Core SPA templates using Visual Studio 2017.

There is more than one way to create an Angular 6 application with .NET Core - let us see some of them.

Make sure you have installed Visual Studio 2017 and .NET Core's latest SDK and, of course, Node and Angular CLI.

Without Using an SPA Template

In this approach, we will not use any template and will add Angular 6 to an API project.

Create the Angular Application Using a .NET Core 2.0 Template in VS 2017

Once you have all these installed, open your Visual Studio 2017 -> Create New Project -> Select Core Web application:

Click 'OK,' and, in the next window, select an API as shown below:

Once the API project is created, open the Command prompt and navigate to the project folder run the following command:

ng new ClientApp

This will create an Angular 6 application within an API project.

The next task is to run our Angular application with .NET Core. For this, we need to add some code within the Startup.cs class.

Add the below lines in the ConfigureService method:

services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});

Add the below lines in the Configure method:

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseHttpsRedirection();
app.UseMvc();
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});

The above code adds the required configuration for running Angular code with .NET Core.

Note: Make sure the property "launchUrl": "api/values" is not present in the Properties/launchSettings.json, if it is available then delete it.

Just run the application in the browser:

Your Angular 6 application is now running with .NET Core.

With an SPA Template

In the first approach, we did not use an SPA template to create an Angular app; in this approach, we will use the Angular template.

Create the Angular Application Using .Net Core 2.1 Template in VS 2017

Once you have all these installed, open your Visual Studio 2017 -> Create New Project -> Select Core Web application:

Click on 'OK,' and, in the next window, select Angular as shown below:

Visual Studio will create a well-structured application for you.

If you compare this project's structure with the previous version, then you would notice that the Views folder is no longer there:

We do not need that Views folder now.

Delete ClientApp and Install Angular 6

If you open a package.json file under the ClientApp folder, you'll notice the Angular version is 5.0 but we want to create an Angular 6 application.

So go to File Explorer and delete the ClientApp folder:

Once the folder is deleted, open the Command prompt and navigate to the project and run the following command:

ng new ClientApp

This command will create a brand new Angular 6 application.

Once the process is completed, go back to Solution Explorer -> ClientApp -> package.json. This file should show Angular 6.0 references:

That is it. We have just created an Angular 6 application with .NET Core.

Let's try to use any random Angular 6 feature just to make sure we have the latest Angular 6 code.

Test Library Feature

We will test the library feature which has been shipped with Angular 6.

Open the command prompt again and navigate to the ClientApp folder -> run the following command:

ng generate library my-shared-library

Logs in the window confirm that we have Angular 6 now. The library will be created under the ClientApp -> Projects folder:

Best ASP.NET Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

ASP.NET Core Hosting - Easy to Migrate Visual Basic 6 to .NET

$
0
0

Converting VB6 code to VB.NET is not a simple process that can be executed easily in spite of using automation tools. A number of automation tools are available in the market, with Microsoft itself being shipped with Visual Basic Upgrade Wizard. Some of the major changes undergone in VB6 is in the Common Language Runtime (CLR) new programming model. To reap maximum benefit out of the new features and structures of VB.NET, it is advisable to rewrite major sections of the application than porting it. Since this is a tedious process you can use VB.NET’s Upgrade Wizard that automatically converts all the syntaxes, which is just half the work done. No sooner you will be faced with other problems and errors during compilation that won’t be handled properly with the Upgrade Wizard. During migration you will have to rewrite and rearchitect the codes to take maximum advantage of VB.NET’s new tools.

.NET migration is a complex process that requires strict adherence to the features and syntactical aspects of the programming language. Here we list some of the essential steps that need to be considered while migrating from VB6 to VB.NET.

1. Application Assessment– Perform a thorough assessment of the application to be upgraded. You can document the existing system functionalities, which may be a tedious process. Use an assessment tool to analyze the VB6 application to understand issues and estimate the approximate cost and effort.

2. Planning and Preparation– Prepare project plan, determine scope and migration requirements by elucidating maximum information about the application. Create functional requirements for the new framework and application.

3. Upgrade Strategies– Develop a migration strategy after brainstorming the application requirements. First you need to get the VB6 application into the new .NET platform with the existing functionality then perform incremental changes to incorporate new functions.

4. Automatic Upgrade Process– After automated migration the quality of the generated code needs to be improved. This involves removing duplicated code, upgrading problematic syntax and controls, fixing data declarations, and the like.

5. Manual Upgrade Process– It is essential to rewrite critical application logic to suit the .NET framework and those that have not been properly converted during automation. You can continue writing new code in VB.NET leaving the bulk of the existing code in VB6 as there is good interoperability between VB6 COM components and VB.NET components.

6. Migrate Data– This involves creating a SQL Server or database and importing data and resizing the database structure.

7. Compiling– Compiling the project gives a list of compilation errors and runtime errors that needs to be analyzed and fixed through an iterative process.

8. Fixing Errors– Bugs can be tracked using various source code analyzers that helps identify duplicate codes and fix data declarations.

9. Quality Assurance– Upgraded application will be subjected to different levels of testing throughout the process to ensure reliability and correctness of the application.

  • Unit test thoroughly each item converted to help identify any flaws in implementation.
  • Perform system testing to ensure the application functionalities are met in the .NET framework version.
  • Import final version legacy data and perform load testing to ensure the application works in the .NET environment.

10. Deployment– Finally deploy to application server and verify the checklist of all the components and functionalities in the application tally.

Best ASP.NET Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

ASP.NET Core Hosting - Queues In .NET Core

$
0
0

I was recently looking into the new Channel<T>  API in .NET Core (For an upcoming post), but while writing it up, I wanted to do a quick refresher of all the existing “queues” in .NET Core. These queues are also available in full framework (And possibly other platforms), but all examples are written in .NET Core so your mileage may vary if you are trying to run them on a different platform.

FIFO vs LIFO

Before we jump into the .NET specifics, we should talk about the concept of FIFO or LIFO, or “First In, First Out” and “Last In, Last Out”. For the concept of queues, we typically think of FIFO. So the first message put into the queue, is the first one that comes out. Essentially processing messages as they go into a queue. The concept of LIFO, is typically rare when it comes to queues, but in .NET there is a type called Stack<T>  that works with LIFO. That is, after filling the stack with messages/objects, the last one put in would then be the first one out. Essentially the order would be reversed.

Queue<T>

Queue<T>  is going to be our barebones simple queue in .NET Core. It takes messages, and then pops them out in order. Here’s a quick code example :

static void Main(string[] args)
{
    Queue<string> messageQueue = new Queue<string>();
    messageQueue.Enqueue("Hello");
    messageQueue.Enqueue("World!");
 
    Console.WriteLine(messageQueue.Dequeue());
    Console.WriteLine(messageQueue.Dequeue());
    Console.ReadLine();
}

Pretty stock standard and not a lot of hidden meaning here. The Enqueue  method puts a message on our queue, and the Dequeue  method takes one off (In a FIFO manner). Our console app obviously prints out two lines, “Hello” then “World!”.

Barring multi threaded scenarios (Which we will talk about shortly), you’re not going to find too many reasons to use this barebones queue. In a single threaded app, you might pass around a queue to process a “list” of messages, but you may find that using a List<T>  within a loop is a simpler way of achieving the same result. Infact if you look at the source code of Queue, you will see it’s actually just an implementation of IEnumerable anyway!

So how about multi threaded scenarios? It kind of makes sense that you may want to load up a queue with items, and then have multiple threads all trying to process the messages. Well using a queue in this manner is actually not threadsafe, but .NET has a different type to handle multi threading…

ConcurrentQueue<T>

ConcurrentQueue<T>  is pretty similar to Queue<T> , but is made threadsafe by a copious amount of spinlocks. A common misconception is that ConcurrentQueues are just a wrapper around a queue with the use of the lock  keyword. A quick look at the source code here shows that’s definitely not the case. Why do I feel the need to point this out? Because I often see people try and make their use of Queue<T>  threadsafe by using locks, thinking that they are doing what Microsoft does when using ConcurrentQueue, but that’s pretty far from the truth and actually takes a pretty big performance hit when doing so.

Here’s a code sample of a ConcurrentQueue :

static void Main(string[] args)
{
    ConcurrentQueue<string> concurrentQueue = new ConcurrentQueue<string>();
    concurrentQueue.Enqueue("Hello");
    concurrentQueue.Enqueue("World!");
 
    string message;
    while(concurrentQueue.TryDequeue(out message))
    {
        Console.WriteLine(message);
    }
 
    Console.ReadLine();
}

So you’ll notice we can no longer just dequeue a message, we need to TryDequeue. It will return true if we managed to pop a message, and false if there is no message to pop.

Again, the main point of using a ConcurrentQueue over a regular Queue is that it’s threadsafe to have multiple consumers (Or producers/enqueuers) all using it at the same time.

BlockingCollection<T>

A blocking collection is an interesting “wrapper” type that can go over the top of any IProducerConsumerCollection<T>  type (Of which Queue<T>  and ConcurrentQueue<T>  are both). This can be handy if you have your own implementation of a queue, but for most cases you can roll with the default constructor of BlockingCollection. When doing this, it uses a ConcurrentQueue<T> under the hood making everything threadsafe (See source code here). The main reason to use a BlockingCollection is that it has a limit to how many items can sit in the queue/collection. Obviously this is beneficial if your producer is much faster than your consumers.

Let’s take a quick look :

static void Main(string[] args)
{
    BlockingCollection<string> blockingCollection = new BlockingCollection<string>(2);
    Console.WriteLine("Adding Hello");
    blockingCollection.Add("Hello");
    Console.WriteLine("Adding World!");
    blockingCollection.Add("World!");
    Console.WriteLine("Adding Good");
    blockingCollection.Add("Good");
    Console.WriteLine("Adding Evening");
    blockingCollection.Add("Evening!");
 
    Console.ReadLine();
}

What will happen with this code? You will see “Adding Hello”, “Adding World!”, and then nothing… Your application will just hang. The reason is this line :

BlockingCollection<string> blockingCollection = new BlockingCollection<string>(2);

We’ve initialized the collection to be a max size of 2. If we try and add an item where the collection is already at this size, we will just wait until a message is dequeued. How long will we wait? Well by default, forever. However we can change our add line to be :
blockingCollection.TryAdd("Hello", TimeSpan.FromSeconds(60));

So we’ve changed our Add call to TryAdd, and we’ve specified a timespan to wait. If this timespan is hit, then the TryAdd method will return false to let us know we weren’t able to add the item to the collection. This is handy if you need to alert someone that your queue is overloaded (e.g. the consumers are stalled for whatever reason).

Stack<T>

As we talked about earlier, a Stack<T> type allows for a Last In, First Out (LIFO) queuing style. Consider the following code :

static void Main(string[] args)
{
    Stack<string> stack = new Stack<string>();
    stack.Push("Hello");
    stack.Push("World!");
 
    Console.WriteLine(stack.Pop());
    Console.WriteLine(stack.Pop());
 
    Console.ReadLine();
}

The output would be “World!” then “Hello”. It’s rare that you would need this reversal of messages, but it does happen. Stack<T>  also has it’s companion in ConcurrentStack<T> , and you can initialize BlockingCollection with a ConcurrentStack within it. 

Best ASP.NET Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.


ASP.NET Core Hosting - Using Layered Architectures In ASP.NET

$
0
0

One approach to designing Web applications is to focus on clearly defined layers of the application’s architecture. This approach is similar to the way an architect designs a building. If you’ve ever seen detailed construction plans for a skyscraper, you know the construction plans include separate blueprints for the foundation, frame, roof, plumbing, electrical, and other floors of the building.

With a layered architecture, specialists can design and develop the “floors” — called layers — independently, provided that the connections between the layers (the interfaces) are carefully thought out.

The layers should be independent of one another, as much as possible. Among other things, that means heeding a few must-dos and shalt-nots:

Each layer must have a clearly defined focus. To design the layers properly, you must clearly spell out the tasks and responsibilities of each layer.

Layers should mind their own business. If one layer is responsible for user interaction, only that layer is allowed to communicate with the user. Other layers that need to get information from the user must do so through the User Interface Layer.

Clearly defined protocols must be set up for the layers to interact with one another. Interaction between the layers occurs only through these protocols.

Note that the layers are not tied directly to any particular application. For example, an architecture might work equally well for an online ordering system and for an online forum. As a result, layered architecture has nothing to do with the ERDs that define a database or the Data Flow Diagrams that define how the data flows within the application. It’s a separate structure.

HOW MANY LAYERS?

There are several common approaches to application architecture that vary depending on the number of layers used. One common scheme is to break the application into two layers:

Application Layer: The design of the user interface and the implementation of business policies are handled in this layer. This layer may also handle transaction logic — the code that groups database updates into transactions and ensures that all updates within a transaction are made consistently.

Data Access Layer: The underlying database engine that supports the application. This layer is responsible for maintaining the integrity of the database. Some or all the transaction logic may be implemented in this layer.

In the two-layer model, the Application Layer is the ASP.NET Web pages that define the pages presented to the user as well as the code-behind files that implement the application’s logic. The Data Access Layer is the database server that manages the database, such as Microsoft SQL Server or Oracle.

Note that ASP.NET 2.0 doesn’t require that you place the application’s logic code in a separate code-behind file. Instead, you can intersperse the logic code with the presentation code in the same file. However, it’s almost always a good idea to use separate code-behind files to separate the application’s logic from its presentation code. All of the applications presented in this book use separate code-behind files.

The division between the Application and Data Access layers isn’t always as clear-cut as it could be. For performance reasons, transaction logic is often shifted to the database server (in the form of stored procedures), and business rules are often implemented on the database server with constraints and triggers. Thus, the database server often handles some of the application logic.

If this messiness bothers you, you can use a three-layer architecture, which adds an additional layer to handle business rules and policies:

Presentation Layer: This layer handles the user interface.

Business Rules Layer: This layer handles the application’s business rules and policies. For example, if a sales application grants discounts to certain users, the discount policy is implemented in this layer.

Data Access Layer: The underlying database model that supports the application.

Creating a separate layer for business rules enables you to separate the rules from the database design and the presentation logic. Business rules are subject to change. By placing them in a separate layer, you have an easier task of changing them later than if they’re incorporated into the user interface or database design.

MODEL-VIEW-CONTROLLER

Another common model for designing Web applications is called Model-View-Controller (MVC). In this architecture, the application is broken into three parts:

Model: The model is, in effect, the application’s business layer. It usually consists of objects that represent the business entities that make up the application, such as customers and products.

View: The view is the application’s user interface. In a Web application, this consists of one or more HTML pages that define the look and feel of the application.

Controller: The controller manages the events processed by the application. The events are usually generated by user-interface actions, such as the user clicking a button or selecting an item from a drop-down list.

In a typical ASP.NET application, the .aspx file implements the view; the model and controller functions are combined and handled by the code-behind file. Thus, the code-behind file can be thought of as the model-controller.

Best ASP.NET Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

ASP.NET Core Hosting - ASPHostPortal :: API Project ASP.NET Core

$
0
0

In this post, we are going to write about what we consider to be the best practices while developing the .NET Core Web API project. How we can make it better and how to make it more maintainable.

Startup Class and the Service Configuration

In the Startup class, there are two methods: the ConfigureServices method for registering the services and the Configure method for adding the middleware components to the application’s pipeline.

So, the best practice is to keep the ConfigureServices method clean and readable as much as possible. Of course, we need to write the code inside that method to register the services, but we can do that in more readable and maintainable way by using the Extension methods.

For example, let’s look at the wrong way to register CORS:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
    });
}    

Even though this way will work just fine, and will register CORS without any problem, imagine the size of this method after registering dozens of services.

That’s not readable at all.

The better way is to create an extension class with the static method: 

public static class ServiceExtensions
{
    public static void ConfigureCors(this IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });
    }
}

And then just to call this extended method upon the IServiceCollection type:

public void ConfigureServices(IServiceCollection services)
{
    services.ConfigureCors();
}

Project Organization

We should always try to split our application into smaller projects. That way we are getting the best project organization and separation of concerns (SoC). The business logic related to our entities, contracts, accessing the database, logging messages or sending an email message should always be in a separate .NET Core Class Library project.

Every small project inside our application should contain a number of folders to organize the business logic.

Here is just one simple example how a complete project should look like: 

Environment Based Settings

While we develop our application, that application is in the development environment. But as soon as we publish our application it is going to be in the production environment. Therefore having a separate configuration for each environment is always a good practice.

In .NET Core, this is very easy to accomplish.

As soon as we create the project, we are going to get the appsettings.json file and when we expand it we are going to see the appsetings.Development.json file:

All the settings inside this file are going to be used for the development environment.

We should add another file appsettings.Production.json, to use it in a production environment:

The production file is going to be placed right beneath the development one.

Data Access Layer

In many examples and different tutorials, we may see the DAL implemented inside the main project and instantiated in every controller. This is something we shouldn’t do.

When we work with DAL we should always create it as a separate service. This is very important in the .NET Core project because when we have DAL as a separate service we can register it inside the IOC (Inversion of Control) container. The IOC is the .NET Core’s built-in feature and by registering a DAL as a service inside the IOC we are able to use it in any controller by simple constructor injection:

public class OwnerController: Controller
{
    private IRepository _repository;
 
    public OwnerController(IRepository repository)
    {
        _repository = repository;
    }
}

Controllers

The controllers should always be as clean as possible. We shouldn’t place any business logic inside it.

So, our controllers should be responsible for accepting the service instances through the constructor injection and for organizing HTTP action methods (GET, POST, PUT, DELETE, PATCH…): 

public class OwnerController: Controller
{
    private ILoggerManager _logger;
    private IRepository _repository;
 
    public OwnerController(ILoggerManager logger, IRepository repository)
    {
        _logger = logger;
        _repository = repository;
    }
 
    [HttpGet]
    public IActionResult GetAllOwners()
    {           
    }
 
    [HttpGet("{id}", Name = "OwnerById")]
    public IActionResult GetOwnerById(Guid id)
    {          
    }
 
    [HttpGet("{id}/account")]
    public IActionResult GetOwnerWithDetails(Guid id)
    {
    }
 
    [HttpPost]
    public IActionResult CreateOwner([FromBody]Owner owner)
    {       
    }
 
    [HttpPut("{id}")]
    public IActionResult UpdateOwner(Guid id, [FromBody]Owner owner)
    {         
    }
 
    [HttpDelete("{id}")]
    public IActionResult DeleteOwner(Guid id)
    {        
    }
}

Actions

Our actions should always be clean and simple. Their responsibilities include handling HTTP requests, validating models, catching errors and returning responses: 

[HttpPost]
public IActionResult CreateOwner([FromBody]Owner owner)
{
    try
    {
        if (owner.IsObjectNull())
        {
            return BadRequest("Owner object is null");
        }
 
        if (!ModelState.IsValid)
        {
            return BadRequest("Invalid model object");
        }
 
        _repository.Owner.CreateOwner(owner);
 
        return CreatedAtRoute("OwnerById", new { id = owner.Id }, owner);
    }
    catch (Exception ex)
    {
        _logger.LogError($"Something went wrong inside the CreateOwner action: {ex}");
        return StatusCode(500, "Internal server error");
    }
}

Our actions should have IActionResult as a return type in most of the cases (sometimes we want to return a specific type or a JsonResult…). That way we can use all the methods inside .NET Core which returns results and the status codes as well.

The most used methods are:

  • OK => returns the 200 status code
  • NotFound => returns the 404 status code
  • BadRequest => returns the 400 status code
  • NoContent => returns the 204 status code
  • Created, CreatedAtRoute, CreatedAtAction => returns the 201 status code
  • Unauthorized => returns the 401 status code
  • Forbid => returns the 403 status code
  • StatusCode => returns the status code we provide as input 

Handling Errors Globally

In the example above, our action has its own try-catch block. This is very important because we need to handle all the errors (that in another way would be unhandled) in our action method. Many developers are using try-catch blocks in their actions and there is absolutely nothing wrong with that approach. But, we want our actions to be clean and simple, therefore, removing try-catch blocks from our actions and placing them in one centralized place would be an even better approach.

.NET Core gives us an opportunity to implement exception handling globally with a little effort by using built-in and ready to use middleware. All we have to do is to add that middleware in the Startup class by modifying the Configure method:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
     app.UseExceptionHandler(config =>
     {
         config.Run(async context =>
         {
             context.Response.StatusCode = 500;
             context.Response.ContentType = "application/json";
 
             var error = context.Features.Get<IExceptionHandlerFeature>();
             if (error != null)
             {
                 var ex = error.Error;
 
                 await context.Response.WriteAsync(new ErrorModel()
                 {
                     StatusCode = 500,
                     ErrorMessage = ex.Message
                 }.ToString(); //ToString() is overridden to Serialize object
             }
         });
     });
 
     app.UseMvc();
}

We can even write our own custom error handlers by creating custom middleware: 

public class CustomExceptionMiddleware
{
    //constructor and service injection
 
    public async Task Invoke(HttpContext httpContext)
    {
        try
        {
            await _next(httpContext);
        }
        catch (Exception ex)
        {
            _logger.LogError("Unhandled exception ...", ex);
            await HandleExceptionAsync(httpContext, ex);
        }
    }
   
    //additional methods
}

After that we need to register it and add it to applications pipeline: 

public static IApplicationBuilder UseCustomExceptionMiddleware(this IApplicationBuilder builder)
{
    return builder.UseMiddleware<CustomExceptionMiddleware>();
}

Using ActionFilters to Remove Duplicated Code

Filters in ASP.NET Core allows us to run some code prior to or after the specific stage in a request pipeline. Therefore, we can use them to execute validation actions that we need to repeat in our action methods.

When we handle a PUT or POST request in our action methods, we need to validate our model object as we did in the Actions part of this article. As a result, that would cause the repetition of our validation code, and we want to avoid that (Basically we want to avoid any code repetition as much as we can).

We can do that by using the ActionFilters. Instead of validation code in our action: 

if (!ModelState.IsValid)
{
  // bad request and logging logic
}

We can create our filter: 

public class ModelValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            context.Result = new BadRequestObjectResult(context.ModelState); // returns 400 with error
        }
    }
}

And register it in the Startup class in the ConfigureServices method: 

services.AddScoped<ModelValidationAttribute>();

Now, we can use that filter with our action methods.

Microsoft.AspNetCore.All Meta-Package

This meta-package contains all of the AspNetCore packages, EntityFrameworkCore packages, SignalR package (from version 2.1) and the supporting packages required for running the framework. It is pretty convenient when starting a new project because we don’t have to manually install and reference all the packages we might need.

Of course, your machine needs to have the .NET Core runtime installed on it in order to use the AspNetCore meta-package.

Routing

In the .NET Core Web API projects, we should use Attribute Routing instead of Conventional Routing. That’s because Attribute Routing helps us match the route parameter names with the actual parameters inside the action methods. Another reason is the description of the route parameters. It is more readable when we see the parameter with the name “ownerId” than just “id”.

We can use the [Route] attribute on top of the controller and on top of the action itself: 

[Route("api/[controller]")]
public class OwnerController: Controller
{
     [Route("{id}")]
     [HttpGet]
     public IActionResult GetOwnerById(Guid id)
     {
           
     } 
}

There is another way to create routes for the controller and actions: 

[Route("api/owner")]
public class OwnerController: Controller
{
     [HttpGet("{id}")]
     public IActionResult GetOwnerById(Guid id)
     {
           
     } 
}

There are different opinions which way is better, but we would always recommend the second way, and this is something we always use in our projects.

When we talk about the routing we need to mention the route naming convention. We can use descriptive names for our actions, but for the routes/endpoints, we should use NOUNS and not VERBS.

The few wrong examples: 

[Route("api/owner")]
public class OwnerController : Controller
{
    [HttpGet("getAllOwners")]
    public IActionResult GetAllOwners()
    {
    }
 
    [HttpGet("getOwnerById/{id}"]
    public IActionResult GetOwnerById(Guid id)
    {       
    }
}

The good examples: 

[Route("api/owner")]
public class OwnerController : Controller
{
    [HttpGet]
    public IActionResult GetAllOwners()
    {
    }
 
    [HttpGet("{id}"]
    public IActionResult GetOwnerById(Guid id)
    {         
    }
}

Logging

If we plan to publish our application to production, we should have a logging mechanism in place. Log messages are very helpful when figuring out how our software behaves in a production.

.NET Core has its own logging implementation by using the ILoggerinterface. It is very easy to implement it by using Dependency Injection feature: 

public class TestController: Controller
{
    private readonly ILogger _logger;
 
    public TestController(ILogger<TestController> logger)
    {
        _logger = logger;
    }
}

Then in our actions, we can utilize various logging levels by using the _logger object.

.NET Core supports logging API that works with a variety of logging providers. Therefore, we may use different logging providers to implement our own logging logic inside our project.

The NLog is the great library to use for implementing our own custom logging logic. It is extensible, supports structured logging and very easy to configure. We can log our messages in the console window, files or even database. 

CryptoHelper

We won’t talk about how we shouldn’t store the passwords in a database as a plain text and how we need to hash them due to security reasons. That’s out of the scope of this article. There are various hashing algorithms all over the internet, and there are many different and great ways to hash a password.

But if need the library that provides support to the .NET Core’s application and that is easy to use, the CryptoHelper is quite a good library.

This library is available for installation through the NuGet and its usage is quite simple:

using CryptoHelper;
 
// Method for hashing the password
public string HashPassword(string password)
{
    return Crypto.HashPassword(password);
}
 
// Method to verify the password hash against the given password
public bool VerifyPassword(string hash, string password)
{
    return Crypto.VerifyHashedPassword(hash, password);
}

Content Negotiation

By default .NET Core Web API returns a JSON formatted result. In most of the cases, that’s all we need.

But what if the consumer of our Web API wants another response format, like XML for example?

For that, we need to create a server configuration to format our response in the desired way: 

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(config =>
    {
        // Add XML Content Negotiation
        config.RespectBrowserAcceptHeader = true;
        config.InputFormatters.Add(new XmlSerializerInputFormatter());
        config.OutputFormatters.Add(new XmlSerializerOutputFormatter());
    });
}

Sometimes the client may request a format that is not supported by our Web API and then the best practice is to respond with the status code 406 Not Acceptable. That can be configured inside our ConfigureServices method as well: 

config.ReturnHttpNotAcceptable = true;

We can create our own custom format rules as well.

Using JWT

JSON Web Tokens (JWT) are becoming more popular by the day in the web development. It is very easy to implement JWT Authentication is very easy to implement due to the .NET Core’s built-in support. JWT is an open standard and it allows us to transmit the data between a client and a server as a JSON object in a secure way.

We can configure the JWT Authentication in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
     services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
       .AddJwtBearer(options =>
       {
          options.TokenValidationParameters = new TokenValidationParameters
          {
             //Configuration in here
          };
       });
}

In order to use it inside the application, we need to invoke this code in the Configure method:

app.UseAuthentication();

We may use JWT for the Authorization part as well, by simply adding the role claims to the JWT configuration 

Conclusion

In this article, our main goal was to familiarize you with the best practices when developing a Web API project in .NET Core. Some of those could be used in other frameworks as well, therefore, having them in mind is always helpful.

If you find that something is missing from the list, don’t hesitate to add it in a comment section.

Thank you for reading the article and I hope you found something useful in it.

ASP.NET Core Hosting - Using MailKit To Send And Receive Email In ASP.NET Core

$
0
0

As commentators on this post have pointed out however, this has now been deprecated and the official documentation actually points you towards a very popular email library called “MailKit“. It’s open source, it’s super extensible, and it’s built on .NET Standard meaning that you can use the same code across .NET Full Framework, UWP and .NET Core projects.

Creating An Email Service

It’s always good practice that when you add in a new library, that you build an abstraction on top of it. If we take MailKit as an example, what if MailKit is later superceded by a better emailing library? Will we have to change references all over our code to reference this new library? Or maybe MailKit has to make a breaking change between versions, will we then have to go through our code fixing all the now broken changes? 

Another added bonus to creating an abstraction is that it allows us to map out how we want our service to look before we worry about implementation details. We can take a very high level view of sending an email for instance without having to worry about exactly how MailKit works. Because there is a lot of code to get through, I won’t do too much explaining at this point, we will just run through it. Let’s go!

First, let’s go ahead and create an EmailAddress class. This will have only two properties that describe an EmailAddress.

public class EmailAddress
{
 public string Name { get; set; }
 public string Address { get; set; }
}

Now we will need something to describe a simple EmailMessage. There are a tonne of properties on an email, for example attachments, CC, BCC, headers etc but we will break it down to the basics for now. Containing all of this within a class means that we can add extra properties as we need them later on.

public class EmailMessage
{
 public EmailMessage()
 {
  ToAddresses = new List<EmailAddress>();
  FromAddresses = new List<EmailAddress>();
 }
 
 public List<EmailAddress> ToAddresses { get; set; }
 public List<EmailAddress> FromAddresses { get; set; }
 public string Subject { get; set; }
 public string Content { get; set; }
}

Now we need to setup our email configuration. That’s our SMTP servers, ports, credentials etc. For this we will make a simple settings class to hold all of this. Since we are good programmers we will use an interface too!

public interface IEmailConfiguration
{
 string SmtpServer { get; }
 int SmtpPort { get; }
 string SmtpUsername { get; set; }
 string SmtpPassword { get; set; }
 
 string PopServer { get; }
 int PopPort { get; }
 string PopUsername { get; }
 string PopPassword { get; }
}
 
public class EmailConfiguration : IEmailConfiguration
{
 public string SmtpServer { get; set; }
 public int SmtpPort  { get; set; }
 public string SmtpUsername { get; set; }
 public string SmtpPassword { get; set; }
 
 public string PopServer { get; set; }
 public int PopPort { get; set; }
 public string PopUsername { get; set; }
 public string PopPassword { get; set; }
}

Now we actually need to load this configuration into our app. In your appsettings.json, you need to add a section at the root for email settings. It should look something like this :

{
  "EmailConfiguration": {
    "SmtpServer": "smtp.myserver.com",
    "SmtpPort": 465,
    "SmtpUsername": "smtpusername",
    "SmtpPassword": "smtppassword",
 
    "PopServer": "popserver",
    "PopPort": 995,
    "PopUsername": "popusername",
    "PopPassword" :  "poppassword"
  }
  ....Other settings here...
}

In the ConfigureServices method or your startup.cs, we can now pull out this configuration and load it into our app with a single line.

public void ConfigureServices(IServiceCollection services)
{
 services.AddMvc();
 services.AddSingleton<IEmailConfiguration>(Configuration.GetSection("EmailConfiguration").Get<EmailConfiguration>());
}

This allows us to inject our configuration class anywhere in our app.

The final piece of the puzzle is a simple email service that can be used to send and receive email. Let’s create an interface and an implementation that’s empty for now. The implementation should accept our settings object as a constructor.

public interface IEmailService
{
 void Send(EmailMessage emailMessage);
 List<EmailMessage> ReceiveEmail(int maxCount = 10);
}
 
public class EmailService : IEmailService
{
 private readonly IEmailConfiguration _emailConfiguration;
 
 public EmailService(IEmailConfiguration emailConfiguration)
 {
  _emailConfiguration = emailConfiguration;
 }
 
 public List<EmailMessage> ReceiveEmail(int maxCount = 10)
 {
  throw new NotImplementedException();
 }
 
 public void Send(EmailMessage emailMessage)
 {
  throw new NotImplementedException();
 }
}

Head back to our ConfigureServices method of our startup.cs to add in a final line to inject in our EmailService everywhere.

public void ConfigureServices(IServiceCollection services)
{
 services.AddMvc();
 services.AddSingleton<IEmailConfiguration>(Configuration.GetSection("EmailConfiguration").Get<EmailConfiguration>());
 services.AddTransient<IEmailService, EmailService>();
}

Phew! And we are done. If at this point we decided MailKit isn’t for us, we still have an email service that can swap in and out libraries as it needs to, and our calling application doesn’t need to worry about what’s going on under the hood. That’s the beauty of abstracting a library away!

Getting Started With MailKit

Getting started with MailKit is as easy as installing a Nuget package. Simply run the following from your Package Manager Console :

Install-Package MailKit

And hey presto! You now have access to MailKit in your application

Sending Email via SMTP With MailKit

Let’s head back to our email service class and fill out the “Send” method with the actual code to send an email via MailKit. The code to do this is below :

public void Send(EmailMessage emailMessage)
{
 var message = new MimeMessage();
 message.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
 message.From.AddRange(emailMessage.FromAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
 
 message.Subject = emailMessage.Subject;
 //We will say we are sending HTML. But there are options for plaintext etc.
 message.Body = new TextPart(TextFormat.Html)
 {
  Text = emailMessage.Content
 };
 
 //Be careful that the SmtpClient class is the one from Mailkit not the framework!
 using (var emailClient = new SmtpClient())
 {
  //The last parameter here is to use SSL (Which you should!)
  emailClient.Connect(_emailConfiguration.SmtpServer, _emailConfiguration.SmtpPort, true);
 
  //Remove any OAuth functionality as we won't be using it.
  emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
 
  emailClient.Authenticate(_emailConfiguration.SmtpUsername, _emailConfiguration.SmtpPassword);
 
  emailClient.Send(message);
 
  emailClient.Disconnect(true);
 }
  
}

The comments should be pretty self explanatory, but let’s quickly run through it.

  • You can send clear text or HTML emails depending on the “TextFormat” you use when creating your message body
  • MailKit has named it’s Smtp class “SmtpClient” which is the same as the framework class. Be careful if you are using Resharper and the like that when you click “Add Reference” you are adding the correct reference.
  • You should choose to use SSL whenever available when connecting to the SMTP Server

Because we built out our EmailService, EmailMessage and EmailConfiguration classes earlier, they are all ready to be used immediately!

Receiving Email via POP With MailKit

And now the code to receive email via POP.

public List<EmailMessage> ReceiveEmail(int maxCount = 10)
{
 using (var emailClient = new Pop3Client())
 {
  emailClient.Connect(_emailConfiguration.PopServer, _emailConfiguration.PopPort, true);
 
  emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
 
  emailClient.Authenticate(_emailConfiguration.PopUsername, _emailConfiguration.PopPassword);
 
  List<EmailMessage> emails = new List<EmailMessage>();
  for(int i=0; i < emailClient.Count && i < maxCount; i++)
  {
   var message = emailClient.GetMessage(i);
   var emailMessage = new EmailMessage
   {
    Content = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody,
    Subject = message.Subject
   };
   emailMessage.ToAddresses.AddRange(message.To.Select(x => (MailboxAddress)x).Select(x => new EmailAddress { Address = x.Address, Name = x.Name }));
   emailMessage.FromAddresses.AddRange(message.From.Select(x => (MailboxAddress)x).Select(x => new EmailAddress { Address = x.Address, Name = x.Name }));
  }
 
  return emails;
 }
}

Again, all rather straight forward.

While we only retrieve a few basic details about the email message, the actual MailKit email object has a tonne of data you can inspect including headers, CC addresses, etc. Extend as you need to!

I Got Exception XYZ

SMTP can sometimes be a bit tricky getting right in terms of SSL, TLS, and ports. Worse yet, the exception messages are often either cryptic, or start pushing you in the completely wrong direction. I created another article here, that should cover any sort of exception you might get when using this code.

Free SMTP Server

It’s worth mentioning that if you are a hobbyist with your own website and want to just send a few emails every now and again under your own domain. A great solution that I use for this very blog is MailGun. It has a great free plan that for most people will be more than enough, but also paid plans for when you really need to start sending a lot of email.

Best ASP.NET Core Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

 

ASP.NET Core Hosting - Using Swagger with ASP.NET Core

$
0
0

Swagger is an auto-magically generated API documenting tool. It takes any standard Web API project and can generate amazing looking (And functioning) docs without a user having to write a single additional line of documentation. Best of all, it can be as simple as a 2 line setup, or as complex as adding additional info to every single API endpoint to explode the level of info inside Swagger.

Getting Started

For the purpose of this guide, I’m just going to be using the standard ASP.net Core Web API template when you create a new project from Visual Studio. But any existing API will work just fine too!

First off, install the following Nuget package from your package manager console.

Install-Package Swashbuckle.AspNetCore

Next in the ConfigureServices method of your startup.cs, add the following code to add the Swagger services to your application.

public void ConfigureServices(IServiceCollection services)
{
 services.AddMvc();
 
 services.AddSwaggerGen(swagger =>
 {
  swagger.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "My First Swagger" });
 });
}

A couple of things to note here, firstly that inside the SwaggerGen lambda you can actually specify a few more details. As an example :

services.AddSwaggerGen(swagger =>
{
 swagger.DescribeAllEnumsAsStrings();
 swagger.DescribeAllParametersInCamelCase();
 swagger.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "My First Swagger" });
});

Here we have said for any enum instead of using the integer value, use the string. And for all parameters can we please use CamelCase. The defaults usually suit most, but if there are specific things you are looking for your docs, you can probably find the setting here.

Secondly is obviously the Info object. Here you can specify things like the documentation author, title, and license among other things.

Head down to the Configure method of your Startup.cs.Add a call to “UseSwagger” and a call to “UseSwaggerUI” Both of these should come before the call to UseMVC.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
 app.UseSwagger();
 app.UseSwaggerUI(c =>
 {
  c.SwaggerEndpoint("/swagger/v1/swagger.json", "My First Swagger");
 });
 
 app.UseMvc();
}

And that’s it! Navigate your browser to https://localhost:{yourport}/swagger  to view your new API documentation.

If you don’t see anything, or it looks a bit odd, jump to the end of this article for a quick trouble shooting session!

XML Comments

The documentation that is auto generated is usually pretty damn good and if you are building a restful API, is usually enough to explain the functions of your API on their own. But there are times when the API needs a bit more explaining. For that, you can use XML Comments on your API action. For example :

/// <summary>
/// Gets a value by ID.
/// </summary>
/// <param name="id">The id of the value you wish to get.</param>
/// <returns></returns>
[HttpGet("{id}")]
public string Get(int id)
{
 return "value";
}

If you are using Visual Studio, you can type three forward slashes in a row and it will auto generate a skeleton set of comments for you. Most importantly is the summary and parameter descriptions that are free text. They are invaluable for being able to explain what an endpoint does and what input it expects.

Next you need to force your application to actually generate the XML data that Swagger can then read. Right click on your project in Visual Studio and select Properties. On the panel that opens up, select “Build” on the left hand side. You should see an option for “Output”, and a checkbox for “Xml documentation file”. Tick this box and the setting will be auto filled out for you.

Note that this setting is per build configuration. If you intend to use Swagger remotely (And therefore likely be built in Release mode before deploying), then you should change the Configuration setting up top on this panel to “Release” and then retick the documentation tickbox.

If you are not using Visual Studio, or you are just interested in how things work behind the scenes. Doing all of this just adds the following line to your csproj file.

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DocumentationFile>bin\Debug\netcoreapp2.0\SwaggerExample.xml</DocumentationFile>
</PropertyGroup>
Next you need to head back to the ConfigureServices method of your startup.cs and add a call to IncludeXmlComments in your Swagger configuration.
services.AddSwaggerGen(swagger =>
{
 swagger.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "My First Swagger", Version = "v1" });
 swagger.IncludeXmlComments(Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "SwaggerExample.xml"));
});

Where SwaggerExample.xml is the xml file you set in your csproj/project configuration.

When you view Swagger again you should now see your XML comments displayed inside the documentation.

Up the top right is our description of our endpoint. And in the id row for our parameters, we also have a description value.

Describing API Response Codes

There may be times where your API returns a non “200” response code that you want to provide documentation for. For example an error of 400 if a particular parameter doesn’t fit certain requirements.

The first step is to decorate your actions with a “Produces” attribute that describes all the possible return codes your endpoint will give out. At the same time you can describe that for a given code, what model you will be returning at the same time. So for example if when you return an error 400, you return a particular class that describes the error, you can define that here.

[HttpGet("{id}")]
[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(404)]
[ProducesResponseType(400)]
public string Get(int id)
{
 return "value";
}

A quick note that you don’t need to specify the return of 200, that is implied, but it’s nice to add anyway. When you view this endpoint in swagger, the non 200 return codes are displayed at the bottom of the endpoint description.

While this lets you know that certain responses are expected, it doesn’t actually give you the reason why they would be returned. For that, we turn again to XML comments.

/// <summary>
/// Gets a value by ID.
/// </summary>
/// <param name="id">The id of the value you wish to get.</param>
/// <returns></returns>
/// <response code="200">Value returned</response>
/// <response code="404">Value was not able to be found</response>
/// <response code="400">Id was below 0</response>
[HttpGet("{id}")]
[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(404)]
[ProducesResponseType(400)]
public string Get(int id)
{
 return "value";
}

Now when we view this endpoint in Swagger again we have the descriptions next to the response codes.

Troubleshooting

I can’t see anything

Check that the nuget package  Microsoft.AspNetCore.StaticFiles is installed in the project. This is required by Swagger to run. If you are unsure, just try installing the package again, this has seriously fixed the issue for me before.

I’m using MVC Core

If you are use the “MVCCore” service rather than just plain MVC. Then you need to explicitly add the API Explorer services. Confused? Head to your ConfigureServices method in your startup.cs. If you see this :

services.AddMvc();

Then you are fine. However if you see this :

services.AddMvcCore();

Then you need to manually add the ApiExplorer service.

services.AddMvcCore().AddApiExplorer();

I’m not using “Attribute Routing”

Then Swagger won’t work for you. You must be using attribute routing to use Swagger.

Best ASP.NET Core Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

Entity Framework Core Tutorial

$
0
0

Who doesn’t love a little bit of data access? Most line-of-business applications are built over some sort of data storage, and nine times out of ten it is a relational database. SQL has a long and distinguished pedigree dating back to some time in the 1980s. Unfortunately, relational data doesn’t match the way we use it in object-oriented languages. To solve this mismatch, we developed tools called object-relational mappers (ORMs).

In this article, we’ll look at one ORM in particular: Entity Framework Core.

A brief history of .NET ORMs

For many years in the .NET space, the king of these tools was NHibernate, which originated in the ALT.NET movement. One of my favorite ORMs from the same ALT.NET era was Subsonic created by Rob Connery. Microsoft, not wanting to be left out, created their own ORM called LINQ2SQL, which was supported only for a couple of years, but has the distinction of being the ORM used to create StackOverflow. Microsoft put in a much more serious effort with Entity Framework. As with a lot of Microsoft products, the early versions were inferior to the community-supported ones. But the technology rapidly improved, and by version 4 Entity Framework was, in my opinion, at least as good as NHibernate.

For a while, all was good in the Entity Framework world. But then came the great revolution that was ASP.NET Core and .NET Core. As part of this change, the Entity Framework team decided that the current EF code base would not support the ambitions of an updated ORM. Thes ambitions included being able to talk seamlessly to different storage backends such as MongoDB and Redis. Entity Framework Core was created. EF Core is now at version 2.1 and is the real deal. Let’s look at how to use it.

Why Entity Framework Core?

The .NET ecosystem contains a few actively maintained ORMs. Dapper comes to mind as the most readily used alternative. Dapper is a micro ORM that really just provides for the mapping from result sets into entities; it has no ability to generate schemas or get you out of writing SQL. EF supports all of this and can mean that you don’t need to write a single bit of SQL in your application. The queries that EF generates are very good and even quite readable, if you do need to drop to SQL to debug. When you need to get an application off the ground quickly, EF provides a low-friction path for data access.

Getting started

Before we dig too deep, let’s look at three of the major concepts in EF: the model, DbSet, and context. The most basic unit in Entity Framework Core is the model; you can think of a model as being a single row inside a relational database table. Models in EF are plain old CLR objects – that is to say, just classes with properties on them.

public class Ant {
    public Guid Id { get; set; }
    public string Name { get; set; }
    public int AgeInDays { get; set; }
    public string FavoriteAntGame { get; set; }
}

This class is a fine model. Notice that we have a property called Id on the model. While you don’t need to do this, it is a good idea to have an Id property that EF will automatically treat as the primary key for the table.

The next piece we need to know about is a DbSet. This is simply a collection that implements IQueryable in much the same way that a List does. There are some additional methods on the class that enable you to do updates you wouldn’t find on a simple IQueryable. DbSets are super powerful because you can work with them like you would any other collection. They can also be a source of performance problems because the abstraction away from the database allows for dramatically inefficient queries. You can think of DbSets as being tables in a database.

Finally, we have the DbContext that holds a number of DbSets which are related to each other. You can think of a DbContext as being the database proper or a schema within the database.

Setting up a data context

We’ve already started down the road of building a database around the concept of an ant hill so let’s go all in on that poor domain selection decision. Let’s add a couple of new entities to our the Ant we specified above. Perhaps a Queen and a Hive.

public class Queen
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public int AgeInDays { get; set; }
}
public class Hive
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public decimal LocationLatitude { get; set; }
    public decimal LocationLongitude { get; set; }
    public Queen Queen { get; set; }
    public IList<Ant> Ants { get; set; } = new List<Ant>();
}

These classes are, again, pretty simple. One thing to notice is that we have a Queen and a collection of Ants hanging off the Hive object. These provide some relationship information for EF and make using the data much easier from an object-oriented perspective.

To make use of EF we’ll pull these various items into a DataContext.

public class Context : DbContext
{
    public Context(DbContextOptions<Context> options) : base(options)
    {
    }
    public DbSet<Ant> Ants { get; set; }
    public DbSet<Hive> Hives { get; set; }
    public DbSet<Queen> Queens { get; set; }
}

If your application is a ASP.NET Core web application, then to start using the context you just need to register it in the services collection

services.AddDbContext<Context>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

This will use the default connection string from the configuration provider. In our example, we’re writing a command line application so we need to provide some of this configuration ourselves. To do so we can make use of the options builder

var optionsBuilder = new DbContextOptionsBuilder<Context>();
optionsBuilder.UseSqlServer("Server=(local);Database=hive_develop;Trusted_Connection=True;");
var context = new Context(optionsBuilder.Options);

In a normal scenario, you’ll want to get that connection string from a configuration source.

Keeping the context small

Frequently I see applications that keep dozens or hundreds (eeek!) of DbSets within a context. This is a bad plan because it encourages creating hyper-complex queries that span a lot of entities. You’re better to take a page out of the domain driven design book and treat each context as a bounded context. Julie Lerman, speaks of this in her data points article from way back in 2013.

Using the context

Now we’ve got a context, let’s start making use of it. The first thing we’ll want to do is lean on Entity Framework to create our actual database. This can be done as simply as calling:

await context.Database.EnsureCreatedAsync()

If we were to drill into the Hive table, we’d see that it has a foreign key relationship to Queen, which Entity Framework Core figured out by just looking at our classes. This is the simplest approach to building a database; however, for more complex and real-world scenarios, you’ll likely want to make use of a concept called Migrations. Migrations provide a mechanism for updating your database as the application evolves. They can be run outside of your application proper as part of a deployment pipeline, and also help when multiple developers might be making changes to the database at the same time.

Simple queries

One of the things that make Entity Framework Core such a powerful ORM is that it has first-class support for LINQ. This makes simple queries remarkably easy to execute. The DbSet in the context implements an interface called IQueryable, which allows you to chain function calls together to filter, project, sort, or any number of other things. Let’s try a few quick examples:

Get all the ants named Bob (a very popular name ant name):

context.Ants.Where(x => x.Name == "Bob")

You can also do compound queries where you provide multiple constraints. Here we want all the ants named Bob who are older than 30 days.

context.Ants.Where(x => x.Name == "Bob" && x.AgeInDays > 30)

Because all these queries are implemented using expressions you can build up queries and only have them execute when you request results from them. So, for example, we can build a search engine style query like so.

private async static Task<IEnumerable<Ant>> Search(Context context, int? age, string name, string game)
{
    var query = context.Ants as IQueryable<Ant>;
    if (age.HasValue)
        query = query.Where(x => x.AgeInDays == age);
    if (!String.IsNullOrEmpty(name))
        query = query.Where(x => x.Name == name);
    if (!String.IsNullOrEmpty(game))
        query = query.Where(x => x.FavoriteAntGame == game);
    return await query.ToListAsync();
}

This allows passing in a number of parameters, some of which may be null. As you can see, we build up a query in a highly readable and scalable fashion. The IQueryable may be passed around to any number of builder functions, each one of which stacks up some further criteria.

Of course, we can do more than just filter data using EF: data can be sorted, projected, or combined in a myriad of ways.

Complex queries

LINQ is a really nice domain-specific language for manipulating and querying objects, however, sometimes you have to relax the abstraction and get back to the relational model. If you find yourself building crazy queries that bend your mind with the complexity of the LINQ, then take a step back: you can drop to SQL to perform your queries.

This is done using the FromSql for queries:

context.Ants.FromSql<Ant>("select * from ants");

or using the ExecuteSqlCommandAsync:

context.Database.ExecuteSqlCommandAsync("delete from ants where name='Bob'");

Unfortunately, you must use a real entity for your SQL queries and you cannot use a projection. This was functionality that was available in EF and will hopefully resurface in EF Core at some point soon. The recommendation in the Entity Framework Core documentation is to use ADO.NET, like some sort of peasant from 2003. Instead, I’d suggest you make use of Dapper, which does support mapping arbitrary data to objects. It isn’t a fully fledged ORM, but it does have the advantage of being very fast and very tunable.

Updating data

Changing data retrieved from the context is really easy, thanks to the fact that all the entities used are tracked. If we wanted to load an Ant and then change the name, it is as simple as:

var ant = await context.Ants.FirstOrDefaultAsync(x => x.Id == id);
ant.Name = "Bob";
await context.SaveChangesAsync();

Performance tip: Async

You’ll notice that Entity Framework Core has a lot of asynchronous methods – they’re the ones ending in Async. These methods are generally a better option than the synchronous ones for applications that need to run multiple database queries at once. You should be aware that async does add some overhead, so it is not universally superior. Benchmarking is really the only solution.

Performance tip: No tracking

Entity Framework Core maintains a memory reference for every object retrieved from the database in order to know what has changed when writing records back. In many scenarios, especially web scenarios, there is no need to maintain this information because the entities you’re saving are rehydrated from an HTTP request. You can make EF Core much more efficient by setting no tracking:

var ants = context.Ants.AsNoTracking() .ToList();

Performance tip: Profiling

You can easily build queries in Entity Framework Core that seem reasonable, but end up being very costly when transformed to SQL. In order to watch the queries you’re making, there is no better tool than Prefix. You can use Prefix to spot common issues like n+1 problems or slow queries. Your users will be grateful that you’ve taken the time to install and run some profiling. And the best part is, Prefix is free.

Best ASP.NET Core Hosting Recommendation

ASPHostPortal.comprovides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

Viewing all 427 articles
Browse latest View live