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

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

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.



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

clock July 31, 2018 08:47 by author Kenny

 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.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 - The Differences Between ASP.NET MVC and ASP.NET WebForms

clock July 27, 2018 07:28 by author Kenny

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.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 - Creating A GraphQL Endpoint in ASP.NET Core

clock July 24, 2018 08:25 by author Kenny

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.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 - Prepare Your Machine and Get to Know Visual Studio Code for Angular 2 and ASP.NET Core Project

clock July 10, 2018 11:44 by author Kenny

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.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 Publish ASP.NET Core 2

clock February 13, 2018 07:34 by author Jervis

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.



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