Microsoft.NET

……………………………………………….Expertise in .NET Technologies

What’s New in .NET Framework 4.0 and New Features in Visual Studio 2010

Posted by Ravi Varma Thumati on October 2, 2009

A look at the upcoming features in Visual Studio 2010 and the .NET Framework for 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

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)

{

   BindDataControls()

}

private void BindDataControls()

{

   //DataBinding here

}

protected void Button1_Click(object sender, EventArgs e)

{

   BindDataControls();

}

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

Framework4.0_1
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.

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.

Framework4.0_2
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.

Framework4.0_3
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++)

{

   DoSomethingReallyComplicated(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.

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:

Framework4.0_4 

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.

Framework4.0_5
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.

Framework4.0_6
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.

Framework4.0_7
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,

   INamingContainer

{

   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 runat=”server”

              ClientIDMode=”Predictable” RowClientIDSuffix=”Pizza”>

 …

</asp:GridView>

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:

Framework4.0_8

 Framework4.0_9

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

     connectionString=”Server=PreProduction;Database=mySite;

                       User;password=world”

     providerName=”System.Data.SqlClient” xdt:Transform=”Replace”

     xdt:Locator=”Match(name)”/>

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

{

   get

   {

      return doorColorValue;

   }

   set

   {

      doorColorValue = value;

   }

}

In VB.NET, this would be:

Public Property DoorColor As String

   Get

      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.

Console.WriteLine(

            DoorColor)

And with nested method calls.

Console.WriteLine( breakfast( 1 ).GetSomeString( 99) )

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

   Else

      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();

   }

   else

   {

      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);

Console.WriteLine(drink.GetZing());

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.

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:

SaveTheseValues(,5,4)

You can do this:

SaveTheseValues(j:5,k:4)

What’s new in .NET Framework 4.0?

  • Next versions of Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) will provide better support for Web 2.0 technologies like REST, POX, and ATOM.
  • Performance and Scalability of WCF and WF are expected to increase by minimum 10X.
  • New workflow models.
  • Seamless integration between WCF and WF including a new Visual Designer.

Parallel Programming

Framework using PLINQ, Task Parallel Library and Coordination Data Structures to better utilize power of multi-processor and multi-core machines.

  • Build declarative applications with WF, WCF and WPF using XAML. So, XAML is no more only for WPF and WF.
  • WCF enhancements :

RESTful enhancements

  • Simplifying the building of REST Singleton & Collection Services, ATOM Feed and Publishing Protocol Services, and HTTP Plain XML Services using WCF
  • WCF REST Starter Kit to be released on Codeplex to get early feedback

Messaging enhancements

  • Transports – UDP, MQ, Local in-process
  • Protocols – SOAP over UDP, WS-Discovery, WS-BusinessActivity, WS-I BP 1.2
  • Duplex durable messaging

Correlation enhancements

  • Content and context driven, One-way support

Declarative Workflow Services

  • Seamless integration between WF and WCF and unified XAML model
  • Build entire application in XAML, from presentation to data to services to workflow

WF enhancements:

Significant improvements in performance and scalability

  • Ten-fold improvement in performance

New workflow flow-control models and pre-built activities

  • Flowcharts, rules
  • Expanded built-in activities – PowerShell, database, messaging, etc.

Enhancements in workflow modeling

  • Persistence control, transaction flow, compensation support, data binding and scoping
  • Rules composable and seamlessly integrated with workflow engine

Updated visual designer

  • Easier to use by end-users
  • Easier to rehost by ISVs
  • Ability to debug XAML

 

Advertisements

One Response to “What’s New in .NET Framework 4.0 and New Features in Visual Studio 2010”

  1. Hello there, just changed into alert to your weblog through Google, and located that it is truly informative. I’m gonna be careful for brussels. I will be grateful in case you proceed this in future. A lot of other folks can be benefited from your writing. Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: