Building Interactive Queries with LINQPad

By Sébastien Finot
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies

About this book

If you need to interact with databases, XML, in-memory collections, or remote services, LINQ can make your life simpler. The best way to discover LINQ is with the help of LINQPad, a free IDE whose first goal is to make sure that writing and interacting with your LINQ query is fun and easy. More generally, LINQPad is a C#/VB/F# scratchpad that instantly executes any expression, statement block, or program with rich output formatting and a wealth of features.

With Building Interactive Queries with LINQPad, you will quickly learn everything you need to know to start using LINQ. To accelerate your learning curve, you will discover how to use LINQPad and its features to test your queries interactively and experiment with all the options offered by LINQ.

In all probability, you already know C#, but have you had a chance to try out LINQ? Building Interactive Queries with LINQPad will introduce you to everything LINQ can offer and will let you interact with every example in LINQPad, LINQ’s best companion.

You will learn how to build and experiment with interactive queries with this practical guide illustrated with short and detailed code samples. You will also get acquainted with other cool applications of LINQpad such as testing, code snippet generation, and so on, along with a broad approach to LINQ (to object, to SQL, to XML, and so on).

Publication date:
July 2013
Publisher
Packt
Pages
126
ISBN
9781782178224

 

Chapter 1. Discovering LINQPad

LINQPad is a free IDE (Integrated Development Environment) that allows you to create programs and query databases. You might already be using software such as Microsoft Visual Studio or Microsoft SQL Management Studio. As such, LINQPad does not replace them (even if you could for some scenarios). Instead, it complements them as a handy tool. As its name suggests, LINQPad's main purpose is to write and run LINQ queries, but it can also execute C# or VB scripts directly from its editor.

In this chapter we will cover the following topics:

  • Download and install LINQPad

  • Discover LINQPad interface

  • Learn how to configure LINQPad

 

Downloading and installing LINQPad


To download LINQPad, go to http://www.linqpad.net in your browser and click on the big download button in the upper-right corner.

Once the setup file has been downloaded, execute it and proceed with the installation, which is pretty straightforward. Unless you have custom preferences, you can leave the default options of the installer.

You can also download other versions of LINQPad. For example, you can find a 64-bit version available (which is especially useful with queries that require more than 3 Gb memory) or the next beta version that might have a feature or a fix that you need.

Editions available

While most of LINQPad is free, you can buy either a Pro or Premium edition. These two editions are exactly the same as the free one, except with more options. For example, the Pro version will set the editor closer to what you might know in Visual Studio by adding autocompletion and tooltips information. The Premium edition will also add cross-database querying, full NuGet integration (http://nuget.org), and direct SQL database editing. You can find more details on licensing and versions on the LINQPad website.

 

Look and feel of LINQPad


You can now start LINQPad. This is how the startup screen looks:

The upper-left window is the connection window. Here you will create and manage your connections to your databases or other data sources, such as OData. We will start using it in Chapter 5, Databases and Relational Data.

On the lower-left are the queries and samples pane. Using this pane, you will be able to access your saved queries quickly.

The upper-right is the code editor. It is not as evolved as Visual Studio, but it has a lot of great features.

In the lower-right corner, which is not visible right now, is the result pane.

The top menus feature many commands and options. Some of them are pretty standard or self-explanatory, so we'll focus on the specific or important ones.

The File menu

The file menu's main purpose is to handle LINQPad-related files (with a .linq extension). The following screenshot shows us the menu in a expanded view:

The following table gives a detailed description of the individual menu items along with the shortcut keys:

Menu Item

Shortcut Key

Description

New Query

Ctrl + N

Creates a new LINQPad query

New Query, same properties

Ctrl + Shift + N

Creates a new query, by using the same properties as the current one. This is especially useful if you have set up a database connection or imported custom assemblies. Here is the full list of the copied properties:

  • Language and query type

  • References

  • Namespaces

  • Database connection

  • The way results are displayed

Clone Query

Ctrl + Shift + C

Same as New Query, same properties, but the query code will also be copied over. If you have text selected when executing this command, only the selection will be copied.

Open

Ctrl + O

Opens a .linq or .sql query file. Note that you can also force LINQPad to open any kind of text-based file by selecting All files (*.*) in the dropdown of the open file dialog. Only a few formats (such as XML-related files) will be properly parsed by LINQPad.

Upload to Instant Share

Ctrl + Shift + U

This allows you to share a query file with someone really easily through the LINQPad sharing website.

Password Manager

 

The password manager allows you to use passwords, without needing to hardcode them into the query. To retrieve a stored password, you just need to call Util.GetPassword ("my password name") in your query. Passwords stored with the password manager are encrypted and saved in a location relative to your profile.

Tablet Mode

 

If you are using a touch-enabled device, the tablet mode will make the interface more usable. Mainly, buttons will be bigger and margins wider so that touching the right target will be easier.

The Edit menu

The edit menu handles standard text operations such as copy and paste, and also all of the autocompletion features. The following screenshot shows us the menu in a expanded view:

A detailed description of the individual menu items, along with the shortcut keys, is covered in the following table:

Menu Item

Shortcut Key

Description

Copy without formatting

Alt + Shift + C

If you try to paste text that you have copied or cut into a rich text editor, such as Microsoft Word, you will also get the text style (font, color, size, and so on). If you need just the raw text, without formatting, use this option.

Copy for Markdown/StackOverflow

Ctrl + Shift + M

Markdown is a markup language, used on www.stackoverflow.com (the best technical website to find answers and share knowledge in my opinion). So if you are asking or answering a question and need to paste formatted code, you can copy it from LINQPad using this command, and paste it as it is.

Paste as Escaped String

Alt + Shift + V

If you have a string that needs escaping, and you don't want to lose time doing it by hand, use this option. It will escape backslash and double quote characters, add opening and closing double quotes, and format it on a 90 characters per line basis.

Find and Replace…

Ctrl + F

Open the find and replace dialog to search for a specific string, and replace it with another one as shown in the following screenshot:.

Here is a short explanation of two specific features:

  • Use Regular expressions: use a regular expression either for the search or the replacement string.

  • Use wildcards: You can use wildcards to enhance your search. Here are wildcards and their value:

    • *: This will match any one or more character

    • ?: This will match a single character

    • #: This represents any digit (0 to 9)

    • []: This matches any one character in the set. For example, [abc] will match every a, b, and c characters.

    • [!]: This matches any one character not in the set. For example, [!abc] will match every characters except a, b, or c.

Incremental Search

Ctrl + I

It is really useful for simple search. Hit Ctrl + I, the cursor changes to a goggle with a down arrow. Start typing your search and while you add characters the search will refine. To get the next result, hit Ctrl + I again, and use Ctrl + Shift + I to get the previous result. By using backspace, you can correct a typo in the search.

Navigate to Query

 

This will open the Navigate To Query dialog. Following are the options:

  • Search Terms: This will search into your saved queries for the search terms. Note that only simple terms can be used for the search (no regular expressions, no wildcards).

  • Result: This displays all of the saved queries that match your search. By double-clicking on a query you will open it in LINQPad.

  • Search My Queries: This include your queries in the search.

  • Search Samples: This include LINQPad's samples in the search.

  • Search Query Text: It also looks into the query text, and not only the filename.

Note that if you don't check either Search My Queries or Search Samples you won't get any result.

Search All Queries / Samples

Ctrl + Shift + F

Opens the Search All Queries & Samples dialog, which gives you more options than the Navigate To Query dialog to find the query you are looking for.

Outlining | Toggle Outlining Expansion

Ctrl + M, M

Collapses or expands a section of code. A wide range of elements can be collapsed: class declaration, properties, methods, multiline comments, and so on. In the following example, the constructor and the Bar method are collapsed. You will need at least a Pro version of LINQPad to use this feature.

Most of these keyboards shortcuts also work in Visual Studio.

Outlining | Toggle All Outlining

Ctrl + M, L

This command expands or collapses all sections of code. It requires the Pro version at least.

Autocompletion | Complete Word

Ctrl + Space

Automatically complete what you are typing with the selection of the members list. Require Pro version at least.

Autocompletion | List Members

Ctrl + K, L

List possible members based on the current context. This is especially useful if you closed the list while typing and need to reopen it. Requires the Pro version at least.

Autocompletion | List Just Tables and Enumerate Objects

Ctrl + T

Shows the Members List, but filtered to only show database tables and collections. Requires the Pro version at least.

Autocompletion | Parameter Info

Shift + Ctrl + Space

Shows the yellow tooltip that lists the current method's signatures. Requires the Pro version at least.

Autocompletion | Insert Snippet…

Ctrl + K, X

Insert one of the existing snippets. LINQPad supports existing Visual Studio snippets too. Requires the Premium version.

Autocompletion | Surround With…

Ctrl + K, S

Quickly surround the selection with one of the many code blocks, such as a region, a loop, a condition, and so on. Requires the Pro version at least.

Execute shell command

Ctrl + Shift + X

Insert in your query a call to Util.Cmd() that allows you to run any command like you were in a command-line Prompt.

The Query menu

The query menu deals with everything related to the current query. The following screenshot shows us the menu in expanded view:

A detailed description of the individual menu items, along with the shortcut keys, is covered in the following table:

Menu Item

Shortcut Key

Description

Execute

F5

Executes the current query.

Cancel

Shift + F5

Cancels the running query. This option is available only when a query is running.

Cancel All Threads and Reset

Ctrl + Shift + F5

Use this option to cancel a running query that started new threads. Note that it will also recycle the application domain.

Show Results

Ctrl + R

Displays or hides the result pane.

Undock Results into Second Monitor

F8

If you have a second monitor and want to use it to keep a bigger result window, this is the way to do it.

Arrange Results Panel Vertically

Ctrl + F8

Toggles between arranging the result pane horizontally and vertically.

Results to Rich Text

Ctrl + Shift + T

Displays the results of your query as rich text, meaning that you will get a nicer presentation, object hierarchy, collapsible results, and so on.

Results to Data Grids

Ctrl + Shift + G

Displays the results of your query in a data grid. This can prove useful when you are querying table-based objects, or if a query returns more than 1,000 rows, as data grids are only limited by available memory.

Auto Scroll Results to End

Ctrl + Shift + E

If you are outputting a lot of text (maybe as a debug or progression), this option will scroll to the end of the execution, instead of staying at the top of the result pane.

Auto Track Execution

Ctrl + Shift + A

When a query is running, you will notice a yellow arrow next to the line currently executed.

Jump To Execution Point

Ctrl + Shift + J

Moves the cursor to the current executed line of code.

Trigger Garbage Collection

Alt + Shift + G

Forces the .NET garbage collector to run immediately. This can be useful in some specific scenarios (for example, when you want to force finalizers to run).

The Help menu

The help menu provides a good list of information, resources, forums, and the link to upgrade to a paid version of LINQPad. The following table describes the options present in the help menu:

Menu Item

Shortcut Key

Description

Help on Current Type / Member

F1

Launches a Google search on the type or member your cursor is on.

Reflect on Current Type/Member

Shift + F1

Launches Red Gate Reflector (if installed) on the type or member your cursor is on.

 

Configuring LINQPad


The default configuration of LINQPad is quite good and we won't need any alteration of its default for the examples of this book, but feel free to change it to match your needs or taste.

Open the Edit menu, and then choose Preferences, as shown in the following screenshot:

The Editor tab

Here you can customize the visual appearance of LINQPad, such as the font, the background color, or display line numbers in the editor.

The Query tab

In this tab, you can set up the default query language you would like LINQPad to start with. For example, if you're like me, you realize at some point that the first thing you do is change the query type when you start a new query. It's time to change your default. You can also change the compiler's optimization options.

The Results tab

The results tab allows you to change the default display of the result windows, and customize the font and colors (using CSS) of the rich text display. Also, you can set a default for DateTime formatting, and increase or decrease the maximum number or rows returned in a single query (a lower number will produce faster results).

The Folders tab

LINQPad stores your queries, snippets, and plugins in the My Document folder, inside separate subfolders, each prefixed with LINQPad. You can change this default behavior on the Folders tab. Note that when you change one of those folders, LINQPad does not copy or move the previous folder content.

The Web proxy tab

If you are using a proxy to connect to the Internet, this is the place to set it up.

The Advanced tab

The advanced tab holds specific settings, with a detailed description for every one of them. For example, you can define tab sizes (and if they need to be converted to spaces), enable MARS (Multiple Active Results Sets, see http://msdn.microsoft.com/en-us/library/h32h3abf(v=vs.80).aspx for more information on this feature) for database connections, or limit the column width of the result pane.

 

Summary


In this chapter, you have learned all of the basics to use LINQPad: how to set it up and how to configure it. You also discovered its menus and options. In the next chapter we are going to start using it by typing some code, see how you can use it to test your code, and see what useful feature it adds to your workflow.

About the Author

  • Sébastien Finot

    Fascinated by computer science on the whole (but with a specific dedication to application development and games), Sébastien Finot has been working for more than 15 years for small and big worldwide companies at various technical positions, ranging from developer to technical project manager or, for the last five years, as the CTO of communication agencies. He is also pursuing an entrepreneurial path with his own company (in France), where he can work on fun and innovative projects. Sébastien has been using LINQ for five years now, and has been a LINQPad user for almost as long.

    Sébastien can be reached using any of the means listed on this website: http://about.me/sebastienf.

    Browse publications by this author
Book Title
Unlock this book and the full library for FREE
Start free trial