Search results for MSDN VB Dev Center - ThinqLinq by ThinqLinq


Custom Logging with Entity Framework EF6

Coming from LINQ to SQL, I’ve long been a fan of its logging simplicity where you just set the context.log to a stream (console.out) to see the stream of sql statements being issued to the database. Prior to EF6, this has been a rather frustrating omission that has finally been rectified with EF 6. Now, you can log SQL statements just as simply, but with a slightly different implementation. In EF, you set the DbContext’s Database.Log property to an Action delegate that takes a string as input pa

Beware of Async Sub or Void

At my VS Live last week, I gave a survey of Asynchronous programming from .Net 1 through .Net 4.5. As part of the presentation, I showed off this simple example of doing Async starting with a synchronous example. Here’s the beginning example: Sub Main() DoWorkAsync() Debug.WriteLine("All Done") Console.ReadLine() End Sub Sub DoWorkAsync() PrintIt() Debug.WriteLine("Done Async") End Sub Public Sub PrintIt() Dim text =

JSON Literals for VB

One of the stand-out features of VB.Net since VB9 has been the inclusion of XML Literals. Followers of this blog should be well familiar with the concept because I first wrote about XML Literals way back in 2006. With them, we can imbed XML directly into our code as follows:Dim value = <root> <child attrib="foo">bar</child> <root> While XML Literals make the task of working with XML more of a joy than a necessary evil, they do add a cer

Hierarchical Trees from Flat Tables using LINQ

I’m often tasked with creating a tree representation of a structure from a flat self-referencing table. For example, in the EF extensions to Northwind, they extended the Employee table so that it has a self-referencing “ReportsTo” column. As you can see from the data below, Andrew Fuller does not report to any other employees, but Nancy, Janet, Margaret, Steven, and Laura all report to Andrew (because their ReportsTo value is the same as Andrew’s EmployeeID). Likewise Michael, Robert, and Anne a

Aggregate clause issues

I was reviewing a Stack Exchange message regarding the Aggregate clause in VB () where they found that the query was issuing multiple requests to the database and occasionally returning the entire database table to memory and using LINQ to Objects over the result. I also found that Frans Bouma blogged about this back in 2008 at  . Consider the following LINQ query over Northwind: Dim query = Aggregate o in Orders             &#1

Unit testing and SMTP

Over the past several years, I’ve become a fan of unit testing. I’m not a test-first/TDD zealot by any means, but have found the definite benefits of testing your custom business logic to assert that it does what you say it will. When going to a client who hasn’t done unit testing at all, I often find it hard enough to get them to start testing and don’t want to over burden their tests with mocking frameworks to abstract out some of the external dependencies. As a result, I have no qualms about

Async Await StateMachine in ILSpy

In my Async Programming in .Net talk I like to show what’s really happening under the covers with the new async/await keywords in VS 2012. To show this, I’m currently using ILSpy instead of Reflector because it is free. I noticed an “issue” tonight when trying to locate the MoveNext method of the state machine generated class, but couldn’t find it. To begin, let’s look at the code sample.Module AsyncWorld Sub DoWorkAsync() PrintIt() Console.ReadLine() End Sub P

SignalR and Reactive Extensions are an Rx for server push notifications

Recently, I had the need to build a system where multiple clients needed to be notified as changes happened on the server. While watching Damian Edwards, Brad Wilson and Levi Broderick present on Async in ASP.Net during the AspConf I was introduced to the dynamic simplicity that SignalR brings to the table. I was even more intrigued by the fact that it integrates directly with IObservable and the Reactive Extensions. After using it for a week, I’m truly impressed by what they’ve done with this l

Windows 8 Live Tiles and LINQ to XML

When I started working with Windows 8 Metro development, I was disappointed to see that the native WinRT API’s relied on the older XmlDocument and XMLDom rather than the newer subset of XDocument/XElement and LINQ to XML. I suppose this was necessary because the older version was more natural for C++ and JavaScript options for Metro applications. If you’re like me and want to use LINQ to XML to work with XML in WinRT, all you need to do is pass the XML strings back and forth between your C#/VB c

LINQ to Database Performance hints

Although I’ve been writing primarily about RX here for a while, I still dig into some good old LINQ to SQL / EF quite a bit. Along the way, I’m frequently finding more tidbits to throw in the toolbox and thought I’d share some observations from a recent performance tuning project. (I’ll avoid disclosing the client and will change the database model to Northwind for this discussion protect the guilty.) In this project, I was brought in at the end of the project as things started going south to

Using Rx to consume a Task based WCF service

Among the many changes that Dev 11 brings is the new default when adding a service reference to generate Task based proxy methods rather than using the APM flavor (using the BeginXXX – EndXXX model). In this post, we’ll look at creating a simple service and then consuming it using the Reactive Extensions. Let’s start by defining the service interface and implementation: Imports System.ServiceModel Imports System.Threading <ServiceContract()> Public Interface ISimpleServicesvc

WinRT Contacts

In preparation for recording a session of Deep Fried Bytes on the WinRT Namespaces, I scanned through the public ones in the Developer Preview to see what I could find. One of the interesting ones that I hadn’t heard about yet is the Contact class in the Windows.ApplicationModel namespace. This appears to be preparing for an integrated contact experience similar to the one found on the people hub on the Windows Phone.  Similar to accessing files, music, pictures, etc, for contacts, you ac

Windows 8 Hands On Labs available

At Build, we had the opportunity to preview a number of Hands On Labs for development and managing Metro styled applications. Unfortunately, they were not available to non-build attendees and we weren’t able to bring them with us from the conference. Thankfully, the hands on labs are now available for everyone. You can download them now from the Build website. I tried a couple of them at the conference and the ones I tried appeared to be fairly well done. Labs are available in C#, VB, C++ and

Cancelling a Reactive Extensions Observable

I’m often asked how do you cancel an Observable. In previous posts, I’ve shown how to stop observing by disposing the result of the subscription to the Observable. Of course, this isn’t the only way. If you are using one of the Observable.Generate methods, you can pass in a pointer to an object (like the System.Threading.CancellationTokenSource) and change a flag on that object, then in the iterate lambda function, reference that object to see if the cancellation flag was set. Here’s an example:

Revising the Reactive Sensor Generator

When first created the Reactive sensor sample I wasn't completely happy with it because if any of the various subscribers were disposed or triggered an OnCompleted (like the Any) clause, it would trigger a completed state to all of the other “listeners”. This is not what I intended.  To make it easy, let’s review how we created the sensor originally: Private _observers As New List(Of IObserver(Of SensorInfo)) Private _running As Boolean Public Function Subscribe(ByVal obs

Updating Reactive Samples to 10425 build

Today, I decided to take the plunge and update my WPF and Silverlight Reactive Extensions samples to the latest (at the time of this writing) build of Rx: version 1.1.10425.0. At this point, I have purposely left the phone samples on the blog targeting the original shipping bits, so they aren’t affected at this point. (ED: the 1.0.10605 stable and experimental releases shipped as of 6/5/2011. Looking at the release notes, this update appears to have much less breaking changes beyond those in the

Using RX to detect shake Gestures

Part of the power of RX lies in it’s ability to compose complex operations  and keep the resulting code maintainable. I previously showed how to perform Drag-Drop operations with RX. This time, I want to take a look at a slightly more complex operation: Detecting “Shake” gestures on the Windows Phone 7. The phone includes the ability to detect motion in 3D space through the built-in Accelerometer in the Microsoft.Devices.Sensors library. This sensor raises events when the phone is moved w

Create an RSS Feed for PDC 2010 videos

I love the fact that Microsoft makes it’s conference materials available for those unfortunate enough not to be able to attend. I also love watching the videos on my Zune. Even better is when I can use the Zune podcasting ability to download these videos. So far, I wasn’t able to find such a feed. Thankfully, fellow MVP, Bill McCarthy posted some quick LINQ to XML code to generate HTML tables based on the Xessions XML that was used for PDC. You can read his post here:

Reactive Extensions responding to UI events

One of the great things about the Reactive Extensions is that they allow you to express rather complex interactions simply. For this example, we’ll consider the mouse drag drop operation in Silverlight. Note: The identical code works in both the web based Silverlight and the Windows 7 phone. If you want to download the phone version of this code, it is available in C# or VB. One of the indicators of simplicity is if you can explain a concept to your mother. How would you explain drag-drop to y

Reactive Extensions Phone 7 samples in VB

For a while, those of us who love Visual Basic have been struggling to make sure that newly released platforms include support for VB. When platforms that cater to the hobbyist, such as the new Windows Phone 7 tools are introduced without support for VB, we are particularly saddened. Happily, the team worked hard to overcome this shortcoming and announced today availability of the Windows Phone 7 tools in Visual Basic using Silverlight. You can download the tools now. In celebration of this opp

Reactive Framework Sorting it out

When I started looking at the Reactive Framework, one of the first things I did was to try creating some of the same standard LINQ queries that I’ve used against LINQ to Objects: Dim unsorted = From s In Sensor Where s.SensorType = "2" Order By s.SensorValue Select s If you try this where Sensor is an IObservable rather than IEnumerable, you will find that the Order By clause generates the following

Reactive Framework Subscribing to Events

Previously in my Reactive framework series, we saw how to create and subscribe to ongoing observable objects. While there are a number of cases where you would want to create your own observable type, often you simply want to compose reactive sequences in response to events raised by other means. Recently, I came across a simple example that can  show you how easy it is to subscribe to event and add functionality through the Reactive Framework’s extension methods. In this scenario, I neede

Reactive Framework as a Background Worker

In this introduction to the Reactive Framework series, we’ve spent a bit of time setting up our Observable and Observers and wiring them up. If you haven’t been following along, here’s links to the previous posts: Reactive Framework Why bother – Reactive Framework Building an IObservable Event Generator Reactive Framework Getting your LINQ on Reactive Framework Subscribing to Observables So far, our observers can listen to our sensor, but it turns out, we can’t know about it

Reactive Framework Subscribing to Observables

It’s been a while since I started the Reactive Framework series. In case you missed the earlier posts, here’s the links to what we’ve done so far: Reactive Framework Why bother – Identifying common scenarios solved by RX Reactive Framework Building an IObservable Event Generator – Generates random Observable values Reactive Framework Getting your LINQ on (Using LINQ over Observables) At this point, we’ve created our observer and set up the the logic that handles our OnNext values. What we hav

Reactive Framework Getting your LINQ on

Last time in our exploration of the Reactive Framework, we built a random Observable event generator. Now that we have our data source, we can start working with it. In the past, we would have hooked up event handlers to the event delegate and imperatively interacted with the values passed in the sender and EventArgs. Of course, when we Thinq LINQ, we try to find simpler, more declarative models to represent our intent. To start, we need to instantiate and start our event generator: Private

Reactive Framework Building an IObservable Event Generator

In my last post, I mentioned a number of cases where you may want to use the Reactive Framework. For some upcoming presentations, I wanted to focus on a couple of these scenarios, particularly on how you can use the Reactive Framework (rX) to work with events from device sensors. You can often find these kind of sensors in a number of industries, including Robotics, automated manufacturing systems, Medical monitors, Telecom usage, and Live financial feeds. In order to demonstrate using rX in thi

LINQ to CSV using DynamicObject and TextFieldParser

In the first post of this series, we parsed our CSV file by simply splitting each line on a comma. While this works for simple files, it becomes problematic when consuming CSV files where individual fields also contains commas. Consider the following sample input: CustomerID,COMPANYNAME,Contact Name,CONTACT_TITLE ALFKI,Alfreds Futterkiste,Maria Anders,"Sales Representative" ANATR,Ana Trujillo Emparedados y helados,Ana Trujillo,"Owner, Operator" ANTON,Antonio Moreno Taquer

LINQ to CSV using DynamicObject Part 2

In the last post, I showed how to use DynamicObject to make consuming CSV files easier. In that example, we showed how we can access CSV columns using the standard dot (.) notation that we use on other objects. Using DynamicObject, we can refer to item.CompanyName and item.Contact_Name rather than item(0) and item(1). While I’m happy about the new syntax, I’m not content with replacing spaces with underscores as that doesn’t agree with the coding guidelines of using Pascal casing for properties

LINQ to CSV using DynamicObject

When we wrote LINQ in Action we included a sample of how to simply query against a CSV file using the following LINQ query: From line In File.ReadAllLines(“books.csv”) Where Not Line.StartsWith(“#”) Let parts = line.Split(“,”c) Select Isbn = parts(0), Title = parts(1), Publisher = parts(3) While this code does make dealing with CSV easier, it would be nicer if we could refer to our columns as if they were properties where the property name came from the header row in the CSV file,

Pin DataTips in Visual Studio 2010

While debugging in Visual Studio 2010, I noticed that the DataTip now has a new feature. At the right hand side of the variable window, there is now a pin icon. Clicking on this pin icon adds the DataTip to the code window allowing it to float over the existing text. In addition to allowing you to drill into the variable’s values as you would in the watch, locals, or autos windows, You can also add comments which remain with the pinned DataTip. When you stop debugging, the DataTip

Setting DataContext Connection String in Data Tier

LINQ to SQL offers a quick mechanism to build a data tier in a n-Tier application. There’s a challenge when using the DBML designer in a Class Library. The designer stores the connection string in the Settings file. Although it appears that you can change it in the config file, any changes you make there will be ignored because they are actually retained in the generated Settings file. While you could go into the DataContext’s .Designer file and change the location of the connection string, an

Testing to see if a record Exists in LINQ to SQL

There are a number of options you can consider when testing to see if a record exists using LINQ to SQL. Which one should you use? It depends… In general, check the generated SQL for various options in SQL Management Studio to see the how the various execution plans compare. For example, each of the following can tell you if a record exists. Dim q1 = Customers.FirstOrDefault(Function(c) c.City="London") Dim q2 = Customers.Count(Function(c) c.City="London") Dim q3

Euler Primes with LINQ Iterators

Thanks' to Steve Smith’s Project Euler with LINQ, I’ve recently begun playing with the Project Euler questions seeing how far I can push my algorithm skills along with LINQ and LINQPad. LINQPad makes it easy to slap together some code samples and output results, including performance metrics, so I don’t need to worry with that plumbing code and can focus on creating fast code. While working on one of the problems I realized the solution would offer a good opportunity to demonstrate a nuance of

Generating Interfaces for LINQ to SQL Entities

At DevLink I had the pleasure of presenting a session on LINQ to SQL Tricks and Tips. The slides and demos for LINQ to SQL Tricks and Tips are available on my download page if you are interested. Following the session, an attendee voiced the desire for LINQ to SQL to create interfaces while it creates the class definitions in order to make it easier to mock the entities in unit testing scenarios. As part of the presentation, I showed Damien Guard’s L2ST4 code generation template. The great thin

MVC Sitemap Navigation with XML Literals

As I continue re-writing this site to use MVC, I find more substructures that I can refactor easily. In the original implementation for the menu, I used the asp:Menu control. As I was working to theme the site, I had problems getting it to work acceptably with CSS styles. I also didn't like the reliance on tables. In an effort to improve on it, I found the method of using unordered lists with list items for the menus (<ul> <li>). I then moved to a modified version of the UL SiteMap

Binding Anonymous Types in MVC Views

While translating this site over to MVC, I ran into a challenge when converting the RSS feed implementation. Currently I'm using XML Literals to generate the RSS and I could certainly continue to use that track from the Controller similar to the Sitemap implementation on Mikesdotnetting. However, putting the XML generation in the controller directly conflicts with the separation of concerns that MVC embraces. If I were only displaying one RSS feed, I might be willing to break this here. However,

VB Syntax Highlighting with JQuery and Chili

At CodeStock, I attended Rod Paddock's intro to JQuery session since I hadn't played with JQuery yet. As often happens when I go to conferences, being in the different environment starts to get the mind thinking in different ways. Sometimes the benefit of the conference isn't necessarily something stated directly, but rather a thought when the mind wanders. One such thought occurred during Rod's presentation where I thought that it might be interesting to "query" sets of text over a la

Fetching XML from SQL Server using LINQ to SQL

With SQL Server, you can use the For Xml clause (read more in BOL). The quickest option is to add For XML Auto at the end of a SQL statement. You can do this with dynamic SQL or inside a stored proc. If you use a stored proc, the DBML tool doesn't recognize this as XML (and return it as an XElement as it does for XML Data type columns). Regardless of whether you are using stored procs or dynamic SQL, the server returns the result as an array of strings broken up into 4000 character chunks. It is

LinqDataSource and CUD operations with Inheritance

When I added the Pingbacks and Trackbacks, I changed the implementation of the Comments to use an inheritance model (TPH) where Comments, Trackbacks, and Pingbacks all inherit from the abstract CommentBase class. To refresh your memory, here's the appropriate part of the DBML designer surface: While this works fine with minimal changes when viewing data, it can cause problems if you are using the LinqDataSource for editing values. When trying to update or delete a record, you may encounter a me

Implementing Pingbacks

Recently, I discussed Sending and Receiving TrackBacks on this blog. The TrackBack API is not the only mechanism which blog engines use to communicate between each other about the links that are included in individual posts. Wikipedia lists three methods to keep track of which articles are cross linked: Refback, Trackback, and Pingback. Of these, perhaps the trickiest to implement is the Pingback because it uses the xml-rpc style of communication rather than SOAP or REST that most .Net programme

ADO.NET Entity Framework Documentation Samples in VB

Last week, I announced that my translations of the Entity Framework samples were available in VB. Today the ADO.Net team announced that next set have been posted. These are part of the ADO.Net Entity Framework Documentation Samples. These are the projects that are used in the EF quick start and walkthroughs that come with the .Net documentation. They are a set of mini applications demonstrating using EF within the context of an application. The Course Manager sample was previously translated, bu

Sending TrackBacks

Yesterday, I showed how we can receive trackbacks from other sites using the TrackBack API. Today, we'll look at the other side of this picture: sending TrackBacks to other sites based on links in the post. Sending a TrackBack entails several steps: Parsing the post to find links to other sites. Checking the target site to see if it supports TrackBacks. Formatting and sending the TrackBack to the target's service. Checking for error responses. Thus with every post I create now

Receiving Trackbacks

If you've been following along, I've been working on enhancing this site a bit recently. A couple of the most recent enhancements can be found in the following posts: Paging with AJAX WCF and LINQ Adding Gravatar support to comments Continuing in this tradition, I wanted to include the ability to be notified when other sites post links to my posts. There are several such API's that support this kind of notification, including Trackbacks and Pingbacks. In this post, we'll look at recei

Entity Framework Samples in Visual Basic

For those Visual Basic users out that that have struggled with the fact that the samples were only available in C#, you can now rejoice. There are a number of projects that have now been translated into Visual Basic for your learning pleasure. You can find these samples on the MSDN Code Gallery’s Entity Framework page. At this point the following projects have been translated. Entity Framework Query Samples Compatible with .NET Framework 3.5 SP1 and Visual Studio 2008 SP1 (Visual Basic and C#

Paging with AJAX WCF and LINQ

These days, it seems that every web site needs to have some use of gratuitous AJAX in order to stay on the bleeding edge. Since we didn't have any here yet, I thought I would throw some in for good measure. I liked the lazy loading of records instead of paging found on some sites, including the Google RSS reader and thought I would see what it would take to add something like that here. If you're not familiar with this paging option, instead of loading a new page of records each time the user

Adding Gravatar support to comments

Having a bit more free time than expected, I thought I would take a bit of time and add some features to this site based on some things I've seen at other sites. A quick one is adding Gravatar support to the comments. If you're not familiar with gravatar's, describes them as a globally recognized avatar, is quite simply an image that follows you from site to site appearing beside your name when you do things. To get a Gravatar, go to and let them know your email add

Delegates and Lambdas in VB 10

Yesterday, I had the pleasure of demonstrating Delegates, Lambdas and Expressions at the Alabama Code Camp. This is not the first time I presented this. The original demo project is still available in the Downloads section of this site. This time however, I was able to round off the VB set of the demos to demonstrate all of the abilities available in C# 3.0 due to the new Statement and Multi-line Lambda language enhancements coming in VB 10. The complete VB 10 version of the project is available

LINQ supported data types and functions

When we were writing LINQ in Action, we weren't able to specify all of the possible methods and functions that have supported query translations for a couple reasons. There were too many to be included in the scope of the book. The book was being written at the same time that LINQ was evolving and more comprehensions were being supported, thus giving us a moving target that we couldn't ensure the accuracy of when the product shipped. We realized that over time, translations for more funct

Adding a dynamic SiteMap for search engine optimization using LINQ

A couple months ago I added a feature to this site to build a Site Map for this site dynamically based on the information from the database for posts and files for the downloads. If your not familiar with how Sitemap files can help your site searchability, Google has a good documentation about Sitemaps in their Webmaster tools. The SiteMap Protocal is a rather simple XML document consisting of a set of url nodes that consist of the following: loc - URL for the page link lastmod - Date

Updated source for ThinqLinq now available

It's been a while since I posted some serious content for which I apologize. I started this site a year and a half ago as a proof of concept around LINQ. When the site went live, I included the download version of the site from the presentations I've been doing on LINQ and Asp.Net. In all this time, I've made significant updates to the site, but haven't made them available, until now. If you're interested, you can download the updated bits from the file downloads here and play with them. I did t

Can and Should with Legacy Constructs

There are times where you wish you didn't have to worry about legacy code. This is particularly true with programming languages where constructs need to be supported even if they have long outlived their usefullness. Consider the following code that many of us "old-timers" learned to make the TRS-80 in the computer store go into an infinate loop (because the sales person didn't know how to break out of the loop). Public Shared Sub Main() 10: Dim x As String = "This is a test" : Console.Writ

LINQ is not an excuse for sloppy code

A couple months ago, I was convinced to try Twitter. In the process, I found which sends me notifications whenever someone tweets the word LINQ. Today I saw the following: "my visual studio crashed on retrieving 39,450 records via Linq.. what a shame.. looking for a workaround and a reason.." (name withheld to protect the guilty). In some ways, this falls into the category of, "Just because you can doesn't mean you should." In this case, the fault lies in the business requ

ThinqLinq on Deep Fried Bytes

Back at DevLinq (er DevLink), I had a chance to sit out on the back porch with Keith and Woody and chat about some of the cool features and rusty washers that you can find in LINQ. Head on over to and check out our conversation. You can also download the webcast to listen to on demand. Even better, you can listen on your Zune. As always, let me know what you Thinq.

Enabling intellisense for LINQ to SQL XML Mapping files

A while back, I showed you how to use an XML Mapping file to enable POCO support with LINQ to SQL instead of requiring you to clutter your class libraries with LINQ to SQL attributes. It turns out, the schema for the XML Mapping files (xmlns="") may not be included in your install of Visual Studio 2008. It was missing from mine. Luckily, the file is available on MSDN. If you add it to the schemas recognized by Visual Studio, you will get instant

Enable the Expression Tree Visualizer in VS 2008

In LINQ in Action, we discuss how to add the LINQ to SQL Query visualizer into the Visual Studio 2008 environment. This tool allows you to open a window during debug time to view the TSQL that is generated from the LINQ expression tree. It also allows you to run the query and view the results. If you're not familiar with it, check out this post by Scott Guthrie. In addition to the query visualizer, you can also build and install the Expression Tree visualizer, not only as a separate application

Object Identity tracking changes with LINQ to SQL SP1

When we wrote LINQ in Action, we took a bit of time to explain how the identity tracking system worked with LINQ to SQL to make sure that changed objects were retained when subsequent queries are requested from a data context. In a nutshell, when you issue a query, the data context translates the LINQ query into TSQL and sends that to the database. The database returns the rowsets to LINQ to SQL. The provider checks the returned rows against those that it is already tracking from previous fetche

Where clause optimized with VB 2008 SP1

There are subtle differences between VB and C# in terms of nullability. This caused a significant difference in the TSQL generated on even simple LINQ queries. Consider the following query from Northwind's Orders table where the Freight column is generated as a Nullable(Of Integer) type: Dim filtered = _ From o In dc.Orders Where o.Freight > 100 Select o First the bad news: with the RTM of VB 2008, this query resulted in the following TSQL: SELECT [t0].[OrderID], [t0].

VB Ordering of Anonymous Type Properties change with VS 2008 SP1

The VS 2008 SP1 includes lots of new features (more than a typical service pack, but that's another matter). There are a number of smaller enhancements that could easily go un-noticed otherwise. One of these is to fix a bug in the way the VB compiler generates anonymous types. In most cases, you will only notice this if you are binding an anonymous projection to a DataGridView or the ASP GridView. With these controls, you will find that the columns used to be generated alphabetically rather th

Filling an object from a DataReader with LINQ using DataContext.Translate

One of the key things that LINQ to SQL does for us is offers a quick way to fill a set of objects with data from a database. Typically this is done by setting up some mapping and calling the GetTable method on the DataContext. There are cases, particularly when you already have an infrastructure set-up to populate objects using a DbDataReader, where it would be nice if you could just populate the columns without the need to set-up a mapping. The DataContext has a little known method called Tran

Fetching child records using Stored Procedures with LINQ to SQL

You can consume stored procs rather than the standard dynamic sql for accessing child objects. To do this, set up your fetch stored procs and make sure that they return the correct data type (not the standard custom generated type for stored procedures). To load a child collection, create a method on the partial implementation of your context. Name the function "LoadCs" where "C" is the name of the child property accessor from the parent object in the designer. This function will take a type as

Screen scraping and creating Word documents with LINQ to XML

At TechEd Developers 2008 in Orlando, I had the pleasure of competing in Speaker Idol. In that competition, we had the opportunity to present a topic in 5 minutes. Unfortunately, the topic I choose really needed 10 minutes to cover at the level of detail it needed. Instead of limiting the topic, I decided to go ahead and present it a bit too fast. If you want to see the video, or see how to use VB 9's XML Literals and LINQ to XML to fetch data from a web page (that must be XHtml compilant), ma

Anonymous Type property ordering in VB

Many people have noticed when binding an anonymous type to a grid in VB that the order of the properties does not reflect the order that they were specified in the projection (Select) clause. Instead, they appear alphabetized. Consider the following query: Dim query = From c In Customers _ Select c.LastName, c.FirstName, c.BirthDate If you bind this query to a DataGrid or DataGridView and allow the columns to be generated automatically, the results will be displayed with the

Projecting into an unmapped property from a LINQ to SQL query

On page 216 of LINQ in Action, I made a comment that unmapped properties in a mapped class cannot be used in a LINQ to SQL projection. This was true with the beta bits, but only partially true with the release bits. To begin, let's consider the Author table we have in the book samples. The Author class has separate fields for the first and last name. Each of these is mapped to the corresponding fields in the Author table. In the book, we show how you can create a read only property in a partial

Joining composite keys with LINQ

LINQ makes working with data in its various guises easier. By intergating it into the language, we have rich integrated support for working with data. However, there are times where the syntax is slighly different from what you would typically expect with TSQL. Once case where this occurs is when trying to join two data sources that are related by more than one field (also know as a composite key). This differs from standard joins where one table has a primary key and the other table has a forei

Querying the complete plays of Shakespeare using LINQ to XML

I was working to come up with some creative uses of LINQ to XML for my new talk I'm giving at the Huntsville, AL Code Camp. I figured it would be good to include a sample which queries a large XML document. Remembering that the complete works of Shakespeare were available in XML form, I did a quick search and found a version at This file separates each play out into separate XML files. Since I wanted to find out which parts had the most lines acr

Managing self referencing tables with LINQ to SQL

Using a single self referencing table is a common database pattern for trees of data. As an example of this concept, we can use the Employee table in Northwind. It has a self referential relationship set up using the ReportsTo field. If we drag this into the LINQ to SQL designer, it will infer the self relation and create the appropriate EntitySet/EntityRef relationship exposing it with the Employees (for subordinates of a given employee) and Employee (for the reference to the boss). The Reports

LINQ Migration hints

So, you're thinqing about convering existing code to use LINQ? Here are a couple quick tricks to get you started: 1) Have your regression tests ready. No warrantee is implied as to your success once completing the following. 2) Find any imports to System.Data.SqlClient including global imports and remove them. See what breaks in your application and re-write it using LINQ to SQL instead of ADO. 3) Search for iteration loops (For Each/foreach) or explicit calls to enumerator.MoveNext and see

Personal Web Starter Kit LINQed up

In case anyone is interested, I have put together a sample port of the original Personal Web Starter Kit using LINQ rather than the standard ADO data tier in the PhotoManager.vb class. With this version, we can eliminate all of the stored procedures and rely on LINQ for our entire data access. In this implementation, I intentionally attempted to retain the original method signatures where possible to make migration more seamless. The project site is at

Adding categories to the RSS feed using LINQ to XML

Last time, we added categories to the web view of the ThinqLinq site. This time, we're going to add them to the RSS feed. Because RSS is "Really Simple", adding the categories is fairly easy. According to the RSS specification, <category> is an optional sub-element of <item>. It can additionally contain the domain that contains that category. In our case, we will point the domain to our implementation that displays all posts for a given category by passing the category id to the quer

Adding a RSS feed for file downloads

Ok, so I've been a bit busy this weekend adding some nice stuff for this site. One thing that I wanted to add was another RSS feed, this time for the file upload section. If you want to subscribe to the File RSS feed, direct your aggregator to the following link: Of course, since this is a learning site, I'll let you in on the code needed to accomplish the task. As you may guess, LINQ makes serving up XML from an object collection using a heterogeneous jo

Filtering items in the ThinqLinq aggregation feed

When I first released ThinqLinq, the only filtering I applied was to only select the top 20 posts. I was recently asked if I could extend the implementation so that it the aggregation feed could be filtered based on the categories. Since ThinqLinq uses LINQ for the data interaction, it is relatively easy to add filtering to the existing query. However, in this case, the filtering is not a simple Where clause on the underlying table. That is because the table structure uses a Many to Many relat

Using LINQ to SQL to return Multiple Results

In the LINQ in Action forum, a user asked about returning multiple result sets from a single stored procedure. Below is one way of dealing with this issue. In the procedure, we used multiple results rather than a result with a return value (through RETURN or an OUTPUT parameter). Here we need to use the IMultipleResult rather than the default ISingleResult implementation. It appears that the designer does not map IMultipleResult in the final build, so we are going to need to do it ourselves. We

Creating HTML emails using VB 9 and LINQ

Today, I'm not looking at sending mass spam using LINQ to pull a list of recipients. I'm actually referring to the ability to generate the message body using XML Literals. Using the System.Net.Mail.MailMessage object, we can easily send emails to an SMTP server. The body of the email can either be plain text or HTML. Dynamically generating the text is often a laborious task involving a string builder and lots of method calls. The body corresponds to the body portion of a HTML page. If you use

Code Snippets and Partial Methods

In my VB 9 language enhancements talks, I do them withalmost all coding on the fly as I find people often can comprehend the code. I start by building a quick class that is used throughout the demos. To assist, I do use the snippet functionality in VB. For example, if you type "property" and then tab twice, the designer will generate a private field with public property accessors. The if you change the highlighted values, any associated names will be changed as well. Private newPropertyValue As