Showing posts with label Visual Studio 2008. Show all posts
Showing posts with label Visual Studio 2008. Show all posts

You can execute applications in two ways: with debugging enabled or without debugging enabled. By default, when you execute an application from VS or VCE, it executes with debugging enabled. This happens, for example, when you press F5 or click the green Play arrow in the toolbar. To execute an application without debugging enabled, choose Debug -> Start Without Debugging.

Both Visual Studio and Visual Studio Express allow you to build applications in two configurations: Debug (the default) and Release . (In fact, you can define additional configurations, but that ’ s an advanced technique not covered here.) You can switch between these configurations using the Solution Configurations drop - down in the
Standard toolbar.

In Visual Studio Express this drop - down list is inactive by default. Enable it by selecting Tools -> Options. In the Options dialog, ensure that Show All Settings is selected, choose the General subcategory of the Projects and Solutions category, and enable the Show Advanced Build Configurations option.

When you build an application in debug configuration and execute it in Debug mode, more is going on than the execution of your code. Debug builds maintain symbolic information about your application, so that the IDE knows exactly what is happening as each line of code is executed. Symbolic information means keeping track of, for example, the names of variables used in uncompiled code, so they can be matched to the values in the compiled machine code application, which won ’ t contain such human - readable information. This information is contained in . pdb files, which you may have seen in your computer ’ s Debug directories. This enables you to perform many useful operations:

• Outputting debugging information to the IDE.
• Looking at (and editing) the values of variables in scope during application execution.
• Pausing and restarting program execution.
• Automatically halting execution at certain points in the code.
• Stepping through program execution one line at a time.
• Monitoring changes in variable content during application execution.
• Modifying variable content at runtime.
• Performing test calls of functions.

In the release configuration, application code is optimized, and you cannot perform these operations. However, release builds also run faster, and when you have finished developing an application you will typically supply users with release builds because they won ’ t require the symbolic information that debug builds include.

The debugging techniques you can use to identify and fix areas of code that don’t work as expected, a process known as debugging. The techniques are grouped into two sections according to how they are used. In general, debugging is performed either by interrupting program execution or by making notes for later analysis. In Visual Studio and Visual Studio Express terms, an application is either running or is in Break mode — that is, normal execution is halted. You’ll look at the Nonbreak mode (runtime or normal) techniques first.

Source of Information : Wrox Beginning Microsoft Visual C Sharp 2008

Whether or not you realize it, if you are like most developers, you are always refactoring code. Every time you change your code to reduce duplication or rename items for the sake of clarity, you are refactoring. Refactoring is simply putting a name to a common development task. The strict definition of the term is “a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior.” That is, refactoring does not add features to the application. Instead, it improves the general maintenance of the code base.

The term refactoring has received a large amount of attention. A number of good books have been written touting the many benefits of refactoring code as you are building your application. This is when you are closest to the code and thus able to quickly make these maintenance-type changes. Many of these books are on the subject of extreme programming. Refactoring has become one of the key tenets of the extreme programmer. In extreme programming, your code base builds feature by feature to satisfy a series of tests. This can result in code that works wonderfully but does not look as though it was designed as a cohesive unit. To combat this problem, you would be wise to go over the code base at frequent intervals and thus improve the general quality of the code (remove duplication, create common interfaces, rename items, put things into logical groups, and so on).

A new set of features has arisen inside code editors to aid with refactoring. These features have their basis in a real need. No developer wants to introduce errors into a relatively stable code base simply for the sake of improving maintenance—especially when running a tight schedule. Imagine explaining to your manager or client that the large spike in bugs is a result of sweeping changes you made to the code to improve future maintenance and readability. We can be thankful that the C# editor inside Visual Studio 2008 provides a reliable set of refactoring tools. These tools let you make changes to the code base without the concern of creating more problems than you are solving.

Visual Basic developers do have an option for refactoring in Visual Studio 2008. A third-party development house, DevExpress (http://www.devexpress.com), struck a deal with Microsoft to include a version of its product for all Visual Studio 2008 VB .NET developers. However there are a couple of features built into Visual Studio for refactoring database elements.

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

The Task List is essentially an integrated to-do list; it captures all the items that, for one reason or another, need attention and tracking. The Task List window then surfaces this list and allows you to interact with it. To show the window, select the View menu and choose the Task List entry illustrates the Task List window displaying a series of user tasks. Tasks belong to one of three categories—comment tasks, shortcut tasks, and user tasks—and only one category can be displayed at a time.

The drop-down at the top of the Task List window enables you to select the current category. Each category will have slightly different columns that it shows for each task category type, but they will all have a Priority column and a Description column. For instance, user tasks and shortcut tasks provide a check box that is used to track task completion; shortcut and comment tasks display a filename and line number; and so on. You can sort the tasks by any of the columns shown in the list. Right-clicking on the column headers provides a shortcut menu that allows you to control the sort behavior, as well as which columns (from a list of all supported columns) should be displayed.

Comment Tasks
Comment tasks are created within your code. Placing a code comment with a special string literal/token will cause Visual Studio to add that comment to the comment task list. Three of these tokens are defined by Visual Studio: HACK, TODO, and UNDONE. To see these tasks in your task window, ensure that you have selected “Comments” from the dropdown at the top of the task list. Double-clicking on the comment task will take you directly to the referenced comment line within the editor window.

Custom Comment Tokens
If needed, you can add your own set of tokens that will be recognized as comment tasks. From the Tools, Options dialog box, select the Task List page under the Environment section; this dialog box provides options for adding, editing, or deleting the list of comment tokens recognized by the task list. You can also set a priority against each of the tokens and fine-tune some of the display behavior by using the Task List Options check boxes, which control whether task deletions are confirmed, and by setting whether filenames or complete file paths are displayed within the task list.

Shortcut Tasks
Shortcut tasks are actually links to a line of code. You add them using the Bookmarks menu by placing the cursor on a line within the editor and then selecting Edit, Bookmarks, Add Task List Shortcut. The actual content of that line of code shows up as the task description. Double-clicking on the task takes you directly to the bookmarked line within the editor window.

User Tasks
User tasks are entered directly into the task window. A Create User Task button appears next to the category drop-down on the Task List window; this button adds a new entry within the list. You can type directly into the description column to add the task’s title.
Unlike shortcut and comment tasks, user tasks aren’t linked to a specific line of code.


Visual Studio’s automation model provides complete control over task lists. Using the exposed automation objects such as TaskList and TaskListEvents, you can, for example, programmatically add or remove tasks from the list; respond to a task being added, edited, or even selected; and control the linking between a task and an editor.

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

IntelliSense is the name applied to a collection of different coding aids surfaced within the text editor window. Its sole purpose is to help you, the developer, write a syntactically correct line of code quickly. In addition, it tries to provide enough guidance to help you write lines of code that are correct in context—that is, code that makes sense given the surrounding lines of code.

As you type within the text editor, IntelliSense is the behind-the-scenes agent responsible for providing a list of code fragments that match the characters you have already entered, highlighting/preselecting the one that makes the most sense given the surrounding context, and, if so commanded, automatically inserting that code fragment in-line. This saves you the time of looking up types and members in the reference documentation and saves time again by inserting code without your having to actually type the characters for that code.

There are many discrete pieces to IntelliSense that seamlessly work in conjunction with one another as you are writing code. You can also trigger all of these IntelliSense features directly from the Edit, IntelliSense menu, or by pressing Ctrl+space. And many of them can be found as well on the text editor’s context menu, or by right-clicking anywhere in the editor window. Let’s look at them one by one.



Complete Word
Complete Word is the basic timesaving kernel of IntelliSense. After you have typed enough characters for IntelliSense to recognize what you are trying to write, a guess is made as to the complete word you are in the process of typing. This guess is then presented to you within a list of possible alternatives (referred to as the completion list) and can be inserted into the code editor with one keystroke. This is in contrast to your completing the word manually by typing all of its characters.

Based on the context of the code and based on the characters typed into the editor, a list of possible words is displayed. One of these words is selected as the most viable candidate; you may select any entry in the list (via the arrow keys or the mouse). Pressing the Tab key automatically injects the word into the editor for you.

You can manually invoke Complete Word at any time by using the Ctrl+space or
Alt+right-arrow key combinations.

Complete Word takes the actual code context into account for various situations. For instance, if you are in the midst of keying in the exception type in a try/catch block, IntelliSense displays only exception types in the completion list. Likewise, typing an attribute triggers a completion list filtered only for attributes; when you’re implementing an interface, only interface types are displayed; and so on. This IntelliSense feature is enabled for all sorts of content: Beyond C# and Visual Basic code, IntelliSense completion works for other files as well, such as HTML tags, CSS style attributes, .config files, and HTML script blocks, just to name a few. Visual Basic offers functionality with
Complete Word that C# does not: It provides a tabbed completion list, in which one tab contains the most commonly used syntax snippets, and the other contains all the possible words.



Quick Info
Quick Info displays the complete code declaration and help information for any code construct. You invoke it by hovering the mouse pointer over an identifier; a pop-up box displays the information available for that identifier. You are provided with the declaration syntax for the member, a brief description of the member, and a list of its exception classes. The description that shows up in the Quick Info balloon also works for code that you write: If you have a code comment associated with a member, IntelliSense parses the comment and uses it to display the description information.



List Members
The List Members feature functions in an identical fashion to Complete Word; for any given type or namespace, it displays a scrollable list of all valid member variables and functions specific to that type. To see the List Members function in action, perform the following steps in an open code editor window:

1. Type the name of a class (Ctrl+spacebar will give you the IntelliSense window with
possible class names).

2. Type a period; this indicates to IntelliSense that you have finished with the type name and are now “scoped in” to that type’s members.

3. The list of valid members is now displayed. You can manually scroll through the list and select the desired member at this point, or, if you are well aware of the member you are trying to code, you can simply continue typing until IntelliSense has captured enough characters to select the member you are looking for.

4. Leverage Complete Word by pressing the Tab key to automatically insert the member into your line of code (thus saving you the typing effort).

This feature also operates in conjunction with Quick Info: As you select different members in the members list, a Quick Info pop-up is displayed for that member.


Parameter Info
Parameter Info, as its name implies, is designed to provide interactive guidance for the parameters needed for any given function call. This feature is especially useful for making function calls that have a long list of parameters and/or a long overload list. Parameter Info is initiated whenever you type an opening parenthesis after a function name. To see how this works, perform these steps:

1. Type the name of a function.

2. Type an open parenthesis.

3. A pop-up box shows the function signature. If there are multiple valid signatures (for example, multiple overloaded versions of this function), you can scroll through the different signatures by using the small up- and down-arrow cues. Select the desired signature.

4. Start typing the actual parameters you want to pass in to the function. As you type, the parameter info pop-up continues coaching you through the parameter list by bolding the current parameter you are working on. As each successive parameter is highlighted, the definition for that parameter appears.



Organize Usings
Organize Usings is a C#-only IntelliSense item. It encapsulates two separate functions: Remove Unused Usings and Sort Usings. It also provides a third command, Remove and Sort, that combines the two actions into one. All three commands live under the Organize Usings menu item on the editor shortcut menu, or under the main Edit, IntelliSense menu.

The Remove Unused Usings function is a great aid for uncluttering your code. It parses through the current body of code and determines which Using statements are necessary for the code to compile; it then removes all other Using statements. The Sort command is straightforward as well: It simply rearranges all of your Using statements so that they appear in A–Z alphabetical order by namespace.



Code Snippets and Template Code
Code snippets are prestocked lines of code available for selection and insertion into the text editor. Each code snippet is referenced by a name referred to as its alias. Code snippets are used to automate what would normally be non–value-added, repetitive typing.
You can create your own code snippets or use the default library of common code elements provided by Visual Studio.

Using the Code Snippet Inserter
You insert snippets by right-clicking at the intended insertion point within an open text editor window and then selecting Insert Snippet from the shortcut menu. This launches the Code Snippet Inserter, which is a drop-down (or series of drop-downs) that works much like the IntelliSense Complete Word feature. Each item in the inserter represents a snippet, represented by its alias. Selecting an alias expands the snippet into the active document.

Each snippet is categorized to make it easier to find the specific piece of code you are looking for. As an example, to insert a constructor snippet into a C# class, we would rightclick within the class definition, select Visual C# from the list of snippet categories, and hen select ctor. Noe that as you select a snippet category, a placeholder is displayed in the text editor window to help establish a “bread-crumb” trail.

After the constructor snippet is expanded into the text editor, you will still, of course, have to write meaningful code inside of the constructor; but, in general, snippets eliminate the process of tedious coding that really doesn’t require much intellectual horsepower to generate. The process is identical with the exception that Visual Basic makes more extensive use of categories.

Surrounding Code with Snippets
C# and XML documents have one additional style of code snippets that bears mentioning:
Surround With snippets. Surround With snippets are still snippets at their core (again, these are simply prestocked lines of code), but they differ in how they are able to insert themselves into your code.

Using a Surround With snippet, you can stack enclosing text around a selection with the text editor. As an example, perhaps you have a few different class declarations that you would like to nest within a namespace. When you use the Surround With snippet, this is a simple two-step process: Highlight the class definitions and fire up the Code Snippet Inserter. This time, instead of selecting Insert Snippet from the shortcut menu, you select
Surround With. The insert works the same way, but this time has applied the snippet (in this case, a namespace snippet) in a different fashion. Compare the before and after text. We have encapsulated the class definitions within a new namespace that sits within yet another namespace—all with just a few mouse clicks.

Creating Your Own Code Snippets
Because code snippets are stored in XML files, you can create your own snippets quite easily. The key is to understand the XML schema that defines a snippet, and the best way to do that is to look at the XML source data for some of the snippets included with the IDE. Snippets are stored on a per-language basis under the install directory for Visual Studio. For example, the Visual Basic snippets can be found, by default, in the folders under the C:\Program Files\Microsoft Visual Studio 9.0\Vb\Snippets directory. Although snippet files are XML, they carry a .Snippet extension.

The XML Snippet Format
The basic structure of this particular snippet declaration is described in below. A more complete schema reference is available as a part of the Visual Studio MSDN help collection; it is located under Integrated Development Environment for Visual Studio, Reference, XML Schema References, Code Snippets Schema Reference.

<CodeSnippets>. The parent element for all code snippet information. It references the specific XML namespace used to define snippets within Visual Studio
2008.

<CodeSnippet>. The root element for a single code snippet. This tag sets the format version information for the snippet (for the initial release of VS 2008, this should be set to 1.0.0). Although multiple CodeSnippet elements are possible within the parent <CodeSnippets> element, the convention is to place one snippet per file.

<Header>. A metadata container element for data that describes the snippet.

<Title>. The title of the code snippet.

<Shortcut>. Typically, the same as the title, this is the text that will appear in the code snippet insertion drop-downs.

<Description>. A description of the snippet.

<Author>. The author of the snippet.

<SnippetTypes>. The parent element for holding elements describing the snippet’s type.

<SnippetType>. The type of the snippet: Expansion, Refactoring, or Surrounds With. You cannot create custom refactoring snippets. This property is really used to tell Visual Studio where the snippet can be inserted within the editor window: Expansion snippets insert at the current cursor position, whereas Surrounds With snippets get inserted before and after the code body identified by the current cursor position or selection.

<Snippet>. The root element for the snippet code.

<Declarations>. The root element for the literals and objects used by the snippet.

<Literal>. A string whose value can be interactively set as part of the snippet expansion process. The Editable attribute on this tag indicates whether the literal is static or editable. The ctor snippet is an example of one without an editable literal; contrast this with the form transparency snippet that you saw—an example of a snippet with an editable literal that allows you to set the form name as part of the snippet insertion.

<ID>. A unique ID for the literal.

<ToolTip>. A ToolTip to display when the cursor is placed over the literal.

<Function>. The name of a function to call when the literal receives focus. Functions are available only in C# snippets.

<Default>. The default string literal to insert into the editor.

<Code>. An element that contains the actual code to insert.

Code Snippet Functions - calling a function to prepopulate the class name within the nippet. Functions are available only with C# (with a subset also available in J#). The rest of the literals rely on the developer to type over the placeholder value with the correct value.

GenerateSwitchCases. Creates the syntax for a switch statement that includes a case statement for each value defined by the enumeration represented by enumliteral (C#/J#).

ClassName(). Inserts the name of the class containing the code snippet (C#/J#).

SimpleTypeName. Takes the type name referenced by typename and returns the shortest name possible given the using statements in effect for the current code block.

CallBase. Is useful when stubbing out members that implement or return the base type: When you specify get, set, or method as the parameter, a call will be created against the base class for that specific property accessor or method (C#).

Adding a Snippet to Visual Studio You can use Visual Studio’s own XML editor to create the XML document and save it to a directory (a big bonus for doing so is that you can leverage IntelliSense triggered by the XML snippet schema to help you with your element names and relationships). The Visual Studio installer creates a default directory to place your custom snippets located in your Documents folder: user\Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets. If you place your XML template here,

Visual Studio will automatically include your snippet for use. The Code Snippets Manager, which is launched from the Tools menu, is the central control dialog box for browsing the available snippets, adding new ones, or removing a snippet. You can also opt to include other folders besides the standard ones. To do so, click on the Add button to enter additional folders for Visual Studio to use when displaying the list of snippets.

Snippets in the Toolbox
Although this capability is technically not part of the official code snippet technology within Visual Studio, you can also store snippets of code in the toolbox. First, select the text in the editor and then drag and drop it onto the toolbox. You can then reuse this snippet at any time by dragging it back from the toolbox into an open editor window.



Brace Matching
Programming languages make use of parentheses, braces, brackets, and other delimiters to delimit function arguments, mathematical functions/order of operation, and bodies of code. It can be difficult to visually determine whether you have missed a matching delimiter—that is, if you have more opening delimiters than you have closing delimiters—especially with highly nested lines of code.

Brace matching refers to visual cues that the code editor uses to make you aware of your matching delimiters. As you type code into the editor, any time you enter a closing delimiter, the matching opening delimiter and the closing delimiter will briefly be highlighted.

Although this feature is referred to as brace matching, it actually functions with the following delimiters:
• Parentheses: ()
• Brackets: [], <>
• Quotation marks: ””
• Braces: {}

In the case of C#, brace matching also works with the following keyword pairs (which essentially function as delimiters using keywords):
• # region, #endregion
• #if, #else, #endif
• case, break
• default, break
• for, break, continue
• if, else
• while, break, continue



Customizing IntelliSense
Certain IntelliSense features can be customized, on a per-language basis, within the Visual Studio Options dialog box. If you launch the Options dialog box (located under the Tools menu) and then navigate to the Text Editor node, you will find IntelliSense options confusingly scattered under both the General and IntelliSense pages.

Completion Lists in this dialog box refer to any of the IntelliSense features that facilitate autocompletion of code, such as List Members and Complete Word are such as:

Show Completion List After a Character Is Typed. This causes the Complete Word feature to automatically run after a single character is typed in the editor window.

Place Keywords in Completion Lists. If this box is checked, language keywords will be displayed within the completion list. As an example, for C#, this would cause keywords such as class or string to be included in the completion list.

Place Code Snippets in Completion Lists. Checking this box will place code-snippet alias names into any displayed completion lists.

Committed by Typing the Following Characters. This check box contains any of the characters that will cause IntelliSense to execute a completion action. In other words, typing any of the characters in this text box while a completion list is displayed will cause IntelliSense to insert the current selection into the editor window.

Committed by Pressing the Space Bar. Checking this adds the space character to the list of characters that will fire a completion commit.

Add New Line on Commit with Enter at End of Fully Typed Word. Checking this box will cause the cursor to advance down an entire line if you fully type a word in the IntelliSense list box. This is useful for those scenarios in which fully typed keywords are unlikely to be followed on the same line with other code.

IntelliSense Pre-selects Most Recently Used Members. If this box is checked, IntelliSense will maintain and use a historical list of the most frequently used members for a given type. This “MFU” list is then used to preselect members in a completion list.


Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

Smart tags and smart tasks (the terms can essentially be used interchangeably) are menu or IntelliSense-driven features for automating common control configuration and coding tasks within the IDE. Designers and editors both implement smart tags in various scenarios.

HTML Designer
As controls are placed onto the HTML designer, a pop-up list of common tasks appears. These tasks, collectively referred to as smart tasks, allow you to “set the dials” for a given control to quickly configure it for the task at hand.

You use the common tasks list to quickly configure a control’s properties, as well as walkthrough common operations you might perform with it. For example, when you add a GridView control to a web page, a common task list appears that allows you to quickly enable sorting, paging, or editing for the GridView. When you add a TextBox control to a web page, a common task list appears that enables you to quickly associate a validation control with the control.

The Windows Forms designer also plays host to smart tags.

Windows Forms Designer
With the Windows Forms designer, the functionality of smart tags remains consistent; they do, however, take a slightly different form. A form control that supports this functionality shows a smart tag glyph somewhere within its bounds (typically to the top right of the control). This glyph, when clicked, opens a small drop-down of tasks.

Code Editor
Smart tags can also appear within code. One example can be found on interfaces. Normally, implementing an interface is a fairly code-intensive task. You have to individually create a member to map to each member defined on the interface. The smart tag in this case allows you to automatically create those members using two different naming modes:

• Explicit naming—Members have the name of the derived interface.

• Implicit naming—Member names do not reference the name of the derived interface.

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

Certain documents, such as source code files and markup files, have a natural parent-child aspect to their organization and syntax. XML nodes, for instance, can contain other nodes. Likewise, functions and other programming language constructs such as loops and try/catch blocks act as a container for other lines of code. Outlining is the concept of visually representing this parent-child relationship.

Both Visual Basic and C# provide a way to manually create named regions of code via a special region keyword. Use #region/#endregion (#Region and #End Region for Visual Basic) to create your own artificial code container that will be appropriately parsed by the code outliner. Because each region is named, this is a handy approach for organizing and segregating the logical sections of your code. In fact, to use one example, the code generated for you by the Windows Forms Designer is automatically tucked within a “Windows Forms Designer generated code” region. One quick way to implement a region is with Surround With: In the editor, highlight the code that you want to sit in a new region, right-click on the highlighted text, select Surround With from the context menu, and then select #region (or #Region for VB).


Code Outlining
Code outlining is used within the code editor; it allows you to collapse or expand regions of code along these container boundaries. A series of grouping lines and expand/collapse boxes are drawn in the selection margin. These expand/collapse boxes are clickable, enabling you to hide or display lines of code based on the logical groupings. Code outlining is best understood using a simple example. This is the initial console application code. It contains a routine called Main, a class declaration, a namespace declaration, and several using statements. The code outline groupings that you see in the selection margin visually indicate code regions that can be collapsed or hidden from view.

Because the class declaration is a logical container, the selection margin for that line of code contains a collapse box (a box with a minus sign). A line is drawn from the collapse box to the end of the container (in this case, because you are dealing with C#, the class declaration is delimited by a curly brace). If you click on the collapse box for the class declaration, Visual Studio will hide all the code contained within that declaration.

Note that the collapse box has changed to a plus sign, indicating that you can click on the box to reshow the now-hidden code, and that the first line of code for the class declaration has been altered to include a trailing box with ellipses.

The HTML Editor also supports outlining in this fashion. HTML elements can be expanded or collapsed to show or hide their containing elements.


Using the Outlining Menu
Several code outlining commands are available under the Edit, Outlining menu.

• Toggle Outlining Expansion—Based on the current cursor position in the editor window, hides or unhides the outline region.

• Toggle All Outlining—Hides or unhides all outline regions in the editor.

• Stop Outlining—Turns off automatic code outlining (any hidden regions will be expanded). This command is available only if automatic outlining is turned on.

• Stop Hiding Current—Removes the outline for the currently selected region. This command is available only if automatic outlining has been turned off.

• Collapse to Definitions—Hides all procedure regions. This command is useful for distilling a type down to single lines of code for all of its members.

• Start Automatic Outlining—Enables the code outlining feature. This command is available only if outlining is currently turned off.

Code outlining is a convenience mechanism: By hiding currently irrelevant sections of code, you decrease the visible surface of the code file and increase code readability. You can pick and choose the specific regions to view based on the task at hand.

If you place the mouse pointer over the ellipses box of a hidden code region, the contents of that hidden region will be displayed to you in a ToolTip-style box; this is done without your having to actually expand/reshow the code region.



HTML Navigation
One problem with large or complex web pages is that navigation through the HTML can be problematic with multiple levels and layers of tag nesting. Envision a page containing a table within a table within a table. When you are editing the HTML (through either the designer or the editor), how can you tell exactly where you are? Put another way, how can you tell where the current focus is within the markup hierarchy?

Using the Tag Navigator
The tag navigator is Visual Studio’s answer to this question. The navigator appears as a series of buttons at the bottom of the web page editor, just to the right of the designer/editor tabs. A bread-crumb trail of tags is shown (as buttons) that leads from the tag which currently has focus all the way to the outermost tag. If this path is too long to actually display within the confines of the editor window, it is truncated at the parent tag side; a button enables you to display more tags toward the parent.

Each tag button displayed by the navigator can be used to directly select the inclusive or exclusive contents of that tag. A drop-down triggered by the tag button will contain options for selecting the tag or selecting the tag content. The former will cause the tag itself, in addition to all of its enclosed content, to be selected. The latter will exclude the tag begin and end, but will still select all of its enclosed content. The navigator is a great mechanism for quickly moving up and down within a large HTML documents tag tree.

Using the Document Outline Window
The Document Outline window displays a tree-view representation of the HTML elements on a page. This hierarchical display is also a great navigation tool because it allows you to take in the entire structure of your web page in one glance and immediately jump to any of the elements within the page.

To use the Document Outline window, choose Document Outline from the View, Other Windows menu. Elements within the head, page, and body elements are displayed, in addition to script and code elements. Clicking on an element will navigate to that element (and select it) within the designer window, and, of course, you can expand or collapse the tree nodes as needed.

The text editor user interface has several visual constructs that help you with common problem areas encountered during the code-writing process. These basic aids provide support for determining what has changed within a code document and what compile problems exist in a document. Additionally, the discrete syntax elements for each individual language are visually delineated for you using colored text.


Change Tracking
When you are in the midst of editing a source code file, it is tremendously useful to understand which lines of code have been committed (that is, saved to disk) and which have not. Change tracking provides this functionality: A yellow vertical bar in the text editor’s selection margin will span any lines in the editor that have been changed but not saved. If content has been changed and subsequently saved, it will be marked with a green vertical bar in the selection margin.

By looking at the yellow and green tracking bars, you can quickly differentiate between:

• Code that hasn’t been touched since the file was loaded (no bar)

• Code that has been touched and saved since the file was loaded (green bar)

• Code that has been touched but not saved since the file was loaded (yellow bar)

Change tracking is valid only for as long as the editor window is open. In other words, change tracking is significant only for the current document “session”; if you close and reopen the window, the track bars will be gone because you have established a new working session with that specific document.


Coding Problem Indicators
The Visual Studio compiler works in conjunction with the code editor window to flag any problems found within a source code document. The compiler can even work in the background, enabling the editor window to flag problems as you type (as opposed to waiting for the project to be compiled).

Coding problems are flagged using “squiggles”: wavy, color-coded lines placed under the offending piece of code. These squiggles are the same mechanism Microsoft Word uses to flag spelling and grammar problems. The squiggle colors indicate a specific class of problem. The below shows how these colors map to an underlying problem.

• Red - Syntax error; the code will not compile because of the syntax requirements and rules of the language.

• Blue - Semantic error; this is the result of the compiler not being able to resolve the type or code construct within the current context. For instance, a type name that doesn’t exist within the compiled context of the current project is flagged with a blue squiggle. Typically, these are good indicators for typos (for example, misspelling a class name).

• Purple - Warning; the purple squiggle denotes code that has triggered a compiler warning.


Active Hyperlinking
Text editors support clickable hyperlinks within documents; clicking on a link launches a browser redirected at the URL. One great use of this feature is to embed URLs for supporting documentation or other helpful reference information within code comments.


Syntax Coloring
The text editor can parse and distinctly color different code constructs to make them that much easier to identify on sight. As an example, the code editor window, by default, colors any code comments green. Code identifiers are black, keywords are blue, strings are colored red, and so on.

In fact, the number of unique elements that the text editor is capable of parsing and coloring is immense: The text editor window recognizes more than 100 different elements. And you can customize and color each one of them to your heart’s content through the Fonts and Colors section, under the Environments node in the Options dialog box. Do you like working with larger fonts? Would a higher contrast benefit your programming activities? How about squeezing more code into your viewable screen real estate? These are just a few reasons you might stray from the defaults with this dialog box.

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

The latest version of C# allows for a simplified property declaration called auto implemented properties. With this feature, you can simply declare a property without having to declare a local, private field to back the property. Instead, the compiler will do this for you. This can be useful when you do not need logic inside the property’s accessors.

As an example, suppose you want a property on the Employee class called Name. You can declare this property without setting a private field variable as shown here:

public string Name { get; set; }

Notice that there is no logic in the get or set statements. Instead, the compiler will create an anonymous field to back the property for you. In addition, the IntelliSense built into the C# code editor makes this property declaration even faster. Simply type prop to stub out a code snippet based on the automatically implemented property syntax.

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

Visual Basic now allows you to omit unused and unwanted arguments from your event handlers. The thought is that this will make for cleaner reading code. In addition, it allows you to assign methods directly to event handlers without trying to determine the proper event signature.

As an example, suppose you had the following code to respond to a button click event:

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
‘your code here
End Sub

You could remove the event handlers from this code (or never put them in). Your new
code would function the same and look as follows:

Private Sub Button1_Click() Handles Button1.Click
‘your code here
End Sub

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

You can now embed XML directly within your Visual Basic code. This can make creating XML messages and executing queries against XML a simple task in VB. To support this feature, VB allows you to write straight XML when using the data types called System.Xml.Linq.XElement and System.Xml.Linq.XDocument. The former allows you to create a variable and assign it an XML element. The latter, XDocument, is used to assign a variable to a full XML document.

Writing XML within your code is a structured process and not just simple strings assigned to a parsing engine. In fact, the compiler uses LINQ to XML behind the scenes to make all of this work. Let’s look at a simple example. The following code creates a variable, emp, of type XElement. It then assigns the XML fragment to this variable.

Dim emp As XElement = <employee>
<firstName>Joe Smith</firstName>
<title>Sr. Developer</title>
<company>Contoso</company>
<location state=”WA”>Redmond</location>
</employee>

You can create a similar fragment as an XDocument. You simply add the XML document definition (<?xml version=”1.0”?>) to the header of the XML. In either scenario, you end up with XML that can be manipulated, passed as a message, queried, and more.

In most scenarios, however, you would not want to hard-code your XML messages in your code. You might define the XML structure there, but the data will come from other sources (variables, databases, and so on). Thankfully, Visual Basic also supports building the XML using expressions. To do so, you use an ASP-style syntax, as in <%= expression %>. In this case, you indicate to the compiler that you want to evaluate an expression and assign it to the XML. For XML messages with repeating data, you can even define a loop in your expressions. As an example, let’s look at building the previous XML using this syntax. Suppose you have an object e that represents an employee. In this case, you might write your XElement assignment as shown here:

Dim e As Employee = New Employee()
Dim emp As XElement = <employee>
<firstName><%= e.FirstName %></firstName>
<lastName><%= e.LastName %></lastName>
<title><%= e.Title %></title>
<company><%= e.Company %></company>
<location state=<%= e.Location.State %>>
<%= e.Location.City %>
</location>
</employee>

VB allows you to write XML code. The two objects (XElement and XDocument) are still important additions to C# developers. However, C# developers will work with the properties and methods of these objects directly and not write and parse XML directly within a code editor.

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

The 2005 version of C# introduced the concept of Friend assemblies. This feature allows you to combine assemblies in terms of what constitutes internal access. That is, you can define internal members but have them be accessible by external assemblies. This capability is useful if you intend to split an assembly across physical files but still want those assemblies to be accessible to one another as if they were internal. Visual Basic developers now have this same feature as of the 2008 version.

You use the attribute class InternalsVisibleToAttribute to mark an assembly as exposing its internal members as friends to another assembly. This attribute is applied at the assembly level. You pass the name and the public key token of the external assembly to the attribute. The compiler will then link these two assemblies as friends. The assembly containing InternalsVisibleToAttribute will expose its internals to the other assembly (and not vice versa). You can also accomplish the same thing by using the command-line compiler switches.

Friend assemblies, like most things, come at a cost. If you define an assembly as a friend of another assembly, the two assemblies become coupled and need to coexist to be useful. That is, they are no longer a single unit of functionality. This can cause confusion and increase management of your assemblies. It is often easier to stay away from this feature unless you have a very specific need.

Friend assembles do not allow for access to private members.

A lot of what is special about Visual Studio 2008 from a language perspective has to do with a new feature set called LINQ (for Language-Integrated Query). LINQ is a new programming model that takes advantage of many of the features. It provides language extensions that are meant to change the way you access and work with data. With it, you can work with your data using object syntax and query collections of objects using VB and C#.

You can use LINQ to map between data table and objects. In this way, you get an easier, more productive way to work with your data. This includes full IntelliSense support based on table and column names. It also includes support for managing inserts, updates, deletes, and reads.

The last of these, reading data, is a big part of LINQ in that it has built-in support for easily querying collections of data. Using LINQ features, you can query not only your data but any collection in .NET. There are, of course, new keywords and syntax for doing so. Query operators that ship with Visual Basic, for example, include Select, From, Where, Join, Order By, Group By, Skip, Take, Aggregate, Let, and Distinct. The C# language has a similar set of keywords. And, if these are not enough, you can extend the built-in query operators, replace them, or write your own.

You use these query operators to query against any .NET data that implements the IEnumerable or IQueryable interface. This may include a DataTable, mapped SQL Server objects, .NET collections including Generics, DataSets, and XML data.

Let’s look at an example. Suppose you had a collection of employee objects called employees and you wanted to access all the employees at a specific location. To do so, you might write the following function:

C#
public static List<Employee> FilterEmployeesByLocation(

List<Employee> employees, string location) {

//LINQ query to return collection of employees filtered by location
var emps = from Employee in employees
where Employee.Location.City == location
select Employee;

return emps.ToList();
}


VB
Public Function FilterEmployeesByLocation( _

ByVal employees As List(Of Employee), _
ByVal location As String) As List(Of Employee)

‘LINQ query to return collection of employees filtered by location

Dim emps = From Employee In employees _
Where Employee.Location.City = location

Return emps.ToList()
End Function

Take a look at what is going on in the previous listing. The function takes a list of employee objects, filters it by a region passed to it, and then returns the resulting list. Notice that to filter the list, we create a LINQ, in-memory query called emps. This query can be read like this: Looking at all the employee objects inside the employees collection, find those whose city matches the city passed into the function. Finally, the emps.ToList() method call in the return statement converts the in-memory query results into a new collection.

This is just a brief overview of LINQ. There are many things going on here, such as compile-time checking and schema validation—not to mention the new LINQ language syntax. You.

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

A partial method (like a partial class) represents code you write to be added as a specific method to a given class upon compilation. This allows the author of a partial class to define a method stub and then call that method from other places within the class. If you provide implementation code for the partial method stub, your code gets called when the stub would be called (actually the compiler merges your code with the partial class into a single class). If you do not provide a partial method definition, the compiler goes a step further and removes the method from the class along with all calls to it.

The partial method (and partial class) was created to aid in code generation and should generally be avoided unless you are writing code generators or working with them because they can cause confusion in your code.

Of course, Visual Studio has more and more code generation built in. Therefore, it is likely you will run into partial methods sooner or later. In most cases, a code generator or designer (such as LINQ to SQL) generates a partial class and perhaps one or more partial methods. The Partial keyword modifier defines both partial classes and partial methods. If you are working with generated code, you are often given a partial class that allows you to create your own portion of the class (to be merged with the code-generated version at compile time). In this way, you can add your own custom business logic to any partial method defined and called by generated code. Let’s look at an example. The following represents an instance of a partial class, Employee. Here there is a single property called Salary. In addition, there is a method marked Partial called SalaryChanged. This method is called when the value of the Salary property is modified.

VB
Partial Class Employee

Private _salary As Double

Property Salary() As Double
Get
Return _salary
End Get

Set(ByVal value As Double)
_salary = value
SalaryChanged()
End Set
End Property

Partial Private Sub SalaryChanged()
End Sub
End Class

C#
partial class Employee {

double _salary;

public double Salary {
get {
return _salary;
}
set {
_salary = value;
SalaryChanged();
}
}

partial void SalaryChanged();
}

The former code might represent code that was created by a code generator. The next task in implementing a partial method then is to create another partial Employee class and provide behavior for the SalaryChanged method. The following code does just that:

VB
Partial Class Employee
Private Sub SalaryChanged()
Dim newSalary As Double = Me.Salary
‘do something with the salary information ...
End Sub
End Class

C#
partial class Employee {
partial void SalaryChanged() {
double newSalary = this.Salary;
//do something with the salary information ...
}
}

When the compiler executes, it replaces the SalaryChanged method with the new partial method. In this way, the initial partial class (potentially code-generated) made plans for a method that might be written without knowing anything about that method. If you decide to write it, then it gets called at the appropriate time. However, it is optional. If you do not provide an implementation of the partial method SalaryChanged, the compiler strips out the method and the calls to the method—as if had never existed.

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

In the latest version of the .NET languages, you can write simple functions that may or may not be named, execute in-line, and return a single value. These functions exist inside your methods and not as separate, stand-alone functions. These functions are called lambda expressions. It’s useful to understand lambda expressions because they are used behind the scenes in LINQ queries. However, they are also valid outside of LINQ.

Let’s take a look at an example. Suppose you want to create a simple function that converts a temperature from Fahrenheit to Celsius. You could do so within your Visual Basic code by first using the keyword Function. Next, you can indicate parameters to that function (in this case, the Fahrenheit value). Lastly, you write an expression that evaluates to a value that can be returned from the lambda expression. The syntax is as follows:

VB
Dim fahToCel = Function(fahValue As Integer) ((fahValue - 32) / 1.8)

The C# syntax is a bit different. In C#, you must explicitly declare a delegate for use by the compiler when converting your lambda expression. Of course, you declare the delegate at the class-level scope. After you have the delegate, you can write the expression inside your code. To do so, you use the => operator. This operator is read as “goes to.” To the left side of the operator, you indicate the delegate type, a name for the expression, and then an = sign followed by any parameters the expression might take. To the right of the => operator, you put the actual expression. The following shows an example of both the delegate and the expression:

C#
//class-level delegate declaration
delegate float del(float f);
//lambda expression inside a method body
del fahToCel = (float fahValue) => (float)((fahValue - 32) / 1.8);

Notice that in both examples, we assigned the expression to a variable, fahToCel. By doing so, we have created a delegate (explicitly converting to one in C#). We can then call the variable as a delegate and get the results as shown here:

VB
Dim celcius As Single = fahToCel(70)

C#
float celcius = fahToCel(-10);

Alternatively, in Visual Basic, we could have written the function in-line (without assigning it to a variable). As an example, we could have written this:

VB
Console.WriteLine((Function(fahValue As Integer) ((fahValue - 32) / 1.8))(70))

Notice in this last example that the function is declared and then immediately called by passing in the value of 70 at the end of the function.

The C# language has its own quirk too. Here you can write multiple statements inside your lambda expression. You do so by putting them inside curly braces and setting off each statement with a semicolon. The following example has two statements inside the lambda expression. The first creates the new value; the second writes it to a console window. Notice too that the delegate must be of type void in this instance and that you still must call the lambda expression for it to execute.

C#
//class level delegate declaration
delegate void del(float f);
del fahToCel = (float fahValue) => { float f =
(float)((fahValue - 32) / 1.8); Console.WriteLine(f.ToString()); };
fahToCel(70);

Lambda expressions are used in LINQ queries for things such as the Where, Select, and Order by clauses. For example, using LINQ, you can write the following statement:

VB
Dim emps = From emp In db.employees
Where(emp.Location = “Redmond”)
Select emp

C#
var emps = from emp in db.employees
where emp.Location == “Redmond”
select emp;

This LINQ code gets converted to lambda expressions similar to this:

VB
Dim emps = From emp In db.employees
.Where(Function(emp) emp.Location = “Redmond”)
.Select(Function(emp) emp)

C#
var emps = from emp in db.employees
where (emp => emp.Location == “Redmond”
select (emp => emp);

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

You can now create an object that does not have a class representation at design time. Instead, an unnamed (anonymous) class is created for you by the compiler. This feature is called anonymous types. Anonymous types provide crucial support for LINQ queries. With them, columns of data returned from a query can be represented as objects (more on this later). Anonymous types get compiled into class objects with read-only properties.

Let’s look at an example of how you would create an anonymous type. Suppose you want to create an object that had both a Name and a PhoneNumber property. However, you do not have such a class definition in your code. You could create an anonymous type declaration to do so as shown here:

VB
Dim emp = New With {.Name = “Joe Smith”, _
.PhoneNumber = “123-123-1234”}

C#
var emp = new { Name = “Joe Smith”,
PhoneNumber = “123=123=1234” };

Notice that the anonymous type declaration uses object initializers to define the object. The big difference is that there is no strong typing after the variable declaration or after the New keyword. Instead, the compiler will create an anonymous type for you with the properties Name and PhoneNumber.

There is also the Key keyword in Visual Basic. It is used to signal that a given property of an anonymous type should be used by the compiler to further define how the object is treated. Properties defined as Key are used to determine whether two instances of an anonymous type are equal to one another. C# does not have this concept. Instead, in C# all properties are treated like a VB Key property. In VB, you indicate a Key property in this way:

Dim emp = New With {Key .Name = “Joe Smith”, _
.PhoneNumber = “123-123-1234”}

You can also create anonymous types using variables (instead of the property name equals syntax). In these cases, the compiler uses the name of the variable as the property name and its value as the value for the anonymous type’s property. For example, in the following code, the Name variable is used as a property for the anonymous type:

VB
Dim name As String = “Joe Smith”
Dim emp = New With {name, .PhoneNumber = “123-123-1234”}

C#
string name = “Joe Smith”;
var emp = new {name, PhoneNumber = “123=123=1234” };

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

You can now add custom features to an existing type as if the type always had the custom features. In this way, you do not have to recompile a given object, nor do you have to create a second, derived object to add these features. Rather, you can add a method to an existing object by using a new compiler feature called extension methods.

Doing so is a bit different between VB and C#. In VB, you first import the
System.Runtime.CompilerServices namespace into your code file. Next, you mark a given Sub or Function with the <Extension()> directive. Lastly, you write a new Sub or Function with the first parameter of the new method being the type you want to extend. The following shows an example. In this example, we extend the Integer type with a new method called DoubleInSize:

VB

Imports System.Runtime.CompilerServices

Public Module IntegerExtensions
<Extension()> _
Public Function DoubleInSize(ByVal i As Integer) As Integer
Return i + i
End Function
End Module

The C# compiler does not require the same import or method attribute. Instead, you first create a static class. Next, you create a static method that you intend to use as your extension. The first parameter of your extension method should be the type you want to extend. Additionally, you apply the this modifier to the type. Notice the following example. In it, we extend the int data type with a new method called DoubleInSize.

C#

namespace IntegerExtensions {
public static class IntegerExtensions{
public static int DoubleInSize(this int i) {
return i+i;
}
}
}

To use an extension method, you must first import (using in C#) the new extension methods into a project. You can then call any new method as if it had always existed on the type. The following is an example in both VB and C#. In this case, a function called DoubleInSize that was added in the preceding example is being called from the Integer (int) class.

VB

Imports IntegerExtensions

Module Module1
Sub Main()
Dim i As Integer = 10
Console.WriteLine(i.DoubleInSize.ToString())
End Sub
End Module


C#
using IntegerExtensions;

namespace CsEnhancements {
class Program {
static void Main(string[] args) {
int i = 10;
Console.WriteLine(i.DoubleInSize().ToString());
}
}
}

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

There is now a shortcut for both declaring an instance of a class and setting the initial value of all or some of its members. With a single line of code, you can instantiate an object and set a number of properties on that object. During runtime, the object will first be created and then the properties will be set in the order in which they appear in the initialization list. This new feature is called object initializers.

Let’s look at an example. Suppose you have a class called Employee that has a number of properties like FirstName, LastName, FullName, Title, and the like. Using object initialization, you can both create an instance of this class and set the initial values of some (or all) of the Employee instance’s properties. To do so, you first construct the object. In Visual Basic, you follow this construction with the With keyword (C# does not require an equivalent indicator). You then place each property initialization inside a set of curly braces. Examples are as shown here:

C#

Employee emp = new Employee { FirstName = “Joe”,

LastName = “Smith”, Title = “Sr. Developer” };


VB

Dim emp As New Employee With {.FirstName = “Joe”, _

.LastName = “Smith”, .Title = “Sr. Developer”}

This single line of code is the equivalent of first creating an Employee class and then writing a line of code for each of the listed properties. Notice that in VB, you need to proceed the initialization using the With keyword; you also access each property using a dot. In C#, you do not need the dot or a keyword indicator.

Of course, you can also use object initialization with parameterized constructors. You simply pass the parameters into the constructor as you normally would. You then follow the constructor with the initialization. For example, suppose that the Employee class had a constructor that took the first and last name respectively. You could then create the object with the parameters and use object initialization for the Title as shown here:

C#

Employee emp = new Employee(“Joe”, “Smith”)

{ Title = “Sr. Developer” };


VB

Dim emp As New Employee(“Joe”, “Smith”) With _

{.Title = “Sr. Developer”}

Object initialization also allows you to write some code in the initialization. In addition, with VB you can use properties of the object you are initializing to help initialize other properties. This is not valid in C#. The C# compiler does not allow you to access the variable until the assignment is complete. To see an example of this, the following code initializes an Employee object and sets the Employee.FullName property by concatenating the first and last names. Notice that the VB code uses the object itself.

C#

Employee emp = new Employee { FirstName = “Joe”,

LastName = “Smith”, FullName = “Joe” + “ Smith”};


VB

Dim emp As New Employee() With {.FirstName = “Joe”, _

.LastName = “Smith”, _

.FullName = .FirstName & “ “ & .LastName}

You can also nest object initialization. That is, if a given property represents another object, you can create the other object as part of the initialization. You can also nest an initialization of the other object within the initialization of the first object. A simple example makes this clear. Suppose that the Employee class has a property called Location. The Location property may point to a Location object that includes the properties for City and State. You could then create the Employee object (along with the nested Location object) as shown here:

C#

Employee emp = new Employee { FirstName = “Joe”,

LastName = “Smith”, Location = new Location

{ City = “Redmond”, State = “WA” } };


VB

Dim emp As New Employee() With {.FirstName = “Joe”, _

.LastName = “Smith”, _

.Location = New Location With _

{.City = “Redmond”, .State = “Washington”}}


Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

In the latest versions of Visual Basic and C#, you can define variables without explicitly setting their data type. And, when doing so, you can still get the benefits of strongly typed variables (compiler checking, memory allocation, and more). The compilers have been improved to actually infer the data type you intend to use based on your code. This process is called local type inference, or implicit typing.

As an example, consider the following lines of code. Here you create a variable of type

String and assign a value.

C#

string companyName = “Contoso”;

VB

Dim companyName As String = “Contoso”

Now, let’s look at the same line of code using type inference. You can see that you do not need the string portion of the declaration. Instead, the compiler is able to determine that you want a string and strongly type the variable for you. In C#, this is triggered by the new keyword, var. This should not be confused with the var statement in languages such as JavaScript. Variables defined as var will be strongly typed. In VB, you still simply use the Dim statement but omit the data type.

C#

var companyName = “Contoso”;

VB

Dim companyName = “Contoso”

These two lines of code are equivalent in all ways. Although in the second example no data type was declared, one is being declared by the compiler. This is not a return to a generalized data type such as Variant or Object. Nor does this represent late-binding of the variable. Rather, it is simply a smarter compiler that strongly types the variable by choosing a data type based on the code. You get all the benefits of early-bound variables while saving some keystrokes.

There are a few things for you to be aware of when using type inference. The first is that it requires your local variable to be assigned a value in order to do the compiler typing. This should not be a big deal because if your variable is not assigned it is not used.

The second item you should consider is that type inference works only with local types. It does not work with class-level variables (also called fields) or static variables. In these cases, using local type inference will result in an error being thrown by the compiler in C#. In VB, you would get the same error provided that Option Strict is set to On. If you are not using Option Strict in your VB code, the variable will not be strongly typed. Instead, the variable will be assigned the generic, Object data type.

Local type inference can be useful in other declaration scenarios as well. This includes defining arrays, creating variables during looping, defining a variable inside a Using statement, and defining a variable that contains the result of a function call. In each of these cases, the compiler can infer your data type based on the context of the code. As another example, the following code creates a Using statement and infers the type of the variable cnn.

C#

using (var cnn = new System.Data.SqlClient.SqlConnection()) {

//code to work with the connection

}

VB

Using cnn = New System.Data.SqlClient.SqlConnection

‘code to work with the connection

End Using

In Visual Basic, you can turn local type inference off and on for a given file. By default, a new VB code file is set to allow type inference. However, if you want to turn it off at the file level, you can do so by setting Option Infer Off at the top of the code file.

.NET Language Additions in 2008

The .NET languages pick up a number of enhancements as a result of updates made to the Common Language Runtime (CLR). Although there are a few specific enhancements to Visual Basic and to C#, the big (and majority of) advancements made in 2008 apply to both languages. Therefore, we cover language enhancements as a group and provide examples in both languages. If a given addition is language specific, it will be indicated as such. The .NET language additions covered here include the following:

- Local Type Inference (also called Implicit Typing)

- Object Initializers

- Extension Methods

- Anonymous Types

- Lambda Expressions

- Partial Methods

- Language Integrated Query (LINQ)

- Friend Assemblies

- XML Language Support (VB only)

- Unused Event Arguments (VB only)

- Automatically Implemented Properties (C# only)

Many of these new language features serve to support an important new feature, Language Integrated Query (LINQ). However, each language feature is useful on its own and should be understood clearly.


Infer a Variable’s Data Type Based on Assignment

Create an Object and Set Its Properties with a Single Line of Code

Add Methods to Existing Classes

Create an Instance of a Nonexistent Class

Write Simple, Unnamed Functions Within Your Code

Add Business Logic to Generated Code

Access and Query Data Using the .NET Languages

Split an Assembly Across Multiple Files

Work with XML Directly Within Your Code

Remove Unused Arguments from Event Handlers (VB Only)

Create an Automatically Implemented Property (C# Only)

Most current .NET developers know that programming includes much more than just language. As a result, when a new edition is released, it is understood that it will include language enhancements, framework additions, and changes to the way you write code. Visual Studio 2008 is no different. It releases in step with the .NET Framework 3.5, VB 9, and C# 3.0. The below highlights some of the key IDE enhancements specific to your .NET language of choice.


VB IDE Enhancements

As in past versions of Visual Basic, the language is only a part of the story. Visual Basic is about both language and productivity tools. It’s worth noting some of the non language, but VB-specific, productivity enhancements that ship with the 2008 version. These are highlighted as listed here:

Improved IntelliSense—The latest version of VB has IntelliSense built-in everywhere, every time you type. Simply type a letter in the code window and the tool guesses (almost always right) at what you are trying to accomplish. The performance is also much improved over prior editions. In addition, VB has much stronger ToolTips to help you code.

VB Power Pack Controls—The VB team is working to add the RAD back into the language and reduce the shock of moving from VB 5/6 to the .NET version. Therefore, they have created off-cycle releases (between 2005 and 2008) of controls that provide additional productivity such as printing, line and shape, and a DataRepeater. In addition, they are committed to continuing to release power pack controls. For more info, search MSDN for “Visual Basic Power Packs.”

Refactor!— Microsoft has made it a key part of VB by striking a deal to offer the Refactor! product from DevExpress free to all licensed VB .NET developers. “Refactoring Code.” is primarily for the C# developers out there. With this deal, VB developers get a lot of existing and many new (2008 only) refactoring tools.

Interop Forms Toolkit—Microsoft continues to provide help to the developers out there still working with VB 6 code. The Interop Forms Toolkit is a new set of tools that allow you to keep your existing code in VB 6 and write new code for the same application using .NET. The toolkit provides interop support between the two environments so that you can begin using .NET without having to rewrite your entire application.


C# IDE Enhancements

The C# language takes another step forward in the 2008 release; the code writing and editing process is also improved with this recent release. Like VB, C# has some language-specific IDE features that aid in writing and editing code. These new features include the following:

Improved IntelliSense—The latest version of C# has an improved IntelliSense engine. This new version puts IntelliSense nearly everywhere you type. It includes statement completion, more helpful Quick Info ToolTips, and faster performance. In addition, the IntelliSense works with all the great new language features in C#. These include implicitly typed variables, extension methods, query expressions, lambda expressions, partial methods, and more.

Refactoring—Visual Studio 2005 introduced refactoring to the toolset of the C# developer. In 2008, the refactoring tools are extended to support the many new features of the language, including query expressions, extension methods, and lambda expressions. Renaming, extracting methods, and other refactoring tools work as well with these new features as they did with the previous C# language syntax. In addition, the refactoring tools now provide additional options and warnings to make sure you don’t end up with some unintended consequences when making changes to working code.

Code Formatting—The C# code editor continues to improve the formatting of your code and the control over how that formatting gets applied. For example, the formatting engine understands things like query expressions. When you write one, it will automatically line up keywords such as From and Where under one another to improve the readability of your code.

Organize Your Using Declarations—As your code ages, you might notice that the using declarations sometimes become a little unwieldy. The C# editor has a new feature to help you manage these declarations. There is now an Organize Usings menu option available from both the Edit menu and the context menu when you right-click on a using declaration. You can use the options on this menu to sort your using declarations by namespace and to clean your code of any unused usings declarations.


Source of Information : Sams Microsoft Visual Studio 2008 Unleashed


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner