JavaScript and ASP.NET MVC Framework Features

In this article I want to share digest of good articles about Java script and ASP.NET MVC Framework. With help of Asp.net MVC Guru articles I will explain an approach to creating JavaScript unit tests that can be easily integrated with Visual Studio and Visual Studio ALM. Also how we can make Microsoft Script Control to execute JavaScript on the server. Article describes how to prevent java script injections attack and how to avoid it. By taking advantage of the Microsoft Script Control, we were able to execute our JavaScript unit tests side-by-side with all of our other unit tests and view the results in the standard Visual Studio Test Results window. ASP.NET MVC Framework need additional support of Java Scripts because a lot of concerns and problems with it that is why this article can be helpful for you.

JavaScript Unit Tests with Visual Studio
Modern ASP.NET web applications take full advantage of client-side JavaScript to provide better interactivity and responsiveness. If you are building an ASP.NET application in the right way, you quickly end up with lots and lots of JavaScript code. There is no shortage of unit testing frameworks for JavaScript. Each of the major JavaScript libraries has its own unit testing framework. For example, jQuery has QUnit, Prototype has UnitTestJS, YUI has YUI Test, and Dojo has Dojo Objective Harness (DOH). Also very good approach to test web sites is Selenium – Selenium is a very powerful framework for automating browser tests. You can create your tests by recording a Firefox session or by writing the test driver code in server code such as C#. You can learn more about Selenium at http://seleniumhq.org/.

Using Server-Side JavaScript for JavaScript Unit Tests

A completely different approach to executing JavaScript unit tests is to perform the tests outside of any browser. If you really want to test JavaScript then you should test JavaScript and leave the browser out of the testing process.

There are several ways that you can execute JavaScript on the server outside the context of any browser:

  • Rhino – Rhino is an implementation of JavaScript written in Java. The Rhino project is maintained by the Mozilla project. Learn more about Rhino at http://www.mozilla.org/rhino/
  • V8 – V8 is the open-source Google JavaScript engine written in C++. This is the JavaScript engine used by the Chrome web browser. You can download V8 and embed it in your project by visiting http://code.google.com/p/v8/
  • JScript – JScript is the JavaScript Script Engine used by Internet Explorer (up to but not including Internet Explorer 9), Windows Script Host, and Active Server Pages.

Internet Explorer is still the most popular web browser. Therefore, I decided to focus on using the JScript Script Engine to execute JavaScript unit tests.

Using the Microsoft Script Control

There are two basic ways that you can pass JavaScript to the JScript Script Engine and execute the code: use the Microsoft Windows Script Interfaces or use the Microsoft Script Control.

The difficult and proper way to execute JavaScript using the JScript Script Engine is to use the Microsoft Windows Script Interfaces. You can learn more about the Script Interfaces by visiting http://msdn.microsoft.com/en-us/library/t9d4xf28(VS.85).aspx

The main disadvantage of using the Script Interfaces is that they are difficult to use from .NET. There is a great series of articles on using the Script Interfaces from C# located at http://www.drdobbs.com/184406028.

I picked the easier alternative and used the Microsoft Script Control. The Microsoft Script Control is an ActiveX control that provides a higher level abstraction over the Window Script Interfaces.

You can download the Microsoft Script Control from here:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=d7e31492-2595-49e6-8c02-1426fec693ac

After you download the Microsoft Script Control, you need to add a reference to it to your project. Select the Visual Studio menu option Project, Add Reference to open the Add Reference dialog. Select the COM tab and add the Microsoft Script Control 1.0.

JavaScript and ASP.NET MVC Framework Features

Using the Script Control is easy. You call the Script Control AddCode() method to add JavaScript code to the Script Engine. Next, you call the Script Control Run() method to run a particular JavaScript function. The reference documentation for the Microsoft Script Control is located at the MSDN website: http://msdn.microsoft.com/en-us/library/aa227633%28v=vs.60%29.aspx The difference between a Basic Unit Test and a Unit Test is that a Unit Test includes a Test Context. We need this Test Context to use the JavaScriptTestHelper class that we created earlier.

Enter the following test method for the new unit test:

 

[TestMethod]
public void TestAddNumbers() {
var jsHelper = new JavaScriptTestHelper(this.TestContext);

// Load JavaScript files
jsHelper.LoadFile("JavaScriptUnitTestFramework.js");
jsHelper.LoadFile(@"..\..\..\MvcApplication1\Scripts\Math.js");
jsHelper.LoadFile("MathTest.js");

// Execute JavaScript Test
jsHelper.ExecuteTest("testAddNumbers");
}

 

Running the Visual Studio JavaScript Unit Test

After you complete all of the steps described above, you can execute the JavaScript unit test just like any other unit test. You can use the keyboard combination CTRL-R, CTRL-A to run all of the tests in the current Visual Studio Solution. Alternatively, you can use the buttons in the Visual Studio toolbar to run the tests:

JavaScript and ASP.NET MVC Framework Features

(Unfortunately, the Run All Impacted Tests button won’t work correctly because Visual Studio won’t detect that your JavaScript code has changed. Therefore, you should use either the Run Tests in Current Context or Run All Tests in Solution options instead.)

ASP.NET JavaScript Routing for ASP.NET MVC–Constraints

If you haven’t had a look at my previous post about ASP.NET routing, go ahead and check it out before you read this post: http://weblogs.asp.net/zowens/archive/2010/12/20/asp-net-mvc-javascript-routing.aspx And the code is here: https://github.com/zowens/ASP.NET-MVC-JavaScript-Routing Anyways, this post is about routing constraints. A routing constraint is essentially a way for the routing engine to filter out route patterns based on the day from the URL. For example, if I have a route where all the parameters are required, I could use a constraint on the required parameters to say that the parameter is non-empty. Here’s what the constraint would look like:

JavaScript and ASP.NET MVC Framework Features

Notice that this is a class that inherits from IRouteConstraint, which is an interface provided by System.Web.Routing. The match method returns true if the value is a match (and can be further processed by the routing rules) or false if it does not match (and the route will be matched further along the route collection).

Because routing constraints are so essential to the route matching process, it was important that they be part of my JavaScript routing engine. But the problem is that we need to somehow represent the constraint in JavaScript. I made a design decision early on that you MUST put this constraint into JavaScript to match a route. I didn’t want to have server interaction for the URL generation, like I’ve seen in so many applications. While this is easy to maintain, it causes maintenance issues in my opinion.

So the way constraints work in JavaScript is that the constraint as an object type definition is set on the route manager. When a route is created, a new instance of the constraint is created with the specific parameter. In its current form the constraint function MUST return a function that takes the route data and will return true or false. You will see the NotEmpty constraint in a bit.

Another piece to the puzzle is that you can have the JavaScript exist as a string in your application that is pulled in when the routing JavaScript code is generated. There is a simple interface, IJavaScriptAddition, that I have added that will be used to output custom JavaScript. Let’s put it all together. Here is the NotEmpty constraint. Here’s how you would use the NotEmpty constraint in C# and it will work with the JavaScript routing generator.

JavaScript and ASP.NET MVC Framework Features

The only catch to using route constraints currently is that the following is not supported:

JavaScript and ASP.NET MVC Framework Features

The constraint will work in C# but is not supported by my JavaScript routing engine.

JavaScript and ASP.NET MVC Framework Features

There’s a few things at work here. The constraint is called “notEmpty” in JavaScript. When you add the constraint to a parameter in your C# code, the route manager generator will look for the JsConstraint attribute to look for the name of the constraint type name and fallback to the class name. For example, if I didn’t apply the “JsConstraint” attribute, the constraint would be called “NotEmpty”. The JavaScript code essentially adds a function to the “constraintTypeDefs” object on the “notEmpty” property (this is how constraints are added to routes). The function returns another function that will be invoked with routing data.

Preventing JavaScript Injection Attacks

The goal of this tutorial is to explain how you can prevent JavaScript injection attacks in your ASP.NET MVC applications. This tutorial discusses two approaches to defending your website against a JavaScript injection attack. You learn how to prevent JavaScript injection attacks by encoding the data that you display. You also learn how to prevent JavaScript injection attacks by encoding the data that you accept.

What is a JavaScript Injection Attack?

Whenever you accept user input and redisplay the user input, you open your website to JavaScript injection attacks. Let’s examine a concrete application that is open to JavaScript injection attacks.

Imagine that you have created a customer feedback website (see Figure 1). Customers can visit the website and enter feedback on their experience using your products. When a customer submits their feedback, the feedback is redisplayed on the feedback page.

Preventing JavaScript Injection Attacks The goal of this tutorial is to explain how you can prevent JavaScript injection attacks in your ASP.NET MVC applications. This tutorial discusses two approaches to defending your website against a JavaScript injection attack. You learn how to prevent JavaScript injection attacks by encoding the data that you display.

You also learn how to prevent JavaScript injection attacks by encoding the data that you accept. What is a JavaScript Injection Attack? Whenever you accept user input and redisplay the user input, you open your website to JavaScript injection attacks. Let’s examine a concrete application that is open to JavaScript injection attacks. Imagine that you have created a customer feedback website. Customers can visit the website and enter feedback on their experience using your products. When a customer submits their feedback, the feedback is redisplayed on the feedback page.

The danger is a little more acute in the case of an ASP.NET MVC application. In an ASP.NET Web Forms application, unlike an ASP.NET MVC application, you can rely on a feature called Request Validation. Request Validation detects whether form data submitted from a page contains dangerous looking text. If you submit form data that contains, for example, angle brackets then an exception is thrown. Be aware that ASP.NET MVC does not use Request Validation. You have complete and total responsibility for preventing JavaScript injection attacks in an ASP.NET MVC application.

This tutorial discussed two approaches for defending your ASP.NET MVC applications against JavaScript injection attacks: you can either HTML encode user submitted data in the view or you can HTML encode user submitted data in the controller. Preventing JavaScript injection attacks is simple. Make sure that you call Html.Encode() whenever you display text retrieved from a user in a view. For example, here’s the portion of the Index view that displays the customer feedback:

 <h1>Customer Feedback</h1>
 <ul>
 <% foreach (Survey survey in ViewData.Model)
 { %>
 <li>
 <%= survey.EntryDate.ToShortDateString() %>
 &mdash;
 <%= survey.Feedback %>
 </li>
 <% } %>
 </ul>

This code contains a loop that iterates through Survey entities. The values of the Feedback and EntryDate properties are displayed for each Survey entity. In order to prevent JavaScript injection attacks, you need to use the Html.Encode() helper method. Here’s the right way to code the loop:

 <h1>Customer Feedback</h1>
 <ul>
 <% foreach (Survey survey in ViewData.Model)
 { %>
 <li>
 <%= survey.EntryDate.ToShortDateString() %>
 &mdash;
 <%= Html.Encode(survey.Feedback) %>
 </li>
 <% } %>
 </ul>

References

Asp-net-javascript-routing-for-asp-net-mvc-constraints

Integrating JavaScript Unit Tests with Visual Studio

http://StephenWalther.com/downloads/Blog/JavaScriptUnitTesting/JavaScriptUnitTests.zip

Before running this code, you need to first install the Microsoft Script Control which you can download from here - http://www.microsoft.com/downloads/en/details.aspx?FamilyID=d7e31492-2595-49e6-8c02-1426fec693ac

Java script injection attacks

Injection of java script attack

Summary

This article is like collection of good article ideas in one place. You could find more information in links above in References section. Java script and ASP.NET MVC powerful feature, you could make your application like a safe place to users, test this application JavaScript code and make configuration on constraints and run additional validation on your routes.

Java Script and ASP.NET MVC

Comments (7) -

  • Your blog provides us a very great information. Its really very helpful to me to find result on search engine. Hope to hear more good information related to searching from your side.
  • Thank you for this great information, you write very well which i like very much. I really impressed by your post.
  • This article describe only few practices about JavaScript and ASP.NET MVC Framework Features, you could add more in comments and I will update it.
  • Hi, I appreciate the information that you have provided in the post. It is worth noting and I really liked the presentation as well. I will surely come back for more of intersting posts.
  • Thank you very much for the info.  What theme is this i really like it wish you would share with me where you got it if you can send me answer to email provided.
  • Excellent Blog. I really want to admire the quality of this post. I like the way of your presenting ideas, views and valuable content. No doubt you are doing great work.

Add comment

Loading