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 - 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 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 - 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 Hosting - ASPHostPortal.com :: How To Using DataAnnotations and Localization in ASP.NET Core MVC

clock March 14, 2017 05:54 by author Armend

Using DataAnnotations and Localization in ASP.NET Core MVC

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

Localization Setup

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

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

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

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

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

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

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

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

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

Best ASP.NET Hosting Recommendation

ASPHostPortal.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 Hosting - ASPHostPortal.com :: Improve Performance of an ASP.NET Website

clock March 7, 2017 04:49 by author Armend

Improve Performance of an ASP.NET Website

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

1. Upgrade Your ASP.NET Framework

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

2. Caching

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

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

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

3. Always keep CSS and JavaScript External

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

4. File Compression

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

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

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

5. Bundling and Minification

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

6. CDN (Content Delivery Network)

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

7. Control Image Requests

There are couple of ways to do this. 

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

8. Script Rendering Order

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

There are some other ways:

  • 1.defer attribute

Hide Copy Code

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

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

  • 2.async attribute

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

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

9. Removing Default HTTP Modules in ASP.NET

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

10. Compile in Release Mode

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

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

Best ASP.NET Hosting Recommendation

ASPHostPortal.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 - ASPHostPortal.com :: Centralized ASP.NET Core Logging in One Line of Code

clock February 14, 2017 05:32 by author Armend

Centralized ASP.NET Core Logging in One Line of Code

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

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

Seq.Extensions.Logging

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

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

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

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

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

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

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

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

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

Under the hood

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

Levelling up

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



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


 

Corporate Address (Location)

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

Tag cloud

Sign in