Securing your ASP.NET MVC Application

Securing your ASP.NET MVC Application

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

as

How To Using Sessions and HttpContext in ASP.NET Core and MVC Core

How To Using Sessions and HttpContext in ASP.NET Core and MVC Core

CheapASPNETHostingReview.com | Best and cheap ASP.NET core 1.0 hosting. If you’re new to ASP.NET Core or MVC Core, you’ll find that sessions don’t work the way they used to. Here’s how to get up and running the new way.

Add Session NuGet Package

Add the Microsoft.AspNetCore.Session NuGet package to your project.

VERSION WARNING: As you’ll find with most Microsoft.* packages, you should make sure the versions all match. At RTM time as of writing, this means “1.0.0”.

Update startup.cs

Now that we have the Session nuget package installed, we can add sessions to the ASP.NET Core pipeline.

Open up startup.cs and add the AddSession() and AddDistributedMemoryCache() lines to the ConfigureServices(IServiceCollection services)

Next, we’ll tell ASP.NET Core to use a Memory Cache to store the session data. Add the UseSession() call below to the Configure(IApplicationBulider app, ...)

Where’s the Session variable gone?

Relax it’s still there, just not where you think it is. You can now find the session object by using HttpContext.Session. HttpContext is just the current HttpContext exposed to you by the Controller class.

If you’re not in a controller, you can still access the HttpContext by injecting IHttpContextAccessor.

Let’s go ahead and add sessions to our Home Controller:

You’ll see the Index() and About() methods making use of the Session object. It’s pretty easy here, just use one of the Set() methods to store your data and one of the Get() methods to retrieve it.

Just for fun, let’s inject the context into a random class:

Let’s break this down.

Firstly I’m setting up a private variable to hold the HttpContextAccessor. This is the way you get the HttpContext now.

Next I’m adding a convenience variable as a shortcut directly to the session. Notice the =>? That means we’re using an expression body, aka a shortcut to writing a one liner method that returns something.

Moving to the contructor you can see that I’m injecting the IHttpContextAccessor and assigning it to my private variable. If you’re not sure about this whole dependency injection thing, don’t worry, it’s not hard to get the hang of (especially constructor injection like I’m using here) and it will improve your code by forcing you to write it in a modular way.

But wait a minute, how do I store a complex object?

How do I store a complex object?

I’ve got you covered here too. Here’s a quick JSON storage extension to let you store complex objects nice and simple

Now you can store your complex objects like so:

and retrieve them just as easily:

Use a Redis or SQL Server Cache instead

Instead of using services.AddDistributedMemoryCache() which implements the default in-memory cache, you can use either of the following.

SQL Server
Firstly, install this nuget package:

  • "Microsoft.Extensions.Caching.SqlServer": "1.0.0"

Secondly, add the appropriate code snippet below:

Redis Cache
Unfortunately, the redis package does not support netcoreapp1.0 at the moment. You can still use this if you’re using net451 or higher.

"Microsoft.Extensions.Caching.Redis": "1.0.0"

Stay up to date

Even though we’ve reached RTM, you should still keep an eye on the ASP.NET Session Repository for any changes.

How To Creating and requesting SQL localized data in ASP.NET Core

How To Creating and requesting SQL localized data in ASP.NET Core

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core 1.0 hosting. This article shows how localized data can be created and used in a running ASP.NET Core application without restarting. The Localization.SqlLocalizer package is used to to get and localize the data, and also to save the resources to a database. Any database which is supported by Entity Framework Core can be used.

asp-dot-net-developer

Configuring the localization

The Localization.SqlLocalizer package is configured in the Startup class in the ConfigureServices method. In this example, a SQLite database is used to store and retrieve the data. The LocalizationModelContext DbContext needs to be configured for the SQL Localization. The LocalizationModelContext class is defined inside the Localization.SqlLocalizer package.

The AddSqlLocalization extension method is used to define the services and initial the SQL localization when required. The UseTypeFullNames options is set to true, so that the Full Type names are used to retrieve the localized data. The different supported cultures are also defined as required.

The UseRequestLocalization is used to define the localization in the Startup Configure method.

The database also needs to be created. This can be done using Entity Framework Core migrations.

Now the SQL Localization is ready to use.

Saving the localized data

The application creates products with localized data using the ShopAdmin API. A test method AddTestData is used to add dummy data to the database and call the provider logic. This will later be replaced by an Angular 2 form component in the third part of this series.

The ProductCudProvider uses the LocalizationModelContext, and the ProductCudProvider class to save the data to the database. The class creates the entities from the View model DTO and adds them to the database. Once saved the IStringExtendedLocalizerFactory interface method ResetCache is used to reset the cache of the localized data. The cache could also be reset for each Type if required.

Requesting the localized data

The Shop API is used to request the product data with the localized fields. The GetAvailableProducts method returns all products localized in the current culture.

The ProductRequestProvider is used to get the data from the database. Each product description and name are localized. The Localization data is retrieved from the database for the first request, and then read from the cache, unless the localization data was updated. The IStringLocalizer is used to localize the data.

The products with localized data can now be added and updated without restarting the application and using the standard ASP.NET Core localization.

How To Configure SQL Server Session State In ASP.NET Core

How To Configure SQL Server Session State In ASP.NET Core

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core hosting. Session is a feature in ASP.NET Core that enables us to save/store user data. Session stores the data in a dictionary on the Server and SessionId is used as a key. The SessionId is stored on the client at the cookie. The SessionId cookie is sent with every request. The SessionId cookie is Browser specific  and it cannot be shared among the Browsers. There is no timeout specified for SessionId cookie and they are deleted when the Browser session ends.

Session are of two types: InProc or In-memory and OutProc or Distributed session. If our session is in-memory and our Application is hosted on Web-Farm environment, we need to use sticky sessions to tie each session to a specific server. Whereas OutProc session does not require sticky sessions and they are the most preferred way to use session in our application.

Configure SQL Server session state

In SQL Server Session state, previous version of ASP.NET requires a number of tables and stored procedures to manage the storage of session in SQL server and this can be configured, using “aspnet_regsql” command or a tool. ASP.NET Core requires only one table. There are multiple ways to generate this storage table. The first is to use “Microsoft.Extensions.Caching.SqlConfig.Tools” tool. Before we run the commands of these tools, we need to install this tool. To install this tool, we need to add this tool in project.json and perform “dotnet restore” command.
Once this tool is installed for our project, we can execute “sql-cache” command, which generates the required table and an index. The command is in the format given below.
 Here, I am using SQL Express edition and following becomes full command, which generates the table and an index.

 cd

sas

Alternatively, we can create this table and an index manually. The script is given below to create a table and an index.

 SQL session state internally uses memory cache, so as to enable SQL Server session. We need to add “Microsoft.Extensions.Caching.SqlServer” dependency along with “Microsoft.AspNet.Session” into project.json file.

We can add a connection string to appSetting.json file or put it directly in ConfigureServices method of startup class. Following is the definition of ConfigureServices and Configure method of startup class.

Example

In the example given below, I have set my name into session in the first request and retrieved the session value in another request.

 ww

With SQL server state in ASP.NET Core, we can also create and use the session extension methods and we can also store complex objects in to the session.

Summary

This article described the steps required to enable SQL Server as a storage mechanism for session state in an ASP.NET Core MVC Application. The usage of SQL server session state is slightly different than the classic ASP.NET Application.

Using a Calculation Engine for .NET

Using a Calculation Engine for .NET

CheapASPNETHostingReview.com | Best and cheap ASP.NET hosting. “Creating a mathematical expression evaluator is one of the most interesting exercises in computer science, whatever the language used. This is the first step towards really understanding what sort of magic is hidden behind compilers and interpreters….“.

I agree completely, and hope that you do too.

Using the CalcEngine class

The CalcEngine class performs two main tasks:

  1. Parses strings that contain formulas into Expression objects that can be evaluated.
  2. Evaluates Expression objects and returns the value they represent.

To evaluate a string that represents a formula, you call the CalcEngine.Parse method to get an Expression, then call the Expression.Evaluate method to get the value. For example:

Function names are case-insensitive (as in Excel), and the parameters are themselves expressions. This allows the engine to calculate expressions such as “=ATAN(2+2, 4+4*SIN(4))”.

The CalcEngine class also provides a Functions property that returns a dictionary containing all the functions currently defined. This can be useful if you ever need to enumerate remove functions from the engine.

Notice how the method implementation listed above casts the expression parameters to the expected type (double). This works because the Expression class implements implicit converters to several types (string, double, bool, and DateTime). I find that the implicit converters allow me to write code that is concise and clear.

If you don’t like implicit converters, the alternative would be to override ToString in the Expression class and add ToDouble, ToDateTime, ToBoolean, etc.

Variables: Binding to simple values

Most calculation engines provide a way for you to define variables which can be used in expressions. The CalcEngine class implements a Variables dictionary that associates keys (variable names) and values (variable contents).

For example, the code below defines a variable named angle and calculates a short sine table:

Variables: Binding to CLR objects

In addition to simple values, the CalcEngine class implements a DataContext property that allows callers to connect a regular .NET object to the engine’s evaluation context. The engine uses Reflection to access the properties of the object so they can be used in expressions.

This approach is similar to the binding mechanism used in WPF and Silverlight, and is substantially more powerful than the simple value approach described in the previous section. However, it is also slower than using simple values as variables.

For example, if you wanted to perform calculations on an object of type Customer, you could do it like this:

CalcEngine supports binding to sub-properties and collections. The object assigned to the DataContext property can represent complex business objects and entire data models.

This approach makes it easier to integrate the calculation engine into the application, because the variables it uses are just plain old CLR objects. You don’t have to learn anything new in order to apply validation, notifications, serialization, etc.

Variables: Binding to dynamic objects

The original usage scenario for the calculation engine was an Excel-like application, so it had to be able to support cell range objects such as “A1” or “A1:B10”. This requires a different approach, since the cell ranges have to be parsed dynamically (it would not be practical to define a DataContext object with properties A1, A2, A3, etc).

To support this scenario, the CalcEngine implements a virtual method called GetExternalObject. Derived classes can override this method to parse identifiers and dynamically build objects that can be evaluated.

If the object returned implements the CalcEngine.IValueObject interface, the engine evaluates it by calling the IValueObject.GetValue method. Otherwise, the object itself is used as the value.

If the object returned implements the IEnumerable interface, then functions that take multiple values (such as Sum, Count, or Average) use the IEnumerable implementation to get all the values represented by the object.

For example, the sample application included with this article defines a DataGridCalcEngine class that derives from CalcEngine and overrides GetExternalObject to support Excel-style ranges. This is described in detail in a later section (“Adding Formula Support to the DataGridView Control”).

Optimizations

I mentioned earlier that the CalcEngine class performs two main functions: parsing and evaluating.

If you look at the CalcEngine code, you will notice that the parsing methods are written for speed, sometimes even at the expense of clarity. The GetToken method is especially critical, and has been through several rounds of profiling and tweaking.

For example, GetToken detects characters and digits using logical statements instead of the convenient char.IsAlpha or char.IsDigit methods. This does make a difference that shows up clearly in the benchmarks.

In addition to this, CalcEngine implements two other optimization techniques:

Expression caching

The parsing process typically consumes more time than the actual evaluation, so it makes sense to keep track of parsed expressions and avoid parsing them again, especially if the same expressions are likely to be used over and over again (as in spreadsheet cells or report fields, for example).

The CalcEngine class implements an expression cache that handles this automatically. The CalcEngine.Evaluate method looks up the expression in the cache before trying to parse it. The cache is based on WeakReference objects, so unused expressions eventually get removed from the cache by the .NET garbage collector. (This technique is also used in the NCalc library.)

Expression caching can be turned off by setting the CalcEngine.CacheExpressions property to false.

Expression optimization

After a string has been parsed, the resulting expression can sometimes be optimized by replacing parts of the expression that refer only to constant values. For example, consider the expression:

This expression contains several constants and functions of constants. It can be simplified to:

This second expression is equivalent to the first, but can be evaluated much faster.

Expression simplification was surprisingly easy to implement. It consists of a virtual Expression.Optimize method that is called immediately after an expression is parsed.

The base Expression class provides an Optimize method that does nothing:

This simply allows all derived classes that derive from Expression to implement their own optimization strategy.

For example, the BinaryExpression class implements the Optimize method as follows:

The method calls the Optimize method on each of the two operand expressions. If the resulting optimized expressions are both literal values, then the method calculates the result (which is a constant) and returns a literal expression that represents the result.

To illustrate further, function call expressions are optimized as follows:

First, all parameters are optimized. Next, if all optimized parameters are literals, the function call itself is replaced with a literal expression that represents the result.

Expression optimization reduces evaluation time at the expense of a slight increase in parse time. It can be turned off by setting the CalcEngine.OptimizeExpressions property to false.

Globalization

The CalcEngine class has a CultureInfo property that allows you to define how the engine should parse numbers and dates in expressions.

By default, the CalcEngine.CultureInfo property is set to CultureInfo.CurrentCulture, which causes it to use the settings selected by the user for parsing numbers and dates. In English systems, numbers and dates look like “123.456” and “12/31/2011”. In German or Spanish systems, numbers and dates look like “123,456” and “31/12/2011”. This is the behavior used by Microsoft Excel.

If you prefer to use expressions that look the same on all systems, you can set the CalcEngine.CultureInfo property to CultureInfo.InvariantCulture for example, or to whatever your favorite culture happens to be.

Sample: A DataGridView control with formula support

The sample included with this article shows how the CalcEngine class can be used to extend the standard Microsoft DataGridView control to support Excel-style formulas. The image at the start of the article shows the sample in action.

Note that the formula support described here is restricted to typing formulas into cells and evaluating them. The sample does not implement Excel’s more advanced features like automatic reference adjustment for clipboard operations, selection-style formula editing, reference coloring, and so on.

The DataGridCalcEngine class

The sample defines a DataGridCalcEngine class that extends CalcEngine with a reference to the grid that owns the engine. The grid is responsible for storing the cell values which are used in the calculations.

The DataGridCalcEngine class adds cell range support by overriding the CalcEngine.GetExternalObject method as follows:

The method analyzes the identifier passed in as a parameter. If the identifier can be parsed as a cell reference (e.g., “A1” or “AZ123:XC23”), then the method builds and returns a CellRangeReference object. If the identifier cannot be parsed as an expression, the method returns null.

The CellRangeReference class is implemented as follows:

The CellRangeReference class implements the IValueObject interface to return the value in the first cell in the range. It does this by calling the owner grid’s Evaluate method.

The CellRangeReference also implements the IEnumerable interface to return the value of all cells in the range. This allows the calculation engine to evaluate expressions such as “Sum(A1:B10)”.

Notice that the GetValue method listed above uses an _evaluating flag to keep track of ranges that are currently being evaluated. This allows the class to detect circular references, where cells contain formulas that reference the cell itself or other cells that depend on the original cell.

The DataGridCalc class

The sample also implements a DataGridCalc class that derives from DataGridView and adds a DataGridCalcEngine member.

To display formula results, the DataGridCalc class overrides the OnCellFormatting method as follows:

The method starts by retrieving the value stored in the cell. If the cell is not in edit mode, and the value is a string that starts with an equals sign, the method uses CalcEngine to evaluate the formula and assigns the result to the cell.

If the cell is in edit mode, then the editor displays the formula rather than the value. This allows users to edit the formulas by typing into in the cells, just like they do in Excel.

If the expression evaluation causes any errors, the error message is displayed in the cell.

At this point, the grid will evaluate expressions and show their results. But it does not track dependencies, so if you type a new value into cell “A1” for example, any formulas that use the value in “A1” will not be updated.

To address this, the DataGridCalc class overrides the OnCellEditEnded method to invalidate the control. This causes all visible cells to be repainted and automatically recalculated after any edits.

Let’s not forget that implementation of the Evaluate method used by the CellRangeReference class listed earlier. The method starts by retrieving the cell content. If the content is a string that starts with an equals sign, the method evaluates it and returns the result; otherwise it returns the content itself:

That is all there is to the DataGridCalc class. Notice that calculated values are never stored anywhere . All formulas are parsed and evaluated on demand.

The sample application creates a DataTable with 50 columns and 50 rows, and binds that table to the grid. The table stores the values and formulas typed by users.

The sample also implements an Excel-style formula bar across the top of the form that shows the current cell address, content, and has a context menu that shows the functions available and their parameters.

Finally, the sample has a status bar along the bottom that shows summary statistics for the current selection (Sum, Count, and Average, as in Excel 2010). The summary statistics are calculated using the grid’s CalcEngine as well.

Testing

I built some testing methods right into the CalcEngine class. In debug builds, these are called by the class constructor:

This ensures that tests are performed whenever the class is used (in debug mode), and that derived classes do not break any core functionality when they override the base class methods.

The Test method is implemented in a Tester.cs file that extends the CalcEngine using partial classes. All test methods are enclosed in an #if DEBUG/#endif block, so they are not included in release builds.

This mechanism worked well during development. It helped detect many subtle bugs that might have gone unnoticed if I had forgotten to run my unit tests when working on separate projects.

Benchmarks

While implementing the CalcEngine class, I used benchmarks to compare its size and performance with alternate libraries and make sure CalcEngine was doing a good job. A lot of the optimizations that went into the CalcEngine class came from these benchmarks.

I compared CalcEngine with two other similar libraries which seem to be among the best available. Both of these started as CodeProject articles and later moved to CodePlex:

  • NCalc: This is a really nice library, small, efficient, and feature-rich. I could not use NCalc in my Silverlight project because it relies on the ANTLR runtime DLL, which cannot be used in Silverlight projects (at least I couldn’t figure out how to do it).
  • Flee: Unlike CalcEngine and NCalc, Flee keeps track of formulas, their values, and dependencies. When a formula changes, Flee re-evaluates all cells that depend on it. One of the interesting features of Flee is that it actually compiles formulas into IL. This represents a trade-off since compilation is quite slow, but evaluation is extremely fast. I decided not to use Flee in my Silverlight project because it is relatively large and the parsing times were too long for the type of application I had in mind.

The benchmarking method was similar to the one described by Gary Beene in his 2007 Equation Parsers article. Each engine was tested for parsing and evaluating performance using three expressions. The total time spent was used to calculate a “Meps” (million expressions parsed or evaluated per second) index that represents the engine speed.

The expressions used were the following:

Where “a” and “b” are variables set to 2 and 4.

Each engine parsed and evaluated the expressions 500,000 times. The times were added and used to calculate the “Meps” index by dividing the number of repetitions by the time consumed. The results were as follows:

Time in seconds Speeds in “Meps”
Library Parse Evaluate Parse Evaluate
CalcEngine 1.4 1.3 1.04 1.18
NCalc 7.1 5.7 0.21 0.26
Flee 1,283.0 0.5 0.00 2.91
CalcEngine* 10.7 1.5 0.14 0.99
NCalc* 145.2 5.7 0.01 0.27

speed

Some comments about the benchmark results:

  • CalcEngine performed well, being the fastest parser and the second fastest evaluator (after Flee).
  • Flee is literally “off the charts” on both counts, almost 900 times slower parsing and 2.5 times faster evaluating than CalcEngine. Because Flee compiles formulas to IL, I expected slow parsing and fast evaluation, but the magnitude of the difference was surprising.
  • Entries marked with asterisks were performed with optimizations off. They are included to demonstrate the impact of the optimization options.

In addition to speed, size is important, especially for Silverlight applications that need to be downloaded to the client machine. Here is a comparison of library sizes:

Library Size (kB)
CalcEngine 26
NCalc 188
Flee 202

size

CalcEngine is the smallest library by far, more than seven times smaller than NCalc. If necessary, it could be trimmed even further by removing some of the less important built-in functions.

Conclusion

The CalcEngine class is compact, fast, extensible, and multi-platform. I think it is different enough from NCalc and Flee to add value for many types of projects, especially Silverlight applications like the one it was created for. You can see the Silverlight app in action in the image below.

excelBookDemo

I hope others will find CalcEngine useful and interesting as well.

How To Creating an ASP.NET Core 1.1 VS 2017 with Docker application

How To Creating an ASP.NET Core 1.1 VS 2017 with Docker application

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core 1.1 hosting. This blog shows how to setup a basic ASP.NET Core 1.1 application using Visual studio 2017 and Docker.

docker11

Now the application needs to be updated to ASP.NET Core 1.1. Open the csproj file and update the PackageReference and also the TargetFramework to the 1.1 packages and target. At present, there is no help when updating the packages, like the project.json file had, so you need to know exactly what packages to use when updating directly.

Then update the docker-compose.ci.build.yml file. You need to select the required image which can be found on Docker Hub. The microsoft/aspnetcore-build:1.1.0-msbuild image is used here.
Now update the DockerFile to target the 1.1.0 version.
Start the application using Docker. You can debug the application which is running inside Docker, all in Visual Studio 2017. Very neat.

vs2017_docker_basic_1

Notes:

When setting up Docker, you need to share the C drive in Docker.

How to Structure The Application in ASP.NET MVC Areas

How to Structure The Application in ASP.NET MVC Areas

CheapASPNETHostingReview.com | Best and cheap ASP.NET MVC hosting. This week I discovered a difficulty related to structuring an ASP.NET MVC web applications one advancement crew was dealing with. The things they have been trying to do was quite straightforward: to create a folder framework each having their particular subfolders for View/Controller/Scripts/CSS and so on. The appliance assets like JS/CSS etc. were not getting rendered properly. The difficulty was owing to NET.config file lying underneath the subfolder, which when moved to the Views folder below that subfolder things went good. The purpose of this post just isn’t to debate regarding the specifics of that difficulty and it is solution.But to discuss regarding how we will very easily framework our ASP.NET MVC Web application as per distinct modules, which is an clear need for just about any big application.

ASP.NET MVC follows the paradigm of “Convention Over Configuration” and default folder structure and naming conventions operates good to get a smaller sized software. But for relatively bigger a single there is a necessity to customise.The framework also offers adequate provisions for the same.You’ll be able to have your personal controller manufacturing facility to get custom methods to making the controller classes and custom see engine for finding the rendering the sights. But when the necessity would be to structure the applying to distinct subfolders as per modules or subsites I believe using “Area” in ASP.NET MVC will likely be useful to make a streamlined software.

You can add a area to some ASP.NET MVC undertaking in Visual Studio as shown beneath.

aspm

as1

Here I have added an area named “Sales”. As shown in the figure below a folder named “Areas” is created with a subfolder “Sales”. Under “Sales” we can see the following

  • The standard folder of Models/Views/Controllers
    • A Web.config under the Views folder. This contains the necessary entries for the RazorViewEngine to function properly
  • A class named SalesAreaRegistration.

res

The code (auto generated) for the SalesAreaRegistration class is shown below:

 System.Web.Mvc.AreaRegistration may be the summary base class use registering the places to the ASP.NET MVC Web Application. The method void RegisterArea(AreaRegistrationContext context) must be overriden to sign up the realm by providing the route mappings. The class System.Web.Mvc.AreaRegistrationContext encapsulates the mandatory information (like Routes) required to sign-up the area.

In Global.asax.cs Application_Start occasion we must RegisterAllAreas() technique as demonstrated under:

 The RegisterAllAreas method looks for all types deriving from AreaRegistration and invokes their RegisterArea method to register the Areas.

Now with the necessary infrastructure code in place I have added a HomeController and Index page for the “Sales” area as shown below.

e

I have to change the Route Registration for the HomeController to avoid conflicts and provide the namespace information as shown below:

 Now I will add a link to the Sales area by modifying the _Layout.cshtml as shown below:

Here I am navigating to the area “Sales” from the main application so I have to provide area information with routeValues. The following overload is being used in the code above:

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes);

About Bundling and Minification in ASP.NET Core

About Bundling and Minification in ASP.NET Core

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core 1.0 hosting. This post is about Bundling and Minification in ASP.NET Core. Bundling and minification are two techniques you can use in ASP.NET to improve page load performance for your web application. Bundling combines multiple files into a single file. Minification performs a variety of different code optimizations to scripts and CSS, which results in smaller payloads. In ASP.NET Core RTM release Microsoft introduced “BundlerMinifier.Core” tool which will help you to bundle and minimize Javascript and style sheet files. Unlike previous versions MVC, the bundling and minification is happening on development time not in runtime. To use “BundlerMinifier.Core” first you need to add reference of BundlerMinifier.Core in the project.json tools section.

Now you need to specify the Javascript and stylesheet files for bundling and minification. You can do this by adding “bundleconfig.json” file. The name can be changed, but if the filename is bundleconfig.json, it will bundle command will take it automatically. Here is a minimal bundleconfig.json file.

The file is self explantory, you can specify multiple file in the inputFiles element, which will be combined and minified based on the minify element. Now you can combine and minify using “dotnet bundle” command. Here is the output when I run the dotnet bundle command on my MVC project.

bundle_minification_running

You can integrate it to the development lifecycle by adding the dotnet build command in the “precompile” script section in project.json file. If you are using Yo ASP.NET generator, the project template will be using precompile script section in project.json.

There are few more commands also available with dotnet bundle tool.

  • dotnet bundle clean – Executing dotnet bundle clean will delete all output files from disk.
  • dotnet bundle watch – To automatically run the bundler when input files change, call dotnet bundle watch. This will monitor any file changes to input files in the working directory and execute the bundler automatically.
  • dotnet bundle help – Get help on how to use the CLI.

Happy Programming :)

Claim NOW Big Promotion From ASPHostPortal.com

How To Validation Bootstrap in ASP.NET MVC

How To Validation Bootstrap in ASP.NET MVC

CheapASPNETHostingReview.com | Best and cheap ASP.NET MVC hosting. In this tutorial I will show you about bootstrap in ASP.NET MVC. I use Bootstrap in almost every project I build these days. I build up a custom Bootstrap configuration to reduce bloat, and have my workflow down-pat for updating those configurations (which I’ll write about in the near future). I have familiarised myself with it’s ins-and-outs to help ensure I use it to it’s full potential without being overkill, and it has sped up my HTML build time immensely.

Bootstrap Validation in ASP.NET MVC

One issue I’ve come across before is finding harmony between ASP.Net MVC’s validation and Bootstrap’s validation classes.

Out of the box when you use Html.ValidationMessageFor() to output a validation (with none of Microsoft’s validation classes set up), this is what I end up with:

form-vanilla-validation

Behind the scenes, the Microsoft validation has put an input-validation-error class on the text boxes that failed validation, and the validation message has some classes that can be styled:

Bootstrap’s method of validation styling is based on the parent’s class (the “form group”), instead of the element itself, thus allowing all children (e.g. labels and text boxes) to have a specific style:

 It’s not difficult to apply the Bootstrap validation classes when model errors exist using a little JavaScript, but I decided to look for a nice NuGet package to do this for me, and I found one – jquery.validate.unobtrusive.bootstrap by Sandro Caseiro.  Simply install it via the NuGet Package Manager Console:

 I use the bundling in the Microsoft.AspNet.Web.Optimization package, so rather than including the JavaScript library file raw in my view, I already have a validate bundle that will include it since this library has followed the naming convention, being jquery.validate.unobtrusive.bootstrap.js, so I don’t even need to update the BundleConfig.cs file:

 This bundle was already being included in my page using the following:

 Unfortunately this didn’t work! The jquery.validate.unobtrusive.bootstrap.js was being included, but when I look at the source, it’s being included BEFORE the jquery.validate.unobtrusive.js file:

The problem is that out of the box, the bundling library orders the packages included in the bundle alphabetically when using a wildcard *.

I saw a nice solution to this on someone’s the jquery.validate.unobtrusive.bootstrap GitHub issues page, it involves creating a custom orderer for the bundle:

Step 1: Create a new orderer class (I placed it within the BundleConfig class to keep it local):

 Step 2: Update the bundle creation code to use this orderer:

 The result is that your scripts will be output in order of the “dots” – a kind of heirarchy assumed based on the file naming convention, which works in this particular situation, at least (and it would be great if it worked in general, signifying a naming convention for JavaScript files):

 And the result is a lovely looking form, utilising Bootstrap validation styling:

form-bootstrap-validation

How to Set Up Angular 2 and TypeScript in a ASP.NET Core Project Using Visual Studio

How to Set Up Angular 2 and TypeScript in a ASP.NET Core Project Using Visual Studio

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core hosting. There are two ways to set up an Angular 2 application. The most preferred way is to use angular-cli, which is pretty simple. Unfortunately, the Angular CLI doesn’t use the latest version. The other way is to follow the tutorial on angular.io, which sets up a basic starting point, but this needs a lot of manual steps.

maxresdefault

There are also two ways to set up the way you want to develop your app with ASP.NET Core. One way is to separate the client app completely from the server part. It is pretty useful to decouple the server and the client to create almost independent applications and to host on different machines. The other way is to host the client app inside the server app. This is useful for small applications, having everything in one place, and it is easy to deploy on a single server.

In this post, I’m going to show you, how you can set up an Angular 2 app, which will be hosted inside an ASP.NET Core application using Visual Studio 2015. The Angular-CLI is not the right choice here because it already sets up a development environment for you and all that stuff is configured a little bit differently. The effort to move this to Visual Studio would be too much. I will almost follow the tutorial on http://angular.io/. But we need to change some small things to get that stuff working in Visual Studio 2015.

Configure the ASP.NET Core Project

Let’s start with a new ASP.NET Core project based on .NET Core. (The name doesn’t matter, so “WebApplication391” is fine). We need to choose a Web API project because the client side Angular 2 App will probably communicate with that API and we don’t need all the predefined MVC stuff.

A Web API project can’t serve static files like JavaScripts, CSS styles, images, or even HTML files. Therefore we need to add a reference to Microsoft.AspNetCore.StaticFiles in the project.json:

And in the startup.cs, we need to add the following line, just before the call of `UseMvc().

Another important thing we need to do in the startup.cs is to support the Routing of Angular 2. If the Browser calls a URL that doesn’t exist on the server, it could be an Angular route. Especially if the URL doesn’t contain a file extension.

This means we need to handle the 404 error, which will occur in such cases. We need to serve the index.html to the client if there was an 404 error on requests without extensions. To do this we just need a simple lambda based MiddleWare, just before we call UseStaticFiles():

Inside the properties folder, we’ll find a file called launchSettings.json. This file is used to configure the behavior of Visual Studio 2015, when we press F5 to run the application. Remove all strings “api/values” from this file, because Visual Studio will always call that specific Web API every time you press F5.

Now we prepared the ASP.NET Core application to start to follow the angular.io tutorial.

Let’s start with the NodeJS packages. Using Visual Studio we can create a new “npm Configuration file” called package.json. Just copy the stuff from the tutorial:

In this listing, I changed a few things:

  • I added “&& gulp restore” to the postinstall script.
  • I also added Gulp to the devDependency to typings.

After the file is saved, Visual Studio tries to load all the packages. This works, but VS shows a yellow exclamation point for errors. Until recently, I didn’t figure out what was going wrong here. To be sure all packages are propery installed, use the console, change directory to the current project, and type npm install

The post install will possibly fail because gulp is not yet configured. We need gulp to copy the dependencies to the right location inside the wwwroot folder, because static files will only be loaded from that location. This is not part of the tutorial on angular.io, but is needed to fit the client stuff into Visual Studio. Using Visual Studio we need to create a new “gulp Configuration file” with the name gulpfile.js:

The task restore copies all the needed files to the Folder ./wwwroot/libs

TypeScript needs some type definitions to get the types and API definitions of the libraries, which are not written in TypeScript or not available in TypeScript. To load this, we use another tool, called “typings.” This is already installed with NPM. This tool is a package manager for type definition files. We need to configure this tool with a typings.config

Now we have to configure TypeScript itself. We can also add a new item, using Visual Studio to create a TypeScript configuration file. I would suggest not to use the default content, but rather the contents from the angular.io tutorial.

The only things I did with this file were to add the “compileOnSave” flag and to exclude the “node_modules” folder from the TypeScript build, because we don’t need to build containing the TypeScript files and because we moved the needed JavaScript to ./wwwroot/libs.

If you use Git or any other source code repository, you should ignore the files generated out of our TypeScript files. In the case of Git, I simply add another .gitignore to the ./wwwroot/app folder.

We do this because the JavaScript files are only relevant to run the application and should be created automatically in the development environment or on a build server, before deploying the app.

The First App

That is all we need to prepare an ASP.NET Core project in Visual Studio 2015. Let’s start to create the Angular app. The first step is to create an index.html in the folder wwwroot:

As you can see, we load almost all JavaScript files from the libs folder. Except a systemjs.config.js. This file is needed to configure Angular2, to define which module is needed, where to find dependencies, and so on. Create a new JavaScript file, call it systemjs.config.js, and paste the following content into it:

This file also defines a main entry point which is a main.js. This file is the transpiled TypeScript file main.ts we need to create in the next step. The main.ts bootstraps our Angular 2 app:

We also need to create our first Angular2 component. Create a TypeScript file with the name app.component.ts inside the app folder:

Conclusion

I propose to use Visual Studio just for small single-page applications because it gets slower the more dynamic files need to be handled. ASP.NET Core is pretty cool to handle dynamically generated files, but Visual Studio still is not. VS tries to track and manage all the files inside the project, which slows down a lot. One solution is to disable source control in Visual Studio and use an external tool to manage the sources.

Another — even better — solution is not to use Visual Studio for front-end development. In a new project, I propose to separate front-end and back-end development and to use Visual Studio Code for the front-end development or even both. You need to learn a few things about NPM and Gulp, and you need to use a console in this case, but web development will be a lot faster and a lot more lightweight with this approach.