St. Louis Day of .NET 2010

August 20th & 21st 2010

Ameristar Casino & Resort St. Charles, MO

Last year we had 500 people, 66 sessions, and 48 speakers.  This year we have even more in store.  Be there with hundreds of developers and IT pros from across the country.

The 2010 St. Louis Day of .NET, such an awesome day it takes 2 days!

St. Louis Day of .NET Logo

VS 2010 Events in St Louis

Monday April 12, 5:30 PM – 3 City Place, 11th Floor Creve Coeur, MO

High Speed, Low Drag: Driving Application Quality with Minimal Friction
Mark Mydland – Principal Group Manager for the Visual Studio Team Edition for Software Testers, Microsoft Corporation

Software teams are continually under pressure to do more in less time, to build higher quality and ever more complex applications on ever increasing ship cadences. In this session we will use Microsoft’s Visual Studio 2010 Application Lifecycle tools to demonstrate how to deliver bugs that get fixed first time, every time

More at http://stlnet.org/

Thursday April 29, 5:30 PM – 3 City Place, 11th Floor Creve Coeur, MO

.NET Rocks is on the Road Again!

Carl and Richard are loading up the RV and driving to our town to show off the latest and greatest in Visual Studio 2010! And to make the night even more fun, we’re going to bring a rock star of the Visual Studio world to the event and interview them for a special .NET Rocks Road Trip show series. Along the way we’ll be giving away some great prizes, showing off some awesome technology and having a ton of laughs.

More at http://www.dotnetrocks.com/roadtrip

Redirecting From a WCF REST Service

REST is based on HTTP and revolves around using the standard HTTP verbs GET, POST, PUT as well as standard HTTP error codes.  The error codes that have to do with redirection are in the 300 block.  Today we’ll focus on 302 which is the status code for a redirection (other 300 codes, such as 301 indicate that the URI moved permanently).

The following code will redirect the client with a 302 status code:

WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Redirect;
WebOperationContext.Current.OutgoingResponse.Location = "/someOtherPage.aspx";
return null; 

For an additional measure we’ll return null as well so that there is no output emitted to the client.  The end result will be that the headers include the 302 status code, the location to redirect to and the body of the response will be empty.

Using Silverlight 4 to Browse NetFlix’s OData Catalog

One of the announcements at Mix 10 was the preview of NetFlix’s OData catalog API.  The Astoria team has been hard at work getting the new release of what is now called WCF Data Services (Formerly ADO.NET Data Services).  In Silverlight 4 the WCF Data Services Client is included as part of the Silverlight runtime which makes it very easy to consume OData Services.

OData?

OData is the Open Data Protocol which Microsoft created originally for ADO.NET Data Services.  The protocol was adopted by enough people that Microsoft focused more effort on it.  OData defines the structure & types for publishing data using HTTP and an Xml Format based on Atom (AtomPub) or JSON.  OData has roots in REST and focuses on using the HTTP protocol to enable easy data access.

OData defines methods to enable querying data sources using structured URIs.

WCF Data Services & Silverlight 4

With Silverlight 4 you can directly add service references to WCF Data Services and the models for the catalog are generated automatically.  The results of the add service reference yields this:

image

image

Once you have the service reference you can work with the data using the NetflixCatalog class which is a DataServiceContext class.  The context generated classes includes DataServiceQuery<T> properties for the main resources in the Netflix OData catalog.

 public partial class MainPage : UserControl
    {
        private DataServiceCollection<Genre> _genres;
        private Genre _selectedGenre;
        private NetflixCatalog _context;

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            _context = new NetflixCatalog(new Uri               ("http://odata.netflix.com/Catalog/"));

            _genres = new DataServiceCollection<Genre>();
            _genres.LoadCompleted += Genres_Loaded;

            var query = (from g in _context.Genres orderby g.Name select g);
            _genres.LoadAsync(query);
        }

If you haven’t done a lot with events and delegates then jumping into Silverlight will be tricky at first.  To load all the genres, we use an event handler which will bind to ComboBox.  This also handles “Continuations”, which is the mechanism Data Services use to enable paging across large datasets.  With the following code we will continue loading genres until we have loaded all of them.

        private void Genres_Loaded(object sender, LoadCompletedEventArgs e)
        {
            if (_genres.Continuation != null)
            {
                _genres.LoadNextPartialSetAsync();
            }
            else
            {
                LoadingGenresLabel.Opacity = 0;
                GenreCombobox.ItemsSource = _genres;
                GenreCombobox.UpdateLayout();
            }
        }

Once all the genres are loaded in the ComboBox you can select one and it will load the titles for that genre.  To load the Titles for a Genre we can use the following code:

        private void GenreCombobox_SelectionChanged(object sender,         SelectionChangedEventArgs e)
        {
            _selectedGenre = GenreCombobox.SelectedItem as Genre;
            if (_selectedGenre != null)
            {
                if (_selectedGenre.CatalogTitles.Count == 0)
                {
                    CatalogTitleListBox.SelectedIndex = -1;
                    _selectedGenre.CatalogTitles.LoadCompleted +=                       GenreCatalogTitles_Loaded;
                    _selectedGenre.CatalogTitles.LoadAsync();
                    LoadingTextBlock.Opacity = 1;
                }
                else
                {
                    CatalogTitleListBox.ItemsSource =                             _selectedGenre.CatalogTitles;
                    CatalogTitleListBox.SelectedIndex = 0;
                }
            }
        }

As you can see, the code for working with a data service to retrieve data is pretty straight-forward.  All the code for this project can be found on CodePlex: Silverlight 4 Netflix.  If you have Silverlight 4 installed you can try Silverlight4Netflix out here.  Otherwise, enjoy the screenshots below!

image

image

image

image

Drop the Soap: WCF, REST, and Pretty URIs in .NET 4

Years ago I was working in libraries when the Web 2.0 revolution began.  One of the things that caught my attention about early start-ups using the AJAX/REST/Web 2.0 model was how nice the URIs were for their applications.  Those were my first impressions of REST; pretty URIs.  Turns out there is a little more to it than that.

REST is an architectural style that focuses on resources and structured ways to access those resources via the web.  REST evolved as an “anti-SOAP” movement, driven by developers who did not want to deal with all the complexity SOAP introduces (which is al lot when you don’t have frameworks hiding it all).  One of the biggest benefits to REST is that browsers can talk to rest services directly because REST works using URIs, QueryStrings, Cookies, SSL, and all those HTTP verbs that we don’t have to think about anymore.

If you are familiar with ASP.NET MVC then you have been exposed to rest at some level.  MVC is relies heavily on routing to generate consistent and clean URIs.  REST for WCF gives you the same type of feel for your services.  Let’s dive in.

WCF REST in .NET 3.5 SP1 and .NET 4

This post will cover WCF REST in .NET 4 which drew heavily from the REST Starter Kit and community feedback.  There is basic REST support in .NET 3.5 SP1 and you can also grab the REST Starter Kit to enable some of the features you’ll find in .NET 4.

This post will cover REST in .NET 4 and Visual Studio 2010.

Getting Started

To get started we’ll create a basic WCF Rest Service Application using the new on-line templates option in VS 2010:

image

When you first install a template you are prompted with this dialog:

image

Dude Where’s my .Svc File?

The WCF REST template shows us the new way we can simply build services.  Before we talk about what’s there, let’s look at what is not there:

  • The .Svc File
  • An Interface Contract
  • Dozens of lines of configuration that you have to change to make your service work

REST in .NET 4 is greatly simplified and leverages the Web Routing capabilities used in ASP.NET MVC and other parts of the web frameworks.  With REST in .NET 4 you use a global.asax to set the route to your service using the new ServiceRoute class.  From there, the WCF runtime handles dispatching service calls to the methods based on the Uri Templates.

global.asax

using System;
using System.ServiceModel.Activation;
using System.Web;
using System.Web.Routing;

namespace Blog.WcfRest.TimeService
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes();
        }

        private static void RegisterRoutes()
        {
            RouteTable.Routes.Add(new ServiceRoute("TimeService",
                new WebServiceHostFactory(), typeof(TimeService)));
        }
    }
}

The web.config contains some new structures to support a configuration free deployment.  Note that this is the default config generated with the template.  I did not make any changes to web.config.

web.config

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule,
           System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </modules>
  </system.webServer>

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <standardEndpoints>
      <webHttpEndpoint>
        <!--
            Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
            via the attributes on the <standardEndpoint> element below
        -->
        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>

</configuration>

Building the Time Service

We’ll create a simple “TimeService” that will return the current time.  Let’s start with the following code:

using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace Blog.WcfRest.TimeService
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class TimeService
    {
        [WebGet(UriTemplate = "CurrentTime")]
        public string CurrentTime()
        {
            return DateTime.Now.ToString();
        }
    }
}

The endpoint for this service will be http://[machinename]:[port]/TimeService.  To get the current time http://[machinename]:[port]/TimeService/CurrentTime will do the trick.

The Results Are In

image

Remember That Route In global.asax?

Turns out it is pretty important.  When you set the route name, that defines the resource name starting after the host portion of the Uri. 

image

Help Pages in WCF 4

Another feature that came from the starter kit are the help pages.  To access the help pages simply append Help to the end of the service’s base Uri.

image

image

Dropping the Soap

Having dabbled with REST in the past and after using Soap for the last few years, the WCF 4 REST support is certainly refreshing.  I’m currently working on some REST implementations in .NET 3.5 and VS 2008 and am looking forward to working on REST in .NET 4 and VS 2010.

Windows Phone 7 Series Dev Tools Available

I am not at MIX.  However, I have been wanting to write about these tools since the MVP Summit where I first saw the beta tools.  You can download all you need here.

Once installed, after clicking, file –> new project you should see:

image

Highlighting windows Phone Application gives you this template.

image

Should you decide to continue (and you should) you will see a split designer where you can drag and drop standard Silverlight controls onto the phone surface.

image

Oh and, when you debug you get a nice VM which runs the Windows Phone 7 Series OS complete with battery warnings and all.  Stormtrooper not included.

image

“Icky” Decisions

@KeithDahlby posted a good question for thought the other day on “the” Twitter:

When implementing the Observer pattern, how do you handle exceptions from observers?

This seemingly harmless question should spark at least a good 15 minute debate.  An obvious question (and the one I asked):

Do you care if an observer throws an exception?

If you consider the classic observer pattern you’ll note that the observed only knows about it’s observers through an interface.  Using an interface for observers to reduce coupling is a good practice but by doing that you’ll want to be sure to retain that reduction of coupling by not allowing the observed to know about any of the concrete observers. 

Deciding to allow the observed to know about it’s observers and allow it to handle exceptions would introduce coupling that could lead to bugs down the road. 

Keith is a super smart guy and knew all along what to do, but the “what” is icky:

That’s what we’re doing, but agreed that it’s icky – wish there were a better option that catch(Exception)

This is icky because in the event an observer is very broken you won’t have a first-hand way to find out (and ReSharper will let you know about the dangers of your empty catch block).  Each observer is now responsible for logging or notifying someone about exceptions which adds some additional complexity (possibly through configuration or another mechanism).

You’ll run into these icky decisions and each one certainly needs healthy debate and some documentation to cover the bases later on when someone might question why the icky option was chosen. 

What was your most recent “icky” situation?

WCF 4 – Loosening the Chains of Configuration

If you have spent anytime in WCF land the first thing you learn about is the joys of configuration.  For the coming release of .NET 4 and WCF 4 the team heard that feedback and has made configuration much easier for the development experience.

Let’s take a look at what’s changed:

Sample 1 – WCF Configuration on .NET 3.5 SP1

  <system.serviceModel>
    <services>
      <service name="WcfServiceConfig35.Service1" behaviorConfiguration="WcfServiceConfig35.Service1Behavior">
        <!-- Service Endpoints -->
        <endpoint address="" binding="wsHttpBinding" contract="WcfServiceConfig35.IService1">
          <!--
              Upon deployment, the following identity element should be removed or replaced to reflect the
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity
              automatically.
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfServiceConfig35.Service1Behavior">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

By the way, I left out about 100 lines of other configuration “stuff” that had to do with System.Web, etc.

Sample 2 – WCF Configuration for the same service as Sample 1, in .NET 4

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

Notice there is no (none, nada, zero) system.serviceModel element.  That said, if you start your service this way you have one teeny issue:

image

By default WCF disables metadata publishing (security through obscurity) so no one could query your service WSDL to build a client.  In order to do that, you simply need the default code that WCF 4 puts in your config.

Sample 3 – WCF Configuration to enable metadata publishing, in .NET 4

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

I will certainly be looking forward to the easing of the configuration pains in WCF 4!

Reclaiming Your Identity with Windows Identity Foundation

Windows Identity Foundation is a new framework from Microsoft that helps to solve the identity crisis so many users face with multiple accounts for on-line services, applications, etc.  WIF (dub-eye-eff, not “wiff”), supports the notion of claims-based authentication where a user will authenticate with an external provider and return to your application with a set of claims (in the form of an encrypted token such as SAML) which you then verify and accept.  Delegating authentication is meant to remove the responsibility of authenticating from your application so that it can focus on doing what the app needs to do and not become full of logic to authenticate users.

What’s in a Claim Anyway?

Claims based security isn’t something new.  The idea behind claims is simple.  Users go to a centralized provider where they authenticate and are given a token which contains information about that user; their name, roles, and any other data the authentication store provides.  The user then takes those claims and presents them to the application.  The application verifies the authenticity of the claims and allows the user to access the resources which they are authorized to use.

Real World Claims

The identity problem hasn’t been eliminated in the real-world.  Think about how many cards you carry in your wallet that identify you to some other external party.  You have a drivers license, credit cards, video club cards, etc.  These cards are generally only trusted by the person issuing them.

Since I’ve been doing a lot of flying lately, let’s consider this example.  When you go through the airport now you are required to have a “government issued ID” in addition to your boarding pass.  In the United States alone there are 50 governments responsible for issuing IDs.  You can also print your own boarding pass and each of the airlines format is slightly different.  When you hand your ID and boarding pass to the TSA agent they are not going to verify who actually printed your ID or the legitimacy of your boarding pass.  They are looking for signs of fraud and that the person in the picture resembles the person standing in front of them.

You present the TSA agent your claims (valid boarding pass and government issued ID) and they verify your claims by checking against known signs of fraudulent IDs.

WIF Terms

Claim – Comes from the attribute store for a user.  Typically a key value pair.

Identity Provider – The service responsible for provisioning users & their attributes.

Relying party – The application which will rely on an STS to provide authentication and a token containing claims.

Security Token Service (STS) – The interface of the Identity Provider which allows you to interact with the Identity Provider as a web service.

Token – The “thing” that contains claims to be used by an application. Typically it is an encrypted cookie or xml file.

Getting Started with WIF

To build your first claims aware application you’ll need to grab the SDK here.  To use WIF you need to have IIS installed.  For instructions on installing IIS on Windows 7, check this post.  Included in the samples are several ways you can use WIF.  For this post we’ll look at the PassiveRedirectBasedClaimsAwareWebApp found in {Program Files}\Windows Identity Foundation SDK\v3.5\Samples\Quick Start\Web Application.

To get started with the samples after you installed IIS, be sure to run the SamplesPreReqSetup.bat in {Program Files}\Windows Identity Foundation SDK\v3.5\Samples\Utilities (You must run this “as administrator”)
image 

After running the pre-requisite setup, you need to run the Setup.bat in {Program Files}\Windows Identity Foundation SDK\v3.5\Samples\Quick Start\Web Application and once again be sure to run as administrator.

To test your app just point your browser to https://localhost/WebControlBasedClaimsAwareWebApp/default.aspx.  Log in with your windows account and you should see a page listing the claims in the token.  Note the https; during the pre-requisite setup the scripts will create an SSL cert and enable SSL on your machine. 

Let’s Add a Claim

The STS is located in the PassiveSTS project.  Open App_Code and then the MySecurityTokenService.cs file.  This is the STS implementation.  You can look through the code to get a feel for how the STS works.  To add claims, jump down to the GetOutputClaimsIdentityMethod.  To add a claim use the following snippet:

outputIdentity.Claims.Add(new Claim("http://christopherDeweese.com/Claims/Twitter", "@cdeweese"));

We’ll also need to alter the web applications to support the claim.  The code in the apps will ignore claims it is not expecting.  Open the default.aspx.cs in WebControlBasedClaimsAwareWebApp.  Add the following code near the top where the ExpectedClaims field is defined:

 string[] ExpectedClaims = new string[]  {   Microsoft.IdentityModel.Claims.ClaimTypes.Name,
"http://WindowsIdentityFoundationSamples/myID",
"http://WindowsIdentityFoundationSamples/2008/05/AgeClaim",
"http://christopherDeweese.com/Claims/Twitter"
                                            };

When you browse to the page your output should look something like:

image 

What Just Happened?

Nothing like learning about it by diving in head-first.  When we made our first request to the web app it could not locate our token with the claims and we were immediately redirected to the STS where we were prompted for our logon credentials.  After we were authenticated the STS built an identity which was returned in an encrypted token and we were redirected back to the web app.  This time the web app found our token and allowed us in, displaying the page we see above.

Conclusion

Windows Identity Foundation is a different way to solve your identity problems.  WIF focuses on a model that focuses on how the problem is dealt with in the “real-world”; though we haven’t solved it there yet either.  This will hopefully be part one of many posts that will cover WIF and the good, bad, and ugly of using it to tackle identity problems head-first.

2010 MVP Summit Experience

MVP Summit 2010 002

Before I get started, I’ll just say that if you are here to read about things I learned or saw at the summit you will be disappointed.  Most all of what I saw and learned was under NDA, so I won’t be talking about any content.  What I will talk about is the experience and my thoughts around the MVP program and my first summit.

As a new MVP I had heard a lot about the MVP summit and what goes into it.  Actually being at the summit truly opened my eyes to the depth of the MVP program and the people who are working hard everyday to build products for Microsoft.

The Summit

The summit has evolved over the years, but the basic idea is to get all the MVPs together to network and link them with product teams to provide real feedback that makes it into products we use everyday.  One of the best parts of the summit was being on the campus at Redmond with the 18,000 people who work there everyday.

Bellevue, the Sights & Sounds

This year’s summit was centralized in Bellevue, WA which is just a few skips down the highway from Redmond.  Bellevue has underwent a lot of updates in the last several years and is one of the cleanest and most attractive towns I’ve been to in a while.  Most MVPs were at the Hyatt or Westin which is attached to the Bellevue Square via a few sky bridges and walkways.  There were almost too many good food choices and an unbelievable amount of shopping available. 

Clint Edmonson, Chris Sutton and I even managed to squeeze in a late night showing of Avatar in Imax 3-D which was phenomenal. 

Product Team Interaction

Meeting with the product teams was a great experience.  Some of the smartest people in the world are working in Redmond and they have a lot of tough choices to make.  All of the product teams have trade-offs to make in terms of balancing the features and delivery times as well as limitations on what they have to work with.  It is hard to articulate what a tough job the teams have without going to specifics.  My respect for the product teams increased 1000-fold, and believe me, those teams know when something isn’t what it could be and they will work to get it there for V-next.

As users of their products it is easy to think that these people have no idea what they are doing, but the fact is I heard many of the teams say they knew something was not what it could be or that they were in situations where they didn’t know what the best choice would be.  Those teams face the same choices us “normal” developers do  except they have the scrutiny of developers across the world when something isn’t perfect. 

Breakout Sessions

I was able to attend several of the breakout sessions which covered various products & technologies.  The largest session I attended was the Developer & Platform Evangelism Session where all the US MVPs met with the evangelism teams that work throughout the United States.  We all received a very nice jacket for our participation.  Thanks DPE!

DPE MVP Jacket

Overall

Being an MVP is a huge honor.  To be included with some of the most passionate and outspoken technologists is an amazing experience.  Seeing MVPs who I only know via Twitter and Blogs and reading about their accomplishments just shows how much MVPs live and breathe technology and making it work for people. 

There are a lot of exciting developments coming in 2010.  Rest assured that as soon as we can, MVPs from all over the world will be sharing those insights with you!

To see more about my MVP Summit experience, check out the Flickr photos.