Composite Usercontrol

Our earlier example showed inheriting an existing control, which was the first of the three techniques for creating custom controls. The next step up in complexity and flexibility is to combine more than one existing control to become a new control. This is similar to the process of creating a UserControl in VB6, but it is easier to do in Windows Forms. The main steps in the process of creating a UserControl are as follows 1. Start a new Windows Control Library project and assign names to the...

Contents

CHAPTER 1 VISUAL STUDIO 2010 3 Visual studio 2010 Express through Ultimate 4 Visual Basic Keywords and syntax 7 Creating a Project from a Project Template 11 Additional Components for Visual Studio 39 enhancing a sample Application 40 Reusing Your First Windows Form 52 Useful Features of Visual studio 2010 54 Recording and Using Macros in Visual Studio 2010 58 Application Lifecycle Management 61 cHAPTER 2 objects AND VisuAL BAsic 67 Objects, Classes, and Instances 68 Working With Visual Basic...

The My KeywoRD

The My keyword is a novel concept that was introduced in the .NET Framework 2.0 to quickly give you access to your application, your users, your resources, the computer, or the network on which the application resides. The My keyword has been referred to as a way of speed-dialing common but complicated resources to which you need access. Using the My keyword, you can quickly access a wide variety of items, such as user details or specific settings of the requester browser. Though not really...

Form Properties Set in Code

As noted earlier, Visual Studio keeps every object's custom property values in the source code. To do this, it adds a method to your form class called InitializeComponent. As the name suggests, this method handles the initialization of the components contained on the form. A comment before the procedure warns you that the Form Designer modifies the code contained in the procedure, and that you should not modify the code directly. This module is part of the Form1.Designer.vb source file, and...

Creating a subclass

To implement inheritance, you need to add a new class to your project. Use the Project O Add Class menu option and add a new class named Employee.vb. Begin with the following code Public Property Salary() As Double End Class This is a regular standalone class with no explicit inheritance. It can be represented by the class diagram shown in Figure 3-3. Again, you can see the class name, its list of instance variables, and the properties it includes as part of its interface. It turns out that,...

Adding Controls at Runtime

You may add controls to a form at runtime. Here is an example that enhances the preceding program to add a third button dynamically at runtime. Add another button to your form that will trigger the addition of Button3, as shown in Figure 14-27. Name the new button AddNewButton and add the following code to handle its Click event Private Sub AddNewButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles addNewButton.Click Dim newButton As Button ' Create the new control...

Document object Model DoM

The Document Object Model (DOM) is a logical view of an XML file. Within the DOM, an XML document is contained in a class named XmlDocument. Each node within this document is accessible and managed using XmlNode. Nodes can also be accessed and managed using a class specifically designed to process a specific node's type (XmlElement, XmlAttribute, and so on). XML documents are extracted from XmlDocument using a variety of mechanisms exposed through such classes as XmlWriter, TextWriter, Stream,...

Termination and cleanup

In the .NET environment, an object is destroyed and the memory and resources it consumes are reclaimed when there are no references remaining for the object. As discussed earlier in the chapter, when you are using objects, the variables actually hold a reference or pointer to the object itself. If you have code such as you know that the myPerson variable is just a reference to the Person object you created. If you also have code like Dim anotherPerson As Person anotherPerson myPerson you know...

The Inner Exception and Targetsite Properties

The InnerException property is used to store an exception trail. This comes in handy when multiple exceptions occur. It's quite common for an exception to occur that sets up circumstances whereby further exceptions are raised. As exceptions occur in a sequence, you can choose to stack them for later reference by use of the InnerException property of your Exception object. As each exception joins the stack, the previous Exception object becomes the inner exception in the stack. For simplicity,...

Char and Byte

The default character set under Visual Basic is Unicode. Therefore, when a variable is declared as type Char, Visual Basic creates a two-byte value, since, by default, all characters in the Unicode character set require two bytes. Visual Basic supports the declaration of a character value in three ways. Placing a c following a literal string informs the compiler that the value should be treated as a character, or the Chr and Chrw methods can be used. The following code snippet shows that all...

Build Configurations

Prior to .NET, a Visual Basic project had only one set of properties. There was no way to have one set of properties for a debug build and a separate set for a release build. As a result, you had to manually change any environment-specific properties before you built the application. This has changed with the introduction of build configurations, which enable you to have different sets of project properties for debug and release builds. Visual Studio does not limit you to only two build...

Using XML with Visual Basic

V Learn the rationale behind XML V Learn about the namespaces within the .NET Framework Class Library that deal with XML and XML-related technologies V Look at some of the classes contained within these namespaces V How to use LINQ to XML to read and edit XML V How Visual Basic enables the use of XML literals within your code V Learn how lambdas are used with Visual Basic and LINQ V How you can create your own lambda expressions to create more generic code This chapter describes how you can...

Error logging

Error logging is important in many applications for thorough troubleshooting. It is common for end users of an application to forget exactly what an error said. Recording specific errors in a log enables you to get the specific error message without recreating the error. While error logging is very important, you only want to use it to trap specific levels of errors because it carries overhead and can reduce the performance of your application. Specifically, log only errors that are critical to...

Writing to an XML Document

In addition to reading from an XML document, you can also write to the document just as easily. For instance, if you wanted to change the name of the first player of the hamlet file, you could make use of the code here to accomplish that task Dim xdoc As XDocument XDocument.Load(hamlet.xml) _ deBar, King of Denmark) _ Console.ReadLine() End Sub End Module In this case, the first instance of the < PERSONA> element is overwritten with the value of Foo deBar, King of Denmark using the SetValue...

Shared Constructor

A class can also have a shared constructor Normal constructors are called when an instance of the class is created. The shared constructor is called only once during the lifetime of an application, immediately before any use of the class. This means that the shared constructor is called before any other shared methods, and before any instances of the class are created. The first time any code attempts to interact with any method on the class, or attempts to create an instance of the class, the...

DoNET components

To better support the disconnected model as defined above, the ADO.NET components separate data access from data manipulation. This is accomplished via two main components the DataSet and the .NET data provider. Figure 10-1 illustrates the concept of separating data access from data manipulation. The DataSet is the core component of the disconnected architecture of ADO.NET. It is explicitly designed for data access independent of any data source. As a result, it can be used with multiple and...

When to Use Inheritance

Inheritance is one of the most powerful object-oriented features a language can support. At the same time, inheritance is one of the most dangerous and misused object-oriented features. Properly used, inheritance enables you to increase the maintainability, readability, and reusability of your application by offering you a clear and concise way to reuse code, via both interface and implementation. Improperly used, inheritance creates applications that are very fragile, whereby a change to a...

The Solution Explorer

The Solution Explorer is a window that is by default located on the right-hand side of your display when you create a project. It is there to display the contents of your solution and includes the actual source file(s) for each of the projects in your solution. While the Solution Explorer window is available and applicable for Express Edition users, it will never contain more than a single project. Those with a version of Visual Studio above the Express Edition level have the capability to...

The Preserve Keyword

The last item in the code snippet in the preceding section illustrates an additional keyword associated with redimensioning. The Preserve keyword indicates that the data stored in the array prior to redimensioning should be transferred to the newly created array. If this keyword is not used, then the data stored in an array is lost. Additionally, in the preceding example, the ReDim statement actually reduces the second dimension of the array. Although this is a perfectly legal statement, this...

The authors

BILL SHELDoN is a software architect and engineer originally from Baltimore, Maryland. Holding a degree in computer science from the Illinois Institute of Technology (IIT), Bill has been actively employed as a software engineer since resigning his commission with the United States Navy. He is a Microsoft MVP for Visual Basic employed in Carlsbad, California. Bill also works as an instructor for .NET courses at the University of California San Diego Extension. In addition to writing books, Bill...

Early Binding versus Late Binding

One of the strengths of Visual Basic has long been that it provides access to both early and late binding when interacting with objects. Early binding means that code directly interacts with an object by directly calling its methods. Because the Visual Basic compiler knows the object's data type ahead of time, it can directly compile code to invoke the methods on the object. Early binding also enables the IDE to use IntelliSense to aid development efforts by enabling the compiler to ensure that...

Custom objects

WHAT you WILL LEARN IN THis CHAPTER_ > Event Handling in Sub Classes > Creating Abstract Base Class Visual Basic is a fully object-oriented language. Chapter 2 covered the basics of creating classes and objects, including the creation of methods, properties, events, operators, and instance variables. You have seen the basic building blocks for abstraction, encapsulation, and polymorphism concepts discussed in more detail at the end of this chapter. The final major techniques you need to...

Nested Try Structures

Sometimes particular lines in a Try block may need special exception processing. Moreover, errors can occur within the Catch portion of the Try structures and cause further exceptions to be thrown. For both of these scenarios, nested Try structures are available. You can alter the example under the section The Throw Keyword to demonstrate the following code Private Function GetAverage6(iItems As Integer, iTotal as Integer) As Single ' Code that might throw an exception is wrapped in a Try...

Namespaces

Even if you did not realize it, you have been using namespaces since the beginning of this book. For example, System, System.Diagnostics, and System.Windows.Forms are all namespaces contained within the .NET Framework. Namespaces are an easy concept to understand, but this chapter puts the ideas behind them on a firm footing and clears up any misconceptions you might have about how they are used and organized. If you are familiar with COM, you will find that the concept of namespaces is the...

Overloading Methods

Methods often accept parameter values. The Person object's Walk method, for instance, accepts an Integer parameter Public Sub Walk(ByVal distance As Integer) mTotalDistance + distance RaiseEvent Walked(distance) End Sub Sometimes there is no need for the parameter. To address this, you can use the Optional keyword to make the parameter optional Public Sub Walk(Optional ByVal distance As Integer 0) mTotalDistance + distance RaiseEvent Walked(distance) End Sub This does not provide you with a lot...

Objects and Visual Basic

WHAT you WILL LEARN IN THis cHAPTER_ V Characteristics of Value Types versus Reference Types V Commands If Then, Else, Select Case V Common Value Types (Structures) V Common Reference Types (Classes) V Parameter passing ByVal and ByRef V Advanced Object Oriented Programming Visual Basic supports the four major defining concepts required for a language to be fully V Abstraction Abstraction is merely the ability of a language to create black box code, to take a concept and create an abstract...

Value and reference Types

Experienced developers generally consider integers, characters, Booleans, and strings to be the basic building blocks of any language. As noted above in .NET, all objects share a logical inheritance from the base Object class. One of the advantages of this common heritage is the capability to rely on certain common methods of every variable. Another is that this enables all of .NET to build on a common type system. Visual Basic builds on the common type system shared across .NET languages....

The object Class

As noted earlier, the Object class is the base class for every type in .NET, both value and reference types. At its core, every variable is an object and can be treated as such. Because the Object class is the basis of all types, you can cast any variable to an object. Reference types maintain their current reference and implementation but are generically handled, whereas value types are taken from their current location on the stack and placed into the heap with a memory location associated...

Xsl transformations

XSLT is used to transform XML documents into another format altogether. One popular use of XSLT is to transform XML into HTML so that XML documents can be presented visually. The idea is to use an alternate language (XSLT) to transform the XML, rather than rewrite the source code, SQL commands, or some other mechanism used to generate XML. Conceptually, XSLT is straightforward. A file (a .xsl file) describes the changes (transformations) that will be applied to a particular XML file. Once this...

Operator Overloading

Many basic data types, such as Integer and string, support the use of operators, including +, -, , < > , and so forth. When you create a class, you are defining a new type, and sometimes it is appropriate for types to also support the use of operators. In your class, you can write code to define how each of these operators works when applied to objects. What does it mean when two objects are added together Or multiplied Or compared If you can define what these operations mean, you can write...

Creating a Test

Using the Test Project template, add a new project named Foo.Math.Tests to the solution, as shown in Figure 7-4. This will add a single class, UnitTest1.vb, to your solution (renamed to AverageTests.vb in Figure 7-5). Delete that class for now, as you will add your own in a moment. In addition, three solution items are added these enable configuring how the testing will run. You will look at these later. For now, add a reference to the Foo.Math project. .NETFramework4 Sort by Name Ascending - '...

UiLDiNg A Control From Scratch

If your custom control needs to draw its own interface, you should use the Control class as your starting point. Such a control gets a fair amount of base functionality from the Control class. A partial list of properties and methods of the Control class was included earlier in the chapter. These properties arrange for the control to automatically have visual elements such as background and foreground colors, fonts, window size, and so on. However, such a control does not automatically use any...

Project Properties

Visual Studio uses a vertically tabbed display for editing your project settings. The project properties display shown in Figure 1-5 provides access to the newly created ProVB_VS2010 project settings. The project properties window gives you access to several different aspects of your project. Some, such as Signing, Security, and Publish, are covered in later chapters. For now, just note that this display makes it easier to carry out several tasks that once required engineers to work outside the...

Shared Methods Variables and Events

So far, all of the methods you have built or used have been instance methods, methods that require you to have an actual instance of the class before they can be called. These methods have used instance variables or member variables to do their work, which means that they have been working with a set of data that is unique to each individual object. With Visual Basic, you can create variables and methods that belong to the class, rather than to any specific object. In other words, these...

Figure 143

In fact, the tool doesn't actually look at your source code. Instead, it uses reflection and once your project has been compiled, it queries the MSIL code your project generates. While this may seem surprising, remember that this tool is looking for several best practices, which may be implemented in different ways in your source code but will always compile in a standard manner. Figure 1-43 shows the optional Code Analysis screen. Note that even when you have the code analysis tools available,...

Abstraction

Abstraction is the process by which you can think about specific properties or behaviors without thinking about a particular object that has those properties or behaviors. Abstraction is merely the ability of a language to create black box code, to take a concept and create an abstract representation of that concept within a program. A Customer object, for example, is an abstract representation of a real-world customer. A DataSet object is an abstract representation of a set of data....

Objects Declaration and Instantiation

Objects are created using the New keyword, indicating that you want a new instance of a particular class. There are numerous variations on how or where you can use the New keyword in your code. Each one provides different advantages in terms of code readability or flexibility. The most obvious way to create an object is to declare an object variable and then create an instance of the object Dim obj As TheClass obj New TheClass The result of this code is that you have a new instance of TheClass...

Lambda Expressions In Visual Basic

While not specifically an XML feature, Visual Basic includes support for lambda expressions. These can be quite handy when dealing with XML, or other code that requires some function to be executed repeatedly. Lambda expressions are at first glance similar to functions. You declare them with the System.Func generic, and then execute them as needed Dim Square As Func of Integer, Integer Function x As Integer x A 2 Dim value As Integer 42 Console.WriteLine Square value This example creates a new...

Using GDI Capabilities in a Windows Form

Here is an example of a form that uses the System.Drawing.Graphics class to draw some graphic elements on the form's surface. The example code runs in the Paint event for the form, and draws an ellipse, an icon which it gets from the form itself , and two triangles one in outline and one filled. Start a Windows Application project in VB 2010. On the Forml that is automatically created for the project, place the following code in the Paint event for the form ' Need a pen for the drawing. We'll...

The xmlData Source controls Namespace Problem

One big issue with using the XmlDataSource control is that when using the XPath capabilities of the control, it is unable to understand namespace-qualified XML. The XmlDataSource control chokes on any XML data that contains namespaces, so it is important to yank out any prefixes and namespaces contained in the XML. To make this a bit easier, the XmlDataSource control includes the TransformFile attribute. This attribute takes your XSLT transform file, which can be applied to the XML pulled from...

WPF Desktop Applications

WHAT YOU WILL LEARN IN THIS CHAPTER_ gt Creating a WPF application gt Implementing a custom WPF application gt Customizing the user interface Windows Presentation Foundation WPF previously known as Avalon is the next-generation presentation library and development paradigm for user interfaces. It was introduced with Windows Vista as a key architectural component in the .NET 3.0 Framework. This chapter introduces you to the WPF programming model and discusses key elements you'll need to know in...

Other Debug Related Windows

As noted earlier, when you run an application in Debug mode, Visual Studio .NET 2010 can open a series of windows related to debugging. Each of these windows provides a view of a limited set of the overall environment in which your application is running. From these windows, it is possible to find things such as the list of calls stack used to get to the current line of code or the present value of all the variables currently available. Visual Studio has a powerful debugger that is fully...

Creating Stored Procedures

Just as with user-defined types and functions, you identify methods as being stored procedures with an attribute. In the case of stored procedures, this is Microsoft.SqlServer.Server .SqlProcedureAttribute. This attribute is basically a marker attribute no additional parameters have any dramatic effect on the behavior of the code. When creating a stored procedure in Visual Basic, you should keep a few considerations in mind. First, and likely most important, is the context. Your code is no...

Removing the frame

Removing the Windows frame from your application is actually fairly easy to do, as you only need to set two properties on your form. The first is WindowStyle, which is set to None the second is AllowTransparency, which is set to True. You can accomplish that by adding the following line before the closing bracket of your window attributes WindowStyle None AllowsTransparency True Once you've added this line to your XAML, run the application in the debugger. This is a good point to test not only...

Writing an XML Stream

An XML document can be created programmatically in .NET. One way to perform this task is by writing the individual components of an XML document schema, attributes, elements, and so on to an XML stream. Using a unidirectional write-stream means that each element and its attributes must be written in order the idea is that data is always written at the end of the stream. To accomplish this, you use a writable XML stream class a class derived from Xmlwriter . Such a class ensures that the XML...

Control Tab Order

The VS 2010 design environment enables you to set the tab order of the controls on a form simply by clicking them in sequence. To activate the feature, open a form in the designer and select View O Tab Order. This will place a small number in the upper-left corner of each control on your form, representing the tab index of that control. To set the values, simply click each control in the sequence you want the tab flow to operate. Figure 14-5 shows a simple form with the tab order feature...

Using xaml to create a window

Since the most common way to interact with XAML is as a Windows definition language, let's create a simple window definition to put some of what we'll discuss in context. Most early WPF applications were built by hand or with tools such as XAMLpad that could output graphics as well as XAML. With the release of Visual Studio 2008, WPF, like the other .NET 3.0 technologies, gained a true IDE and with the availability of Blend, a powerful design tool. The focus for WPF is now on creating...

Using a Mapped Property of a WPF Control

There are a couple of potential solutions to this problem however, for the purposes of this chapter, which focuses on demonstrating the features of the Windows Forms Integration library, the solution described here uses a mapped property on your control. The capability to access the mapped properties of WPF controls is one of the features of this library that provides you with greater flexibility. One of the available properties on control ElementHostl, the PropertyMap collection, enables you...

Extending the my namespace

You are not limited to only what the My namespace provides. Just as you can with other namespaces, you can extend this namespace until your heart is content. To show an example of extending the My namespace so that it includes your own functions and properties, in your Windows Forms application, create a new module called CompanyExtensions.vb. The code for the entire module and the associated class is presented here lt HideModuleName gt _ Module CompanyOperations Private _CompanyExtensions As...

XSLT Transforming between XML Standards

The first example used four XSLT elements to transform an XML file into an HTML file. Such an example has merit, but it doesn't demonstrate an important use of XSLT transforming XML from one standard into another standard. This may involve renaming elements attributes, excluding elements attributes, changing data types, altering the node hierarchy, and representing elements as attributes, and vice versa. Returning to the example, a case of differing XML standards could easily affect your...

User Controls Combining WPF and Windows Forms

WHAT YOU WILL LEARN IN THIS CHAPTER_ V The Windows Forms Integration Library V Using WPF controls in Windows Forms V Using Windows Forms controls in WPF V Integration library limitations Chapter 15 looked at advanced features of Windows Forms. One of these features goes well beyond Windows Forms user controls. User controls are used in Windows Forms, ASP.NET, WPF, and Silverlight. The concepts around user controls reflect a best practice for encapsulating application logic within a reusable...

Creating Resource Managers

In addition to using the classes in System.Transactions for managing transactions, you can also use them to define your own resource managers. These resource managers can then participate in transactions with databases, MSDTC, message queues, and more. There are three basic steps to defining a resource manager 1. Create an enlistment class. This class is used to track the resource manager's participation in the transaction. That is, this is the class that will vote on whether the transaction...

Additional components for Visual studio

You might be interested in two additional tools that work with Visual Studio. Even better, both are free. The first is a tool for creating your own Visual Basic snippets. As discussed, snippets can be powerful tools when you need to replicate relatively small but commonly used blocks of code that will be customized. While Visual Studio ships with several such snippets, Microsoft probably hasn't included the snippet you want the most. This is where the first tool comes in a Snippet Editor for...

Working with SQL Server

V How to use SQL Server Compact to create local copies of your SQL Server databases to create a local cache V How to use SQL Server Compact and the Sync Framework to create a local synchronized cache of your SQL Server databases V How to use SQL Server's XML features to return data as XML V How to create CLR objects within your SQL Server databases V How to create and use WCF Data Services to expose your data as a RESTful service Most of the relationship between a developer and SQL Server...

Sql servers builtin xml features

Two of the major XML-related features exposed by SQL Server are as follows V FOR XML The FOR XML clause of a T-SQL SELECT statement enables a rowset to be returned as an XML document. The XML document generated by a FOR XML clause is highly customizable with respect to the document hierarchy generated, per-column data transforms, representation of binary data, XML schema generated, and a variety of other XML nuances. V OPENXML The OPENXML extension to Transact-SQL enables a stored procedure...

Laying out Controls on the Form

Now go to the Design mode for the Forml.vb file that was created by the Windows Forms template when you created this project. Extend the default size of the design surface with the size of your control in mind, allocating enough room to align three rows of Windows Forms controls above your custom user control. Starting at the top, you are going to add a new Button control to the upper-left corner of the form. The label on this button will be Select Folder to change this you will update the Text...

Reviewing the WSDL Document

The preceding console-application code provides an instantiation of the ServiceMetadataBehavior object and defines a Uri object for it as well. You can simply type in that address to get at the WSDL file for the service you just built. Therefore, calling http localhost 8000 calculator from your browser provides the WSDL file shown in Figure 13-7. Vf httplfliocaihosfcSOOOfcalc ulator - Windows Internet Explorer m http ,'locaJhort 8000 calculator ' U T X P t gt . Sjy Favorites ft Suqq t i Si1 t...

WcF Data services client Library

The flexibility of querying WCF Data Services using an URL is attractive, but you hardly want to build an application that creates URLs whenever you want to query or edit a database. Fortunately, WCF Data Services also provides the capability to manipulate the data using LINQ. DS converts the LINQ requests into the appropriate URL. To use the client library, you need to add a Service Reference to your data service see Figure 12-40 . Just as with other WCF services, adding the service reference...

Exposing Data Using WCF Data Services

WCF Data Services is a specialized WCF library that converts the HTTP requests to some provider. Currently, DS supports the Entity Framework as well as custom objects. Adding DS support to a project containing an Entity Framework model is as simple as adding a new WCF Data Service class to the project see Figure 12-37 . This adds a new class to the project that represents the actual service ' TODO replace class name with your data class name Inherits DataService Of class name ' This method is...

Synchronizing Data

As mentioned earlier, although you can use SQL Server Compact as a standalone database, it really shines when it is used in combination with a remote database and synchronization. Synchronization enables you to reduce the network traffic required when querying the database, while still keeping up-to-date data on the client. It may be one-way synchronization, pulling the most recent server changes down to the client, or it may be bidirectional, keeping both client and server synchronized. The...

Deciding between TsQL and Visual Basic

Once you have enabled CLR integration with your database, your next set of decisions revolves around when to use T-SQL and the native services of SQL Server versus when to use Visual Basic and the .NET Framework. Your final choice should be based on the needs of the application, rather than because a technology is new or interesting. Table 12-2 outlines some common application-building scenarios and which option would be most appropriate. TABLE 12-2 Using T-SQL versus Visual Basic Generally...

Creating your own namespaces

Every assembly created in .NET is part of some root namespace. By default, this logic actually mirrors COM, in that assemblies are assigned a namespace that matches the project name. However, unlike COM, in .NET it is possible to change this default behavior. Just as Microsoft has packaged the system-level and CLR classes using well-defined names, you can create your own namespaces. Of course, it is also possible to create projects that match existing namespaces and extend those namespaces, but...

Maximumsize and Minimumsize Properties

The MaximumSize and MinimumSize properties specify the control's maximum and minimum height and width, respectively. Forms had these properties in Windows Forms 1.0 and 1.1, but in 2.0 all controls have them. If the maximum height and width are both set to the default value of 0, then there is no maximum. Similarly, if the minimum height and width are set to zero, then there is no minimum. The form or control can be any size. If these properties are set to anything else, then the settings...

Padding and Margin Properties

To assist in positioning controls in the FlowLayoutPanel, all controls have a property called Margin. There are settings for Margin.Left, Margin.Right, Margin.Top, and Margin.Bottom. These settings determine how much space is reserved around a control when calculating its automatic position in a FlowLayoutPanel. You can see the Margin property in action by changing the Margin property for one or more of the buttons in the previous example. If you change all the Margin settings for the first...

Debug Properties

The Express Edition of Visual Basic 2010 supports local debugging. This means it supports not only the .NET-related Debug and Trace classes discussed in Chapter 6, but also actual breakpoints and the associated interactive debugging available in all versions of Visual Studio. However, as noted, the full versions of Visual Studio provide enhanced debugging options not available in Visual Basic 2010 Express Edition. Figure 1-9 shows the project debugger startup options from Visual Studio 2010....

Compiler Settings

When you select the Compile tab of the project properties, you should see a window similar to the one shown in Figure 1-7. One update to Visual Studio 2010 is the return of the Build Configuration settings. In Visual Studio 2008, the Visual Basic Settings for Visual Studio removed these items from the display and instead, when developers asked to debug their code, a debug version was built and executed, and only if the developer did an explicit build. Note that if you are using Beta 2, you...

Data Access with the Entity Framework

gt What is Object-Relational Mapping gt What is the Entity Framework gt How the Entity Framework works with databases gt Using the Entity Framework to edit data gt Using the Entity Framework to create new databases In the past, Microsoft has been known to change the recommended data access strategy relatively frequently. For example, Data Access Objects DAO was released in the Visual Basic 3.0 time frame, followed by RDO Remote Data Objects as an option in the Visual Basic 4 days, and ADO...

The Object Context

As you have seen from the preceding queries, you use a context object as the root of all your queries. This context is the logical equivalent of the Connection object in ADO.NET, but it does much more. The context object is a class that inherits from ObjectContext. In addition to providing access to the database, the ObjectContext is also responsible for allowing you to retrieve metadata about the entities within your model and helping the objects track their changes. Once you have made changes...

Parameterized Properties

The Name property you created is an example of a single-value property. You can also create property arrays or parameterized properties. These properties reflect a range, or array, of values. For example, people often have several phone numbers. You might implement a PhoneNumber property as a parameterized property, storing not only phone numbers, but also a description of each number. To retrieve a specific phone number you would write code such as the following Dim homePhone As string...

Using the CType Function

Whether you are using late binding or not, it can be useful to pass object references around using the Object data type, converting them to an appropriate type when you need to interact with them. This is particularly useful when working with objects that use inheritance or implement multiple interfaces, concepts discussed in Chapter 3. If Option strict is turned off, which is the default, then you can write code using a variable of type Object to make an early-bound method call Public sub...

Rest

REST, or REpresentational State Transfer, is an application model first defined by Roy Fielding in his doctoral thesis. While you may have never heard of Roy Fielding in the past, you likely use one of his creations daily he was one of the principal authors of the HTTP specification. In his thesis, he described a way to create applications that work the way the Internet works V Every piece of data or resource is uniquely identified by some address within the system. V You use a consistent...

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

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 Try Parse

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...

Checked ListBox 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 Data Context 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...

Table LayoutPanel 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...