|
|
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.
Browse by Tags
All Tags » LINQ (RSS)
-
There has been a lot of excitement in the community about the new ASP.NET MVC framework that is about to ship (literally any day now – announcement coming soon). As with anything new, people are also asking for more tutorials/samples/documentation that cover how to get started and build applications with it. Over the last few months I’ve been helping to contribute to an ASP.NET MVC book that Scott Hanselman, Rob Conery, and Phil Haack have been writing for Wrox. The book is now in production, and will be available to buy in stores soon (you can pre-order it on Amazon today). I wrote the first chapter of the book – which is a 185 page end-to-end tutorial that walks-through building a small, but complete, ASP.NET MVC application from scratch. The agreement I made with Wrox was that I’d write it for free in return for them also making it available as a free PDF download. I’m excited to announce that you can now download this free end-to-end tutorial chapter (it is a 14mb PDF file). It’s licensed under a “Creative Commons Attribution No Derivatives” license – which means you can share, distribute, print, or hand it out to anyone. NerdDinner ASP.NET MVC Tutorial The tutorial starts by using the File->New Project command in Visual Studio to create a brand new ASP.NET MVC project, and then incrementally adds functionality and features. Along the way it covers how to: - Create a database
- Build a model with validation and business rules
- Implement data listing/details UI on a site using Controllers and Views
- Enable CRUD (Create, Update, Delete) data form entry
- Use the ViewModel pattern to pass information from a Controller to a View
- Re-use UI across a site using partials and master pages
- Implement efficient data paging
- Secure an application using authentication and authorization
- Use AJAX to deliver dynamic updates
- Use AJAX to add interactive map support
- Perform automated unit testing (including dependency injection and mocking)
The application the tutorial builds is called “NerdDinner”. It provides an easy way for people to organize, host and search for new topic-based dinners online: Scott Hanselman has been hosting NerdDinners for years, and came up with the idea of building the tutorial around an application that facilitates this. He is also now hosting a live custom-skinned version of the application at www.nerddinner.com) Download Links Hope this helps, Scott P.S. The book is entering production now and so is officially in un-edited status (meaning professional editors haven’t gone through it yet). We’ll update the PDF with any important edits once the text is final. P.P.S. And yes – this is one of the reasons my blog has been more quiet than normal the last few months. Expect more regular blog posting again soon once I recover from this. :-) 
|
-
Apologies for the sparseness of my posting the last few weeks - work and life have been busy here lately. Below is a new post in my link-listing series to help kick things up a little. Also check out my ASP.NET Tips, Tricks and Tutorials page and Silverlight Tutorials page for links to popular articles I've done myself in the past. ASP.NET ASP.NET AJAX .NET -
Ukadc.Diagnostics: Josh Twist pointed me at a new CodePlex project he is working on that extends the System.Diagnostics features in .NET to include richer logging features (SQL trace support, email support, etc). Visual Studio Silverlight WPF Hope this helps, Scott 
|
-
A few months ago we released an ASP.NET 3.5 Extensions Preview that contained a bunch of new features that will be shipping later this year (including ASP.NET AJAX Improvements, ASP.NET MVC, ASP.NET Silverlight Support, and ASP.NET Dynamic Data). The ASP.NET Dynamic Data support within that preview provided a first look at a cool new feature that enables you to quickly build data driven web-sites that work against a LINQ to SQL or LINQ to Entities object model. ASP.NET Dynamic Data allows you to automatically render fully functional data entry and reporting pages that are dynamically constructed from your ORM data model meta-data. In addition to supporting a dynamic rendering mode, it also allows you to optionally override and customize any of the view templates using any HTML or code you want (given you full control of the experience). ASP.NET Dynamic Data Preview Today we released an updated ASP.NET Dynamic Data Preview. You can learn more about it and download it here. This new dynamic data preview now works with the standard built-in ASP.NET data controls (GridView, ListView, FormView, DetailsView, etc). The dynamic data support enables these controls to automatically handle foreign-key relationships. For example, on a gridview you'll now get automatic friendly name display of foreign key column values and automatic drop-down list selection support of these values when in edit mode: The new dynamic data support also provides automatic UI validation support (both client-side and server-side) based on the constraints you set on your data model classes. For example, if a column in the database is limited to 50 characters in size, and is marked as non-nullable, appropriate UI control validators will automatically be applied by ASP.NET dynamic data to enforce this constraint in the UI pages as well. If you change the constraints within your LINQ to SQL or LINQ to Entities data model classes, the UI will automatically pick up these changes and enforce the new constraints on the next web request. In addition to standard data model metadata, you can also declare custom metadata to further control validation and the default display of UI of objects. You will be able to use all of the above features with both LINQ to SQL and LINQ to Entities. Visual Studio Dynamic Data Project Wizard In addition to the core ASP.NET dynamic data runtime support, the VS web tools team today also shipped a first preview of a new dynamic data project wizard that enables you to quickly get a data driven web-site started. The wizard allows you to select a database, and then the tables, views and sprocs within it that you want to build a LINQ to SQL data model around: After creating a data model, the wizard allows you to easily choose dynamic data driven template pages to build UI around it: You can then choose what type of inserting/editing/updating UI is supported on each page: And when you click finish it will setup a project with your data model classes and data UI pages setup to run. You can learn more about the wizard and watch it in action in a blog post and screencast here. How to Get Started You can learn more about this new dynamic data preview and download and run it locally here. You can watch David Ebbo's dynamic data presentation at MIX 08 to learn more about how it works. Also check out Scott Hunter's screen-cast here, and Brad Millington's screen cast here. You can ask questions and submit feedback via the www.asp.net forums here. Hope this helps, Scott 
|
-
I'm slowly recovering from keynoting at MIX last week, and have been digging my way out of backlogged email the last few days. I'm going to try and finish catching up on blog comments this weekend - apologies for the delay in getting back to some of your questions. To kick-start my blogging again I thought I'd post a new link-listing series. Today's post is mostly focused on ASP.NET and web related links. I'm going to be doing more Silverlight and WPF posts soon. ASP.NET ASP.NET AJAX ASP.NET MVC -
Thoughts on ASP.NET MVC Preview 2 and Beyond: Phil Haack from the ASP.NET team has a great post where he talks about the ASP.NET MVC Preview 2 release, as well as some of the features and work that will show up in the next preview drop. One of the major focuses in Preview 3 will be improvements to the testing workflow of controllers. -
ASP.NET MVC Test Project Integration with NUnit and Rhino Mocks: Joe Cartano from the VS Web Tools team walks-through using some NUnit and Rhino Mocks project templates that he has created. These plug-into the new VS 2008 tools support for ASP.NET MVC, and enable you to easily get a test project started when you create a new ASP.NET MVC application. .NET Hope this helps, Scott 
|
-
"LINQ in Action", published by Manning, is by far the best book available on Linq, both for those new to Linq and those already following it. The authors, Fabrice Marguerie, Steve Eichert, and Jim Wooley, have done a fabulous job of explaining Linq from the basics to the advanced. They even made it enjoyable to read, which makes it one of the best .Net books ever!
The authors' introductory chapter shows us right away that this book is different by presenting a perfect balance of the problem, the history, and the solution. Linq is a huge subject, but the authors are up to it, and they quickly whet the readers appetite for all of Linq -- Objects, Sql, and Xml. We then get a very thorough explanation of the new language enhancements that Linq relies on, but which the authors clearly show to have uses of their own. The chapter on Linq's building blocks, covering sequences, query operators, query expressions, and expression trees, was especially instructive to me, even though I've followed Linq from the alpha days, so again I'm sure this book has something for everyone. The book then covers Linq to Objects very thoroughly, including common scenarios and performance considerations that other books never consider.
The book then progresses to three chapters on Linq to Sql, which are of course my favorite since I'm really into O/R Mapping. The authors cover not just the basics to get beginners up to speed, but they also cover far more advanced content than I was expecting. For instance, they discuss not just the designer to setup mappings, but also the SqlMetal tool, and manual mappings using either attributes or xml. They also discuss the various concurrency options, the entity life cycle, inheritance, and more. The authors then give us three chapters on Linq to Xml, which again have something for everyone -- I especially like the chapter on common scenarios. The book finishes with a very thorough chapter on extending Linq, with a Linq to Amazon example, and a chapter that ties it all together with a real-world example that was gradually put together during the course of the entire book.
The authors also provide additional support and material online, including a bonus chapter on Linq to Datasets. There is also downloadable code in both C# and VB, although the book actually shows both languages in most cases, and always points out the differences when there are differences between them.
Disclaimer: I personally know Jim and have seen him present on Linq multiple times, Steve was a user of my WilsonORMapper, even contributing to it, and I've known Fabrice in the online world for quite some time too -- but I did very much enjoy and learn even more from their most excellent book on Linq.

|
-
Here is the latest in my link-listing series. Also check out my ASP.NET Tips, Tricks and Tutorials page for links to popular articles I've done myself in the past. ASP.NET ASP.NET AJAX -
Using JQuery with VS 2008 JavaScript Intellisense: One of the improvements we shipped in our recent VS 2008 Hotfix Roll-Up last week was to address issues with JavaScript intellisense support for JQuery (another popular AJAX framework). Brennan Stehling, James Hart, and Lance Fisher have done blog posts recently that discuss how to enable even richer JQuery intellisense inside VS 2008 using intellisense-friendly JQuery libraries that are referenced while coding (and then swapped out for the real library at runtime). You can read their blog posts about how this works here and here and here. Visual Studio -
Visual Studio Programmer Themes Gallery: Visual Studio enables you to customize the color settings of the text editor and IDE, as well as to export and import the settings (use the Tools->Import and Export Settings menu to do this). Scott Hanselman has a great post that provides previews of a bunch of cool pre-built themes that people have published that you can download and use for free. .NET -
Using the Expression Tree Visualizer: Charlie Calvert has a nice post that talks about one of the very useful debugging tools in the LINQ samples package provided with VS 2008. It enables you to easily visualize expression tree variables within the debugger - which can be incredibly useful when you are trying to write your own custom LINQ provider (like the ones above). To learn more about Expression Trees and some of the underlying concepts that make LINQ possible, also check out Charlie's earlier post on them here. Hope this helps, Scott 
|
-
I just arrived back from my trip from Asia, and decided to celebrate (since I'm jet-lagged and can't sleep) with a new post in my link-listing series. You can check out my ASP.NET Tips, Tricks and Tutorials page for links to popular articles I've done myself in the past. ASP.NET ASP.NET AJAX Visual Studio .NET -
Marshaling between Managed and Unmanaged Code: Yi Zhang and Xiaoying Guo from my team in Shanghai have written a great MSDN article that describes how to use the marshaling interop features of the CLR to call native code. One of the tools they highlight is an awesome P/Invoke Interop Assistant application they built that makes it much, much easier to generate p/invoke interop signatures when calling native methods. A must-have tool for anyone doing native/managed interop! IIS -
Microsoft Web Deployment Tool Technical Preview 1: Yesterday the IIS team posted the first preview of a new Microsoft Web Deployment tool. This tool works with both IIS6 and IIS7 and enables automated deployment, synchronization, and migrating of applications on web servers. If you are looking for a great way to automate the deployment of your ASP.NET applications then this tool is definitely one to check out. To learn more, read the walkthroughs at the bottom of this page (in particular the "Introduction to MS Deploy" one). This tool is awesome and should make automated deployment much easier. Hope this helps, Scott 
|
-
LINQ (language integrated query) is one of the new features provided with VS 2008 and .NET 3.5. LINQ makes the concept of querying data a first class programming concept in .NET, and enables you to efficiently express queries in your programming language of choice. One of the benefits of LINQ is that it enables you to write type-safe queries in VB and C#. This means you get compile-time checking of your LINQ queries, and full intellisense and refactoring support over your code: While writing type-safe queries is great for most scenarios, there are cases where you want the flexibility to dynamically construct queries on the fly. For example: you might want to provide business intelligence UI within your application that allows an end-user business analyst to use drop-downs to build and express their own custom queries/views on top of data. Traditionally these types of dynamic query scenarios are often handled by concatenating strings together to construct dynamic SQL queries. Recently a few people have sent me mail asking how to handle these types of scenarios using LINQ. The below post describes how you can use a Dynamic Query Library provided by the LINQ team to dynamically construct LINQ queries. Downloading the LINQ Dynamic Query Library Included on the VS 2008 Samples download page are pointers to VB and C# sample packages that include a cool dynamic query LINQ helper library. Direct pointers to the dynamic query library (and documentation about it) can be found below: Both the VB and C# DynamicQuery samples include a source implementation of a helper library that allows you to express LINQ queries using extension methods that take string arguments instead of type-safe language operators. You can copy/paste either the C# or VB implementations of the DynamicQuery library into your own projects and then use it where appropriate to more dynamically construct LINQ queries based on end-user input. Simple Dynamic Query Library Example You can use the DynamicQuery library against any LINQ data provider (including LINQ to SQL, LINQ to Objects, LINQ to XML, LINQ to Entities, LINQ to SharePoint, LINQ to TerraServer, etc). Instead of using language operators or type-safe lambda extension methods to construct your LINQ queries, the dynamic query library provides you with string based extension methods that you can pass any string expression into. For example, below is a standard type-safe LINQ to SQL VB query that retrieves data from a Northwind database and displays it in a ASP.NET GridView control: Using the LINQ DynamicQuery library I could re-write the above query expression instead like so: Notice how the conditional-where clause and sort-orderby clause now take string expressions instead of code expressions. Because they are late-bound strings I can dynamically construct them. For example: I could provide UI to an end-user business analyst using my application that enables them to construct queries on their own (including arbitrary conditional clauses). Dynamic Query Library Documentation Included with the above VB and C# Dynamic Query samples is some HTML documentation that describes how to use the Dynamic Query Library extension methods in more detail. It is definitely worth looking at if you want to use the helper library in more depth: Download and Run a Dynamic Query Library Sample You can download and run basic VB and C# samples I've put together that demonstrate using the Dynamic LINQ library in an ASP.NET web-site that queries the Northwind sample database using LINQ to SQL: You can use either Visual Web Developer 2008 Express (which is free) or VS 2008 to open and run them. Other Approaches to Constructing Dynamic LINQ Queries Using the dynamic query library is pretty simple and easy to use, and is particularly useful in scenarios where queries are completely dynamic and you want to provide end user UI to help build them. In a future blog post I'll delve further into building dynamic LINQ queries, and discuss other approaches you can use to structure your code using type-safe predicate methods (Joseph and Ben Albahari, authors of the excellent C# 3.0 In a Nutshell book, have a good post on this already here). Hope this helps, Scott 
|
-
The ASP.NET 3.5 Extensions CTP we shipped this past weekend contains a bunch of great new features. One of the cool new features is something we call "ASP.NET Dynamic Data Support". In a nutshell this enables you to really quickly build data driven web-sites that work against a LINQ to SQL (and in the future LINQ to Entities) object model - and optionally allows you to-do this without having to build any pages manually. The best way to see this in action is to watch David Ebbo's awesome 17 minute screen-cast: You can also follow the steps below to easily get started and use the dynamic data support: Step 1: Create a ASP.NET Dynamic Data Site: Once you have the ASP.NET 3.5 Extensions CTP release installed, you can use VS 2008 or the free Visual Web Developer 2008 Express to create a new Web Site or Web Application Project that has the ASP.NET dynamic data support enabled: This will create a new web-site you can use that has some default template files in them, along with CSS style-sheets you can use to customize the look and feel of them: Step 2: Add a LINQ to SQL Data Model to Your Site LINQ to SQL is an O/RM (object relational mapper) that ships in .NET 3.5, 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. The easiest way to get started with an ASP.NET Dynamic Data site is to add a new LINQ to SQL data model to your project (right-click->add new item->LINQ to SQL Classes item). This will bring up the LINQ to SQL class designer. Drag database tables from your server explorer to define a set of classes (with relationships) for your database schema: Step 3: Enable Dynamic Templates in Your Project: By default ASP.NET Dynamic Data projects provide built-in support for creating automatic "scaffolding" views of your LINQ to SQL and LINQ to Entities data models. Dynamic Data projects include template pages and user controls that can automatically create built-in data browsing/editing/selection/deleting UI that is dynamically constructed at runtime based on the LINQ to SQL or LINQ to Entities data model you've added to your project. To enable this auto-scaffolding support, open the web.config file of your project, search for the "dynamicData" section within it, and set the "enableTemplates" attribute to "true": Note: this auto-scaffolding feature is currently turned off by default for security reasons (we want you to be explicit about turning it on). Note: as you can see above, the ASP.NET dynamic data section provides optional URL mapping support that allows you to customize the URLs for your dynamic scaffold pages to be in whatever URL format you want. Step 4: Run Your Site Hit F5 to run your project. You'll by default be taken to a default.aspx page that lists all of the table objects in your data model: Note: the default.aspx home-page is in the project - if you don't like how it looks just open it up and edit it however you want. Clicking on any of the table names in the list above will take you to a dynamic data page that lists the data within it: The default data view pages automatically create functional data navigation UI that includes built-in data paging and editing support (and are ASP.NET AJAX enabled): The data view pages automatically infer relationships between your related objects and provide automatic filtering support: The data view pages also automatically show relationships between your objects and allow users to easily navigate amongst them. For example, notice how the Category column for products allows me to navigate to the category details for a specific product: The data view pages also enable automatic selection, editing and delete support. Notice below how when in inline edit mode they automatically infer friendly foreign key names (allowing you to edit the "Category" and pick a name from a dropdownlist instead of having to specify a "CategoryID" integer): All of this works without having to create a single custom .aspx page or write any custom code. All of the web UI is created dynamically off of your LINQ to SQL or LINQ to Entities data model. Step 5: Customizing the Site Further Having all of the above functionality work out of the box against your ORM data model is great for quickly getting your site up and running. Once you get the basic site experience working, you can optionally go in and fully customize it - both at the data validation/business logic level as well as at the UI layer. You can add standard LINQ to SQL data model and business validation rules to your data model in order to enforce constraints. The dynamic data pages will automatically work off of this logic, and provide appropriate error messages and validation UI based on them. You can also optionally go in and customize the UI of any of the data pages you want. Dynamic data projects allow you to customize the default look and feel of all data pages on the site, as well as customize the default look and feel of all column types used on the site. You can customize both of these via the default template files added under the "/App_Shared" folder when you create a new dynamic data project: Simply edit any of the files above to customize the default data page views and/or default data column appearances. You can also then optionally override the UI of specific data view pages by explicitly adding a .aspx page that maps to it in your project. For example, I could override the default ListDetails behavior for Products by adding a \Products\ListDetails.aspx page to my project: You can then add any standard ASP.NET data control to the page. You can also use the new dynamic data aware ASP.NET data controls that ship in the ASP.NET 3.5 Extensions CTP to the page. These allow you to completely customize the look and feel of the UI - while still using the new dynamic meta-data provider to infer relationships and meta-data about your data model classes for default behavior. Learning More The above walk-through only touches on a few of the scenarios and capabilities you can enable with ASP.NET Dynamic Data Projects. To learn more: - Watch David's webcast
- Check out the ASP.NET Dynamic Data QuickStarts
- Subscribe to David Ebbo's, Scott Hunter's, and Marcin Dobosz's blogs
- Visit the ASP.NET Dynamic Data Forum to ask questions
To learn more about LINQ to SQL and how you can use it to create data model classes, also check out my previous blog posts below: You can also watch the great LINQ and LINQ to SQL "How do I?" videos on the www.asp.net site here. Hope this helps, Scott 
|
-
Today we shipped Visual Studio 2008 and .NET 3.5. You can download the final release using one of the links below: -
If you are a non-MSDN subscriber, you can download a 90-day free trial edition of Visual Studio 2008 Team Suite here. A 90-day trial edition of Visual Studio 2008 Professional (which will be a slightly smaller download) will be available next week. A 90-day free trial edition of Team Foundation Server can also be downloaded here. -
If you want to use the free Visual Studio 2008 Express editions (which are much smaller and totally free), you can download them here. -
If you want to just install the .NET Framework 3.5 runtime, you can download it here. Quick Tour of Some of the New Features Visual Studio 2008 and .NET 3.5 contain a ton of new functionality and improvements. Below are links to blog posts I've done myself as well as links to videos you can watch to learn more about it: VS 2008 Multi-Targeting Support VS 2008 enables you to build applications that target multiple versions of the .NET Framework. This means you can use VS 2008 to open, edit and build existing .NET 2.0 and ASP.NET 2.0 applications (including ASP.NET 2.0 applications using ASP.NET AJAX 1.0), and continue to deploy these application on .NET 2.0 machines. You can learn more about how this works from my blog post here: ASP.NET AJAX and JavaScript Support .NET 3.5 has ASP.NET AJAX built-in (no separate download required). In addition to including all of the features in ASP.NET AJAX 1.0, ASP.NET 3.5 also now includes richer support for UpdatePanels integrating with WebParts, ASP.NET AJAX integration with controls like <asp:menu> and <asp:treeview>, WCF support for JSON, and many other AJAX improvements. VS 2008 and Visual Web Developer 2008 also now have great support for integrating JavaScript and AJAX into your applications. You can learn more about this from my blog posts here: You can watch some videos that discuss ASP.NET AJAX and Visual Studio 2008 support for it here. I also highly recommend the excellent ASP.NET AJAX in Action book to learn more about ASP.NET AJAX (both client-side and server-side). VS 2008 Web Designer and CSS Support VS 2008 and Visual Web Developer 2008 Express includes a significantly improved HTML web designer (the same one that ships with Expression Web). This delivers support for split-view editing, nested master pages, and great CSS integration. Below are some articles I've written that discuss this more: ASP.NET 3.5 also has a new <asp:ListView> control that provides the ability to perform rich data scenarios with total control over the markup. It works nicely with the new CSS support in VS 2008. You can learn more about it from my article here: You can watch some videos that discuss the new Visual Studio 2008 web designer features and the new ListView/DataPager controls here. Language Improvements and LINQ The new VB and C# compilers in VS 2008 deliver significant improvements to the languages. Both add functional programming concepts that enable you to write cleaner, terser, and more expressive code. These features also enable a new programming model we call LINQ (language integrated query) that makes querying and working with data a first-class programming concept with .NET. Below are some of the articles I've written that explore these new language features using C#: Here are a few additional blog posts I've written that show off some of the new VS 2008 code editing support and some cool ways to use these new language features: The Visual Basic team has also created some great free videos that cover LINQ. You can watch them here. Data Access Improvements with LINQ to SQL LINQ to SQL is a built-in OR/M (object relational mapper) in .NET 3.5. It enables you to model relational databases using a .NET object model. 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 business logic and validation rules into your data model. Below are some of the articles I've written that explore how to use it: I think you'll find that LINQ and LINQ to SQL makes it much easier to build much cleaner data models, and write much cleaner data code. I'll be adding more posts to my LINQ to SQL series in the weeks and months ahead (sorry for the delay in finishing them earlier - so much to-do and so little time to-do it all!). Scott Stanfield is also working on creating some great LINQ to SQL videos for the www.asp.net site based on my article series above (all videos are in both VB and C#). You can watch the first 4 videos in this series here. Browsing the .NET Framework Library Source using Visual Studio As I blogged a few weeks ago, we will be releasing a reference version of the .NET Framework library source code as part of this release. Visual Studio 2008 has built-in debugger support to automatically step-into and debug this code on demand (VS 2008 can pull down the source for the appropriate .NET Framework library file automatically for you). We are deploying the source servers to enable this right now, and will be publishing the steps to turn this feature on in the next few weeks. Lots of other improvements The list above is only a small set of the improvements coming. For client development VS 2008 includes WPF designer and project support. ClickOnce and WPF XBAPs now work with FireFox. WinForms and WPF projects can also now use the ASP.NET Application Services (Membership, Roles, Profile) for roaming user data. Office development is much richer - including support for integrating with the Office 2007 ribbon, and with Outlook. Visual Studio Tools for Office support is also now built-into Visual Studio (you no longer need to buy a separate product). New WCF and Workflow projects and designers are now included in VS 2008. Unit testing support is now much faster and included in VS Professional (and no longer just VSTS). Continuous Integration support is now built-in with TFS. AJAX web testing (unit and load) is now supported in the VS Test SKU. And there is much, much more... Installation Suggestions People often ask me for suggestions on how best to upgrade from previous betas of Visual Studio 2008. In general I'd recommend uninstalling the Beta2 bits explicitly. As part of this you should uninstall Visual Studio 2008 Beta2, .NET Framework Beta2, as well as the Visual Studio Web Authoring Component (these are all separate installs and need to be uninstalled separately). I then usually recommend rebooting the machine after uninstalling just to make sure everything is clean before you kick off the new install. You can then install the final release of VS 2008 and .NET 3.5 on the machine. Once installed, I usually recommend explicitly running the Tools->Import and Export Settings menu option, choosing the "Reset Settings" option, and then re-pick your preferred profile. This helps ensure that older settings from the Beta2 release are no longer around (and sometimes seems to help with performance). Note that VS 2008 runs side-by-side with VS 2005 - so it is totally fine to have both on the same machine (you will not have any problems with them on the same box). Silverlight Tools and VS Web Deployment Project Add-Ins Two popular add-ins to Visual Studio are not yet available to download for the final VS 2008 release. These are the Silverlight 1.1 Tools Alpha for Visual Studio and the Web Deployment Project add-in for Visual Studio. Our hope is to post updates to both of them to work with the final VS 2008 release in the next two weeks. If you are doing Silverlight 1.1 development using VS 2008 Beta2 you'll want to stick with with VS 2008 Beta2 until this updated Silverlight Tools Add-In is available. Hope this helps, Scott 
|
-
Earlier this year I blogged about a new language extensibility feature of C# and VB called "Extension Methods". Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. In doing so they enable a variety of useful scenarios (including LINQ). They also provide a really convenient way to add a dash of "syntactic sugar" into your code. Over the last few months I've been making a list of cool extension methods that I plan to sit down and implement when I get some free time (not sure when that is... but at least I can still have fun coming up with the ideas!) Two of the scenarios I added to my extension method list were easy methods to automate generating JSON (JavaScript Object Notation) or XML serialization strings for any .NET object. Simple Scenario: The ToJSON() extension method Assume I had a Person object defined like below (note: I'm using the new automatic properties feature to implement it): I'd like to then be able to initialize a collection of Person objects and programmatically retrieve a JSON string representation of them by just calling a ToJSON() extension method on it like below: This would work just like the built-in ToString() method on the Object class in .NET today - except that it would generate a JSON-format representation of the collection that I could use for AJAX scenarios on the client: Note: Clicking on the hour-glass in the debugger above allows us to bring up the Text Visualizer in VS to see a clean version of the JSON serialization: This string format could then be used within JavaScript on the client to instantiate an appropriate JavaScript object that represents my collection (note: ASP.NET AJAX has a built-in JavaScript library to support this). Implementing the ToJSON Extension Method Implementing a basic ToJSON() extension method is pretty simple. All I needed to-do was use the JavaScriptSerializer class in the System.Web.Script.Serialization namespace, and define two extension methods like below. One of the methods serializes an object graph any levels deep, the other is an overloaded version that allows you to optionally constrain how deep it recurses (for example: ToJSON(2) would serialize only 2 levels deep in the object graph). Note that the ToJSON() extension methods above are defined for type "Object" - which means they can be used with all objects in .NET (not just collections). This means that in addition to calling .ToJSON() on collections like I did above, I could also have called ToJSON() on individual Person objects, as well as any other .NET datatype. To use the extension method, all I need to-do is add a using statement at the top of my program that references the namespace it was defined within: VS 2008 then takes care of providing intellisense and compile time support for it to all objects: Note: In addition to the JavaScriptSerializer class, .NET 3.5 also now includes a new System.Runtime.Serialization.DataContractJsonSerializer class that you can use for JSON serialization/deserialization. Summary Hopefully the above sample provides a simple example of how you can easily encapsulate useful functionality into extension methods. Overtime I expect that we'll start to see some nice utility libraries come out that provide helpful extension methods like above. I'd be curious to see suggestions for other common scenarios you think should be packaged up into re-usable extension methods (feel free to use the comments of this post to suggest them). We can then figure out how to get a good CodePlex project created that bundles up some of them together into one library to easily use. Hope this helps, Scott P.S. Please check out my Tips/Tricks and Tutorials page to find other useful ASP.NET and .NET posts I've done. 
|
-
One of the subtle (but cool) new language features in the VS 2008 version of C# is the ?? "null coalescing" operator. This provides a nice, terse way to check whether a value is null, and if so return an alternate value. Simple Example Usages Several folks have blogged about the ?? operator in the past - read here, here, here, and here for some previous examples on how to use it. Simply put, the ?? operator checks whether the value provided on the left side of the expression is null, and if so it returns an alternate value indicated by the right side of the expression. If the value provided on the left side of the expression isn't null, then it returns the original value. For example, let's assume we have a string variable "message". We could check whether message was null, and return an alternate value using the code below: Because the "message" variable above wasn't null, the "result" variable is assigned the original "hello world" message value. In the code snippet below, however, message is a null value, and so the ?? operator will return the alternate value we've provided: The ?? operator works for both reference types and value types. For example, below we are checking whether the nullable integer "number" variable is null. Because it isn't, the result will be the original value (55): If "number" is null, then result is assigned the value 0: Using the ?? operator with LINQ Last month I wrote a blog post that covered using the new LINQ to XML support in .NET 3.5. One of the "gotchas" you often need to deal with when handling raw XML are cases where XML shapes are irregular and/or missing elements/attributes. The ?? operator can be very useful in these scenarios. For example, let's consider a scenario where we have an XML file or feed with the following contact data: We could write the below LINQ to XML code in C# to open the XML file and retrieve back a sequence of anonymous type objects with "Name", "Title", "Email" and "YearsAtCompany" properties, and then databind the results to an <asp:gridview> control on a page: Notice above how I'm using the explicit conversion operator support on the XElement class to retrieve strongly typed values from the XML. This enables me to just cast the c.Element("YearsAtCompany") value to an int - and it will then automatically convert the string value to an integer for me, and type the "YearsAtCompany" property on my anonymous type to be an int. When we run the above code snippet, we'll then get a nice Gridview listing of our contacts: This explicit conversion support works great when the <YearsAtCompany> element is always defined. But it will throw a runtime error in the case where we have a <Contact> that is missing a <YearsAtCompany> sub-element: One way to fix this is to modify our LINQ to XML query so that we indicate that YearsAtCompany is a nullable integer. We can do this by changing the explicit cast to be (int?) instead of (int): This enables our query to execute cleanly and not raise any errors. Instead a null value will be assigned to the YearsAtCompany property if no <YearsAtCompany> element is present in the XML. When we run the application and databind the results to the Gridview, you can see the YearsAtCompany column for our third contact is empty as a result (since the value is null): But what if we didn't want a missing XML value to result in a null integer value - but instead just indicate a value of 0? Well.... that is where we can use the new ?? operator support. We can just modify the LINQ to XML query like below to indicate a default value of 0 if no element is present: This indicates that if the <YearsAtCompany> element is missing in the XML, and the result would otherwise be null, instead assign a value of 0. Notice in the intellisense above how C# automatically detects that this means that the YearsAtCompany property on the new anonymous type will never be null - and so it marks the property to be of type (int) instead of (int?). And now when we run the page we'll see a value of 0 show up in our third row instead of a blank value: Summary You can use the new C# ?? operator in all types of scenarios. Hopefully the LINQ to XML scenario above provides some interesting food for thought on how you can use it with any LINQ scenario (including LINQ to SQL, LINQ to XML, LINQ to Objects, LINQ to SharePoint, etc). I think you'll find it cool and pretty useful. Hope this helps, Scott 
|
-
Over the last few weeks I've been writing a series of blog posts that cover LINQ to SQL. LINQ to SQL is a built-in O/RM (object relational mapper) that ships in the .NET Framework 3.5 release, and which enables you to model relational databases using .NET classes. You can use LINQ expressions to query the database with them, as well as update/insert/delete data. Below are the first eight parts in this series: In Part 5 of the series I introduced the new <asp:LinqDataSource> control in .NET 3.5 and talked about how you can use it to easily bind ASP.NET UI controls to LINQ to SQL data models. I also demonstrated how to use it a little more in a follow-up post I did that discusses the new <asp:ListView> control (Part 1 - Building a Product Listing Page with Clean CSS UI). In both of these articles the queries I performed were relatively straight-forward (the where clause worked against a single table of data). In today's blog post I'll demonstrate how to use the full query expressiveness of LINQ with the LinqDataSource control, and show how you can use any LINQ to SQL query expression with it. Quick Recap: <asp:LinqDataSource> with a Declarative Where Statement In these two posts I demonstrated how you can use the built-in filter capabilities of the LinqDataSource control to declaratively express a filter statement on a LINQ to SQL data model. For example, assuming we had created a LINQ to SQL data model for the Northwind database (which I covered how to-do in Part 2 of this series), we could declare a <asp:LinqDataSource> control on the page with a declarative <where> filter that returns back only those products in a specific category (specified via a querystring "categoryid" value): We could then point a <asp:gridview> control at the datasource and enable paging, editing, and sorting on it: When we run the above page we'll then have a GridView with automatic sorting, paging, and editing support against our Product data model: Using declarative <where> parameters like above works well for many common scenarios. But what happens if you want the Product filtering to be richer or more complex? For example, what if we only wanted to display products made by suppliers based in a dynamic set of countries? Using the <asp:LinqDataSource> Selecting Event To handle custom query scenarios you can implement an event handler to handle the "Selecting" event on the <asp:LinqDataSource> control. Within this event handler you can write whatever code you want to retrieve a data model result. You could do this with a LINQ to SQL query expression, or call a Stored Procedure or use a Custom SQL Expression to retrieve the LINQ to SQL data model. Once you retrieve a sequence of data, all you need to-do is to assign it to the "Result" property on the LinqDataSourceSelectEventArgs object. The <asp:LinqDataSource> will then use this sequence as its data to work with. For example, below is a LINQ to SQL query expression that retrieves only products from suppliers based in a specific set of countries: VB: C#: Note: you do not need to write your query expression in-line within the event handler. A cleaner approach would be to encapsulate it within a helper method that you just call from the event handler. I show how to create one of these helper methods in the beginning of my Part 8 blog post (using a GetProductsByCategory helper method). Now when we run our page using the custom Selecting event handler, we'll only see those products whose suppliers are located in our array of countries: One of the really cool things to notice above is that paging and sorting still work with our GridView - even though we are using a custom Selecting event to retrieve the data. This paging and sorting logic happens in the database - which means we are only pulling back the 10 products from the database that we need to display for the current page index in the GridView (making it super efficient). You might ask yourself - how is it possible that we get efficient paging and sorting support even when using a custom selecting event? The reason is because LINQ uses a deferred execution model - which means that the query doesn't actually execute until you try and iterate over the results. One of the benefits of this deferred execution model is that it enables you to nicely compose queries out of other queries, and effectively "add-on" behavior to them. You can learn more about this in my LINQ to SQL Part 3 blog post. In our "Selecting" event handler above we are declaring a custom LINQ query we want to execute and are then assigning it to the "e.Result" property. We haven't actually executed it yet though (since we didn't try and iterate through the results or call ToArray() or ToList() on it). The LINQDataSource is therefore able to automatically append on a Skip() and Take() operator to the query, as well as apply an "orderby" expression to it -- all of these values being automatically calculated from the page index and sort preference of the GridView. Only then does the LINQDataSource execute the LINQ expression and retrieve the data. LINQ to SQL then takes care of making sure that the sort and page logic is handled in the database - and that only the 10 product rows required are returned from it. Notice below how we can also still use the GridView to edit and delete data, even when using a custom LinqDataSource "Selecting" event: This editing/deleting support will work as long as our Selecting event assigns a Result query whose result sequence is of regular entity objects (for example: a sequence of type Product, Supplier, Category, Order, etc). The LINQDataSource can then automatically handle cases where UI controls perform updates against them. To learn more about how updates work with LINQ to SQL, please read Part 4 of this series. Then read Part 5 of the series to see Updates in action with the LinqDataSource. Performing Custom Query Projections with the Selecting Event One of the powerful features of LINQ is its ability to custom "shape" or "project" data. You can do this in a LINQ to SQL expression to indicate that you want to retrieve only a subset of values from an entity, and/or to dynamically compute new values on the fly using custom expressions that you define. You can learn more about how these LINQ query projection/shaping capabilities in Part 3 of this series. For example, we could modify our "Selecting" event handler to populate a GridView to display a custom set of Product information. In this Grid we'll want to display the ProductID, Product Name, Product UnitPrice, the Number of Orders made for this Product, and the total Revenue collected from orders placed for the Product. We can dynamically compute these last two values using a LINQ expression like below: VB: C#: Note: The Sum method used in the Revenue statement above is an example of an Extension Method. The function it takes is an example of a Lambda expression. The resulting type created by the LINQ query expression is an anonymous type - since its shape is inferred from the query expression. Extension Methods, Lambda Expressions, and Anonymous Types are all new language features of VB and C# in VS 2008. The result of our custom LINQ expression when bound to the GridView will be UI like below: Note that paging and sorting still work above with our GridView - even though we are using a custom LINQ shape/projection for the data. One feature that will not work with custom shapes/projections, though, is inline editing support. This is because we are doing a custom projection in our Selecting event, and so the LinqDataSource has no way to safely know how to update an underlying entity object. If we want to add editing support to the GridView with a custom shaped type, we'd want to either move to using an ObjectDataSource control (where we could supply a custom Update method method to handle the updates), or have the user navigate to a new page when performing updates - and display a DetailsView or FormView control that was bound to a Product entity for editing (and not try and do inline editing with the grid). Summary You can easily perform common query operations against a LINQ to SQL data model using the built-in declarative filtering support of the LinqDataSource. To enable more advanced or custom filtering expressions, you can take advantage of the LINQDataSource's Selecting event. This will enable you to perform any logic you want to retrieve and filter LINQ to SQL data. You can call methods to retrieve this data, use LINQ Query Expressions, call a Stored Procedures, or invoke a Custom SQL Expression to-do this. Hope this helps, Scott 
|
-
Over the last few weeks I've been writing a series of blog posts that cover LINQ to SQL. LINQ to SQL is a built-in O/RM (object relational mapper) that ships in the .NET Framework 3.5 release, and which enables you to model relational databases using .NET classes. You can use LINQ expressions to query the database with them, as well as update/insert/delete data. Below are the first seven parts in this series: In my last two posts (Part 6 and Part 7) I demonstrated how you can optionally use database stored procedures (SPROCs) to query, insert, update and delete data using a LINQ to SQL data model. One of the questions a few people have asked me since doing these posts has been "what if I want total control over the SQL expressions used by LINQ to SQL - but I don't want to use SPROCs to-do it?" Today's blog post will cover that - and discuss how you can use custom SQL expressions that you provide to populate your LINQ to SQL data model classes, as well as perform insert, updates, and deletes. Using LINQ Query Expressions with LINQ to SQL For the purposes of this blog post, let's assume we've used the LINQ to SQL ORM designer in VS 2008 to define a set of data model classes like below for the Northwind database (note: read Part 2 of this series to learn how to use the LINQ to SQL ORM designer to do this):
In Part 3 of this blog series I covered how you can use the new LINQ language support in VB and C# to query the above data model classes and return back a set of objects that represent the rows/columns in the database. For example, we could add a "GetProductsByCategory" helper method to the DataContext class of our data model that uses a LINQ query to return back Product objects from the database: VB:
C#:
Once we've defined our encapsulated LINQ helper method, we can then write code like below that uses it to retrieve the products, and iterate over the results: VB:
When the LINQ expression within our "GetProductsByCategory" method is evaluated, the LINQ to SQL ORM will automatically execute dynamic SQL to retrieve the Product data and populate the Product objects. You can use the LINQ to SQL Debug Visualizer to see in the debugger how this LINQ expression is ultimately evaluated. Using Custom SQL Queries with LINQ to SQL In our sample above we didn't have to write any SQL code to query the database and retrieve back strongly-typed Product objects. Instead, the LINQ to SQL ORM automatically translated the LINQ expression to SQL for us and evaluated it against the database. But what if we wanted total control over the SQL that is run against our database, and don't want LINQ to SQL to-do it for us in this scenario? One way to accomplish this would be to use a SPROC like I discussed in Part 6 and Part 7 of this series. The other approach is to use the "ExecuteQuery" helper method on the DataContext base class and use a custom SQL expression that we provide. Using the ExecuteQuery Method The ExecuteQuery method takes a SQL query expression as an argument, along with a set of parameter values that we can use to optionally substitute values into the query. Using it we can execute any raw SQL we want against the database (including custom JOINs across multiple tables). What makes the ExecuteQuery method really useful is that it allows you to specify how you want the return values of your SQL expression to be typed. You can do this either by passing a type-object as a parameter to the method, or by using a generic-based version of the method. For example, we could change the GetProductsByCategory() helper method we created earlier - using a LINQ expression - to instead use the ExecuteQuery method to execute our own raw SQL expression against the database and return "Product" objects as a result: VB:
C#:
We can then call the GetProductsByCategory() helper method using the exact same code as before:
But unlike before it will be our custom SQL expression that will run against the database - and not dynamic SQL executed in response to using a LINQ query expression. Custom SQL Expressions and Object Tracking for Updates By default when you retrieve a data model object using LINQ to SQL, it will track all changes and updates you make to it. If you call the "SubmitChanges()" method on the DataContext class, it will then transactionally persist all of the updates back to the database. I cover this in more depth in Part 4 of this LINQ to SQL series. One of the cool features of the ExecuteQuery() method is that it can fully participate in this object tracking and update model. For example, we could write the code below to retrieve all products from a specific category and discount their prices by 10%:
Because we typed the return value of our ExecuteQuery call in the GetProductsByCategory method to be of type "Product", LINQ to SQL knows to track the Product objects we returned from it. When we call "SubmitChanges()" on the context object they will be persisted back to the database. Custom SQL Expressions with Custom Classes The ExecuteQuery() method allows you to specify any class as the return type of a SQL query. The class does not have to be created using the LINQ to SQL ORM designer, or implement any custom interface - you can pass in any plain old class to it. For example, I could define a new ProductSummary class that has a subset of Product properties like below (notice the use of the new C# Automatic Properties feature):
We could then create a GetProductSummariesByCategory() helper method on our NorthwindDataContext that returns results based on it. Notice how our SQL statement below requests just the subset of product values we need - the ExecuteQuery method then handles automatically setting these on the ProductSummay objects it returns:
We can then invoke this helper method and iterate over its results using the code below:
Custom SQL Expressions for Inserts/Updates/Deletes In addition to using custom SQL expressions for queries, we can also execute them to perform custom Insert/Update/Delete logic. We can accomplish this by creating the appropriate partial Insert/Update/Delete method for the entity we want to change in a partial class on our DataContext. We can then use the ExecuteCommand method on the DataContext base class to write the SQL we want to execute. For example, to override the Delete behavior for Product classes we could define this DeleteProduct partial method:
And now if we write the below code to remove a specific Product instance from our database, LINQ to SQL will call the DeleteProduct method - which will cause our custom SQL to execute in place of the default dynamic SQL that LINQ to SQL would otherwise use:
Summary The LINQ to SQL ORM automatically generates and executes dynamic SQL to perform queries, updates, inserts and deletes against a database. For advanced scenarios, or cases where you want total control over the SQL query/command executed, you also have the ability to customize the ORM to use either SPROCs, or your own custom SQL Expressions, instead. This provides you with a great deal of flexibility when building and extending your data access layer. In future blog posts in this series I'll cover some remaining LINQ to SQL concepts including: Single Table Inheritance, Deferred/Eager Loading, Optimistic Concurrency, and handling Multi-Tier scenarios. Hope this helps, Scott 
|
-
Over the last few weeks I've been writing a series of blog posts that cover LINQ to SQL. LINQ to SQL is a built-in O/RM (object relational mapper) that ships in the .NET Framework 3.5 release, and which enables you to model relational databases using .NET classes. You can use LINQ expressions to query the database with them, as well as update/insert/delete data. Below are the first six parts in this series: In part 6 I demonstrated how you can optionally use database stored procedures (SPROCs) and user defined functions (UDFs) to query and retrieve data using your LINQ to SQL data model. In today's blog post I'm going to discuss how you can also optionally use SPROCs to update/insert/delete data from the database. To help illustrate this - let's start from scratch and build-up a data access layer for the Northwind sample database: Step 1: Creating our Data Access Layer (without using SPROCs yet) In my Part 2: Defining our Data Model Classes tutorial I discussed how to use the LINQ to SQL ORM designer that is built-in to VS 2008 to create a LINQ to SQL class model like below:
Adding Validation Rules to our Data Model Classes After defining our data model classes and relationships we'll want to add some business logic validation to our data model. We can do this by adding partial classes to our project that add validation rules to our data model classes (I cover how to-do this in-depth in my Part 4: Updating our Database LINQ to SQL tutorial). For example, we could add validation rules to enforce that the Customer's phone number follows a valid phone pattern, and that we don't add Orders where the customer's RequiredDate for delivery is before the actual OrderDate of the Order. Once defined in partial classes like below, these validation methods will automatically be enforced anytime we write code to update our data model objects in an application. VB:
C#:
Adding a GetCustomer() Helper Method to our DataContext Now that we have our data model classes created, and have applied validation rules to them, we can query and interact with the data. We can do this by writing LINQ expressions against our data model classes to query the database and populate them (I cover how to-do this in my Part 3: Querying our Database LINQ to SQL tutorial). Alternatively we could map SPROCs to our DataContext and use them to populate the data model classes (I cover how to-do this in my Part 6: Retrieving Data using Stored Procedures LINQ to SQL tutorial). When building a LINQ to SQL data layer you'll usually want to encapsulate common LINQ queries (or SPROC invocations) into helper methods that you add to your DataContext class. We can do this by adding a partial class to our project. For example, we could add a helper method called "GetCustomer()" that enables us to lookup and retrieve a Customer object from the database based on their CustomerID value: VB:
C#:
Step 2: Using our Data Access Layer (still without SPROCs) We now have a data access layer that encapsulates our data model, integrates business validation rules, and enables us to query, update, insert, and delete the data. Let's look at a simple scenario using it where we retrieve an existing customer object, update the customer's ContactName and Phone Number, and then create a new Order object and associate it with them. We can write the below code to do all of this within a single transaction. LINQ to SQL will ensure that our business logic validation rules are clean before saving anything in the database: VB:
C#:
LINQ to SQL monitors the modifications we make to the objects we retrieve from the DataContext, and keeps track of all of the objects we add into it. When we call DataContext.SubmitChanges() at the end, LINQ to SQL will check that our business logic rules are valid, and if so automatically generate the appropriate dynamic SQL to update our Customer record above, and insert a new record into the Orders table. Hang on a second - I thought this post was about using SPROCs??? If you are still reading this, you might be feeling confused about where SPROCs fit into this post. Why did I show you above how to write code that works with our data model objects, and then causes dynamic SQL to run? Why haven't I showed you how to call a SPROC for doing inserts/updates/deletes instead yet? The reason is that the programming model in LINQ to SQL for working with data model objects backed by SPROCs is the same as those updated via dynamic SQL. The way you add data model validation logic is exactly the same (so all the validation rules on our data model classes above still apply when we use SPROCs). The code snippet above where we use our data access layer to retrieve a customer, update it, and then add a new order associated with it is also exactly the same regardless of whether we are using dynamic SQL for updates, or whether we have configured our data model classes to use SPROCs instead. This programming model symmetry is powerful both in that you don't have to learn two ways of doing things, and also because it means that you don't have to decide up front at the beginning of your project whether you are going to use SPROCs or not. You can start off using the dynamic SQL support provided by the LINQ to SQL ORM for all queries, inserts, updates and deletes. You can then add your business and validation rules to your model. And then later you can optionally update your data mapping model to use SPROCs - or not if you decide you don't want to. The code and tests you write against your data model classes can stay the same regardless of whether you use dynamic SQL or SPROCs. We'll now spend the rest of this blog post demonstrating how we can update the data model we've built to use SPROCs for updates/inserts/deletes - while still using the same validation rules, and working with the same code snippets above. How to Use SPROCs for Insert/Update/Delete Scenarios We can modify the data access layer we've been building to use SPROCs to handle updates, instead of dynamic SQL, in one of two ways: 1) By using the LINQ to SQL designer to graphically configure SPROCs to execute in response to Insert/Update/Delete operations on our data model classes. or: 2) By adding a NorthwindDataContext partial class in our project, and then by implementing the appropriate Insert/Update/Delete partial methods provided on it (for example: InsertOrder, UpdateOrder, DeleteOrder) that will be called when we insert/update/delete data model objects. These partial methods will be passed the data model instances we want to update, and we can then execute whatever SPROC or SQL code we want to save it within the database. When we use approach #1 (the LINQ to SQL designer) to graphically configure SPROCs to call, it is under the covers generating the same code (in a partial class it creates) that you'd write when using approach #2. In general I'd recommend using the LINQ to SQL designer to configure the SPROCs for the 90% case - and then in more advanced scenarios go in and custom tweak the SPROC invocation code it generates if you need to. Step 3: Doing Order Inserts with a SPROC We'll begin switching our data model to use SPROCs by starting with the Order object. We'll first go to the Visual Studio "Server Explorer" window, expand into the "Stored Procedures" node of our database, and then right-click and choose "Add New Stored Procedure": We'll then create a new SPROC that we'll call "InsertOrder" that inserts a new order record into our Orders table: Notice above how the SPROC defines the "OrderID" parameter as an output param. This is because the OrderID column in the database is an identity column that is set to auto-increment each time a new record is added. The caller of the SPROC will pass in NULL as a value when calling it - and the SPROC then passes back the newly created OrderID value as the output value (by calling the SCOPE_IDENTITY() function at the end of the SPROC). After creating the SPROC we'll then open up the LINQ to SQL ORM designer for our data access layer. Like I discussed in my last blog post in this series (Part 6: Retrieving Data Using Stored Procedures), we can drag/drop SPROCs from the server-explorer onto the method pane of our DataContext designer. We'll want to-do this with our newly created InsertOrder SPROC: Our last step will be to tell our data access layer to use the InsertOrder SPROC when inserting new Order objects into the database. We can do that by selecting the "Order" class in the LINQ to SQL ORM designer, and then by going to the property grid and clicking the "..." button to override how Insert operations happen for it: Clicking the "..." button will bring up a dialog that allows us to customize how insert operations happen: Notice above how the default mode ("Use Runtime") is to have LINQ to SQL calculate and execute dynamic SQL to handle the insert operations. We can change that by selecting the "Customize" radio button and then pick our InsertOrder SPROC from the list of available SPROCs: The LINQ to SQL designer will populate a parameter list for the SPROC we picked, and enable us to map properties on our Order class to parameters of our InsertOrder SPROC. By default it is smart and tries to "best match" them based on name. You can go in and override them if you want. Once we click "ok" on the dialog, we are done. Now whenever a new Order is added to our DataContext and the SubmitChanges() method is invoked, our InsertOrder SPROC will be used instead of executing dynamic SQL. Important: Even though we are now using a SPROC for persistence, the custom Order "OnValidate()" partial method we created earlier (in step 1 of this blog post) to encapsulate Order validation rules still executes before any changes are saved or the SPROC is invoked. This means we have a clean way to encapsulate business and validation rules in our data models, and can re-use them regardless of whether dynamic SQL or SPROCs are used. Step 4: Doing Customer Updates with a SPROC Now let's modify our Customer object to handle updates using a SPROC. We'll start by creating a new "UpdateCustomer" SPROC like below: Notice above how in addition to passing in the @CustomerID parameter, we are also passing in a @Original_CustomerID parameter. The CustomerID column in the Customers table is not an auto-increment identity column, and it can be modified as part of an update of the Customer object. Consequently we need to be able to provide the SPROC with both the original CustomerID and the new CustomerID in order to update the record. We'll look at how we map this using the LINQ to SQL designer shortly. You'll notice above how I'm also passing in a @Version parameter (which is a timestamp) to the SPROC. This is a new column I've added to the Northwind Customers table to help handle optimistic concurrency. I will cover optimistic concurrency in much more depth in a later blog post in this LINQ to SQL series - but the short summary is that LINQ to SQL fully supports optimistic concurrency, and enables you to use either a version timestamp or to supply both original/new values to your SPROCs to detect if changes have been made by another user since you last refreshed your data objects. For this sample I'm using a timestamp since it makes the code much cleaner. Once we've created our SPROC, we can drag/drop it onto the LINQ to SQL designer to add it as a method on our DataContext. We can then select the Customer class in the ORM designer and click the "..." button to override the Customer object's Update behavior in the property grid: We'll select the "Customize" radio button and pick our UpdateCustomer SPROC to use: When mapping our Customer object's properties to the SPROC parameters, you'll notice that we'll want to be deliberate about whether we supply the "current" property value on the data object, or the original value that was in the database when the object was first retrieved. For example, we'll want to make sure we map the "current" value of the Customer.CustomerID property for the @CustomerID SPROC parameter, and that we map the original value for the @original_customerID SPROC parameter. Once we click "ok" on the dialog, we are done. Now whenever a new Customer is updated and the SubmitChanges() method is invoked, our UpdateCustomer SPROC will be used instead of executing dynamic SQL. Important: Even though we are now using a SPROC for persistence, the Customer "OnPhoneChanging()" partial method we created earlier (in step 1 of this blog post) to encapsulate Phone Number validation rules still executes before any changes are saved or the SPROC is invoked. We have a clean way to encapsulate business and validation rules in our data models, and can re-use them regardless of whether dynamic SQL or SPROCs are used. Step 5: Using our Data Access Layer Again (this time with SPROCs) Once we've updated our data layer to use SPROCs instead of dynamic SQL for persistence, we can re-run the exact same code we wrote in Step 2 earlier against our data model classes: Now the updates for the Customer object, and the insert for the Order object, are executing via SPROCs instead of dynamic SQL. The validation logic we defined still executes just like before, though, and the data access code we write to use the data model classes is exactly the same. Some Advanced Notes When Using SPROCs A few quick notes that you might find useful for more advanced SPROC scenarios with LINQ to SQL: Usage of SPROC Output Params: In the Insert scenario (Step 3) above I showed how we could return back the new OrderID value (which is an auto-increment identity column in the Orders table) using an output parameter of the SPROC. You aren't limited to only returning back identity column values when using SPROCs with LINQ to SQL - in fact you can update and return back output values for any parameter of your SPROC. You can use this approach both for Insert and Update scenarios. LINQ to SQL will then take the return value and use it to update the property value of your data model object without you having to-do any second queries against the database to refresh/populate them. What Happens if the SPROC Throws an Error? If a SPROC raises an error when doing an Insert/Update/Delete operation, LINQ to SQL will automatically cancel and rollback the transaction of all changes associated with the current SubmitChanges() call on the DataContext. This ensures that your data is always kept in a clean, consistent state. Can you write code instead of using the ORM designer to call SPROCs? As I mentioned earlier in this post, you can use either the LINQ to SQL ORM designer to map your insert/update/delete operations to SPROCs, or you can add partial methods on your DataContext class and programmatically invoke them yourself. Here is an example of the explicit code you could write in a partial class for the NorthwindDataContext to override the UpdateCustomer behavior to call a SPROC: The code above was actually what was generated by the LINQ to SQL ORM designer when we used the designer to map the SPROC and then associate the update behavior of the Customer object with it. You can use it as a starting point and then add any additional logic you want to it to make it more advanced (for example: use the return value of the SPROC to raise custom exceptions for error conditions, optimistic concurrency, etc). Summary LINQ to SQL is a very flexible ORM. It enables you to write clean object-oriented code to retrieve, update and insert data. Best of all - it enables you to cleanly design data model classes independent of how they are persisted and loaded from a database. You can use the built-in ORM engine to efficiently retrieve and update data in the database using dynamic SQL. Or alternatively you can configure your data layer to use SPROCs. The nice thing is that your code consuming the data layer, and all of the business logic validation rules you annotate it with, can be the same regardless of which persistence approach you use. In future blog posts in this series I'll cover some remaining LINQ to SQL concepts including: Single Table Inheritance, Deferred/Eager Loading, Optimistic Concurrency, and handling Multi-Tier scenarios. I'm on vacation next week, and so will hopefully have some free time to get a few of them written then. Hope this helps, Scott 
|
|
|
|