Scott Hanselman

Visual Studio Explosion! - VS2010 SP1 *BETA* Released and Context

December 10, '10 Comments [33] Posted in ASP.NET | ASP.NET MVC | Bugs | IIS | Microsoft | MSDN | VB | VS2010
Sponsored By

Link to VS2010 Wallpapers Site It's a holiday miracle! OK, maybe not a miracle, but folks have been working hard on Visual Studio 2010 Service Pack 1. The BETA was released today. See how BETA is in RED? That's because it's a beta.

Funny thing about beta service packs. They are Service Packs so there are lots of good bug fixes. But it's beta, which means we, Dear Reader, are not sure if they've missed some.

It's beta software, so be careful. Back things up, maybe take a disk image.

There is a go-live license, which means you can use this software today and use it in production. Upgrading from SP1 Beta to SP1 "final" will be one step.

If you hate betas, feel overwhelmed, don't like being on the cutting edge and don't want obscure details, stop reading now and go here.

Download Links:

Here's the curent Visual Studio 2010 SP1 Beta README file.

Beta Caveats (That's a fancy word for "Warning")

Be aware that Microsoft is in the middle of a lot of Beta Releases. It's your choice to play now or wait.

First, MOST of this beta stuff works together just fine. You may have seen my PDC talk where I used all of this together to build an application.

For example, all this works together today:

  • VS 2010 SP1 Beta
  • ASP.NET MVC 3 RC2 (releasing VERY VERY SOON - install it over the top to maintain Razor IntelliSense)
  • Razor Tooling
  • SQL Compact Edition 4 Beta
  • Entity Framework 4 Code First (CTP5)

There may be some bugs, so If you need things to not break at all, then just wait a month or two for all this Beta to calm down. For example, the new "Async CTP" isn't compatible with the web tooling.

Some folks have asked, "When will the beta releases be over and I can start working with final code?"

ASP.NET MVC 3, WebMatrix, IIS Express, SQL Compact Edition 4 and more will all be released in mid-January. Visual Studio 2010 Service Pack 1 will finalize a few months later. Use VS2010 today and come spring you'll have some new improvements that will build on VS2010 and make coding more enjoyable. They'll all work together.

That said, if you have a little patience, I encourage you to check out Visual Studio 2010 SP1 Beta. There's LOTS of great fixes, updated features and new tooling. Here's a sense of what's updated. We'll get a more complete (meaning "official") list nearer to release. This list isn't complete. I'm working on getting a complete list.

What's in Visual Studio 2010 SP1 BETA

In addition to fixes for bugs and things reported via Microsoft Connect, there's also these updates to Visual Studio 2010.

Web Bug Fixes

Just over 100 bug fixes related to web development, including fixes for JavaScript/CSS/HTML editors, crash bugs, design view bugs, and Visual Web Developer bugs.

HTML5 Schema Support

We’ve added *initial* support for HTML5 to the HTML editor so you can get IntelliSense and validation for HTML5 elements and attributes (choose HTML or XHTML5 from the schema drop-down). Includes support for popular new elements, e.g. video, audio, section, header, etc., and data-* attributes. The implementation is not complete and we are continuing to work on providing a great HTML5 experience for a future version of Visual Studio. There are *no* IntelliSense updates for HTML5 JavaScript APIs, e.g. Canvas, Cross-document Messaging, DOM Storage, etc.

IIS Express Support

Support for IIS Express as a local hosting option for Web Sites and Web Application Projects, including the option to set it as the default for new projects. No need to be an administrator to use IIS Express, including creating new sites from within Visual Studio. IIS Express supports:

  • SSL
  • Classic & Integrated pipeline modes
  • Basic & Windows authentication
  • Edit & Continue in debug
  • Creating new virtual directories when using IIS or IIS Express in Web Sites

Here's IIS Express appearing in a dialog choosing where a new Web Application should be:

IIS Express

Project Properties has been updated. Note the choices for IIS Express, Visual Studio Development Server, etc.

IIS Express

Here we're able to add a New Virtual Directory from within Visual Studio.

clip_image006

Note, SP1 does *not* include IIS Express, you need to download and install it separately. IIS 7.5 Express Beta 3 can be installed using Web PI 3.0 via the UX or directly via this direct link. Note that you don't need WebMatrix to get IIS Express now (win!).

IIS Express Beta 3

SQL Compact Edition 4 Tooling

I've blogged about EF Code First ("Entity Framework Magic Unicorn") before, which released a CTP5 today. I've also talked about SQL Compact Edition 4, a tiny xcopyable file based SQL Server. I showed them all working together in my PDC talk PDC10: Building a Blog with Microsoft "Unnamed Package of Web Love"

In that talk, I was able to open SQL Compact Edition 4 database files directly in Visual Studio. Internally we call that "SQL Compact Edition Tooling." Microsoft folks often refer to the Runtime and the Tooling separately.

Here's the SQL Compact Edition 4 Tools for VS2010 SP1 Beta that I used in my PDC talk. Additionally Web Deploy v2 is coming, and will allow you to easily migrate SQL Compact 4 to SQL Server directly when you outgrow the former. You can install both of them directly from the Web Platform Installer 3.0.

Go here to install Web PI 3, shut it down, then run it again from the Start Menu and select the things you want.

Additional Good Stuff

  • Silverlight 4 Tools for Visual Studio 2010 plus RIA Services is now included in the box along with Silverlight 3 support.
  • Unit Testing on .NET 3.5 – Today all unit tests are run under .NET 4. While acceptable for most users because of the compatibility done in .NET 4, this caused problems for some of you with .NET 3.5-specific dependencies.
  • IntelliTrace F5 for 64 bit and SharePoint projects – This is awesome for me as I needed IntelliTrace on x64 literally yesterday.
  • Performance Wizard for Silverlight – Now you can use the profiling tools on Silverlight apps as well.
  • VB Compiler runtime switch – This switch will enable Visual Basic developers to target their apps and libraries at platforms where the full VB Runtime hasn’t traditionally been available. Should be a win for VB on phone, XNA, etc.

Some Choice Bug Fixes (my choice)

  • The XAML editor respects control visibility
  • Offline Helper View with Index (is back)
  • IntelliTrace with F5 on Sharepoint Projects
  • More C++ MFC support for Windows 7 shiny things
  • Silverlight startup performance improvments

Simple Conclusion in Context

  • Keep using Visual Studio 2010 and feel no pressure to install a beta anything. There's lots of great stuff in VS2010 to explore.
  • If you install VS2010 SP1 beta, don't uninstall it if you can avoid it. Rather, wait for SP1 final which will upgrade your beta cleanly and leave you in the best state.
  • If you want to see the update wave of Web Tools and get some beta bug fixes, install the SP1 Beta and report bugs. If you're using SQL Compact, check out their tools as well.
  • If you aren't installing the beta tools today, then relax, and install the final web tools stuff in the January then VS2010 SP1 later in spring.
  • When it's all released, you'll be able to install all this as one package from Web Platform Installer. You'll run Web PI, select Visual Studio 2010 SP1, then install.

Related Links

Enjoy.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

The Weekly Source Code 56 - Visual Studio 2010 and .NET Framework 4 Training Kit - Code Contracts, Parallel Framework and COM Interop

August 12, '10 Comments [11] Posted in ASP.NET | ASP.NET Ajax | ASP.NET Dynamic Data | ASP.NET MVC | BCL | Learning .NET | LINQ | OData | Open Source | Programming | Source Code | VB | Web Services | Win7 | Windows Client | WPF
Sponsored By

Do you like a big pile of source code? Well, there is an imperial buttload of source in the Visual Studio 2010 and .NET Framework 4 Training Kit. It's actually a 178 meg download, which is insane. Perhaps start your download now and get it in the morning when you get up. It's extremely well put together and I say Kudos to the folks that did it. They are better people than I.

I like to explore it while watching TV myself and found myself looking through tonight. I checked my blog and while I thought I'd shared this with you before, Dear Reader, I hadn't. My bad, because it's pure gold. With C# and VB, natch.

Here's an outline of what's inside. I've heard of folks setting up lunch-time study groups and going through each section.

C# 4 Visual Basic 10 
F# Parallel Extensions
Windows Communication Foundation Windows Workflow
Windows Presentation Foundation ASP.NET 4
Windows 7 Entity Framework
ADO.NET Data Services (OData) Managed Extensibility Framework
Visual Studio Team System RIA Services
Office Development  

I love using this kit in my talks, and used it a lot in my Lap Around .NET 4 talk.

There's Labs, Presentations, Demos, Labs and links to online Videos. It'll walk you step by step through loads of content and is a great starter if you're getting into what's new in .NET 4.

Here's a few of my favorite bits, and they aren't the parts you hear the marketing folks gabbing about.

Code Contracts

Remember the old coding adage to "Assert Your Expectations?" Well, sometimes Debug.Assert is either inappropriate or cumbersome and what you really need is a method contract. Methods have names and parameters, and those are contracts. Now they can have conditions like "don't even bother calling this method unless userId is greater than or equal to 0 and make sure the result isn't null!

Code Contracts continues to be revised, with a new version out just last month for both 2008 and 2010. The core types that you need are included in mscorlib with .NET 4.0, but you do need to download the tools to see them inside Visual Studio. If you have VS Pro, you'll get runtime checking and VS Ultimate gets that plus static checking. If I have static checking and the tools I'll see a nice new tab in Project Properties:

Code Contracts Properties Tab in Visual Studio

I can even get Blue Squigglies for Contract Violations as seen below.

A blue squigglie showing that a contract isn't satisfied

As a nice coincidence, you can go and download Chapter 15 of Jon Skeet's C# in Depth for free which happens to be on Code Contracts.

Here's a basic idea of what it looks like. If you have static analysis, you'll get squiggles on the lines I've highlighted as they are points where the Contract isn't being fulfilled. Otherwise you'll get a runtime ContractException. Code Contracts are a great tool when used in conjunction with Test Driven Development.

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics.Contracts;

namespace ContractsDemo
{
[ContractVerification(true)]
class Program
{
static void Main(string[] args)
{
var password = GetPassword(-1);
Console.WriteLine(password.Length);
Console.ReadKey();
}

#region Header
/// <param name="userId">Should be greater than 0</param>
/// <returns>non-null string</returns>
#endregion
static string GetPassword(int userId)
{
Contract.Requires(userId >= 0, "UserId must be");
Contract.Ensures(Contract.Result<string>() != null);

if (userId == 0)
{
// Made some code to log behavior

// User doesn't exist
return null;
}
else if (userId > 0)
{
return "Password";
}

return null;
}
}
}

COM Interop sucks WAY less in .NET 4

I did a lot of COM Interop back in the day and it sucked. It wasn't fun and you always felt when you were leaving managed code and entering COM. You'd have to use Primary Interop Assemblies or PIAs and they were, well, PIAs. I talked about this a little bit last year in Beta 1, but it changed and got simpler in .NET 4 release.

Here's a nice little sample I use from the kit that gets the Processes on your system and then makes a list with LINQ of the big ones, makes a chart in Excel, then pastes the chart into Word.

If you've used Office Automation from managed code before, notice that you can say Range[] now, and not get_range(). You can call COM methods like ChartWizard with named parameters, and without including Type.Missing fifteen times. As an aside, notice also the default parameter value on the method.

static void GenerateChart(bool copyToWord = false)
{
var excel = new Excel.Application();
excel.Visible = true;
excel.Workbooks.Add();

excel.Range["A1"].Value2 = "Process Name";
excel.Range["B1"].Value2 = "Memory Usage";

var processes = Process.GetProcesses()
.OrderByDescending(p => p.WorkingSet64)
.Take(10);
int i = 2;
foreach (var p in processes)
{
excel.Range["A" + i].Value2 = p.ProcessName;
excel.Range["B" + i].Value2 = p.WorkingSet64;
i++;
}

Excel.Range range = excel.Range["A1"];
Excel.Chart chart = (Excel.Chart)excel.ActiveWorkbook.Charts.Add(
After: excel.ActiveSheet);

chart.ChartWizard(Source: range.CurrentRegion,
Title: "Memory Usage in " + Environment.MachineName);

chart.ChartStyle = 45;
chart.CopyPicture(Excel.XlPictureAppearance.xlScreen,
Excel.XlCopyPictureFormat.xlBitmap,
Excel.XlPictureAppearance.xlScreen);

if (copyToWord)
{
var word = new Word.Application();
word.Visible = true;
word.Documents.Add();

word.Selection.Paste();
}
}

You can also embed your PIAs in your assemblies rather than carrying them around and the runtime will use Type Equivalence to figure out that your embedded types are the same types it needs and it'll just work. One less thing to deploy.

Parallel Extensions

The #1 reason, IMHO, to look at .NET 4 is the parallelism. I say this not as a Microsoft Shill, but rather as a dude who owns a 6-core (12 with hyper-threading) processor. My most favorite app in the Training Kit is ContosoAutomotive. It's a little WPF app that loads a few hundred thousand cars into a grid. There's an interface, ICarQuery, that a bunch of plugins implement, and the app foreach's over the CarQueries.

This snippet here uses the new System.Threading.Task stuff and makes a background task. That's all one line there, from StartNew() all the way to the bottom. It says, "do this chunk in the background." and it's a wonderfully natural and fluent interface. It also keeps your UI thread painting so your app doesn't freeze up with that "curtain of not responding" that one sees all the time.

private void RunQueries()
{
this.DisableSearch();
Task.Factory.StartNew(() =>
{
this.BeginTiming();
foreach (var query in this.CarQueries)
{
if (this.searchOperation.Token.IsCancellationRequested)
{
return;
}

query.Run(this.cars, true);
};
this.EndSequentialTiming();
}, this.searchOperation.Token).ContinueWith(_ => this.EnableSearch());
}

StartNew() also has a cancellation token that we check, in case someone clicked Cancel midway through, and there's a ContinueWith at the end that re-enables or disabled Search button.

Here's my system with the queries running. This is all in memory, generating and querying random cars.12% CPU across 12 processors single threaded

And the app says it took 2.3 seconds. OK, what if I do this in parallel, using all the processors?

2.389 seconds serially

Here's the changed code. Now we have a Parallel.ForEach instead. Mostly looks the same.

private void RunQueriesInParallel()
{
this.DisableSearch();
Task.Factory.StartNew(() =>
{
try
{
this.BeginTiming();
var options = new ParallelOptions() { CancellationToken = this.searchOperation.Token };
Parallel.ForEach(this.CarQueries, options, (query) =>
{
query.Run(this.cars, true);
});
this.EndParallelTiming();
}
catch (OperationCanceledException) { /* Do nothing as we cancelled it */ }
}, this.searchOperation.Token).ContinueWith(_ => this.EnableSearch());
}

This code says "go do this in a background thread, and while you're there, parallelize this as you like." This loop is "embarrassingly parallel." It's a big for loop over 2 million cars in memory. No reason it can't be broken apart and made faster.

Here's the deal, though. It was SO fast, that Task Manager didn't update fast enough to show the work. The work was too easy. You can see it used more CPU and that there was a spike of load across 10 of the 12, but the work wasn't enough to peg the processors.

19% load across 12 processors 

Did it even make a difference? Seems it was 5x faster and went from 2.389s to 0.4699 seconds. That's embarrassingly parallel. The team likes to call that "delightfully parallel" but I prefer "you're-an-idiot-for-not-doing-this-in-parallel parallel," but that was rejected.

0.4699 seconds when run in parallel. A 5x speedup.

Let's try something harder. How about a large analysis of Baby Names. How many Roberts born in the state of Washington over a 40 year period from a 500MB database?

Here's the normal single-threaded foreach version in Task Manager:

One processor chilling.

Here's the parallel version using 96% CPU.

6 processes working hard!

And here's the timing. Looks like the difference between 20 seconds and under 4 seconds.

PLINQ Demo

You can try this yourself. Notice the processor slider bar there at the bottom.

ProcessorsToUse.Minimum = 1;
ProcessorsToUse.Maximum = Environment.ProcessorCount;
ProcessorsToUse.Value = Environment.ProcessorCount; // Use all processors.

This sample uses "Parallel LINQ" and here's the two queries. Notice the "WithDegreeofParallelism."

seqQuery = from n in names
where n.Name.Equals(queryInfo.Name, StringComparison.InvariantCultureIgnoreCase) &&
n.State == queryInfo.State &&
n.Year >= yearStart && n.Year <= yearEnd
orderby n.Year ascending
select n;

parQuery = from n in names.AsParallel().WithDegreeOfParallelism(ProcessorsToUse.Value)
where n.Name.Equals(queryInfo.Name, StringComparison.InvariantCultureIgnoreCase) &&
n.State == queryInfo.State &&
n.Year >= yearStart && n.Year <= yearEnd
orderby n.Year ascending
select n;

The .NET 4 Training Kit has Extensibility demos, and Office Demos and SharePoint Demos and Data Access Demos and on and on. It's great fun and it's a classroom in a box. I encourage you to go download it and use it as a teaching tool at your company or school. You could do brown bags, study groups, presentations (there's lots of PPTs), labs and more.

Hope you enjoy it as much as I do.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

.NET 4.1 Preview - New Base Class Library (BCL) Extension Methods - RFC

April 1, '09 Comments [16] Posted in ASP.NET | DLR | Javascript | Learning .NET | Microsoft | Musings | Open Source | PHP | Programming | Python | Silverlight | Source Code | Tools | VB | Web Services | Windows Client | XML
Sponsored By

As web programmers, we use a lot of strings to move data around the web. Often we’ll use a string to represent a date or an integer or a boolean. Basically "1" in instead of 1, or "April 1, 2009" rather than a proper ISO-8601 formatted culture-invariant date.

While these strings are flying around via HTTP it's not a huge deal, but sometimes this loose, even sloppy, use of strings can leak into our own code. We might find ourselves leaving the data times as strings longer and longer, or not even bothering to convert them to their proper type at all. This problem is made worse by the proliferation of JSON, and schema-less/namespace-less XML (that I've often called "angle-bracket delimited files" as they're no more useful than CSVs in that point.

.NET 4.0 is pretty much locked down, but version 4.1 still has some really cool "Futures" features that are being argued about. If we don't know the type of a string, or we want to leave the string, as a string, longer than usual, what if we had an class that could be both a string and another type, essentially deferring the decision until the variable is observed. For example:

StringOr<int> userInput= GetUserInput("Quantity"); 
string szUserInput=userInput.StringValue; 
int intUserInput=userInput.OtherValue;

Sometimes you just don't know, or can't know.

This reminds me of a similar, but orthogonal physics concept, that of the Heisenberg Uncertainty Principle. Sometimes you know that an object is a string, and sometimes you know how long it is, but you can’t know both at the same time.

One of my favorite jokes goes:

Heisenberg gets pulled over by the police. The officer asks, “Do you know how fast you were going?” Heisenberg answers, “No, but I know exactly where I am!”

This library doesn't solve THAT issue, with respect to strings, but we’ve got folks in DevDiv working on this and many other metaphysical - and physical - problems as they apply to computer science.

Big thanks to Eilon, who's working hard to get this pushed into the .NET 4.1 Base Class Library. Visit Eilon's blog for more details on this new library, more code, graphics and details on how Intellisense will handle this new case.

Hopefully, someone is working to make this important new library Open Source.

Your thoughts, Dear Reader?

Related Posts

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

BizSpark - Free Software and Production Licenses for Startups in the Startup Phase

January 27, '09 Comments [21] Posted in ASP.NET | ASP.NET MVC | Cloud | Programming | VB | Windows Client
Sponsored By

BizSpark LogoLast November, Microsoft started a new program called BizSpark for startups that's pretty sweet. It's pretty not-too-evil also.

If you are a small business and you sell a product or service to your customers, you might want to check it out. Here's the criteria:

  • Actively engaged in development of a software-based product or service that will form a core piece of its current or intended business.
  • Privately held, and in business for less than 3 years.
  • Less than US $1 million in annual revenue.

What do you get?

Here's what you get from the program:

Development Tools, Platform Technologies and Production Licenses

  • All the software included in the Microsoft® Visual Studio® Team System Team Suite (VSTS) with MSDN Premium subscription
  • Expression Studio Version 2
  • VSTS Team Foundation Server (standard edition)
  • Production use rights to host a “software as a service” solution (developed during participation in the BizSpark Program, on any platform) over the Internet, with regard to the latest versions of Microsoft products including:
    • Microsoft Windows Server® (all editions up to and including Enterprise)
    • Microsoft SQL Server (all editions)
    • Microsoft Office SharePoint Portal Server
    • Microsoft System Center
    • Microsoft BizTalk Server
    • Microsoft Dynamics CRM (coming soon)
  • In addition to the core program offering, BizSpark startups will be eligible for other Microsoft offerings, such as:
    • Microsoft Azure Services Platform - The Azure Services Platform is the collection of Foundational, Developer and Live Platform Service such as Windows Azure, Live Mesh, Compute Services, Storage Services, Workflow Services, Identity Services, Connectivity Services, SQL Data Services. All developers will have access to the Azure Services Platform developer tools which includes the local development fabric.

After three years, they assume you've either succeeded and are making money, or you're gone. If you're around and you want to continue, you pay for your MSDN subscriptions the regular way, and if you want to keep using your production licenses, you pay for those using the Service Provider Licensing program.

If you want in, you need to find a sponsor, and there's a list on the site. If you can't find one, though, Bill Staples (a General Manager at MSFT) can sponsor you (details on his site, click "Contact Me" under his picture) which is nice of Bill.

BizSpark is for companies that SELL something (product or service), not for pure consulting companies, but if your consulting company has at least one product or service, that appears to meet the criteria.

I asked folks on Twitter to see if they were using it and if it was a good thing, and everyone said it was a good program. It's a messed up economic time, and I think BizSpark would be an easy way to get a small business or startup idea of the ground without thinking about software licensing for 3 years. If you've got an idea for a business, or you already have a business, this could be the program for you. Tell Bill I sent you (he's one of my many bosses, so be nice and don't get me sacked) and he'll help you get setup.

Are you in this program? Is it a good thing? Leave a comment.

Update: The guy at MSFT who runs the program is Julien Codorniou and feel free to email him at julienco at microsoft.com with questions. Mention my name for free candy (not really).

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

The Weekly Source Code 31- Single Instance WinForms and Microsoft.VisualBasic.dll

August 2, '08 Comments [19] Posted in Learning .NET | Source Code | VB | Windows Client
Sponsored By

I got an interesting question recently emphasis mine:

I am regular reader of you blog. I need some help in single instance winform. I have to open application when a file (.ext) is clicked (File is associated with that application like .doc with WINWORD). Application should be single instance. When I click the .ext file it should open the application with that content. If an instance is runnng it should ask the user whether you want to close this application and then open the new .ext file. Need help in C#.

Some questions are more interesting than others, but I think we've all had to solve this "Single Instance" problem over and over again over the last 15 years. I did this with a Dan Appleman VBX in Visual Basic 3 and I've seen piles of solutions with Mutexes and all sorts of overly complex dancing to solve this apparently simple problem. This is a really old technique, but three years later, there's just not enough people that know that the WindowsFormsApplicationBase class exists and has a lot of useful functionality in it.

There was an interesting thread over here about handling this. Someone asked the question and someone said "WinForms 2.0 has support for single instance apps built in." and the next guy said "Only for Visual Basic applications, though."

Microsoft.VisualBasic.dll has got to be one of the most useful standard installed parts of the .NET Framework out there. Folks are afraid to reference it from C#. It feels wrong.

Kind of like busting out with French words in the middle of English sentences, referencing Microsoft.VisualBasic.dll has that je ne sais quoi that tends to give C# folks a feeling of mal de mer but that assembly has a specific raison d'être. See? Feels wrong, but it still works. There's good stuff in Microsoft.VisualBasic.dll, and just because it isn't System.Something doesn't mean you shouldn't reference it with abandon. Go nuts.

Back to the problem. There's many examples, but the easiest one I've seen was over at OpenWinForms.com and it was written in C# referencing Microsoft.VisualBasic.dll. I've modified it here to make a single instance app that will open a text file name passed in on the command line. If you call the same application a second time, it'll take the new command line argument and load that text file in the first instance.

Launching it as "SuperSingleInstance foo.txt" from a command line...

Single Instance

Then, from the same command line, while the first one runs, launching a second "SuperSingleInstance bar.txt" from a command line. The first instance is reused, brought to the front, and gets an event letting us know someone tried to launch us and that event includes the new command line.

Single Instance (2)

The code is really cool as all the work is in WindowsFormsApplicationBase. It's a little confusing because you have to call a controller instance and tell it about your MainForm, rather than calling Application.Run(). The StartupNextInstance event is called in your first application when a second instance of your app gets fired up. It talks cross process between the new second instance and your original one and passes over the command line.

using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;

namespace SuperSingleInstance
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string[] args = Environment.GetCommandLineArgs();
SingleInstanceController controller = new SingleInstanceController();
controller.Run(args);
}
}

public class SingleInstanceController : WindowsFormsApplicationBase
{
public SingleInstanceController()
{
IsSingleInstance = true;

StartupNextInstance += this_StartupNextInstance;
}

void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
{
Form1 form = MainForm as Form1; //My derived form type
form.LoadFile(e.CommandLine[1]);
}

protected override void OnCreateMainForm()
{
MainForm = new Form1();
}
}
}

The Form is trivial, just loading the text from the file into a TextBox.

using System;
using System.Windows.Forms;
using System.IO;

namespace SuperSingleInstance
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
string[] args = Environment.GetCommandLineArgs();
LoadFile(args[1]);
}
public void LoadFile(string file)
{
textBox1.Text = File.ReadAllText(file);
}
}
}

There's other nice functionality in WindowsFormsApplicationBase like support for SplashScreens and network availability events. Again, check out the good stuff over at http://www.openwinforms.com/, like the Controller I used in this post.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web
Page 1 of 2 in the VB category Next Page

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.