Visual Basic 2010 Sample Download Project
Create Data Search – This sample allows you to search a record within the database using the datagrid object and binding navigator control.
Download – Stored Procedure in Visual Basic 2010
- Create a new database using SQL commands and resource files to control the scripts to execute. A new database with a new table is created. The table is then populated with additional scripts. An additional script is executed to create the stored procedures that are used within this sample.
- Execute a stored procedure that does not require any parameters by using a SqlDataReader object.
- Execute a stored procedure that requires an input parameter and fill a grid control with the results of a SqlDataAdapter.
- Execute a stored procedure that requires both input and output parameters and that uses a return value.
Download – Create Database - The application leads you through the steps in creating and populating the database:
- Create the database The SqlCommand class uses the CREATE DATABASE statement to create the How to Demo database.
- Create the data table The SqlCommand class uses the CREATE TABLE statement to create a table named NW_Seafood. The table includes fields for product ID, product name, quantity per unit, and unit price.
- Create a stored procedure The SqlCommand class uses the INSERT INTO statement and the SELECT statement to add code to the new table and retrieve the data from the table.
- Create a view The SqlCommand class uses the CREATE VIEW statement to select rows in the NW_Seafood table.
- Populate the table The SqlCommand class uses the EXECUTE statement to run a procedure that retrieves rows from the Northwind database and add them to the NW_Seafood table.
- Display the data in the table The SqlCommand class uses the SELECT statement to fill a DataSet that is then used as the DataSource of a DataGrid control. Table and column style objects are used to customize the appearance of the DataGrid.
Download – Combo Box Databind Sample- The code demonstrates how to bind six different types of data sources to a ComboBox control. Data is bound from:
- an array
- an ArrayList of strings
- an ArrayList of class objects
- a DataTable
- a DataView
- a BindingSource object
When the main form loads, the Products table from the Northwind database is retrieved into a DataSet using a simple SQL Select statement. A DataView that provides a sorted view of the ProductName column is also created at this time. The Products table is loaded into another DataSet using a TableAdapter and BindingSource.
This sample demonstrates the data validation features available in the Visual Studio designers. Two arbitrary and fictitious rules are used to validate the data. Code is added using the Dataset Designer. Double-clicking a column name creates the event for the column change. Double-clicking the field list creates the event for the row change.
The sample solution includes two projects. One is a Windows Control Library project named MyCompanyControls. The second is a Windows Application project named CustomDataControls.
The control library defines the PhoneBox control. The control simply inherits from MaskedTextBox control and sets the Mask property to a Phone Number with Area Code. The library project also contains an embedded resource, PhoneBox.bmp, to represent the icon in the ToolBox and Data Sources window.
The PhoneBox control is available in the CustomDataControls project. By selecting Rebuild from the project’s shortcut menu, the PhoneBox will appear in theToolbox in a new section named MyCompanyControls. You need to have Form1 opened in the designer in order to see the ToolBox items.
The Data Sources window is used to add the PhoneBox to the list of controls for String. In the Data Sources window, select the HomePhone column under theEmployee table. Select the drop-down and choose Customize. This opens the dialog box for customizing the list of controls for given types. This list is populated with the list of controls currently in the Visual Studio ToolBox that implement the DefaultBindingPropertyAttribute. The PhoneBox control inherits from MaskedTextBox, which supports the DefaultBindingPropertyAttribute. Select String under Data Type and find the PhoneBox control in the list. The check by the PhoneBox control indicates to Visual Studio that the PhoneBox control is one of the available controls for any object that has a string property.
ADO.Net Entity Framework Application Sample
This project contains the Entity Data Model (EmployeeModel.edmx) that maps between the database (Employee.mdf) and the business objects defined in the Model project. There is also a custom T4 template (ContextTemplate.tt) that is based on the default template but has entity generation removed as we are using the pre-defined business objects. The T4 template also adds the IEmployeeContext interface to the generated context.
The Entity Data Model includes a Model Defined Function (MDF) which calculates an Employee’s tenure. The Employee repository in the Common project has a private method for calculating tenure which is marked with an EdmFunction attribute. When running against the Entity Framework the MDF will be used instead of this method and evaluation will occur in the database. The method includes an implementation which is used when running against fakes.
Visual Studio includes the Data Sources window, through which you can set up bindings not only to server-based data, but also to local data, Web services, and business objects. Dragging a table to a form creates a data-bound form, handling most of the steps that you had to complete manually in earlier versions.
The basic steps for creating an application such as this are as follows:
- Create a Windows Application project.
- Add a new data source.
- Select the display controls for table columns, or accept the default selections.
- Drag the table onto the form.
- Add the code for inserting, updating, and deleting records. Examine the code for the Click event of the Save item on the ToolStrip.
The sample solution contains two projects. The CustomerLibrary project defines several business classes, including Customers, Orders, and CustomerManager. TheCustomerManager class creates instances of these classes. Those instances are displayed in the client project.
In the Form Designer, two BindingSource controls are created that link the business objects to the business classes. The controls on the form are then bound toBindingSource controls. For more information, see How to: Connect to Data in an Object.
Occasionally Connected Data Sample
The sample demonstrates synchronization. Click Synchronize in the sample application. This downloads data from the server to the .sdf file. Next, make data changes in the server data grid, and then click the save button.
This application contains two classes, one with standard serialization and one with custom serialization. The user interface includes buttons to serialize and deserialize the two classes. The class with standard serialization can be serialized to either a SOAP file or a binary file. The class with custom serialization is serialized to a SOAP file. A TextBox control is used to display the SOAP files. The two classes both have the SerializableAttribute attribute. The classes are described in the following table.
The form is divided into three sections:
- A list of tasks.
- A display area for XML.
- A display area for execution results.
All three areas are loaded and updated dynamically. Using a collection of items, rather than a series of button controls, allows you to add as many options as you like, without having to rearrange controls on the designer.
When the sample loads, it checks for the existence of three files in the \bin folder of the project folder:
- Simple.xml
- New.xml
- Bad.xml
If the files exist, you will be able to choose from a set of commands loaded into a CheckedListBox control. You will need read/write permission to the \bin folder, as some of the commands require saving changes on disk.
The MainForm contains a StatusStrip control that indicates whether the network connection is currently connected or disconnected. Each time the status of network connectivity changes, the My.Computer.Network.NetworkAvailabilityChanged Event event is raised. The handler for this event resides in the My Project\MyEvents.vb file. To access this file, double-click My Project in Solution Explorer. On the Application tab in the Project Designer, click the View Code button. The logic that updates the Status Panel resides in the SetConnectionStatus method of MainForm. Network events in Visual Basic are marshaled back to the main application thread; handlers of these events can, therefore, manipulate the user interface directly.
The ClickOnce feature can be used to programmatically handle several installation and maintenance tasks. This includes the following:
- Checking for updates Uses the CheckForUpdate method to check for new updates.
- Updating an application Uses the UpdateAsync method to download the updated application.
- Downloading optional files Uses the DownloadFileGroupAsync method to download files.
- Deployment information The My.Application.Deployment property is used to retrieve and report the name, version, location, and last update check.
The project includes an XML file as an embedded resource. The XML file contains the Products table of the Northwind database. The application loads an untyped dataset from the XML file. When the console application is run, it accepts input from the user that is either a product ID or “quit”. If “quit” is entered, the console application ends. If a valid product ID is entered, its associated product information is displayed. If an invalid product ID is entered, an exception message is displayed..
The main form contains one TabControl with several tab pages. Each tab page calls a different group of Environment or SystemInformation members:
- Properties This tab demonstrates Environment properties.
- Special folders The code calls the GetNames method on the Environment..::.SpecialFolder to retrieve a list of all the special folder names. This list is used as a data source for the ListBox control.
- Methods This tab shows results from calling Environment methods, including Exit and ExpandEnvironmentVariables . The string arrays returned by theGetLogicalDrives and GetCommandLineArgs methods are used as data sources to ListBox controls.
- Environment variables The code calls the GetEnvironmentVariables method. The Keys property of the returned collection is used as the data source for aListBox control. This tab page also demonstrates retrieving one environment variable by calling the GetEnvironmentVariable method.
- System information This tab retrieves all the information provided by the SystemInformation.
This sample consists of a solution named ExcelAuto.sln that contains two projects. ExcelAuto.vbproj is an interactive Windows-based application for automating Excel and setting up a scheduled task. ExcelAutoTask is a console application that contains Excel automation code that is run when the task is scheduled.
When the ExcelAutomation application runs, it opens a form that has buttons for automating Excel.
When you click Load Spreadsheet with Data, ExcelAuto creates a new Excel application. It then creates an Excel workbook from a template and updates the cells with data stored in a file named OrderData.xml. This data represents order status from the Northwind database sample. The spreadsheet is a status report that displays the status of Northwind orders.
You may also want to try the e-mail and task scheduling features in the sample.
This sample demonstrates features that are implemented in most applications:
- User options The Options form enables users to reset the high scores and turn sound on and off.
- Help The application includes a compiled Help project. The compiled Help is accessed through the Help menu item.
- Mouse The mouse is used not only to play the game, but to drag the form around when the title bar is hidden.
- Keyboard The “M” key toggles the menu and title bar on and off. The “P” key pauses and restarts the game action.
- Several Visual Basic and .NET Framework features are highlighted:
- GDI+ graphics The game action is implemented by using drawing functions from the System.Drawing namespace.
- Registry High scores are stored in the registry.
- Object-oriented programming The game action and drawing is controlled by several classes that act together. The main game classes are the Grid and Blockclasses. The PointTranslator class adds utility functions for drawing the blocks. The HighScores class handles retrieving and setting scores.
This sample contains:
- Form1 Provides a simple form that shows all listeners currently enabled for My.Application.Log and has controls that allow text to be written toMy.Application.Log.
- app.config Defines the configuration for My.Application.Log — where messages should be written, which messages should be filtered, and so on.
This sample demonstrates how My.Application.Log can be used to write a plain text file, the event log, and an XML file. You can easily implement a customTraceListener that writes to other locations as well, such as a database or an e-mail message.
Each message is assigned the “Severity” selected on the form. When the listener receives the message, it may discard the message based on its filter level. For example, the EventLogTraceListener component is configured to write error messages only, so any messages you write with a severity “Information” or “Warning” will be written to the XML and plain text file and not to the EventLog.
To change the behavior of the sample, edit the app.config file of the project. Comments in the file serve as a guide to changes.
You can use My.Application.Log and the application model to log startup, shutdown, and unhandled exceptions. To see the code for this sample, double-click My Project in Solution Explorer. On the Application pane, click the View Code button.
This sample runs a time-consuming task on a separate thread, launched by a button click:
- Run on same thread The task runs on the same thread as the main form. This blocks the user from interacting with the main form until the task finishes. No multithreading code is needed for this task.
- Run on worker pool thread The task uses the BeginInvoke method created by the compiler for all delegates to run the task.
- Background worker This task uses the BackgroundWorker Component to create a new thread.
This example does not include synchronization, because the multiple threads are not accessing any data.
A setting is used to keep track of the number of times the application has been run. Each time the application runs, the setting is examined, and one of several available desktop images is selected based on that number. Consequently, every time that you run the application, you see a new background.
The code resides in the SetBackground method of Form1 and in the application startup and shutdown events, which are handled in My Project\MyEvents.vb. To view this file, double-click My Project in Solution Explorer. On the Application panel of the Project Designer, click the View Application Events button.
Settings are created and modified on the Settings tab of the Project Designer. There are two types of settings: application and user. Application settings are those with values that are common to all instances of the application. User settings are created and modified for each user. In this sample, the setting that persists the number of times an installation of the application has been executed is a user setting.
The sample consists of a solution named PowerPointAuto.sln that contains a single project: PowerPointAuto.vbproj. This project is a Windows-based application that has a single form that remotely controls PowerPoint.
When the PowerPointAuto application runs, it opens a single form that has buttons for automating PowerPoint.
Clicking Print Preview demonstrates use of the Print Preview Functionality.
Send Mail Sample in Visual Basic 2010
- Internet Information Services (IIS) is required.
- SMTP Service must be installed and running. SMTP Service is an option installed with IIS.
- The SmtpServer property must be set to the IP address or server name where the SMTP Server is running. In most cases this is the “localhost” computer. Therefore, the SmtpServer property value can be either the friendly name, “localhost”, or “127.0.0.1″. The latter is the default for this application. To find the SMTP server name:
- Open the IIS snap-in (In Control Panel, open Administrative Tools, and then open Internet Information Services).
- Expand the Default SMTP Virtual Server node.
- Click Domains. In the right pane you will see a list of Domain Names. You may set the SmtpServer property to one of these names or its corresponding IP address.
The Default SMTP Virtual Server must also be running. Be aware that it is possible for the SMTP Service to be running, but the Default SMTP Server in IIS to be stopped. There is a difference between the service itself and the actual server run by the service. If your Default SMTP Virtual Server is not running, a red X icon will be visible over its node in the IIS snap-in. To start the server, right-click its node and click Start.
Set the relay restrictions:
-
- In IIS, right-click Default SMTP Virtual Server and select Properties.
- In the Properties dialog box click the Access tab.
- Click Relay.
- In the Relay Restrictions dialog box, select the box labeled All except the list below. The bottom check box can be selected or cleared.
This application has a single form with controls similar to the Microsoft Outlook e-mail client. When the form loads, it checks to make sure that the user has the SMTP Service installed and that it is running.
The sample contains three solutions, each with one project:
- RemoteCustomer: the Server
- RemoteHost: the Host
- Client: the Client.
- Remote Customer
- Customer (client activated)
- SingleCallCustomer (WellKnown singlecall)
- SingletonCustomer (WellKnown singleton)
The RemoteCustomer is a class library that exposes three creatable types:
Each class is located in the same namespace, RemotingSample, which is defined in each class source file.
Remote Host
The RemoteHost project contains a Windows Forms application that will read an XML configuration file that is named Host.exe.config to make available the classes defined in the RemoteCustomer project. For a production application, you might want to host the class library (RemoteCustomer.dll) in a Windows service.
Client
The Client project is a Windows Forms application. It relies on a configuration file that is named Client.exe.config to know where to look for the remote objects.
- Object-oriented approach The classes Tape, Recorder, Channel, and TapeFrame are implemented. Modules are replaced by classes.
- ByRef and ByVal ByRef is replaced with ByVal where appropriate.
- XML Comments These comments replace the formatted comment blocks.
- Naming conventions Hungarian names are removed.
- Boolean types Boolean variables replace Integer values.
This sample demonstrates these tasks:
- User name The current Windows user’s name is displayed on the main form. This value is retrieved from the My.User Object.
- Database access My.User allows developers to plug in their own means of custom authentication and authorization by means of the IPrincipal and IIdentityinterfaces. These interfaces describe aspects of the current user that are independent of a specific authentication and authorization architecture. Implementers of the interfaces define how the user should be authenticated and what roles the user is currently enrolled in. This sample provides a very basic implementation of the IPrincipal and IIdentity interfaces to demonstrate how My.User can be configured to use developer-defined authorization and authentication mechanisms, respectively.
|
What’s New in Visual Basic 2010
Auto-Implemented Properties
Auto-implemented properties provide a shortened syntax that enables you to quickly specify a property of a class without having to write code to Get and Set the property.
Collection Initializers
Collection initializers provide a shortened syntax that enables you to create a collection and populate it with an initial set of values. Collection initializers are useful when you are creating a collection from a set of known values, for example, a list of menu options or categories.
Implicit Line Continuation
In many cases, implicit line continuation enables you to continue a statement on the next consecutive line without using the underscore character (_). For a list of all the cases in which you can omit an underscore character.
Multiline Lambda Expressions and Subroutines
Lambda expression support has been expanded to support subroutines in addition to multiline lambda functions and subroutines.
New Command-Line Option for Specifying a Language Version
The /langversion command-line option causes the compiler to accept only syntax that is valid in the specified version of Visual Basic.
Type Equivalence Support
You can now deploy an application that has embedded type information instead of type information that is imported from a Primary Interop Assembly (PIA). With embedded type information, your application can use types in a runtime without requiring a reference to the runtime assembly. If various versions of the runtime assembly are published, the application that contains the embedded type information can work with the various versions without having to be recompiled.
Dynamic Support
Visual Basic binds to objects from dynamic languages such as IronPython and IronRuby.
Covariance and Contravariance
Covariance enables you to use a more derived type than that specified by the generic parameter, whereascontravariance enables you to use a less derived type. This allows for implicit conversion of classes that implement variant interfaces and provides more flexibility for matching method signatures with variant delegate types. You can create variant interfaces and delegates by using the new In and Out language keywords. The .NET Framework also introduces variance support for several existing generic interfaces and delegates, including the IEnumerable(Of T)interface and the Func(Of TResult)and Action(Of T) delegates.