|
|
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 » .NET (RSS)
-
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 th | |
|