Related Topics: Microsoft Cloud, Java IoT, Machine Learning

Microsoft Cloud: Article

Behind the Scenes of ASP.NET MVC 2

Understand the internals to build better apps

With Visual Studio 2010, Microsoft is shipping the next version of the popular ASP.NET MVC Framework with its IDE. A year ago I blogged about my findings when getting my hands on the first version of ASP.NET MVC. The MVC Framework provides really nice features that make it very easy to build web applications on top of ASP.NET. The updated support in Visual Studio also makes it very appealing to choose MVC instead of traditional ASP.NET.

The most important thing about using any framework is to understand its internals. Without that knowledge you easily run into the problem of using the framework in an unintended way resulting in problems down the road that might be hard or impossible to fix. Therefore I am going to start a series of articles, analyzing the internals of ASP.NET MVC 2 with the intention to educate us all about what is going on behind the scenes in order to build better applications – sounds like a plan? :-)

There are two key takeaways in this article that hopefully make you decide to read to the very end:
a) Enable Client Side Validation to reduce network roundtrips
b) Make sure you deploy your app without any debug switches on

Create a New ASP.NET MVC 2 Application
First of all you need Visual Studio 2010. It seems Microsoft offers it in a Trial version on their Visual Studio MSDN Page. Once you have it installed go ahead and create a new ASP.NET MVC 2 Application:

Create a new ASP.NET MVC 2 Project in Visual Studio 2010

Create a new ASP.NET MVC 2 Project in Visual Studio 2010

The project wizard will prompt you whether to create Unit Tests for your MVC Controller classes. Great to see that testing is really taken more seriously and that Visual Studio supports us with ensuring good test coverage :-)

The template project comes with two controllers (Home and Account) and also implements a membership service to deal with users that can logon to our site. The database used to store the account information is configured in the web.config file. By default the AspNetSqlMembershipProvider is used that stores information in a SQL Express Database. One new thing in VS2010 is that besides having one web.config file you can have a web.config.debug and web.config.release file. These configuration-specific files allow you to run transformations on the original web.config file to e.g.: get rid of debug settings.

Basically we are ready to go and launch the application – just Hit F5. You will notice that Visual Studio – when launching a Web Application from within the IDE – will use a standalone Development Web Server (WebDev.WebServer40.exe). The Web Server adds an icon to the system tray, and from there allows you to browse to the main page or simply stop the web server at any time.

Exploring the Application – Walking through a simple scenario
Before I start exploring the application I need to get my tools up and running to look behind the scenes. First of all I use the FREE dynaTrace AJAX Edition to see what is going on in the browser. If you are new to the AJAX Edition I recommend reading my Getting Started Blog. Microsoft has really improved its JavaScript/AJAX Libraries. They ship jQuery and also have their own AJAX Libraries for building Web 2.0 Applications. Therefore it is essential to use tools such as the AJAX Edition (for Internet Explorer), FireBug (for FireFox) or SpeedTracer (for Chrome) to analyze what is going in the browser.

The second thing I need to analyze Server-Side activity is a tool that allows me to trace the executed .NET code while I browse through the web site. I am using dynaTrace with the ASP.NET MVC FastPack that gives me all I need to get a Quick Start on analyzing everything going on within my application. I also use the dynaTrace Visual Studio 2010 Add-In that eliminates some configuration steps when launching an application from Visual Studio. Now let’s get started.

Step 1: Launch the Application
Either launch it in debug mode or – like in my case – launch it with dynaTrace support:

Launch the ASP.NET MVC Application using the dynaTrace Launcher

Launch the ASP.NET MVC Application using the dynaTrace Launcher

After the application is launched we see the ASP.NET Development Server in the tray icon. The details show us which web site is hosted on which port:

My ASP.NET MVC 2 Application hosted in the Web Development Server

My ASP.NET MVC 2 Application hosted in the Web Development Server

Visual Studio also opens a browser and opens the URL that hosts our application. As I also want to use the dynaTrace AJAX Edition to analyze browser activity such as Network Requests, JavaScript, AJAX(XHR) or Rendering I click on the dynaTrace Icon in the AJAX Edition Toolbar in Internet Explorer:

Connect the browser to the dynaTrace AJAX Edition to capture  browser activity such as JavaScript, Network, Rendering, ...

Connect the browser to the dynaTrace AJAX Edition to capture browser activity such as JavaScript, Network, Rendering, ...

Step 2 – Walking through a Use Case Scenario
Alright – let’s walk through the following use-case scenario to test the user management feature of the out-of-the-box implementation of our ASP.NET MVC 2 Application. I click on [Log On]. I enter a bogus user name password combination to test whether I cannot just logon. Yeah – seems I cannot logon as I get the message that my login was unsuccessful with the provided username and password. Let’s click on Register to register a new account. In my first attempt I enter a too-short password then a non matching password and confirm password. The App shows me errors -> just as expected. I try it again with correct input values – voila – works :-) . I finish my use case by clicking on Home, About and then [Log Off].

Analyzing the Browser Activities – ENABLE Client-Side Validation to improve performance
I assumed that checking for the password length (minimum of 6 characters) and checking for matching password and confirm password would all be done in the browser using JavaScript. Looking at the browser activities captured by the AJAX Edition shows me that by default there is NO JavaScript at all on that web-site. All register form data is sent to the server and the server does all the validation. I can tell that by looking at the JavaScript column on the Summary View in the AJAX Edition:

AJAX Summary View shows that we have NO JavaScript activity at  all

AJAX Summary View shows that we have NO JavaScript activity at all

Good thing that MVC makes it easy to enable client-side validation. Scott Guthrie has a nice blog article explaining Model Validation in ASP.NET MVC. Check out Step 3 in his blog and learn how to enable Client-Side Validation. I made the necessary changes to my register.aspx page and also added additional verification data to my RegisterModel class, e.g: to verify the correct format of the entered email address. Let’s see what the difference is now. The AJAX Edition shows me that my register.aspx page has some new inline JavaScript code that contains all my validation rules. These rules register a propertychange handler and verify the input of the text fields whenever I change the value of the input field. In case I violate the verification rule a status message gets displayed next to the input field. The following screenshot shows how this looks like for the end-user when entering a wrong email address:

Client-Side Validation eliminates unnecessary roundtrips to the  server

Client-Side Validation eliminates unnecessary roundtrips to the server

The AJAX Edition gives me insight into the actual JavaScript that gets executed on the propertychange event of the email field:

MvcValidation Library verifies the email input value against the  validation pattern

MvcValidation Library verifies the email input value against the validation pattern

The key takeaway here is to make use of the client-side validation feature. It results in a more interactive user interface, reduces round-trips to the server, and therefore frees resources on the server for more important work.

Analyzing Server-Side Activities – Don’t forget to TURN OFF debug compilation

Starting from the AJAX Edition Network View I pick the request of my first use case walkthrough where I used a non existing username and password on the logon page:

Network View shows slow request to my first login attempts (1.8s)  and allows me to drill to the server-side execution

Network View shows slow request to my first login attempts (1.8s) and allows me to drill to the server-side execution

Drilling to the Server-Side PurePath allows me to see the full execution trace of this particular request to explore a) what is really going on in the page life-cycle of my ASP.NET MVC 2 Application and b) why this took 1.8seconds:

Account Controller validates password and redirects back to LogOn  View becuase of failed authentication

Account Controller validates password and redirects back to LogOn View because of failed authentication

The PurePath shows how ASP.NET MVC starts by creating the Controller – in our case it is the Account controller and invokes the LogOn action that verifies the passed logon credentials. The slowest method in the execution trace is LogOn which takes 1.4s. The reason why it is that slow is because this is the first time the database gets accessed – we can see that in the two thrown exceptions in the beginning. This method then calls the stored procedure dbo.aspnet_Membership_GetPasswordWithFormat and passes the 5 parameters to it as can be seen in the Details dialog of the SQL Statement:

Bind  Values for the Stored Procedure call include the passed username

Bind Values for the Stored Procedure call include the passed username

The password verification fails and therefore the Account controller sets a Model Error to indicate the problem of an incorrect password. This causes the Controller to default back to the LogOn view instead of being redirected to the Home View.

After the controller returns, ASP.NET continues “normally” and starts rendering the LogOn View as requested by the Controller. The interesting detail here is that when using the RenderPartial method the ASP.NET MVC framework internally browses through different directories to find the user control. In debug mode this lookup happens every time – even when the control has already been looked up causing a huge number of internal hidden exceptions. The reason why I stress this fact is because it is just too easy to forget to turn off the debug compilation switch in the web.config file. I know – it should not happen – but, I do have several stories where this has happened. For more details on this check out my post on Hidden Performance Problems with HtmlHelper.RenderPartial I wrote about a year ago.

Next: Getting deeper into ASP.NET MVC
That’s it for the first blog of this series. I will continue to extend the default ASP.NET MVC and explain more of its internals. I will also focus on memory analysis in .NET in general. My colleague Alois already wrote several nice articles about Memory Leak Detection in Java – now it is time to catch up with him and provide helpful hints for my fellow .NET folks :-)

The used dynaTrace ASP.NET FastPack and the Visual Studio Add-In can be downloaded by dynaTrace users on the dynaTrace Community Portal. For all others – if you are interested in more details check out the White Paper I wrote on Performance Management in Enterprise .NET Systems. Stay tuned.

Related reading:

  1. How to test jQuery enabled Apps using JSON with Visual Studio Visual Studio Team System offers a nice Web- and Load-Testing...
  2. VSTS LifeCycle Integration to monitor SharePoint I am currently attending MSFT TechEd in Orlando. During lasts...
  3. Randomizing Input Data for Visual Studio Load Tests While preparing for my presentation Load and Performance Testing: How...
  4. Getting ready for TechReady8: Load- and Web-Testing with VSTS and dynaTrace I’ve been invited by Microsoft to show dynaTrace’s integration into...
  5. VS2010 Load Testing for Distributed and Heterogeneous Applications powered by dynaTrace Visual Studio 2010 is almost here – Microsoft just released...

More Stories By Andreas Grabner

Andreas Grabner has been helping companies improve their application performance for 15+ years. He is a regular contributor within Web Performance and DevOps communities and a prolific speaker at user groups and conferences around the world. Reach him at @grabnerandi

Latest Stories
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
DXWorldEXPO LLC announced today that Kevin Jackson joined the faculty of CloudEXPO's "10-Year Anniversary Event" which will take place on November 11-13, 2018 in New York City. Kevin L. Jackson is a globally recognized cloud computing expert and Founder/Author of the award winning "Cloud Musings" blog. Mr. Jackson has also been recognized as a "Top 100 Cybersecurity Influencer and Brand" by Onalytica (2015), a Huffington Post "Top 100 Cloud Computing Experts on Twitter" (2013) and a "Top 50 C...
As DevOps methodologies expand their reach across the enterprise, organizations face the daunting challenge of adapting related cloud strategies to ensure optimal alignment, from managing complexity to ensuring proper governance. How can culture, automation, legacy apps and even budget be reexamined to enable this ongoing shift within the modern software factory? In her Day 2 Keynote at @DevOpsSummit at 21st Cloud Expo, Aruna Ravichandran, VP, DevOps Solutions Marketing, CA Technologies, was jo...
Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
"NetApp is known as a data management leader but we do a lot more than just data management on-prem with the data centers of our customers. We're also big in the hybrid cloud," explained Wes Talbert, Principal Architect at NetApp, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Since we launched LinuxONE we learned a lot from our customers. More than anything what they responded to were some very unique security capabilities that we have," explained Mark Figley, Director of LinuxONE Offerings at IBM, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
I love the beginning of the year. It is always enjoyable to see people's predictions for trends in the coming year. Publications like Fortune, CNN Money, Washington Post and the Atlantic speculate about what gadgets and technologies are going to take off in popularity this year, psychics predict which celebrities will have babies and fall in love, and I start to think about trends like DevOps and where the software delivery industry is headed next.CollabNet, Eric Robertson, predicted.
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its Call for Papers is now open. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expe...
Evan Kirstel is an internationally recognized thought leader and social media influencer in IoT (#1 in 2017), Cloud, Data Security (2016), Health Tech (#9 in 2017), Digital Health (#6 in 2016), B2B Marketing (#5 in 2015), AI, Smart Home, Digital (2017), IIoT (#1 in 2017) and Telecom/Wireless/5G. His connections are a "Who's Who" in these technologies, He is in the top 10 most mentioned/re-tweeted by CMOs and CIOs (2016) and have been recently named 5th most influential B2B marketeer in the US. H...
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.