March 2005 - Posts

Example Code, Redux

I’m still trying to rationalize the existence of example code. You know, the poison pills programmers copy and paste into an otherwise healthy body of software.

Sometime today, I was thinking back my first physics class, and of three key idealizations. These idealizations have helped students learn physics since the debut of Principia Mathematica in the 1680s.

The idealizations are:

  The immoveable object.
  The irresistible force.
  The frictionless surface.

Of course, nobody actually builds bridges or launches rockets using irresistible forces and frictionless surfaces, but the concepts do make the first chapters in a physics textbook easier, and we learn from them. If there are parallels to these idealizations in the sample code on MSDN, in books, and on this blog, they would be:

  The never-null parameter.
  The always-on network.
  The perfect string of user input.

We learn from them.

posted by scott with 8 Comments

Indigo Notes

I’ve had some time to experiment, and downloaded the WinFX CTP to give Indigo a whirl. The installation onto a Virtual PC with the VS2005 February CTP went swimmingly. I thought for a first try I’d write a client for an existing web service, and since I have a few VPCs with Reporting Services installed I looked to start a conversation between the two.

I created a plain console mode application, and added a reference to the System.ServiceModel assembly. The next step was to generate proxy classes from the Reporting Services service contract (the WSDL from ReportService.asmx).

You can create proxies with the Service Model Metadata command line tool “svcutil”. Reporting Services requires an authenticated caller by default, but I did not find a way for svcutil to send my credentials. I could work around this problem by hitting the WSDL page with IE and saving a WSDL file to disk, but it turns out authentication made for more difficulties later on, so ultimately I setup Reporting Services to allow anonymous access.

The first pass with svcutil failed and told me it could not import the type ArrayOfStrings. With help from Hoop in the newsgroups, I finally got the right command line switches needed to create proxy classes.

>svcutil /out:ssrs.cs /config:app.config /tm /uxs http://reporting/reportserver/reportservice.asmx

 

 

Microsoft (R) Service Model Metadata Tool

[Microsoft(R) .NET Framework, Version 2.0.50110.20]

Copyright (C) Microsoft Corporation. All rights reserved.

 

Generating files...

C:\dev\indigo\ListReports\app.config

C:\dev\indigo\ListReports\ssrs.cs

In the above command line I’m asking svcutil to generate a config file, to generate code using typed messages (/tm) and to generate code using the XML serializer (/uxs). The generated code goes into a file I named ssrs.cs. I’ll point out the impact of these switches in a moment, but it is interesting to note that the tool refers to the XML serializer as The Xml Serializer, so use caution, we may not realize the power we are wielding with these new tools.

The tool generates a file with all of the data contracts and service contracts, and with a proxy class to instantiate and invoke the service methods. An example of a data contract is the complex type CatalogItem (excerpted below), which represents an item (report, data source, folder) in the Report Server catalog.

[System.SerializableAttribute()]

[System.Xml.Serialization.XmlTypeAttribute(

  Namespace="http://schemas.microsoft.com/.../reportingservices")]

public partial class CatalogItem

{

    // ...  

 

    private string nameField;

 

    ///

    public string Name

    {

        get

        {

            return this.nameField;

        }

        set

        {

            this.nameField = value;

        }

    }

 

    // ...

}

Since we requested svcutil to use The XML Serializer we have serialization attributes decorating the classes instead of the DataContract attributes mentioned by Clemens Vasters. It is nice to see the generated code using private backing fields and exposing public properties - this approach does simplify serialization and data binding and is something the current tools do not give us. To mark the class as partial is also a nice touch and allows for easy extensibility without forcing inheritance.

There is also the service contract itself in the generated code, excerpted below.

[

  System.ServiceModel.ServiceContractAttribute(

    Namespace="http://schemas.microsoft.com/.../reportingservices",

    FormatMode=System.ServiceModel.ContractFormatMode.XmlSerializer)

]

public interface ReportingServiceSoap

{

    // ...   

 

    [System.ServiceModel.OperationContractAttribute(

      Action="http://schemas.microsoft.com/.../ListChildren",

      ReplyAction="http://schemas.microsoft.com/.../ListChildren")]

 

    ListChildren_ResponseMessage ListChildren(ListChildren_RequestMessage request);

 

    // ...

}

The ListChildren method returns an array of CatalogItem objects representing the content of a folder in the Report Server catalog. The method is documented as taking two parameters: the path of the folder to list, and a boolean to indicate if the listing should recurse through the subfolders. Since I told svcutil to generate typed messges (/tm), the tool packaged these parameters and return into ListChildren_Request and ListChildren_Response classes respectively. I’m not sure how I feel about this construct as yet, but it does make our intention to hop over the network look explicit.

The following program uses the generated goop to list all of the reports on the server.

using System;

 

namespace ListReports

{

    class Program

    {

        static void Main(string[] args)

        {

            ReportingServiceSoap ssrs;

            ssrs = new ReportingServiceSoapProxy();

 

            ListChildren_RequestMessage request;

            request = new ListChildren_RequestMessage();

            request.Item = "/";

            request.Recursive = true;

 

            ListChildren_ResponseMessage response;

            response = ssrs.ListChildren(request);

 

            foreach (CatalogItem item in response.CatalogItems)

            {

                if (item.Type == ItemTypeEnum.Report)

                {

                    Console.WriteLine(item.Path + item.Name);

                }

            }

        }

    }

}

Going back in time for a moment, the svcutil tool also generated an app.config file. One of the strengths in Indigo is the ability to defer the endpoints, transports, and protocols to configuration files and keep them out of the code. I tweaked the app.config slightly and the result looks like the following.

 

   

     

          address="http://reporting/ReportServer/ReportService.asmx"

          bindingConfiguration="ReportingServiceSoap"

          bindingSectionName="customBinding"

          configurationName="ReportingServiceSoap"

          contractType="ReportingServiceSoap">

         

              identityData=""

              identityType="None"

              isAddressPrivate="False" />

     

   

   

     

       

         

              mapAddressingHeadersToHttpHeaders="True"

              transferTimeout="00:10:00" />

         

              maxReadPoolSize="64" maxWritePoolSize="16"

              messageVersion="Soap11Addressing1" encoding="utf-8" />

       

     

   

 

An endpoint defines the network address to use, as well as the binding (how to communicate) and contract (what operations are available). Our binding specifies we will be using HTTP. It is in this area where Indigo truly feels like a technology preview, in the sense that watching a 30-second movie trailer on TV is just a preview to sitting in front of a big screen watching the full length feature. I couldn’t dig out enough details on configuration to determine what knobs are available for tweaking and tuning in this area, but it gives off an aura of being infinitely flexible, and composable.

On the surface, and from a client perspective only, the Indigo experience is not dramatically different from what we have today, and should be easy to pick up. The exception is configuration, which has a lot more to offer – all we need is better documentation to understand what is possible.

Getting underneath into the details, or developing a service, however, requires one to learn a new Indigo vocabulary. Indigo-ese, shall we say. One of the best ways to learn Indigo-ese is to listen or read as people use Indigo-ese. The following sources are chock full of Indigo-ese:

  Clemens Vasters: “A Weekend With Indigo”: Part I, Part II, Part III.
  Steve Maine: Amaze Your Friends With Duplex Contracts.
  Don Box: Service Contracts In Indigo.
  David Chappell: Introducing Indigo: An Early Look

posted by scott with 0 Comments

Thought For The Day

Taking the thoughts, ideas, and emotions we have in our brain,

and encoding them into an audible form, or a textual representation,

is a lossy compression at best…

posted by scott with 9 Comments

Team $ystem

Don’t you just love when those brash, young h4xxorz in the newsgroups type Microsoft with a $ sign? Such a rebellious nature….

It’s interesting to watch the reaction to the obfuscated pricing announcement for VS 2005 Team System (a readable version, with opinion, is presented by Mike Gunderloy).

Is Team System expensive?

Expensive is a relative term, isn’t it?

Is CaliberRM expensive? Is Rational Rose Enterprise expensive? Is ClearCase or Perforce expensive? Have you ever priced just their yearly support contracts for an enterprise?

I don’t think the price is surprising given the above list, but I was hoping Team Foundation Server would be where Microsoft tried to make  money back. The server seems reasonably priced, but Visual Studio and MSDN subscriptions are handing out sticker shock – particularly to independent consultants who pay for subs out of their own pocket.

MSDN subscribers are accustomed to having the fully loaded IDE, but it doesn't look like this will come with an easily justifiable price anymore.

posted by scott with 2 Comments

The Worst of the .NET 1.x Years

It’s been a wild ride for the last 5 years. We’ve seen the best - what about the worst?

1)Visual Basic.NET

The problem isn’t with the language – VB is a great language, and I’m not formulating my “best and worst lists” based on technology virtues alone, but on the “experience”.

The controversy over Visual Basic.NET started before the product’s release date. Then came the salary surveys, the misinformation, disinformation, statistics, lies, videotapes, benchmarks, whining, moaning, and gnashing of teeth.

The debate over the merits of this language seem to be in an infinite loop.

Bill Vaughn is right: Microsoft should have named the new language B#. Same language – different name – it would be a success story.

2)Managed C++

Being a former C++ __type myself, I investigated the __new managed __extensions. __For some __reason I could __never __warm __up to the __syntax. I hear^ there are^ some changes^ in store^ for 2005.

3) Tight Coupling of Visual Studio to IIS

With an ASP.NET project, have you ever…
had the wwwroot$ share disappear?
wrestled with front page server extensions?
seen an entire folder disappear?
tried to put the project under source control?
tricked Visual Studio into thinking the project isn’t really a web project?
built the project with an automated build engine? No - no - without Nant!
debugged as non-admin?
been unable to open a web project?
seen a ‘web access failed’ error message?
had a problem moving a web project from one computer to the other?
created a web application without admin privs?

This too shall pass in 2.0

4) IDisposable

If I had a dime for every time the intricacies of IDisposable were explained in newsgroups, mailing lists, conference halls, chat rooms, bathrooms, and blogs – I’d buy myself a Formula One race car, and drive it 6 days a week on my own private racetrack.

Then to find out there is special case reference counting in the framework...

5) Smart Clients

Despite all the hype – smart clients seem to have gained very little traction in the 1.x timeframe. Smart clients are once again poised to take the world by storm with Click-Once deployment in 2.0. Where has the love been for the HREF EXE? Do you think we can write an application like World Wind with AJAX?

The above opinions are my own, and do not necessarily represent the viewpoints of anyone else I know.

posted by scott with 12 Comments

The Best Of .The NET 1.x Years

Given that .NET 1.x is entering legacy status before the end of the year, I thought it might be fun to explore the best and worst of what .NET developers have lived through for the past 5 years.

First: the best.

1) Metadata

Metadata is the lifeblood of the common language runtime. Just think of the number of features made possible (or made better) by the presence of metadata: garbage collection, form designers, code access security, and verification to name a few. The fact that metadata is extensible through custom attributes opens up a world of possibilities. Sure, we might have gotten tools like NUnit and Reflector without metadata, but they might have really sucked.

2) Visual Studio

The multilingual IDE does web, windows, and mobile development, too. If you face being stranded on a desert island with a Windows machine, AC power, and broadband access, but can install only one piece of software on top - take Visual Studio. Given enough time, you can write the rest. (What piece of software would you write first?).

Again, extensibility plays a huge rule in the success of Visual Studio. If you haven’t worked with one of the many great VS.NET ad-ins in Scott Hanselman's Ultimate List, you just haven’t lived.

3) Community

When people like Chris Brumme spend their time waiting at the dentist writing deep technical blog posts like “TransparentProxy”, then you know times are changing. When I'm at the dentist I usually hide behind large, potted vegetation reading National Geographic, pretending I’m somewhere else, and hoping they forget I’m there, but everyone handles thier phobias differently.

Besides blogs, we have an explosion of webcasts, chats, user groups, code camps, and geek dinners. There is no time to shower or pay bills - submerse yourself now in the world that Scoble built.

4).NET Class Libraries

Every non-trivial framework has the occasional bump in the road, but let’s not talk about the System.DirectoryServices namespace while we are in a good mood, ok? The usability, intuitiveness, and discoverability of the libraries have played a large role in the adoption of .NET and the productivity of .NET programmers.

5) The Common Type System (CTS)

The CTS lays the foundation for not only C#, C++, and Visual Basic to work together, but a slew of other languages (see former Bon Jovi look-alike Jason Bock’s .NET languages list). No small feat, the CTS. It’s a rewarding experience being able to jump into a new language with foreign syntax but still have some bearing as to what is happening underneath.

Next up: the worst. Don't miss this one.

What would you include in the “best of” list?

posted by scott with 12 Comments

SiteMapResolve

The SiteMap.SiteMapResolve event is set to cause major headaches in ASP.NET 2.0 development. Jeff Prosise talks about the need for the event in a post entitled “Cool ASP.NET 2.0 Programming Trick”. Jeff appears to be taking the wrong approach.

As ASP.NET developers we are accustomed to wiring up events to methods in our Page derived classes. However, SiteMapResolve is a global (defined as public and static) event on the SiteMap class and will fire when resolving a node for any page in the application, not just the subscribing page. Also, we aren’t used to unsubscribing to events in ASP.NET but SiteMapResolve, being a root, will hold on to any references we hand off through a delegate until the universe collapses, or the AppDomain unloads, whichever happens first.

The best solution to work with SiteMapResolve is going to involve a singleton or static class. The best solution I have so far appears to be unfortunately very messy.

posted by scott with 5 Comments

Recruiters

There seems to be a surge in ‘recruitment’ lately, but I use the term loosely.

I’ve been receiving emails from strangers like the following:

Subject: I have a C# developer position

Are you interested? If so, give me a call.

Is recruiting just so easy thee days that they don’t even have to try? Isn’t this like writing:

Subject: I have a sex organ

Are you interested? If so, give me a call.

I’d think it would be obvious that a few more minor details, like compensation, location, and type of work, are needed for someone to judge their interest in a sexual organ, but maybe I’m just conservative that way.

posted by scott with 4 Comments

For Example

I’ve heard complaints about the poor state of example code. Example code, it seems, is ruining programmers across the globe.

Let’s divide the world’s code into two categories: production code, and example code. Much like matter and anti-matter, the two should never meet. They exist for different purposes, and have distinct goals.

The only feature these two have in common is that both production and sample code can be difficult to write. Yes, ask any author – coming up with sample code to illustrate a specific point can be a hair pulling experience. Do I contrive an example to keep the sample as short as possible while getting the point across? Alternatively, do I come up with a “real” example at the risk of complicating the explanation? Like everything else we do, there are tradeoffs to evaluate.

Improving sample code isn’t going to improve the developers of the world. The developer who cuts and pastes from MSDN documentation has other fundamental problems.

Don’t blame bad software on the authors of sample code. Instead, blame the authors of the software.

posted by scott with 4 Comments

The ThreadStaticAttribute

Thread local storage (TLS) was a fun way to piggyback data into the thread environment block (TEB) in the old days. You can ask each thread in a process to reserve a location to store your special data, say for example, a pointer to a data structure representing a database transaction. No matter where the thread goes, you can always pull the transaction reference out of TLS and go to work – no function parameters required!

The managed equivalent of TLS is the ThreadStaticAttribute class.

Taking advantage of TLS has always been tricky in an environment using thread pooling. As Scott Hanselman and Jef Newsom point out – ASP.NET uses a thread pool, and one has to take extreme care using the ThreadStaticAttribute in ASP.NET. The majority of people asking about using TLS have not really wanted to track a resource associated with a thread, but a resource associated with an HTTP request - which is just what HttpContext.Items is in place to take care of.

I’ll offer up one more reason to avoid ThreadStatic in ASP.NET, and that is the new Async page feature coming in ASP.NET 2.0 (@Page Async=”True”).

Instead of blocking request threads during processing of web service calls to say, Reporting Services, marking an ASP.NET 2.0 Page as Async allows the thread to hop back into the pool and process other requests. When the web request finishes, a thread will return to finish rendering the page. Will it be the same thread? I don’t have proof yet but I would seriously doubt it will be guaranteed. Use TLS and you'll certainly be pooched sooner or later.

There is not a lot out yet about Async pages in 2.0 – I’m interested to see if it will be working in the Feb CTP. Looks like Frtiz Onion has an example up already.

posted by scott with 0 Comments

The BoneheadAttribute

I had some time to research SQL Server 2005 this weekend and ran across the HostProtectionAttribute (HPA).

The ability to write stored procedures and such with your favorite .NET language opens up a dangerous number of APIs, like Process.Start, which can kill a server’s throughput and reliability. The HostProtectionAttribute lets SQL Server look out for dangerous code.

Say we write the following stored procedure:

<SqlProcedure()> _

Public Shared Sub PureEvil2()

    SyncLock (GetType(StoredProcedures))

        ' do work

    End SyncLock

End Sub

The above code will compile and deploy into the SAFE bucket of SQL Server without complaint. Execute the proc however, and the host protection kicks in:

Msg 6522, Level 16, State 1, Procedure PureEvil2, Line 1 A .NET Framework error occurred during execution of user defined routine or aggregate 'PureEvil2': System.Security.HostProtectionException: Attempted to perform an operation that was forbidden by the CLR host.

SQL Server doesn’t like our code trying to block a thread. Underneath the covers, SyncLock (VB) and lock (C#) use System.Threading.Monitor. Using Reflector on a v2.0 framework install we can see the Monitor class decorated with a custom HostProtectionAttribute.

[HostProtection(SecurityAction.LinkDemand, Synchronization=true, ExternalThreading=true)]

public sealed class Monitor

{

// ...  

}

SQL Server is looking for the attribute at execution time. Since the HPA can target a struct, class, method, constructor, delegate, or assembly, there must be a bit of overhead involved. I wonder why the verification can’t take place during the CREATE ASSEMBLY deployment?

It will also be interesting to see if the ASP.NET team can take advantage of HPA in the future to keep killer code out of ASP.NET.

posted by scott with 1 Comments

Craftmanship

Sometimes I wonder what I’d be doing if it weren’t for software development.

I’d like to think of myself as being a craftsman in some other profession.

Then the time comes when I need to attach a small block of wood to a wall using two screws. The tricky part is to accomplish the task without destroying the wood, the wall, the screws, or any of the tools.

So much for craftsmanship with my hands. Perhaps I would be a goat herder.

posted by scott with 3 Comments