Recent posts about LINQ and related topics - Page 1 by ThinqLinq

External USB Monitor for road warriors

I’ve been a consultant for a number of years. Typically, I’m working on a customer’s site to provide solutions for them both in what I’m currently working on, and to pay attention to other needs that they may have that I can help to offer solutions for. At the client’s location I’m given a desk to work at, but I’m responsible for my own equipment. The laptop situation is no problem, but I’ve been spoiled by having dual monitors in the past.

Six months ago, I happened upon a great solution to the problem. The AOC 16” USB powered monitor. It is just about the same size as my laptop and offers an additional 16” display at 1366x798 resolution. This is great for email, twitter, and debugging purposes. Being a USB monitor I can’t recommend using it for hi-res video, but then again, you wouldn’t be watching Netflix on the job anyway, right?

Posted on - Comment
Categories:

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 certain level of complexity to the language. Any language feature then needs to be maintained moving forward. When I asked Anders about adding them to C#, he pointed to the ongoing maintenance issue along with the supposition that although XML was becoming a de-facto data persistence syntax, would adopting the literals into the language then set a precedence that they would need to support other persistence mechanisms when XML was replaced with some other syntax.

With the rise of REST and decline of SOAP, we have indeed seen the popularity of XML wane in favor of the more compact json syntax. The popularity is increased due to the fact that most JavaScript clients make parsing json into objects trivial. As a result, I have had conversations at conferences joking about the need for json literals in the language as well. At a recent conference an idea came to me which could actually make them (almost) a reality.

At its heart, json is simply a string representation of the JavaScript object structures. These object structures behave much like the .Net dynamic PropertyBag object. As a result, all we really need is a way to embed a long, multi-line string into our VB code and then parse it into a dynamic PropertyBag in order to consume it. Unfortunately, VB doesn’t support multi-line strings. However, it does support multi-line XML. All we need to do is wrap the multi line string inside of an XML element literal:

        Dim jsonLiteral = <js>[
            {author:'Jim Wooley', bookName:'LINQ in Action'},
            {author:'Frank Herbert', bookName:'Dune'},
            {author:'Joe Albahari', bookName:'LINQ Pocket Reference'},
            {author:'Joseph Rattz', bookName:'Pro LINQ'},
            {author:'Charlie Calvert', bookName:'Essential LINQ'}
        ]</js>

With that, we just need to decode the jsonLiteral.Value into a dynamic object. A quick search of Stack Overflow finds a number of handy options for this task. For the sake of this example, I’m just going to use the System.Web.Helpers.Json library that’s part of MVC. We’ll create an extension method to take an XElement and convert it into a dynamic object using the Json.Decode method:

<Extension>
Public Module JsonExtensions
    <Extension>
    Public Function JsonDecode(input As XElement) As Object
        Return Json.Decode(input.Value)
    End Function
End Module

With this in place, we can now operate on the literal just as if it was any other dynamic object type. Here’s the full code for this example.

Option Strict Off

Imports System.Runtime.CompilerServices
Imports System.Web.Helpers

Public Class Test1

    Public Sub TestJsonLiteral()
        Dim jsonLiteral = <js>[
            {author:'Jim Wooley', bookName:'LINQ in Action'},
            {author:'Frank Herbert', bookName:'Dune'},
            {author:'Joe Albahari', bookName:'LINQ Pocket Reference'},
            {author:'Joseph Rattz', bookName:'Pro LINQ'},
            {author:'Charlie Calvert', bookName:'Essential LINQ'}
        ]</js>

        For Each book In jsonLiteral.JsonDecode()
            Console.WriteLine(book.author)
        Next
    End Sub
End Class

<Extension>
Public Module JsonExtensions
    <Extension>
    Public Function JsonDecode(input As XElement) As Object
        Return Json.Decode(input.Value)
    End Function
End Module

I’m sure that there are features that this technique doesn’t cover (including LINQ because Object isn’t directly convertible to IEnumerable). I’m also not sure if this really has any practical benefit. It just is interesting to consider.

Posted on - Comment
Categories: VB - VB Dev Center - Linq to XML -

INETA Community Champion for 2012 Q4

INETA Community Champions I’ve been active in the technology community since 2000 when .Net was just announced. This started with doing some small talks at user group meetings and helping to update their web site. It didn’t take long before I was running meetings and networking with other groups.

Over the years, I’ve gradually increased my reach by speaking at events increasingly far from my home base, including events as far away as London, Las Vegas, and Redmond. Prior to it’s being disbanded, my speaking involvement lead me to being selected as a member of the INETA Speaker Bureau. I continue to work with INETA as a member of their more localized version, the INETA Community Speakers program.

I’ve also continued reaching out to help mentor other user group leaders through being an INETA Membership Mentor for a number of years. I also participate in UG Leader summits when I’m able.

Recently, I was honored to be recognized by my peers as an INETA Community Champion for Q4 2012. While I never aspired for such recognition, it’s a privilege to have my efforts recognized by the community at large. Having received this award doesn’t mean the work is done. I continue to share my experiences with others to help grow the community as much as I can. Who knows what the future might bring, but I hope I can continue to bring the love of technology to others, just as my mentors have done for me in the past.

Posted on - Comment
Categories: Code Camp -

Office 2013 RT excludes programming features

When I started my programming career, I started with writing Access applications with VBA. While I have moved away from these applications for the most part, I occasionally find the need to come back to office automation tasks in Excel, Word and Access. When reviewing the version of Office that comes with the new Surface tablet running Windows RT and Office 2013 RT, I checked out the developer tool bar to see what it offered. Here’s the new toolbar in Excel 2013 RT:

ExcelDeveloperToolbar

As a point of reference, here is the toolbar as it appeared in Excel 2010:

Excel2010DeveloperBar

Notice here that the Code (including VBA and Macros), Add-ins, and Controls sections have been removed from the RT version of Office. I suspect the issue here is that VBA is really locked into the x86 architecture. Since Windows RT runs on the ARM rather than x86 processors, the amount of effort to migrate this functionality was not worth the effort.

As a result, if you have Office solutions that you want to continue to use on the new platforms, be careful what features you use. If you need to continue building solutions based on office, I suspect that support will be added for the new Office app model based on HTML and JavaScript. While we’ve heard rumblings for some time on the impending demise of VBA, this appears to be a clear sign that continuing to invest time and money on extending the old VBA based solutions appears to be a dead-end solution in the new tablet/mobile world.

Posted on - Comment
Categories:

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 all report to Steven.

image

In order to generate a tree representation of these records, we could start with any records that have no direct reports and then lazy load each of their children. Unfortunately for large graphs, the number of database hits will grow exponentially as we add tree levels. Typically with parent-child relationships, we could eager load the children using the DataLoadOptions with LINQ to SQL or .Includes with Entity Framework. However with self-referencing entities, this isn’t allowed. With LINQ to SQL, you will get an InvalidOperationException “Cycles not allowed in LoadOptions LoadWith type graph.”

So, how do we load the tree in one pass and build the object graphs? It’s really not that hard once you realize how reference types (classes) work in .Net. Let’s start by creating a holder for each employee and their associated direct reports:

Public Class HierarchicalEmployee
    Public Sub New(emp As Employee)
           Model = emp
    End Sub
    Public Property Model As Employee
    Public Property DirectReports As New List(Of HierarchicalEmployee)
End Class

Now that we have this type, we can fill it using a simple LINQ request. In order to optimize the next step, we’ll push the values into an in-memory Dictionary indexed by the EmployeeID:

Dim allEmployees = Employees.
    Select(Function(emp) New HierarchicalEmployee(emp)).
    ToDictionary(Function(emp) emp.Model.EmployeeID)

Next, we iterate over the full list. For records that have a ReportsTo value, we’ll add their object pointer to their parent’s DirectReports list:

For Each emp In allEmployees.Values
  If emp.Model.ReportsTo.HasValue Then
    allEmployees(emp.Model.ReportsTo.Value).DirectReports.Add(emp)
  End If
Next

Notice, here we take advantage of the Dictionary’s hash rather than having to iterate over the list each time we want to find the parent record. Finally, instead of returning the full list, we only return the employees that don’t have any children (where the ReportsTo is null).

 
Dim rootEmployees = allEmployees.Values.
    Where(function(emp) Not emp.Model.ReportsTo.HasValue())

If we want to test this out in LinqPad, just use the Dump method on the resulting rootEmployees. As a result, you’ll see the following in the results pane. Notice Andrew is the only root object. He has 5 direct reports and one of his reports had 3 reports. You could just as easily bind this to a treeview control or output it using your favorite UI tooling.

 

image

The nice thing about this solution is that if we check the generated SQL, we will just see a simple (single) SQL request to generate the entire graph. As a summary, here’s the complete code from the LinqPad sample:

 

Sub Main
    Dim allEmployees = Employees.
        Select(Function(emp) New HierarchicalEmployee(emp)).
        ToDictionary(Function(emp) emp.Model.EmployeeID)

    For Each emp In allEmployees.Values
        If emp.Model.ReportsTo.HasValue Then
            allEmployees(emp.Model.ReportsTo.Value).DirectReports.Add(emp)
        End If
    Next
    
    Dim rootEmployees = allEmployees.Values.
        Where(function(emp) Not emp.Model.ReportsTo.HasValue())
        
    
    rootEmployees.Dump
End Sub

Public Class HierarchicalEmployee
    Public Sub New(emp As Employee)
           Model = emp
    End Sub
    Public Property Model As Employee
    Public Property DirectReports As New List(Of HierarchicalEmployee)
End Class
Posted on - Comment
Categories: VB Dev Center - LINQ - Entity Framework -