Welcome to MSDN Blogs Sign in | Join | Help

Videos of C# Authors at PDC

Here are links to a few short video interviews by prebynski with C# MVPs and luminaries speaking while they attended PDC 2009 last week in Los Angeles. This is a chance to hear the interests and opinions of folks who are immersed in the culture and technology surrounding C#. All three of these interviewees are with authors who are currently working on new books about C#. Hear their take on new technologies such as Azure and Dynamic in C#, as well as their thoughts on the latest developments in existing technologies such as LINQ, WPF and Silverlight.

kick it on DotNetKicks.com
Posted by Charlie Calvert | 0 Comments
Filed under: , , ,

Community Convergence LVII

Welcome to the fifty-seventh issue of Community Convergence. In this post I’ll focus on new articles from the C# team, as well as events taking place at PDC.

From the C# Team

Eric Lippert

Kirill Osenkov

Luca Bolognese

Dustin Campbell

Sam Ng

Charlie Calvert

From others at Microsoft

Mitsu

Jason Zander

Scott Guthrie

Scott Hanselman

Brad Abrams

Dan Fernandez

Downloads and Announcements

kick it on DotNetKicks.com

Video: Azure Services in Visual Studio 2010 Beta 2, Part III

This is the first of three videos showing how Visual Studio 2010 Beta 2 provides support for the development and deployment of Azure Services applications. In these short How Do I Videos, I filmed Jim Nakashima as he demonstrated practical techniques for quickly deploying applications to the cloud. These videos will eventually be published in the How Do I section of the C# Dev Center. I’m hosting them here for now, so that they will be available in time for PDC.

Azure Services in Visual Studio Part III

 

Download the Videos

Click the links below to download the videos to your local machine and view them at their native 1024 X 768 resolution.

Other Posts in this Series

kick it on DotNetKicks.com

Video: Azure Services in Visual Studio Beta 2, Part II

This is the second in a series of three videos showing how Visual Studio 2010 provides support for the development and deployment of Azure Services applications. In these short How Do I Videos, I filmed Jim Nakashima as he demonstrated practical techniques for quickly deploying applications to the cloud. These videos will eventually be published in the How Do I section of the C# Dev Center. I’m hosting them here for now, so that they will be available in time for PDC.

Azure Services in Visual Studio Part II

 

Download the Videos

Click the links below to download the videos to your local machine and view them at their native 1024 X 768 resolution.

To see the post which embeds the first video in this series, click here.

kick it on DotNetKicks.com

Videos: Azure Services in Visual Studio 2010 Beta 2 with Jim Nakashima, Part I

This is the first of three videos showing how Visual Studio 2010 Beta 2 provides support for the development and deployment of Azure Services applications. In these short How Do I Videos, I filmed Jim Nakashima as he demonstrated practical techniques for quickly deploying applications to the cloud. These videos will eventually be published in the How Do I section of the C# Dev Center. I’m hosting them here for now, so that they will be available in time for PDC.

Azure Servies in Visual Studio Part I

 

Download the Videos

Click the links below to download the videos to your local machine and view them at their native 1024 X 768 resolution.

The second post in this series is available here.

kick it on DotNetKicks.com

Microsoft SDK for Facebook Released

Microsoft has created an SDK to make it easier for you to write Facebook applications.

Resources

kick it on DotNetKicks.com
Posted by Charlie Calvert | 1 Comments
Filed under:

HDI Video: Generate from Usage in Visual Studio 2010 with Karen Liu

Karen Liu, the Lead Program Manager for the Visual C# and Visual Basic IDEs, has created a new video on Generate from Usage (GFU), a feature found in Visual Studio 2010, Beta 2. This post recaps what is included in the video, including the sections that show how GFU can be used to enhance test first development. The video is shot in both VB and C#. Since this is a C# blog, I’ll show only C# code, and will translate the VB code that Karen shows into C#.

Generate from Usage (GFU) is a new feature in 2010 that allows you to write code that consumes a library or API before that API even exists. Using Visual Studio menus or shortcuts, you can automatically generate classes, constructors, methods, fields and properties from the code you typed in the editor.

As the video begins, Karen first types in the code to initialize a class called Automobile that does not yet exist:

Code Snippet
  1. var myCar = new Automobile(Make: "Honda", Model: "Accord");

Notice that the class name Automobile is not colored in teal, which is Visual Studio’s way of telling you that it does not yet it exist. When seen inside Visual Studio, the word Automobile will also have red squiggly (or wavy) underline, and a small blue smart tag under the letter A, as shown in Figure 1.

Figure01

Figure 1: The red squiggle is Visual Studio’s way of telling you that the type Automobile will not compile. The blue smart tag under the letter A let’s the user know that an expansion tip is available by simultaneously pressing the Control key and a period (Ctrl + .).

The smart tag under the letter A is Visual Studio’s way of telling you to press the control and period keys to bring up a special expansion tip, as shown in Figure 2. Here we see two options, one for directly creating a class called Automobile, and the other for bringing up a dialog which allows us to define or tweak the details of the type of we create.

Figure02

Figure 2: Viewing an expansion tip in Visual Studio.

You can also bring up the options to create a new class or type by right clicking on the word Automobile and selecting Generate from the popup menu, as shown in Figure 3.

Figure03

Figure 3: A second way to generate a class is to right click the word Automobile and choose Generate from the popup menu.

If you select the option to create a new class, then Visual Studio will automatically generate a new file called Automobile.cs and place inside it a new class called Automobile. The entire generated file is shown in Listing 1.

Listing 1: The code generate when you choose to create a new class based on an undefined identifier in Visual Studio 2010.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace DeleteMe
  7. {
  8.     class Automobile
  9.     {
  10.     }
  11. }

You can now go back to your original source file where you will see that there is still a red squiggly and blue tool tip, as shown in Figure 4. These hints are shown because we have not yet created a constructor for the Automobile class. If we again press control plus period, then the option to generate these code elements is made available to us, as shown in Figure 4.

Figure04

Figure 4: Selecting the smart tag a second time brings up an option to automatically generate the constructor and associated fields for your class.

The code that is generated by selecting the expansion tip is shown in Listing 2. Notice that on lines 10 and 11 fields were created for your class and on lines 16 and 17 code was generated inside the constructor for initializing them. A comment in the form of a TODO item is also added to your class. These TODO items are visible in the Visual Studio Task List. You can access the Task List by choosing View | Task List from the menu, or by pressing Ctrl+W, T. Be sure to choose the Comments option from the drop down at the top of the Task List.

Listing 2: The code for the Automobile’s constructor is automatically generated by the IDE.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace GenerateFromUsageSample
  7. {
  8.     class Automobile
  9.     {
  10.         private string Make;
  11.         private string Model;
  12.  
  13.         public Automobile(string Make, string Model)
  14.         {
  15.             // TODO: Complete member initialization
  16.             this.Make = Make;
  17.             this.Model = Model;
  18.         }
  19.     }
  20. }

Karen next types in code for a TurnLeft method, and for a property called IsFacingNorth. As she types each item, a smart tag appears, and again she has the option to press Ctrl+. to automatically generate code for the Automobile class. The code typed in the program’s entry point is shown in Listing 3, and the code generated by the IDE is shown mostly in Listing 4. Notice, however, that code for a private object called distance was automatically generated in the Main method. The IDE actually gives you the option to create either a private field, as shown here, or a public property.

Listing 3: The complete code for Karen’s first sample includes a constructor, a method called TurnLeft, and a property called IsFacingNorth.

Code Snippet
  1.  
  2. namespace GenerateFromUsage
  3. {
  4.     class Program
  5.     {
  6.         private static object distance;
  7.         static void Main(string[] args)
  8.         {
  9.             var myCar = new Automobile(Make: "Honda", Model: "Accord");
  10.             myCar.TurnLeft(distance);
  11.             myCar.IsFacingNorth = true
  12.         }
  13.     }
  14. }

Listing 4: The code generated by the IDE for the TurnLeft method and the IsFacingNorth property.

Code Snippet
  1. using System;
  2.  
  3. namespace GenerateFromUsage
  4. {
  5.     class Automobile
  6.     {
  7.         private string Make;
  8.         private string Model;
  9.  
  10.         public Automobile(string Make, string Model)
  11.         {
  12.             // TODO: Complete member initialization
  13.             this.Make = Make;
  14.             this.Model = Model;
  15.         }
  16.  
  17.         internal void TurnLeft(object distance)
  18.         {
  19.             throw new NotImplementedException();
  20.         }
  21.  
  22.         public bool IsFacingNorth { get; set; }
  23.     }
  24. }

When looking at Listing 4, notice that code for generating a NotImplementedException is automatically generated in the TurnLeft method. The IDE was also smart enough to discern that the IsFacingNorth property returns a bool. All the lines of code shown in Listing 4 were generated by typing just three lines of code in the main method found in Listing 3.

The C# Side

In the second part of the video Karen shows how you can use generate from usage (GFU) to enhance your experience when creating unit tests. Many theorists advocate using a test first methodology in which you first create a test, and then write the code that you want to test. You will see that GFU can be used to make this style of development quite natural and simple to use inside of Visual Studio.

NOTE: This section of the post requires high end versions of Visual Studio that contain the test wizards. Even if you don’t have those tools, you can still follow along to see how Generate from Usage can be used in all versions of Visual Studio to make it easier to create unit tests.

Begin by starting a new console application called Customer. Choose Tests | New Test from the Visual Studio menu. Select Basic Unit Test from the dialog, and name it Customers, as shown in Figure 5. When you press OK in the Add New Test dialog you will be prompted for the name of your unit test project. Type in CustomerTests. When you are done, the Solution Explorer for your project should look as it does in Figure 6.

Figure06 

Figure 5: Create a new unit test project that will house a file called Customers.

Right click on the Customer node in the solution explorer and choose Add | New Folder to create a new directory called Models. When you are done you should see a new node in the solution explorer, as shown in Figure 6.

Figure07 

Figure 6: This solution contains two projects, one a simple console application called Customer that contains a folder called Models. The other project is called CustomerTests and it is designed to hold unit tests.

I want to check if my Customer list is create correctly. In the Customers file from your test project, create a method called IsCustomerListValid. Inside the method create code to initialize a CustomerList object, as shown in Listing X.

Listing 5: A simple unit test with the code to initialize a class called CustomerList. Note that the CustomerList is not colored in Teal, since its declaration has not been created yet.

Code Snippet
  1. using System;
  2. using System.Text;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using Microsoft.VisualStudio.TestTools.UnitTesting;
  6.  
  7. namespace CustomerTests
  8. {
  9.     [TestClass]
  10.     public class Customers
  11.     {
  12.         [TestMethod]
  13.         public void IsCustomerListValid()
  14.         {
  15.             CustomerList cust = new CustomerList();
  16.         }
  17.     }
  18. }

At this stage, there is no CustomerList, so in Visual Studio you will again see the red squiggles and the blue smart tag, just as I showed in Figure 2. Without needing to take your hands off the keyboard, you can press control plus dot to bring up the expansion tips as in Figure 2. This time select New Type. A dialog comes up like the one shown in Figure 7. In the dialog we can change the accessibility, the kind of code to generate and the project file and directory where we want to place it. Set the Access to public and the Kind to class. Use the Project drop down to select the Customer project and the the Create new file drop down to select the Model directory. Type in CustomerList.cs as the name of the file to create.

Figure05

Figure 7. Selecting the kind of type that you want to create, as well as the project, folder and file in which you want to place it.

When you press OK in the Generate New Type dialog, the new type will be created, and the IDE will add the using directive and the correct references. You can now fill out your test and your generated class as shown in Listing 6 and 7. Note that we have used generate from usage to enhance the CustomerList class with a method called Add. I then manually wrote code to create a list into which the text we pass can be inserted.

Listing 6: A simple unit test.

Code Snippet
  1. using Customer.Models;
  2. using Microsoft.VisualStudio.TestTools.UnitTesting;
  3.  
  4. namespace CustomerTests
  5. {
  6.     [TestClass]
  7.     public class Customers
  8.     {
  9.         [TestMethod]
  10.         public void IsCustomerListValid()
  11.         {
  12.             CustomerList cust = new CustomerList();
  13.             cust.Add("Karen");
  14.             Assert.IsNotNull(cust);
  15.         }
  16.     }
  17. }

Listing 7: The using directive, namespace, CustomerList class and header for the Add method were auto-generated. I manually created the list and inserted the call to Add an item into it.

Code Snippet
  1. using System.Collections.Generic;
  2.  
  3. namespace Customer.Models
  4. {
  5.     public class CustomerList
  6.     {
  7.         List<string> list = new List<string>();
  8.  
  9.         public void Add(string p)
  10.         {
  11.             list.Add(p);
  12.         }
  13.     }
  14. }

You can now use the Test | View menu to bring up the Test List Editor and Test View to select and run your test.

Summary

In this post you got a second look at the code used in Karen Liu’s generate from usage video. You saw that GFU can be used to create classes, constructors, parameters, properties and fields. You also explored the powerful Generate New Type dialog which gives you the flexibility to choose the kind of type you want to create, as well as the project, directory and file in which you want to insert it. Finally, you saw that generate from usage can be powerful aid when you are engaged in test first development.

Resources

kick it on DotNetKicks.com

Classic, Lightweight and ScriptFree MSDN Library Views

There have been a number of changes to the MSDN library of late, and to the way it is integrated with Visual Studio 2010. Kathleen McGrath and Mark D'Urso have created a nice little video that walks you through some of the new features such as the classic, lightweight and script-free views, as well as the new feedback mechanism. If you have questions about how the new features in the library work you might find that this is a useful way to spend 9 minutes and 36 seconds.

You might also enjoy Kathleen’s video interview with Ryan Linton. It  focuses on using help from inside Visual Studio.

kick it on DotNetKicks.com

New Article by Bill Wagner on Dynamic Method Bags in C# 4.0

C# MVP and wunderkind Bill Wagner has written an article entitled Dynamic Method Bags which is now available on MSDN. Bill explores the new dynamic feature in C# 4.0. Most posts on this subject explain how to use dynamic to call Python, Ruby or Office. In his article, Bill explains how dynamic can be used not to call another language or tool, but to call your own C# objects without directly using the reflection API’s. The solution he provides combines generics, expression tress and dynamic to create a “type that allows developers to add new methods at runtime” and call those methods through dynamic dispatch.

Resources

kick it on DotNetKicks.com
Posted by Charlie Calvert | 5 Comments
Filed under: ,

New Article on Detecting Memory Leaks . NET Applications

MSDN has published an excellent article by Fabrice Marguerie entitled “How to Detect and Avoid Memory and Resource Leaks in .NET Applications.” In the article, the author explains how memory leaks are introduced into .NET applications, and what you can do to discover and eliminate them. The code shown in the article is in C#, but the topics covered will likely be useful to a broad range of .NET developers.

 FabriceMarguerie

Figure 1: Fabrice Marguerie is a Microsoft MVP, French Software Architect and Web Entrepreneur with an in-depth understanding of .NET technology.

Fabrice explains his subject in great depth, providing information that will be useful both to advanced developers, and to those with an intermediate-level understanding of .NET development. Features included in the text include:

  • An explanation of how memory and resource leaks occur in .NET application
  • A demonstration of how to detect those leaks
  • A list of common causes of memory leaks and how to avoid them
  • A useful reference section listing a number of tools that can be used to help you find and manage leaks

This is a well written article with a wealth of information in it. Hurry on over to the Dev Center and take a look.

References

kick it on DotNetKicks.com
Posted by Charlie Calvert | 9 Comments
Filed under: ,

CSharp “How Do I Videos (Podcasts)” for the Zune Software

It can be handy to create custom RSS feeds for the Zune so that it is easy to download and watch selected videos. You can watch these videos either on your PC, or on the Zune itself. Here is a custom feed I created that contains all the new C# 4.0 language and IDE How Do I Videos, plus a selection of other How Do I videos. In total, at this time, there are 35 videos in the feed. The RSS I created uses a simple and quite minimal syntax tested only with Internet Explorer 8 and the software for Zune 4.0.740.0. The source for the C# program that generated the feed includes regular expressions, LINQ to Objects and LINQ to SQL. I discuss that program briefly at the bottom of this post.

You can use this custom feed from inside IE, as shown in Figure 0. However, I really created this feed to run on the Zune, so you should import the feed into the Zune software as a series of podcast. I explain this latter process in the next section of this post.

Figure00

Figure 0: Viewing a simple RSS feed in IE 8. Click the image to expand it.

Using the Feed in the Zune Software

In this section I provide a quick tutorial for those who’ve never used Podcasts with a Zune. Open the custom RSS feed in IE and grab the URL from the address bar. Alternately, you can just right click on any of the links to the feed in this document and choose Copy Shortcut or whatever the equivalent command is in Firefox or other browsers. Open the Zune software and turn to the Collection | Podcasts page. Click the button on the bottom left of the page called Add a Podcast. The Subscribe dialog appears. Paste in the URL for the feed, as shown in Figure 1, and then click the Subscribe button. The various How Do I podcasts included in the feed should begin downloading to your system, as shown in Figure 2.

Figure01 

Figure 1: Subscribing to an RSS Podcast feed in Zune Software 4.0.740.0 

Figure02

Figure 2: Viewing a feed in the Zune Software.

You can then plug in your Zune and right click on the feed and choose to sync the videos to your device. I’ll confess, however, that many of these videos look best on a PC, since you need a certain amount of screen real estate to adequately view the code typed in by the presenters.

Creating the RSS Feed by Screen Scrapping

I created this feed by the time honored hack of screen scraping. I first copied the URL for the home page of each video and passed it to C# code designed to download the HTML associated with the URL. The program parsed the HTML looking for the elements I needed in my feed. LINQ to XML provided a handy tool for creating my simple RSS feed. I simply passed in the data retrieved from the HTML file to a set of LINQ routines designed to produce the XML for an RSS feed.

This technique is simple to implement.  Screen scraping is nevertheless a very brittle practice, as my code will last only so long as the basic structure of the HTML pages that I’m parsing remains static. How long such conditions will prevail one can only suppose.

I called my quick and dirty program CreateRssFeed, and its source is available for download. The program is based on two custom classes, one for generating the RSS feed, the other for using Regular Expressions to parse the HTML file.  I store the URLs for the 35 HDI video pages in a file called UrlsToProcess.txt. I won’t bore you with the complete listings for this code, but I show the main body in Listing 1, and a short excerpt from the RSS feed is shown in Listing 2.

When you download the source, you will find versions for both VS 2008 and VS 2010, Beta 2. The latter solution contains both a console and a windows forms app. They each have their advantages, but I tend to prefer the former.

Listing 1: The main body of the program.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using CreateRssVideo.Code;
  5.  
  6. namespace CreateRssVideo
  7. {
  8.     class ProgramConsole
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             string[] urls = File.ReadAllLines("UrlsToProcess.txt");
  13.             List<string> items = new List<string>();
  14.  
  15.             ParseHdiVideoPages parser = new ParseHdiVideoPages(items);            
  16.             foreach (var url in urls)
  17.             {
  18.                 parser.ProcessUrl(url);
  19.                 Console.WriteLine(items[items.Count-1]);
  20.             }
  21.  
  22.             File.WriteAllText(@"..\..\CSharpZuneReadyHowDoIVideos.rss", parser.RetrieveXml());
  23.         }
  24.     }
  25. }

 

Listing 1: An abbreviated version of the RSS Feed created by the code for the CreateRssVideo program.

Code Snippet
  1. <?xml version="1.0" encoding="utf-8" standalone="yes"?>
  2. <!--Charlie's RSS Feed for Videos-->
  3. <rss version="2.0">
  4.   <channel>
  5.     <title>CSharp How Do I Video Custom Feed for Zune Software</title>
  6.     <description>VS 2010 Related Videos</description>
  7.     <link>http://blogs.msdn.com/charlie</link>
  8.  
  9.     <item>
  10.       <title>Add Tool Windows to the Visual Studio IDE?</title>
  11.       <description>This video demonstrates how to</description>
  12.       <link>http://msdn.microsoft.com/en-us/vstudio/dd250814.aspx</link>
  13.       <enclosure url="http://download.microsoft.com/CreatingToolWindows.wmv" type="video/x-ms-wmv" />
  14.     </item>
  15.  
  16.   </channel>
  17. </rss>

The C# code for the CreateRssVideo program uses the build-in WebClient object to download the HTML for the video home page as a string:

private static string RetrieveHtmlFromSite(string urlName)
{
    WebClient objWebClient = new WebClient();
    byte[] requestedUrl = objWebClient.DownloadData(urlName);
    UTF8Encoding utf8 = new UTF8Encoding();
    string htmlAsString = utf8.GetString(requestedUrl);
    return htmlAsString;
}

It then uses bits of Regular Expression code to parse the HTML and extract the title, description and video URL from it:

private string FindStringInHtmlFile(string htmlAsString, string regEx)
{
    Regex r = new Regex(regEx, RegexOptions.IgnoreCase);

    MatchCollection matchCollection = r.Matches(htmlAsString);
    string groupItem = "";

    if (matchCollection.Count > 0)
    {
        foreach (Group groupItemFound in matchCollection[0].Groups)
        {
            groupItem = groupItemFound.Value;
        }
    }
    return groupItem;
}        

Below is a sample of one of the simple regular expressions that I pass into the FindStringInHtmlFile method. This particular bit of code is used to retrieve the description of the video from the HTML file:

private static string regExDescriptionText = @"([A-Z\s0-9#\.,\(\)\-]+)";
private string regExDescription = @"<p><strong>About this Video</strong></p><p>" + regExDescriptionText;

While we are parsing the HTML, the program works step by step to create the RSS document using LINQ to XML. The first stage in the RSS creation is to new-up an outline or shell that will hold the meat of the document:

public void Start()
{
    string link = "http://blogs.msdn.com/charlie";
    string title = "CSharp How Do I Video Custom Feed for Zune Software";
    string description = "VS 2010 Related Videos";

    theDocument = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
        new XComment("Charlie's RSS Feed for Videos"),
        GetChannel(link, title, description));
}        

private static XElement GetChannel(string link, string title, string description)
{
    return new XElement("rss", new XAttribute("version", "2.0"),
        new XElement("channel",
                        new XElement("title", title),
                        new XElement("description", description),
                        new XElement("link", link)));
}

The Start method creates the document itself, including an XML declaration and a comment. The GetChannel method adds a few simple fields to the document that describes its purpose and which list the URL for my home page. Compare this code with the first few lines from Listing 1 to be sure you understand its purpose.

As the information for each HDI video is discovered, a new <item> node is created for the RSS feed. This node lists the title for the video, describes the video, and references the URL for the HTML page where the video is stored. Finally, and most importantly, the code includes the <enclosure> node which stores the URL of the actual video. It is the <enclosure> node that the Zune software uses to locate the video which it downloads to your system:

private static XElement GetItem(string itemTitle, string description, string linkUrl, string videoUrl)
{
    XElement item = new XElement("item",
                new XElement("title", itemTitle),
                new XElement("description", description),
                new XElement("link", linkUrl),
                new XElement("enclosure",
                    new XAttribute("url", videoUrl), new XAttribute("type", "video/x-ms-wmv")));
    return item;
}

Once the <item> node has been created, it is added to the XML document itself:

public void AddItem(string itemTitle, string description, string linkUrl, string videoUrl)
{            
    XElement item = GetItem(itemTitle, description, linkUrl, videoUrl);            

    var linkNode = from x in theDocument.Descendants("link")
                   select x;
    
    linkNode.First().AddAfterSelf(item);            
}

Note that this code includes a simple LINQ query used to discover the proper insertion point in the XML document, and then employs the LINQ to XML AddAfterSelf operator to insert the new <item> XML node into the code for the RSS feed. The program enters and loop and repeats the process of creating and inserting <item> nodes into our RSS feed multiple times. Once all the URLs in our UrlsToProcess.txt document have been examined the program exits.

Summary

The primary purpose of this post is to provide an RSS feed that you can use to download videos for viewing in the Zune software or in the Zune itself. I also showed a simple, and very brittle, screen scraping program that I used to create the feed. I wrote this program for my own use, and pass it on to you with only minimal claims of its value. If nothing else, it provides some examples of how to have fun writing Regular Expressions, and demonstrates how easy it is to use LINQ to Objects and LINQ to XML to create XML documents.

kick it on DotNetKicks.com

VSL at DevConnections

The following talks will be given by Visual Studio Languages team members at the DevConnections Conference in Las Vegas.

Tuesday, November 10, 2009 Title Speaker
10:00am - 11:00am VMS01: The Future of C# Charlie Calvert
11:15am - 12:15pm VMS02: Future Directions for Visual Basic Jared Parsons
1:45pm - 2:45pm VMS03: Microsoft Visual C# IDE Tips and Tricks Charlie Calvert
3:15pm - 4:15pm VMS04: Microsoft Visual Basic IDE Tips and Tricks Jared Parsons

For additional Information see:

kick it on DotNetKicks.com

Visual Studio 2010 Beta 2 does not Load: The “Application Cannot Start” and Raster Font Errors

I was working at home the other night with a freshly installed copy of Visual 2010 Beta 2. I closed the IDE for a moment, and when I tried to reopen it, I got an error that read: “The application cannot start.” I found I could start the IDE by using the Jump Lists in Windows 7 to start a specific application rather than simply opening the IDE without loading a project. After getting back inside the development environment, I rummaged about for a bit and finally fixed the problem, probably by resetting my profile (Tools | Import Export Settings). That may or may not work for you, but these two excellent and authoritative posts are more likely to solve your problem if you encounter a similar error:

ApplicationCannotStart

Figure 1: There is no joy in Mudville, Visual Studio 2010, Beta 2 will not start!

I was having an excellent time working inside VS 2010 Beta 2, so I was frustrated to hit this glitch. I don’t want you to wander into the same troubled climes, so I’m posting here this good information from two experts on the VS IDE. By the way, these issues are all fixed in our new internal builds, and those fixes will be part of the final release of Visual Studio 2010.

kick it on DotNetKicks.com

A Chance to Influence the MSDN Visual Studio Documentation (Help System)

The docs team here at Microsoft has created a new survey to solicit your opinion on the help system found in the MSDN technical library. This the same information you see if you press F1 in Visual Studio to get help on the IDE or your development language. I know the people who create and process this survey, and I can assure that any feedback you give will be processed and carefully considered. The team is strongly driven by input from our users, and this is your chance to have your say. I’ve taken the survey myself, and found that it consists of about 10 pages with an average of 2 or 3 questions per page. I didn’t spend much time contemplating each question, and was therefore able to finish the survey in about 5 minutes.

Links

Thank you for your input!

kick it on DotNetKicks.com
Posted by Charlie Calvert | 9 Comments
Filed under: ,

Running IronPython Scripts from a C# 4.0 Program

IronPython is a scripting language hosted on the .NET platform. This posts shows how you can use the Dynamic Language Runtime (DLR) and the new C# 4.0 dynamic keyword to call an IronPython script from a C# program.

Before going any further, it might be helpful to take a moment to explore the architecture that makes this technology possible. The key building block is the DLR, which sits on top of the .NET 4.0 CLR and provides the tooling for adding dynamic programs such as Python to the family of .NET languages. C# 4.0 adds the dynamic keyword and some related technologies to integrate support for dynamic binding into the language. The end result is that developers can arbitrary Python scripts directly from C# or other .NET languages.

Setting up a C# Project to Call IronPython

In two previous posts I described how to install and run a simple IronPython program:

If you don’t already have the latest version of IronPython installed or if you need a little refresher course in writing Python scripts, then you might want to glance at these posts. Otherwise, you can just keep reading to learn how to call Python from C#.

After the IronPython installation, its interpreter and its libraries will be installed in your Program Files directory, as shown in Listing 1. The interpreter is installed in ipy.exe, where ipy is pronounced “Eye-Pie.” The interpreter remains dormant when you call Python from C#, so our focus here should be on the assemblies shown in the second half of the listing, with a particular emphasis on IronPython.dll.

Listing 1: At the command prompt you can easily see the core files that form the basis for the IronPython installation.

C:\Program Files (x86)\IronPython 2.6 CTP for .NET 4.0 Beta 2>dir *.exe *.dll
 Volume in drive C has no label.
 Volume Serial Number is 4C6B-EE0E

 Directory of C:\Program Files (x86)\IronPython 2.6 CTP for .NET 4.0 Beta 2

10/18/2009  01:47 PM            12,624 ipy.exe
10/18/2009  01:47 PM            12,624 ipyw.exe

 Directory of C:\Program Files (x86)\IronPython 2.6 CTP for .NET 4.0 Beta 2

10/18/2009  01:47 PM         1,433,424 IronPython.dll
10/18/2009  01:47 PM           435,536 IronPython.Modules.dll
10/18/2009  01:47 PM           875,856 Microsoft.Dynamic.dll
10/18/2009  01:47 PM            58,192 Microsoft.Scripting.Debugging.dll
10/18/2009  01:47 PM           159,056 Microsoft.Scripting.dll
               7 File(s)      2,987,312 bytes
               0 Dir(s)  16,881,614,848 bytes free

To run a Python script inside a C# program, you should include some or all of the libraries shown in Listing 1 in the References section of your project. To get started, choose File | New Project (Ctrl-Shift-N) from the Visual Studio 2010 menu and create a new console application. Then open the Solution Explorer (Ctrl-W, S) and go to the References section for your project. Right click and choose Add Reference. Take a moment to appreciate how quickly the Add References dialog appeared (the team worked hared on this performance improvement), and then select the Browse tab and navigate to the directory where IronPython resides. The path to the directory hosting IronPython will probably be similar to the one shown in Listing 1. For now, the simplest choice is to select all the assemblies found in that directory, as shown in Figure 1. If you wish to keep things simple, then you only need to select IronPython.dll, Microsoft.Dynamic.dll and Microsoft.Scripting.dll to compile and run the program shown in this example.

 Figure01

Figure 1: Using the Add References dialog to select the assemblies found in that directory.

When you are done, the IronPython libraries should appear in the References section of the Solution Explorer, as shown in Figure 2.

Figure02

Figure 2: The References node of the Solution Explorer for a C# program that calls an IronPython script.

Writing the Code for Calling IronPython

Now that you have your project set up correctly you need to do two things:

  1. Write or find a script containing Python code that you want to run
  2. Write C# code to call the script.

Listing 2 shows a very simple IronPython script that contains a single method called Simple() that writes a few strings to a console window. Save this script to a file called Test.py, and add it to your project, as shown in Figure 2. There are several ways to do this. One is to right click on your project in the Solution Explorer, and choose Add | New Item. Add a text file, and call it Test.py. Click on the new node when it is added to your project, and set its Copy to Output Directory property to Copy Always. If the Properties window is not visible, you can bring it up by selecting Ctrl-W, P.

Listings 3a and 3b show the C# code for calling the script, and Listing 4 shows the output from the C# program that hosts the script.

Listing 2: A Simple Python script stored in a file called Test.py. This code prints out some basic information about the environment in which Python is running.

import sys

def Simple():
	print "Hello from Python"
	print "Call Dir(): "
	print dir()
	print "Print the Path: " 
	print sys.path

Listing 3a: A simple C# program for calling a Python script

Code Snippet
  1. using System;
  2. using IronPython.Hosting;
  3. using Microsoft.Scripting.Hosting;
  4.  
  5. public class dynamic_demo
  6. {
  7.     static void Main()
  8.     {
  9.         var ipy = Python.CreateRuntime();
  10.         dynamic test = ipy.UseFile("Test.py");
  11.         test.Simple();
  12.     }
  13. }

Listing 3b: The same C# program shown in Listing 3a, but this presentation is easier for you to block copy into your own version of the program.

using System;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

public class dynamic_demo
{
    static void Main()
    {
        var ipy = Python.CreateRuntime();
        dynamic test = ipy.UseFile("Test.py");
        test.Simple();
    }
}

The code in Listing 2 is a very simple Python script. Before calling it from C#, you might want to see it in action. That way you can be sure the script works and you can verify what the script is supposed to do. To get started, block copy the code in Listing 2. Use the Windows Start Menu to open up the Python Console window and paste in the code. Finally, you should explicitly call the Simple() method, as shown in Figure 3. When looking at this screen shot, you can see the version of the Python Console on the first two lines. The next 8 lines show the code that I pasted into the console. Finally, you see where I typed in the call to Simple(), and after that the output from the script. Once again, this has nothing to do with calling the code from C#, it is just a way of verifying that you have a valid script, and of confirming how it should perform.

Figure03

Figure 3: A screenshot showing a run of the Python script that we will be calling from our C# program.

Now let’s look at the 3 lines of code used to call this script from a C# program. This code is shown in Listings 3a and 3b. It first creates an instance of the Python runtime, as shown in line 9:

var ipy = Python.CreateRuntime();

The call to CreateRunTime loads or sets up the core Python libraries and the DLR code needed to to execute the Python script. The second line of code, found on line 10, calls UseFile to load our simple Python script into memory. Notice that the result of this call is a dynamic object. The dynamic  keyword is a new feature in C# 4.0 and Visual Studio 2010 which tells the compiler to resolve this particular call not at compile time, but at runtime.

It’s very important to understand that the dynamic keyword breaks the strong type checking that has always been a hallmark of C# development. There is no doubt that the ability to call dynamic objects is a useful and important feature. However, it should be used sparingly since it sidesteps the strict type checking that makes C# such a powerful and useful language.

The dynamic keyword is needed here because Python is an interpreted scripting language where calls are bound at run time, not at compile time. There is no simple or practical way to bind calls to Python at compile time because Python is designed to be a dynamic language which is resolved at runtime. Since C# is a strongly typed language it expects to resolve calls at compile time with strict type checking. In short, we are at an impasse. C# binds statically at compile time, Python dynamically at runtime. Something has to give, and the only valid solution was for C# to allow runtime binding for method calls.

It is important to grasp that calls into Python are not strictly type checked at compile time, and are therefore not guaranteed to succeed at runtime. Just because your program compiled without error does not mean that you have properly bound each call in your program. In this case we call the method named Simple(), which does in fact exist. As a result, the call succeeds, as shown by the output from the program found in Listing 4.

Listing 4: The output from the C# program which calls a Python script.

Hello from Python
Call Dir():
[]
Print the Path:
['.', 'C:\\Users\\Charlie\\Documents\\SyncData\\Source\\ProjectsShared\\Python\\CallPython\\CallPython\\bin\\Debug\\Lib', 
'C:\\Users\\Charlie\\Documents\\SyncData\\Source\\ProjectsShared\\Python\\CallPython\\CallPython\\bin\\Debug\\DLLs']
Press any key to continue . . .


Listing 4 shows the good side of working with dynamic code. Now let’s take a moment to consider the dark side. Suppose we called a method on our dynamic test class that does not exist. For the sake of argument, let’s call the method NonexistentMethod(), which is shown in Listing 5.

Listing 5: This code contains a call to a method called NonexistentMethod() that does not exist in our Test.py file. As a result, the call will fail at runtime.

 var ipy = Python.CreateRuntime();
dynamic test = ipy.UseFile("Test.py");
test.Simple();            // Succeeds
test.NonexistentMethod(); // Fails

The code in Listing 5 contains a call to the method Simple() that will succeed, since the Python script shown in Listing 2 does contain a method called Simple(). However, the call to the method NonexistentMethod() will raise an exception at runtime. This happens because the call cannot be resolved at runtime. At compile time, however, the compiler knows nothing about the object called test. It makes no attempt to see whether or not the call will succeed. It simply takes your word for it and allows the compilation to succeed. At runtime, however, the error raises its head, as shown in Figure 4 and Listing 6.

Figure03a

Figure 4: The exception raised inside the IDE at runtime when you attempt to call a method that does not exist.

Listing 6: The details of the exception that you receive at runtime when you attempt to call a method that does not exist.

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException was unhandled
  Message='Microsoft.Scripting.Hosting.ScriptScope' does not contain a definition for 'NonexistentMethod'
  Source=Anonymously Hosted DynamicMethods Assembly
  StackTrace:
       at CallSite.Target(Closure , CallSite , Object )
       at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid1[T0](CallSite site, T0 arg0)
       at dynamic_demo.Main() in C:\Users\Charlie\Documents\SyncData\Source\ProjectsShared\Python\CallPython\CallPython\Program.cs:line 12
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

The team went to lengths to ensure that the error you get at runtime looks almost exactly like the error you would have received at compile time had you attempted to call a static method that did not exist. Everything possible is done to make this experience easy for your to understand and handle, including giving you an exception that you can catch with your own custom code.

It goes without saying that everyone on the Visual Studio Languages team at Microsoft understands the implications of introducing the dynamic keyword into the C# language. We understand completely the advantages of statically linked code, and believe that strict type checking is a powerful tool that helps developers create robust code. In most cases, you should still use statically linked calls in your program. There are, however, scenarios that cannot be efficiently supported from the C# language without the introduction of dynamic programming. One is calling a dynamic language such as Python, and another is calling into a some COM objects, such as those used in those used by Microsoft Office. In order to make it easy for you to use dynamic languages and to perform COM Interop, the dynamic keyword was introduced into the C# 4.0 language, and the DLR became a built-in extension of .NET 4.0. Use these tools judiciously, and they will be your friend. Abuse them, and you are on your own.

Summary

In this article you learned how to call a simple Python script from a C# application. You saw how to set up the References section for your program so that it contains the assemblies used when calling an IronPython script. You then saw how to write a simple Python script, and how to call it from a C# program.

The dynamic technology on display in this example makes use of a body of code called the DLR, or Dynamic Language Runtime. The dynamic keyword that is part of C# 4.0 provides supports when you call dynamic languages or COM objects, and particularly when you use C# 4.0 to call into Microsoft Office applications. Coverage of calling into Office is separate subject, and will be covered in another post. A third topic deserving of coverage is using the dynamic keyword in scenarios where you previously used reflection.

kick it on DotNetKicks.com
Posted by Charlie Calvert | 3 Comments
Filed under: , , ,
More Posts Next page »
 
Page view tracker