Temperature User Defined Type for SQL Server Yukon

In SQL Server 2005/Yukon you can create user defined types using managed code. User defined types can be used in declaring variable and table columns. It is generally considered to only make sense for scalar types - things that can be sorted, compared, etc. not unlike the native numeric types and datetime. This is not however a fixed requirement, but its definitely the primary scenario being addressed by UDTs.

Here is an example of a temperature type, which is in fact a scalar. All UDT's have to be inserted as strings (i.e. in quotes). Not surprisingly, as part of the contract to implement a user defined type you should have a ToString and Parse method. This example allows the user to insert values in either Kelvin, Fahrenheit, or Centigrade by suffixing the entry with K, F, or C respectively. The default is Kelvin should you not include a suffix for the scheme, so 273, 273K, 0C, and 32F are all equivalent entries. All entries are converted and stored into Kelvin. This makes it easy to have the type byte orderable for easy sorting/comparisons, however this implementation also keeps track of the input format. So if you enter in 0C, you'll get OC back by default. You can however call x.Centigrade, x.Fahrenheit, or x.Kelvin properties to get the measurement scheme you desire. And since the type is byte orderable, you can sort by columns of this type and you'll get something like....

0K, -272C, 32F, 0C, 273K, 274K, 100C, all ordered by their underlying storage which in Kelvin is.
0, 1, 273, 273, 273, 274, 373.

Finally I have also declared as an example a TempAdder user defined aggregate to round out the example. I'm no scientist, but I'm not sure that temperatures are exactly additive, so this is really just for example purposes. The UDA is relatively self explanatory. You are responsible for keeping a variable around to accumulate values into. That leads into the accumulate method which gets called for every item in the result set to be aggregated. There is an init method for initializing your variables and finally a terminate method which is what is called when the result set is finished and you can return the result. The odd method is the merge method - which takes another aggregator. Because of parallel query processing, it is possible for two threads to individually deal with different parts of the entire result set. For this reason, when one thread finishes it's part of the aggregation, it will pass the other aggregator it's aggregator so they can be merged. For this reason I have my interim totals as a public property on the aggregator so i have access to that in the merge method. Furthermore, if you are calculating averages for example you may need the count as well as a public property.

Bottom line - is that creating user defined types and aggregates is a pretty straightforward. Any complexity will be a result of the actual complexity of your types. Consider a lineage type that must work with multiple measurement schemes (metric and imperial) and also multiple units of measurement (cm, m, km) but also multiple units of measurement at one time (i.e. 4' 10”). Don't even get me started on 2”x4”s which aren't actually 2” by 4”. The nice thing about UDT's is that it allows you to encapsulate a lot of this code deep down in your storage layer, allowing your business applications to deal with things more abstractly.

using System;
using System.Data.Sql;
using System.Data.SqlTypes;

[Serializable]
[SqlUserDefinedType(Format.SerializedDataWithMetadata, IsByteOrdered = true, MaxByteSize = 512)]
public class Temperature : INullable
{
 
 private double _kelvin;
 private bool n = true;
 private string inputFormat;

 public string InputFormat
 {
  get { return inputFormat; }
  set { inputFormat = value; }
 }

 public double Kelvin
 {
  get { return _kelvin; }
  set
  {
   n = false;
   _kelvin = value;
  }
 }

 public double Centigrade
 {
  get { return (_kelvin -273); }
  set
  {
   n = false;
   _kelvin = value + 273;
  }
 }

 public double Fahrenheit
 {
  get { return (this.Centigrade*1.8 + 32); }
  set
  {
   n = false;
   this.Centigrade = (value - 32)/1.8;
  }
 }
 public override string ToString()
 {
  string s = this.Kelvin + "K";

  if (this.InputFormat == "C")
  {
   s = this.Centigrade + "C";
  }
  else if (this.InputFormat == "F")
  {
   s = this.Fahrenheit + "F";
  }

  return s;
 }

 public bool IsNull
 {
  get
  {
   // Put your code here
   return n;
  }
 }

 public static Temperature Null
 {
  get
  {
   Temperature h = new Temperature();
   return h;
  }
 }

 public static Temperature Parse(SqlString s)
 {
  if (s.IsNull || s.Value.ToLower().Equals("null"))
   return Null;
  Temperature u = new Temperature();
  string ss = s.ToString();

  if (ss.EndsWith("C"))
  {
   u.Centigrade = double.Parse(ss.Substring(0, ss.Length - 1));
   u.InputFormat = "C";
  }
  else if (ss.EndsWith("F"))
  {
   u.Fahrenheit = double.Parse(ss.Substring(0, ss.Length - 1));
   u.InputFormat = "F";
  }
  else if (ss.EndsWith("K"))
  {
   u.Kelvin = double.Parse(ss.Substring(0, ss.Length - 1));
   u.InputFormat = "K";
  }
  else
  {
   u.Kelvin = double.Parse(ss);
   u.InputFormat = "K";
  }

  return u;
 }

}

using System;
using System.Data.Sql;
using System.Data.SqlTypes;
using System.Data.SqlServer;


[Serializable]
[SqlUserDefinedAggregate(Format.SerializedDataWithMetadata, MaxByteSize = 512)]
public class TempAdder
{
 public void Init()
 {
  total = new Temperature();
  total.Kelvin = 0;
 }

 private Temperature total;

 public Temperature Total
 {
  get { return total; }
  set { total = value; }
 }

 public void Accumulate(Temperature Value)
 {
  this.Total.Kelvin  = this.Total.Kelvin + Value.Kelvin;
 }

 public void Merge(TempAdder Group)
 {
  this.Total.Kelvin = this.Total.Kelvin + Group.Total.Kelvin;
 }

 public Temperature Terminate()
 {
  return this.Total;
 }
}


 

Modeling as a Productivity Enhancer in Visual Studio Team System

It's been a theme for me over the past couple of weeks where people have mentioned that they can't afford the time to do modeling. If you've done a lot of UML modeling, you know what I'm talking about. But it doesn't have to be that way. Now just to ward of the UML flames, even when UML modeling seems like a waste of time, it may actual pay for itself if you uncover a requirement or a design flaw that you wouldn't have otherwise. Certainly catching this kind of thing early than later pays for itself. But that's not what I'm talking about.

In my days as an ERwin/ERX user, doing data modeling was done in this tool not only because it was good to visualize something quickly before committing to code. Using ERwin/ERX was just plain faster than cutting DDL code manually - or heck, even using the Database diagramming in SQL Server. One simple feature was foreign key migration - you drew a relationship from parent to child and bam - it copied down the pk from the parent table and set it up as a fk on the child table.

For the VSTS class designer to be successful (or any of the designers for that matter) MS needs to make using them just plain faster than stubbing out the code manually. Visual Studio has a great editor so they have their work cut out for them. It gets even better with things like code snippets. Why not enable some of the code snippets in the class designer? I can still create a single field wrapped up by a public property faster in the code editor using a snippet (in C# “prop“) than using the class designer - but I don't see why they couldn't add support for that in the class designer too.

A feature I stumbled upon last week was the ability to override a member. Simply right click on the descended class, and select “Override Member“ and you'll see a list of members from the ancestor that are overridable. Select the member to override and bam - you have the code stub. This reminds me a bit of the Inherited Class Skeleton Generator. This represents the kinds of productivity features that can make models/designers more usable, even if just for productivity sake.

There are obviously some types of edits that are better performed in the code editor, such as actually editing code fragments. Other types of edits can be performed more appropriately in the model such as stubbing out the api/members of a class, overriding members, etc. Let's not forget the other types of edits which are much better done in a WYSIWYG designer such as the windows or web forms designer.

One thing I'd like to see come in the Class Designer is a flattened out view of a class that collapses all inherited members into one layer. I'll call this the consumer or intellisense view of a class. It's helpful for viewing the entire interface to a class so I can see how the whole thing makes sense to a user. I would propose a greyed out notation or perhaps a lock icon or something similar to the online help view of a class.

Copy & Paste Support in VSTS Class Designer/Whitehorse

You may have noticed that the refactoring menu's that you see in the code editor are also available in the Class Designer. Furthermore, you can also copy & paste things from one class to another. So if you copy a property from one class to another, not only do you get the property added to the class, but also all the code in your getter's and setters. Ok so this is a nice touch that can help with a refactoring effort that requires moving stuff around - but don't consider this code reuse :)

New Course! Architecting Applications with Visual Studio Team System (Bootcamp)

On March 17th in Toronto, I'll be teaching our first delivery of this new course. It's a one day hands on, instructor led - whirlwind bootcamp style course that gives you a lap around Visual Studio Team System - specifically with a Solution Architect's perspective. We touch a little bit on the project management stuff, testing and some of the developer tools, but primarily we'll spend more than half the day on modeling as we walk through the Whitehorse designers.

Now how can we teach a course on a product that's not even in beta you ask? Very carefully. A lot of people are evaluating if and how they'll use VSTS in their shops once it is released so by popular demand we're offering this course a little earlier than we would normally. This course probably needs to be 3 days to properly focus on best practices and true “architecture” but for the purposes of evaluating this technology and letting people make their own minds, we are focusing primarily on the tools provided. With that in mind, this abbreviated 1 day course is being delivered in 6 cities across Canada: Toronto, Montreal, Ottawa, Vancouver, Calgary and Quebec City. There is also a promotional price of $299 CAD. For more details, full schedule and registration, visit http://www.objectsharp.com/ttdinvitation/vstsbootcamp.aspx 

 

 

Anticipation

Now here is news that I have been waiting to hear.  Whidbey Beta 2 will probably be released in the next couple of days.  For me, this is very cool news, as I have been looking forward to getting the Go Live license.  For more information, check out Wesner Moise's blog entry here.

DevTeach June 18-22, Montreal and a $50.00 Rebate Code!

DevTeach is a really nice conference. I went to it for the first time last year and it's a very intimate and interactive conference. While smaller than your TechEd's and PDC's, it manages to attract a very good set of speakers....Kevin McNeish, Brian Noyes, Julia Lerman, Don Kiely, Patrick Hynds, Carl Franklins, Mario Cardinal, Ted Neward, Nick Landry, Etienne Tremblay, Sam Gentile, Jim Duffy, Guy Barrette, Eric Cote, Markus Egger, Kate Gregory and me too. I'll be doing a DataSet tips and tricks talk - but mostly just so I can get a free pass to go and see all the other great talks. This year it is being held once again in Montreal which is a beautiful city with a great night life.

And last but not least, here is a rebate code for $50.00 "TO000OBJSHARP". You can register at http://www.devteach.com

Get your Free Visual Studio Tools for Office custom applications here.

Ok, this is very cool - not often somebody gives you something for free.

Is your company upgrading to Office 2003 between June & July of this year?

Could you envision a customized solution built on top of Office - perhaps using Visual Studio Tools for Office, to solve some business need? If so, not only can we help with that, but Microsoft Canada is willing to foot the bill for the development effort. This is a great risk free way to try out Visual Studio Tools for Office projects - either the current 2003 or 2005 versions.

For more info, drop me an email. bgervin@objectsharp.com

What are you doing for your summer job?

We have a very exciting internship project coming up this summer for a university student, perhaps co-op - but not mandatory.

This high-profile project is to develop a software system to monitor the various systems in a “green” home that is completely off of the power grid. The house is fed by batteries charged by solar and wind (and a backup generator). There are many other systems in place to optimize power usage throughout the house. Although this home is off the grid, it's not off the internet, so the software will have to publish it's information and allow remote access via it's 2-way satellite system. The software will also be developed in .NET, likely using the current whidbey beta.

You are a university student with some combination of electrical engineering and computer science. You are strong “quality-oriented” programmer. You have strong design skills and are good at listening and capturing requirement. The position will be located in southern ontario.

If you are interested, please send your resume to bgervin@Objectsharp.com .

.NET Celebrity Auction

Be a sport and click on this link:

http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=5552696499

Then make a generous bid. If you'll win, you'll get an hour (or more) of help from a .NET guru/celebrity (or possibly me). But more, you'll also be helping Tsunami relief efforts.

The top bid gets to pick their consultant. Then next, and so on and so on. If you are in southern Ontario, and you get me, I'll make it up to you by coming to your office - for a whole day, hang out, and bring donuts. What will I do? I can tell you everything I know about Visual Studio Team System (breaking all kinds of NDA rules, etc.), try to convince you to use data sets, do some code reviews, help debug something nasty, defrag your hard drive, organize your mp3's, tell you what DataGrid girl is really like, whatever.

I'm visiting Vancouver, Calgary, Ottawa, Montreal over the next 3 months so if you live/work near there, my offer stands, pending my schedule. I'll also be in Orlando possibly in June (for TechEd), LA in Sept (for PDC), and Chicago in August, so ditto on those as well.

For more info on how it all works....

http://www.stephenforte.net/owdasblog/#a61b646aa-ca24-47ef-b013-012bf852f79d

And finally, special thanks to the other RD's who are volunteering their time (especially all those fellow Canadians). Last but not least, special thanks to Stephen Forte and Julia Lerman for organizing this.

Trip to Ottawa and Requirements Traceability

I just got back from Ottawa, where last night I was speaking to the Ottawa .NET community about Visual Studio Tools for Office. (more on that later).

I wasn't surprised by the Grep Cup weekend inflated hotel rates, but I was surprised to find a “2.8% DMF Fee” on my hotel bill (on top of the 15% worth of federal and provincial taxes). Upon request, I was informed that this was a “Destination Marketing Fee” which goes to fund marketing efforts to promote tourism in the area. Various Ontario tourism centers (including Hamilton - go figure?) have been lobbying the provincial governments since post 9/11 in an effort for them to allow a tax (a real tax, not a fee) for the same purpose. This past summer however, the hotels decided that this was going nowhere so they decided to start collecting (on a voluntary basis) a fee (not a real tax).

Maybe it's just me, but I'm thinking the best way to attract people to your city is not to put a sneaky “DMF Fee” charge on those same people's hotel bill when they come to visit you and hope they don't ask about it. Even worst, because it's a fee charged by the hotel, and not a real tax - guess what - you pay tax on the DMF Fee. Icarumba! It turns out it's voluntary fee and not hotels collect it. The front desk staff sensed I was not pleased about being asked to pay for marketing fees on top of my room rate so they quickly waived the fee. But I wonder how many people willing pay this?

This all reminds me very much about requirements management and software development. Often, people, usually too close to the problem, design features into software that doesn't meet the requirements of the user. Take for example those goofy glyphs on the Lotus Notes login window. What about clippy? Is that satisfying anybody's requirements - or is it just pissing you off? With all of our best intentions, it is extremely important that we take the time to perform reality checks on what we are building against the requirements of our users.

Now to bring it all home. Do users really want to do their work in a web browser? Browsers are great for wandering and finding stuff, but do they want to see the value of their stock portfolio in a browser? You need to find the best environment for the job your users are trying to accomplish. If somebody is accustomed to using Excel to aggregate a bunch of their financial information, then maybe Visual Studio Tools for Office is the right tool for that job. While writing applications in Excel isn't exactly new, with VSTO you have the integration with the .NET Framework, Web Services, and the smart client deployment model, you can apply all professional development skills you have at your disposal to creating applications with Word & Excel. And don't worry, I have yet to see clippy show up in Visual Studio Office projects.