Performing Explicit conversions

Keep in mind that even when you choose to allow implicit conversions, these are only allowed for a relatively small number of data types. At some point you'll need to carry out explicit conversions. The following code is an example of some typical conversions between different integer types when option Strict is enabled Dim myShort As Short Dim myUInt16 As UInt16 Dim myInt16 As Int16 Dim myInteger As Integer Dim myUInt32 As UInt32 Dim myInt32 As Int32 Dim myLong As Long Dim myInt64 As Int64...

Calling the stored Procedure

Calling the stored procedure is just a matter of creating a SqlConnection object to connect to the database, and a SqlCommand object to run the stored procedure. Now you have to decide what you want to return by calling the stored procedure. In this case, you return an instance of the SqlDataReader object. The TestForm.vb file contains a method called GetAuthorSqlReader that takes an author ID and returns an instance of a SqlDataReader. Here is the code for the method Private Function...

String Constants

If you ever have to produce output based on a string you'll quickly find yourself needing to embed certain constant values. For example, it's always useful to be able to add a carriage-return linefeed combination to trigger a new line in a message box. One way to do this is to learn the underlying ASCII codes and then embed these control characters directly into your String or StringBuilder object. Visual Basic provides an easier solution for working with these the...

Basic ADONET Namespaces and Classes

The core ADO.NET namespaces are shown in Table 10-1. In addition to these namespaces, each new data provider will have its own namespace. For example, the Oracle .NET data provider adds a namespace of System.Data.oracleClient for the Microsoft-built Oracle data provider . This namespace is the core of ADO.NET. It contains classes used by all data providers . Its classes represent tables, columns, rows, and the DataSet class. It also contains several useful interfaces, such as IDbCommand,...

Memory Management

This section looks at one of the larger underlying elements of managed code. One of the reasons why .NET applications are referred to as managed is that memory deallocation is handled automatically by the system. The CLR's memory management fixes the shortcomings of COM's memory management. Developers are accustomed to worrying about memory management only in an abstract sense. The basic rule has been that every object created and every section of memory allocated needs to be released destroyed...

summary Raq

This chapter introduced you to the concepts of both declarative programming and XAML as an implementation of a declarative programming language. As noted throughout the chapter, XAML focuses on information and the desired transformations to achieve results, whereas Visual Basic focuses more on implementing algorithms and custom logic for changes in state. XAML is used to define what you want as opposed to having you define what and how the system should do something. In the context of a new...

Recording and Using Macros in Visual Studio 2010

Visual Studio macros are part of the environment and are available to any language. Macro options are accessible from the Tools O Macros menu, as shown in Figure 1-38. The concept of macros is simple Record a series of keystrokes and or menu actions, and then play them back by pressing a certain keystroke combination. For example, suppose that one particular function call with a complex set of arguments is constantly being called on in code, and the function call usually looks the same except...

Parse and TryParse

Most value types, at least those which are part of the .NET Framework, provide a pair of shared methods called Parse and TryParse. These methods accept a value of your choosing and then attempt to convert this variable into the selected value type. The Parse and TryParse methods are only available on value types. Reference types have related methods called DirectCast and Cast, which are optimized for reference variables. The Parse method has a single parameter. This input parameter accepts a...

Implementing Late Binding

Late binding occurs when the compiler cannot determine the type of object that you'll be calling. This level of ambiguity is achieved using the Object data type. A variable of data type Object can hold virtually any value, including a reference to any type of object. Thus, code such as the following could be run against any object that implements a DoSomething method that accepts no parameters Public Sub DoWork ByVal obj As Object obj.DoSomething End Sub End Module If the object passed into...

server Explorer

As development has become more server-centric, developers have a greater need to discover and manipulate services on the network. Visual InterDev, used for building classic ASP web sites, and which was available around the same time as Visual Basic 6, started in this direction with a Server Object section in the InterDev Toolbox. The Server Explorer feature in Visual Studio takes this concept and makes working with servers easier. The Server Explorer is more sophisticated in that it enables you...

Team Foundation server TFs

The server components of Visual Studio Application Lifecycle Management ALM are not automatically integrated into Visual Studio, but it is appropriate to mention a couple of key attributes of TFS that extend it beyond VSS. Similar to VSS, the primary role most developers see for TFS is that of source control. This is the capability to ensure that if multiple people are working on the same project and with the same set of source files, then no two of them can make changes to the same file at the...

A CheckedListBox Limiting selected Items

This example inherits the built-in CheckedListBox control and extends its functionality. If you are not familiar with this control, it works just like a normal ListBox control except that selected items are indicated with a check in a check box at the front of the item, rather than by highlighting the item. To extend the functionality of this control, the example includes the creation of a property called MaxItemsToSelect. This property holds a maximum value for the number of items that a user...

DECLARATIVE PROGRAMMING AND VISuAL BASIC

In any discussion of declarative programming, it is probably best to first consider to what it is being compared. Visual Basic, like most modern OOP languages C , C C , F , etc. , is not primarily a declarative language. It is what is known as a procedural or imperative language. This reflects that developers in these languages focus on how to get the computer to complete a task. These languages are powerful, and declarative programming isn't going to completely replace them. However, they work...

packaging logic in visual controls

There are four primary sources of controls for use on Windows Forms interfaces V Controls packaged with the .NET Framework referred to in this chapter as built-in controls V Existing ActiveX controls that are imported into Windows Forms These are briefly discussed in Chapter 30. V Third-party .NET-based controls from a software vendor V Custom controls that are created for a specific purpose in a particular project or organization If you can build your application with controls from the first...

common ADONET Tasks

Before jumping into the depths of ADO.NET, step back and make sure that you understand some of the common tasks you might perform programmatically within ADO.NET. This section looks at the process of selecting, inserting, updating, and deleting data. For all of the data-access examples in this chapter, you need the pubs database. As of this writing, you can find this link at www.microsoft.com downloads details Once installed, you will find the pubs.mdf file in the C SQL Server 2000 Sample...

Querying Static XML Documents

Notice that querying a static XML document using LINQ to XML takes almost no work at all. The following example makes use of the hamlet.xml file, querying for all the players actors who appear in a play. Each of these players is defined in the XML document with the lt PERSONA gt element Dim xdoc As XDocument Dim query From people In xdoc.Descendants PERSONA _ Select people.Value Using LiNQ to Query XML Documents 381 Console.WriteLine 0 Players Found, query.Count Console.WriteLine Press ENTER to...

Raster Graphics And Vector Graphics

Currently, when you create a Windows Forms control you decide how large, in pixels, that button should be. A similar action is taken with regard to HTML forms, where you can specify either a size in pixels or a percentage of the screen. In both cases, the computer simply lays out a square or rounded square based on a flat set of pixels. It does the same with other images you use, working with what are known as raster graphics. Raster graphics are a collection of points on the surface of a...

The DBNull Class and isDBNull Function

When working with a database, a value for a given column may not be defined. For a reference type this isn't a problem, as it is possible to set reference types to Nothing. However, for value types, it is necessary to determine whether a given column from the database or other source has an actual value prior to attempting to assign a potentially null value. The first way to manage this task is to leverage the DBNull class and the IsDBNull function. This class is part of the system namespace,...

Retrieving Data using LiNQ to SQL Creating the Console Application

To illustrate using LINQ to SQL, the LinqReading example begins by calling a single table from the pubs database and using this table to populate some results to the screen. The next step is to add a LINQ to SQL class. When working with LINQ to SQL, one of the big advantages is that Visual Studio does an outstanding job of making it as easy as possible. Visual Studio provides an object-relational mapping designer, called the Object Relational Designer O R Designer , that enables you to visually...

other Methods and Properties of the DataContext object

In addition to the items just described, several other methods and properties are available from the DataContext object. Table 10-4 shows some of the available methods from DataContext. TABLE 10-4 Partial List of DataContext Methods GetCommand GetTable Refresh SubmitChanges Enables you to create a database on the server Enables you to determine whether a database exists and can be opened Deletes the associated database Enables you to pass in a command to the database to be executed Enables you...

creating userDefined Types

One feature of SQL Server that does not usually get the attention it deserves is the capability to create user-defined types UDTs . These enable developers to define new data types that may be used in columns, functions, stored procedures, and so on. They can make database development easier by applying specific constraints to values, or simply to better identify the intent of a column. For example, when presented with a table containing a column of data type varchar 11 , you may still be...

TableLayoutPanel Control

Another control that uses dynamic layout of child controls is the TableLayoutPanel. This control consists of a table of rows and columns, resulting in a rectangular array of cells. You can place one control in each cell. However, that control can itself be a container, such as a Panel or FlowLayoutPanel. You can control the dimensions of the columns and rows by setting some key properties. For columns, set the number of columns with the ColumnCount property, and then control each individual...

Validating Data Entry

Most controls that you place on a form require that its content be validated in some way. A TextBox might require a numeric value only or simply require that the user provide any value and not leave it blank. The ErrorProvider component discussed earlier makes this task significantly easier than it was in previous versions. To illustrate the use of an ErrorProvider in data validation, create a new Windows Application project and change the Text property for the blank Forml to Data Validation...

figure 127

When an error occurs during debugging, your first thought is likely to be What just happened But how do you reproduce that error As indicated in Figure 1-27, the IntelliTrace window tracks the steps you have taken in this case showing that I had used the Run Code button a second time since the steps shown in Figure 1-26. By providing a historical trail, IntelliTrace enables you to reproduce a given set of steps through your application. You can also filter the various messages either by message...

Visual Studio 2010 Express Through Ultimate

For those who aren't familiar with the main elements of .NET development there is the common language runtime CLR , the .NET Framework, the various language compilers and Visual Studio. Each of these plays a role, for example the CLR covered in Chapter 4 manages the execution of code on the .NET platform. Thus code can be targeted to run on a specific version of this runtime environment. The .NET Framework provides a series of classes that developers leverage across implementation languages....

Intellisense Code expansion and Code snippets

One of the reasons why Microsoft Visual Studio is such a popular development environment is because it was designed to support developer productivity. That sounds really good, but let's back it up. People who are unfamiliar with Visual Studio might just assume that productivity refers to organizing and starting projects. Certainly, as shown by the project templates and project settings discussed so far, this is true, but those features don't speed your development after you've created the...

events Methods and Properties

Table 6-4 describes the relevant event of the EventLog component. EntryWritten Generated when an event is written to a log Table 6-5 describes the relevant methods of the EventLog component. TABLE 6-5 Relevant EventLog Methods createEventSource Creates an event source in the specified log DeleteEventSource Deletes an event source and associated entries writeEntry Writes a string to a specified log Exists Used to determine whether a specific Event Log exists SourceExists Used to determine...

adonet architecture

The main design goals of ADO.NET are as follows V Customer-driven features that are still backwardly compatible with ADO.NET 1.x V Improving performance on your data-store calls V Providing more power for power users V Taking advantage of SQL Server-specific features ADO.NET addresses a couple of the most common data-access strategies used for applications today. When classic ADO was developed, many applications could be connected to the data store almost indefinitely. Today, with the explosion...

Creating a Toolstrip and Adding Toolbar Elements

Imagen Name Toolstripcontainer

Try an example to see how to build a toolbar using the ToolStrip control. Create a new Windows application. Add a ToolStrip control to the blank Form1 that is included with the new project. Make the form about twice its default width so that you have plenty of room to see the ToolStrip as you work on it. The ToolStrip is positioned at the top of the form by default. It does not contain any elements, although if you highlight the ToolStrip control in the component tray, a menu designer will...

Using Multiple Tables for an Object

Alternately, there are instances when you would like to store parts of a single entity on different tables. This is typically when you know that only some of the records in a database will need certain fields and you prefer a more normalized database. For example, if you are creating a contact management application, you will have some fields that every record will contain, such as FirstName, LastName, etc. However, some of the contacts may have additional properties, such as a BirthDate,...

Executing Commands Asynchronously

In ADO.NET, additional support enables Command objects to execute their commands asynchronously, which can result in a huge perceived performance gain in many applications, especially in Windows Forms applications. This can come in very handy, especially if you ever have to execute a long-running SQL statement. This section examines how this functionality enables you to add asynchronous processing to enhance the responsiveness of an application. The SqlCommand object provides three different...

Using the Generate from Usage Feature

Visual Studio 2010 adds a very exciting testing feature the capability to create your classes from the tests. This enables you to do pure test-first development, without the actual effort of creating the structure of your classes after you have tested them. Using this method, you leverage IntelliSense to create the basic structure of the tested code while writing your tests. Initially, these tests will fail, as the tested class does not have any functionality. You then edit your class to add...

Class Diagrams

One of the features introduced with Visual Studio 2005 was the capability to generate class diagrams. A class diagram is a graphical representation of your application's objects. By right-clicking on your project in the Solution Explorer, you can select View Class Diagram from the context menu. Alternatively, you can choose to Add a New Item to your project. In the same window where you can add a new class, you have the option to add a new class diagram. The class diagram uses a .cd file...

Reviewing the Reference

You've now added a Service References folder to your project, which contains the proxy details for your Calculator service. This proxy is a collection of files, as shown in Figure 13-10. Note that you'll need to show all the files in order to see the files shown in Figure 13-10. Solution 'ProVB_WCFCalculatorLibrary' 3 proj V amp ProVB ServiceHost t gt 3 1 My Project V d References j amp Service References ft CalculaterService configuration.svcinfo tf configu rations l.svcinfo J 'G...

entity framework architecture

Figure 11-1 shows the architecture used within the Entity Framework. As you can see from the diagram, the Entity Framework is composed of a number of logical layers. The lowest layer is related to the actual data access, and involves the familiar ADO.NET data providers. This should be expected from the earlier description of the Entity Framework not as an entirely new method of retrieving data, but as an extension of your existing knowledge of ADO.NET. The additional layers are intended to make...

Building a service with a Data Contract

For an example of working with data contracts, you can create a new WCF service again within a Console Application project called ProVB_WCFWithDataContract. As with the other samples this solution is available as part of the online code download. In this case, you still need an interface that defines your service contract, and then another class that implements that interface. In addition to these items, you need another class that defines the data contract. Like the service contract, which...

HOSTiNG WiNDOWS FORMS CONTROLS iN WPF

In the case of WPF hosting Windows Forms controls, you might choose to do this if you have an existing application that relies on certain controls that have not yet been implemented in WPF. For example, the following table lists some of the controls that are not directly supported in WPF In addition to these controls that aren't directly supported, still other controls may behave differently in this release. For example, the ComboBox control in WPF doesn't provide built-in support for...

working with the common provider model

In ADO.NET 1.x, you could code to either the provider-specific classes, such as SqlConnection, or the generic interfaces, such as IDbConnection. If there was a possibility that the database you were programming against would change during your project, or if you were creating a commercial package intended to support customers with different databases, then you had to use the generic interfaces. You cannot call a constructor on an interface, so most generic programs included code that...

xaml syntax

The ProVB_XAML example doesn't have much purpose yet, but it makes it easier to keep the discussion of XAML in context. The next step is to take a more detailed look at just what XAML is and how it relates to WPF. XAML is a markup-based protocol. Similar to SOAP and several other XML-based formats, the XAML specification describes a potentially open standard for describing user interface elements. Regardless of whether XAML ever actually becomes an open standard, Microsoft has implemented WPF...

Versioning And Deployment

Components and their clients are often installed at different times by different vendors. For example, a Visual Basic application might rely on a third-party grid control to display data. Runtime support for versioning is crucial for ensuring that an incompatible version of the grid control does not cause problems for the Visual Basic application. In addition to this issue of compatibility, deploying applications written in previous versions of Visual Basic was problematic. Fortunately, .NET...

Hosting the WCF service in a Console application

The next step is to take the service just developed and host it in some type of application process. You have many available hosting options, including the following V Windows Presentation Foundation applications V Internet Information Services IIS 5.1 V Internet Information Services IIS 6.0 V Internet Information Services IIS 7.0 and the Windows Activation Service WAS As stated earlier, this example hosts the service in a simple console application. There are a couple of ways to activate...

Creating an MDI Parent form

In Windows Forms, a regular form is converted to an MDI parent form by setting the IsMdiContainer property of the form to True. This is normally done in the Properties window at design time. A form can also be made into an MDI parent at runtime by setting the IsMdiContainer property to True in code, but the design of an MDI form is usually different from that of a normal form, so this approach is not often needed. You cannot have both Autoscroll and IsMdiContainer set to True at the same time....

Using TryCast

A method similar to DirectCast is TryCast. TryCast converts values of one type into another type, but unlike DirectCast, if it can't do the conversion, then TryCast doesn't throw an exception. Instead, TryCast simply returns Nothing if the cast can't be performed. TryCast only works with reference values it cannot be used with value types such as Integer or Boolean. Using TryCast, you can write code like this Public Sub TryCast1 ByVal obj As Object Dim temp TryCast obj, Object If temp Is...

Showing Forms via Sub Main

If you do not wish to use the default way to load your Windows Forms application, you can take explicit control of the startup process in code. You might do this, for example, because you have logic you must run for authentication before the first form is loaded. To take control of the startup process, first create an empty subroutine named Sub Main in a code module. If your project does not yet contain a code module, you may need to create one. Code modules are discussed in Chapter 2. Uncheck...

Using Xaml To Declare A Workflow

In .NET 3.0 and 3.5, XAML was fairly tightly coupled to WPF. Starting with .NET 4.0 and beyond, Microsoft has placed a major focus on decoupling these two items and having the XAML syntax used across multiple different areas, for example WPF, WF, and WCF. After all, what better way to illustrate a complex workflow or interface than to create a XAML markup that defines the key interface elements for a WCF endpoint or to define the meta data when binding to data With .NET Framework 4, the XAML...

openFileDialog and saveFileDialog

These two controls open the standard dialog control that enables users to select files on the system. They are quite similar except for the buttons and labels that appear on the actual dialog box when it is shown to the user. Each prompts the user for a file on the system by allowing the user to browse the files and folders available. Use the properties described in Table 14-6 to set up the dialogs. TABLE 14-6 Important Properties of the OpenFileDialog and SaveFileDialog Controls...

Writing to Trace Files

As an alternative to the event log, you can write your debugging and error information to trace files. A trace file is a text-based file that you generate in your program to track detailed information about an error condition. Trace files are also a good way to supplement your event logging if you want to track detailed information that would potentially fill the Event Log, or diagnosis of a problem requires analysis of a specific sequence of execution events. This section covers using the...

Conceptual Model

Your Entity Framework applications deal directly with the conceptual models you either generate or create. To see how these are constructed, create a simple console application SimpleEF and add an ADO.NET Entity Data Model to the application by selecting Project O Add New Item see Figure 11-2 . When you add an Entity Framework model to your application, it starts a wizard to generate the classes. The first step is to decide if you will generate your classes initially from a database or from a...

An MDi Example in VB 2010

To see these changes to MDI forms in action, try the following exercise. It shows the basics of creating an MDI parent and having it display an MDI child form 1. Create a new Windows application. It will have an empty form named Forml. Change both the name of the form and the form's Text property to MDIParentForm. 2. In the Properties window, set the IsMDIContainer property for MDIParentForm to True. This designates the form as an MDI container for child windows. Setting this property also...

connecting to a sQL server compact database

As with other editions of SQL Server, the key to connecting to a SQL Server Compact database is in the connection string. However, because SQL Server Compact does not have the same features in terms of server and integrated security, different options are used to connect to the database, the most important of which are described in Table 12-1. Only the data source and password values can be set within the IDE. table 12-1 SQL Server Compact Connection Options Provider name...