Scott Hanselman

How to delete Open or Insecure Wi-Fi HotSpots from Windows 8: Wifi.exe Command Line Utility with Source

June 6, '13 Comments [19] Posted in Open Source | Tools | Win7 | Win8
Sponsored By

image

For the most part I'm happy with Windows 8 but one feature was removed that makes no sense to me - the wireless networks dialog.

Sure, you can "Forget this network" by right clicking on a Wi-Fi Connection, but only when that network is in range. The old Wireless Networks dialog where you could add and remove networks is gone. Who knows how many saved Wi-Fi hotspot profile I have littering my system?

So, The Problem: I want to remove saved Wi-Fi Profiles whenever I feel like it. I wrote a command line util that will work in Windows 7 and Windows 8.

TL;DR Version

There's a build zipped up of Wifi.exe available here and the source is on GitHub.

UPDATE: I've put Wifi-Manager up on Chocolately so you can now "cinst wifi-manager." Thanks to Brendan Forster for the heavy lifting! Learn more about the Chocolatey package manager here!

Caveats and "Ya I know."

First, let me be clear that I have written a command line utility to replace another command line utility. I get it. I knew it when I did it. Others smarter than I have done similar things and written utilities that match their way of thinking rather than learning an unintuitive syntax. Don't hate the playa, hate the Regular Expression.

Aside: This is also a problem with my iPhone. I likely have 50+ saved Wi-Fi spots on my phone and no way to delete them without jail-breaking.

You can access Wi-Fi profiles with the netsh.exe that comes with Windows, so you could list out profiles like this:

c:\>netsh wlan show profiles

Profiles on interface Wi-Fi:

User profiles
-------------
All User Profile : Wayport_Access
All User Profile : HANSELMAN
All User Profile : HANSELMAN-N
All User Profile : HanselSpot
All User Profile : EliteWifi
All User Profile : Qdoba Free Wifi

Then, for each one, call

c:\>netsh wlan show profile "Qdoba Free Wifi"

Profile Qdoba Free Wifi on interface Wi-Fi:
=======================================================================

Profile information
-------------------
Version : 1
Type : Wireless LAN
Name : Qdoba Free Wifi
Control options :
Connection mode : Connect manually

Connectivity settings
---------------------
Number of SSIDs : 1
SSID name : "Qdoba Free Wifi"
Network type : Infrastructure

For each of these profiles, check if they are secure or open, and if you are connecting manually or automatically. Then, if you wanted, you could netsh wlan delete profile name="Qdoba Free Wifi" and remove a profile, even when it's not near you.

In my recent podcast with security expert Troy Hunt, he pointed out that it's easy to create a fake honeypot Wi-Fi spot that has the same name as a common open network, like Starbucks, for example.

  • Given: If my PC or phone is set up to automatically connect to any open hotspot named "Starbucks" then it will just connect to one...even an evil hotspot.
  • Therefore: it would be nice to automatically delete profiles for Wi-Fi spots that are both open (no security) and set to automatically connect.

I was tired, so I thought I'd bang out a little utility to do this. I could have used PowerShell or something but I felt like using C#. It's exercise.

UPDATE: Lee Holmes went and wrote it in PowerShell! Amazing.

Wifi.exe and it's Usage

Tired of reading? There's a build zipped up of Wifi.exe available here and the source is on GitHub. You may need to Right Click | Properties | Unblock the zip.

There's no warranty. The code sucks and I'm a horrible person and you're running a util you found on my blog. However, it works awesome on my machine. Issues appreciated, tidy PRs appreciated more, running Resharper and doing a PR, less so. I'll update the build if good bugs require it.

If you run Wifi.exe (I put it in my path) you'll see something like this:

c:\>wifi
AP-guest manual WPA2PSK
HANSELMAN-N auto WPA2PSK
HANSELMAN auto WPA2PSK
HanselSpot auto WPA2PSK
Qdoba Free Wifi manual open
Wayport_Access auto open Warning: AUTO connect to OPEN WiFi

Delete WiFi profiles that are OPEN *and* AUTO connect? [y/n]
n

Notice the columns, and the prompt. There's a warning when a hotspot is both open and set to auto-connect. If you answer Y to the prompt, the utility will delete that profile. You can also type 'wifi /deleteautoopen' to bypass the prompt and auto-delete just profiles that are auto and open.

A pull request a few minutes after I pushed this code also added the ability to

wifi delete "HOTSPOTNAME"

which is nice also. Thanks!

The Code

One of the great things about writing command line apps like this is that there's literally a dozen ways to do everything. They are trivial and silly but also useful and used daily. In this case I've got command line argument processing to think about, parsing output from a spawned process, doing the parsing in a clean way, making sure it works on a non-English machine (which I thought about but didn't test), as well as cleaning up of generated temp files.

It's hardly impressive code, but some of it was fun or interesting. Here's a few bits I liked.

Making Columns with Console.WriteLine and String.Format

Did you know that you can right- and left-align columns within a fixed with using String.Format? Few people know about this and I've seen whole libraries written custom to do the work that's built right in.

Console.WriteLine(String.Format("{0,-20} {1,10} {2,10} {3,30} ", a.Name, a.ConnectionMode, a.Authentication, warning));

Note the {0,-20} (left aligned) and the {1,10} (right aligned). Those are just like {0} and {1} in a String.Format but they include alignment and width.

Gratuitous use of Linq

It wouldn't be a silly utility without in crazy LINQ, eh? Who needs Regular Expressions when you can when you can do a SQL query over your string? ;) Actually, I don't know if this is a good thing or not. It was fun, though, and it works. Your thoughts?

This takes the output from wlan show profiles (seen above) and parses it into a list of just the AP Names. I think it should work in any language, assuming the : colons are there.

string result = ExecuteNetSh("wlan show profiles");
var listOfProfiles = from line in result.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)
where line.Contains(":")
let l = line
where l.Last() != ':'
select l.Split(':')[1].Trim();

foreach (string profile in listOfProfiles)
ExecuteNetSh(String.Format("wlan export profile \"{0}\" folder=\"{1}\"", profile, Environment.CurrentDirectory));

Cleaning up the temp XML files

I export a bunch of very specific XML files with a VERY non-specific extension. I can't control their file name and I don't want guess what their name is because I would need to recreate their AP Name encoding scheme. Instead, I look for any XML files in the current folder (given the rare chance that YOU, the utility runner, have XML files in the same folder already) and only delete the ones with the namespace that I know to be present in Wi-Fi profiles. I patted myself on the back for this one, but just lightly.

static XNamespace ns = "http://www.microsoft.com/networking/WLAN/profile/v1";

//Delete the exported profiles we made, making sure they are what we think they are!
foreach (string file in Directory.EnumerateFiles(Environment.CurrentDirectory, "*.xml"))
if (XElement.Load(file).Name.Namespace == ns)
File.Delete(file);

Capturing Command Line Output

Finally, here's how you get the output of a command line process you started:

Process p = new Process();
p.StartInfo.FileName = "netsh.exe";
p.StartInfo.Arguments = arguments ?? String.Empty;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();

string output = p.StandardOutput.ReadToEnd();
return output;

Pretty basic, but useful to bookmark.

Alternatives

After I wrote this I noticed there are some WinForms utilities to do this. That's great. I wouldn't mind making may own, except I'd want it to look exactly like the Windows 7 dialog. It'd be fun just to see if I could get it pixel perfect.

Feel free to go check out the code, play with it and make fun of me. https://github.com/shanselman/Windows-Wifi-Manager


Get Involved! Check out my latest production with TekPub. A meticulously edited TWO HOURS of video content where we cover everything we think a developer should know to "Get Involved" in the developer community.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is 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

RELEASED - Download Internet Explorer 10 for Windows 7

February 26, '13 Comments [58] Posted in ASP.NET | HTML5 | Win7
Sponsored By

IE10 for Windows 7Just about a month ago the IEBlog published a post to allow business to manage the update schedule for Internet Explorer 10. It says "this approach lets organizations control when they are ready to deploy IE10 to their Windows 7 users." I took from this that IE10 on Windows 7 was imminent.

Today it's out. You can download IE10 for Windows 7 now. The details are over at the IE blog.

In the next few weeks and months Windows 7 machines will get automatically upgraded to IE10. For Web Developers like me, that means that between Windows 8 which already has IE10 and all these Windows 7 users who will now have IE10, that more people will have a modern browser than ever before.

IE10 was faster on my machine than IE9, and they say it is smarter about battery life. It also has IE10's upgraded JavaScript engine and includes spell check with auto-correct (finally!). Benchmarks are benchmarks but SunSpider implies about 40% faster than IE9, while PeaceKeeper looks like 25%. The V8 benchmark looks more like 100% faster. Point is, it's faster. How much faster? Depends on who you ask. Your mileage and machines will vary.

Once you've upgraded to IE10, go check out some of these sites. Be sure to view the source!

  • http://ie10bethethief.com - Robert Kirkman from Image Comics (You know him from The Walking Dead) also has a great comic I get each month on Comixology called Thief of Thieves.
    • This new site for Thief of Thieves not only has some great art (lots of SVG!) but also is a good example of using touch and the W3C Pointer Events standard. According to the IE blog, it also uses:
      • CSS3 animations for some of the larger scene transitions on the site
      • MSGesture API for handling more advanced pointer interactions like the safe cracking exercise
      • pageVisibility API to detect when an open page isn’t being actively used so we can control audio appropriately
      • setImmediate API to improve performance and power consumption on tablet devices. SetImmediate, like setInterval and setTimeout, is a timing API and requests the CPU to process the instruction as soon as it’s possible to.
  • Atari Arcade - Lots of classic Atari games, remade using HTML5 and Touch on the web.
  • Pulse - Very cool news aggregator done entirely in HTML5 with support for swipes and multi-finger gestures. Also works nice on mobile phones with responsive design.
  • Contre Jour - The 2011 iPad game of the year is now written in HTML5/JavaScript and CSS3. It works really well on touch systems like my Ultrabook. This originally came out in October but they've just added 20 new levels and it's free!

Developers

Enjoy!


Sponsor: Free eBook - 50 ASP. NET & SQL Server performance tips from the dev community, to help you avoid, find, and fix performance issues in your ASP.NET app. Download it from http://red-gate.com/50ways

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is 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

Guide to Installing and Booting Windows 8 Developer Preview off a VHD (Virtual Hard Disk)

September 14, '11 Comments [245] Posted in Tools | Win7 | Win8
Sponsored By

New Windows 8 Boot Manager?I've posted before about my intense love for Booting off a VHD (Virtual Hard Disk). It's lovely. Of course, once Hyper-V on the client happens, it will matter less, but for now, here I am, a guy with a perfectly good, working Windows 7 machine who wants to also run the Windows 8 Developer Preview.

I could do a few things to play with Windows 8. I could:

  • Try a virtualization solution, but it might not work, I may not have the drivers I need and it won't be as shiny as running "on the metal."
  • Sacrifice a machine I have lying around. I'll probably do that at some point, but I'd like to try it out on my actual hardware that I use all day long.
  • Swap out my C: drive and use my main machine. I don't have a tool-less case, and I'm also very lazy, so, um, ya.
  • Dual boot. Dual booting may feel ninja but it ALWAYS ends on tears. And sometimes blood.
  • Boot on real hardware from a Virtual Hard Disk.

Booting off a VHD is my current preferred solution for trying crazy stuff because the only speed hit I'll take is on the virtualized hard drive. Everything else is real hardware. I do this all the time with presentation VHDs and one-off daily builds of stuff.

Warranty

Of course, this is just some dude's blog. I puzzled this out and while booting to VHD is supported, messing with your boot manager - especially with Preview (that means, NOT RELEASE QUALITY) Software is a recipe for losing your job and a messy divorce. There's no warranty, express or implied. If you quake in fear from the following instructions, you need to STOP. It may be the case that you are actually a Non-Technical Friend and you don't realize it. Well, someone just told you. Please don't destroy your hard drive. I don't know you and I don't how how you got here. Stop calling. Jimmy no live here, you no call back!

Booting a Windows 8 VHD off a Windows 7 Primary System

These instructions come with the WORKS ON MY MACHINE seal of approvalWhew, now that's out of the way, let's void a few warranties, shall we?

Please note that there are a half dozen ways to do this. You can do it all from the command line using tools like ImageX, DISM, etc, or you can do a lot of it graphically with tools like BellaVista. This is just the way I did it. It's not gospel. I'm sure the folks in the comments will have much nicer ways. Take them all with a nice grain of sea salt. You can also SYSPREP the VHD directly from the ISO's WIM with IMAGEX if you know what that stuff means. It's a little subtle and requires you go get some tools. While my process  is a little baroque, it just needs the one ISO->USB tool.

Step 0 - Have a lot of Disk Space

I like to have a roomy VHD. You can make one that expands or you can make a fixed size. 40 gigs is usually enough, but I like 60 gigs as a nice round number, plus this is the Windows 8 Developer Preview with Developer Tools. If you don't have enough space when an expandable disk "bloats" itself to the fixed size on boot, it'll blue screen, so expandable or not, have the slack space.

Step 1 - Make a USB stick or DVD from the ISO

Go get the Windows 7 USB/DVD download tool and get yourself a USB stick that will hold at LEAST 10 gigs. I used a 16 gig one. Go through the process by pointing at the ISO you downloaded and then preparing your USB key. You can also use the resulting USB key to boot and install Windows 8 from your sacrificial hardware if you like.

Choose ISOChoose Media TypeInsert USB deviceCreating Bootable USB device

Step 2 - Make a Virtual Hard Drive

You can do this later in the process by pressing Shift-F10 while in the Setup Tool, but I like to prep things up front. You can do it from the Disk Management GUI or from DISKPART at the Administrator command line.

Be aware that your VHD needs to be on an internal drive or SATA drive. USB won't work as the drivers are initialized too late in the boot process.

Also, if your machine is BitLockered, your VHD needs to be on a non-BitLockered partition and you need to suspend BitLocker during this process. Also, know your recovery key because I don't know it.

2a. Start up an Administrator Console and run DISKPART. Execute the lines after DISKPART> below, changing them for your own system.

C:\Users\Scott\Desktop>diskpart

Microsoft DiskPart version 6.1.7601
Copyright (C) 1999-2008 Microsoft Corporation.
On computer: HEXPOWER7

DISKPART> create vdisk file=d:\VMs\Win8.vhd type=expandable maximum=60000

100 percent completed

DiskPart successfully created the virtual disk file.

DISKPART> select vdisk file=d:\VMs\Win8.vhd

DiskPart successfully selected the virtual disk file.

DISKPART> attach vdisk

100 percent completed

DiskPart successfully attached the virtual disk file.

DISKPART> create partition primary

DiskPart succeeded in creating the specified partition.

2b. OR do it from the Disk Management GUI:

Create and Attach Virtual Hard Disk

At this point, you've got a VHD that's empty, but ready to have Windows installed to it. The VHD and your system are NOT ready to be booted from. That will come in a minute.

Step 3 - Boot off the Windows 8 USB Key

Now, restart your computer with your new USB key plugged in and startup your BOOT MENU. The hotkey is usually F12 to bring it up. You want to boot off the Windows 8 USB key.

Side Note: Folks with Gigabyte Motherboards. These motherboards are notoriously hard to figure out a USB boot. You need to make sure that you USB key is only plugged into the board directly in the back. Then, don't use the Boot Menu, it never works. Instead, enter the BIOS with the DEL key and manually put your USB Key (it'll be detected by brand, so be prepared to recognize the string) at the top of the Hard Drive boot order.

Boot of your USB key

Step 4 - Attach the VHD while still inside SETUP

Pay attention here. Actually, hell, pay attention to the whole thing, it's subtle.

Start the SETUP process, click Install Not but DO NOT PICK A HARD DRIVE. As shown in this screenshot, instead hit SHIFT-F10 to get to a console. We want to attach our VHD and install to THAT instead.

Shift-F10 from within Windows 8 Setup

In the screenshot above I haven't touched anything, yet.

Below, I've run DISKPART and selected and attached the VHD with these now familiar commands:

DISKPART> select vdisk file=d:\VMs\Win8.vhd
DISKPART> attach vdisk

That will look like this screenshot.

DISKPART commands have been issued, but the drives aren't refreshed yet

Next, ALT-TAB back over to the list of disks and hit REFRESH. You'll see your VHD show up. Mine is the 60 gig one. That's the blank we are going to install to.

Now the 60 gig VHD is visible

Note that installation will warn you that this VHD can't be booted to. Yet. That's cool, go ahead and install to that empty VHD.

photo 4

At some point it'll ask you to restart the computer. The setup process isn't done yet, but go ahead and reboot and remove the USB key.

Your system should reboot and setup will continue, this time off the VHD.

NOTE: I had expected at this point to go and manually create a BCD entry using BCDEDIT.EXE from an Administrator command line as I did in my first post on booting to VHD but it seems that is all done for us now!

The Windows 8 Developer Preview build automatically noticed that I was trying to boot off a VHD and added a Windows Bootloader option and put the description in as "Windows Developer Preview," saving me a half dozen tedious steps. I was very pleasantly surprised! I'd like to hear if you had the same experiences, Dear Reader.

I could tell it was working because my C: drive is a totally silent SSD and my D: drive is spinning rust. When the setup continued I could totally hear the hard drive that holds the VHD spinning. The installation completed happily at this point with me having to manually create an entry with BCDEDIT.

I confirmed it with bcdedit.exe /v while running Windows 8 Developer Preview.

Setup completed, and I rebooted again to make sure I could get back into Windows 7.

In fact, I was shocked to find a completely new bootloader had come into play. I was literally open-mouthed staring at it. It's not text, it's graphical and friendly! It actually and literally "did the right thing." Awesome.

This seems to be the Windows 8 boot manager that you'll see if Windows 8 Developer Preview is the default. Otherwise you'll see the Windows 7 text-mode one first. Very cool. I hope it stays past the Developer Preview.

New Windows 8 Boot Manager?

Here's what you get if you click Other Options.

New Windows 8 Boot Manager?

That's it. To recap:

  1. Make an empty VHD
  2. Attach to the VHD just before installing Windows 8 Developer Preview
  3. Install to the VHD
  4. Rejoice

Hope this works for you, Dear Reader. I'm happily booting Windows 8 Developer Preview to VHD today.

One final disclaimer to be CRYSTAL CLEAR. I puzzled this process out with the same bits given out at http://dev.windows.com. I don't work for the Windows team and I don't know anyone over there. I have no idea if this will work in the future. I only know it worked on my home machine, tonight, once.

Related Links

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is 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. He is 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

How many PCs in the world have the .NET Framework installed?

January 20, '10 Comments [43] Posted in ASP.NET | Learning .NET | Microsoft | Win7 | Windows Client | WPF
Sponsored By

image I did a second .NET Framework features informal poll recently, and as with all .NET related polls the question comes up: How many PCs have the .NET Framework on it?

If you're a company that is considering creating a client application using .NET (not Silverlight, but the .NET Framework) you'd probably like to know if your end-user needs to install something extra to use your app.

So I started asking questions. We've said things here and there about the pervasiveness of the .NET Framework but I wanted to get the final word (at the time of this writing) and put it somewhere easy to fine.

After some digging, here's what I've got:

  • Well over 90% of the PCs in the world have some version of the .NET Framework installed.
  • Over 65% of Windows PCs in the world have .NET 3.5 SP1 installed.

This is a lot higher than I thought, and it's pretty cool.

The .NET Framework is smaller than you'd think (that's why I wrote SmallestDotNet). The very small .NET 4 Client Profile makes it easier (both speed and download size) to put .NET on a machine.

I think these numbers will help folks who might be considering using .NET for a client application.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is 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 5 in the Win7 category Next Page

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