Search results for Visual Basic.Net - ThinqLinq by ThinqLinq


Roslyn resources

Today I’m giving a hand’s on hack session on using Roslyn to create code Diagnostics. As part of that, I put together a listing of some resources that might be helpful and thought I’d share them with everyone. Realize that these links are based on the versions for the Visual Studio 2015 RC and are subject to change when the product releases. With that in mind, here are the links: Download Visual Studio versions: Github repository for the Roslyn compilers: http

ThinqLinq Samples on Github

When I first created this site, I used it both as a test bed for technologies as I played with them and as a repository for others to use for my presentations and other insights. Over the years people have been free to grab these samples, but haven’t had good ways of giving back to help improve the samples. In the mean time, there have been quite a number of technology changes. While I may have been late to the party on some, there’s only so many things one can focus on. One of the advances we’

Reactive Extensions RX in Action the movie

I’ve been giving presentations for some time now. By far, my favorite talk to give is my Reactive Extensions in Action. This past summer, I had the talk recorded at the Code on the Beach conference. If you haven’t had a chance to see it live, now’s your chance. The focus of this talk is to focus on some of the practical uses of Rx rather than the underpinnings of how it works. I hope you enjoy and this sparks ideas from you on how you can use it in your applications. Rx in Action recorded at C

Rx for Windows Phone article now available

A couple of years ago I gave a presentation at the last MIX for doing asynchronous programming using Reactive Extensions (Rx) on the Windows Phone. The video of the presentation is still available for watching. Around the same time, I was approached by Code Magazine to write a similar article, which I was happy to oblige. It took a while but I was happy to see the article finally published in the Sep/Oct 2013 edition of Code Magazine. In the article I demonstrate how to use Rx to build a dice r

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

Dynamic Programming in a Statically Typed World

Tomorrow night, I’m giving my presentation discussing not only how, but when to consider using the dynamic features of C# 4 and VB (forever). If you attend the presentation, you can download the samples and slides from my download page. Part of the key in this presentation is  discussing the Why as compared to the simpler How of Dynamic. Here are some of my top reasons to use the dynamic features: Testability When trying to use unit testing, the compiler often limits the ability to follow

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

Visual Studio 2010 Keyboard Binding Poster

When I work with new teams, I often get asked how I did x using the keyboard instead of reaching for the mouse. I find if I can keep my hands on the keyboard, I can often be much more productive. So, how do you learn to take advantage of the keyboard shortcuts, I recommend downloading one of the Key binding posters like the ones that were just released for Visual Studio 2010. The posters are available for VB.Net, C#, F#, and C++. Once you have then downloaded, pick a  a different key bind

Replace Foreach with LINQ

One of the best ways to start Thinqing in LINQ is to find places where you can replace iterative loops with LINQ queries. This won’t necessarily make your applications any faster at the moment, but by taking advantage of the declarative syntax, it will allow you to change your underlying implementation (ie. parallelize it with PLINQ) easier in the future. Recently, I came across some code that mimicked creating a control array as we used to have in VB6 by iterating over a list of fields and addi

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

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,

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

Using Cast Or OfType Methods

When working with generic lists, often you want to work with a more specific type than the list natively exposes. Consider the following where Lions, Tigers and Bears derive from Circus Animal: Dim items As New List(Of Object) items.Add(New Lion) items.Add(New Tiger) items.Add(New Bear) Dim res1 = items.Cast(Of CircusAnimal)() Dim res2 = items.OfType(Of CircusAnimal)() In this case, both res1 and res2 will return an enumerable of CircusAnimal objects rather than jus

Watch language differences when parsing Expression Trees

I’ve run into a number of cases where people have built LINQ providers and only tested them with C# clients. In one case, I was sitting next to the person who wrote the provider when we discovered that using a VB client didn’t work with their provider because they failed to test it. I’ve even seen it in the sample Entity Framework provider  available on the MSDN Code Gallery when parsing the .Include() method. Hopefully, you will be able to access my VB translation of the EF sample provid

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

Iterators OR Excuse me waiter theres a goto in my C sharp

At Codestock '09, I gave my LINQ Internals talk and had a number of people express shock when I showed the underlying implementation of their beloved iterators when looking at the code through Reflector. Let's look first at the C# that we wrote. This is similar to the implementation of LINQ to Object's Where method as shown in the sequence.cs file that's part of the C# Samples. public static IEnumerable Where(this QueryableString source, Func predicate) { foreach (char curChar in source)

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

Add Extension Methods in LinqPad

As we already announced, the samples for chapters 1-8 of our LINQ in Action book are available through LINQPad. This includes the LINQ to Objects and LINQ to SQL. I've been working on the LINQ to XML chapters (9-11) and hope that we will add them to the download soon. In the process, I've needed to learn a bit about how LINQPad works under the covers in order to add specialized classes. By default, LINQPad offers three options: Expressions, Statements and Programs. With the Expressions, you can

LINQ In Action Samples available in LINQPad

I've been asked for some time what I think about the LINQPad tool. For those of you unfamiliar with it, LINQPad is a small but powerful tool that allows you to test your LINQ queries along with other VB and C# code. With this tool, you insert your code snippets in the code window and run it directly. If you point it to a database connection, LINQPad will build the .DBML behind the scenes and let you access the generated classes just as you would inside visual studio. When you execute the code, y

GhostDoc with full VB support

I have used the GhostDoc tool before and found it to be helpful in adding comment stubs to methods. Using it is really easy. Just select the method you want to annotate and press the hot-key (CTRL-SHIFT-D by default). For example, when we were showing how to implement pingbacks we added a method that parsed the post and sent the pingbacks accordingly. To refresh your memory, the method's signature was as follows Public Shared Sub ParsePostAndSendPostbacks(ByVal source As PostItem) End Sub Alth

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

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

F Sharp and the Excel Financial Functions

With my focus on LINQ, I have been considering the functional implications of the changes to the standard imparitive languages. As a result, I've been trying to watch the changes coming with the new F# Functional programming language which will be part of VS 2010. When thinking about the use cases for F#, areas with heavy computational needs are often the best use case. In many ways, I would think one ideal place for using F# would be in Excel where many business people have no problems chaining

VB 10 Samples and White-paper

If you want to get a head start on the new language features coming in VB 10, head on over to the MSDN Code Gallery and download the samples and white-paper. Some of the new features are: Multi-line and statement lambdas Auto-Implemented Properties Collection and list initializers No PIA (that's Primary Interop Assembly, not the other PIA) Generic Variance Implicit line continuation We'll be showing these off at the MDC in a couple weeks. Make sure to come out and see what these are al

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

LINQ to Reflection IsNot LinqProvider

In one of the sessions I attended at DevLinq (er, DevLink), the presenter was discussing the providers that shipped with VS 2008. Among these, he included the standard LINQ to Objects, LINQ to XML, LINQ to SQL, LINQ to Entities and LINQ to Datasets. In addition, he added LINQ to Reflection which struck me as unusual, so I looked it up. In this case, LINQ to Reflection isn't really a provider, but just a specific implementation of LINQ to Objects which happens to query reflection informat

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

LINQ to SQL support for POCO

One of the strengths that LINQ to SQL has over the upcoming Entity Framework is its support for POCO, or Plain Old Class Objects. With LINQ to SQL, the framework doesn't require any particular base classes, interfaces or even reliance on the 3.5 framework for the resulting objects. I demonstrated this in the talk I did at the Teched Tweener weekend. Download the demo project to see this in action. In this sample, I created two separate projects. The first class library project, I created only t

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

Consuming a DataReader with LINQ

Last night at the Atlanta MS Pros meeting, I gave the first my new talks on LINQ Migration Strategies. If you missed it, you can catch me at the Raleigh, NC and Huntsville, AL code camps. Baring that, check out the presentation slides. This talk focuses on how you can extend existing structures using the power of LINQ. Among other things, this includes LINQ to DataSets and the XML Bridge classes. During the presentation, fellow MVP, Keith Rome asked a question that I couldn't let sit. Is it pos

Dynamically extending LINQ queryies without building expression trees

As more content is added to this site, I wanted to add a searching function. The implementation here is relatively simple. We will parse the input string into the various words represented and perform a TSQL LIKE filter in the WHERE clause. Doing this on a single string is relatively simple. We just use the String.Contains method in the WHERE clause as follows: Dim query = From p in dc.PostItems _ Where p.Description.Contains(InputValue) _ Select p This

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

Projecting XML from LINQ to SQL

Among the new cool features in Visual Studio 2008, one of the best may be the XML Literal support with VB 9 and LINQ. In my last post, I mentioned some changing features from the Beta to RTM. One that could easily be overlooked is a change to the way LINQ to SQL can now directly project into XML literals. Through the Beta cycle, there was an issue with projecting XML elements directly from a LINQ to SQL query. If you haven't seen LINQ to SQL with XML, here's a code sample that explains what I'

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

Adding RSS posts to ThinqLinq using System.ServiceModel.Syndication.SyndicationFeed

When I originally started the ThinqLinq project I began by loading the RSS feed from my DevAuthority blog, and iterating over the results adding them to the PostItems table in the data context. With LINQ this is relatively easy. Loading the XML from the feed is done with a single line: Dim Feed As System.Xml.Linq.XDocument = _ XDocument.Load("") The xml document consists some basic informational elements which are not terribly important in this instance as w

Code Camp 2007 downloads

I've uploaded the files for my presentations for the fall Code camp season which I just presented last weekend at the Birmingham, Alabama code camp. If you missed the talks, you can pick up the downloads at the following links. Also, I will be at the Charleston, South Carolina code camp this coming weekend (10/13) so you can catch me there. Additionally, the ThinqLinq talk is still available on the Links to all three parts of the webcasts are available on the file download pa

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

Playing with fire simulating extension members via Extension Methods

As I was listening to Scott Hanselman's Hanselminutes episode on LINQ to XML, he made a statement insinuating that you could add stateful behavior to objects via extension methods. As I was adding a comment stating that it was not possible, I started thinking and figured out a way. I DO NOT RECOMMEND DOING THIS. It is possible, but will not scale. That being said, here's a possible implementation to set and retrieve a MiddleName value to a Person object that does not have a middle name property

Stop using IIF

For a long time, VB has had an operator called IIF which allows you to evaluate a condition and return a true value or false value as a single line evaulation. I'm sure some of you out there have used the IIF function at some point in the past. If you're unsure, here's a quick sample piece of code.     Console.WriteLine(IIf(x > 1, Evaluate(True), Evaluate(False))) In this case, we evaulate the expression x > 1. If it is true, we call a method called Evaluate passing true a

LINQ to SQL Compiled Queries

As LINQ nears release, people are starting to consider the performance implications that the extra overhead brings. Currently there are two threads on this: thread1, thread2. For those that are intested in the performance implications, I highly recommend checking out the outstanding series of posts by Rico Mariani. Ultimately if you want to get the best performance, you need to use the Compile function of the CompiledQuery class. Let's consider the following query (Note, turn this into C# by a

Use the new LINQ Contains extension method for the SQL IN clause

For a while, users were requesting a way to map the SQL "IN" clause as in the following: SELECT Customer.Name FROM Customer WHERE Customer.State IN ('GA', 'FL', 'AL') Prior to Beta 2, this would mean either separate OR clauses for each item, or worse yet a heterogeneous join between the database and an in memory array. Why do I say, worse yet? Because the heterogeneous join option meant bringing all of the records from the database and filtering on the client. Beta 2 introduced a new "Cont

Option Infer in VB

With the upcoming language enhancements in VB and C#, some leads are concerned with code maintainability when not explicitly declaring the resulting type on an anonymous type. If you are not familiar with local variable type inference, here are a couple examples: VB: dim i = 5 dim j = "foo" C#: var i = 5; var j = "foo"; In both cases, the first variable (i) is inferred as an integer and the second is inferred as a string. In some cases, particularly in a

Changed order of LINQ operators for VB 9

With the March Orcas CTP, the order of operations has changed for VB LINQ Queries again. No, they have NOT moved Select back to the beginning. In this case, they have moved the Order By clause before the Select. In case you prefer a bit of code consider the following: May 2006 CTP: dim res = From fi in New System.IO.DirectoryInfo("C:\").GetFiles() _ Select fi _ Order By LastAccessTime March 2007 CTP: dim res = From fi in NEw System.IO.DirectoryInfo("C:\").GetFiles

Querying Winforms with LINQ

A couple of months ago, someone asked on one of the forums how you could dynamically switch a control from a textbox to a label based on the editability of the record based on business requirements. The best solution was to change properties on the textboxes to make them look like labels. Below is a quick method to do this: Private Sub SwitchControl(ByVal box As TextBox) If box.ReadOnly Then box.BorderStyle = BorderStyle.Fixed3D Else box.BorderStyle = BorderStyle.None End If b

Single Instance Winform in Citrix published application

About a year ago I one of the first blog posts I wrote related to Single Instance Winform applications. While these are much easier to do with VB 2005, I didn't expect to run into issues with it after it was working fine for a year. In our production environment, my current company uses Citrix with Terminal Services to serve the desktop to all users. We have one application which we wanted to serve out as a published application. We set it up and it appeared to work fine. As deployments go, it w

ASP Security is more than just SQL Injection

Last night's Atlanta Microsoft Database Forum meeting had another discussion of SQL Injection and how it is a bad thing. In the end, the best thing to do to avoid it is to use parameterized queries (which include, but are not limited to Stored procedures). In short, if you write your data access code in your application like the following, you are prime for an attack: dim stSql as string = "select * from users where userid='" & Request("UserId") & "'" Instead, take a little more care an

LINQ Webcast online

Last month, WROX press recorded several of the sessions at the Atlanta Code Camp, including mine on how the language changes in VB 9 and C# 3 lead to LINQ. If you missed the talk, you can now watch it online at I haven't had a chance to watch the whole thing yet, but from what I saw so far it looks like they did a pretty good job with it, including indexing the talk. Check it out and let me know what you think.

LINQ over Datasets or the Bang is back in VB9

One of the features that was added to the May CTP of LINQ was the ability to query over DataSets. There are some minimal methods of manipulating data in existing implementations of the DataSet, including filtering with DataViews, the .Filter method and using DataTable.Select(). If you wanted to work with multiple tables, you needed to use a DataViewManager object. The overview of these options is online on Msdn. One of the new features of the May CTP of LINQ includes the ability to create queri

LINQ to XML Rocks Because

I’m in the process of finalizing a number of presentations on LINQ. I will be posting the demos and slides soon. As a teaser, here’s a quick snippet from the XLinq demo. I begin by showing the new functional construction syntax for XLINQ. 'Uses Functional Construction Dim x As New XElement("LinqEssentials", _ New XElement("Category", "LINQ"), _ New XElement("Category", "DLINQ"), _ New XElement("Category", "XLINQ")) Dim y As New XElement("LanguageFeatures") y.Add(New XElement("release", New XAtt

Rounding in .Net

A while back I was stung by the rounding "bug" and forgot to blog about it. I was unaware of the fact that Round by default uses accounting rounding where you round to the nearest EVEN value. Thus round(1.5,0)=2 and round(0.5,0) = 0. Although this agrees with the ISO standard, it does not agree with the behavior we are taught to expect in elementary math, nor does it agree with the functionality of .ToString where 0.5.ToString("n0") = "1". This discrepancy can cau

ERL in VB.Net

A while back I posted that the ERL function is still available in Vb.Net. I was prompted to re-look at the code from a recent newsgroup post and realized that, while it is possible to use ERL, there is a definite performance penalty. Consider the original sample as below: 10: REM This program doesn't do much 20: Try 30: REM Throw an error 40: Throw New DivideByZeroException 50: Catch ex As DivideByZeroException 60: Console.WriteLine("Error occured in line: " & Erl())

Change VB9 to B Sharp

Over on the MSDN Forums, there is a post pondering changing the name of VB.Net to B# (see: Here's my tongue-in-cheek take. As a programmer and musician, there is a problem with B#. In music (or at least on the keyboard) B#=C. Even if we go with the idea that such a change would put B# on the same level as C, we would still be behind the times in languages (we would need B++ and B## or Bx (x=double sharp) to get to the s

Decimal.TryParse with Currency input values

I found an issue (or rather the issue recently found me) concerning my advice advocating using Decimal.TryParse on currency items. It turns out if you use the base implementation of Decimal.TryParse, it will not work when presented with currency values by default. Instead, you need to use the overload and specify the NumberStyle explicitly as below: Dim res As Decimal If Decimal.TryParse("$1.00", Globalization.NumberStyles.Currency, Nothing, res) Then Console.WriteLine(res.ToString)

DataGridView binding with abstract base classes

I recently ran into one of the most frustrating issues to face someone debugging a released application: a bug which only appears intermittently. In the instance, I have a collection of business objects that are being bound to a DataGridView. Periodically, the grid would throw repeated TargetInvocationExceptions when being bound. In my case, the collection contained both objects directly implementing a base class and other objects inheriting from the base class and extending upon it. I found th

Advantage of TryParse

I recently had the opportunity of showing the Altanta VB group the advantages of using the new TryParse method introduced in .Net 2.0. The presentation materials along with a sample project are available at the group's website. In early versions of .Net, in order to check the validity of a data type, you had to go to some excess measures. There are a number of options: 1) Don't check the data. The user wouldn't be silly enough to try to type their name in a date field, or would they. Oh, they

VB.ReallyOld features still in VB.Net

While typing some code, I noticed that REM is still supported as a way to comment code. The only reason I can see why one would want to do this is to retain legacy code. There are some other really old features that haven't been documented since VB3, most notably the useful ERL() function. (It is back in the official documentation as well.) This means the following is valid VB.Net code: 10: REM This program doesn't do much 20: Try 30: REM Throw an error 40: Throw New DivideByZeroExcepti

Disposing a user control within a DataGridViewComboBoxColumn

By default, User controls dispose of all of the controls as part of their cleanup process. However, when using a DataGridViweComboBoxColumn, the column is still bound to the data source. While disposing you can encounter multiple exceptions as the values in each bound ComboBox cell is disposed if the ComboBox's datasource is disposed prior to the grid's binding source. To avoid this issue, make sure to force your BindingSource that the data grid is bound to to Nothing/Null at the beginning of th

Property as string Nullable by default

It appears that the string parameter of a method is Nullable by default under 2.0. I am having cases where my UI using the new object binding is returning Nothing to a property Set declared as below: Public Property MyValue() as String Set(ByVal value as string) 'value may be Nothing/Null here rather than an empty string End Set ... End Property Thus any action you take on the value will need to check for nothing first (including Trim, ToUpper, etc). This is particularly problematic when

Accessing Private methods via reflection

At a recent Atlanta VB Study Group meeting, the topic of Reflection was presented. As part of the discussion, I mentioned that it is possible to call private methods from external classes. Unfortunately I stumbled briefly trying to demonstrate how to accomplish this. In the meeting, I attempted to modify the existing code. Below are the appropriate code snippets for demonstration purposes. Public Class MyClass Private Sub YouCantSeeMe() MessageBox.Show("You shouldn't be here.

Single Instance Winform Issue

In the simplest terms, a single instance application is an application which will only display one copy to a user at any time. This can be simply accomplished by a calling application by checking to see if a process is already running. The System.Diagnostics.Process namespace offers a number of ways of getting a handle on an existing process, including GetProcessByName("ProcessName"), GetProcessById(MyId), and GetProcesses(). Once you have a handle on it, you can inquire about the proc