Scott Hanselman

The Weekly Source Code 45 - Kicking Butt on Windows 7 *and* Windows XP

September 01, 2009 Comment on this post [11] Posted in Source Code | Win7 | Windows Client
Sponsored By

image I really advocate folks reading as much source as they can because you become a better writer by reading as much as writing. That's the whole point of the Weekly Source Code - reading code to be a better developer.

There's a very cool developer context going on right now called "Code7." If you code a Windows 7 application between now and October 7 you could win a giant bag of money and/or a trip to PDC.

There's a pile of new APIs in Windows 7 (as well as existing and useful Vista APIs) like these:

  • Windows 7 Taskbar Integration
  • Transactional File System
  • I/O Optimization
  • Event Tracing for Windows (ETW)
  • Windows 7 Libraries
  • Windows 7 Sensor and Location Platform
  • Aero Glass

In some of these instances, there isn't hardware (yet) for things like Ambient Light Sensors. One dude has taken a Webcam and hooked it into the Windows 7 Sensors API and made a program to dim his monitors with the new Monitor Configuration API*. He might even make it turn off his machine when he walks away.

XP2Win7 - Windows 7 Sample Code/Application

I've been checking out what sample applications there are to start learning about Windows 7. The coolest so far as been the "PhotoView" application. Don't sweat the fact it's YAPA (Yet Another Photo Application) and consider it a loosely confederated collection of samples.

MainWindow

What's cool about this application is that it works on Windows XP and Windows Vista and Windows 7. This may be obvious and even a silly statement to you, Dear Reader, but it's a nice reminder that and app can be awesome on all three platforms. 99% of the apps that I use work great on Windows 7. Sure, some drivers and wacky VPN things will need to be updated, but it's comforting to me to know I can write an app for Windows that will, um, work on Windows. ;)

This PhotoView application, also called XP2Win7 is written managed code and uses plugins to "light up on up-level platforms." That's fancy Microsoft talk that means if your operating system has a feature the app will detect it and use it.

There's a great overview Word Document that explains the app and how it is written. The MSI will install the app, then optionally the source in ~\MyDocuments\Xp2Win7 if you have trouble finding it. You'll need Visual C++ if you want to build a few parts...just read the readme. It's a pretty extraordinarily broad sample with examples on how to make MMC ReportViewer snapins, delayed services, register scheduled tasks, piles.

(Unfortunately the guys that wrote this didn't use MEF for their plugin model, but I'll talk to them. It would allow them to remove a lot of boilerplate plugin monkey code.)

It uses the Windows API Code Pack (I talk about this below) to do a lot of its work. Here's a few fun parts.

TaskBar JumpLists

When the app is run under Windows 7 it includes "jumplists" when you right-click (or swipe-up) on the taskbar button:

image

This is easily added with the Taskbar API. Notice the multiple categories, user tasks, recent items, and custom categories.

Taskbar.JumpList.CustomCategories.Clear();
Taskbar.JumpList.UserTasks.Clear();
Taskbar.JumpList.KnownCategoryToDisplay = KnownCategoryType.Recent;

CustomCategory allAlbumsCategory = new CustomCategory("All Albums");
//...snip out enumerating of the filesystem to get photo albums
Taskbar.JumpList.CustomCategories.Add(allAlbumsCategory);

Taskbar.JumpList.UserTasks.Add(
new JumpListLink()
{
Title = "Reset configuration",
Path = typeof(XP2Win7.VistaPlugins.ConfigurationResetter.Program).Assembly.Location,
Arguments = XP2Win7.VistaPlugins.ConfigurationResetter.Program.ResetCommand
});
Taskbar.JumpList.UserTasks.Add(
new JumpListLink
{
Title = "Launch indexing task",
Path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Constants.ServiceCommandLine),
Arguments = Constants.ServiceAsTaskCommandLine
});
Taskbar.JumpList.UserTasks.Add(
new JumpListLink { Title = "Open albums directory", Path = Host.UserConfiguration.AlbumRepositoryPath });

Taskbar.JumpList.RefreshTaskbarList();

Windows 7 Libraries

You can also add Windows 7 Libraries for your application:

//Create new shell library under the default Libraries
using (ShellLibrary library = new ShellLibrary("XP2Win7", true))
{
library.LibraryType = LibraryFolderType.Pictures;
library.IconResourceId = GetPictureLibraryIcon(); //Set the same Icon as the Picture library
library.IsPinnedToNavigationPane = true;


foreach (string folderPath in GetPicturesFolders())
{
library.Add(folderPath);
}

library.ShowManageLibraryUI(Application.Current.MainWindow,
"Manage the XP2Win7 library", "You can manualy add or remove folders",
true);
}

User Access Control (UAC)

Windows Vista and Windows 7 both include User Access Control (UAC). You'll recognize the little shield icon next to a button that will require a prompt from the user in the dialog below.

Application reconfiguration

Their application uses this in a few places. First, can we even show the little shield? We only want to do that if UAC is enabled:

protected override BitmapSource BitmapSource
{
get
{
if (UacHelpers.UserAccountControl.IsUacEnabled)
{
return Microsoft.SDK.Samples.VistaBridge.Library.StockIcons.StockIcons.Shield;
}
else
{
return ImageFromResource(Assembly.GetExecutingAssembly(),
"UserAccountControl.StartService-128x128.png");
}
}
}

Then, if they do click the button, and we want to launch some process as Administrator, we'll need to call a special API to do that. This is mean easy by helper APIs.

if (UacHelpers.UserAccountControl.IsUacEnabled || !UacHelpers.UserAccountControl.IsUserAdmin)
{
UacHelpers.UserAccountControl.CreateProcessAsAdmin(
typeof(ServiceStarter.Program).Assembly.Location, "XP2Win7ImageDataService");
}
else
{
Process.Start(typeof(ServiceStarter.Program).Assembly.Location, "XP2Win7ImageDataService");
}

Pretty slick and easy to code. The Windows API Code Pack makes all these APIs and dozens more easy for managed code developers (C#, VB, and everyone else.)

Windows API Code Pack

Another great pile of Windows sample code is the Windows API Code Pack. This thing is a gold mine of samples and they are all in C# and VB. There's like 20+ samples. Here's a few:

Power Management

It's nice if your app knows the power status of the machine it's on and avoid doing crazy stuff if it's on batteries.

Power Management

You can get all sorts of great power-related info:

private void GetPowerSettings()
{
settings.PowerPersonality = PowerManager.PowerPersonality.ToString();
settings.PowerSource = PowerManager.PowerSource.ToString();
settings.BatteryPresent = PowerManager.IsBatteryPresent;
settings.UpsPresent = PowerManager.IsUpsPresent;
settings.MonitorOn = PowerManager.IsMonitorOn;
settings.MonitorRequired = PowerManager.MonitorRequired;

if (PowerManager.IsBatteryPresent)
{
settings.BatteryShortTerm = PowerManager.IsBatteryShortTerm;
settings.BatteryLifePercent = PowerManager.BatteryLifePercent;

BatteryState batteryState = PowerManager.GetCurrentBatteryState();

string batteryStateStr = string.Format(
"ACOnline: {1}{0}Max Charge: {2} mWh{0}Current Charge: {3} mWh{0}Discharge Rate: {4} {0}Estimated Time Remaining: {5}{0}Suggested Critical Battery Charge: {6} mWh{0}Suggested Battery Warning Charge: {7} mWh{0}",
Environment.NewLine,
batteryState.ACOnline,
batteryState.MaxCharge,
batteryState.CurrentCharge,
batteryState.ACOnline == true ? "N/A" : batteryState.DischargeRate.ToString() + " mWh",
batteryState.ACOnline == true ? "N/A" : batteryState.EstimatedTimeRemaining.ToString(),
batteryState.SuggestedCriticalBatteryCharge,
batteryState.SuggestedBatteryWarningCharge
);

settings.BatteryState = batteryStateStr;
}
}

There's also lots of power-related events you can be notified of:

PowerManager.IsMonitorOnChanged += new EventHandler(MonitorOnChanged);
PowerManager.PowerPersonalityChanged += new EventHandler(
PowerPersonalityChanged);
PowerManager.PowerSourceChanged += new EventHandler(PowerSourceChanged);
if (PowerManager.IsBatteryPresent)
{
PowerManager.BatteryLifePercentChanged += new EventHandler(BatteryLifePercentChanged);

// Set the label for the battery life
SetLabelButtonStatus(batteryLifePercentLabel, string.Format("{0}%", PowerManager.BatteryLifePercent.ToString()));
}

PowerManager.SystemBusyChanged += new EventHandler(SystemBusyChanged);

Stock Icons

A lot of folks don't realize that there's a pile of stock icons that are available in Windows and you can access them programmatically.

image 

That means if you need the stock icon for a BluRayRom or a ZipFile, you can just ask for it.

Task Bar Progress

One of the nicest subtle features of Win7 is that if you've got a Progress Bar doing something in your application you can make its progress known in the Taskbar icon itself. This is fantastic for long-running processes like file copies, etc.

Notice the progress bar in this application and the taskbar button in the bottom right reflects it.

image

There's also icon/image overlays and other nice touches. Even better, this is epic-easy:

// When the user changes the trackBar value,
// update the progress bar in our UI as well as Taskbar
progressBar1.Value = trackBar1.Value;

TaskbarManager.Instance.SetProgressValue(trackBar1.Value, 100);

Since your app can have multiple progress bars, you have to manually decide what you want the taskbar progress to look like.

Core Helpers

Finally there's some nice "CoreHelpers" to make your applications easy to read and run on XP, Vista and Win7 at the same time:

//example
if (CoreHelpers.RunningOnXP()) { ... }
//example
if (CoreHelpers.ThrowifNotWin7() { ... }
// and all the others you'd expect for XP, Vista, Win7

I've just touched the surface of these samples. If you're doing Windowe Client development be sure to check out http://windowsclient.net/ and http://www.msdn.com/windows for more and start writing your application for the https://www.code7contest.com.

1. Get Windows 7 and the SDK

2. Develop and Test Your Application

3. Get the Windows 7 Logo

4. Light Up Your Application with Windows 7

Related Links

* Note the (lightweight) parameter I passed into this MSDN URL. Check out the new "Lightweight" MSDN Library and give the team feedback on the site!

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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Amazon Kindle vs. Amazon Kindle DX - The Final Word

August 29, 2009 Comment on this post [33] Posted in Reviews
Sponsored By
Amazon Kindle vs. Amazon Kindle DX

I'm absolutely thrilled with my Amazon Kindle. I read it every night and have probably bought a dozen books with it, several newspapers and I read many dozen PDFs. I own the standard-sized Amazon Kindle 2 - it's the little one in the picture on the right.

The Kindle 2 is 8" x 5.3" x 0.36" but the screen is 6" diagonally. It's got a 600x800 pixel display, so that's 167 dpi with 16 grays. As a comparison, you monitor is likely 96dpi, possible 120dpi. An iPhone is 163 dpi.

The Kindle DX is 10.4" x 7.2" x 0.38" and the screen is 9.7" (yes, nearly 10"!) diagonally. It's spendy, but the screen is MASSIVE. That's 1200 x 824 pixel resolution at 150 dpi. It's got 4gig internal storage which I've found is effectively unlimited.

The screen on a Kindle is EXTREMELY clear. It's not backlit and it's not an LCD. It's e-ink and it's totally unique when you see it. It's very very close to paper and once you've started reading you really do forget it's not paper. There's zero eye strain, or no more than a regular book.

Let's get serious on size and layout here. The real tragedy of the Kindle is the bezel. That's the space between the screen and the edge. I don't know what the technical limitations are and I don't really care. There's just WAY to too much "whitespace" between the edge of the kindle and the screen itself. It's distracting and it's wasteful. There's easily enough room on the Kindle 2 to make the screen a 7" screen just by tightening up that space. Also, the keyboard on the Kindle 2 uses far too much vertical space.

Here's a screenshot taking from the Kindle 2 of a book. Notice that it starts with the word "morning" and ends with "duration, so the."

screen_shot-35927

Here's the same book, same point, starting with "morning" on the Kindle DX. The "so the" appears right in the middle of this screen. Effectively you can fit double the text on the page of the Kindle DX.

screen_shot-64748 

Also, the Kindle DX has native PDF support. That means you can just plug it in over USB, copy a PDF and boom, you're viewing it. It works for 95% of PDFs, but every once in a while I've had it fail. Rare, and usually it's because there's some advanced PDF feature being used that the Kindle doesn't support. The failures have only been on internal documents that have annotations and stuff. I don't know what the real limitations of the PDF support are, but I'm sure they're improving it constantly, and the Kindle can update it's OS over the 3G network, so those updates will presumably just happen.

Here's a screenshot of a PDF taken from the Kindle DX. It's totally readable. It would be totally NOT readable on the non-DX Kindle for two reasons. First, no PDF support built in, and two, if it was converted to Kindle-format, it'd be destroyed.

screen_shot-64745 

In English, this means if you're wanting to read technical books, you get a Kindle DX. Period. The small-size Kindle 2 is fantastic for prose and horrible for charts, graphs and code.


Kindle Thickness 

If you're torn between the two, it's understandable. After having used both for a week, I am also. The Kindle DX is too big and the Kindle is too small. By too small,I mean, the Kindle should have the SAME size and a larger screen. I could totally see another Kindle that's in between sizes, but I know that'll never happen, which is a shame.

Kindles Side By Side 

Bottom Line

If you're interested in a Kindle, and you read a lot of PDFs or non-Amazon eBooks, get the Kindle DX. If you read fiction and rarely, if ever, need PDF support (or only need the basics) then get the little Kindle.

While the DX is large, its PDF support is so nice that I'm compelled to prefer the DX over the little one, for myself. 

Related Posts

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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Hanselminutes Podcast 176 - NServiceBus with Udi Dahan

August 21, 2009 Comment on this post [5] Posted in Podcast
Sponsored By

Udi Dahan My one-hundred-and-seventy-sixth podcast is up. Udi Dahan is an Enterprise Development Expert and also the author of NServiceBus. Udi educates Scott on how a service bus works, and how it fits into a world of brokers, workflows and services.

Subscribe: Subscribe to Hanselminutes Subscribe to my Podcast in iTunes

Download: MP3 Full Show

Do also remember the complete archives are always up and they have PDF Transcripts, a little known feature that show up a few weeks after each show.

Telerik is our sponsor for this show.

Check out their UI Suite of controls for ASP.NET. It's very hardcore stuff. One of the things I appreciate about Telerik is their commitment to completeness. For example, they have a page about their Right-to-Left support while some vendors have zero support, or don't bother testing. They also are committed to XHTML compliance and publish their roadmap. It's nice when your controls vendor is very transparent.

As I've said before this show comes to you with the audio expertise and stewardship of Carl Franklin. The name comes from Travis Illig, but the goal of the show is simple. Avoid wasting the listener's time. (and make the commute less boring)

Enjoy. Who knows what'll happen in the next show?

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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Hanselminutes Podcast 175 - Optimizing Your Website with Jeff Atwood and Stackoverflow

August 17, 2009 Comment on this post [6] Posted in ASP.NET | ASP.NET MVC | Podcast
Sponsored By

JeffAtwood My one-hundred-and-seventy-fifth podcast is up. It's the return of Jeff Atwood. He and the team have been making lots of great speed optimizations to Stackoverflow lately. What tools are they using? What kinds of speed improvements are they seeing, and what can you do to exploit their experience?

Subscribe: Subscribe to Hanselminutes Subscribe to my Podcast in iTunes

Download: MP3 Full Show

Do also remember the complete archives are always up and they have PDF Transcripts, a little known feature that show up a few weeks after each show.

Telerik is our sponsor for this show.

Check out their UI Suite of controls for ASP.NET. It's very hardcore stuff. One of the things I appreciate about Telerik is their commitment to completeness. For example, they have a page about their Right-to-Left support while some vendors have zero support, or don't bother testing. They also are committed to XHTML compliance and publish their roadmap. It's nice when your controls vendor is very transparent.

As I've said before this show comes to you with the audio expertise and stewardship of Carl Franklin. The name comes from Travis Illig, but the goal of the show is simple. Avoid wasting the listener's time. (and make the commute less boring)

Enjoy. Who knows what'll happen in the next show?

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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Hanselminutes Podcast 174 - Hanselminutiae-five with Richard Campbell

August 14, 2009 Comment on this post [7] Posted in ASP.NET | Podcast
Sponsored By

richard_headshot_webMy one-hundred-and-seventy-fourth podcast is up. In this slightly unusual episode, I sit down with my good friend Richard Campbell and we share stories about scaling large websites over the years. I thought this was a really good show, if a little long and I'm thinking to have Richard on as a regular thing, if he's interested.

Subscribe: Subscribe to Hanselminutes Subscribe to my Podcast in iTunes

Download: MP3 Full Show

Do also remember the complete archives are always up and they have PDF Transcripts, a little known feature that show up a few weeks after each show.

Telerik is our sponsor for this show.

Check out their UI Suite of controls for ASP.NET. It's very hardcore stuff. One of the things I appreciate about Telerik is their commitment to completeness. For example, they have a page about their Right-to-Left support while some vendors have zero support, or don't bother testing. They also are committed to XHTML compliance and publish their roadmap. It's nice when your controls vendor is very transparent.

As I've said before this show comes to you with the audio expertise and stewardship of Carl Franklin. The name comes from Travis Illig, but the goal of the show is simple. Avoid wasting the listener's time. (and make the commute less boring)

Enjoy. Who knows what'll happen in the next show?

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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

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