All About ASP.NET and ASP.NET Core 2 Hosting BLOG

Tutorial and Articles about ASP.NET and the latest ASP.NET Core

Entity Framework Core Tutorial

clock October 16, 2018 09:52 by author Kenny

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.com provides 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

clock October 12, 2018 12:11 by author Kenny

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.com provides 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 MailKit To Send And Receive Email In ASP.NET Core

clock October 5, 2018 06:09 by author Kenny

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.com provides 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

clock September 25, 2018 09:26 by author Jervis

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 Layered Architectures In ASP.NET

clock September 7, 2018 11:57 by author Kenny

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.com provides 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

clock August 24, 2018 11:39 by author Kenny

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.com provides 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

clock August 21, 2018 09:56 by author Kenny

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.com provides 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

clock August 14, 2018 13:13 by author Kenny

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.com provides 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#

clock August 10, 2018 11:11 by author Kenny

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.com provides 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

clock August 3, 2018 11:29 by author Kenny

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.com provides 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.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link

 photo ahp banner aspnet-01_zps87l92lcl.png

 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in