A. Tips for Developers

Accessing the Source Code

Most of the source code shown in this book is drawn from sample programs that are available for download. The sample programs are stored in a zip file that you can download and decompress to a directory where you have rights to compile and run programs. If you are uncertain where to place the files you download, we recommend putting them in your Documents directory.

Most of the chapters in this book have source code associated with them. The code is divided by chapter. For example, all the programs associated with Chapter 2, “Getting Started,” are in a directory called Chapter02. Many of the individual programs containing the source are mentioned by name in the text. You might also find it helpful to run each of the sample programs to become familiar with the contents, or to use the Windows built-in search facilities to find sample programs that cover a particular feature. For instance, after downloading the source, you might type a few words from the book’s source code into Windows Search. The search facility could then take you directly to the program that contains that code.

You can access the source code from the following URL:

www.informit.com/register

Go to this URL, sign in, and enter the ISBN. After you register the product, a link to the source content will be listed on your Account page, under Registered Products.

Northwind and the Visual Studio Samples

The sample programs just mentioned are the primary reference code for this book. However, you might find other samples useful.

The C# team created a series of LINQ samples that ship with Visual Studio 2008. To access these samples, choose Help, Samples from Visual Studio. From the samples link, you will find instructions to access a local copy of the samples and to download a copy from the Web. The samples come in a zip file. You should decompress the contents of this file to a directory over which you have complete control. For instance, you might place it in your Documents or My Documents directory. The projects included with the samples contain Visual Studio solution files that can be opened and run by selecting the F5 key, or by choosing Start Debugging from the Visual Studio Debug menu.

Dinesh helped oversee the creation and development of the samples, and Charlie drove the actual release of the samples. As a result, you should find that many of the samples that ship with Visual Studio make an excellent companion to the material found in this book. In particular, you should explore the excellent SampleQueries project, which contains more than 500 examples of how to write LINQ queries. The SampleQueries project was originally developed by C# Compiler PM Alex Turner, and the code in that sample has been reviewed by many developers on the C# development and documentation team. Other important projects, such as the ObjectDumper sample, are included in this group of samples.

The C# Visual Studio samples ship with all copies of Visual Studio 2008 except for the Express version. Updated copies of the samples are also available online. Because the online versions have been updated, they are the preferred versions of the samples. However, most of the changes in the online version are minor, and you will find the versions that ship with Visual Studio to be very useful.

Included with the samples is a custom version of the Northwind database. This database is used by both the C# team’s samples and the LINQ to SQL samples used in this book.

You can download the C# team’s samples from Code Gallery at http://code.msdn.microsoft.com/csharpsamples.

The copy of the Northwind database that is included with the C# samples has extra data and metadata designed to illustrate some of the features of LINQ. Because there are some 50 LINQ operators, it was not possible to illustrate them all using the standard release of Northwind. Therefore, the database was modified slightly to allow Alex and other team members to write queries that illustrated how to use all the LINQ operators.

You should be able to download the original, unmodified version of Northwind from either of these URLs:

http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46A0-8DA2-EEBC53A68034&displaylang=en

http://tinyurl.com/yzx6lz

Version Numbers

The version numbers of the releases of the .NET Framework and C# that have appeared in recent years are somewhat confusing. The following list can help you disambiguate these version numbers:

• Visual Studio 2005 includes C# 2.0 and the .NET Framework 2.0.

• The release of Windows Vista was accompanied by .NET Framework 3.0.

• Visual Studio 2008 includes C# 3.0 and .NET Framework 3.5.

Essential Downloads

Everyone who reads this book should have several essential programs installed on this system. Without these programs you will not be able to run some or all of the sample programs described in this text.

Installing Visual Studio Express

If you do not already have a copy of Visual Studio installed, you can download a free copy of the Express version from Microsoft’s web site. All the programs in this text can be compiled with Visual Studio Express. Most of the sample programs used in the book were developed with Visual Studio Express for C#. You can download this product here:

http://www.microsoft.com/express/

Installing the .NET Framework

If you have Visual Studio on your system, the .NET Framework will have been installed automatically. The .NET Framework includes all the tools and libraries needed to compile the programs found in this book.

The Framework is free. The current version of the Framework is 3.5, Service Pack 1. Most of the code in this book was developed against the .NET Framework Version 3.5 and tested with Service Pack 1. Thus, you should be able to run the samples against 3.5 or 3.5 Service Pack 1. The .NET Framework Version 4.0 will ship at the same time as the next version of Visual Studio, and it and other, future versions of the Framework can also be used to compile all the programs in this book. Early versions of the Framework are not LINQ-aware and cannot be used to compile most of the programs shown in this text.

Here is the home page for the .NET Framework:

http://msdn.microsoft.com/en-us/netframework/default.aspx

On this page you can find links to the current and previous versions of the .NET Framework..

By default, the .NET Framework is installed into your Windows directory:

C:WindowsMicrosoft.NETFrameworkv3.5

At the command prompt, you can type the following to move to your Windows directory:

cd %windir%

You should then be able to change into the .NET Framework directory by typing this:

cd Microsoft.NETFramework

From there, you can type DIR to see the list of installed frameworks, or type cd v3.5 to enter the .NET Framework 3.5 directory.

Although I don’t recommend it, you can compile the samples discussed in this book from the command line. The compiler is called CSC.exe and it is found in that directory. MSBuild.exe, and the other tools you need to develop LINQ applications, are also available in the v3.5 directory. As a result, if you want to compile from the command line, you need to either work from inside that directory or ensure that the directory is on your path.

Visual Studio makes it much easier for you to develop the programs found in this book, and I strongly recommend that you use it unless you have some specific reason for avoiding it. However, all the code and sample programs shown in this book can be developed and run from the command line using the .NET Framework. The steps for compiling a LINQ program from the command line will be outlined later in the section “Compiling from the Command Line” of this appendix. Please note that you can use the tool called SqlMetal.exe instead of the Object Relational Designer.

Installing SQL Server Express

Database technology plays a key role in this book, primarily in Chapters 7 through 10. Microsoft ships a free database called SQL Server Express. Although it isn’t designed for deployment as part of an enterprise database application, SQL Server Express nevertheless supports the APIs and functionality found in the full version of Microsoft SQL Server. It provides a good test platform for you to run LINQ queries against while you are learning about LINQ or other database APIs. All the queries you write should work unchanged in the regular version of Microsoft SQL Server if you decide to upgrade to that product. You can find links to download the free SQL Server Express from the Express home page:

http://www.microsoft.com/express/

Compiling C# Programs

The simplest way to compile and run a C# program is from inside Visual Studio. All the programs in this book will compile with the free version of Visual Studio called Visual Studio Express. I developed almost all the sample programs for this book using Express. As mentioned previously, you can download this small, light version of Visual Studio from this URL:

http://www.microsoft.com/Express/

You can build two primary types of programs in Visual Studio. The first is a console application that displays output at the command line, and the second is a Windows Forms application that runs inside the Windows GUI. Most of the programs in this book are command-line applications, but I’ve rewritten some as Windows Forms applications because that format offers a simpler way to help you sort out a large number of small samples.

To create a console application in Visual Studio, follow these steps:

1. Choose File, New Project. The dialog shown in Figure A.1 appears.

Figure A.1. The New Project dialog in Visual Studio Express.

image

Click OK to select the default name and location for the project.

After you complete these two steps, the Visual Studio editor should open with the following code visible and ready to edit:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

You can start typing code directly into the Main method:

static void Main(string[] args)
{
    var list = new List<int> { 1, 2, 3 };

    var query = from n in list
                select n;

    foreach (var item in query)
    {
        Console.WriteLine(item);
    }
}

To run the program, select Debug, Start Without Debugging. The default key binding for this command is Ctrl-F5. You can also run a program by choosing Debug, Start Debugging. The key binding for this command is F5. When working with console applications, I prefer the first of these two options because it leaves the console window open so that you can view the results of your work.

You can create a Windows Forms application in Visual Studio by choosing File, New Project and selecting Windows Forms Application. Choose View, Toolbox from Visual Studio. From the Common Controls section of the Toolbox, drag a Button and TextBox onto the main form for your project, as shown in Figure A.2.

Figure A.2. Creating a simple Windows Forms application.

image

Double-click the Button to create an event handler where you can write your code:

private void button1_Click(object sender, EventArgs e)
{
    var list = new List<int> { 1, 2, 3};

    var query = from n in list
                where n % 2 == 0
                select n;

    textBox1.Text = query.Single().ToString();
}

If you want to display multiple items in the form, drop down a ListBox rather than a TextBox. Click the Button to create a method, just as you did before, but this time write code that looks like this:

private void button1_Click(object sender, EventArgs e)
{
    var list = new List<int> { 1, 2, 3};


    var query = from n in list
                select n;

    foreach (var item in query)
    {
        listBox1.Items.Add(item.ToString());
    }
}

Compiling from the Command Line

If you use Visual Studio as your development environment, you will rarely encounter difficulties compiling and running simple programs of the type covered in this book. Because the Express version of Visual Studio is both free and an excellent, high-quality development tool, most people can use it or other versions of Visual Studio to work with the programs in this book. However, sometimes you might need to compile from the command line. The next few paragraphs outline some examples demonstrating how to proceed.

To compile LINQ programs from the command line, you need a copy of the .NET Framework 3.5 or greater installed on your system. The Framework is installed automatically if you install Visual Studio. You can also download it separately, as explained earlier.

Here is a simple batch file for compiling and running a console application called SimpleNumericQuery that consists of a single source file called Program.cs:

PATH=%PATH%;%windir%Microsoft.NETFrameworkv3.5
csc.exe /out:SimpleNumericQuery.exe /target:exe Program.cs
SimpleNumericQuery.exe

This code is designed to be run from the command prompt. You can launch the Windows command prompt by clicking the Vista Start button and typing CMD. This launches a command window where you can enter the code for compiling your program.

The first line of this batch file sets up the path. The second line compiles the program, and the third runs the program.

Here is how to compile a Windows Forms application:

PATH=%PATH%;%windir%Microsoft.NETFrameworkv3.5
csc.exe /out:MyProg.exe /target:exe Program.cs Form1.cs Form1.Designer.cs
MyProg.exe

You can learn more about the command-line compiler by opening a command prompt, setting the path as shown in the sample batch files in this section of the text, and typing the following:

csc /?

There are advanced tools for compiling C# applications from the command line. These include the MSBuild.exe program that ships with the .NET Framework and the open-source NANT project available from http://nant.sourceforge.net/. MSBuild can be very easy to use. For instance, if you create a project in Visual Studio, in many cases you can compile that project from the command line by simply setting up the path and typing MSBuild.exe from the directory where the source for your project is stored.

Connecting to a Database

To learn how to connect to a database, read this post from Charlie’s blog:

http://blogs.msdn.com/charlie/archive/2007/11/19/connect-to-a-sql-database-and-use-the-sql-designer.aspx

I will maintain this post on my blog, but the following is the text in case you don’t have access to online materials.

To begin working with LINQ to SQL in Visual Studio 2008, you need a database that you can query and a copy of Microsoft SQL Server or SQL Express. In this post, I’ll focus on SQL Express because it is free and because it gets installed by default when you install all versions of Visual Studio except for some forms of Visual Studio Express.

Follow these steps to install and access the copy of the Northwind database that accompanies the samples that ship with Visual Studio 2008:

1. From Visual Studio, choose Help, Samples.

2. Follow the directions to install the Visual Studio 2008 C# Samples to a subfolder of your Documents directory. Note that the latest copies of the samples are always available online at http://go.microsoft.com/fwlink/?LinkID=85559.

3. After installation, the Northwnd.mdf database file is found in a directory called CSharpSamplesLinqSamplesData, where CSharpSamples is a subdirectory created when you installed the samples.

Choose File, New Project (or press Ctrl-Shift-N) and create a new console application:

1. In Project types, select Windows, as shown in Figure A.3.

Figure A.3. Creating a new console application.

image

2. In Templates, select Console Application, as shown in Figure A.3.

Create a connection to the Northwind database:

1. Choose View, Server Explorer (or press Ctrl-W, L). In Express editions of Visual Studio, this tool is called Database Explorer.

2. Right-click the Data Connections node, and choose Add Connection. This brings up the Add Connection dialog, shown in Figure A.4.

Figure A.4. Click the Browse button in the Add Connection dialog and locate your copy of Northwnd.mdf.

image

3. In the Add Connection dialog, click the Browse button and navigate to and select your copy of Northwnd.mdf.

4. Click the OK button.

At this stage Northwnd.mdf should appear in your server or Database Explorer, as shown in Figure A.5.

Figure A.5. The Server Explorer provides a view of the Northwind database.

image

Using the Object Relational Designer

The Object Relational Designer, (LINQ to SQL Designer) is explained in some depth in Chapter 8, “Reading Objects with LINQ to SQL,” and it is occasionally referenced in the other chapters on LINQ to SQL. We have also included a short getting started guide in this appendix.

The Object Relational Designer allows you to configure and view the metadata of the database tables you want to query. There is a command-line version of this tool called SqlMetal that is not covered in this document. By default, SqlMetal is part of the Visual Studio and .NET Framework 3.5 install and is stored in %ProgramFiles%Microsoft SDKsWindowsv6.0Ain.

Select Project, Add New Item (or press Ctrl-Shift-A). This command brings up the Add New Item dialog. Select LINQ to SQL Classes from the list of Visual Studio Installed Templates, as shown in Figure A.6.

Figure A.6. Choose the LINQ to SQL Designer from the list of available templates available in the Add New Item dialog.

image

Drag the Customer table from the Server Explorer onto the Designer, as shown in Figure A.7.

Figure A.7. The LINQ to SQL Designer with the Server Explorer on the left and the Solution Explorer on the right.

image

In Figure A.7 the Customer table has been dragged from the Server Explorer onto the SQL Designer. Stored procedures can be dragged onto the area where you see the text that begins “Create methods by dragging items....”

Several things happened as you completed the preceding steps:

1. When you added the SQL Designer to your project, a new node in the Solution Explorer called DataClasses1.dbml was added to your project. As shown in Figure A.7, it contains two files, DataClasses1.dbml.layout and DataClasses1.designer.cs.

2. When you dragged the Customer table onto the designer, an Object Relational Mapping (ORM) was created between the Customer table in the database and a Customer class generated by the SQL Designer. The result of this mapping was the production of a class called Customer that was placed in DataClasses1.designer.cs. This class is called an entity class, and it allows you to access the data and fields of the Customer table.

3. A second class, called a DataContext, was also created in DataClasses1.designer.cs. You can use this class to automatically connect to your database and easily access the data and fields in the Customer table.

4. A file called app.config was added to your project. It contains an automatically generated connection string for your database.

This is not the place to fully explore the O/R Designer and the code it generates. However, the preceding steps give you two key benefits:

• They ensure that you can automatically connect to the database.

• They let you access the Customer table in the database via an object in your program.

After you drag items from the Server Explorer onto the SQL Designer, you can modify the view that your program will have of the data. For instance, you can delete some of the fields from the Customer table, as shown in Figure A.8. This operation modifies the classes generated, not the actual table on the server.

Figure A.8. A modified view of the Customer table with only three fields visible and other fields deleted.

image

You can now test your work by opening Program.cs in the Visual Studio editor and typing in the following code:

using System;
using System.Linq;

namespace ConsoleApplication41
{
    class Program
    {
        static void Main(string[] args)
        {
            DataClasses1DataContext db = new DataClasses1DataContext();

            var query = from c in db.Customers
                        where c.City == "London"
                        select c.City;

            foreach (var q in query)
            {
                Console.WriteLine(q);
            }
        }
    }
}

Summary

In this brief introduction to the Object Relational Designer, you have seen how to

• Download and install the Northwind database from the samples that ship with Visual Studio.

• Access the database through the SQL Designer.

You can learn more about LINQ by running the SampleQueries project that ships with Visual Studio samples referenced in this article.

Important Resources

Here are a few of the most valuable blog posts that have been written about LINQ:

Mocking DataContext for testability

• http://andrewtokeley.net/archive/2008/07/06/mocking-linq-to-sql-datacontext.aspx

• http://blogs.msdn.com/mattwar/archive/2008/05/04/mocks-nix-an-extensible-linq-to-sql-datacontext.aspx

Performance related blog posts:

• http://blogs.msdn.com/ricom/archive/2007/06/22/dlinq-linq-to-sql-performance-part-1.aspx

• http://blogs.msdn.com/ricom/archive/2008/01/14/performance-quiz-13-linq-to-sql-compiled-query-cost-solution.aspx

• http://www.sqlskills.com/BLOGS/BOBB/post/MHO-LINQ-to-SQL-and-Entity-Framework-Panacea-or-evil-incarnate-Part-6.aspx

Entity Framework Mapping Scenarios:

• http://weblogs.asp.net/zeeshanhirani/archive/2008/12/08/my-christmas-present-to-the-entity-framework-community.aspx

Reference Materials: Getting Help

This book is not primarily a reference. Instead, it is meant to explain how LINQ works, the structure of its architecture, and best practices for its use. However, a good reference can help supplement the materials found in this book and can help answer many common questions about LINQ.

The LINQ documentation created by Microsoft is primarily a reference document. It is available both inside Visual Studio and for free via the MSDN library found on the web. Here are some important pages that can help you navigate through the online LINQ documentation:

• The Root MSDN Library Page: http://msdn.microsoft.com/en-us/library/default.aspx

• .NET Development: http://msdn.microsoft.com/en-us/library/aa139615.aspx

.NET Framework 3.5: http://msdn.microsoft.com/en-us/library/w0x726c2.aspx

• System.Linq: http://msdn.microsoft.com/en-us/library/system.linq.aspx

• System.Data.Linq: http://msdn.microsoft.com/en-us/library/system.data.linq.aspx

• System.Xml.Linq: http://msdn.microsoft.com/en-us/library/system.xml.linq.aspx

• Code generation: http://msdn.microsoft.com/en-us/library/bb399400.aspx

• More on joins: http://msdn.microsoft.com/en-us/library/bb311040.aspx

• For more information on the operators, see the section of the online help called “The .NET Standard Query Operators.” It was written by Anders Hejlsberg and Mads Torgersen. The URL is http://msdn.microsoft.com/en-us/library/bb394939.aspx.

I do not suggest using these references materials as a primary means of learning LINQ. However, these pages can be a useful addendum to this text. If you understand in a general way how LINQ works, but you need answers to detailed questions, the links provided here may sometimes help you find answers.

Finding LINQ Providers

I maintain a list of links to LINQ providers on my blog. Here is the address of the relevant article:

http://blogs.msdn.com/charlie/archive/2006/10/05/Links-to-LINQ.aspx

Including Data Files in Your Project

When you’re working in Visual Studio, defining the path to a document can be a chore. You face two primary problems:

The path to your project may be long and complex.

• Projects can easily be moved from one location to another, which causes the path to change.

Both of these problems can be solved easily when you are working inside the IDE. If you are working with an XML file that you want your program to load, do these three things:

1. Place the file in the directory where your main project file resides.

2. Add the file to your project.

3. Set the Copy to Output Directory property of your XML file to Copy if Newer.

This ensures that the XML file is in the same directory as the project executable. Hence, it can be loaded directly into the project without your having to consider the path to the file: doc.Load(“MyFile.xml”);

C# Keywords and Contextual Keywords

C# has a wide variety of keywords and contextual keywords. Keywords are reserved words and may not be used by developers as variable names. Contextual keywords are reserved words in certain circumstances but may be used as variable names.

Consider the contextual keyword var. If it’s used to designate that type inference should be used as part of a type definition, it is a keyword:

var myInteger = 3;

It is the context in which this word is used that makes var a reserved word in this case. If it’s used in a different context, it is not a keyword. For instance, here var is simply a variable name:

int var = 3;

The C# team developed this policy because they did not want to break existing code. They knew that some developers might have used var as a variable name, and they did not want to force them to modify their code. Instead, they developed contextual keywords so that they could add new features to the language without breaking existing code.

Most LINQ keywords are contextual, because they were added to the language in version 3.0, after C# had been out for several years. The following are the existing C# keywords and contextual keywords as of C# 3.0.

C# Keywords

image

Contextual Keywords

image

Visual C# 2008 Key Bindings

The developers of Visual Studio put a considerable amount of effort into defining a set of key bindings that can make it easy to navigate through the component parts of a C# project. Table A.1 is an overview of the default key bindings for C# developers.

The C# Express edition of Visual Studio has only one possible set of key bindings; it corresponds to the settings shown in Table A.1. Other versions of Visual Studio, however, have multiple key bindings available, including those for C# developers, VB developers, general developers, Team Test developers, and web developers. Here is how to change the settings so that the key bindings are set to the default values for C# developers:

1. Select Tools, Import and Export Settings.

2. Choose Reset All Settings, and click Next.

3. You can optionally save your current settings or select to overwrite your existing settings. Click Next.

4. Select the Visual C# Development Settings, and click Finish.

The items shown in Table A.1 are broken into different categories. For instance, the first items are part of the Edit category, the File category is second, and so on.

Table A.1. The Visual C# Key Bindings

image

image

image

image

image

 

Answers to Chapter 4 Exercises

Here are the answers to the exercises found in Chapter 4, “C# 3.0 Technical Overview.” The exercises are found in the section “Generic Methods, Delegates, and Lambdas”—more specifically, in the subsection “Lambdas.”

1. Action<string> display = (a) => Console.WriteLine(a);

2. Func<int, int> multiply = (a) => (a * 5);

3. Action displayWarning = () => Console.WriteLine("Warning");

4. Func<int, int, int, decimal> calculate = (a, b, c) => (a + b) / c

5. Func<int, int, long> add = (a, b) => ((long)a + b);

6. Func<int, int, long> add = (a, b) => ((long)a + b);

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public static void Display(string value)
        {
            Console.WriteLine(value);
        }

        public static int Multiply(int a)
        {
            return a * 5;
        }

        public static void DisplayWarning()
        {
            Console.WriteLine("Warning");
        }

        public static decimal Calculate(int a, int b, int c)
        {
            return (a + b) / c;
        }

        public static long Add(int a, int b)
        {
            return a + (long)b;
        }

        public static string ShowMe(string a, int b, int c)
        {
            return string.Format(a, b, c, (b + c));
        }

        static void Main(string[] args)
        {
            Action<string> display = (a) => Console.WriteLine(a);

            Display("Some Text");
            display("Some text");

            Func<intint> multiply = (a) => (a * 5);

            Console.WriteLine(Multiply(3));
            Console.WriteLine(multiply(3));

            Action displayWarning = () => Console.WriteLine("Warning");

            DisplayWarning();
            displayWarning();

            Func<intintintdecimal> calculate =
               (a, b, c) => (a + b) / c;

            Console.WriteLine(Calculate(5, 4, 3));
            Console.WriteLine(calculate(5, 4, 3));

            Func<intintlong> add = (a, b) => ((long)a + b);


            Console.WriteLine(Add(Int32.MaxValue, Int32.MaxValue));
            Console.WriteLine(add(Int32.MaxValue, Int32.MaxValue));

            Func<stringintintstring> showMe =
                (a, b, c) => string.Format(a, b, c, (b + c));

            Console.WriteLine(ShowMe("{0} + {1} = {2}", 3, 5));
            Console.WriteLine(showMe("{0} + {1} = {2}", 3, 5));

        }
    }
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset