Beth's Chinese blog
Yesterday Soma announced The MSDN Code Gallery where Microsoft employees and the community can post samples and resources they want to share. This is a great site to use to share code, docs, videos, or any other content without having to manage a source-controlled project that takes code contributions like those on CodePlex. You can use the MSDN Code Gallery for those "fire-and-forget" samples or you can get creative and publish a landing page, enable discussions and even track issues.
Check out the Visual Basic samples up there that have been published so far. I've started publishing the How Do I video code samples up there and have enabled discussions so it's easier to ask questions and hopefully the community will join in since my bandwidth is much smaller than all you folks. :-)
Enjoy!
Man! I haven't blogged all week and I'm going through withdrawal. I've been up in Redmond with the gang and back-to-back meetings all day and meet-and-greet dinners every night make it hard to have time to answer emails let alone blog. But now I'm up in Victoria, BC for Code Camp that's tomorrow. I'll be speaking on all things new and exciting in VB9. Check out the schedule and come on over if you're in the area. I'll also be in Denver next week speaking at a Microsoft event there.
Another couple things of interest this this week that I should share, the Visual Basic Forums bug pilot was launched. You can now report bugs directly into the VB forums on MSDN and these will be routed into our bug tracking systems. So get in there and report your Visual Basic bugs.
Also, Paul and I rocked the house playing guitar hero and rock band last weekend. "Visual Basic in the HOOOOUUUUSEEEE".
It's always a busy but extremely enjoyable time in Redmond.
If you haven't seen it yet, Bill Horst has a great series of posts on the VB Team blog on Converting SQL to LINQ. In this series he walks through, step by step, how to translate SQL queries that we've been writing for so long into Visual Basic LINQ queries. He starts with simple clauses and moves into more complex scenarios as the series progresses. If you're trying to wrap your head around LINQ but you have SQL down pat, this resource is for you. Check it out! (RSS feed is here)
Visual Basic MVP, Jim Wooley, just launched a site called ThinqLinq that's completly written in Visual Basic using LINQ and according to Jim, only took him 2 hours to write! To quote Jim: "The site is a testimate to the power of LINQ and the RAD capabilities that it brings." The site contains LINQ samples, downloads and other golden nuggets you should definitely check out.
Tim Heuer and Joe Shirey are putting together free developer and architect focused events in Phoenix and Denver and I'll be there speaking on all things new and good in Visual Basic 9.
I plan on showing practical examples of LINQ and Visual Basic's unique expression syntax and as we write the queries I'll show how the new language features tie into them to make them work. I'll also be showing the new VB specific XML features that make querying, transforming, and creating XML a total breeze. If you're using any language to manipulate and work with XML then you'll want to have a look at VB 9. Remember, there's also a good set of How-To's on the VB Developer Center under the Video Tutorials page to help you get started.
PHOENIX 29 JAN REGISTER HERE
DENVER 31 JAN REGISTER HERE
I hope you can make it. Enjoy!
In my previous post on TableAdapters and Transactions I showed a couple techniques on how to perform hierarchical updates inside a transaction when you have multiple related DataTables in your DataSet. The example I gave here shows how to use database transactions or the TransactionScope to update your data properly using Visual Studio 2005. It required a bit of code to manage the proper update order of rows, the connection and transaction on the TableAdapters, as well as managing a rollback situation where you wanted to preserve the original changes in the DataSet.
Luckily in Visual Studio 2008 the DataSet Generator has been enhanced to generate a new class that will automatically take care of all of these things in only a few lines of code! Enter the TableAdapterManager.
In this post I'm going to take the previous application and "upgrade" it using Visual Studio 2008. To be clear, I'm not going to update the target framework at all because I want the application to still run under the .NET Framework 2.0. (Visual Studio 2008 can be used to develop applications against .NET 2.0, 3.0 and 3.5 Frameworks under a feature called Multi-Targeting. For more information on how you can use Visual Studio 2008 to target multiple frameworks and upgrade projects, read here.)
When you open up the NorthwindTransaction.sln file in Visual Studio 2008 it will run an Upgrade Project Wizard that will convert the .sln file to be compatible with Visual Studio 2008. After that runs, double-click the OrdersDataSet in the Solution Explorer to open the DataSet Designer. In the properties window you will see "Hierarchical Update"; set that to True then click Save. This indicates to the DataSet Generator that it should generate the TableAdapterManager class. Note that when you create new DataSets the default is already True.
Now open up the OrderForm to open the Windows Form Designer. Delete the Dropdown on the ToolStrip at the top (TransactionToolStripDropDownButton) because we're just going to have one simple Save() method now. Right-click on the form and view the code. In the Click eventhandler for the OrdersBindingNavigatorSaveItem remove the Case statement and instead just call Me.Save():
Private Sub OrdersBindingNavigatorSaveItem_Click() Handles OrdersBindingNavigatorSaveItem.Click Me.Validate() 'Commit all data to the OrdersDataSet Me.OrdersBindingSource.EndEdit() Me.Order_DetailsBindingSource.EndEdit() If Not Me.OrdersDataSet.HasErrors Then If Me.OrdersDataSet.HasChanges Then If Me.Save() Then MessageBox.Show("Your changed have been saved.", Me.Text, _ MessageBoxButtons.OK, MessageBoxIcon.Information) Else MessageBox.Show("Your changes could not be saved!", Me.Text, _ MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If Else MessageBox.Show("Please make changes first.", Me.Text, _ MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If Else MessageBox.Show("Please correct the errors with this data first.", Me.Text, _ MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If End Sub
Now here comes the fun part. We're going to delete all the Savexxx() methods and write a single Save() method that uses the new TableAdapterManager. This code is doing the same thing as the SaveInDatabaseTransaction() method was previously.
''' <summary> ''' Performs an ordered save so that keys are properly updated in ''' the child table and so that deleted child rows are submitted ''' to the database first inside a database transaction automatically. ''' VS 2008 generates code that takes care of the saving in the proper ''' order in a database transaction. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Private Function Save() As Boolean Dim saved As Boolean = False If Me.OrdersDataSet.HasChanges Then Try Dim manager As New OrdersDataSetTableAdapters.TableAdapterManager 'Back up the dataset so that if the transaction fails, then the entire ' dataset is restored to it's original state. manager.BackupDataSetBeforeUpdate = True manager.Order_DetailsTableAdapter = Me.Order_DetailsTableAdapter manager.OrdersTableAdapter = Me.OrdersTableAdapter saved = (manager.UpdateAll(Me.OrdersDataSet) > 0) Catch ex As Exception MsgBox(ex.ToString) End Try End If Return saved End Function
Notice how much simpler the code is now than was previously. Before we were having to manage the update order, the connection and transaction management, and the rollback state behavior ourselves. This is all taken care of for us now. Now that we're not using them anymore, we can also remove the MergeAfterSave method on the form as well as the AssignConnection methods on the TableAdapter partial classes. Note that if we had created a new Form, an instance of the TableAdapterManager would have been created for us that was preset with the TableAdapter instances already.
Run the application and select a customers' orders and add, update and delete parent and child rows on the form. When we click the save button the rows will be updated and inserted in parent-child order and deleted in child-parent order all within a database transaction. If we open up SQL Server Profiler we can have a look:
You can also indicate to the TableAdapterManager that you want updates processed first by setting the UpdateOrder property. Take a look at the TableAdapterManager documentation for more information.
The TableAdapterManager saves us a lot of code but you'll still need to make sure you've set up your DataSet properly to handle foreign-key constraints like I show in this post as well as call the Fill methods on the TableAdapters in the proper order. Take a look at this documentation for more details on enabling foreign-key constraints in your DataSets so that they can be properly updated by the TableAdapterManager. I've attached the updated application for you to play with.
Update: Also check out this "How Do I" video on how to use the TableAdapterManager to update related DataTables.
Here's a summary of all the content the VB team members, including myself, have created for you on the Developer Center and our blogs these past couple of months to make it easier to find. Remember you can also grab rss feeds for Downloads, How-Do-I videos and Resources all from the home page.
Also, if you missed the Channel 9 VB Christmas carol with Amanda Silver, Chris Anderson and Don Box you should definitely check it out!
Video How-To’s:
- Video How to: Simple Object Model and Query (Visual Basic) (LINQ to SQL)- Video How to: Writing Queries in Visual Basic- Video How to: Declare an Object by Using an Object Initializer- Video How to: Enable XML IntelliSense in Visual Basic
Channel 9 Interviews:
- Type Inference in Visual Basic with Bill Horst- Refactoring in Visual Basic with Refactor!- XML Literals Performance and Namespaces Explained- Brian Beckman Does Higher Algebra with Visual Basic
MVP Articles (featured on Dev Center):
- Creating Visual Studio Add-Ins
MSDN Articles:
- Map LINQ: Create Dynamic Maps with Visual Basic 9.0 and WPF- Basic Instincts: Extension Methods in Visual Basic 2008
Blog Articles:
- Converting SQL to LINQ, Part 6: Joins (Bill Horst)- LINQ for the Web Using VB (By Paul Yuknewicz)- Mail Merging with Word, LINQ and XML Literals in VB- Northwind Meets Virtual Earth - Generate VE Maps with LINQ- Visual Studio Tip of the Day - Let's Build an Add-In- Visual Studio Tip of the Day Browser- Higher Algebra with Operator Overloads (Brian Beckman)- Converting SQL to LINQ, Part 5: GROUP BY and HAVING (Bill Horst)- Converting SQL to LINQ, Part 4: Functions (Bill Horst)- Euchre Revisited: Fixing bugs and services releases (Matt Gertz)- Silverlight Ux Musings: Providing Panning Functionality for a Canvas of Objects - Part 2 [Corrina Barber]- Converting SQL to LINQ, Part 3: DISTINCT, WHERE, ORDER BY and Operators (Bill Horst)- Silverlight Ux Musings: Providing Panning Functionality for a Canvas of Objects - Part 1 [Corrina Barber]- Converting SQL to LINQ, Part 2: FROM and SELECT (Bill Horst)- Launching External Tools from inside Visual Studio (Jonathan Aneja)- Drawing Maps with Visual Basic (Scott Wisniewski)- Hidden Gems in Visual Basic 2008 (Amanda Silver)- Converting SQL to LINQ, Part 1: The Basics (Bill Horst)- One is the Loneliest Number (Matt Gertz)- Use WPF and inline XAML in your Fox, Excel or VB6 applications- Use ElementHost to Add WPF to your Windows Forms or put your WinForm controls in your WPF app using WindowsFormsHost- How to Create dynamic XAML to display arbitrary XML- Use LINQ to Foxpro or any SQL data and display it in a WPF form using DataSetExtensions and DataRowExtensions - Create your own media browser: Display your pictures, music, movies in a XAML tooltip- WPF Animation: Use dynamic XAML to animate movies using XAMLReader or animate in code using BeginStoryBoard - Use DataTemplates and WPF in code to create a general purpose LINQ Query results display- Use LINQ with WPF : Styles and DataTemplates in code- Extract TreeView or ListView ImageList icons from a DLL
LINQ Cookbook:
- LINQ Cookbook, Recipe 12: Calculate the Standard Deviation (Doug Rothaus)- LINQ Cookbook, Recipe 11: Desktop Search Statistics (Doug Rothaus)- LINQ Cookbook, Recipe 10: Pre-compiling Queries for Performance (Doug Rothaus)
Downloads:
- Visual Basic Express 2008- .NET Framework 3.5- Visual Studio 2008 Shell- Visual Basic 2008 Code Snippet Editor (Thank you Bill McCarthy for another awesome version!)
And if you're starting to dig into WPF development with Visual Basic, the VB team released a dedicated page for all the WPF samples from Petzold’s book that are being translated by the community. Evan Lim and Ged Mead (MVP) are helping with the translation. Evan is also currently teaching WPF & Blend courses at Foothill Community College in Los Altos, CA.
VB WPF Samples:
- Chapter 1: The Application and the Window- Chapter 2: Basic Brushes- Chapter 3: The Concept of Content- Chapter 4: Buttons and Other Controls- Chapter 5: Stack and Wrap- Chapter 6: The Dock and the Grid- Chapter 7: Canvas- Chapter 8: Dependency Properties- Chapter 9: routed Input Events- Chapter 10: Custom Elements- Chapter 11: Single-Child Elements- Chapter 12: Custom Panels
I'll be speaking at the Victoria Code Camp on January 26th so if you're in the area and you have nothing else to do on your Saturday come on up to beautiful Victoria. This is going to be a GREAT code camp! I did the same sessions at DevTeach in Vancouver in November and we had a lot of fun (read about them here and here).
What can I say about VB 9 -- it's AWESOME! This language has really come a long way. There are so many language enhancements this version that I don't know where to start. I plan on talking about LINQ and as we write a variety of queries I'll show how the new language features tie into them to make them work. I'll also be showing the new XML features that are very specific to Visual Basic like XML Literals, Embedded Expressions and Axis Properties that make querying, transforming, and creating XML a total breeze. If you're using any language to manipulate and work with XML then you'll want to have a look at VB 9. There's a good set of How-To's on the VB Developer Center under the Video Tutorials page to help you get started.
I'll also be doing a session totally dedicated to XML in VB 9. I'll start with the basics there and then move deeper into the LINQ to XML API and show a bunch of examples using XML Literals and VB's unique, easy-to-use, LINQ syntax. Some of the examples I'll show I've blogged about like the Word Mail Merge example, an Excel import/export example, an RSS Viewer and we'll have some fun mapping customers in Northwind using Virtual Earth.
I'm looking forward to this event. Hope to see you there!
There's still a lot of Visual Basic 6 systems running the world and if you're one of the developers maintaining those systems you may be looking at migration strategies to move to .NET. You don't have to take on a complete rewrite of your system, there are many ways of interoperating with VB6 from .NET and vice versa.
Check out Rob Windsor on dnrTV where he shows us how to interoperate with VB 6.0 applications and .NET in a variety of ways. He walks through different approaches to architecting these hybrid systems. He also shows how to use the Interop Forms Toolkit to demonstrate a phased migration strategy where you can convert VB 6 forms and controls to .NET pieces at a time.
Also take a look at these How Do I videos and articles on building and deploying interop forms and user controls.