OLEDBConnection.Open() generates 'Unspecified error' - c#

I have an application that uploads an Excel .xls file to the file system, opens the file with an oledbconnection object using the .open() method on the object instance and then stores the data in a database. The upload and writing of the file to the file system works fine but I get an error when trying to open the file on our production server only. The application works fine on two other servers (development and testing servers).
The following code generates an 'Unspecified Error' in the Exception.Message.
Quote:
System.Data.OleDb.OleDbConnection x = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + location + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'");
try
{
x.Open();
}
catch (Exception exp)
{
string errorEmailBody = " OpenExcelSpreadSheet() in Utilities.cs. " + exp.Message;
Utilities.SendErrorEmail(errorEmailBody);
}
:End Quote
The server's c:\\temp and c:\Documents and Settings\\aspnet\local settings\temp folder both give \aspnet full control.
I believe that there is some kind of permissions issue but can't seem to find any difference between the permissions on the noted folders and the folder/directory where the Excel file is uploaded. The same location is used to save the file and open it and the methods do work on my workstation and two web servers. Windows 2000 SP4 servers.

While the permissions issue may be more common you can also encounter this error from Windows file system/Access Jet DB Engine connection limits, 64/255 I think. If you bust the 255 Access read/write concurrent connections or the 64(?) connection limit per process you can get this exact same error. At least I've come across that in an application where connections were being continually created and never properly closed. A simple Conn.close(); dropped in and life was good. I imagine Excel could have similar issues.

Try wrapping the location in single quotes
System.Data.OleDb.OleDbConnection x = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + location + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'");

If you're using impersonation you'll need to give permission to the impersonation user instead of/in addition to the aspnet user.

Anything in the inner exception? Is this a 64-bit application? The OLEDB providers don't work in 64-bit. You have to have your application target x86. Found this when getting an error trying to open access DB on my 64-bit computer.

I've gotten that error over the permissions thing, but it looks like you have that covered. I also have seen it with one of the flags in the connection string -- you might play with that a bit.

Yup. I did that too. Took out IMEX=1, took out Extended Properties, etc. I managed to break it on the dev and test servers. :) I put those back in one at a time until it was fixed on dev and test again but still no workie on prod.

not sure if this is the problem you are facing,
but, before disposing of the connection, you should do Connection.Close(),because the Connection.Dispose() command is inherited from Component and does not properly dispose of certain connection resources.
not properly disposing of the connection could lead to access issues.

Related

How do I create a generic file path to a local database in a C# Application?

I have a simple data entry Windows Form with a datagridview display that links to a local database. When I run the program and try to add data on another computer, I get this message:
Unhandled exception has occurred in your application. If you click Continue, the application will ignore this error and attempt to continue. If you click Quit, the application will close immediately.
An attempt to attach an auto-named database for file C:\Users\roberto.yepez\Documents\Visual Studio\2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."
The file path is to the path on the computer where I coded the program.
Here is my code:
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\roberto.yepez\Documents\Visual Studio 2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf';Integrated Security=True".ToString());
I am a self-taught coder, please help! :)
I believe you're running into a problem because your local sql server to which your code is trying to attach the StudentInfo1.mdf (whose path is in the connection string) already contains a database called StudentInfo1 - it decided to try and create a database of this name based on the name of the mdf file. I'm guessing that you can pick your own name by specifying Initial Catalog in your connection string but this would mean there are two databases with possibly the same set of tables and a potential for confusion
Per the comment I posted I would instead advocate that you use SQL Server Management Studio to permanently attach your db (you make have already done this) and then adjust your connection string so that it refers to the permanently attached db. This reduces the chances that your next question will be "my code says it's updating my db but I cannot see any changes!?"
Please move this connection string
"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\roberto.yepez\Documents\Visual Studio 2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf';Integrated Security=True"
to app.config file. When you deploy to production, change the paths in that app.config, according to the production machine settings.
You can even apply transformations on the app.config to deploy in various machines/scenarios.

C# Connection string save into AppData?

So I have a DB (webster.accdb) which will be getting installed on a server (eg. \SERVER\WEBSTER)
However different locations may have differing SERVER names (ADMIN1 etc etc)
When the program originally installs, it checks the con string in app.config which I have put as "DEFAULT" - literally the string.
The program checks the connection string in app config, and if it is DEFAULT, then it runs a little prompt i have made which asks for details from the user regarding the server name and a few other specifics.
They click "connect" and it writes the newly constructed connection string to app.config and the program loads after a series of tests.
Now this works under VS tests and installs on D: drives in temp folders. My issue is that if 'properly' installed to the programfiles section, then we now have the issue of access being denied to alter the file.
So could someone point me in the right direction with regards to the correct process as i know I'm doing it wrong:
Create an XML in Appdata for the user, which has the con strings, and this is generated on first use, and is used for the constrings from then on?
Save the con strings as Settings, and use This code to update settings, then make sure all my con strings in my program no longer point to configuration, but to settings??
Something better because I am clueless and this is totally not how i should be doing this at all!
Code used to update the config:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["LOTSConnectionString"].ConnectionString = "Data Source=" + txtpcname.Text + ";Initial Catalog=" + cmbdispense.SelectedItem + ";Integrated Security=False;User ID=webbit;Password=ill923r6MG";
config.Save(ConfigurationSaveMode.Modified, true);
Access Denied means the user which is executing the app either does not have permission or because of inbuilt security by Operating System, app is executing under restricted permissions. Try executing app with Administrator by right clicking on it and choosing run as.
You can prevent this by Setting up connection string at the time of installation instead. Prompt a user to enter details during installation.
So pretty much I self confess to not understanding the benefits of the USER section of the config.
I have changed my connection strings to just "STRING" and put in the USER section of Settings.
Now i can refer to my strings as
properties.settings.default["ConString"].tostring
This is then saved to User/APPDATA/Local
For noobs like me reading this, that means the original app.config file in programfiles stays THE SAME, but an excerpt is taken out of it relating to the user section and put into appdata.
What was confusing me the whole time was selecting "connection string" in settings, which didnt allow selection as a USER setting.

SQL Server CE Local Application issues

I'm here for a trouble with SQL Server CE in a C# application.
This is a really simple question, at first I was trying to do an INSERT into a table, but it didn't do it, so I searched and the solution was to put the literal string to connect to the database.
try
{
cnTrupp.Open();
SqlCeCommand com = new SqlCeCommand("INSERT INTO tipo_venta(nombre) VALUES (#nombre)", cnTrupp);
com.Parameters.AddWithValue("#nombre", pNombre);
com.ExecuteNonQuery();
com.Dispose();
}
catch (SqlCeException e)
{
LogFile log = new LogFile(e.Message);
}
finally
{
cnTrupp.Close();
}
After that with the literal string, I was wondering, when I deploy the app, how I'm supposed to change that connection string? so it points to the actual database in the new computer
The comments on "Paul Sasik"'s post talk about the Data Source=|DataDirectory|\example.sdf entry in the app.config file of your application.
For the sake of completeness: This |DataDirectory| part is a macro that expands automatically to the folder where your application is running and should not be hardcoded. If you want to change the folder, you may use the following line in Program.cs:
AppDomain.CurrentDomain.SetData("DataDirectory", <New Folder>);
At least this is true for desktop applications. As mobile applications (in VS 2005 and 2008) don't support the same configuration mechanism, you have to create the connection string manually there.
Make use of the .NET app.config file. This is a VB article but will get you started.
.NET config files are fairly easy to work with but with information like a db connection, you might want to consider encrypting the string in the config file. Or at least the password. That is if security is a concern. Many times it's not. Especially on mobile devices which are inherently unsecure (at least in the WinCE world... up to CE5 v.6)

connect Access via c#

i need to open a connection to a remote access db.
in the local environment to the remote acess db is working great .
when i run this application from production server (other server) it's fail with message
"
It is already opened exclusively by another user, or you need permission to view its data.
"
my code :
conString =
#"Provider=Microsoft.JET.OLEDB.4.0;"
+ #"data source=" \\150.248.248.38\d$\TestApp\vending.mdb;Jet OLEDB:Database Password=1234;";
OleDbConnection connAccess = new OleDbConnection(conString);
try
{
connAccess.Open();
objDiningRoom.Connection = connAccess;
....
}
catch (Exception ex)
{
}
finally
{
connAccess.Close();
connAccess.Dispose();
}
*Its not open in other place
thanks
This looks like it is a permissions problem.
Make sure you give the IUSR account (or whatever account ASP.NET runs as) read/write permissions to your database.
you can try :here
copied from there :
This commonly occurs when your database file is opened exclusively
by another application (usually MS
Access). Close all applications that
use this database and try again.
This error may occur if the account being used by Internet Information
Server (IIS), (usually IUSR), does
not have the correct Windows NT
permissions for a file-based database
or for the folder containing the
file.
Check the permissions on the file and the folder. Make sure that you
have the ability to create and/or
destroy any temporary files.
Temporary files are usually created
in the same folder as the database,
but the file may also be created in
other folders such as /Winnt. If
you use a network path to the
database (UNC or mapped drive),
check the permissions on the share,
the file, and the folder.
Check to make sure that the file and the data source name (DSN) are
not marked as Exclusive.
Simplify. Use a System DSN that uses a local drive letter. Move the
database to the local drive if
necessary to test.
The "other user" might be Visual InterDev. Close any Visual InterDev
projects that contain a data
connection to the database.
This error may also occur when accessing a local Microsoft Access
database linked to a table where the
table is in an Access database on a
network server. In this situation,
please refer to the following article
in the Microsoft Knowledge Base for a
workaround: Q189408 PRB: ASP Fails to
Access Network Files Under IIS 4.0

Read from Excel using OleDb in a Windows Service?

Disclaimer: I know this is a bad way to do things. It is the only option we have with our client.
Problem:
We need to read data from an Excel file every x amount of time. The data is constantly changing via a 3rd party Excel plug in. The environment for the application is Windows XP, SP1 and .Net 2.0. No upgrading the OS to SP2/3 or upgrading the .Net Framework. Again, this is all per customer parameters.
Here is current code we have:
String sConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Settings.ReutersFilePath + ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\"";
using (OleDbConnection objConn = new OleDbConnection(sConnectionString))
{
try
{
objConn.Open();
_dataSet = new DataSet();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + ConfigurationManager.AppSettings["Excel.WorksheetName"] + "$]", objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(_dataSet);
_dataTable = _dataSet.Tables[0];
objConn.Close();
// Persists new data to a database.
UpdateSQL();
}
catch (Exception ex) { }
finally
{
_isCurrentlyProcessing = false;
if (objConn != null && (objConn.State != ConnectionState.Broken || objConn.State != ConnectionState.Closed))
{
objConn.Close();
}
}
}
This code works when running from console or a Windows form, but when we run it from a Windows service, it cannot access the Excel file. Is there a limitation in XP w/SP1 that doesn't allow interaction with desktop applications like there is in Vista? Can this be done from a service? The reliability of running this from a service is much needed from the client.
Edit:
The service is running as LocalSystem.
Edit #2:
The error I get when running from a service is: The Microsoft Jet database engine cannot open the file ''. It is already opened exclusively by another user, or you need permission to view its data.
The Excel file IS open on the desktop, but it has to be open for it to get updates from the 3rd party application.
In addition to #sontek's answer.
[only applicable If you are the owners/developers of the Spreadsheet in question...]
You may find it easier to work with a "data push" model rather than a "data pull" model. It's usually an easier programming model to push the data via an excel macro directly into your data store, based upon some event from your plug-in. this is often a much better scenario than a service polling on a timer.
Excel doesn't allow you to open a file simultaneously. You need to either create it as a shared workbook or make a copy of the file and work off of the copy.
There is also full excel API (Microsoft.Office.Interop.Excel) that you could try using, which would allow you to hook into the currently opened excel/workbook.
What user is the service running as? Make sure that user has access to the specific file.
It seems most likely that it is a permissions issue. Windows services run under a different user account than desktop applications.
Also, you mention that you are executing this method every x amount of time. Make sure you are using the right timers. http://www.aspfree.com/c/a/C-Sharp/Timer-Objects-in-Windows-Services-with-C-sharp-dot-NET/
And you should be able to attach a debugger to the service by using "Attach to Process" and selecting your host process. This might give you more info on your problem. http://msdn.microsoft.com/en-us/library/7a50syb3(VS.80).aspx
SpreadsheetGear for .NET can open a file even if Excel currently has the file open and it is well suited to using from a Windows Service.
However, the file on disk will not reflect changes which have not been saved by Excel, and SpreadsheetGear would not be able to open a workbook while Excel is in the middle of saving, so the service would have to take that into account.
Disclaimer: I own SpreadsheetGear LLC
You could try making it a shared workbook (Tools > Share Workbook). This lets multiple users edit the same workbook concurrently. I'm not sure if that would work for you as some workbook features get locked down when it is shared

Categories