Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Professional Visual Studio 2005 (2006) [eng]

.pdf
Скачиваний:
132
Добавлен:
16.08.2013
Размер:
21.9 Mб
Скачать

Chapter 38

If you want to change to a different query, you can do so with the “Select an object to preview” dropdown list. If the query you’re previewing requires parameters, you can set their values in the Parameters list in the top-right pane of the dialog.

Database Projects

If you’re just creating a database and don’t require any other type of project, Visual Studio 2005 has a Database Project template you can use to define a simple SQL Server 2005 database project. This offers the additional benefit of being able to create stored procedures and functions in either Visual Basic or C#, rather than in straight SQL form.

Script-Based Database Projects

You can create script-based SQL Server 2005 projects via the Other Project Types Database Project Template group in the New Project dialog. When you define this type of project, you still define your queries and scripts in standard SQL language and use the various data designers discussed throughout this chapter to create tables, views, and stored procedures.

You can add scripts to programmatically create your database tables by right-clicking the table you need in the Server Explorer and choosing Generate Create Script from the context menu. Doing so creates the script, stores it in the database, and then adds it to the Solution Explorer (see Figure 38-24).

Figure 38-24

The Generate Create Script option is only available for script-based project types.

Everything else you do in the database project is saved in database query files and SQL definitions.

When you make changes to a table layout after generating the create script, you should generate a change script to programmatically update the database definition in the SQL Server database. The easiest way to do this is to make the changes to the table in the table designer, right-click anywhere in the designer, and choose the Generate Change Script command from the context menu.

At this point, you’re given the option to save the script to a text file as well as to the database.

526

Visual Database Tools

Even here, Visual Studio provides you with additional aid by including a set of item templates specific to script-based database projects. This ranges from an SQL script file stub to a database query or stored procedure (see Figure 38-25).

Figure 38-25

Managed Code Language-Based Database Projects

Managed code database projects are found in their respective language groups in the New Project dialog. Rather than being script-based, your functions and stored procedures are defined in managed code (either Visual Basic or C#) and can be debugged with the CLR debugger (discussed in Chapter 52).

When you add items to this kind of database project, Visual Studio presents you with a combination of database-specific templates such as Stored Procedure and User-Defined Function, and regular code files, including class and module definitions.

The following listing shows a sample managed code stored procedure written in Visual Basic. The Microsoft.SqlServer.Server.SqlProcedure attribute is prefixed to the subroutine’s definition to identify it as a stored procedure to the build process, but internally the routine appears as normal managed code:

<Microsoft.SqlServer.Server.SqlProcedure()> _

Public Shared Sub PriceSum(<Runtime.InteropServices.Out()> ByRef value As SqlInt32) Using connection As New SqlConnection(“context connection=true”)

value = 0 connection.Open()

Dim command As New SqlCommand(“SELECT Price FROM Products”, connection) Dim reader As SqlDataReader

reader = command.ExecuteReader()

Using reader

While reader.Read()

value += reader.GetSqlInt32(0) End While

End Using End Using

End Sub

527

Chapter 38

Summar y

With the variety of tools and windows available to you in Visual Studio 2005, you can easily create and maintain databases without having to leave the IDE. You can manipulate data as well as define database schema visually using the Properties tool window in conjunction with the Schema Designer view.

Once you have your data where you want it, Visual Studio keeps helping you by providing a set of drag- and-drop components that can be bound to a Data Source. These can be as simple as a checkbox or textbox, or as feature rich as a DataGridView component with complete table views. The ability to drag whole tables or individual fields from the Data Sources window onto the design surface of a form and have Visual Studio automatically create the appropriate controls for you is a major advantage for rapid application development.

Finally, you can use Visual Studio 2005 to create whole database projects in SQL Server 2005 that use managed code for stored procedures and functions. All in all, Visual Studio 2005 brings the ease-of-use factor firmly into the database editing area of development and will be a benefit to all developers.

528

Regular Expressions

Regular expressions are a great way to retrieve a set of matches for complex search criteria, but they’re underused because they can be quite complex and appear almost unintelligible to a lot of developers. With Visual Studio 2005, regular expressions are now not only usable in the normal program code, but also featured in other areas of the environment such as the Find and Replace dialog.

To help more programmers understand how to use them, this chapter introduces regular expressions and shows how they can be used in different situations. It discusses the particular implementation of regular expressions in Visual Studio 2005, along with descriptions of the major components of regular expression syntax so you can begin to build your own expressions confidently regardless of the situation.

At their core, regular expressions are a series of pattern-matching strings that use an extensive set of pattern constructs to control how strings of text can be matched. The character patterns can be used to find and then extract, replace, or remove substrings within large blocks of text, and are used often to extract information from large files with a defined syntax, such as HTML pages or even XML files and header information on e-mails.

Visual Studio 2005 provides an implementation of regular expressions through its use of the .NET Framework’s System.Text.RegularExpressions namespace, which includes several members that can be used in your code to perform the various functions of the regular expression engine using typical programming practices. Note that while the regular expression engine in Visual Studio is extensive, there may be differences between its implementation and that of other languages that use regular expressions, such as PHP or awk. In addition, the regular expressions that can be built in the Find and Replace dialog are a subset of the full set of functionality. Only syntactical elements appropriate in the context of finding and replacing text in files are available.

Chapter 39

Where Can Regular Expressions Be Used?

Using regular expressions can aid you in three primary areas of Visual Studio 2005: normal program code, with full access to the .NET Framework regular expression classes; the Find and Replace dialog, which has a subset of the regular expression syntax but also comes with a regular expression builder to make creating regular expression strings easier; and Visual Studio Tools for Office Smart Tags, which includes an Expressions collection that uses regular expressions to build smart tag search patterns.

Regular Expression Programming

Using regular expressions in program code has been around for a long time, with languages such as Visual Basic 6 able to take advantage of COM components such as MSXML to perform regular expression functionality. The introduction of the first version of Visual Studio .NET included a managed code namespace called System.Text.RegularExpressions that exposed a number of methods and members, most notably the Regex object, which is used to store the actual pattern matching string along with a series of members relating to the string, including any matching results.

A typical use of the namespace in program logic is shown in the following code listing. The code creates a new Regex object containing the pattern TextToMatch. It then uses a Match object to store the first instance of the pattern, which is returned by the Match method exposed by the Regex object. Finally, it determines whether there was a match and then outputs a message to the console, including the position at which the string was found:

Dim myRegex As New Regex(“TextToMatch”)

Dim myMatch As Match = myRegex.Match(“Search string containing TextToMatch”) If myMatch.Success Then

Console.WriteLine(“Found match at position “ & myMatch.Index.ToString()) End If

While this example is simple, it illustrates how the different regular expression objects can be used in familiar programming techniques. Later in this chapter you’ll see a variety of additional techniques you can use with regular expression objects in your code.

Note that this code assumes you have the RegularExpressions namespace explicitly imported into your code. You can do this in your own project with the following line at the top of the module containing the regular expression code:

Imports System.Text.RegularExpressions

Find and Replace

Regular expression matching in the Find and Replace dialog was present in Visual Studio 2003, but the IDE left it up to you to write your own pattern matching strings without giving you any feedback to indicate whether the regular expression was even correctly formatted. With Visual Studio 2005, the implementation of regular expression searching changed to include a regular expression builder that takes away a lot of the guesswork when creating your strings.

Regular expression matching is available in both the Quick Find and Quick Replace functions, as well as the more extensive Find in Files and Replace in Files modes, but it is disabled by default. To use regular

530

Regular Expressions

expression matching in a search or replace action, you’ll first need to activate them by expanding the Find Options section of the Find and Replace dialog. Check the Use option and then select Regular Expressions from the associated drop-down list (which defaults to Wildcards).

Once regular expression matching is enabled, the right-facing triangular buttons next to the Find What and Replace With text boxes enable you to pick from a set of regular expression syntactical elements (see Figure 39-1).

Figure 39-1

Note that these options are only a subset of the pattern constructs you can use in your searches. However, most searches will be possible using the lists in these menus. The regular expression element list available to the replace text is different, containing shortcuts to the tagged expression constructs.

When using a construct that encapsulates a set of characters such as the set constructs, you can either add the regular expression syntax first and then fill it out with the characters, or first add the characters, highlight them, and then add the regular expression, which will automatically wrap the selection you made.

There are minor syntactical differences between regular expression patterns in the Find and Replace dialog compared to the Regex object of the .NET Framework. Mostly these are minor, but there is one significant difference in the way they use the braces construct. Braces ({}) are used in .NET regular expressions to denote multiple instances of the previous search text. For instance, the{2} will find one or two occurrences of the letter e, resulting in a match for thee but not for them. However, in the Find and Replace dialog, braces represent tags instead of multiple instances. To replicate this behavior you would need to specify the(e)^2.

Visual Studio Tools for Office Smart Tags

The other main area for using regular expressions in Visual Studio is in the new Visual Studio Tools for Office 2005 toolkit that integrates Visual Studio 2005 and Microsoft Office 2003 with advanced managed code solutions for Microsoft Excel, Outlook, and Word.

531

Chapter 39

One of the new features of VSTO with the 2005 release of the toolkit is the capability to add documentcentric smart tags that use managed code to perform their recognition and action components. Recognition in VSTO smart tags can be performed by adding strings of text to the Terms collection, which will match the text exactly, including case, or by adding pattern matching strings to the Expressions collection object. While the smart tag object model doesn’t help you create regular expressions, once you’ve figured out the correct pattern it’s to easy to add it to the smart tag’s Expressions collection, as the following sample code demonstrates:

Private Sub AddCompanySmartTag()

Dim CompanyDetails As New Microsoft.Office.Tools.Word.SmartTag( _

“www.test.com/CompanyDetails#CompanyDetailsSample”, “Company Details”)

CompanyDetails.Expressions.Add(“regular expression goes here”)

SaveCompanyName = New Microsoft.Office.Tools.Word.Action(“Save Name”)

CompanyDetails.Actions = New Microsoft.Office.Tools.Word.Action() _

{SaveCompanyName}

Me.VstoSmartTags.Add(CompanyDetails)

End Sub

Because the Expressions member is a collection object, you can build and store multiple expressions to match against.

VSTO2005 is discussed at length in Chapter 55, including how to add smart tags to documents.

What Are Regular Expressions?

Now that you know how regular expressions are used in different parts of Visual Studio 2005, you may still be wondering how you construct a regular expression. Well, a regular expression consists of a series of characters, or a string, including special characters, that identify different ways of performing pattern matching. The simplest regular expression is plain text and is identical to searching for the characters directly — for example, the statement Dim myRegex As New Regex(“TextToMatch”) creates a regular expression that finds any instances in a block of text that match the string TextToMatch.

The next step is the introduction of simple constructs, such as the asterisk to represent multiple instances or a period to indicate any single character except a line break. Using these two constructs in combination, you can locate a string that includes other information. For example, the following code looks for any instance of the string Text followed by the string ToMatch, regardless of how far apart they are:

Dim myRegex As New Regex(“Text.*ToMatch”) Dim myMatches As MatchCollection = _

myRegex.Matches(“Search string containing Text Other Information ToMatch”) For Each myMatch As Match In myMatches

Console.WriteLine(“Found match at position “ & myMatch.Index.ToString() & _ “: “ & myMatch.Value)

Next

Regular expression constructs can also be used to mark special conditions such as the start or end of a line or word, as well as to provide alternative search terms. For example, the regular expression

532

Regular Expressions

(This|That) will match any instance of This or That in the search text. Advanced forms of this kind of optional searching are also available to your pattern construction, such as classes of characters represented by square brackets; for example, [abc] will find any instance of a, b, or c.

Using Regular Expressions to Replace Data

When using regular expressions to modify data, such as replacing it with other information or removing it from the source text, additional pattern constructs are used. These extra syntactical elements relate to the parts of the text that were found in the pattern matching part of the process and how they should be treated — for example, when the text is found, you save parts of it with aliased variables that you can then use in the replacement phase with your new text.

Consider the following example in which the elements of a string containing a date are swapped around:

NewDateYMD = Regex.Replace(OldDateMDY, _ “\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b”, _ “${year}-${month}-${day}”)

The Replace method of the Regex object takes three parameters: an input string that is used as the source for the replacement action, the search pattern to find the string to replace, and the replacement pattern for the required outcome. In this case, the search pattern looks for the following:

A oneor two-digit number, stored in memory with the alias month, followed by

A forward slash character, followed by

A oneor two-digit number, stored in memory with the alias day, followed by

A forward slash character, followed by

A twoor four-digit number, stored in memory with the alias year

The \b elements at the beginning and end of the pattern indicate a word boundary. When the regular expression finds a match for this search pattern, it then replaces it with the following string:

Whatever text was stored in the year alias, which will be a twoor four-digit number, followed by

A hyphen character, followed by

Whatever text was stored in the month alias, which will be a oneor two-digit number, followed by

A hyphen character, followed by

Whatever text was stored in the day alias, which will be a oneor two-digit number

The following table shows several input strings and what is produced as the output of this command:

Original String

New String

 

 

12/31/05

05-12-31

The date is 12/31/05.

The date is 05-12-31.

3/1/2005

2005-3-1

 

 

533

Chapter 39

Note how the replacement functionality leaves the remainder of the string unchanged because it is only replacing the matched portion of the original text.

Regular Expression Syntax

While complex regular expressions can be daunting, once you understand the syntax of each matching pattern, it becomes straightforward to interpret. The following table introduces you to the patterns you can use in constructing your regular expressions:

Pattern Syntax

Description

 

 

{}

In Find and Replace, a tagged portion of text. However, in code, braces

 

are used to indicate a number of occurrences of the previous expression.

 

For example, is(my){2}book will only match the string ismymybook.

*

An asterisk will match any number of occurrences of the previous expres-

 

sion or character, including none. It is equivalent to {0,}.For example,

 

is(my)*book will match the strings isbook, ismybook, and ismymy-

 

book, but not isyourbook.

+

Similar to the asterisk, this will match a number of occurrences of the previ-

 

ous expression, but requires at least one. This pattern is equivalent to {1,}.

 

In the previous example, using + instead of * would result in isbook

 

being omitted from the matches.

?

Takes the previous expression one step further and restricts the pattern to

 

match one instance only, but will also pass if there is no instance of the

 

pattern. This pattern is the equivalent of {0,1}. Using an example pattern

 

of is(my)?book would match isbook, ismybook but not ismymybook.

^ and $

Marks the start and end positions of a line of text

< and >

Marks the start and end positions of a word. You can also use \b as a

 

word boundary escape character.

^digit

Find and Replace uses this nomenclature for finding a set number of

 

instances of an expression. If you were looking for the string ismymybook

 

in your code listing, you would use the pattern is(my)^2book.

()

Parentheses are used to group an expression. In the previous examples

 

the phrase my was grouped for subsequent constructs by enclosing it in

 

parentheses. If you used a pattern of ismy*book it would return only text

 

that contained 0 to many instances of the letter y, such as ismyyybook.

[]

A class of characters from which the pattern can match one. That set of

 

characters can have a range of characters specified by using a hyphen.

 

For example, [a-cm-p] will find any one character that is any of the

 

alphabetic characters, a, b, c, m, n, o, or p.You can also include the ^ char-

 

acter in the set to indicate that the pattern should not match the following

 

characters. For example, changing the preceding example pattern to

 

[^a-cm-p] will find any one character that is not in the range of alpha-

 

betic characters listed.

 

 

534

 

 

Regular Expressions

 

 

 

 

Pattern Syntax

Description

 

 

 

 

.

Matches any single character except a line break special character, so

 

 

b..k will match the strings book and back, but not brick.

 

|

Indicates an either-or situation and is usually used in a group expression

 

 

to provide alternate strings that can be matched.

 

 

For example book(case|end) will match either bookcase or bookend.

 

~

Preceding an expression in the Find and Replace dialog with the tilde

 

 

character indicates that that the expression will be used to exclude

 

 

matches.

 

 

For example, is~(your)book will find the strings ismybook and

 

 

ishisbook, but not isyourbook.

 

\

Used as an escape character, the backslash indicates that the following

 

 

regular expression character is to be considered literally, so \~ will find

 

 

the tilde character, rather than assume it is an exclusion construct.

 

\n

Indicates a line break character

 

\e

Indicates the escape character

 

\h

Represents the backspace character

 

\t

Used to indicate the tab character

 

 

 

In addition to these rules, there are also a number of regular expression aliases that allow you to shortcut some complex patterns. These expressions are available only in the Find and Replace dialog:

Expression

Description

:b

Matches either a space or tab character

:z

Matches a number and is equivalent to a pattern of ([0-9]+)

:d

Matches a single digit, which is the same as the pattern ([0-9])

:c

Matches an alphabetic character and is equivalent to ([a-zA-Z])

:a

Matches an alphanumeric character and is equivalent to ([0-9a-zA-Z])

:w

Matches an alphabetic string, thereby replacing the pattern ([a-zA-Z]+)

:h

Matches all hexadecimal numbers, which is equivalent to ([0-9a-fA-

 

F]+)

:q

Matches a quoted string with either quotation marks or apostrophes. To

 

write this out explicitly as a pattern, you would need to specify

 

((“[^”]*”)|(‘[^’]*’)).

 

 

535