|
|
These blog entries are written by industry experts and leaders. We consider this content to be a good read for any software developer or web technologist.
May 2007 - Posts
-
This afternoon I kicked off a Team Build and waited...
.. and waited ...
... and waited...
... and then realized something was terribly wrong with the TFS server. A general sense of panic swept into the office when we couldn't bring up the login dialog box on the server's console. A recent rash of hardware failures made us jumpy and we feared the worst. Just a couple months ago, 2 out of 3 drives in a RAID 5 array died in a single afternoon. What are the odds?
The server came back to life after a hard reboot, but the last build was "stuck". There wasn't any activity on the build server, yet TFS thought the build was still in progress. I couldn't find a way to stop the build in Visual Studio, so I turned to the Internet. My first search brought up KillBill.exe – a utility in the TFS PowerPack that "Stops a Team Build currently running on a build server". Perfect!
Afterwards, I found out you can also stop a build from the command line, but that's not nearly as entertaining as an application that evokes thoughts of a hyper-violent kung-fu cinematic mashup.
The other utility in the TFS PowerPack is the "Work Item Terminator". There is a theme at work in this project, and I like it. I hope future versions include the "Clockwork Orange Build Timer" and the "Check-in policy Robocop".

|
-
Microsoft earlier today announced a new product called "Microsoft Surface". If you haven't checked out the online videos of it yet, I highly recommend watching them here. It is one of those products that looks and feels like it comes from a science fiction movie - but it is actually real. Popular Mechanics also has a good article (including their own video) of how it works that you can read and watch online here. One of the really cool things about Microsoft Surface is that the table UI experience is built entirely using WPF and the .NET Framework - which is a great statement about the power of what WPF provides. If you are interested in learning more about programming WPF, there are two great books out there that I've been recommending to people: Both books have 5 star ratings on Amazon.com. You can download the first chapter of Chris' book for free from this web page. Hope this helps, Scott 
|
-
In Part 1 of my LINQ to SQL blog post series I discussed "What is LINQ to SQL" and provided a basic overview of some of the data scenarios it enables. In my first post I provided code samples that demonstrated how to perform common data scenarios using LINQ to SQL including: - How to query a database
- How to update rows in a database
- How to insert and relate multiple rows in a database
- How to delete rows in a database
- How to call a stored procedure
- How to retrieve data with server-side paging
I performed all of these data scenarios using a LINQ to SQL class model that looked like the one below: In this second blog post in the series I'm going to go into more detail on how to create the above LINQ to SQL data model. LINQ to SQL, the LINQ to SQL Designer, and all of the features that I'm covering in this blog post series will ship as part of the .NET 3.5 and Visual Studio "Orcas" release. You can follow all of the steps below by downloading either Visual Studio "Orcas" Beta 1 or Visual Web Developer Express "Orcas" Beta1. Both can be installed and used side-by-side with VS 2005. Create a New LINQ to SQL Data Model You can add a LINQ to SQL data model to an ASP.NET, Class Library or Windows client project by using the "Add New Item" option within Visual Studio and selecting the "LINQ to SQL" item within it: Selecting the "LINQ to SQL" item will launch the LINQ to SQL designer, and allow you to model classes that represent a relational database. It will also create a strongly-typed "DataContext" class that will have properties that represent each Table we modeled within the database, as well as methods for each Stored Procedure we modeled. As I described in Part 1 of this blog post series, the DataContext class is the main conduit by which we'll query entities from the database as well as apply changes back to it. Below is a screen-shot of an empty LINQ to SQL ORM designer surface, and is what you'll see immediately after creating a new LINQ to SQL data model: Entity Classes LINQ to SQL enables you to model classes that map to/from a database. These classes are typically referred to as "Entity Classes" and instances of them are called "Entities". Entity classes map to tables within a database. The properties of entity classes typically map to the table's columns. Each instance of an entity class then represents a row within the database table. Entity classes defined with LINQ to SQL do not have to derive from a specific base class, which means that you can have them inherit from any object you want. All classes created using the LINQ to SQL designer are defined as "partial classes" - which means that you can optionally drop into code and add additional properties, methods and events to them. Unlike the DataSet/TableAdapter feature provided in VS 2005, when using the LINQ to SQL designer you do not have to specify the SQL queries to use when creating your data model and access layer. Instead, you focus on defining your entity classes, how they map to/from the database, and the relationships between them. The LINQ to SQL OR/M implementation will then take care of generating the appropriate SQL execution logic for you at runtime when you interact and use the data entities. You can use LINQ query syntax to expressively indicate how to query your data model in a strongly typed way. Creating Entity Classes From a Database If you already have a database schema defined, you can use it to quickly create LINQ to SQL entity classes modeled off of it. The easiest way to accomplish this is to open up a database in the Server Explorer within Visual Studio, select the Tables and Views you want to model in it, and drag/drop them onto the LINQ to SQL designer surface: When you add the above 2 tables (Categories and Products) and 1 view (Invoices) from the "Northwind" database onto the LINQ to SQL designer surface, you'll automatically have the following three entity classes created for you based on the database schema: Using the data model classes defined above, I can now run all of the code samples (expect the SPROC one) described in Part 1 of this LINQ to SQL series. I don't need to add any additional code or configuration in order to enable these query, insert, update, delete, and server-side paging scenarios. Naming and Pluralization One of the things you'll notice when using the LINQ to SQL designer is that it automatically "pluralizes" the various table and column names when it creates entity classes based on your database schema. For example: the "Products" table in our example above resulted in a "Product" class, and the "Categories" table resulted in a "Category" class. This class naming helps make your models consistent with the .NET naming conventions, and I usually find having the designer fix these up for me really convenient (especially when adding lots of tables to your model). If you don't like the name of a class or property that the designer generates, though, you can always override it and change it to any name you want. You can do this either by editing the entity/property name in-line within the designer or by modifying it via the property grid: The ability to have entity/property/association names be different from your database schema ends up being very useful in a number of cases. In particular: 1) When your backend database table/column schema names change. Because your entity models can have different names from the backend schema, you can decide to just update your mapping rules and not update your application or query code to use the new table/column name. 2) When you have database schema names that aren't very "clean". For example, rather than use "au_lname" and "au_fname" for the property names on an entity class, you can just name them to "LastName" and "FirstName" on your entity class and develop against that instead (without having to rename the column names in the database). Relationship Associations When you drag objects from the server explorer onto the LINQ to SQL designer, Visual Studio will inspect the primary key/foreign key relationships of the objects, and based on them automatically create default "relationship associations" between the different entity classes it creates. For example, when I added both the Products and Categories tables from Northwind onto my LINQ to SQL designer you can see that a one to many relationship between the two is inferred (this is denoted by the arrow in the designer): The above association will cause cause the Product entity class to have a "Category" property that developers can use to access the Category entity for a given Product. It will also cause the Category class to have a "Products" collection that enables developers to retrieve all products within that Category. If you don't like how the designer has modeled or named an association, you can always override it. Just click on the association arrow within the designer and access its properties via the property grid to rename, delete or modify it. Delay/Lazy Loading LINQ to SQL enables developers to specify whether the properties on entities should be prefetched or delay/lazy-loaded on first access. You can customize the default pre-fetch/delay-load rules for entity properties by selecting any entity property or association in the designer, and then within the property-grid set the "Delay Loaded" property to true or false. For a simple example of when I'd want to-do this, consider the "Category" entity class we modeled above. The categories table inside "Northwind" has a "Picture" column which stores a (potentially large) binary image of each category, and I only want to retrieve the binary image from the database when I'm actually using it (and not when doing a simply query just to list the category names in a list). I could configure the Picture property to be delay loaded by selecting it within the LINQ to SQL designer and by settings its Delay Loaded value in the property grid: Note: In addition to configuring the default pre-fetch/delay load semantics on entities, you can also override them via code when you perform LINQ queries on the entity class (I'll show how to-do this in the next blog post in this series). Using Stored Procedures LINQ to SQL allows you to optionally model stored procedures as methods on your DataContext class. For example, assume we've defined the simple SPROC below to retrieve product information based on a categoryID: I can use the server explorer within Visual Studio to drag/drop the SPROC onto the LINQ to SQL designer surface in order to add a strongly-typed method that will invoke the SPROC. If I drop the SPROC on top of the "Product" entity in the designer, the LINQ to SQL designer will declare the SPROC to return an IEnumerable<Product> result: I can then use either LINQ Query Syntax (which will generate an adhoc SQL query) or alternatively invoke the SPROC method added above to retrieve product entities from the database: Using SPROCs to Update/Delete/Insert Data By default LINQ to SQL will automatically create the appropriate SQL expressions for you when you insert/update/delete entities. For example, if you wrote the LINQ to SQL code below to update some values on a "Product" entity instance: By default LINQ to SQL would create and execute the appropriate "UPDATE" statement for you when you submitted the changes (I'll cover this more in a later blog post on updates). You can also optionally define and use custom INSERT, UPDATE, DELETE sprocs instead. To configure these, just click on an entity class in the LINQ to SQL designer and within its property-grid click the "..." button on the Delete/Insert/Update values, and pick a particular SPROC you've defined instead: What is nice about changing the above setting is that it is done purely at the mapping layer of LINQ to SQL - which means the update code I showed earlier continues to work with no modifications required. This avoids developers using a LINQ to SQL data model from having to change code even if they later decide to put in a custom SPROC optimization later. Summary LINQ to SQL provides a nice, clean way to model the data layer of your application. Once you've defined your data model you can easily and efficiently perform queries, inserts, updates and deletes against it. Using the built-in LINQ to SQL designer within Visual Studio and Visual Web Developer Express you can create and manage your data models for LINQ to SQL extremely fast. The LINQ to SQL designer also provides a lot of flexibility that enables you to customize the default behavior and override/extend the system to meet your specific needs. In upcoming posts I'll be using the data model we created above to drill into querying, inserts, updates and deletes further. In the update, insert and delete posts I'll also discuss how to add custom business/data validation logic to the entities we designed above to perform additional validation logic. Mike Taulty also has a number of great LINQ to SQL videos that I recommend checking out here. These provide a great way to learn by watching someone walkthrough using LINQ to SQL in action. Hope this helps, Scott 
|
-
I decided to catch up with the latest Silverlight release. With the WPF/E release last year I dabbled with Conway's Game Of Life, but instead of porting old code I decided to try something new. During my short stint in the video game industry I found Gamasutra to be a great source of technical articles, and the article "Advanced Character Physics" by Thomas Jakobsen gave me an idea. The article describes the verlet integration algorithm used in molecular dynamics models. The subject matter sounds intimidating, but the algorithm turns out to be relatively simple.
Verlet integration (pronounced vehr-LEY (think French)) doesn't track the velocities of each particle in a system. Instead, Verlet calculates a particle's next position using its current and previous positions. The nice feature of Verlet is that enforcing a constraint (like not allowing a particle to move outside of a wall, or not allowing a particle to move too far away from another, attached particle) is almost as easy as repositioning the particle – at least there is no need to calculate a new velocity.
I built a simple, swinging "rope" in Silverlight. The "rope" is composed of 12 Pluralsight logos. Gravity pulls the rope downward, while a left-to-right breeze can blow the rope across the screen. Credit Ian Griffiths for building the Pluralsight eye in XAML . A static screen shot doesn't show the realistic motion ...
... so if you have the Silverlight 1.0 beta install, try the sample here.
You can download the source code here.
Note to Karl Seguin: don't download the code. This was a late night hack on a holiday weekend. If you break into tears then it's not my fault! :)

|
-
I recently finished a couple of different books by Nick Hornby and have come to the conclusion that Nick Hornby is our greatest living critic. I am not sure who beat him for the National Book Critics Circle Award, but they shouldn't have. The first book was Songbook, I actually started reading this book a couple months back but finally got around to finishing it. In this book Hornby talks about 31 different songs that mean something to him. I tried my best to find each song and listen to it while reading the essay about it, but couldn't find them all. Hornby shows such a passion and love for songs, but is also willing to look at the work in context and from a critics perspective. My favorite song from the pack is definitly "Your Love is the place that I Come From" by Teenage Fanclub. The second book was Housekeeping Vs. The Dirt which is the second installment of columns written by Hornby for The Believer. In each of the columns Hornby details the books he has bought and read for the month. I loved his previous collection of the columns, and this one was even better. I am very much like Hornby in that I often buy books that I don't read for months (or years!) but still go out every weekend and buy a couple more, it is great to find someone else with the sickness. Hornby does an incredible job of being both a critic and a true lover of music and books. The only bad thing is that I have now read all of his books (expect for some sportswriting anthologies that I might have to check out) and have to wait for more. -James 
|
-
June is going to be a really busy travel month for me. I'll be presenting at the following events if you are interested in attending and stopping by to say hi: TechEd 2007 in Orlando on June 4th and 5th: I'll be doing a Silverlight talk and two ASP.NET and VS "Orcas" talks. Click here for more details about the conference. ReMIX 07 in Budapest, Hungary on June 11tht: I'll be doing the keynote at the ReMIX conference as well as presenting Silverlight breakout talks. Click here for more details about the conference. ReMIX 07 and DevDays 07 in Amsterdam, Netherlands on June 13th and 14th: I'll be doing the keynote at the ReMIX and DevDays conferences as well as presenting ASP.NET "Orcas" and Silverlight breakout talks. Click here and here for more details about the conferences. ReMIX 07 in Zurich, Switzerland on June 18th: I'll be doing the keynote at the ReMIX conference, as well as presenting Silverlight breakout talks. I'm also going to see if I might be able to speak at a local user group event in the evening. Click here for more details about the conference. Presentation in Mountain View, California on June 22nd I'll be doing a keynote presentation at an event on the Microsoft campus in Mountain View California the morning of June 22nd. I'll then be attending Tim O'Reilly's "Foo" Camp event that weekend in Sebastopol. Presentation in Phoenix, Arizona on June 27th Scott Cate is helping organize an event in Phoenix on Wednesday June 27th. More details coming soon. 17 talks, 6 cities, 4 countries and 17,000 people - all within 23 days start to finish. Hope to meet some of you at the events! :-) - Scott 
|
-
Back in February, JetBlue flight operations were shut down by a winter ice storm and a series of bad decisions. Some passengers stewed inside airplanes for 11 hours as the planes were stuck on the airport tarmac. Baseline tells the story of the JetBlue meltdown through the eyes of CIO Charles Mess.
There are more than a few interesting software stories inside the article. For instance, the checked baggage of enraged passengers was piled to the ceiling inside the JFK airport. JetBlue had no software in place to match passengers to their luggage. Time to call in the .NET developers:
A technology team … was dispatched to the airport to help out with the effort.
Over three days, programmers cobbled together an application using a Microsoft SQL database and handheld devices from Symbol Technologies that could scan a bag tag and identify the passenger. Agents could then access the database to provide passengers with information on the location of their lost luggage.
Isn't this a developer's fantasy? There you are, wallowing in code for the weekly TPS reports. Suddenly, you are whisked away into a riot scene and told to build something real quick for operation "Save the Samsonite". I wonder if "dispatched" means "flown by a sleek black helicopter with jet turbines on the side", because that would be like totally Tom Clancy.
Later in the article we find out that one of JetBlue's new initiatives is to:
Enhance the new lost-bag tracking system so it can become a core application.
Ah, this proves one of the fundamental laws of software development: It doesn't matter what constraints were in place when you cobbled the code together – it will end up in production for at least 5 years.

|
-
The latest and greatest of the best unit testing framework available for .NET is now available. -James 
|
-
The ReportViewer components in Visual Studio 2005 can display and export reports. The report definitions can be local .rdlc files, or remote files hosted and rendered by SQL Server Reporting Services. There are components available for both web and Windows applications.
A couple notes:
These components are not part of the .NET framework, so you need to install a redistributable package on the machines where the components will execute. The installation package will GAC the four assemblies required by the ReportViewer components.
More importantly:
Microsoft did update the ReportViewer components in SP1 for Visual Studio, but did not update the redistributable package. To synch test and prod machines with development, you'll need to download updates from the links in this article: FIX: The Report Viewer 2005 Service Pack 1 Redistributable Package is available.

|
-
One of the things I'm going to try and start doing is a weekly blog post of useful/interesting links on .NET related topics that I've found on the web. Below is this week's version: ASP.NET - Storing Binary Files Directly in the Database using ASP.NET 2.0: Scott Mitchell has a good article that shows how to upload and store images within a SQL database, and then serve them out dynamically from within a web application (very useful for photo albums). You could combine this article with Rick's above to enable an optional "Save As" option that allows site visitors to save high-resolution versions of images or other file types.
Visual Studio - Debugging SQL Server 2005 Stored Procedures in Visual Studio: Scott Mitchell published another great article on how to debug SPROCs using Visual Studio 2005. You can use this approach to set a breakpoint within a SPROC in your database, and then hit it like a normal debug breakpoint when debugging an ASP.NET application that calls it.
- Using Visual Studio Macros to Increase Productivity: Dan has a nice post describing some of the Macros he has created to manage large projects in Visual Studio. The Visual Studio macro recorder and editor are two features that not enough developers take advantage of (myself included). Whenever you find yourself repeating a task a number of times, I'd highly recommend creating a macro within VS to automate it for future uses.
Silverlight - Silverlight 1.1 Alpha Layout System and Controls Framework: One of the features missing in the Silverlight 1.1 Alpha that we shipped at MIX is support for layout management. This is a powerful feature of WPF, and makes it much easier to position and control UI on a page (I'll post more about this in the future). Dave Relyea from the Silverlight UI team posted a cool sample on his blog that provides a sample implementation of layout management that works with the 1.1 Alpha and includes both Stack and Grid layout manager support. He also then shipped a number of cool custom controls including buttons, labels, textbox, and border controls. Very cool stuff.
- Silverlight Toolbar Example: A nice sample from Vivek that describes how to create an animated toolbar where the buttons expand when you hover over them. You might also want to check out the "Office UI Ribbon" sample on the www.silverlight.net sample gallery web-site that demonstrates how to build a really cool toolbar within the browser.
WPF .NET General - NDepend 2.2: Scott Dorman has written up a great post on NDepend - which is a .NET utility that enables you to perform code analysis on your .NET projects. This can be useful especially with large projects that you've inherited. NDepend also supports a SQL-like query language that enables you to define your own code rules/analytics to search a code base with.
- Dynamic Language Runtime (DLR) ported to Mono: One of the announcements we made at MIX was that we are shipping a new "dynamic language runtime" framework library for .NET that makes it much easier to build dynamic languages on top of .NET (both the full .NET Framework and Silverlight). We are also shipping four dynamic language implementations of our own: IronPython, IronRuby, Javascript and Dynamic VB. We shipped the source code to the DLR and IronPython as a CodePlex project with a permissive license. This article on O'Reilly describes how someone has already taken the code and got it up and running on Mono. Miguel de Icaza was up in Redmond this week at a compiler dev lab we held and JasonZ and I got a chance to take him out to dinner last night. You can read about Miguel's trip on his blog here.
Hope this helps, Scott 
|
-
-
My Toolbox column in the June 2007 issue of MSDN Magazine is now avaiable online. The June issue examines three products:
- GhostDoc - a free Visual Studio Add-On that helps automate the repetitive task of adding XML comments.
- Authorize.NET - one of many payment gateways that you can use to start accepting online payments.
- ReSharper - enhance your Visual Studio develop-time experience with this productivity tool, which offers extended refactoring support, customizable code formatting, built-in unit testing, tools for quickly exploring the types, classes, and files in a project, and so forth.
This month's issue reviewed Hitchhiker's Guide to Visual Studio and SQL Server (Seventh Edition), by William R. Vaughn. Here is an excerpt from the review:
When I first started programming data-driven Visual Basic applications back in the late 1990s, a coworker encouraged me to pick up a copy of William R. Vaughn’s Hitchhiker’s Guide to Visual Basic and SQL Server, a tome whose heft and thickness earned it the nickname "the doorstop." Throughout the 90s, Vaughn published six editions of his popular Guide. After a nine-year hiatus he has released the seventh edition, written with Peter Blackburn, and renamed Hitchhiker’s Guide to Visual Studio and SQL Server (Addison-Wesley, 2007). Like the previous editions, the seventh provides detailed and thorough discussions on important topics, from installation of SQL Server™ 2005 to T-SQL basics to creating and working with data through a .NET application.
As always, if you have any suggestions for products or books to review for the Toolbox column, please send them into toolsmm@microsoft.com.
|
-
Over the last few months I wrote a series of blog posts that covered some of the new language features that are coming with the Visual Studio and .NET Framework "Orcas" release. Here are pointers to the posts in my series: The above language features help make querying data a first class programming concept. We call this overall querying programming model "LINQ" - which stands for .NET Language Integrated Query. Developers can use LINQ with any data source. They can express efficient query behavior in their programming language of choice, optionally transform/shape data query results into whatever format they want, and then easily manipulate the results. LINQ-enabled languages can provide full type-safety and compile-time checking of query expressions, and development tools can provide full intellisense, debugging, and rich refactoring support when writing LINQ code. LINQ supports a very rich extensibility model that facilitates the creation of very efficient domain-specific operators for data sources. The "Orcas" version of the .NET Framework ships with built-in libraries that enable LINQ support against Objects, XML, and Databases. What Is LINQ to SQL? LINQ to SQL is an O/RM (object relational mapping) implementation that ships in the .NET Framework "Orcas" release, and which allows you to model a relational database using .NET classes. You can then query the database using LINQ, as well as update/insert/delete data from it. LINQ to SQL fully supports transactions, views, and stored procedures. It also provides an easy way to integrate data validation and business logic rules into your data model. Modeling Databases Using LINQ to SQL: Visual Studio "Orcas" ships with a LINQ to SQL designer that provides an easy way to model and visualize a database as a LINQ to SQL object model. My next blog post will cover in more depth how to use this designer (you can also watch this video I made in January to see me build a LINQ to SQL model from scratch using it). Using the LINQ to SQL designer I can easily create a representation of the sample "Northwind" database like below: My LINQ to SQL design-surface above defines four entity classes: Product, Category, Order and OrderDetail. The properties of each class map to the columns of a corresponding table in the database. Each instance of a class entity represents a row within the database table. The arrows between the four entity classes above represent associations/relationships between the different entities. These are typically modeled using primary-key/foreign-key relationships in the database. The direction of the arrows on the design-surface indicate whether the association is a one-to-one or one-to-many relationship. Strongly-typed properties will be added to the entity classes based on this. For example, the Category class above has a one-to-many relationship with the Product class. This means it will have a "Categories" property which is a collection of Product objects within that category. The Product class then has a "Category" property that points to a Category class instance that represents the Category to which the Product belongs. The right-hand method pane within the LINQ to SQL design surface above contains a list of stored procedures that interact with our database model. In the sample above I added a single "GetProductsByCategory" SPROC. It takes a categoryID as an input argument, and returns a sequence of Product entities as a result. We'll look at how to call this SPROC in a code sample below. Understanding the DataContext Class When you press the "save" button within the LINQ to SQL designer surface, Visual Studio will persist out .NET classes that represent the entities and database relationships that we modeled. For each LINQ to SQL designer file added to our solution, a custom DataContext class will also be generated. This DataContext class is the main conduit by which we'll query entities from the database as well as apply changes. The DataContext class created will have properties that represent each Table we modeled within the database, as well as methods for each Stored Procedure we added. For example, below is the NorthwindDataContext class that is persisted based on the model we designed above:  LINQ to SQL Code Examples Once we've modeled our database using the LINQ to SQL designer, we can then easily write code to work against it. Below are a few code examples that show off common data tasks: 1) Query Products From the Database The code below uses LINQ query syntax to retrieve an IEnumerable sequence of Product objects. Note how the code is querying across the Product/Category relationship to only retrieve those products in the "Beverages" category: C#: VB: 2) Update a Product in the Database The code below demonstrates how to retrieve a single product from the database, update its price, and then save the changes back to the database: C#: VB: Note: VB in "Orcas" Beta1 doesn't support Lambdas yet. It will, though, in Beta2 - at which point the above query can be rewritten to be more concise. 3) Insert a New Category and Two New Products into the Database The code below demonstrates how to create a new category, and then create two new products and associate them with the category. All three are then saved into the database. Note below how I don't need to manually manage the primary key/foreign key relationships. Instead, just by adding the Product objects into the category's "Products" collection, and then by adding the Category object into the DataContext's "Categories" collection, LINQ to SQL will know to automatically persist the appropriate PK/FK relationships for me. C# VB: 4) Delete Products from the Database The code below demonstrates how to delete all Toy products from the database: C#: VB: 5) Call a Stored Procedure The code below demonstrates how to retrieve Product entities not using LINQ query syntax, but rather by calling the "GetProductsByCategory" stored procedure we added to our data model above. Note that once I retrieve the Product results, I can update/delete them and then call db.SubmitChanges() to persist the modifications back to the database. C#: VB: 6) Retrieve Products with Server Side Paging The code below demonstrates how to implement efficient server-side database paging as part of a LINQ query. By using the Skip() and Take() operators below, we'll only return 10 rows from the database - starting with row 200. C#: VB: Summary LINQ to SQL provides a nice, clean way to model the data layer of your application. Once you've defined your data model you can easily and efficiently perform queries, inserts, updates and deletes against it. Hopefully the above introduction and code samples have helped whet your appetite to learn more. Over the next few weeks I'll be continuing this series to explore LINQ to SQL in more detail. Hope this helps, Scott 
|
-
One of the nice features that Silverlight supports is the ability to go "full screen" and effectively take over the entire screen of a computer (hiding everything else from sight - including the browser frame). This can be very useful when building immersive UI experiences, games, rich video players, etc. For a nice example of this feature in action, make sure to check out the Fox Movies Sample on www.silverlight.net: Once the page loads and the movie starts playing, double-click on the video surface in the middle to switch into full-screen mode (note: the screen-shot above is not in full-screen but rather browser mode). You can then hit the escape key to switch back into normal browser viewing. How to Implement Full Screen Mode with Silverlight 1.1 using .NET One of the questions I've seen a few people ask is "how can you implement full screen-mode when building Silverlight applications using .NET?" The good news is that the answer is actually pretty easy: 1) First add an input driven event handler to your application (for example: a mouse down or keyboard event handler). For security reasons Silverlight doesn't allow developers to switch an application into full-screen mode on first application load (you don't want an application to spoof you). So you'll instead need to trigger full-screen mode in response to a user action. 2) Within your input event handler set the BrowserHost.IsFullScreen property to true (note: the BrowserHost class lives within the System.Windows.Interop namespace). This will cause Silverlight to switch into full screen mode. Setting this property to false will return it back to normal browser mode. Simple Full Screen Mode Sample You can download a simple Silverlight full screen-mode sample I put together written in C# here. When you run the sample it will load a super simple Silverlight application within the browser and display a text message prompting you to click it to switch into full-screen mode:  If you click the "Click for Full Screen" text, the application will switch into full-screen mode - which will hide everything else running on the system and take over the entire screen:  When you switch into full-screen mode, Silverlight will display a user message blurb that will pop-up on the screen for a few seconds and instruct the user that they can press the escape key to switch back into browser mode. After a few seconds this message will disappear and only your content will be visible. In my sample above I also allow the user to click on the "Click to Return to Browser" text and switch back into browser mode as well. Walkthrough the Simple Full Screen Mode Code The code to implement the above sample is pretty simple. To begin with we can open and edit the root .XAML file for the application, and add a UI element to it that we want to use to trigger the full-screen mode. In the sample above I used a <TextBlock> control that I named "MyMessage". Below is all of the XAML for the entire application:  The below screen-shot shows the code-behind for the .XAML file above - and contains all of the code for the entire application:  Within the application's Page_Loaded() event handler above I am wiring up two event handlers: MyMessage_MouseLeftButtonDown - This event handler will execute anytime a user clicks on the TextBlock message control I added into my XAML file. Within this event handler I'm simply toggling the BrowserHost.IsFullScreen property to true or false depending on whether or not it is already in full screen mode. BrowserHost_FullScreenChange - This event handler will execute anytime Silverlight switches between full screen and browser mode. It provides a good place to add logic to update the UI when this happens. In the example above I am changing the text on the TextBlock control. I could also have optionally resized controls and/or moved them around the screen to new coordinate positions. Currently the Silverlight 1.1 Alpha doesn't have layout manager support, so controls won't automatically re-position unless you write code to manage this yourself (don't worry - layout manager controls for Silverlight like in the desktop WPF version are coming). In addition to the IsFullScreen property, BrowserHost class has a number of additional properties and events that are very useful:  The ActualHeight and ActualWidth properties are particularly useful to lookup the screen dimensions when you switch into full-screen mode - which you can then use when positioning and scaling your UI controls on the page. Summary Supporting full-screen mode within Silverlight applications is pretty easy to enable, and offers the ability to provide a nice, immersive user experience. To learn more about Silverlight, please read my comprehensive Silverlight announcement post as well as visit the www.silverlight.net community site. To watch me walkthrough building a Silverlight application from scratch using .NET and Visual Studio "Orcas", please watch this video here. Hope this helps, Scott 
|
-
-
Over the last two months I've published a series of posts covering some of the new language features that are coming as part of the Visual Studio and .NET Framework "Orcas" release. Here are pointers to the first four posts in my series: Today's blog post covers the last new feature in my language series: Anonymous Types. What are Anonymous Types? Anonymous types are a convenient language feature of C# and VB that enable developers to concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type. Anonymous types are particularly useful when querying and transforming/projecting/shaping data with LINQ. Anonymous Type Example In my previous Query Syntax blog post I demonstrated how you could transform data with projections. This is a powerful feature of LINQ that enables you to perform query operations on a data source (regardless of whether it is a database, an XML file, or an in-memory collection), and shape the results of the data being queried into a different structure/format than the original data source is in. In my previous Query Syntax blog post I defined a custom "MyProduct" class that I used to represent my transformed product data. By explicitly defining the "MyProduct" class I have a formal CLR type contract that I can use to easily pass my custom-shaped product results between web-services or between multiple classes/assemblies within my application solution. However, there are times when I just want to query and work with data within my current code scope, and I don't want to have to formally define an explicit class that represents my data in order to work with it. This is where anonymous types are very useful, as they allow you to concisely define a new type to use inline within your code. For example, assume I use the LINQ to SQL object relational mapper designer within "Orcas" to model the "Northwind" database with classes like below:
I can then use the below code to query the Product data in my database, and use the projection/transformation capability of LINQ to custom shape the data result to be something other than the "Product" class above. Rather than use an explicitly defined "MyProduct" class to represent each custom-shaped row of data retrieved from the database, I can instead use the anonymous type feature to implicitly define a new type with 4 properties to represent my custom shaped data like so:
In the code above I'm declaring an anonymous type as part of the select clause within my LINQ expression, and am having the compiler automatically create the anonymous type with 4 properties (Id, Name, UnitPrice and TotalRevenue) - whose property names and type values are inferred from the shape of the query. I'm then using the new "var" keyword within C# to programmatically refer to the IEnumerable<T> sequence of this anonymous type that is returned from the LINQ expression, as well as to refer to each of the anonymous type instances within this sequence when I programmatically loop over them within a foreach statement later in my code. While this syntax gives me dynamic language-like flexibility, I also still retain the benefits of a strongly-typed language - including support for compile-time checking and code intellisense within Visual Studio. For example, notice above how I am doing a foreach over the returned products sequence and I am still able to get full code intellisense and compilation checking on the anonymous type with custom properties that was inferred from the LINQ query. Understanding the Var Keyword C# "Orcas" introduces a new var keyword that may be used in place of the type name when performing local variable declarations. A common misperception that people often have when first seeing the new var keyword is to think that it is a late-bound or un-typed variable reference (for example: a reference of type Object or a late-bound object like in Javascript). This is incorrect -- the var keyword always generates a strongly typed variable reference. Rather than require the developer to explicitly define the variable type, though, the var keyword instead tells the compiler to infer the type of the variable from the expression used to initialize the variable when it is first declared. The var keyword can be used to reference any type in C# (meaning it can be used with both anonymous types and explictly declared types). In fact, the easiest way to understand the var keyword is to look at a few examples of it using common explict types. For example, I could use the var keyword like below to declare three variables:
The compiler will infer the type of the "name", "age" and "male" variables based on the type of their initial assignment value (in this case a string, an integer, and a boolean). This means it will generate IL that is absolutely identical to the code below:
The CLR actually never knows that the var keyword is being used - from its perspective there is absolutely no difference between the above two code examples. The first version is simply syntactic sugar provided by the compiler that saves the developer some keystrokes, and has the compiler do the work of inferring and declaring the type name. In addition to using built-in datatypes with the var keyword, you can obviously also use any custom types you define. For example, I could go back to the LINQ query projection I did in my previous blog post that used an explicit "MyProduct" type for the data-shaping and adapt it to use the var keyword like so:
Important: Although I'm using the "var" keyword above, I'm not using it with an anonymous type. My LINQ query is still shaping the returned data using the "MyProduct" type - which means that the "var products" declaration is simply a shorthand for "IEnumerable<Product> products". Likewise, the "var p" variable I defined within my foreach statement is simply shorthand for a a variable of type "MyProduct p". Important Rule about the Var Keyword Because the var keyword produces a strongly-typed variable declaration, the compiler needs to be able to infer the type to declare based on its usage. This means that you need to always do an initial value assignment when declaring one. The compiler will produce a compiler error if you don't:
Declaring Anonymous Types Now that we've introduced the "var" keyword, we can start to use it to refer to anonymous types. Anonymous types in C# are defined using the same object initializer syntax I covered in my first blog post in this language series. The difference is that instead of declaring the type-name as part of the initialization grammar, when instantiating anonymous types you instead just leave the type-name blank after the "new" keyword:
The compiler will parse the above syntax and automatically define a new standard CLR type that has 4 properties. The types of each of the 4 properties are determined based on the type of the initialization values being assigned to them (for example: in the sample above the "Id" property is being assigned an integer - so the compiler will generate the property to be of type integer). The actual CLR name of the anonymous type will automatically be generated by the C# compiler. The CLR itself actually doesn't know the difference between an anonymous type and a named type - so the runtime semantics of the two are absolutely identical. Bart De Smet has a good blog post here that details this if you want to see the exact class name pattern and IL generated. Note above how when you type "product." on the anonymous type, you still get compile-time checking and full intellisense within Visual Studio. Notice also how the intellisense description indicates it is an "AnonymousType" - but still provides full declaration information of the properties (this is the text circled in red). Using Anonymous Types for Hierarchical Shaping One of the powerful scenarios that anonymous types makes easy is the ability to easily perform hierarchical shape projections of data with a minimum amount of code. For example, I could write the below LINQ expression to query all products from the Northwind database whose price is greater than $50, and then shape the returned products in a hierarchical structure sorted by the Products' stock reorder level (using the "group into" clause supported by LINQ query syntax):
When the above code is run in ASP.NET, I'll get the below output rendered in my browser:
I could likewise do nice hierarchical shapings based on JOIN results. For example, the below code creates a new anonymous type with some standard product column properties, as well as a hierarchical sub-collection property that contains the orderdetails of the 5 most recent orders that customers have placed for that particular product:
Notice how I can neatly traverse the hierarchical data. Above I'm looping over the product query, and then drilling into the collection of the last 5 orders for each product. As you can see, I have full intellisense and compile-time checking everywhere (even on properties of objects within the nested sub-collection of order details on the anonymous type). Data Binding Anonymous Types As I mentioned earlier in this blog post, there is absolutely no difference from a CLR perspective between an anonymous type and an explicitly defined/named type. Anonymous types and the var keyword are purely "syntactic sugar" that avoid you having to type code - the runtime semantics are the same as using explicitly defined types. Among other things, this means that all of the standard .NET type reflection features work with anonymous types - which means that features like databinding to UI controls work just fine with them. For example, if I wanted to display the results of my previous hierarchical LINQ query, I could define an <asp:gridview> control within a .aspx page like below: The .aspx above contains a gridview with 2 standard boundfield columns, and one templated field column that contains a nested <asp:bulletedlist> control that I'll use to display the product's hierarchical orderdetail sub-results. I could then write the below LINQ code to perform my hierarchical query against the database and databind the custom-shaped results against the GridView to display: Because the GridView supports binding against any IEnumerable<T> sequence, and uses reflection to retrieve property values, it will work just fine against the anonymous type I'm using above. At runtime the above code will produce a simple grid of product details with a hierarchical list of their recent order quantities like so: Obviously you could make this report much richer and prettier - but hopefully you get the idea of how easy it is to now perform hierarchical queries against a database, shape the returned results however you want, and then either work against the results programmatically or databind them to UI controls. Summary Anonymous types are a convenient language feature that enable developers to concisely define inline CLR types within code, without having to explicitly provide a formal class declaration of the type. Although they can be used in lots of scenarios, there are particularly useful when querying and transforming/shaping data with LINQ. This post concludes my 5-part language series for "Orcas". Going forward I'll be doing many more LINQ posts that will demonstrate how to actually take advantage of all of these new language features to perform common data access operations (defining data models, querying, updating, using sprocs, validation, etc). I wanted to get this 5 part language series done first, though, so that you'll have a good way to really understand the underlying language constructs as we drill into scenarios within my upcoming posts. Hope this has helped, Scott

|
-
Pat Helland is back at Microsoft and writes one helluva blog post about the last two years. -James 
|
-
PowerPoint 2007 doesn't have a macro recorder. When I discovered this fact, three possible explanations jumped to mind:
- PowerPoint developers ran into a technology obstacle or time constraint that prevented them from shipping the macro recorder in 2007.
- Statistics indicated nobody was using the PowerPoint macro recorder, and a member of the team decided to cut the feature.
A participant in a usability test was fiddling with the macro recorder when something amazing happened.
Something . . . unexpected.
PowerPoint achieved sentience, and began to create new software from information it found in bullet points. Amazing software. Business software. Commercial software. Viruses. Operating systems. Games. The more slide decks the process found, the more knowledge it leveraged to create new software. Eventually it created a replacement for itself and dubbed its replacement PowerPoint Compiler 2.0.
Knowing they couldn't unleash such a disruptive and powerful force into the world, MS employees powered down the computer, destroyed the hard drive, and removed all traces of the macro recorder from the PowerPoint code base.
I suspect #1 is the most likely culprit, but it is #3 that will haunt my dreams tonight.

|
-
I noticed my x60 tablet had “Intel Virtualization Technology” off by default in the bios. In talking to people and reading blogs, a lot of manufacturers configure their machines similarly.
Turning on VT Technology enables “Hardware Assisted Virtualization” in Virtual PC, which gives virtual machines a performance boost. See Scott Hanselman’s “Virtual PC Tips and Hardware Assisted Virtualization” for more details.
It’s a simple job to enable VT Technology in the BIOS, but I started wondering why every machine seems to have this feature turned off. “Off by default” is a security mantra, and it turns out hardware virtualization extensions do open a potential risk.
The slide deck "Hardware Virtualization Rootkits" (PDF) is an interesting read. It seems a rootkit could use VT Technology to run at a higher privilege level than the operating system itself! Microsoft recommends that manufactures turn the feature off by default for non-server class machines. See: “CPU Virtualization Extensions: Analysis of Rootkit Issues”.
Just more proof that you can’t ship any kind of feature these days without thinking of the security implications.

|
-
As I mentioned in my last post I will be moving to Raleigh this summer. I moved to Cincinnati about six years ago, mainly because my wife got a job she really loved with Proctor and Gamble. Proctor and Gamble outsourced their entire IT organization to HP and my wife decided she was ready to leave. About a year ago we were sitting around and thought about how we really don't have any strong ties to Cincinnati, and since we haven't starting having kids yet we are pretty much free to move and live wherever we want. So we started thinking about it and we ended up deciding on Raleigh. It's in the South, pretty close to the beach, filled with interesting tech companies (Epic Games, Microsoft, Red Hat, etc), and three big universities. We thought about more drastic choices like Seattle or California, but in the end we wanted to stay in the east close to my immediate and extended family. We made a trip out to Raleigh last year and liked what we saw, so we recently went back and picked out an apartment and will be moving this summer. Neither of us have jobs lined up, so it should be fun! -James 
|
|
|