Visual Basic 6 and LINQ

 

 

 

 

 

Is it possible to use LINQ and Lambda Expressions in Visual Basic 6?

One solution is to use COM Interop. When a COM client like Visual Basic 6 calls a .NET COM object, the common language run-time creates the managed object and a COM callable wrapper (CCW) for the object.

What is COM callable wrapper (CCW) ?

Code that operates within the .NET Common Language Runtime (CLR) is called managed code. This code has access to all the services that the CLR brings to the table, such as cross-language integration, security and versioning support, and garbage collection. Code that does not operate within the CLR is called unmanaged code. Because COM was designed before the CLR existed, and COM code does not operate within the infrastructure provided by the CLR, it can’t use any of the CLR services. All of your COM components are, by definition, unmanaged code.
Managed code components not only depend on the CLR, they require the components with which they interact to depend on the CLR. Because COM components don’t operate within the CLR, they are unable to call managed code components directly. The unmanaged code simply cannot reach into the CLR to directly call managed components. The way out of this dilemma is to use a proxy. In general terms, a proxy is a piece of software that accepts commands from a component, modifies them, and forwards them to another component. The particular type of proxy used in calling managed code from unmanaged code is known as a COM callable wrapper, or CCW.

If you need to use LINQ and Lambda Expressions in your Visual Basic 6 code, you can create a .NET component and expose it to the COM environment using CCW process. For creating .NET components, you can use a class library template and you need to follow the following steps to register your .NET COM for COM interop.

Step 1. With a project selected in Solution Explorer, on the Project menu, click Properties.
Step 2. Click the Compile tab in Visual Basic. Click the Build tab in C#.
Step 3. Select the Register for COM interop check box.

When you build your project, it creates a dll file together with a type library file (tlb) that COM client such as VB6 requires to establish the communication. The following example shows how to create a .NET COM with the required interfaces assuming the Register for COM interop is already checked.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;

namespace VB6andLINQ
{
    [Guid("5B43FD73-4B20-40BB-A6C8-8312E5137E79")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface _BrowseDirectory
    {
        [DispId(1)]
        Int32 GetFilesUsingLINQ(string sourceDir);
    }

    [Guid("A2731C3E-9A90-4938-93A5-114EC61957DA")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("VB6andLINQ.BrowseDirectory")]
    public class BrowseDirectory : _BrowseDirectory
    {
        static int MatchedCount = 0;
        public Int32 GetFilesUsingLINQ(string sourceDir)  
        {
            string[] fileNames = null;
            try
            {
                fileNames = Directory.GetFiles(sourceDir, "*.txt",
                                                SearchOption.AllDirectories);
            }
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine("You do not have permission to access one or more" +
                                     " folders in this directory tree.");
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("The specified directory {0} was not found.", 
                                                                     sourceDir);
            }
            string searchTerm = "binding";
            var fileContents = from file in fileNames.AsParallel()
                               from line in File.ReadLines(file)
                               where line.Contains(searchTerm)
                               select new { File = file, Line = line };
            try
            {
                foreach (var item in fileContents)
                {
                    MatchedCount++;
                }
            }
            catch (AggregateException ae)
            {
                ae.Handle((ex) =>
                {
                    if (ex is UnauthorizedAccessException)
                    {
                        Console.WriteLine(ex.Message);
                        return true;
                    }
                    return false;
                });
            }
            Console.WriteLine("\nFound {0} match(es) for the word \"{1}\" in {2}.",
                                                MatchedCount, searchTerm, sourceDir);
            return MatchedCount;
        }
    }
}

LINQ to Craigslist in C#


 

 

 

Searching Craigslist using LINQ

The RSS feed from the results page of Craigslist is an XML file. LINQ to XML is an up-to-date, redesigned approach to programming with XML. It provides the in-memory document modification capabilities of the Document Object Model (DOM), and supports LINQ query expressions. Although these query expressions are syntactically different from XPath, they provide similar functionality.
The following example shows how to search in Craigslist categories by providing the site name, and the category.

LINQ Useful Links

The Language-Integrated Query (LINQ) covers a set of features that lets you retrieve information from a data source. In many cases, data is stored in a database that is separate from the application. Traditionally, interacting with a relational database would involve generating queries using SQL. Other sources of data, such as XML, would require their own approaches that were completely different. However, LINQ gives C# the ability to generate queries for any LINQ-compatible data source. Furthermore, the syntax used for the query is the same, no matter what data source is used.

The following links are useful to learn the LINQ programing model:

1-      LINQ Official Website

http://msdn.microsoft.com/en-us/netframework/aa904594

2-      LINQ to Everything by Charlie Calvert

http://blogs.msdn.com/b/charlie/archive/2008/02/28/link-to-everything-a-list-of-linq-providers.aspx

3-      Joining LINQ to SQL and LINQ to Excel by Eric White

http://blogs.msdn.com/b/ericwhite/archive/2008/12/04/joining-linq-to-sql-and-linq-to-excel.aspx

4-      Building a LINQ Provider by Pedram Rezaei

http://msdn.microsoft.com/en-us/vcsharp/ee672195.aspx

5-      Dynamic LINQ by Scott Guthrie

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

6-      101 LINQ Samples

http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

7-      LINQ to Facebook

http://www.codeproject.com/KB/aspnet/LinqToFqlAddon.aspx

From C# Learners

8-      LINQ

https://csharplearners.com/category/linq/

More » «LINQ Useful Links»

LINQ and C#

Challenge 
Almost every application uses data in some form, whether the data comes from in memory, databases, XML files, or text files. Many developers find it difficult to switch from strongly typed object-oriented programming to the data access tier in an application. In C#, developers can navigate easily through the namespaces, work with a debugger in the Visual Studio IDE, and more. However, when accessing data, you will notice that things are quite different and more tedious. Developers end up in a world that is not strongly typed, where debugging is a pain or even non existent, and lots of time is spent sending strings to the database as commands. The goal for LINQ was to provide a methodology that simplifies and unifies the implementation of accessing any kind of data. It makes it easier to interact with SQL, relational databases, XML, and the programming languages that communicate with them. LINQ does not force you to use a specific architecture, but facilitates the implementation of several existing architectures for accessing data. Some examples include RAD/prototype, Client/server, N-tier, and Smart client.

Solution 
LINQ stands for Language-Integrated Query and covers a set of features that lets you retrieve information from a data source. In many cases, data is stored in a database that is separate from the application. Traditionally, interacting with a relational database would involve generating queries using SQL (Structured Query Language). Other sources of data, such as XML, would require their own approaches that were completely different. However, LINQ gives C# the ability to generate queries for any LINQ-compatible data source. Furthermore, the syntax used for the query is the same, no matter what data source is used. Accessing a relational database is the same as data stored in an array, and the query capability is fully integrated into the C# language. LINQ in C# is essentially a language within a language and as a result, the subject of LINQ is quite large, involving many features, options, and alternatives. It contains set of standard query operators that provide the underlying query architecture for the navigation, filtering, and execution operations of nearly every kind of data source. LINQ also provides the means for developers to stay within the coding environment that they comfortable with and access the underlying data as objects that work with the IDE, IntelliSense, and even debugging. These aspects, combined with shorter, more meaningful, and expressive syntax boosts developer productivity.

Benefit
LINQ is a lightweight disguise over programmatic data integration. It hardly matters what you are querying against, because queries will be quite similar using a whole new set of procedures and keywords. It gives developers a simplified way to write queries by using a unified query syntax to use regardless of the source of data. It promotes faster development time by removing run-time errors and catching errors at compile time. LINQ is fully integrated with IntelliSense, and supports debugging directly in the development language. Using LINQ, you can query directly against your database and even against the stored procedures that your database exposes. The result of making these set operations, transforms, and constructs first-class operations is a set of methods called the standard query operators. These operators provide query capabilities that include sorting, filtering, aggregation, and projection over a large number of different data sources. LINQ-compatible data sources include LINQ to Objects, LINQ to ADO.NET, LINQ to SQL, LINQ to XML, LINQ to DataSet, and LINQ to Entities. By being able to use LINQ to Objects, C# arrays and collections are treated like databases. This gives developers extensive flexibility and an easy way to query data in the collections. LINQ can be extended to support other data sources such as LINQ to SharePoint, LINQ to Exchange, and LINQ to LDAP. By using LINQ, developers can now enjoy the benefits of a single declarative pattern that can be expressed in any .NET-based programming language, and closes the gap between relational data and object-oriented development.

C# and Auto-Compiled LINQ Queries

The recently released Microsoft Entity Framework (EF) June 2011 CTP includes support for Auto-Compiled LINQ Queries. This allows every LINQ to Entities query to be automatically executed when compiled and placed in the EF query cache. Every time you run the query subsequently, the EF will find it in its query cache and won’t have to go through the whole compilation process again. This feature also provides a boost to queries issued using WCF Data Services, as it uses LINQ in the background.

How does it Work?

The EF will pass the nodes in the expression tree and create a hash, and become the keys used in the query cache. If it does not find the query in the cache then it will go ahead and compile it and store the compiled query in the cache for subsequent use. Each subsequent time, the hash will be calculated and find the compiled query in the tree, thus saving the compilation overhead.

Which performs faster: when the “Auto-Compiled LINQ Queries” is used or when the CompiledQuery is invoked?

The size and complexity of the application and queries will greatly influence its performance boost. By running a regular query 10 times using auto-compiled mode and 10 times where the compilation is turned off, the total time measured by Visual Studio’s profiling tools for the compiled queries is about 3 times faster than the non-compiled one.

In general, auto-compiled queries are not as fast as invoking a CompiledQuery. What we discussed here is that the new released CTP provides the performance savings for free.

Copyright © All Rights Reserved - C# Learners