Using Asynchronous Methods in ASP.NET 4.5

Using Asynchronous Methods in ASP.NET 4.5

CheapASPNETHostingReview.com Best and cheap ASP.NET 4.5 hosting. This tutorial will teach you the basics of building an asynchronous ASP.NET Web Forms application using Visual Studio Express 2012 for Web, which is a free version of Microsoft Visual Studio. You can also use Visual Studio 2012.

ASP.NET 4.5 Web Pages in combination .NET 4.5 enables you to register asynchronous methods that return an object of type Task. The .NET Framework 4 introduced an asynchronous programming concept referred to as a Task and ASP.NET 4.5 supports Task. Tasks are represented by the Task type and related types in the System.Threading.Tasks namespace. The .NET Framework 4.5 builds on this asynchronous support with the await and async keywords that make working with Task objects much less complex than previous asynchronous approaches. The awaitkeyword is syntactical shorthand for indicating that a piece of code should asynchronously wait on some other piece of code. The async keyword represents a hint that you can use to mark methods as task-based asynchronous methods. The combination of awaitasync, and the Taskobject makes it much easier for you to write asynchronous code in .NET 4.5. The new model for asynchronous methods is called the Task-based Asynchronous Pattern (TAP). This tutorial assumes you have some familiarity with asynchronous programing using await and asynckeywords and the Task namespace.

How Requests Are Processed by the Thread Pool

On the web server, the .NET Framework maintains a pool of threads that are used to service ASP.NET requests. When a request arrives, a thread from the pool is dispatched to process that request. If the request is processed synchronously, the thread that processes the request is busy while the request is being processed, and that thread cannot service another request.

This might not be a problem, because the thread pool can be made large enough to accommodate many busy threads. However, the number of threads in the thread pool is limited (the default maximum for .NET 4.5 is 5,000). In large applications with high concurrency of long-running requests, all available threads might be busy. This condition is known as thread starvation. When this condition is reached, the web server queues requests. If the request queue becomes full, the web server rejects requests with an HTTP 503 status (Server Too Busy). The CLR thread pool has limitations on new thread injections. If concurrency is bursty (that is, your web site can suddenly get a large number of requests) and all available request threads are busy because of backend calls with high latency, the limited thread injection rate can make your application respond very poorly. Additionally, each new thread added to the thread pool has overhead (such as 1 MB of stack memory). A web application using synchronous methods to service high latency calls where the thread pool grows to the .NET 4.5 default maximum of 5, 000 threads would consume approximately 5 GB more memory than an application able the service the same requests using asynchronous methods and only 50 threads. When you’re doing asynchronous work, you’re not always using a thread. For example, when you make an asynchronous web service request, ASP.NET will not be using any threads between the asyncmethod call and the await. Using the thread pool to service requests with high latency can lead to a large memory footprint and poor utilization of the server hardware.

Processing Asynchronous Requests

In web applications that see a large number of concurrent requests at start-up or has a bursty load (where concurrency increases suddenly), making web service calls asynchronous will increase the responsiveness of your application. An asynchronous request takes the same amount of time to process as a synchronous request. For example, if a request makes a web service call that requires two seconds to complete, the request takes two seconds whether it is performed synchronously or asynchronously. However, during an asynchronous call, a thread is not blocked from responding to other requests while it waits for the first request to complete. Therefore, asynchronous requests prevent request queuing and thread pool growth when there are many concurrent requests that invoke long-running operations.

Choosing Synchronous or Asynchronous Methods

This section lists guidelines for when to use synchronous or asynchronous Methods. These are just guidelines; examine each application individually to determine whether asynchronous methods help with performance.

In general, use synchronous methods for the following conditions:

  • The operations are simple or short-running.
  • Simplicity is more important than efficiency.
  • The operations are primarily CPU operations instead of operations that involve extensive disk or network overhead. Using asynchronous methods on CPU-bound operations provides no benefits and results in more overhead.

    In general, use asynchronous methods for the following conditions:

  • You’re calling services that can be consumed through asynchronous methods, and you’re using .NET 4.5 or higher.
  • The operations are network-bound or I/O-bound instead of CPU-bound.
  • Parallelism is more important than simplicity of code.
  • You want to provide a mechanism that lets users cancel a long-running request.
  • When the benefit of switching threads out weights the cost of the context switch. In general, you should make a method asynchronous if the synchronous method blocks the ASP.NET request thread while doing no work. By making the call asynchronous, the ASP.NET request thread is not blocked doing no work while it waits for the web service request to complete.
  • Testing shows that the blocking operations are a bottleneck in site performance and that IIS can service more requests by using asynchronous methods for these blocking calls.

    The downloadable sample shows how to use asynchronous methods effectively. The sample provided was designed to provide a simple demonstration of asynchronous programming in ASP.NET 4.5. The sample is not intended to be a reference architecture for asynchronous programming in ASP.NET. The sample program calls ASP.NET Web APImethods which in turn call Task.Delay to simulate long-running web service calls. Most production applications will not show such obvious benefits to using asynchronous Methods.

Few applications require all methods to be asynchronous. Often, converting a few synchronous methods to asynchronous methods provides the best efficiency increase for the amount of work required.

The Sample Application

You can download the sample application from https://github.com/RickAndMSFT/Async-ASP.NETon the GitHub site. The repository consists of three projects:

  • WebAppAsync: The ASP.NET Web Forms project that consumes the Web API WebAPIpwgservice. Most of the code for this tutorial is from the this project.
  • WebAPIpgw: The ASP.NET MVC 4 Web API project that implements the Products, Gizmos and Widgets controllers. It provides the data for the WebAppAsyncproject and the Mvc4Async project.
  • Mvc4Async: The ASP.NET MVC 4 project that contains the code used in another tutorial. It makes Web API calls to the WebAPIpwg service.

The Gizmos Synchronous Page

The following code shows the Page_Load synchronous method that is used to display a list of gizmos. (For this article, a gizmo is a fictional mechanical device.)

The following code shows the GetGizmos method of the gizmo service.

The GizmoService GetGizmos method passes a URI to an ASP.NET Web API HTTP service which returns a list of gizmos data. The WebAPIpgw project contains the implementation of the Web API gizmos, widget and product controllers.
The following image shows the gizmos page from the sample project.

gizmos

Creating an Asynchronous Gizmos Page

The sample uses the new async and await keywords (available in .NET 4.5 and Visual Studio 2012) to let the compiler be responsible for maintaining the complicated transformations necessary for asynchronous programming. The compiler lets you write code using the C#’s synchronous control flow constructs and the compiler automatically applies the transformations necessary to use callbacks in order to avoid blocking threads.

ASP.NET asynchronous pages must include the Page directive with the Async attribute set to “true”. The following code shows the Page directive with the Async attribute set to “true” for the GizmosAsync.aspx page.

 The following code shows the Gizmos synchronous Page_Load method and the GizmosAsyncasynchronous page. If your browser supports the HTML 5 <mark> element, you’ll see the changes in GizmosAsync in yellow highlight.

 The asynchronous version:

The following changes were applied to allow the GizmosAsync page be asynchronous.

  • The Page directive must have the Async attribute set to “true”.
  • The RegisterAsyncTask method is used to register an asynchronous task containing the code which runs asynchronously.
  • The new GetGizmosSvcAsync method is marked with the async keyword, which tells the compiler to generate callbacks for parts of the body and to automatically create a Taskthat is returned.
  • “Async” was appended to the asynchronous method name. Appending “Async” is not required but is the convention when writing asynchronous methods.
  • The return type of the new new GetGizmosSvcAsync method is Task. The return type of Task represents ongoing work and provides callers of the method with a handle through which to wait for the asynchronous operation’s completion.
  • The await keyword was applied to the web service call.
  • The asynchronous web service API was called (GetGizmosAsync).

Inside of the GetGizmosSvcAsync method body another asynchronous method, GetGizmosAsync is called. GetGizmosAsync immediately returns a Task<List<Gizmo>> that will eventually complete when the data is available. Because you don’t want to do anything else until you have the gizmo data, the code awaits the task (using the await keyword). You can use the await keyword only in methods annotated with the async keyword.

The await keyword does not block the thread until the task is complete. It signs up the rest of the method as a callback on the task, and immediately returns. When the awaited task eventually completes, it will invoke that callback and thus resume the execution of the method right where it left off. For more information on using the await and async keywords and the Task namespace, see the async references section.

The following code shows the GetGizmos and GetGizmosAsync methods.

The asynchronous changes are similar to those made to the GizmosAsync above.

  • The method signature was annotated with the async keyword, the return type was changed to Task<List<Gizmo>>, and Async was appended to the method name.
  • The asynchronous HttpClient class is used instead of the synchronous WebClient class.
  • The await keyword was applied to the HttpClientGetAsync asynchronous method.

The following image shows the asynchronous gizmo view.

The browsers presentation of the gizmos data is identical to the view created by the synchronous call. The only difference is the asynchronous version may be more performant under heavy loads.

RegisterAsyncTask Notes

Methods hooked up with RegisterAsyncTask will run immediately after PreRender. You can also use async void page events directly, as shown in the following code:

The downside to async void events is that developers no longer has full control over when events execute. For example, if both an .aspx and a .Master define Page_Load events and one or both of them are asynchronous, the order of execution can’t be guaranteed. The same indeterminiate order for non event handlers (such as async void Button_Click ) applies. For most developers this should be acceptable, but those who require full control over the order of execution should only use APIs like RegisterAsyncTask that consume methods which return a Task object.

Performing Multiple Operations in Parallel

Asynchronous Methods have a significant advantage over synchronous methods when an action must perform several independent operations. In the sample provided, the synchronous page PWG.aspx(for Products, Widgets and Gizmos) displays the results of three web service calls to get a list of products, widgets, and gizmos. The ASP.NET Web API project that provides these services uses Task.Delay to simulate latency or slow network calls. When the delay is set to 500 milliseconds, the asynchronous PWGasync.aspx page takes a little over 500 milliseconds to complete while the synchronous PWG version takes over 1,500 milliseconds. The synchronous PWG.aspx page is shown in the following code.

The asynchronous PWGasync code behind is shown below.

Using a Cancellation Token

Asynchronous Methods returning Taskare cancelable, that is they take a CancellationTokenparameter when one is provided with the AsyncTimeout attribute of the Page directive. The following code shows the GizmosCancelAsync.aspx page with a timeout of on second.

The following code shows the GizmosCancelAsync.aspx.cs file.

In the sample application provided, selecting the GizmosCancelAsync link calls the GizmosCancelAsync.aspx page and demonstrates the cancelation (by timing out) of the asynchronous call. Because the delay time is within a random range, you might need to refresh the page a couple times to get the time out error message.

Server Configuration for High Concurrency/High Latency Web Service Calls

To realize the benefits of an asynchronous web application, you might need to make some changes to the default server configuration. Keep the following in mind when configuring and stress testing your asynchronous web application.

  • Windows 7, Windows Vista, Window 8, and all Windows client operating systems have a maximum of 10 concurrent requests. You’ll need a Windows Server operating system to see the benefits of asynchronous methods under high load.
  • Register .NET 4.5 with IIS from an elevated command prompt using the following command:
    %windir%\Microsoft.NET\Framework64 \v4.0.30319\aspnet_regiis -i
    See ASP.NET IIS Registration Tool (Aspnet_regiis.exe)
  • You might need to increase the HTTP.sys queue limit from the default value of 1,000 to 5,000. If the setting is too low, you may see HTTP.sys reject requests with a HTTP 503 status. To change the HTTP.sys queue limit:

    • Open IIS manager and navigate to the Application Pools pane.
    • Right click on the target application pool and select Advanced Settings.
  • If your application is using web services or System.NET to communicate with a backend over HTTP you may need to increase the connectionManagement/maxconnection element. For ASP.NET applications, this is limited by the autoConfig feature to 12 times the number of CPUs. That means that on a quad-proc, you can have at most 12 * 4 = 48 concurrent connections to an IP end point. Because this is tied to autoConfig, the easiest way to increase maxconnection in an ASP.NET application is to set System.Net.ServicePointManager.DefaultConnectionLimit programmatically in the from Application_Start method in the global.asax file. See the sample download for an example.
  • In .NET 4.5, the default of 5000 for MaxConcurrentRequestsPerCPU should be fine.
Code Editing ASP.NET Web Forms in Visual Studio 2013

Code Editing ASP.NET Web Forms in Visual Studio 2013

CheapASPNETHostingReview.com | In many ASP.NET Web Form pages, you write code in Visual Basic, C#, or another language. The code editor in Visual Studio can help you write code quickly while helping you avoid errors. In addition, the editor provides ways for you to create reusable code to help reduce the amount of work you need to do.

This walkthrough illustrates various features of the Visual Studio code editor.

During this walkthrough, you will learn how to:+

  • Correct inline coding errors.
  • Refactor and rename code.
  • Rename variables and objects.
  • Insert code snippets.

Prerequisites

In order to complete this walkthrough, you will need:

  • Microsoft Visual Studio 2013 or Microsoft Visual Studio Express 2013 for Web. The .NET Framework is installed automatically.

Creating a Web application project and a Page

In this part of the walkthrough, you will create a Web application project and add a new page to it.

To create a Web application project

  1. Open Microsoft Visual Studio.
  2. On the File menu, select New Project The New Project dialog box appears.
  3. Select the Templates -> Visual C# -> Web templates group on the left.
  4. Choose the ASP.NET Web Application template in the center column.
  5. Name your project BasicWebApp and click the OK button.
  6. Next, select the Web Forms template and click the OK button to create the project.

Visual Studio creates a new project that includes prebuilt functionality based on the Web Forms template.

Creating a new ASP.NET Web Forms Page

When you create a new Web Forms application using the ASP.NET Web Application project template, Visual Studio adds an ASP.NET page (Web Forms page) named Default.aspx, as well as several other files and folders. You can use the Default.aspx page as the home page for your Web application. However, for this walkthrough, you will create and work with a new page.

To add a page to the Web application

  • In Solution Explorer, right-click the Web application name (in this tutorial the application name is BasicWebSite), and then click Add -> New Item.
    The Add New Item dialog box is displayed.
  • Select the Visual C# -> Web templates group on the left. Then, select Web Form from the middle list and name it FirstWebPage.aspx.

ada1

  • Click Add to add the Web Forms page to your project.
    Visual Studio creates the new page and opens it.
  • Next, set this new page as the default startup page. In Solution Explorer, right-click the new page named FirstWebPage.aspx and select Set As Start Page. The next time you run this application to test our progress, you will automatically see this new page in the browser.

Correcting Inline Coding Errors

The code editor in Visual Studio helps you to avoid errors as you write code, and if you have made an error, the code editor helps you to correct the error. In this part of the walkthrough, you will write a line of code that illustrate the error correction features in the editor.

To correct simple coding errors in Visual Studio

  1. In Design view, double-click the blank page to create a handler for the Load event for the page.
    You are using the event handler only as a place to write some code.
  2. Inside the handler, type the following line that contains an error and press ENTER:

When you press ENTER, the code editor places green and red underlines (commonly call “squiggly” lines) under areas of the code that have issues. A green underline indicates a warning. A red underline indicates an error that you must fix.

Hold the mouse pointer over myStr to see a tooltip that tells you about the warning. Also, hold your mouse pointer over the red underline to see the error message.

The following image shows the code with the underlines.

ada2

The error must be fixed by adding a semicolon ; to the end of the line. The warning simply notifies you that you haven’t used the myStr variable yet.

Refactoring and Renaming

Refactoring is a software methodology that involves restructuring your code to make it easier to understand and to maintain, while preserving its functionality. A simple example might be that you write code in an event handler to get data from a database. As you develop your page, you discover that you need to access the data from several different handlers. Therefore, you refactor the page’s code by creating a data-access method in the page and inserting calls to the method in the handlers.

The code editor includes tools to help you perform various refactoring tasks. In this walkthrough, you will work with two refactoring techniques: renaming variables and extracting methods. Other refactoring options include encapsulating fields, promoting local variables to method parameters, and managing method parameters. The availability of these refactoring options depends on the location in the code.

Refactoring Code

A common refactoring scenario is to create (extract) a method from code that is inside another member, such as a method. This reduces the size of the original member and makes the extracted code reusable.

In this part of the walkthrough, you will write some simple code, and then extract a method from it. Refactoring is supported for C#, so you will create a page that uses C# as its programming language.

To extract a method in a C# page

  • Switch to Design view.
  • In the Toolbox, from the Standard tab, drag a Button control onto the page.
  • Double-click the Button control to create a handler for its Click event, and then add the following highlighted code:

    The code creates an ArrayList object, uses a loop to load it with values, and then uses another loop to display the contents of the ArrayList object.

  • Press CTRL+F5 to run the page, and then click the button to make sure that you see the following output
  • Return to the code editor, and then select the following lines in the event handler.
  • Right-click the selection, click Refactor, and then choose Extract Method.

    The Extract Method dialog box appears.

  • In the New Method Name box, type DisplayArray, and then click OK.

    The code editor creates a new method named DisplayArray, and puts a call to the new method in the Click handler where the loop was originally.

  • Press CTRL+F5 to run the page again, and click the button.

    The page functions the same as it did before. The DisplayArray method can now be call from anywhere in the page class.

Renaming Variables

When you work with variables, as well as objects, you might want to rename them after they are already referenced in your code. However, renaming variables and objects can cause the code to break if you miss renaming one of the references. Therefore, you can use refactoring to perform the renaming.

To use refactoring to rename a variable

  1. In the Click event handler, locate the following line:
  2. Right-click the variable name alist, choose Refactor, and then choose Rename.

    The Rename dialog box appears.

  3. In the New name box, type ArrayList1 and make sure the Preview reference changescheckbox has been selected. Then click OK.

    The Preview Changes dialog box appears, and displays a tree that contains all references to the variable that you are renaming.

  4. Click Apply to close the Preview Changes dialog box.

    The variables that refer specifically to the instance that you selected are renamed. Note, however, that the variable alist in the following line is not renamed.

    The variable alist in this line is not renamed because it does not represent the same value as the variable alist that you renamed. The variable alist in the DisplayArraydeclaration is a local variable for that method. This illustrates that using refactoring to rename variables is different than simply performing a find-and-replace action in the editor; refactoring renames variables with knowledge of the semantics of the variable that it is working with.

Inserting Snippets

Because there are many coding tasks that Web Forms developers frequently need to perform, the code editor provides a library of snippets, or blocks of prewritten code. You can insert these snippets into your page.

Each language that you use in Visual Studio has slight differences in the way you insert code snippets. For information about inserting snippets, see Visual Basic IntelliSense Code Snippets. For information about inserting snippets in Visual C#, see Visual C# Code Snippets.

jQuery Tooltip Validation Using Twitter Bootstrap

jQuery Tooltip Validation Using Twitter Bootstrap

CheapASPNETHostingReview.com | Generally, we use a jQuery unobtrusive validation plugin in ASP.NET MVC Applications.We are going to discuss the following topics in this article:

  1. Disadvantages of jQuery unobtrusive validation in MVC.
  2. jQuery tooltip validation

There are some disadvantages of using this plugin. When using the jQuery unobtrusive validation plugin, it creates a span tag to display error messages. If you have, for example, a horizontal form on top of the other controls, then this behavior might not be working for you, since they will break the page layout. It was the case for me and as such, I decided to change the default behavior of the jQuery unobtrusive validation library and instead of using a span to show the error message, I decided to use a tooltip. I am going to show you how I achieved this, using a tooltip with the help of a bootstrap.

Before going to the tooltip validation, first look at the traditional jQuery unobtrusive example.

The following is an example of an application of unobtrusive validation.

validation

When I click the Register button, the error message comes, as shown below:

click on Register button

If I increase the length of the error message, the layout will be broken like this. In the same way, when I place the same length error message below, the Textbox controls come as shown in the screenshot. The same layout-change problem occurs. Hence, this is a bad idea of using a default behavior of the  jQuery Unobtrusive validation plugin. I replaced the error type with a tooltip. It won’t change the layout structure.

Now the jQuery tooltip validation article begins from here,

jQuery tooltip validation using Twitter Bootstrap

Step 1

Create ASP.NET MVC Application.

  1. Create Application with MVC template.

Create a application

2. Add the following files.

add files

3. Create HomeController.cs.

Right click->Controllers folder->Add->Controller->name it as HomeController.cs.

add controller

4. Add Index Method to the Controller.

5. Add View to Index Action method.

Right click->Index Method->Add View->click OK.

Add view

Index view is created.

6. Now, replace the Index.cshtml code with the code given below:

Step 2

Add the script for the validation,

  1. Add myscript.js to the script folder.

    myscript.js

Step 3

Add styles for the error display.

Now run the Application and you will get the Window as shown below:

Enter details

Without entering anything into the fields, just click on the Register button and see what happens.

Register

Restore Database Scema on DNN

Restore Database Scema on DNN

CheapASPNETHostingReview.comDotnetnuke standard installs using the dbo as the default user. Some hosts however, like shared hosting service providers, do not allow you to use dbo. So in this case you have to install Dotnetnuke using your assigned username. This should work without any problems. But in case you have an existing website which was installed using the dbo user and you would like to migrate it to a hosting provider that does not allow dbo you have a problem.

DNN-title-banner

The easiest way to migrate a Dotnetnuke website is by backing up the entire web and the database and restore it to the new environment. This will work fine only if your new environment allows dbo. If it does not you will find that when restoring the database all objects will have been assigned to your username and not to dbo and your web will not run.

To resolve this issue you can follow the steps outlined below after which your web will run without any problems. As this procedure requires changes to the databse please be sure to have a backup of your database and website. Note: This procedure is for a SQL server 2005 database!

Step 1:
Open your web.config file and look for “owner”. Change the owner from dbo to your database username. 
Open your web.config file and look for “owner”. Change the owner from dbo to your database username.

Step 2:
In Microsoft SQL Server management studio select all stored procedures that DO NOT have aspnet in their name, rightclick and select “script as create to new query editor window”. 
In Microsoft SQL Server management studio select all stored procedures that DO NOT have aspnet in their name, rightclick and select “script as create to new query editor window”.

This will create a script for all the selected stored procedures.

Step 3:
Where it says “new owner” below you should change it for your database username! 
Where it says “new owner” below you should change it for your database username!

  • In the just created script search and replace “create procedure” with “alter procedure”
  • Search and replace “create procedure” with “alter procedure” (Note! with 2 spaces!)
  • Search and replace “[dbo]” with “[new owner]”
  • Search and replace “dbo.” with “new owner.”
  • Execute the script

Step 4:
In Microsoft SQL Server management studio select all stored views that DO NOT have aspnet in their name, rightclick and select “script as create to new query editor window”. 
In Microsoft SQL Server management studio select all stored views that DO NOT have aspnet in their name, rightclick and select “script as create to new query editor window”.

Step 5:

  • Search and replace “[dbo]” with “[new owner]”
  • Search and replace “dbo.” with “new owner.”
  • Search and replace “create view” with “alter view”
  • Search and replace “new owner.GetListParentKey” width “dbo.GetListParentKey”
  • Execute the script

Step 6:

  • Go to “functions” “Scalar-valued functions”
  • rightclick and select “script as create to new query editor window” for function “fn_GetVersion”
  • Search and replace “dbo.” with “new owner.” (including the “.”!)
  • Execute script

Step 7:

Open a new query window and paste the following script:

Search and replace [USERNAME] for your database username and execute the script.

Step 8:
Refresh your database manager window and you should now see that all AspNet tables and storedprocedures belong to the dbo user/schema. Open your website in your browser. Your website should now load as normal.

Tips To Secure your ASP.NET MVC Application

Tips To Secure your ASP.NET MVC Application

CheapASPNETHostingReview.com | Best and cheap ASP.NET hosting. Securing your ASP.NET MVC application ought to be priority number a single each time you begin a brand new net application. Employing the attributes Authorize and ValidateAntiForgeryToken in every single controller and action will be the only method to stay away from any safety holes. In this post I’ll show you the best way to secure your ASP.NET application by implementing the AuthorizeAttribute and ValidateAntiForgeryTokenAttribute classes.

The basics

In the extremely least, you need to add an [Authorize] attribute to every controller or controller Action in case you would like several of the controller actions to be accessible by anonymous users. As an example, you probably want ALL users to possess access for the login and register actions of one’s web application.

By decorating the HomeController using the Authorize attribute (notice I didn’t specify any user part) the application will avert any unauthenticated user from executing any in the actions in this controller.

The following is an instance of decorating a controller action with all the Authorize attribute, you desire to complete this if you only want to restrict access to a few of the actions in a controller instead of all actions.

Safeguarding against Cross-site request forgery attack (CSRF or XSRF)

The Authorize attribute delivers protection which is sufficient in most situations. Nonetheless, there’s security hole with this and therefore it opens your web application for a cross-site request forgery attack. By way of example, right after a user logs into your website the website will concern your browser an authentication token inside a cookie. Every single subsequent request, the browser sends the cookie back for the site to let the web site realize that you are authorized to take what ever action you are taking, so far every thing is very good.

Right here would be the issue with only using the Authorize attribute, let’s say that a user is logged in to your website and then they visit a spam web site by clicking on a hyperlink that points to one more web site which causes a kind post back to your site… this can be negative, your browser will send the authentication cookie to your website generating it seem as when the request came out of your website and initiated by an authenticated user when it genuinely didn’t.

The above situation is known as cross-site request forgery and can be avoided by adding the ValidateAntiForgeryToken attribute offered inside the .NET framework, this attribute is employed to detect regardless of whether a server request has been tampered with.

The initial step would be to add the ValidateAntiForgeryToken attribute to every single Post Action as follows:

The next step is to add the HtmlHelper strategy @Html.AntiForgeryToken() inside the type within your view.

The way the ValidateAntiForgeryToken attribute operates is by checking to view that the cookie and hidden kind field left by the Html.AntiForgeryToken() HtmlHelper essentially exists and match. If they do not exist or match, it throws an HttpAntiForgeryException shown beneath:

“A essential anti-forgery token was not supplied or was invalid”

By adding the ValidateAntiForgeryToken for your controller actions your internet site will likely be prepared to stop CSRF/XSRF attacks.

Implementing Forms Authentication using Active Directory (AD)

Often times you might run across a project where you need to authenticate users of your website using Active Directory credentials, the good news is that you can use the existing “Account” controller to achieve this, only a few modifications are necessary.

When you create a new MVC Web Application project and choose the Internet Application template, the Account controller is added to the project, you can use this controller with AD to authenticate your users. For the Account controller to work with AD we need to remove all Actions but the following:

  • Logon()
  • Logon(LogOnModel model, string returnUrl)
  • LogOff()

Your Account controller should look like the following after you remove the unnecessary Actions such as ChangePassword, Register, etc.

After this, go ahead and clean up the AccountModel as well so the only model class left is the LogOnModel:

Lastly, add the following to the project’s web.config file:

1ed

Using DataAnnotations and Localization in ASP.NET Core MVC

Using DataAnnotations and Localization in ASP.NET Core MVC

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core MVC hosting. 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.

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.

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.

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.

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.

How to Turn off Asp.net Custom Errors in Web.config

How to Turn off Asp.net Custom Errors in Web.config

CheapASPNETHostingReview.com | Best and cheap ASP.NET Hosting. Some times after hosting web application on the server, we get unexpected error as shown in the below fig. But we did get the detailed message for the unexpected errror. In this article, I would like to share how can we get detailed message for the unexpected error.

disableerror

This type of unexpected error may occurs on local or remote server. In asp.net, we can find the exact error message by setting mode=”Off” with in customErrors tag in web.config of our application. This is the way by which we can find out the exact error in our web application

When we set the customErrors mode=”Off” then we can easily track the error in the application as shown in the fig.

disableerror1

In Asp.net, there are three error modes to trace an error. These modes decide whether or not an error message is displayed. RemoteOnly mode is default mode for displaying error messages.

  1. Off Mode

    This mode is responsible for displaying error mesage on local and remote server in case of an error.

  2. On Mode

    This mode is responsible for displaying custom error page with message on local and remote server in case of an error. By using this mode, we can show our own custom error messages page for specific errors on local and remote server.

  3. RemoteOnly

    This mode is responsible for displaying error mesage on remote server only in case of an error. By using this mode, we can show our own custom error messages page for specific errors on remote server only.

I hope you will enjoy these tricks while programming with Asp.Net. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Tag Helper Component in ASP.NET Core 2.0

Tag Helper Component in ASP.NET Core 2.0

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core 2.0 hosting. How to dynamically write HTML using Tag Helper Components in ASP.NET Core 2.0 ? In this post we will discuss about Tag helper component in ASP.NET Core 2.0

Create an empty project and add a controller:

Add a view:

Add a Tag Helper Component:

Update the Startup class, inject the component class to service container:

Run and observe the page generated (view source or developer tools in browser):

meta

Note that the two meta tags were dynamically generated by the Tag Helper Component.

Discussion

ASP.NET Core 2.0 has introduced “Tag Helper Components” that improve and complement Tag Helpers by giving developers capability to use Dependency Injection with them.

The way this works is that:

  1. We create a Tag Helper to target existing or new (i.e. custom) HTML elements.
  2. We then create a class that inherits from TagHelperComponent and override its Process() method to append HTML content to the Tag Helper’s HTML element.
  3. We then inject this class into the service container, which is executed at runtime.

In case you’re wondering if the solution above is missing a Tag Helper for head HTML element, it’s not. ASP.NET Core team has provided us with two built-in Tag Helpers, one targets head and the other targets the body element: HeadTagHelper and BodyTagHelper

In the solution above our Tag Helper Component is adding few meta tags to the head element. This could be used, for instance, by a blogging engine to output them for search engine optimisation.

I’ve hard-coded entries but of course using Dependency Injection we can inject a service that could retrieve these from a database:

Another possible use-case for a Tag Helper Component, that targets head or body, is to dynamically inject scripts/styles e.g.:

There is an interesting application of this for JavaScript logging

Custom Tag Helpers & Components

We can use these components for custom Tag Helpers too. Let’s say we want to target all the footer elements and inject current time (or visitors count, logo, copyright etc.). We can first create a Tag Helper to target a footer element:

Note: the base class is the new TagHelperComponentTagHelper and not the TagHelper used for non-component scenarios.

Now we can create a Tag Helper Component that targets this Tag Helper:

How To Logging with Microsoft.NET

How To Logging with Microsoft.NET

CheapASPNETHostingReview.com | Best and cheap ASP.NET Hosting. Through this article, we will explain in depth logging in .NET applications. We will explain this through two steps:

  1. Introduction to System.Diagnostics (prebuilt logging namespace in .NET)
  2. Introduction to Log4net

I. System.Diagnostics Namespace

The System.Diagnostics namespace provides classes that allow you to interact with system processes, event logs, and performance counters, Classes like EventLog which provides functionality to write to event logs, read event log entries, and create and delete event logs and event sources on the network. TraceSource which also provides a set of methods and properties that enable applications to trace the execution of code and associate trace messages with their source. In this paragraph, we will implement a tracing/Logging library based on the TraceSource Class. This library enable users to:

  • trace different scenarios inside applications [StartStopErrorInformationCriticalWarning]
  • The Trace destination is configurable, it can be a file, it can be a console application and it supports also sending Log Message by mail.

To do so, this logging utility contains:

  • Interface called Logger.cs
  • Interface called ILogger.cs
  • Enumeration called LogType which presents the destination of trace messages

The class that implements the interface ILogger.cs:

Now let’s see how to configure the library through the configuration file. The configuration file will determine:

  1. The name of the source
  2. The type of destination message [a text file, a console file, etc…]
  3. The trace option output, in our case, the output of any trace containing this message
    • The type of trace [information, Error, warning, etc…]
    • Date Time of the trace
    • Thread ID
    • Process ID
    • TimeStamp

Testing the library:

Console_Display

If we want to customize the destination of trace messages, for example, display the trace message in a file system, we just add a ‘TextWriterTraceListener‘ to the configuration file:

Displaying trace messages in Bloc Notes.

TextListener

  1. You can customize the tracing output’s target by adding or removing TraceListener instances to or from the collection stored in the TraceSource.Listeners property. By default, trace output is produced using an instance of the DefaultTraceListener class. The preceding configuration file example demonstrates removing the DefaultTraceListener and adding a TextWriterTraceListener/ConsoleTraceListener to produce the trace output for the trace source.

    As a Microsoft developer, I have always been more comfortable when implementing my own libraries based on .NET prebuilt namespaces because I want to have absolute control on my source code, but I have seen many projects using Logging with third party libraries, for example, Log4Net. In the next paragraph, we will learn how to integrate this library into our applications.

II. Logging with Log4NET

The Apache log4net library is a tool to help the programmer output log statements to a variety of output targets. Log4net is a port of the log4j framework to Microsoft.NET platform. To integrate this library, you must use nuget package manager.

3_-_Add_Log4net_through_nuget

Like the TraceSource class, Log4net library enables the developer to customize message tracing (changing the log destinations and the format of messages). We will write two scenarios:

  • Default Configuration [Console Configuration]

4-_Default_Log4Net_configuration

  • Using custom configuration [saving messages into a text file].

XML Configuration file

Displaying trace messages in Bloc Notes.

5-FileAppender

Summary

Log4net is a port of Log4j to the .NET universe, Log4j is a popular logging framework and that’s why log4net has rapidly grown. The class System.Diagnostics.TraceSource provides high performance logging and tracing for applications but both use nearly the same mechanism.

I hope that you appreciated my effort. Thank you for viewing my blog post, try to download the source code and do not hesitate to leave your questions.

ASP.NET Core Angular Visual Studio 2017 Templates

ASP.NET Core Angular Visual Studio 2017 Templates

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core hosting. The latest tooling in Visual Studio 2017 for .NET Core is pretty good. However, it seemed like built-in templates are a bit lacking. Fortunately, the dotnet sdk, and subsequently the CLI, have libraries available for various Single Page Application framework quick starts.

With the latest version of VS2017 installed, you should have the dotnet core SDK version 1.0.3 installed.

The “dotnet –info” command can be used to confirm SDK version.

ffa

To get started with “dotnet new” (new being the command to create new projects), the SPA templates for Angular and other various frameworks can be utilized after installing this package:

This will run for a bit and install various dependencies. After installation is complete, the available templates can be viewed by running “dotnet new” by itself.

ffa1

The template I’m interested in is the Angular one, of course. By using this template, you get a nice base starting point for an Angular application. Some of the niceties are having the build process already configured for bundling, minification, and various dependencies already configured.

ffa12

Webpack, TypeScript, and other things appear already configured when the project is opened in VS2017.

ffa121

Running the project for the first time can take a bit of time since all of the npm packages and such are pulled down. But, the template does have a few little niceties and is a fully working Angular project. The “Hello, world!” view has some nice information about the template and details some parts of the technology used in the template.

ffa1211

This is a pretty handy template. It supports SEO optimization and Server-side Rendering (SSR). The build process is completely handled by NPM, Webpack and .NET.

One caveat I ran into immediately was in the upgrade process. The template uses Angular 2.x. You can drop to a console and update to Angular 4.x like this:

However, that breaks the application/template entirely. That’s a bit concerning to me. I’d rather drop back to using my previous Angular 2.x template and update it to use VS2017 rather than dealing with a build process that is somewhat fragile.

It is possible to clone it, update the npm packages, run webpack, and have it working. I’m still playing around with it, but may have some code snippets to share soon. At some point, I’d like to have my plunker demos moved over to a standard template that can easily be deployed to Azure or another cloud hosting service.