How to re write Office Automation Code - c#

VS 2008 / C# / MS 2007
I have a Saved Import Feature in Access Database which invokes ODBC Connection. Instead of depending on In-built Saved Import feature, i am trying to rewrite the feature in C# which will call ODBC Connection to Import Data to MS Access Database.
I am not able to call the connection string which is saved in the Access Database which calls ODBC Drivers. I keep failing .. !!
Access.Application access1 = new Access.Application();
try
{
string sSalisburyAccessDB = Server.MapPath("App_Data/Database1.mdb");
access1.OpenCurrentDatabase(sSalisburyAccessDB, true, null);
// Drop the existing table data
access1.DoCmd.DeleteObject(Access.AcObjectType.acTable, "plans");
access1.DoCmd.DeleteObject(Access.AcObjectType.acTable, "price");
// Run the saved import
access1.DoCmd.RunSavedImportExport("TestODBC");
// Close the database
access1.CloseCurrentDatabase();
// Quit MS Access
access1.Quit(Access.AcQuitOption.acQuitSaveAll);
Response.Write("successful");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

To me it seems you are using automation in IIS (Server.Mappath... ans Response.Write...) ?
IF this is the case THEN this is NOT supported by MS - see http://support.microsoft.com/default.aspx?scid=kb;EN-US;q257757#kb2
Reasons are several: starting from security and not ending with the fact that office was never built for such server usage scenario...
I don't understand why you are not just using ODBC from C# instead of MS Access ? Perhaps you could show some more surce code or the exception/error message... ?
EDIT - after long discussion (see comments):
IF you need to access the Faircom DB then add a using System.Data.Odbc; and try
OdbcConnection DbConnection2Salisbury = new OdbcConnection("DSN=Salisbury;DBQ=S:\;CODEPAGE=1252;");
DbConnection2Salisbury.Open();
After this you are able to use ADO.NET to query etc. the Faircom DB i.e. with OdbcCommand and OdbcDataReader etc.
For some information see http://msdn.microsoft.com/en-us/library/system.data.odbc.aspx
For sample code see http://www.easysoft.com/developer/languages/csharp/ado-net-odbc.html

Related

ODBC connection with Universe 9.6

We have a legacy system running on Universe DBMS 9.6 . We are trying to export data from it and we have enable rpc daemon so that we can connect via odbc.
Now we are able to connect to the server but we are not able to run any queries. We are getting following error
query - SELECT * FROM DEBTOR
exception - UniVerse/SQL: syntax error. Unexpected symbol. Token was
";". Scanned command was SELECT
There are two types of database in universe ie Table and File based. But we are able to query the table based database but we cannot query File based and there are some configurations that will enable querying the File based ones. We are stuck at this place.
Using u2Client library in c# to access the db. Any help is appreciated
Code used to connect Universe
U2ConnectionStringBuilder conn_str = new U2ConnectionStringBuilder();
conn_str.UserID = "id";
conn_str.Password = "pwd";
conn_str.Server = "serverIP";
conn_str.Database = "DBNAME";
conn_str.ServerType = "UNIVERSE";
conn_str.Pooling =false;
conn_str.AccessMode = "Uci";
conn_str.RpcServiceType = "uvserver";
string s = conn_str.ToString();
U2Connection con = new U2Connection();
con.ConnectionString = s;
con.Open();
Console.WriteLine("Connected.........................");
U2Command xmd = new U2Command("SELECT * FROM TABLE_NAME", con);
var op = xmd.ExecuteReader();
Exception catches while executing the last statement
We tried a driver from Rocket software Universe side is working and it is sending the data to the client but client cant understand the protocol or some error that causes exception . We confirmed that the server responded to the query with data by checking the TCP packets. But we are out of luck.
So we decided to create our own software which is developed in Universe Pick Basic which will be connected to external system via ssh and created a new protocol that both client and server understands it. And we succeeded ,now we can export and import data to universe.
Officially Universe 9.6 isn't supported for use with the U2 Toolkit for .NET. Per the documentation (page 6):
Supported versions of UniData and UniVerse
UniData 7.1 or later
UniVerse 10.3 or later
You can still use straight ODBC or UniObjects to extract data from your database. If you're planning to use ODBC, in addition to enabling RPC, make sure you have configured your Universe account for ODBC per Rocket's ODBC documentation. Before writing C# code, I have often verified my ODBC setup using Excel's external data access tools.

Intranet Form using ASP.NET MVC and Access

I'm totally new to Web Programming, and have been asked to produce a web form that will be hosted on the company Intranet Site. The form will be used to submit data to a back end database.
My problem is that the database has been developed using MS Access 2007. Whereas I would like to use ASP.NET MVC 3 I'm not sure I will be able to us MS Access for this as a back-end database. Most examples I seem to find all hook up to SQL Server (Data Context), which i understand is the best way to go about it.
My problem is that due to time restrictions, I wont be able to change this database over to SQL at present. There has been a lot of work done creating things such as Forms, Reports etc within the Access Database that I don't have time to replicate in .Net for now.
Can anyone give me some advice on which would be the best method for building a Intranet Data Entry form in the short term.
I will look to bring the entire project up to date when the time is available.
You should be able to simply add the Access connection string to the web.config file and use that DB instead.
<connectionStrings>
<add name="MyConn" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|name_of_db.accdb;" providerName="System.Data.OleDb" />
</connectionStrings>
Model-View-Controller is a software design pattern, referring to separation of the interface and logic.
You can still use MVC with MS Access. You could use the OLEDBConnection class, however I would recommend you use an ORM such as NHibernate which supports Access connectivity (Tutorial outlined below).
At a later date you can simply map all of the NHibernate mappings to SQL Server and switch the connection string which will point at your new SQL Server database rather than MS Access.
Linking MS Access to NHibernate:
http://www.thoughtproject.com/Snippets/NHibernateWithAccess/
Connecting to MS Access via OLEDB:
http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx
// C#
public void ConnectToAccess()
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" +
#"Data source= C:\Documents and Settings\username\" +
#"My Documents\AccessFile.mdb";
try
{
conn.Open();
// Insert code to process data.
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}
finally
{
conn.Close();
}
}
More info at MSDN.

How to create an Access database using C# and continuously save real-time data to it

I am currently in the process of making an application that runs 24/7 and constantly collects information from an OPC-sever.
What I need to do now is to send this information to a database (.accdb-file). This need to happen very, very quickly. I fetch a new value from the server every millisecond and I need to send that value to the database at the same speed. Lastly I'm compressing the database to a .zip-file at 00:00 every day.
I have been searching the web like a maniac but I can't seem to find an "Up-to-date" tutorial. Every one I have found so far uses "Microsoft.Jet.OLEDB.4.0" as provider but it doesn't exsist on my Windows 7 PC.
I have made a small application to test connections with and I'll attach my current code bellow to give you a hint of what I have tried so far, none of this seems to work, though.
private void button1_Click(object sender, EventArgs e)
{
System.Reflection.Assembly oAssembly = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream oStream = oAssembly.GetManifestResourceStream("RSLogixDB.accdb");
System.IO.FileStream fileStream = new System.IO.FileStream("C:\\Users\\sezettersth\\Documents\\RSLogixDB.accdb", System.IO.FileMode.Create);
byte[] abyt = new byte[oStream.Length];
oStream.Read(abyt, 0, (int)oStream.Length);
fileStream.Write(abyt, 0, (int)oStream.Length);
fileStream.Close();
if (fileStream != null)
{
fileStream.Close();
fileStream = null;
}
if (oStream != null)
{
oStream = null;
}
}
This is the first approach I tried, here I use a homemade class that is used for creating and writing to files. It didn't work for .accdb-files, unfotunately. (The comments on the first lines include providers that I have tried.
private void button1_Click(object sender, EventArgs e)
{
//sFileDia.ShowDialog();
//Provider=Microsoft.ACE.OLEDB.12.0
//Povider=.NET Framework Data Provider for OLE DB
//Povider=Microsoft.Jet.OLEDB.4.0
//Driver={Microsoft Access Driver (*.mdb, *.accdb)};
//Data Source=C:\\Users\\sezettersth\\Documents\\RSLogixDB.accdb;
//Persist Security Info=False;
//Provider=Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\sezettersth\\Documents\\RSLogixDB.accdb;Persist Security Info=False
string RSLogixDB = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\sezettersth\\Documents\\RSLogixDB.accdb;Persist Security Info=False";
string RSLogixDBPath = "C:\\Users\\sezettersth\\Documents\\RSLogixDB.accdb";
OleDbConnection connection = new OleDbConnection(RSLogixDB);
string connectionStr = connection.ConnectionString;
//OleDbDataReader dataReader = new OleDbDataReader(RSLogixDB);
ImportExport textwriter = new ImportExport();
textwriter.setExportPath(RSLogixDBPath);
textwriter.endExport();
}
There has to be a simple solution to this, I can't be the only one using Access without the "Microsoft.Jet.OLEDB.4.0" provider.
(I haven't started the code for zipping the file and if you have an idea on how to do that I'm happy to hear it, but the main focus here is the database issue.)
UPDATE: The problem might not lie on the provider as I initially though, Microsoft.ACE.OLEDB.12.0 allows me to create a .accdb-file but it is just an empty txt-file with a fancy extension basically and it cannot be opened or used with MS Access. How do I make a working .accdb-file?
Regarding your code
To be honest, I'm at a loss at what you are trying to achieve in the code samples you presented.
From what I can see, you are simply creating a file RSLogixDB.accdb.
Maybe I'm missing something, but that's not how you create a database at all.
Have you looked and tried the code in the answers to these SO questions:
How i Create Access Database at runtime in C#?
How to create Microsoft Access database in C# programmatically?
Now, some more explanations.
Jet vs ACE
First, the ACCDB file format is the result of a complete revamp of Jet now called ACE.
It's only used with Access 2007/2010 and contains new functionalities that are not backward compatible.
To open such a file, you must have either Access 2007/2010 installed (or the free Access Runtime at least) or the specific ACE drivers from Microsoft.
Regarding 32/64 bitness
For the sake of your sanity, regardless of your OS bitness, only use Office and Access 32 bits. Even Microsoft doesn't recommend using the 64 bits version except if you are pushing Excel to its limits.
you can't mix Office 32 bits and 64 bits applications
you can't install the 32 bits and 64 bits ACE drivers on the same machine
Use either the version 2007 or 2010 of the ACE drivers, but avoid having both installed.
make sure that your .Net application is compiled for the same bitness as Access/ACE driver installed (so you should specifically compile to x86 if you follow the advice above, not AnyCPU!).
Performance
You can get very decent performance with an Access database if you keep a few rules:
if possible, keep the database on the same machine as the application that will write to it (avoid network slowdowns)
if your application is the only one using the database, open the database in exclusive mode instead of shared mode:
// Share Mode=16 - use if multiple users must have simultaneous access to the db
string constr = #"Provider=Microsoft.ACE.OLEDB.12.0;Mode=16;Data Source=C:\...\RSLogixDB.accdb;user id=;password=;";
// Share Mode=12 - exclusive mode if only your app needs access to the db
string constr = #"Provider=Microsoft.ACE.OLEDB.12.0;Mode=12;Data Source=C:\...\RSLogixDB.accdb;user id=;password=;";
open a dummy connection to the database when your application starts and keep it open until you don't need the database (to zip it for instance or when your app shuts down).
This is actually a very important performance improvement: opening a new connection to an Access database is expensive because the driver need to create/destroy/update the .accdl lock file.
If you keep an always-open connection to the database, you will greatly speed-up your read/writes to it. For more info on this subject, please check this article:
Where is the OLE DB connection pooling?
Back to the task
The way I would do what you are trying to achieve:
Use Access to manually create a simple database RSLogixDB.accdb with the table that would hold the data.
Also create a dummy table in it with little or no data. We'll use it to keep the connection open and avoid the lock file performance issues.
If you need to re-create the database every day from scratch, then keep a copy of that original database as a template, then copy that template and fill the copy with the new daily data.
If you're the only user of the db, open it in exclusive mode.
Open a connection and read data from the dummy table, but don't close it. Keep it open.
save data to your data table all day long
at midnight, close the database (close the dummy table), make sure the lock file .accdl has disapeared then zip the database.
Replace the database by the template if you need to start with an empty db.
I would also compact the database to reduce its size before zipping it.
If the standard performance of ADO.Net data access is insufficient for your case, have a look at using the native DAO routines. Check out the answer to this SO question:
Writing large number of records (bulk insert) to Access in .NET/C#
If you ever need the connection string for connecting to a particular database then the first stop should always be http://www.connectionstrings.com/
For Access you'd probably find this page helpful: http://www.connectionstrings.com/access-2007
I found this for you. Connecting to MS Access (Windows 7)
also this forum thread will help you.
Thanks
Paul.
I believe that your connection cannot be established because the Jet OLEDB driver does not come with Windows 7, but needs to be installed separately. One way to do this is to install Microsoft Access, another way is to look for the MDAC redistributable package from Microsoft (MDAC = Microsoft Data Access Components).
You can check if - and if yes - which version of MDAC you have by following the instructions on the following link:
http://support.microsoft.com/kb/301202/en-us
As for now (AUG22), you can have both x32- and x64-bit OLEDB/ACE (/MS Access Database Microsoft.Jet.OLEDB.4.0 and Microsoft.ACE.OLEDB.12.0) drivers installed on the same PC:
I have followed the setup instructions from this article "Using Database Libraries with 32-bit and 64-bit Altium Design Software on the same Computer" and they worked well for me for Win10 Professional x64 v.21H2 (Build 19044.1826) with MS Office x32.
I'm using x32 OLEDB drivers with the legacy VS2019 .NET Framework 4.7.x applications' solutions and x64 ACE drivers with the (modern) VS2022 applications' solutions.

Connecting to databases in C# : ArgumentException

I'm running Visual Studio Developer Preview 2011 on a Windows 7 x64 machine.
I'm a beginning to learn C# and am having difficulties connecting to a database. I created a database with MS Access and created a connection by using the Connect to a Database option.
Here is the connection string
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\USER\Documents\BlankDB.mdb
I am following this tutorial
I added the variable masterConnectionString to the Project Settings and initialized it with the value of the connection string.
The program compiles but at run-time I get the following error
A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll
Additional information: Keyword not supported: 'provider'. After this the program terminates.
If I remove the provider part from the string the following exception is thrown.
Additional information:
A network-related or instance-specific error occurred while establishing a connection to SQL Server.
The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
(provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I have been trying for sometime now and this is really frustrating. Is there some other easier method of connecting to databases in C# ? Is it possible to create a SQL Server database from within Visual Studio?
Here is the code that I use to connect to the data base.
static void TryCreateTable()
{
using (SqlConnection con = new SqlConnection(DogsDB.Properties.Settings.Default.BlankDBConnectionString))
{
con.Open();
try
{
using (SqlCommand command = new SqlCommand("CREATE TABLE Dogs1 (Weight INT, Name TEXT, Breed TEXT)", con))
{
command.ExecuteNonQuery();
}
}
catch
{
Console.WriteLine("Table couldn't be created.");
}
}
}
You are following a tutorial for sql server. To connect to your MS Access db, your connection code should look something like this:
OleDbConnection sqlConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\USER\\Documents\\BlankDB.mdb");
Make sure the backslashes are escaped.
Then you can do
try{
sqlConn.Open();
OleDbCommand command = new OleDbCommand("CREATE....", sqlConn);
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
catch(InvalidOperationException ioe)
{
....
}
catch(OleDbException ode)
{
....
}
sqlConn.Close();
That's an OleDB connection string, not a SQL Server connection string.
You need to use it with an OleDbConnection.
If you want to use SQL Server rather than Access, you can create a database using SQL Server Management Studio or VS's Server Explorer.
You can then connect to it using a SQL Server connection string.
You can see sample connection strings here.
There are several reasons you are getting this error.
1) The reference website is to use SQL Server database not Access.
2) You are running on a x64 operating system which means the following is true.
The Microsoft OLE DB Provider for Jet and the Jet ODBC driver are available in 32-bit versions only. You can't run them in 64 bit mode.
For example, you have a 32-bit application that uses the Microsoft OLE DB Provider for Jet. If you migrate the application to run in the
64-bit mode, the application cannot connect to the data source by
using the Microsoft OLE DB Provider for Jet. This issue occurs because
the application requires a 64-bit version of the Microsoft OLE DB
Provider for Jet. Note also that a website can be either an 32 bit or
64 bit application.
So the solution is use the following:
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=13255
If you run a program in a 64 bit environment and need to utilize jet
to open an access, excel or text file there are several options to
make this work. •Run the program in WoW64 mode (emulates 32-bit on 64
bit systems). This will make the 32 bit drivers work. •If the
application is an web app hosted on IIS 7 you can choose to configure
the web sites application pool to run in 32-bit mode. •With the new
Office 2010, there will be new drivers coming, "2010 Office System
Driver", which will be provided as booth 32-bit and 64-bit versions.
You can use these drivers to let you application connect to Access,
Excel and text-files in a 64 bit environment, utilizing the new 64 bit
drivers. The provider name is "Microsoft.ACE.OLEDB.14.0". You don't
need to buy or install the Office suite, the components are available
as a separate download.
If you want additiona assistance you will have to provide the code your using.
You should update the code in your question AFTER you have researched and installed the linked library.

Local database, I need some examples

I'm making an app that will be installed and run on multiple computers, my target is to make an empty local database file that is installed with the app and when user uses the app his database to be filled with the data from the app .
can you provide me with the following examples :
what do I need to do so my app can connect to its local database
how to execute a query with variables from the app for example how would you add to the database the following thing
String abc = "ABC";
String BBB = "Something longer than abc";
and etc
Edit ::
I am using a "local database" created from " add > new item > Local database" so how would i connect to that ? Sorry for the dumb question .. i have never used databases in .net
Depending on the needs you could also consider Sql CE. I'm sure that if you specified the database you're thinking of using, or your requirements if you're usure you would get proper and real examples of connection strings etc.
Edit: Here's code for SqlCe / Sql Compact
public void ConnectListAndSaveSQLCompactExample()
{
// Create a connection to the file datafile.sdf in the program folder
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\datafile.sdf";
SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);
// Read all rows from the table test_table into a dataset (note, the adapter automatically opens the connection)
SqlCeDataAdapter adapter = new SqlCeDataAdapter("select * from test_table", connection);
DataSet data = new DataSet();
adapter.Fill(data);
// Add a row to the test_table (assume that table consists of a text column)
data.Tables[0].Rows.Add(new object[] { "New row added by code" });
// Save data back to the databasefile
adapter.Update(data);
// Close
connection.Close();
}
Remember to add a reference to System.Data.SqlServerCe
I'm not seeing anybody suggesting SQL Compact; it's similar to SQLite in that it doesn't require installation and tailors to the low-end database. It grew out of SQL Mobile and as such has a small footprint and limited feature-set, but if you're familiar with Microsoft's SQL offerings it should have some familiarity.
SQL Express is another option, but be aware that it requires a standalone installation and is a bit beefier than you might need for an applciation's local cache. That said it's also quite a bit more powerful than SQL Compact or SQLite.
Seems like you're:
-Making a C# app that will be installed and run on multiple
computers
-That needs a local database (I'm assuming an RDBMS)
-You need to generate a blank database at installation
-You then need to be able to connect to the database and populate it when
the app runs.
In general, it seems that you need to read up on using a small database engine for applications. I'd start by checking out SQLite, especially if you need multi-OS capability (eg., your C# program will run on Microsoft's .NET Framework and Novell's Mono). There are C# wrappers for accessing the SQLite database.
I believe this question is about the "Local Database" item template in Visual Studio:
What are you considering as a database? From what little you've provided in your question, I'd suggest SQLite.
You can get sample code from their site Sqlite.NET
Not sure I fully understand what you're asking but Sqlite is a good option for lightweight, locally deployed database persistence. Have a look here:
http://www.sqlite.org/
and here for an ADO.NET provider..
http://sqlite.phxsoftware.com/
For 1)
The easiest way to provide this functionality is through SQL Server Express User Instances. SQL Server Express is free, so your user does not have to pay additional license for SQL Server, and the User Instance is file-based, which suits your requirement.
For 2)
This is a big topic. You may want to go through some of the tutorials from Microsoft to get the feeling of how to connect to DB, etc.

Categories

Resources