Know your application better with visual studio 2010 load testing

August 10, 2012 § Leave a comment

Why this article again?

Good question! yeah when you implement a complex system & high volume data performing transaction. The Automation comes to rescue everywhere for testing as well as system. So I sharing it to everyone

Here is article on

Know your application better with visual studio 2010 load testing


We’ve reached a day when every business applications are built with a varieties of complexity and grows with large volume of data. Over the time when data volume grows or user base increase , there is a scope of decreasing the overall performance of the application or even failed to deliver as expected. For this reason as a precaution actual capability of the application must be measured in advance to avoid unexpected situations. Now a days simple application which will serve single user consistently is becoming antique. This is time when applications scalability and performance plays a vital role in the software specification as well as architecture. And thus the performance testing and analysis became handy. Goal of this article to provide a quick and simple approach to configure load test for real scenario and analyze results. Through this article I will share my experience of implementing load testing and analyzing results with visual studio 2010 ultimate.


“load testing with visual studio 2010” goggling this phrase is more then enough for anyone to find lots of fantastic articles about basic load testing setup. So in this article we will not walk in that path, instead I will share some additional info and share some configurations that will require to setup load testing for real life and focus on the analyzing the results. But before moving on I recommend you to learn basics of web test and load test if you are completely new to this kingdom. Visual studio 2010 shipped with very handy testing tool, we are going to utilize this tool to perform load testing. I recommend you to go through how to setup web test first, it will help you understand better.You can suggest any additional info to make this post more helpful.

Load Testing Topology

Load testing involves generating traffic to a system and measuring how it responds. Tools simulate heavy volumes of users taking various realistic scenarios in the system and we will use visual studio 2010 for this purpose. There is two ways to run load tests. Generate load from Visual Studio 2010 this will uses only 1 core/processor with limited to 250 simulated users. Another way is load testing through test rig which can simulate lots more users require much more more configuration in network and hardware layer. To avoid complexity we will not focus on test rig, but some day we will share this experiences too. The following diagram shows how a thorough load test could be set up using visual studio 2010.
Load Testing Topology

Load Testing

While doing load testing these are the considerations

  • Understanding the environment of the application being tested
  • A test plan defining user scenarios
  • Tools to generate load and capture metrics
  • Analysis of performance indicators

Visual studio 2010 can simulate approximately 1000 users per processor. we can generate load from Visual Studio 2010 through 2 approach

  • Default: uses only 1 core/processor and limited to 250 simulated users
  • Test Rig: can use multiple core/processor and can simulate lots more users

It is recommended that performance testing database and application database shouldn’t on the same server otherwise while test controllers sample and save the load test run results in the database on the application server it may impact the test results.
configaration 1
Visual studio load testing tool is consist of versatile concepts implemented and msdn got all well explained, which could be way out of head for a starter, So rather I listed few impotent concepts that are least required for carry out the load test.

  • Think Time: the time spent by a user perusing a Web page, including viewing the page and determining the next action. Think time does not include the time that is required for a page to load.
  • Ramp time: This property allows the increase number of user from one step to the next to occur gradually rather than immediately
  • Sample Rate: Time interval between collecting test data.For longer load tests, increasing the sample rate reduces the amount of data that you collect.
  • Run duration: Total time the test is expected to run.
  • Warm up: the load test will increase the load gradually during the warm-up period

we will use above concepts are configured in our attached sample project. To simulate real time request/response we can utilize mix that can control the percentage of load that is distributed among tests, browser types, or network types in a load test scenario.There are three types of mix

  • Test mix: It can specify for the probability that a particular test will be randomly selected by a virtual user during a load test run.
  • Browser mix: It do not simulate the test in a stripped down browser. Test agents includes a set of associated headers for the selected browsers and added to each HTTP request before submit.
  • Network mix: It simulate network bandwidth at the application layer. It does not simulate latency.


Configure and Use Sample Project

Sample project consist of 2 projects

  • TestingBox: test project consist of web test and performance test
  • TestingBox-Demo: we project invoked by the load test

In order to use the sample project within your application, you need to configure theses parameters below according to your needs,

  • Think Time: to simulate realistic wait times we set 3 seconds.
  • Think Profile: Normal Distribution
  • Step Ramp time: the user load would be increased from 10 to 20 users over a 10 second period
  • Sample Rate time: system will collect result data after each 10 second
  • Run duration: 10 minutes which is calculated based on the step load distribution
  • Warm up duration:load test will increase the load gradually within 5 seconds.

Another consideration is database.Visual Studio strictly requires SQL Server for the load test store. If you don’t have a SQL Server database, you cannot save test run data. You can check the databse setting from Test (visual studio menu) > Manage Test Controllers. A dialog will appear which allows set/reset of connection string of test data store.
configaration 2


Analyze Results

The primary goal of performance testing is to study application performance under normal load and heavy load for sustained durations or for short durations. In order to know our applications capability, our load tetsing should be answer these questions below

  • Does web application function properly under given load?
  • Does the page response times satisfy target requirements?
  • Which one is the slowest page on web application during tests?
  • Which page take longest time to download?
  • How many simultaneous users can web application handle?

And in this section we will try to find these answers by analyzing graphs provided by visual studio load testing.
At visual Studio 2010 several built-in graphs are provided. we can use the built-in graphs as is or we can customize them. Additionally, we can create our own graphs.
Load test analyzer graphs display counters. Each graph follow a specific measurement to plot a graph. The y-axis is not labeled with any specific range, but is instead labeled with values from 0-100 that represent a percentage of the total range for each counter. For example, for a counter with a range of 1000, a data point of 60 on the y-axis would correspond to a value of 600 for the counter. The horizontal timeline x-axis for a collapsing graph has an origin of 00:00 and a range that covers the entire test run. Average’s are not plotted in graph.
result monitor
We can analyze load test results by using the Load Test Analyzer in the following ways:

  • Monitor a load test in real time while it is running.
  • Analyze a load test results
  • Analyze results from previous load test(s).

Now lets try to find our answers from the graphs.
Does web application function properly under given load?
We can create an HTTP summary graph which will contain “Request time out”,”Passed request”,”Failed Requests”. This will provide time-based frequency of errors over the duration of the test. Error rate is an important metric in stress testing. This indicates the maximum number of users that can be served correctly, without errors and hence application capacity.
Ideally error percentage should be zero throughout the test run. If error percent is high, root cause of the error should be analyzed. It could be because of wrong inputs to the load test, network connectivity problem or the server might have crashed.
http summary
Does the page response times satisfy target requirements?
Visual studio load testing has a builtin graph called “Page Response Time”. This response Time versus Elapsed Time report indicates the average response time of the transactions over the elapsed time of the load test as shown.
From this graph it is possible to identify peaks in the response time over a period of time. Ideal behavior of response time graph is that response time does not increase with load. The point at which the graph increases sharply indicates beyond this load server cannot serve the request and users will see no response or a very slow response
Which one is the slowest page on web application during tests?
Same “Page Response Time” graph can be utilize for this purpose. This graph represents average response time for the each page in time. Each bar in the graph is the average server response time for each page.From this graph it possible to identify slowest page of the application.
result as a grid
Which page take longest time to download?
Same “Page Response Time” graph can be utilize for this purpose too.Each point in the graph is the average of the page download time during that interval. Page Download time graph of individual pages help you to identify the exact page that has high download time.
How many simultaneous users can web application handle?
Built in”Test Response Time” graph can be used for this purpose. If we analyze Response Time Vs Test response Graph we can find out the capability of the web application.The Response Time graph shows the time the server took for responding as the test load is increased. The peak indicates that the server has reached its capacity to serve data, and is unable to scale further.

Finally, visual studio load test has so much more to offer, this post only focused on those analysis that I thought important to get to know your application better. You can come up with lots of custom reports by utilize the result data if you need to. Hope this will help you.


Microsoft Open Sources Entity Framework

August 1, 2012 § Leave a comment

Microsoft continues to make in-roads into open source development. Early last year it open sourced several development related tools, including NuGet and several libraries for its ASP.Net language. And by the end of the year the company announced sponsorship of projects to port both the Node.js development platform and the big data analytics tool Apache Hadoop to Windows. It’s even making Linux available on Azure, the company’s cloud computing platform.

And now it has open sourced Entity Framework, a framework that helps developers simplify data manipulation.

Entity is now part of Microsoft Open Technologies, a subsidiary launched earlier this year to house open source projects. You can find the source code for Entity on Codeplex, Microsoft’s answer toGitHub.

It’s another step in the right direction, but it’s nothing earth shattering. Microsoft is continuing to put its open source efforts into low risk developer tooling projects. Although representatives Microsoft’s partners in porting Node.js and Hadoop (Joyent and HortonWorks, respectively) have spoken highly of Redmond’s involvement in those projects, I’m not sure how community involvement the other projects have garnered. I’d still like to see Microsoft open source something bigger, something more core to the company’s business.

Top 7 Things to Know About Web Service Security for Windows Phone

July 11, 2011 § Leave a comment

Top 7 Things to Know About Web Service Security for Windows Phone

(source :


As an increasing number of mobile applications trend toward web services for making the applications appear “live”, it is important that the requests that the application makes consider adequate security procedures. Let’s understand some of the things that a Windows Phone developer should consider when designing a Windows Phone application.

Only Basic Authentication is Supported

The Windows Phone 7 platform is based on Silverlight 3. However, the Silverlight platform for Windows Phone 7 only supports basic authentication. This means that Silverlight 4 networking features such as NTLM authentication,UDP multicast client, and WCF RIA services are not supported for Windows Phone 7.

WCF Data Services Are Not Supported

Previously called ADO.NET data services, Windows Phone 7 operating system does not support WCF data services.

JSON Serialization Support

Windows Phone 7 platform does not support complete JSON serialization. However, partial serialization support is available through the DataContractJsonSerializer class.

Sockets and Custom Bindings

Sockets and custom bindings are not supported in Windows Phone 7 operating system.

Basic Authentication and HTTPS

Since Windows Phone 7 operating system only supports basic authentication, it makes the scenario of HTTPS calls more interesting. To exercise the HTTPS scenario, you need to have an HTTP connection over a Secure Sockets Layer (SSL) or Transport Later Security (TLS)connection.

You achieve this by specifying a URL starting with https://, and Windows Phone platform takes care of the underlying wiring. When you make a call to an https://” endpoint, Windows Phone checks the certificate returned by the web service and verifies that the certificate is from a trusted authority. Once this is verified, further communication takes place in an encrypted environment.

Mutual Authentication Not Supported

Windows Phone lets you install trusted certificates on the device. However the Windows Phone platform does not expose the certificate values to applications running on the device. This limits the application from implementing mutual authentication scenarios.

Promoting For Credentials

Safe programming practices dictate that it is most secure to prompt the user for credentials when the scenario demands one. However, applications today in the name of usability allow storing for credentials on the device itself so that applications can use them without prompting a user. When storing credentials on a phone, please be sure to apply appropriate encryption.


In this article, we learned a few important things every application developer should know about security using web services in their Windows Phone application.

Developing a Basic C# Application for the iPad Using Monotouch

January 14, 2011 § Leave a comment


Developing applications for Apple’s iOS devices including the iPhone, iPod Touch and iPad has, for the most part, meant using the Objective C language. For C# developers, this is a big turn off. Moving from C# to Objective C is something like going from Visual Basic to GW Basic. The languages are similar but different. Novell’s Monotouch brings the power and elegance of C# to the table, making it possible for Microsoft developers to code in a language they’re comfortable with.

You’ll find the process even easier if you like to build forms in code rather than using a drag-and-drop designer like Microsoft Visual Studio. Monotouch provides bindings for all the form elements in the CocoaTouch class library. Admittedly, they are different from your typical Windows Forms app, but there are similarities just the same. All the standard elements like buttons and text boxes are there along with a whole host of new elements specifically designed for the touch environment on small screens.

Getting Started

The first thing you need to know right off the bat is that you’ll need an Intel-based Mac if you want to actually test or debug your code. Monotouch uses the Apple SDK for a multitude of things including the device emulator, Interface Builder and, ultimately, the final executable code as it is linked to the base Apple libraries. To get the Apple SDK and their Xcode tool you’ll have to register with Apple’s developer program. If you want to actually deploy an app, you’ll have to pay the $99 annual fee.

Novell offers a trial version of Monotouch that does everything you need except deploy onto a physical device. You can write all the code you want as long as you use the device emulator for testing. Be sure you follow the installation guide as the order of installation is important. Monotouch relies on the latest Mono runtime for OSX that must be installed first. There’s also a special version of Monodevelop with additional tools for Monotouch. If you’re comfortable with using Microsoft Visual Studio, you’ll feel right at home with Monodevelop.

There are a multitude of resources to help you get up to speed quickly with developing using Monotouch. The tutorials web page has links to how-to articles, sample code and screen casts. If you learn better from a book there’s an excellent recently-released book titled iPhone Programming with MonoTouch and .NET/C# by Wally McClure, Martin Bowling, Craig Dunn, Chris Hardy and Rory Blyth. Both Wally McClure and Craig Dunn have active blogs with lots of good information as well.

If you decide to try out code samples from either the book or from the Monotouch site, you’ll need to know a few things. First and foremost is the SDK version number. Many sample apps were built with earlier versions of the SDK and will have that set in the project options. If you compile an app and you don’t have the target SDK installed, you’ll get an error. To change the target SDK, simply open application options under the Project menu and change SDK version under the iPhone Build entry as shown below.

change SDK version under the iPhone Build entry
(Full Size Image)
Figure 1

Code Basics

One of the things you should do before you get too far along in coding is read Apple’s user interface (UI) document. If you have any plans of actually publishing and selling an application, it will need to comply with their guidelines or you’ll never get it approved for the Apple store. You’ll want to pay close attention to the screen rotation requirement. All apps must support screen rotation, so you’ll need to know how to adjust your screen elements when that happens.

Coding for the iPhone family frequently utilizes the Model-View-Controller (MVC) design pattern. You can see it in many of the class names and supporting code. Apple’s iOS development introductory tutorial builds a basic “Hello World” app for the iPhone and uses MVC as a part of the design. Understanding these patterns and how they apply to different programming tasks will help you build better applications. The Cocoa Fundamentals Guide is a good read to help get you oriented to the Apple way of user interface design, and it includes a chapter on design patterns.

Building a UI around the CocoaTouch UIViewController is a pretty standard approach to creating a basic interface. Adding the ability to autorotate with a UIViewController is accomplished with the following snippet of code:

  public class AppViewController : UIViewController
      public AppViewController () {}
      public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
          return true;

This code will cause all the elements in the UIViewController to reorient when the operating system rotates the screen. It doesn’t do anything other than change things like text labels and buttons so that they render properly based on how the user is holding the device. You’ll have to write more code if you want to do something like add a navigation pane on the left hand side of the screen when the device is in landscape orientation.

Building an app for the iPad is fundamentally no different from the iPhone. The only real difference is the hardware, meaning screen size and iPhone specific capabilities such as GPS and the magnetometer. Creating a new iPad solution in Monodevelop looks something like the screen capture below:

iPad solution in Monodevelop
(Full Size Image)
Figure 2

Once you have the solution created you’ll see the basic components of your app appear in the Solution pane including Main.cs and MainWindow.xib. These are the two necessary pieces to any basic app. Main.cs contains all the code necessary to initialize the app and display the UI described in MainWindow.xib. This should look like the following:

Monotouch: MainWindow.xib
(Full Size Image)
Figure 3

If you double-click on the MainWindow.xib file, you’ll open up Interface Builder and have the opportunity to build your user interface using the Apple tools. This will take some getting used to as it is quite different from the Microsoft Visual Studio approach. For this demo we put a text label and a button on the main surface and saved the file. Selecting Run from the Monodevelop menu will launch the iPhone (iPad) simulator and run your application. For the simple text label and button you should see the following:

iPhone (iPad) simulator
(Full Size Image)
Figure 4

Wrap Up

Building apps with Monotouch should look and feel a lot like Microsoft Visual Studio. You’ll have to adjust your thinking somewhat to the Apple way of doing things, but the transition isn’t that difficult. The demo version of Monotouch lets you get your feet wet without spending a lot of cash. You will have to buy the full version ($399 for the Professional Edition) when you get ready to actually deploy to the device.

10 Best Things Microsoft Did in 2010

December 2, 2010 § Leave a comment

10 Best Things Microsoft Did in 2010

When it comes to the enterprise, Microsoft hit the ball out of the park in 2010. Here’s our favorite offerings.

It’s been a successful year for Microsoft. The company took a lot of heat, but overall accomplished quite a bit — especially for its enterprise customers. Here’s our top tips for what Redmond got right in the past year.

BTW: Because we’re an IT publication, we focused on Microsoft’s enterprise offerings, and left off those from its entertainment/gaming division (Go Kinect!), with allowances for Windows Phone 7 because of its enterprise applications. Be sure to post your favorite 2010 Microsoft product — both for IT and consumer — in our comments section!

10. Office for Mac 2011
Oft-neglected Mac users finally have an improved version of Office. Most notable is the inclusion of an Outlook client for the Mac.

9. Bing
Microsoft completed its integration with Yahoo! (replacing the Yahoo! search engine with Bing) in the United States and Canada in August. It also integrated the ad platform so advertisers have one platform to work with. Bing continues to gain share, but it’s still overshadowed by Google.

8. Windows Intune
Microsoft released two beta versions of this cloud-based systems-management tool. When it becomes available next year, Windows Intune will allow midsize IT departments to manage updates, centralize malware protection, perform proactive monitoring and track inventory, among other things. Perhaps best of all, the $11 per PC per month subscription includes Windows 7 Enterprise upgrade rights and the option to purchase the Microsoft Desktop Optimization Pack for an additional $1 per PC per month. As an added bonus, Microsoft released a free version of Microsoft Security Essentials for small businesses.

7. Visual Studio 2010
Launched in April, Microsoft’s popular IDE got a major facelift with substantial visual editing improvements, a new code editor, extended language support and parallel programming capabilities. It’s also optimized for SharePoint and cloud development.

6. Lync Server 2010
Microsoft released its successor to Office Communications Server 2007, Lync Server 2010, providing what it promises is the first viable alternative to PBXes. Microsoft intends to be a major player in the office telecom market.

5. SQL Server 2008 R2
Not only did Microsoft ship SQL Server 2008 R2 this year, but it has started shipping SQL Server 2008 R2 Parallel Data Warehouse Edition (code-named “Madison”) based on the massive parallel processing product that Microsoft acquired nearly two years ago from DATAllegro Inc. The solution appears on hardware in mid-December as part of the new HP Enterprise Data Warehouse Appliance. Microsoft last month released the community technology preview (CTP) of the next version of SQL Server, code-named “Denali,” which it says will up the bar on scalability and availability.

4. SharePoint 2010
In May, Microsoft launched SharePoint 2010 with some key new features:
support for enterprise search, centralized administration, digital asset management and business connectivity services.

3. IE 9
Microsoft showed it’s not going to go back to its days of complacency in the browser market with the recent release of the Internet Explorer 9 beta. Among other things, Internet Explorer 9 emphasizes HTML5 support.

2. Windows Phone 7
In 2010 Microsoft announced, lined up partners for and delivered its successor to Windows Mobile with a brand-new and unique UI. Whether it’s able to put a dent into the momentum of Droids and iPhones remains to be seen, but Microsoft appears to be back in the game.

1. Cloud
Microsoft went “all-in” in the cloud this year. The company released its Windows Azure and SQL Azure cloud Platform as a Service (PaaS) in February and in October announced a roadmap that promises to flesh out the offering in the coming year in support of hybrid cloud services. Microsoft also announced numerous big wins for its Business Productivity Online Suite, which the company is re-branding as Office 365. Moreover, Microsoft announced the Windows Azure Platform Appliance, which will let large enterprises and partners run Windows Azure on-premises.


Wondering why Microsoft Office 2010 isn’t on this list?

10 Top Office 2010 Features

Thought we left Office 2010 off the 10 Best Things Microsoft Did This Year list? No, we thought it deserved its own section, as it was perhaps the most important new product from Microsoft in 2010. Here are our 10 favorite features in the new suite.


  • The Ribbon: The Ribbon is about as divisive as a speech by Newt Gingrich or Keith Olbermann. Many find it more intuitive, while just as many are confused. Like it or hate it, it’s a centerpiece of the entire suite.
  • Locking the Office Doors: Office is a big target for hackers. One new piece of protection is Data Execution Prevention, which keeps rogue EXEs from running in memory space reserved for data.
  • Backstage: Backstage shows up when you click the file tab. Instead of a simple list of functions, Backstage has a center panel that shows up when you click a task, and it presents options related to that task.
  • Most Excel-lent: Excel 2010 has two main new features: PivotTables, which can be enhanced through Slicers (which offer better filtering of the data), and Sparklines, which can take a single cell and create a mini-popup chart that demonstrates patterns.
  • A Brighter Outlook: Outlook is more and more the master of your communications. Now, it not only manages alternative e-mail back-ends such as Gmail and Hotmail, but it even ties directly to social networks.
  • Office Web Apps: Office 2010 includes scaled-down Web versions of core apps such as OneNote, PowerPoint, Word and Excel. With Office Web Apps, you can work entirely online with a Web browser – even storing files on Windows Live.
  • Get the Picture: PowerPoint and Word feature picture editors that used to be the domain of dedicated programs; the new editors can even adjust saturation and color temperature.
  • Making a Powerful Point: Similar to how Word and PowerPoint can edit pictures, you can now edit video from within PowerPoint 2010.
  • Spell Check: Often we spell a word correctly, but it’s just the wrong word. Word 2010 helps stop that with context-sensitive spell check, and thus should know the difference between “there” and “their.”
  • Found in Translation: Word includes a built-in language translator, perfect for an international company or your kid’s homework.


November 8, 2010 § Leave a comment


The ValidateInputAttribute has received a nice little tweak in MVC 3 offering more fine grained control over parameters of a request.

In MVC 2 using ValidateInputAttribute was limited to the request level, that is all parameters in the request where either validated or not.  Lets demonstrate this with a simple example – a simple forum posting page,

<%@ Page Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage<Common.Model.ForumPost>” %>
<asp:Content ContentPlaceHolderID=”TitleContent” runat=”server”>
<asp:Content ContentPlaceHolderID=”MainContent” runat=”server”>
<h2>Post Question</h2>
<% using (Html.BeginForm()) { %>
<%=Html.LabelFor(c => c.Subject)%>
<%=Html.TextBoxFor(c => c.Subject)%>
<%=Html.LabelFor(c => c.Body)%>
<%=Html.TextAreaFor(c => c.Body)%>
<input type=”submit” value=”Post” />
<%} %>

We don;t care what the controller actions actually do but lets describe them here anyway

public class HomeController : Controller
    public ActionResult Post()
        return View();
    public ActionResult Post(ForumPost post)
        return View();

Now attempting to post any sort of markup back to the action will result in an exception being thrown,

If we wanted to allow markup to go through we can add the [ValidateInput(false)] attribute to the action.  The only problem with that is if we only wanted to allow markup in the Body and not the Subject we would have to write our own tests in the controller to prevent this.  Not the most ideal or clean solution.

MVC 3 solves this quite simply by extending the ValidateInputAttribute and allowing use to specify exclusions.  This means we can have validation turned on but specifically state the we don’t want to validate a specific request parameter(s) (e.g. Body).

[ValidateInput(true, Exclude = "Body")]

A very minor tweak that makes a big leap to being able to produce cleaner more readable code.

New Features in Microsoft Visual Studio 2010 and the .NET Framework 4.0

October 18, 2010 § 1 Comment

Visual Studio 2008 may be better than sliced bread, but the development team at Microsoft has already been working on the next release. They have recently given us Visual Studio 2010 and the .NET Framework 4.0 as a Community Technology Preview (CTP); it boasts several features that would appeal to developers.

This article won’t go into every single feature, but will go into features that are the most relevant to .NET developers. Please note that because this is a CTP, it doesn’t mean that the final release will be exactly as you see in the CTP or as is described here. I can go over the features roughly as follows:

New Features in the Visual Studio 2010 IDE and .NET Framework 4.0

  • Call Hierarchy of methods
  • A New Quick Search
  • Multi-targeting more accurate
  • Parallel Programming and Debugging
  • XSLT Profiling and Debugging
  • The XSD Designer

New ASP.NET features

  • Static IDs for ASP.NET Controls
  • The Chart control
  • Web.config transformation

New VB.NET features

  • Auto Implemented Properties for VB.NET
  • Collection Initializers
  • Implicit Line Continuations
  • Statements in Lambda Expressions

New C# features

  • Dynamic Types
  • Optional parameters
  • Named and Optional Arguments

Conclusion and Resources

New Features in the Visual Studio 2010 IDE and .NET Framework 4.0

Call Hierarchy of Methods

In complicated solutions, a single method may be used from several different places, and attempting to follow how a particular method is being called can be difficult. Call hierarchy attempts to address this problem by visually presenting the flow of method calls to and from the method you are looking at. In other words, you can look at what calls your method and what your method calls in a treeview format.

Obviously, I cannot present a truly complex example, but a simple example should help illustrate the point.

protected void Page_Load(object sender, EventArgs e)

private void BindDataControls()
   //DataBinding here

protected void Button1_Click(object sender, EventArgs e)

Now, if you wanted to figure out what calls BindDataControls(), you can right-click on it and choose “View Call Hierarchy.”

This gives you a window with a treeview format, as shown below, with nodes that you can expand ad infinitum (or until your machine runs out of memory). You also can right-click on the method names and go to their definition, or you can reset those methods as the root of the Call Hierarchy window if you want to work your way from there and don’t care about other methods anymore Further, you can view call hierarchies from the object browser too, so you needn’t always be viewing the code. This is a helpful visual cue for very complicated projects that we’ve all worked on at some point or another.

(Full Size Image)

A New Quick Search

A nifty little feature that Microsoft has added is the Quick Search window. This isn’t the same as the Search or Search and Replace window that searches for specific textual strings. It’s different in the sense that it searches across symbols (methods, properties, and class names) across your solution and filters them in the result view for you.

In this example, I typed in ‘but’ and it brought back all symbols that contained ‘but’ regardless of position. You can specify multiple words to search for by separating them with a space.

(Full Size Image)

Multi-targeting more accurate

Although VS 2008 supports targeting different frameworks from the same IDE, one problem was that the Toolbox and Intellisense displayed types that were available to the .NET 3.5 Framework whether or not you were working with a .NET 3.5 project. This may have caused problems when you tried to use something, only to realize that it wasn’t actually available to you.

VS 2010 gets smarter by only displaying items that you can use in the Toolbox and Intellisense (and other relevant areas).

Further, if you change your project to use a framework version that isn’t available on your machine, you will be prompted and can choose to retarget to another version or download the target framework that you wanted.

Parallel Programming and Debugging

Don’t let the name intimidate you. I think Microsoft has done a great job of allowing you to take advantage of multi-processor systems with very easy syntax to enable parallel programming that you can quickly adapt to.

In addition, to make things easier, VS 2010 comes with a set of visual tools that will help you debug and view simultaneously running threads. This means that you can view the task instances and the call stacks for each task in parallel.

If you’ve been using the Parallel Extensions to the .NET Framework, then most of this will be familiar to you.

A Task.StartNew will kick off your threads for you. If you then hit a breakpoint and view the VS 2010 Threads window, you can view the state of each thread and where it is currently. This can be seen below—the green indicating the main thread and the yellow indicating all the worker threads spawned.

(Full Size Image)

There will also be a Multistack window that allows you to peruse the call stacks of all of the threads currently being executed; this is again a helpful visual cue that groups together tasks sharing a stack frame.

Parallel Programming itself becomes a feature of the .NET Framework 4.0 as opposed to it being an extension right now. With Parallel Programming, you get Parallel LINQ (PLINQ) and syntax to make parallelization of algorithms easier. In fact, it’s unbelievably easy.

Say you have a for loop that performed a complicated task:

for (int i = 0; i < 10; i++)

Assuming DoSomethingReallyComplicated does something really complicated (as the name implies), you could parallelize it by using Parallel.For and enclosing the iteration in a lambda expression.

Parallel.For(0, 10, i => { DoSomethingReallyComplicated(i); });

Similarly, there is Parallel.ForEach<> for foreach loops. You could also use Parallel LINQ to do the same thing. Taking a theoretical, basic LINQ equivalent to the above, you would get this:

from i in Enumerable.Range(0,9)
   where DoSomethingAndReturnAValue(i)
   select i

PLINQ would involve a very slight change; just add AsParallel():

from i in Enumerable.Range(0,10).AsParallel()
   where DoSomethingAndReturnValue(i)
   select i

You should be able to see the real effects of these changes on multi-core machines under intensive circumstances. Of course, there is much more than I’ve gotten into here, such as parallel profiling views, but that’s beyond the scope here. You could get started now, if you’d like, by downloading the Parallel FX CTP.

XSLT Profiling and Debugging

Everyone hates XSLT. If you don’t hate XSLT, you haven’t used it enough. Part of this attitude towards XSLT stems from the difficulty you face when debugging it—it is a huge unknown and can blow up in your faces when you least expect it.

Visual Studio 2010 will offer an XSLT profiler to help with writing XSLT in the context of profiling and optimization. After writing your XSLT, you can use the “Profile XSLT” option in Visual Studio to supply it with a sample XML file that gets used for the analysis.

I decided to test out a sample XSLT from the Gallery of Stupid XSL and XSLT Tricks page because they would undoubtedly be complicated. The XSLT Profile on Compute square roots using the Babylonian Method produced this:

(Full Size Image)

Clicking on the ‘offending’ functions then takes you to the function details, among other views on the analysis available to you. Available to you are the paths of execution taken, assembly-level view of the execution, call hierarchy, statistics by function, and function details.

(Full Size Image)

Also available to you in the menu options is XSLT Debugging. You can launch an XSLT file with sample XML and step through it as you would normal managed code.

(Full Size Image)

No, your eyes aren’t deceiving you. You can set breakpoints, have locals set, and step through the template functions as you please. This should help alleviate your collective fears of XSLT immensely.

The XSD Designer

While I’m on the subject of XML, VS 2010 also introduces a new XSD Designer.

(Full Size Image)

It comes with a schema explorer, a visual view of the relationships in different levels of detail, and sample XML generation.

New ASP.NET Features

Static IDs for ASP.NET Controls

A few much-needed features make their way to ASP.NET in the .NET Framework 4.0. You now have the ability to specify the ClientID that gets rendered to the page instead of having to fiddle with viewstate or hidden fields to manage the IDs that get generated out to the page. If you’ve ever had to use the .ClientID property of a control or found yourself using ClientScript.RegisterStartupScript or ClientScript.RegisterClientScriptBlock, you will know what I mean; it doesn’t always feel good to have to write all your JavaScript in the codebehind. It’d be nice to let the JavaScript sit on the page or in an external JavaScript file—where it belongs—so that a change in the JavaScript doesn’t require a recompilation of the website, while at the same time still using dynamic ASP.NET controls.

With ASP.NET 4.0, you now can create controls that support static Client IDs. To do this, simply get your control to implement INamingContainer. When using the control on the page, set its ClientIDMode property to Static.

For example, here is the codebehind for a simple web user control (ASCX) with a label in it.

public partial class WebUserControl1 : System.Web.UI.UserControl,
   protected void Page_Load(object sender, EventArgs e)
      this.ClientIDMode = ClientIDMode.Static;

You would need to expose the ClientIDMode property so that the parent page can set it. That’s all you need to do, and the control gets rendered to the page with an ID of Label1.

When it comes to databound controls, though, you’d have to do things a little differently; it’s really not acceptable to have more than one control with the same ID on a page. For this purpose, the ClientIDMode can be set to predictable and you also can specify a suffix that ensures that the IDs generated are predictable (but not fixed).

An example of its usage would be (in a gridview):

<asp:GridView ID="GridViewTest" runat="server"
              ClientIDMode="Predictable" RowClientIDSuffix="Pizza">

And any controls rendered in the gridview should have IDs like “GridView1_PizzaLabelTest_1”.

The Chart Control

The Chart control is finally here! This control sports various chart types, including point, column, bar, area, doughnut, range, and types I hadn’t even heard of before such as Renko and Kagi…. The chart also has scale breaks for ‘excessive’ data, and even can be rendered in a 3D mode. As a quick test, I got to make these charts based on the meteor consumption of my friends:

(Full Size Image)

Combined with ASP.NET AJAX functionality, this can open up a vast array of presentation configurations for your website if you deal with such data.

The chart works off an HTTP Image Handler. This means that you also have the option of plugging in your own charting image handling assembly if you want to customize it further.

Web.config transformation

In enterprise environments, your ASP.NET application will have to go across various stages of deployment such as testing, staging, preproduction, and production. Due to the relatively isolated nature of these environments, you often will have had to create separate web.config files for each environment and ensure that any changes you make to one web.config has made it to the other web.configs as well.

VS Team System 2010 has implemented a web.config transformation feature that can perform the value-based transformation that you need when deploying to different environments. The transformation is performed as part of an MS Build task, but you will need to specify the transforms to perform across the various web.configs; this is done by adding a set of xdt:Transform attributes to various nodes that may need changing (such as the obvious connection string).

An example of this would be:

<add name="theSiteDB"
                       User Id=hello;password=world"
     providerName="System.Data.SqlClient" xdt:Transform="Replace"

Because of the XML-based nature of these transforms, it therefore is also possible to perform the transformation manually via the VS 2010 GUI or create deployment packages for the various environments that require minimal human intervention.

New VB.NET Features

Auto implemented properties

Often, you find yourselves declaring public properties like this:

public string DoorColor
      return doorColorValue;
      doorColorValue = value;

In VB.NET, this would be:

Public Property DoorColor As String
      Return _doorColor
   End Get
   Set(ByVal value As String)
      _doorColor = value
   End Set
End Property

More often than not, no extra logic ever gets placed in the get/set blocks. This is why C# was given an auto implemented property in which the private variable is declared behind the scenes for you.

public string DoorColor
   get; set;

This feature was not present for VB.NET in .NET Framework 3.5, but is now available in .NET Framework 4.0. It’s as simple as this:

Public Property DoorColor As String

Collection Initializers

The syntax to initialize collections in VB.NET 10 (in .NET Framework 4.0) is now slightly shorter.

Dim breakfast = {New Crumpets With {.CrumpetAge = 99,
                                    .CrumpetSmell = "Bad"},
   New Crumpets With {.CrumpetAge = 29, .CrumpetSmell = "Good"}}

Note that you don’t need to specify the collection type because it is implicitly understood. In .NET 3.5, this would not have compiled because it would have understood ‘breakfast’ as type ‘Object’ instead of Crumpets. .NET 4.0 understands Crumpets, a statement I never thought I’d actually write down.

Implicit Line Continuations

C# has had this for a long time—long lines of code can be split across several lines for more readability. VB.NET has had it, but you’ve always had to add an underscore (_) at the end of each line, which could get a little annoying. Certain types of statements can now be split across several lines without the _ required.

Therefore, the collection initializer example from the previous section can be declared like this:

Dim breakfast =
      New Crumpets With {
                    .CrumpetAge = 221,
                    .CrumpetSmell = "Foul"
      New Crumpets With {
                    .CrumpetSmell = "good",
                    .CrumpetAge = 1

It works on Console.WriteLine, too.


And with nested method calls.


Changes to Lambda Expressions: statements and subs

In VB.NET 9 (.NET Framework 3.5), Lambda Expressions always needed to return a value regardless of whether it was required or not. This could often cause confusion when switching between C# and VB.NET. The .NET Framework 4.0 addresses this issue by allowing VB.NET to create Lambda Expressions that don’t return anything. And, Lambda Expressions can now also contain statements instead of having to pass the logic to other methods as you had to do previously.

To write expressions that return nothing:

Dim lambdaNothing = Sub() Nothing
Dim lambdaSomething = Sub(Message) Console.WriteLine(Message)

To write expressions that contain statements:

Dim lambdaReturn = Function(i)
   If i >= 100 Then
      Return 3
   ElseIf i >= 10 AndAlso i < 100 Then
      Return 2
      Return 1
   End If
End Function

New C# Features

Dynamic Types and Dynamic Programming

C# should now support a new static type called 'dynamic'. This essentially allows for dynamic dispatch or late binding of the variable in question. For example, suppose you have two simple classes with a common-name method:
public class Coffee
   public int GetZing()
      return 1;

public class Juice
   public string GetZing()
      return "Orange";

You also have a method that returns one of the two object types:

private Object GetOneOfThem(int i)
   if (i > 10)
      return new Juice();
      return new Coffee();

You can then make a call to GetOneOfThem() without knowing what type you're going to have returned, but you can still attempt to call method names on it.

dynamic drink = GetOneOfThem(someVariable);

At runtime, GetOneOfThem() evaluates to either Juice() or Coffee() and then the corresponding method is called based on what the compiler resolves 'drink' to be. The above is a very simple example of dynamic programming—there is more to this. The underlying implementation of dynamic programming is the DLR—the Dynamic Language Runtime—which is what allows you to invoke things in a dynamic fashion. You can read more about dynamic programming and other new features in C#.

Optional Parameters

VB.NET has had this for a long time, and now C# gets it too—optional parameters in your function signatures.

private string GetMeaninglessDrivel(string drivelSeed="bork")

In the past, the lack of optional parameters in C# was overcome by overloading the method several times and calling the same common method from all overloads with different values being passed in. Optional parameters can help prevent unnecessary multiple overloads of methods and making a class unnecessarily complex.

Named and Optional Arguments

This feature is somewhat related to Optional Parameters. Suppose you have a method that has several optional parameters.

private void SaveTheseValues(int i=1, int j=2, int k=3)

If you wanted to pass in values just for j and k, but not i, you can now name the arguments that you are passing in instead of passing in values and skipping values with multiple commas.

So, instead of this:


You can do this:


Conclusion and Resources

That was a quick overview of what will probably be available to you in Visual Studio 2010 and the .NET Framework 4.0. To reiterate, you must keep in mind that because it is a CTP, not everything that you see will be exactly as it is when it is finally released (which is why I often discourage books that come out at the same time as the Visual Studio release - they're based on Betas and CTPs and so will not be completely reliable)

You can have a look at VS 2010 yourself if you'd like and if you can meet the hefty requirements for the Virtual PC image. You will need about 70 to 80 GB of hard disk space available, 2GB of RAM and a dual-core system at the least. The download is here.

The Parallel FX Library is also available as a CTP that works with the .NET 3.5 framework. You can download the Parallel FX CTP here.

Don't forget to have a read through the C# Future documentation as well for more information on the DLR.

Finally, you can also participate in the feedback process by submitting any bugs you find to the Microsoft Connect program for VS 2010.

Where Am I?

You are currently browsing the Microsoft category at Naik Vinay.