Scott Hanselman

NuGet Package of the Week #3 - PhoneyTools for Windows Phone 7

March 21, 2011 Comment on this post [0] Posted in NuGet | NuGetPOW | Silverlight | WinPhone
Sponsored By

image Have you implemented the NuGet Action Plan? Get on it, it'll take only 5 minutes: NuGet Action Plan - Upgrade to 1.1, Setup Automatic Updates, Get NuGet Package Explorer.

The Backstory: I was thinking since the NuGet .NET package management site is starting to fill up that I should start looking for gems (no pun intended) in there. You know, really useful stuff that folks might otherwise not find. I'll look for mostly open source projects, ones I think are really useful. I'll look at how they built their NuGet packages, if there's anything interesting about the way the designed the out of the box experience (and anything they could do to make it better) as well as what the package itself does.

PhoneyTools includes new controls, classes and techniques for Windows Phone 7

I've heard that since NuGet is bundled with ASP.NET MVC that some folks think it's just for Web Development. This weeks package is one for Windows Phone 7. You can make packages for pretty much whatever you like. Looks like there are already 26 libraries that are tagged with "phone" on the NuGet site.

These tools are by Shawn Wildermuth and include a bunch of useful classes and controls that make Windows Phone application creation easier.

image

I'll fire up Visual Studio with Windows Phone Tools that I downloaded from http://create.msdn.com. (See how clean my Visual Studio looks? Yours can be tidy as well.)

My Totally Nothing Windows Phone 7 App

You can see that I created a totally basic do-nothing Windows Phone 7 application and that the NuGet Package Manager Console is docked at the bottom.

I type:

PM> Install-Package PhoneyTools
'SilverlightToolkitWP (≥ 4.2011.2.1)' not installed. Attempting to retrieve dependency from source...
Done.
Successfully installed 'SilverlightToolkitWP 4.2011.2.1'.
Successfully installed 'PhoneyTools 0.5'.
Successfully added 'SilverlightToolkitWP 4.2011.2.1' to WindowsPhoneApplication2.
Successfully added 'PhoneyTools 0.5' to WindowsPhoneApplication2.

Looks like PhoneyTools brought in the SilverlightToolkitWP as a dependency. If I want to poke around, I can double click on the NuPkg (which is associated with the NuGet Package Explorer you can get here with ClickOnce) and see what's going on.

NuGet Package Explorer - PhoneyTools.0.5 (11)

Looks like he's got his project's assembly as well as an install.ps1 and uninstall.ps1 in the tools folder. What's in there?

References to assemblies are added by convention automatically

The install.ps1 and uninstall.ps1 run automatically when you, ahem, install and uninstall. He's got a check for the version of NuGet in there (that looks like it was copy/pasted from one of my packages) as well as a manual stop to add a reference. That extra line for adding References is not needed. I know Shawn so I'm sure he'll be fine with me using this as a teaching moment as it's not 100% obvious how this new stuff works.

param($installPath, $toolsPath, $package, $project) 

if ($host.Version.Major -eq 1 -and $host.Version.Minor -lt 1)
{
"NOTICE: This package only works with NuGet 1.1 or above. Please update your NuGet install at http://nuget.codeplex.com. Sorry, but you're now in a weird state. Please 'uninstall-package PhoneyTools' now."
}
else
{
$project.Object.References.Add("AgiliTrain.PhoneyTools"); #don't need this
}

It might seem intuitive to add the reference manually, but assemblies that are in the lib folder will actually be added and removed automatically as references just because they are in the lib folder! There's no need to do it manually.

In fact, you can have one package that includes versions of assemblies for many different Framework Versions. From the NuGet documentation on Supporting Multiple .NET Framework Versions and Profiles:

\lib
\MyAssembly.dll
\MyAssembly.Core.dll
\Net40
\MyAssembly.dll

In projects that target the .NET Framework 2.0 and the .NET Framework 3.5, NuGet copies both MyAssembly.dll and MyAssembly.Core.dll. But in projects that target the .NET Framework 4, only MyAssembly.dll from the Net40 folder will be copied. If you want MyAssembly.Core.dll to be installed in a project that targets the .NET Framework 4, you must include it in the Net40 folder

For Silverlight, he should do:

lib    
\sl4
\AgiliTrain.PhoneyTools.dll

And when NuGet 1.2, he can use \sl4-wp. That way someone can release a package that includes a different payload for Silverlight 4 vs. Silverlight on the Windows Phone 7.

Playing with PhoneyTools

Now that I've got the PhoneyTools installed, what can I do? According to the PhoneyTools CodePlex project, this is a project that contains several classes and controls for use with Windows Phone 7 applications. There are plans for:

And the word is that he's targeting Mix for the first release. This release is in beta. There's nice simple utility stuff like automatically fading "toast" style messages...

FadingMessage.Show("Doing something important...");

That do what you'd expect (you can make them look like whatever)...

image

To more sophisticated controls like an alternative SelectSwitch:

SelectSwitch

And a SimpleLongListSelector Control that handles a lot of boring work for you and makes creating a giant long list with categories easy so that this XAML:

<my:SimpleLongListSelector x:Name="longList">
<my:SimpleLongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ImageUrl}"
Height="75" />
<TextBlock Style="{StaticResource PhoneTextNormalStyle}"
Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</my:SimpleLongListSelector.ItemTemplate>
</my:SimpleLongListSelector>

Along with this LINQ query against a data source:

// For Complex Object and ItemTemplate
var qry = from g in games
orderby g.Genre, g.Name
group g by g.Genre into genre
select genre;

longList.SetGroupingItemsSource<Game>(qry.ToList());

Gives you a nice clean result, and you can click on the category headers to quickly jump to another category.

ItemTemplate

There's lots more, and remember that we noticed the Silverlight Toolkit for Windows Phone "'SilverlightToolkitWP" was a NuGet package as well? There's lot of info on that Toolkit at Tim Heuer's blog as it contains useful controls and classes as well. Between Phoney and the Silverlight Toolkit I think I'm ready to write my app.

Please continue to insist on NuGet packages for useful stuff. Put pressure on the groups you work with and convince them this is a useful thing.

Also, please join me at TechEd 2011 in Atlanta as I present DEV338 NuGet: Microsoft .NET Package Management for the Enterprise!

I'm glad folks are using NuGet for more than just Web Apps. I hope you do to, Dear Reader.

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

Hanselminutes Podcast 257 - Selenium for Web Automation Testing with Jim Evans

March 21, 2011 Comment on this post [3] Posted in ASP.NET | Podcast | Tools
Sponsored By

image Scott chats with Jim Evans from the Selenium team about how to get into Web Automation Testing. What's new in Selenium v2? Can you use Selenium with any browser? How does .NET fit into the process? All this and more in this Web Testing Episode.

Download: MP3 Full Show

Links:

NOTE: If you want to download our complete archives as a feed - that's all 257 shows, subscribe to the Complete MP3 Feed here.

Also, please do take a moment and review the show on iTunes.

Subscribe: Subscribe to Hanselminutes or Subscribe to my Podcast in iTunes or Zune

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.

Building quality software is never easy. It requires skills and imagination. We cannot promise to improve your skills, but when it comes to User Interface and developer tools, we can provide the building blocks to take your application a step closer to your imagination. Explore the leading UI suites for ASP.NET AJAX, MVC, Silverlight, Windows Forms and WPF. Enjoy developer tools like .NET Reporting,ORM,Automated Testing Tools, Agile Project Management Tools, and Content Management Solution. And now you can increase your productivity with JustCode, Telerik’s new productivity tool for code analysis and refactoring. Visit www.telerik.com.

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

Entity Framework 4.1 Release Candidate with Go-Live (with Final Release to follow in a month)

March 17, 2011 Comment on this post [13] Posted in Channel9 | VS2010
Sponsored By
image

I was in Redmond this last week and talked to Jeff Derstadt, the Lead Developer on Entity Framework Code First (or, as I say, EF Magic Unicorn). What's the deal with this new feature in Entity Framework? What about the bad rap that EF got back in the day? What's new in EF4 and how does EF Code First sit on that? Which is the right choice, Model First, Database First or Code First? All of this plus demos in this off-the-cuff interview. There's lots of good info in this video including some insight into much needed migrations. Hint: They are working on them!

This week, the Entity Framework team put out a Release Candidate of Entity Framework 4.1, and are planning a final release in a month. Hm, what conference happens in a month?

The EF 4.1 RC is now publicly available (“ADO.NET Entity Framework 4.1 Release Candidate” for short, doh!) It's cool that they are able to do out of band releases for things like this, so we don't have to wait a year or more for new functionality.

Note that while CodeFirst is awesome, EF4.1 is not just about Code First, the DbContext API is equally applicable to Database First and Model First and EF 4.1 includes new code generation item templates for customers working with the EDM designer.

What’s in EF 4.1 RC?

From their blog, the ADO.NET Entity Framework 4.1 RC introduces two new features:

  • The DbContext API is a simplified abstraction over ObjectContext and a number of other types that were included in previous releases of the ADO.NET Entity Framework. The DbContext API surface is optimized for common tasks and coding patterns. DbContext can be used with Database First, Model First and Code First development.
  • Code First is a new development pattern for the ADO.NET Entity Framework and provides an alternative to the existing Database First and Model First patterns. Code First is focused around defining your model using C#/VB.NET classes, these classes can then be mapped to an existing database or be used to generate a database schema. Additional configuration can be supplied using Data Annotations or via a fluent API.

And an unfortunate but necessary NuGet gotcha, as the package as been renamed.

NuGet Package Rename

Previous releases of Code First were made available as the "EFCodeFirst" NuGet package. The EF 4.1 RC release contains features that are also applicable to Model First and Database First development, therefore we have chosen to adopt the "EntityFramework" package name for this release, and future releases. If you are currently using the "EFCodeFirst" package you will need to swap to the "EntityFramework" package to get the supported go-live release. If you own a package that depends on ‘EFCodeFirst’ we would encourage you to swap the dependency over to the ‘EntityFramework’ package as soon as possible.

Have you implemented the NuGet Action Plan? Get on it, it'll take only 5 minutes: NuGet Action Plan - Upgrade to 1.1, Setup Automatic Updates, Get NuGet Package Explorer.

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

NuGet Package of the Week #2 - MvcMailer sends mails with ASP.NET MVC Razor Views and Scaffolding

March 16, 2011 Comment on this post [20] Posted in ASP.NET | ASP.NET MVC | NuGet | NuGetPOW | VS2010
Sponsored By

Have you implemented the NuGet Action Plan? Get on it, it'll take only 5 minutes: NuGet Action Plan - Upgrade to 1.1, Setup Automatic Updates, Get NuGet Package Explorer.

The Backstory: I was thinking since the NuGet .NET package management site is starting to fill up that I should start looking for gems (no pun intended) in there. You know, really useful stuff that folks might otherwise not find. I'll look for mostly open source projects, ones I think are really useful. I'll look at how they built their NuGet packages, if there's anything interesting about the way the designed the out of the box experience (and anything they could do to make it better) as well as what the package itself does.

MvcMailer sends mails with ASP.NET MVC Razor Views and Scaffolding

I just love the idea behind this NuGet package. This is effectively a port/reimagining of the Rails ActionMailer with an ASP.NET twist. It's wonderful for a number of reasons.

First, because (and this is an ingredient for all great pieces of software) we've all had this idea but never implemented it! I've been talking about writing this for six months. Of course, Talk is Cheap, Show Me The Code. I'm thrilled I never wrote it because it wouldn't have been this good.

Second, because the way that the author, Sohan, has implemented this really builds on existing technologies in a very "LEGO" way. Great open source apps often build on other great ones cleanly. He's really avoided duplication by separating concerns and focused on just the new functionality MvcMailer adds.

clip_image002

There comes a time in every project when you need to email a user. Traditionally it (almost always sucks). As Sohan points out, it usually looks like this:

StringBuilder mailBody = new StringBuilder();
mailBody.Append("<html><head><style type=\"text\css\">...</style></head>");
mailBody.Append("<body>")
mailBody.AppendFormat("Hi {0}<br/>", user.FirstName);
...
... XX lines of similar Appending unless it its done!
...
mailBody.Append("</body></html>");

If you're special, maybe you put a template text file somewhere and do a .Replace("{token}") but it still sucks.

Additionally, you want the ability to send not only rich HTML email but also plain text (or more likely, multipart) emails. Fortunately, with ASP.NET MVC we are already creating nice HTML template for output the user, just over HTTP. Why can't we do the same with email?

How MvcMailer Works and Why It's Cool

The MvcMailer NuGet Package is clever on a number of levels, truly. I mention this so that we (you and I, Dear Reader) might learn together. It's full of little gems and clever best-practices that we can use in our own NuGet packages.

In his install.ps1 - that's the PowerShell script that runs when you install a package - he has a little ReadMe in the form of a series of Write-Host commands. This is a simple, clever and effective way to get my attention. And it did!

Write-Host ---------------------------READ ME---------------------------------------------------
Write-Host
Write-Host Your default Mailer Scaffolder is set to $mailerScaffolder
Write-Host
Write-Host You can generate your Mailers and Views using the following Scaffolder Command
Write-Host
Write-Host "PM> Scaffold Mailer UserMailer Welcome,GoodBye"
Write-Host
Write-Host Edit the smtp configuration at web.config file before you send an email
Write-Host
Write-Host You can find more at: https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide
Write-Host
Write-Host -------------------------------------------------------------------------------------

He also makes use of the version specific lib folders. There's a 40 folder underneath lib. That's because this package only works on .NET 4 and NuGet knows it because of the named lib folders. You can target Silverlight, etc with these folders.

The MvcMailer makes use of Steve Sanderson's excellent (and prescient) scaffolding system. Steve took the basic MvcScaffolding prototype and turned it into two packages, the MvcScaffolding one, and a base package called T4Scaffolding that isn't MVC specific. You can Get-Scaffolder and Set-Scaffolder and generate whatever you like, and he does.

If I type Get-Scaffolder, I see where MvcMailer has plugged in:

PM> Get-Scaffolder

Name Description Package
---- ----------- -------
Mailer.Aspx Scaffold ... MvcMailer 1.1
Mailer.Razor Scaffold ... MvcMailer 1.1
T4Scaffolding.CustomScaffolder Creates a... T4Scaffolding 0.9.7
T4Scaffolding.CustomTemplate Allows yo... T4Scaffolding 0.9.7
T4Scaffolding.EFDbContext Makes an ... T4Scaffolding 0.9.7
T4Scaffolding.EFRepository Creates a... T4Scaffolding 0.9.7

Now I can Scaffold out a Welcome and GoodBye mailer (or whatever, like Change Password, etc.

PM> Scaffold Mailer UserMailer Welcome,GoodBye
Added MvcMailer output 'Mailers\IUserMailer.cs'
Added MvcMailer output 'Mailers\UserMailer.cs'
Added MyScaffolder output 'Views\UserMailer\_Layout.cshtml'
Added MyScaffolder output 'Views\UserMailer\Welcome.cshtml'
Added MyScaffolder output 'Views\UserMailer\GoodBye.cshtml'

Ah, but I need both HTML and Text versions, so I'll do  it again -WithText:

PM> Scaffold Mailer UserMailer Welcome,GoodBye -WithText
Mailers\IUserMailer.cs already exists! Skipping...
Mailers\UserMailer.cs already exists! Skipping...
Views\UserMailer\_Layout.cshtml already exists! Skipping...
Views\UserMailer\Welcome.cshtml already exists! Skipping...
Views\UserMailer\GoodBye.cshtml already exists! Skipping...
Added MyScaffolder output 'Views\UserMailer\_Layout.text.cshtml' Added MyScaffolder output 'Views\UserMailer\Welcome.text.cshtml' Added MyScaffolder output 'Views\UserMailer\GoodBye.text.cshtml'

Very cool. Now I've got templates nicely organized as if they were Views for both HTML and Text for Welcome and GoodBye. I can take the generated code for my UserMail and extend it. For example, if I want to send some data to my mailer (I likely do) I'll change it to look like this:

public virtual MailMessage Welcome(string firstName, string email)
{
var mailMessage = new MailMessage{Subject = "Welcome"};

mailMessage.To.Add(email);
ViewBag.FirstName = firstName;
PopulateBody(mailMessage, viewName: "Welcome");

return mailMessage;
}

Then I can call this from a regular controller in response to an action. This could certainly be done on one line if you like that.

var mailer = new UserMailer();
var msg = mailer.Welcome(firstName: "Scott", email: "scottha@microsoft.com");
msg.Send();

I like named parameters.

NOTE: The Send() method is an extension method, and you need to make sure you have using Mvc.Mailer in your namespaces. This slowed me down a smidge until I figured it out.

Now, I don't want to setup my SMTP mail server, so I'll change the web.config to write emails out to a temp folder:

<system.net>
<mailSettings>
<!-- Method#1: Configure smtp server credentials -->
<!--<smtp from="some-email@gmail.com">
<network enableSsl="true" host="smtp.gmail.com" port="587" userName="some-email@gmail.com" password="valid-password" />
</smtp>-->
<!-- Method#2: Dump emails to a local directory -->
<smtp from="some-email@gmail.com" deliveryMethod="SpecifiedPickupDirectory">
<network host="localhost" />
<specifiedPickupDirectory pickupDirectoryLocation="c:\temp\"/>
</smtp>
</mailSettings>
</system.net>

When I execute /Home/SendWelcomeEmail, I've got a nice email sitting in my temp folder (note the Outlook Icon):

MvcMailerTempEmail

And here's my email. Note the user data passed in, in the form of my email and first name.

Welcome - Message (HTML)  (32)

I just love that this package exists and that it's such a great example of open source building on existing projects and plugging into existing conventions cleanly. It's also a testament to Steve's extensibility points  in T4Scaffolding and Andrew Nurse and friends in Razor as neither team had an idea this project was happening! Kudos to Sohan for this useful and polished project. I hope the community appreciates his work and supports him with bug fixes, improvements and more! Thank him in the comments and follow his project on GitHub!

One Other Clever Thing

Here's one other clever thing that Sohan does (borrowing from Steve Sanderson) He has to determine what your preferred View Engine is, so he counts the number of ASPX files and the number of Razor files and figures the one you have the most of is your preference.

### Copied from MvcScaffolding
function CountSolutionFilesByExtension($extension) {
$files = (Get-Project).DTE.Solution `
| ?{ $_.FileName } `
| %{ [System.IO.Path]::GetDirectoryName($_.FileName) } `
| %{ [System.IO.Directory]::EnumerateFiles($_, "*." + $extension, [System.IO.SearchOption]::AllDirectories) }
($files | Measure-Object).Count
}

function InferPreferredViewEngine() {
# Assume you want Razor except if you already have some ASPX views and no Razor ones
if ((CountSolutionFilesByExtension aspx) -eq 0) { return "razor" }
if (((CountSolutionFilesByExtension cshtml) -gt 0) -or ((CountSolutionFilesByExtension vbhtml) -gt 0)) { return "razor" }
return "aspx"
}

# Infer which view engine you're using based on the files in your project
### End copied

$mailerScaffolder = if ([string](InferPreferredViewEngine) -eq 'aspx') { "Mailer.Aspx" } else { "Mailer.Razor" }
Set-DefaultScaffolder -Name Mailer -Scaffolder $mailerScaffolder -SolutionWide -DoNotOverwriteExistingSetting

Very cool.

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

Figuring out why my SVCHOST.EXE is at 100% CPU without complicated tools in Windows 7

March 15, 2011 Comment on this post [23] Posted in Tools
Sponsored By

Windows Task Manager won't save youThe SvcHost.exe process hosts services that run in the background on Windows. It's literally "Service Host." You may have a dozen services or more running inside that process. More complex is that you'll sometimes see multiple SvcHost.exe's in your TaskManager. 

Let me tell you now, Task Manager will not save you. You can see the PIDs for a running Service for the Services tab, but when a service goes insane, good luck nailing it down.

This inevitably leads you to questions like, "What Services are running inside what SvcHost.exe?" and "Which Service is using 100% CPU."

There's lots of ways to figure this out, but first I'll tell you that simply killing the SvcHost.exe process that is using the most CPU will also kill ALL the other services that were running inside that host process.

There's many command line ways to figure this stuff out, like

net start

or

sc query type= service

or

tasklist /svc

But this post is about doing it the easy way without lining up Process IDs and such.

Which Service is Freaking Out?

From the Start Menu, type "Resource Monitor" and run it.

Resource Monitor

Click the checkboxes to the left of each of the svchost.exe processes (or just those that you care about). Now, switch to the CPU tab:

Resource Monitor - CPU

See the names of the logical services in the middle pane? Now you can sort by the CPU column and you've got the name of your out of control process.

You can right click and try to stop or restart just the one services, or even use default browser's default search engine to "Search Online" for that service name:

Resource Monitor with the Right Click Menu showing

This tip has helped me several times while writing and debugging services. Resource Monitor is your friend. Many folks don't' even know it's there!

Enjoy!

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.