Scott Hanselman

Ajax Control Toolkit July 2011 Release - Now on NuGet

August 9, '11 Comments [13] Posted in ASP.NET | ASP.NET Ajax
Sponsored By

Say what you will about the Ajax Control Toolkit. Some like it, some don't, but it got 1.15 MILLION downloads last year. Is the ACT dead? Not yet, and there's ongoing work around WebForms, jQuery and an ACT style of programming. More on this soon.

installpackage

There's like 40 different controls in the Ajax Control Toolkit. They continue to be updated and have cross-browser support. The first release this year added IE9 support. This new July 2011 release adds a a new HTML Editor and more complete browser support including (from Stephen Walther's blog):

The HTML Editor Extender works on all modern browsers including the most recent versions of Mozilla Firefox (Firefox 5), Google Chrome (Chrome 12), and Apple Safari (Safari 5). Furthermore, the HTML Editor Extender is compatible with Microsoft Internet Explorer 6 and newer.

How do you use it? Now that the AjaxControlToolkit is in NuGet, it's easy either from the Package Manager Console, or from the GUI.

Installing AjaxControlToolkit from NuGet

You COULD register the AjaxControlToolkit at the top of your page:

<%@ Register TagPrefix="act" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit"%>

But the NuGet package already added that to your web.config!

<pages>
<controls>
<add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
</controls>
</pages>

Although I think the prefix should be "act," so I'll change it. Then, just use the controls on your page in ASP.NET WebForms. For example, here's how you turn a standard TextBox into a Color Picker:

<act:ToolkitScriptManager ID="manager" runat="Server" />
<asp:TextBox ID="txtColorPicker" runat="server" />

<act:ColorPickerExtender TargetControlID="txtColorPicker" runat="server" />

The ToolkitScriptManager only needs to be on the page once.

Textbox turned into a ColorPicker

This is just one example. Check out the dozens of controls at the Ajax Control Toolkit Sample site.

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 twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

NuGet Package of the Week #9 - ASP.NET MiniProfiler from StackExchange rocks your world

July 22, '11 Comments [40] Posted in ASP.NET | ASP.NET Ajax | ASP.NET MVC | NuGet | NuGetPOW | Open Source
Sponsored By

Glimpse, MiniProfiler and ELMAH equals Love and Kittens (VENN DIAGRAM)I LOVE great debugging tools. Anything that makes it easier for me to make a site correct and fast is glorious. I've talked about Glimpse, an excellent firebug-like debugger for ASP.NET MVC, and I've talked about ELMAH, and amazing logger and error handler. Now the triad is complete with MiniProfiler, my Package of the Week #9.

Yes, #9. I'm counting "System.Web.Providers" as #8, so phooey. ;)

Hey, have you implemented the NuGet Action Plan? Get on it, it'll take only 5 minutes: NuGet Action Plan - Upgrade to 1.4, Setup Automatic Updates, Get NuGet Package Explorer. NuGet 1.4 is out, so make sure you're set to automatically update!

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.

This week's Package of the Week is "MiniProfiler" from StackExchange.

MiniProfiler for ASP.NET

Each are small bad-ass LEGO pieces that make debugging, logging and profiling your ASP.NET application that much more awesome.

So what's it do? It's a Production Profiler for ASP.NET. Here's what Sam Saffron says about this great piece of software Jarrod Dixon, Marc Gravell and he worked on...and hold on to your hats.

Our open-source profiler is perhaps the best and most comprehensive production web page profiler out there for any web platform.

Whoa. Bold stuff. Is it that awesome? Um, ya. It works in ASP.NET, MVC, Web Forms, and Web Pages.

The powerful stuff here is that this isn't a profiler like you're used to. Most profilers are heavy, they plug into the runtime (the CLR, perhaps) and you'd avoid messing with them at production time. Sometimes people will do "poor man's profiling" with high performance timers and log files, but there's always a concern that it'll mess up production. Plus, digging around in logs and stuff sucks.

MiniProfiler will profile not only what's happening on the page and how it renders, but also separate statements whose scope you can control with using() statements, but also database access. Each one is more amazing.

First, from an ASP.NET application, install the MiniProfiler package via NuGet. Decide when you will profile. You can't profile everything, so do you want to profile local requests, just requests from administrators, or from certain IPs? Start it up in your Global.asax:

protected void Application_BeginRequest()
{
if (Request.IsLocal) { MiniProfiler.Start(); } //or any number of other checks, up to you
}

protected void Application_EndRequest()
{
MiniProfiler.Stop(); //stop as early as you can, even earlier with MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);
}

Add a call to render the MiniProfiler's Includes in a page, usually the main layout after wherever jQuery is added:

<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
@MvcMiniProfiler.MiniProfiler.RenderIncludes()
</head>

The, if you like, put some using statements around some things you want to profile:

public class HomeController : Controller
{
public ActionResult Index()
{
var profiler = MiniProfiler.Current; // it's ok if this is null

using (profiler.Step("Set page title"))
{
ViewBag.Title = "Home Page";
}

using (profiler.Step("Doing complex stuff"))
{
using (profiler.Step("Step A"))
{ // something more interesting here
Thread.Sleep(100);
}
using (profiler.Step("Step B"))
{ // and here
Thread.Sleep(250);
}
}

using (profiler.Step("Set message"))
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
}

return View();
}
}

Now, run the application and click on the chiclet in the corner. Open your mouth and sit there, staring at your screen with your mouth agape.

Mini Profiler rocks your world with stats right in your page

That's hot. Notice how the nested using statements are nested with their timings aggregated in the popup.

If you want to measure database access (where the MiniProfiler really shines) you can use their ProfiledDbConnection, or you can hook it into Entity Framework Code First with the ProfiledDbProfiler.

If you manage connections yourself or you do your own database access, you can get Profiled connections manually:

public static MyModel Get()
{
var conn = ProfiledDbConnection.Get(GetConnection());
return ObjectContextUtils.CreateObjectContext<MyModel>(conn);
}

Or, if you are using things like Entity Framework Code First, just add their DbProvider to the web.config:

<system.data>
<DbProviderFactories>
<remove invariant="MvcMiniProfiler.Data.ProfiledDbProvider" />
<add name="MvcMiniProfiler.Data.ProfiledDbProvider" invariant="MvcMiniProfiler.Data.ProfiledDbProvider"
description="MvcMiniProfiler.Data.ProfiledDbProvider"
type="MvcMiniProfiler.Data.ProfiledDbProviderFactory, MvcMiniProfiler, Version=1.6.0.0, Culture=neutral, PublicKeyToken=b44f9351044011a3" />
</DbProviderFactories>
</system.data>

Then tell EF Code First about the connection factory that's appropriate for your database.

I've spent the last few evenings on Skype with Sam trying to get the EF Code First support to work as cleanly as possible. You can see the checkins over the last few days as we bounced back and forth. Thanks for putting up with me, Sam!

Here's how to wrap SQL Server Compact Edition in your Application_Start:

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);

//This line makes SQL Formatting smarter so you can copy/paste
// from the profiler directly into Query Analyzer
MiniProfiler.Settings.SqlFormatter = new SqlServerFormatter();

var factory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
var profiled = new MvcMiniProfiler.Data.ProfiledDbConnectionFactory(factory);
Database.DefaultConnectionFactory = profiled;
}

Or I could have used SQLServer proper:

var factory = new SqlConnectionFactory("Data Source=.;Initial Catalog=tempdb;Integrated Security=True");

See here where I get a list of People from a database:

 (45)

See where it says "1 sql"? If I click on that, I see what happened, exactly and how long it took.

SQL Profiler

It's even cooler with more complex queries in that it can detect N+1 issues as well as duplicate queries. Here we're hitting the database 20 times with the same query!

 (46)

Here's a slightly more interesting example that mixes many database accesses on one page.

Detecting Duplicates

Notice that there's THREE chiclets in the upper corner there. The profiler will capture GET, POSTs, and can watch AJAX calls! Here's a simple POST, then REDIRECT/GET (the PRG pattern) example as I've just created a new Person:

Creating a person and profiling them

Notice that the POST is 141ms and then the GET is 24.9. I can click in deeper on each access, see smaller, trivial timings and children on large pages.

I think that this amazing little profiler has become, almost overnight, absolutely essential to ASP.NET MVC.

I've never seen anything like it on another platform, and once you've used it you'll have trouble NOT using it! It provides such clean, clear insight into what is going on your site, even just out of the box. When you go an manually add in more detailed Steps() you'll be amazed at how much it can tell you about your side. MiniProfiler works with WebForms as well, because it's all about ASP.NET! There are so many issues that pop up in production that can only be found with a profiler like this.

Be sure to check out the MiniProfiler site for all the detail and to download samples with even more detail. There's lots of great features and settings to change as seen in just their sample Global.asax.cs.

Stop what you're right doing now, and go instrument your site with MiniProfiler! Then go thank Jarrod Dixon, Marc Gravell and Sam Saffron and the folks at StackExchange for their work.

UPDATE - July 24th

Some folks don't like the term "profiler" to label what the MiniProfiler does. Others don't like the sprinkling of using() statements and consider them useless, perhaps like comments. I personally disagree, but that said, Sam has created a new blog post that shows how to automatically instrument your Controller Actions and View Engines. I'll work with him to make a smarter NuGet package so this is all done automatically, or easily optionally.

This is done for Controllers with the magic of the MVC3 Global Action Filter:

class ProfilingActionFilter : ActionFilterAttribute
{
IDisposable prof;

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var mp = MiniProfiler.Current;
if (mp != null)
{
prof = MiniProfiler.Current.Step("Controller: " + filterContext.Controller.ToString() + "." + filterContext.ActionDescriptor.ActionName);
}
base.OnActionExecuting(filterContext);
}

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
if (prof != null)
{
prof.Dispose();
}
}
}

And for ViewEngines with a simple wrapped ViewEngine. Both of these are not invasive to your code and can be added to your Global.asax.

public class ProfilingViewEngine : IViewEngine
{
class WrappedView : IView
{
IView wrapped;
string name;
bool isPartial;

public WrappedView(IView wrapped, string name, bool isPartial)
{
this.wrapped = wrapped;
this.name = name;
this.isPartial = isPartial;
}

public void Render(ViewContext viewContext, System.IO.TextWriter writer)
{
using (MiniProfiler.Current.Step("Render " + (isPartial?"parital":"") + ": " + name))
{
wrapped.Render(viewContext, writer);
}
}
}

IViewEngine wrapped;

public ProfilingViewEngine(IViewEngine wrapped)
{
this.wrapped = wrapped;
}

public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
{
var found = wrapped.FindPartialView(controllerContext, partialViewName, useCache);
if (found != null && found.View != null)
{
found = new ViewEngineResult(new WrappedView(found.View, partialViewName, isPartial: true), this);
}
return found;
}

public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
var found = wrapped.FindView(controllerContext, viewName, masterName, useCache);
if (found != null && found.View != null)
{
found = new ViewEngineResult(new WrappedView(found.View, viewName, isPartial: false), this);
}
return found;
}

public void ReleaseView(ControllerContext controllerContext, IView view)
{
wrapped.ReleaseView(controllerContext, view);
}
}

Get all the details on how to (more) automatically instrument your code with the MiniProfiler (or perhaps, the MiniInstrumentor?) over on Sam's Blog.

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 twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Mix 11 Videos - Download them all with RSS

April 18, '11 Comments [19] Posted in ASP.NET | ASP.NET Ajax | ASP.NET Dynamic Data | ASP.NET MVC | Channel9 | HTML5 | IE9 | IIS | Mix | NuGet | Speaking | VS2010
Sponsored By

Such a fun time was had at Mix 11 this last week in Vegas. I only saw a few talks as I was busy presenting, but now as I sit at home on my first day back, I say to myself, Self, how can I get all the Mix videos at once?

First, you can watch all the videos online at http://channel9.msdn.com/Events/MIX/MIX11 

Second, you can get them via RSS. Most major browsers are hiding the RSS button these days, but the discovery metadata is all still there. In IE9, for example, if you show the Command Bar, you can see the RSS Feeds for the Mix site:

Hey, the Mix Site has RSS feeds in its Meta Tags!

What's all this awesomeness? Oh, yes, it's the Mix talks via RSS with enclosures, just as you've always wanted. Now you can list the thousand ways that you might retrieve these lovely files and abuse Microsoft's bandwidth while hoarding knowledge on your multi-terabyte personal SAN.

Direct links to the Mix RSS feeds that include Enclosures:

So now you can get them with iTunes or Zune, or PowerShell, 'cause that's bad-ass. Yes, you can use Curl also, nyah.

$feed=[xml](New-Object System.Net.WebClient).DownloadString("http://channel9.msdn.com/Events/MIX/MIX11/RSS")
foreach($i in $feed.rss.channel.item) {
$url = New-Object System.Uri($i.enclosure.url)
$url.ToString()
$url.Segments[-1]
(New-Object System.Net.WebClient).DownloadFile($url, $url.Segments[-1])
}

Or, you can subscribe in iTunes from Advanced|Subscribe to Podcast, assume, of course, you want iTunes in your life.

I hate iTunes with the heat of a thousand suns

Or, in Zune (which is a good Podcast Downloader even if you don't have a Zune) you can go to Collection|Podcasts and click Add A Podcast:

Zune's OK

Another nice, lightweight Podcast Download is the Open Source "Juice!" from http://juicereceiver.sourceforge.net/

Juice Podcast Downloader

Go get them! Here's the presentations that Web Platform and Tools Team (ASP.NET, IIS, etc) presented:

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 twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Introducing NuGet Package Management for .NET - Another piece of the Web Stack

October 6, '10 Comments [69] Posted in ASP.NET | ASP.NET Ajax | ASP.NET MVC | Nupack
Sponsored By

NuGet

Microsoft's been filling out the Web Stack with more and more right-sized LEGO pieces lately, and today ScottGu announced the developer preview of NuGet. It's a piece of the stack that's been notably missing for years and after using it for a while now, I'm not sure how I lived without it.

NuGet is a package management system for .NET. The goal of NuGet is to make the process of incorporating third party libraries into your solutions as simple as possible.

Package Management itself is not a new concept. From Apt and "deity" before it at the system-level on *nix, to Ruby Gems, Maven, Synaptic, portage, dpkg, rpm and others, it's a well understood space. There are package managers for operating systems that install machine-wide libraries, and there are package managers for developers and their projects that manage dependencies and install libraries. NuGet takes inspiration from Ruby Gems and adds some .NET specifics.

NuGet - The Idea

Here's how it works. Notice the "Package Manager Console" window at the bottom of Visual Studio 2010. That's PowerShell. (It'll be in View | Other Windows for this release)

MvcApplication4 - Microsoft Visual Studio (4)

I type List-Package and NuGet goes to a central ATOM feed and retrieves a list of packages like this (not complete, I snipped it for the example)

Id Version Description
-- ------- -----------
Antlr 3.1.1 ANother Tool for Language Rec...
Artem.XmlProviders 2.5 Implementation of XML ASP.NET...
AutoMapper 1.1.0.118 A convention-based object-obj...
Castle.Components.Validator 1.1.0 The Validator component is us...
Castle.Core 1.2.0 Core of the castle project
Castle.DynamicProxy 2.2.0 Castle DynamicProxy is a libr...
Castle.Ioc 2.1.1 Castle Project offers two Inv...
EFCTP4 1.0 This CTP is a an early previe...
elmah 1.1 ELMAH (Error Logging Modules ...

tarantino-db-deployer 1.0.146.0 This is a database migration ...
WebFormsMVP 0.9.7.2 A simple Model-View-Presenter...
xunit 1.6.1 xUnit.net is a developer test...

At this point, as an example, perhaps I want to get the ELMAH (Error Logging Modules and Handlers) open source library setup in my MVC project. I have long said that ELMAH, as a project, deserves way more attention than it gets.

One of the reasons that it doesn't get used - as is the case with many .NET open source libraries - is that it takes too much effort to get it working. Unzip it, put it in a folder somewhere in your project, figure out what needs to be added to web.config, you know.

With NuGet, I type "Install-Package elmah" and it's done. If I wanted to be extra cool with PowerShell aliases I could have just typed "install-packageelmah."

PM> Install-Package elmah
Successfully added 'elmah 1.1' to MvcApplication4

And that's it. Elmah is automatically brought down to my machine, a reference is added to my project and everything it needs is merged non-destructively into my web.config.

MvcApplication4 - Microsoft Visual Studio (5)

I'll run my app and hit /elmah.axd just to prove it.

Error log for  on HANSELMAN-W500 (Page #1) - Windows Internet Explorer

Complex Packages and their Dependencies

Looks good. But what if I want to add a more complex project, maybe NHibernate.Linq. From the Package Manager Console I'll start typing install-package nh and get Intellisense for all the packages that are available.

image

And the console reports:

PM> Install-Package NHibernate.Linq
'NHibernate.Core (>= 2.0)' not referenced. Retrieving dependency...Done 'log4net (= 1.2.1)' not referenced. Retrieving dependency...Done 'Iesi.Collections (= 1.0)' not referenced. Retrieving dependency...Done 'Antlr (>= 3.0)' not referenced. Retrieving dependency...Done Successfully added 'log4net 1.2.1' to MvcApplication4 Successfully added 'Iesi.Collections 1.0' to MvcApplication4 Successfully added 'Antlr 3.1.1' to MvcApplication4 Successfully added 'NHibernate.Core 2.1.2' to MvcApplication4 Successfully added 'NHibernate.Linq 1.0' to MvcApplication4

Notice that NHibernate.Linq knows its dependant on a bunch of other things. All those packages got pulled in and put in the packages folder. Notice the nupkg file there? That's just a ZIP file. Let's look inside.

A nupkg file open in Windows Explorer

Unzipping the nupkg we see lots of stuff. The binary is in there, but also a nuspec file that looks like this. Dig around in there and you'll find some standard packaging namespaces from openformats.org.




NHibernate.Linq
1.0
NHibernate Linq support is based on the existing, proven in production, Linq provider in NHibernate Contrib. The plans to overhaul that and merge that into NHibernate’s proper for the next release are still active, but the project team feels most strongly that production quality Linq support is something that we ought to provide for our users now.

Ayende

en-US
false
2010-10-03T16:32:29
2010-10-03T16:32:29




NuGet walks its way up the dependency chain and gets all the packages it needs, installing each. Packages can add scripts, content, references, and even run postscripts (ahem) written in PowerShell if they need something fancy.

I can even remove all that and its dependancies.

PM> Remove-Package NHibernate.Linq -RemoveDependencies

Let's add a few more interesting packages to my project. First, I'll add David Ebbo's wonderful T4MVC templates.

PM> install-packageT4MVC
Successfully added 'T4MVC 2.6.30' to MvcApplication4

David's project isn't actually DLLs, it's a T4 template and a config file, but no problem, it's added to the project.

T4MVC in my project

Next I'll add the Entity Framework "Magic Unicorn" library that I love so much.

PM> install-packageEFCTP4

You are downloading EFCTP4 from Microsoft, the license agreement
to which is available at ....Check the package for additional dependencies,
which may come with their own license agreement(s).
Your use of the package and dependencies constitutes your acceptance
of their license agreements. If you do not accept the license agreement(s),
then delete the relevant components from your device.
Successfully added 'EFCTP4 1.0' to MvcApplication4

Note that this package includes some licensing stuff, as do many OSS projects, so I'm told as I get it. Finally I'll add SQL Compact Edition 4 as well with a little...

PM> install-packageSQLCE
Successfully added 'SQLCE 4.0.8402.1' to MvcApplication4

I've added NHibernate.Linq and four dependencies, then removed them all. I've added T4MVC, SQL Compact, Entity Framework CTP 4, and ELMAH.

We see we can add basically anything to a solution and it's only modifying the solution, and the packages folder next to it. Nothing is being added to the GAC (Global Assembly Cache) and no one is installing anything or messing with things system-wide. NuGet is about affecting local projects and solutions...and possibly adding functionality to enable me to make changes even faster...

Can you say Scaffolding?

I'll add one more interesting package. It's not a library like EFCTP4, or a database like SQLCE, or a T4 template like T4MVC. It's actually an example of PowerShell scripts that extend the Package Manager Console itself with new commands that interact with my project.

Note: This is just a sample/example, because we want to see and hear what you want, and how you want to use it. Talk is cheap, show me the code! ;)

install-package MvcScaffold

Typing

PM> install-packageMvcScaffold

adds new commands to my console via a PowerShell script. It adds Add-MvcView, so I could so something basic like

PM> Add-MvcView Empty
Added file 'Views\Empty.aspx'

But that's not interesting. Let's assume I have a Code First class like this in my project and I've compiled once (in fact, a sample model is included with the EFCTP4 package):

using System.Data.Entity;

namespace MvcApplication4.Models {
public class Product {
public int ID { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
public class MyProductContext : DbContext {
public DbSet Products { get; set; }
}
}

Since I've got a nice Product, why not:

PM> Scaffold-MvcViews -ModelType Product  Added file 'Views\Product\List.aspx'
Added file 'Views\Product\Details.aspx'
Added file 'Views\Product\Edit.aspx'
Added file 'Views\Product\Create.aspx'
Added file 'Views\Product\Delete.aspx'

Which gives me a nice scaffolded set of views generated from T4 Code Templates (or your custom ones, if you like)

image

Pretty sweet. A lot has been done and prepped for me and all from the Package Manager Console within VS. I can personally see folks creating templates or meta-packages that encapsulate some CRUD (Create, Read, Update, Delete) best practices and sharing them via NuGet packages.

Can Haz UI?

I've focused on the Command Line, because it's awesome and "computers need to be hard©" but you could have certainly added your packages like this:

Add Package Reference in the Solution Explorer

Clicking Add Package Reference brings up this dialog box. Look familiar?

Add Package Reference Dialog

From here I can search for packages, install, as well as see what packages I've already got installed. I can also check for updates and download new versions.

NuGet Developer Preview

Now this is just a Developer Preview, but look at it generically. We can interact with Visual Studio from PowerShell, package up Open Source libraries, scripts, content or perhaps even meta-packages (install-package hanselpack or install-package dearReaderLibs).

Phil talks about the Guiding Principles for NuGet on his blog. There will be a central feed with no central approval process for adding libraries. The community will police and moderate packages. But, anyone can host a feed. You can host an internal feed at your work, or even just point NuGet at a file system folder and share packages across your group.

Open Source

NuGet is interesting for a couple of reasons. NuGet isn't a classic Microsoft closed-source project; it's been accepted into the CodePlex Outercurve Foundation and is entirely hosted and managed in a Mercurial Repository at the CodePlex.com Forge. Developers from inside Microsoft and developers from outside Microsoft have been committing to the same repository. All the bugs and issues are managed transparently on that projects.

Yeah, we're slow, but we're working to turn this ship around. NuGet can, and has, accepted contributions, most recently from some folks on the "Nu" open source project. In fact, working with the Nu folks caused us to change the name of this project from its original name of "NPack" to NuGet. There's been a lot of "Source Opened" at Microsoft and a lot of "Open Source but No Takebacks" with some Open Source, but with NuGet I'm stoked to see us start giving (and taking back) in a more open way.

As Phil says, go over to the NuGet website on CodePlex and check out our guide to contributing to NuGet. It's early, and there's a LOT of work to be done, but we're planning to make this available for use in all editions of Visual Studio 2010.

Get the NuGet Preview today with ASP.NET MVC 3 Beta

Go get ASP.NET MVC 3 Beta and NuGet is included inside. Here's the direct download link.

To summarize:

  • NuGet is open source and in the Outercurve Foundation
  • NuGet integrates with VS and with PowerShell
  • NuGet will have a community managed gallery without central approving authority
  • NuGet won't mess up your computer or install anything outside your solution
  • You can host your own feeds, or read packages out of a network share/folder

The whole team - inside and outside Microsoft - really hopes you like it.

Personal Aside: Changing Jobs

An a related aside, one of the reasons I came to Microsoft was to work on and encourage open source like NuGet. For the last few years I've been working in MSDN and STO (Server and Tools Online) most recently leading a community team with a great bunch of folks, including Joe Stagner, Jon Galloway, Rey Bango, Jesse Liberty, and Pete Brown. This week I'm leaving MSDN to go to work as Community Architect for the Web Platform and Tools (WPT) team under ScottGu, Bill Staples and Omar Khan. Pete will take over as the lead of my team and they'll all join Developer Guidance (née Patterns and Practices). We'll hang out a lot together, though, I have no doubt, and I'll be at the Patterns and Practices Symposium as well as PDC 2010 this year.

The WPT team includes ASP.NET, IIS, as well as open source projects like NuGet, ASP.NET MVC and Orchard. I'll be promoting Open Source inside and outside Microsoft, making sure the customers voice is heard as products are architected, as well as speaking and teaching whenever they'll let me. I won't be moving to Seattle. ;)

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 SherWeb

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 SherWeb
Previous Page Page 2 of 4 in the ASP.NET Ajax category Next Page

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