Using C # to remotely Access database Access databases _ basic applications

Source: Internet
Author: User
Tags access database port number


First, technical points

As we all know, Windows applications start a process at run time that includes several threads, and communication between different processes is necessary to develop a distributed application that traditionally requires not only an in-depth understanding of the objects of processes on both sides of the communication stream, but also a deep understanding of the host of low-level protocols, Application programming interfaces and configuration tools. In short, it is a complex task that requires a great deal of expertise and experience.

Fortunately. NET provides us with the remote processing function, it provides the communication method can quickly and conveniently completes the above-mentioned establishment communication task. Therefore, the. NET Framework provides support whether it is necessary to quickly develop a WEB application or to spend more time building critical enterprise-wide applications. With. NET remoting, a client application can use an object from another process on the same computer or on any other computer that is available on its network.

To create an application that enables two objects to communicate directly across applications using. NET remoting, you simply generate the following objects:

1. Objects that can be processed remotely.

2, the application that listens for requests to this remote object is the server program.

3, the client application that makes the request to the remote object.

. NET, there are two ways to communicate objects in different applications: one is to transfer object replicas across application domain boundaries, and one is to exchange messages using proxies. MarshalByRefObject is the base class for objects that communicate by using proxies to exchange messages. When a remote object is used across applications, the base class of the object must be inherited from MarshalByRefObject.

Second, the realization of the program

(1) First, we create a new solution named "Testremoteaccess" in the IDE of VS to accommodate the three projects described previously for remoting, first add the class library named "RemoteObject" to the solution, and then change the default created class name to " Cremoteaccess ", and inherits from" MarshalByRefObject ", the code is as follows:

Using System;
Using System.Collections.Generic;
Using System.Text;
Namespace RemoteObject
{
public class Cremoteaccess:marshalbyrefobject
{}
}



We need to create all the functions within this object to connect to and access the local Access database for the server-side client program to call at the same time. Methods for connecting and accessing Access databases are no longer detailed here, see attachment source code.

First, all functions that need to be exposed to the client must have their visibility set to public. The variable m_connstring needs to be set to public static, in order to save the database connection string after the client invokes setremoteaccessconnstring for constant access during this connection, as follows:

......
public static string m_connstring;
......
public void setremoteaccessconnstring (string connstr)
{
m_connstring = ConnStr;
}
......

After a successful connection to the Access database, we need to return the dataset to the requesting client for display and editing, and we declare several related functions in the remote object:

private void LoadData (String sqlstr, String tablename)
public void SaveData (DataTable clientdatatable)
Public DataTable getusertable (string sqlstr, String tablename)

The client can pass the SQL query script to fetch data from the related database table by calling Getusertable, and return a DataTable, which can then be appended to DataGridView to display the data. Getusertable the acquisition of the data by calling the private LoadData function. The SaveData function is used to save the edited dataset back to the local Access database file with the following code:

......
M_connection. Open ();
M_adapter. Update (clientdatatable);
......


(2) The remote object creation is complete and we need to create a server-side application that listens for the remote object request. In the Testremoteaccess solution, create a new Windows Form project named: "TestServer", dragging the next few components from the toolbox, the interface looks like this:


In addition to the ability to access objects remotely, the server program testserver the most important role is to get the actual Access database file path and set the remote object's database connection string. We must add a reference to a class library such as a remote object and a remoting and network communication protocol. At the beginning of the server program startup, you need to create an instance of the remote object and register the communication port, and then call the RemotingConfiguration.RegisterWellKnownServiceType method. The description of the method in MSDN is as follows: By initializing a new instance of Wellknownservicetypeentry with a given parameter, the object type on the service end is registered as a known type, and all customers who know the URI of the registered known object can obtain the proxy for the object. The so-called URI is the Uniform Resource Identifier (uniform Resource Identifier). The code is as follows:


......
Remotableobject = new Remoteobject.cremoteaccess ();
TcpChannel channel = new TcpChannel (8080);
ChannelServices.RegisterChannel (channel);
RemotingConfiguration.RegisterWellKnownServiceType (typeof (Remoteobject.cremoteaccess), "RithiaTestAccessServer" , Wellknownobjectmode.singleton);
......



When you select the Access database file to be accessed, we need to invoke the Setremoteaccessconnstring method of the remote object, which will hold the connection string that connects to the Access database file during this connection to the server program, as follows:


......
Providerstr = Providerstrpart + Txtaccessmdbfilename.text + "; Jet oledb:database password= "+ txtaccesspassword.text;
......
Remotableobject.setremoteaccessconnstring (PROVIDERSTR);
......



(3) Finally, we create a client program for connecting and requesting services, which obtains the relevant dataset by calling the server program testserver the registered remote object and saves the edited data back to the actual database file. In the Testremoteaccess solution, create a new Windows Form project named: "TestClient", dragging the next few components from the toolbox, the interface looks like this:

The client program needs to know the computer name or IP address that the server program is running on and the port number that is listening, and then create an instance of the remote object and create a DataTable to receive the returned data, as follows:

......
String Remoteurl;
Host = Txthost.text;
Port = Txtport.text;
Remoteurl = "tcp://" + Host + ":" + Port + "/rithiatestaccessserver";
Try
{
TcpChannel chan = new TcpChannel ();
ChannelServices.RegisterChannel (Chan);
RemoteObject = (remoteobject.cremoteaccess) Activator.GetObject (typeof (Remoteobject.cremoteaccess), RemoteURL);
remotedatatable = new DataTable ();
Button3. Enabled = false;
}
catch (Exception E)
{
MessageBox.Show (E.message.tostring ());
}
Finally
{
}
......

The client program registers the corresponding channel and port number according to whether the channel that the service program listens to is TCP or HTTP. and combines the URL of the remote object, that is, the Url= Channel://Host Name: The URI of the port number/object, and then creates an instance of the remote object that can be accessed as if it were a local object. We can invoke the Getusertable method of the remote object to get the result set of the specified query script, as follows:

......
remotedatatable = remoteobject.getusertable (Txtsql.text, "Test");
Datagridview1.datasource = remotedatatable;
......

When you save a result set, you simply call the SaveData method, and the code is as follows:

......
Remoteobject.savedata (remotedatatable);
......

Iii. Results

The program successfully passed the trial run in Visual Studio. Net 2005 and Windows XP SP2.
SOURCE Download: http://d.download.csdn.net/down/401452/q520525745
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.