C#
C#
C#
couldn't get any information material. All the material available on the net is partial to sql, and hence the
purpose we will develop this application in 2 phase First we will see how to make the database connection
to the MSAccess and see what the intricacies of it. And then we will finish with the application.
Enough of the talking and let us move towards the main topic. The connection to the database is rather
modified as compared with the ADO connection that we had earlier. The following figure shows the
sequence properly (i hope)
OleDbConnection--> OleDbCommand --> OleDbDataReader
now those who are familiar with ado will obiviously recognise the simillarity but for some clarification
and for those who are not well versed with ado here is little explanation.
OleDbConnection --> represents single connection to the database, and depending upon the capabilites of
the underlying database it gives you the power to manipulate the database. The point to remember here is
even though oledbconnection object goes out of scope it does not get closed. And therefore you will have
to explicitely call the close() method of the object.
OleDbCommand --> this is our normal command object as we had in ado. You can call sql stored
procedures and sql queries through this object.
OleDbDataReader --> Now this class is of paramount importance since it gives actual access to the
underlying dataset of the database. Once you call the ExecuteReader method of the OleDbCommand it
gets created the dotnet beta 2 sdk says not to create the object of this class directly.
Now you can see more about these main object in .net beta 2 documentation and here is the source code
of how to make the program access the database.
using System;
using System.Data.OleDb;
class OleDbTest{
•Avoid dialog boxes when you open a password-protected database or when user-level security is turned
on.
This article demonstrates how to automate Microsoft Access by using Microsoft Visual C# 2005 or
Microsoft Visual C# .NET. The topics and the sample code show you how to do the following:
•Avoid dialog boxes when you open a password-protected database or when user-level security is turned
on.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
When you automate an application such as a Microsoft Office application, the calls to the properties and
methods of the Office application's objects must be connected in some way to those objects. The process of
connecting property and method calls to the objects that implement those properties and methods is
commonly called binding. In Visual C#, the two types of binding that are available are early binding and
late binding. The type of binding you choose can affect many aspects of your program, including
performance, flexibility, and maintainability.
This article explains and compares early and late binding for Visual C# Automation clients and provides
code samples that demonstrate both types of binding.
Late binding
In contrast to early binding, late binding waits until run time to bind property and method calls to their
objects. To do this, the target object must implement a special COM interface: IDispatch. The
IDispatch::GetIDsOfNames method allows Visual C# to interrogate an object about what methods and
properties it supports and the IDispatch::Invoke method then allows Visual C# to call those methods and
properties. Late binding in this fashion has the advantage of removing some of the version dependencies
that are inherent with early binding. However, it has the disadvantages of removing compile-time checks on
the integrity of automation code, as well as not providing Intellisense features that can provide clues to
correct calls to methods and properties.
To use late binding in Visual C#, use the System.Type.InvokeMember method. This method calls
IDispatch::GetIDsOfNames and IDispatch::Invoke to bind to the Automation server's methods and
properties.
try
{
// Get the class type and instantiate Excel.
Type objClassType;
objClassType = Type.GetTypeFromProgID("Excel.Application");
objApp_Late = Activator.CreateInstance(objClassType);
Notice that the View argument determines whether the report is displayed in Access or
whether it is sent to the printer. The WhereCondition argument can limit the report's
recordset, if you use a valid SQL WHERE clause (without the word WHERE.) Notice that you
can use System.Reflection.Missing.Value to skip any object parameters that are optional.
If you are previewing a report, be sure to set the Visible property of the Application object
so that Access is visible on the screen. In this way, the user can view the report in the Access
window.
There is another way to print a report or other objects in the database. Use the PrintOut
method of the DoCmd object. In this example, you select a report named Employees in the
Database window, and then you call PrintOut to print the selected object. The PrintOut
method allows you to provide arguments that correspond to the Print dialog box in Access:
Or, in some cases, you may want to use both the OpenReport and the PrintOut methods to
print a report. Suppose you want to print multiple copies of the Employees report but only for
a specific employee. This example first uses OpenReport to open the Employees report in
preview mode, using the WhereCondition argument to limit the records to a specific
employee. Then, PrintOut is used to print multiple copies of the active object:
Access 2002 introduced the Printer object. You can use this object to customize Access
printer settings more easily than in earlier versions of Access. For an example of using the
Printer object in Access to print a report, click the article number below to view the article in
the Microsoft Knowledge Base:
There are two types of security in Microsoft Access: password-protected databases and user-
level security through a workgroup file (System.mdw). If you are trying to open a database
that is password protected, you will receive a dialog box prompting for the database
password. User-level security is different from a password-protected database. When user-
level security is activated, Access displays a logon dialog box prompting for both a user name
and password before the user can open any database in Access. For more information about
Access security and the workgroup information file, click the article number below to view the
article in the Microsoft Knowledge Base:
Here is an example, where oAccess has been previously set to an instance of Access that
does not have a database open. This code provides the password to the database to avoid a
dialog box:
The oDB.Close does not actually close the database in Access. It only closes the DAO
connection to the database that was made through the DBEngine object. The DAO
connection is no longer necessary after the OpenCurrentDatabase method is used. Notice
the code to release the oDB and oDBEngine objects. You must use these objects so that
Access quits correctly after the code is completed.
For more information, click the article number below to view the article in the Microsoft
Knowledge Base:
For more information about starting Access with command-line switches, click the article
number below to view the article in the Microsoft Knowledge Base:
The Access Runtime must be started with a database. Because of this requirement, if you
want to automate the Access Runtime, you must start the Msaccess.exe and specify a
database to open. After you use GetActiveObject or BindToMoniker to retrieve the
Application object, you can then automate the Access Runtime. If you do not use this
approach when you try to automate the Access Runtime, you will receive an error message
such as the following when you try to instantiate the instance:
System.Runtime.InteropServices.COMException (0x80080005)
Server execution failed.
For more information click the article number below to view the article in the Microsoft
Knowledge Base:
To make sure that the Northwind sample database is installed on Access 2002 or on Access
2003, click Sample Databases on the Help menu, and then click Northwind Sample
Database.
3. On the File menu, click New, and then click Project. Select Windows Application
from the Visual C# Project types. By default, Form1 is created.
Note You must change the code in Visual Studio 2005. By default, Visual C# adds one
form to the project when you create a Windows Forms project. The form is named
Form1. The two files that represent the form are named Form1.cs and
Form1.designer.cs. You write the code in Form1.cs. The Form1.designer.cs file is where
the Windows Forms Designer writes the code that implements all the actions that you
performed by dragging and dropping controls from the Toolbox.
For more information about the Windows Forms Designer in Visual C# 2005, visit the
following Microsoft Developer Network (MSDN) Web site:
http://msdn2.microsoft.com/en-us/library/ms173077.aspx
(http://msdn2.microsoft.com/en-us/library/ms173077.aspx)
4. Add a reference to Microsoft Access Object Library. To do this, follow these steps:
1. On the Project menu, click Add Reference.
2. On the COM tab, locate Microsoft Access Object Library, and then click
Select.
Note Microsoft Office 2003 includes Primary Interop Assemblies (PIAs). Microsoft
Office XP does not include PIAs, but they can be downloaded. For more
information about Office XP PIAs, click the following article number to view the
article in the Microsoft Knowledge Base:
Note If you are referencing the Access 10.0 object library and you receive errors
when you try to add the reference, click the article number below to view the
article in the Microsoft Knowledge Base::
6. Add five radio button controls and one button control to Form1.
7. Select all of the radio button controls, and then set the Size property to 150,24.
8. Add event handlers for the Form Load event and for the Click event of the Button
control:
The handler for the Form's Load event is created and displayed in Form1.cs.
3. Double-click Button1.
The handler for the button's Click event is created and displayed in Form1.cs.
with:
{
MessageBox.Show("Can't determine path to msaccess.exe");
return null;
}
tryGetActiveObject:
// Enable exception handler:
try
{
// Attempt to use GetActiveObject to reference a running
// instance of Access:
oAccess = (Access.Application)
Marshal.GetActiveObject("Access.Application");
}
catch
{
//GetActiveObject may have failed because enough time has not
//elapsed to find the running Office application. Wait 1/2
//second and retry the GetActiveObject. If you try iMaxTries
//times and GetActiveObject still fails, assume some other
//reason for GetActiveObject failing and exit the procedure.
iTries++;
if(iTries < iMaxTries)
{
System.Threading.Thread.Sleep(500); //wait 1/2 second
this.Activate();
goto tryGetActiveObject;
}
MessageBox.Show("Unable to GetActiveObject after " +
iTries + " tries.");
return null;
}
// First, get the clsid from the progid from the registry key
// HKEY_LOCAL_MACHINE\Software\Classes\<PROGID>\CLSID:
oKey = oReg.OpenSubKey(@"Software\Classes\" + sProgId + @"\CLSID");
sCLSID = oKey.GetValue("").ToString();
oKey.Close();
// Select the report name in the database window and give focus
// to the database window:
oAccess.DoCmd.SelectObject(Access.AcObjectType.acReport, sReport,
true);
// Select the report name in the database window and give focus
// to the database window:
oAccess.DoCmd.SelectObject(Access.AcObjectType.acReport, sReport,
true);
// Select the form name in the database window and give focus
// to the database window:
oAccess.DoCmd.SelectObject(Access.AcObjectType.acForm, sForm, true);
oForm = oAccess.Forms[sForm];
oCtls = oForm.Controls;
oCtl = (Access.Control)oCtls["PrintLabelsFor"];
object[] Parameters = new Object[1];
Parameters[0] = 2; //second option in option group
oCtl.GetType().InvokeMember("Value", BindingFlags.SetProperty,
null, oCtl, Parameters);
NAR(oCtl);
oCtl = null;
// Specify the user name and password for the Access workgroup
// information file, which is used to implement Access security.
// Note: If you are not using the system.mdw in the default
// location, you may include the /wrkgrp command-line switch to
// point to a different workgroup information file.
sUser = "Admin";
sPwd = "";
// Select the report name in the database window and give focus
// to the database window:
oAccess.DoCmd.SelectObject(Access.AcObjectType.acReport, sReport,
true);
// Select the report name in the database window and give focus
// to the database window:
oAccess.DoCmd.SelectObject(Access.AcObjectType.acReport, sReport,
true);
24.Click Print report, and then click Go!. The Print_Report procedure prints a report from
the Northwind database.
25.Click Preview report, and then click Go!. The Preview_Report procedure previews a
report from the Northwind database. Close the Access instance when you are ready to
continue.
26.Click Show form, and then click Go!. The Show_Form procedure displays the
Customer Labels dialog box form from the Northwind database. It also sets the option
group on the form to "Specific Country" and selects "USA" from the list. Close the
Access instance when you are ready to continue.
27.Click Print report (Security), and then click Go!. The Print_Report_Security
procedure shows you how to automate Access and how to avoid the logon dialog box if
user-level security is turned on. In this example, assume the default logon by passing
the user Admin with a blank password. The code then prints a report in the Northwind
database.
28.Click Preview report (Runtime), and then click Go!. The Preview_Report_Runtime
procedure shows you how to automate the Access Runtime to preview a report in the
Northwind database. If the retail version of Access is installed, the procedure will still
work correctly. Close the instance of Access when you are ready to continue.
Binding for Office automation servers with Visual C#
.NET
SUMMARY
When you automate an application such as a Microsoft Office application, the calls to the properties and methods of the
Office application's objects must be connected in some way to those objects. The process of connecting property and method calls
to the objects that implement those properties and methods is commonly called binding. In Visual C#, the two types of binding
that are available are early binding and late binding. The type of binding you choose can affect many aspects of your program,
including performance, flexibility, and maintainability.
This article explains and compares early and late binding for Visual C# Automation clients and provides code samples that
demonstrate both types of binding.
Early binding
With early binding, Visual C# uses type information that is available about the Office Application in question to bind directly
to the methods or properties it needs to use. The compiler can perform type and syntax checks to ensure that the correct number
and type of parameters are passed to the method or property, and that the returned value will be of the expected type. Because less
work is required at run time to make a call to a property or method, early binding is sometimes faster; however, although early
binding may be faster, performance differences when compared to late binding are often negligible.
Early binding does have the minor disadvantage that it can introduce possible version compatibility issues. For example, suppose
that an Automation server such as Microsoft Excel 2002 introduces a new method or property that was unavailable in Excel 2000,
or makes a change to an existing property or method. These changes may alter the binary layout of the object and cause problems
with a Visual C# application that uses the Excel 2002 type information to automate Excel 2000. To avoid this problem with early
binding, it is generally recommended that you use the type information for the earliest version of the Office Application that you
wish to support when you develop and test your Automation client.
The following steps demonstrate how to build an Automation client that uses early binding. Note that, as the steps illustrate, early
binding requires you to reference the type library for the Automation client.
Create an Automation client that uses early binding
Start Microsoft Visual Studio .NET. On the File menu, click New and then click Project.
Select Windows Application from the Visual C# Projects types. Form1 is created by
default.
Add a reference to the Microsoft Excel Object Library. To do this, follow these steps:
2. On the COM tab, locate theMicrosoft Excel Object Library and click Select.
Note Office 2003 includes Primary Interop Assemblies (PIAs). Office XP does not
include PIAs, but they can be downloaded. For additional information about
Office XP PIAs, click the following article number to view the article in the
Microsoft Knowledge Base:
3. Click OK in the Add References dialog box to accept your selections. If you
receive a prompt to generate wrappers for the libraries that you selected, click
Yes.
2. On the View menu, select Toolbox to display the Toolbox, and add a button to Form1.
with:
try
{
// Instantiate Excel and start a new workbook.
objApp = new Excel.Application();
objBooks = objApp.Workbooks;
objBook = objBooks.Add( Missing.Value );
objSheets = objBook.Worksheets;
objSheet = (Excel._Worksheet)objSheets.get_Item(1);
8. Scroll to the top of the code window. Add the following line to the end of the list of
using directives:
9. using System.Reflection;
10.using Excel = Microsoft.Office.Interop.Excel;
Late binding
In contrast to early binding, late binding waits until run time to bind property and method
calls to their objects. To do this, the target object must implement a special COM interface:
IDispatch. The IDispatch::GetIDsOfNames method allows Visual C# to interrogate an
object about what methods and properties it supports and the IDispatch::Invoke method
then allows Visual C# to call those methods and properties. Late binding in this fashion has
the advantage of removing some of the version dependencies that are inherent with early
binding. However, it has the disadvantages of removing compile-time checks on the integrity
of automation code, as well as not providing Intellisense features that can provide clues to
correct calls to methods and properties.
To use late binding in Visual C#, use the System.Type.InvokeMember method. This
method calls IDispatch::GetIDsOfNames and IDispatch::Invoke to bind to the
Automation server's methods and properties.
Create an Automation client that uses late binding
Start Microsoft Visual Studio .NET. On the File menu, click New and then click Project.
Select Windows Application from the Visual C# Projects types. Form1 is created by
default.
On the View menu, select Toolbox to display the Toolbox, and add a button to Form1.
with:
try
{
// Get the class type and instantiate Excel.
Type objClassType;
objClassType = Type.GetTypeFromProgID("Excel.Application");
objApp_Late = Activator.CreateInstance(objClassType);
4. Scroll to the top of the code window. Add the following line to the end of the list of
using directives:
5. using System.Reflection;