Referencing the correct version of Oracle.DataAccess in .NET - c#

I'm trying to reference Oracle.DataAccess from a .NET 4.0 project, written on Visual Studio 2013. My machine's GAC has two versions of Oracle.DataAccess installed: 4.112.1.2 (provided by Oracle version 11gr2) and 4.121.2.0 (provided by Oracle version 12c).
I want to reference version 4.112.1.2 (my project must run with %ORACLE_HOME% set to 11gr2's install location, and referencing 4.121.2.0 causes runtime failures when this is the case). I do not have an admin account on my machine, so I can't just uninstall the 12c dll.
I have tried the following steps to force the executable to load the 4.112.1.2 dll at runtime:
Reference the dll in my .csproj file using the strong name:
<Reference Include="Oracle.DataAccess, Version=4.112.1.2, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86"/>
Updating my App.Config file to force a redirect:
<dependentAssembly>
<assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89b483f429c47342" culture="neutral"/>
<codeBase version="4.112.1.2" href="C:\Path\To\11gr2\Oracle.DataAccess.dll"/>
<bindingRedirect oldVersion="4.121.2.0" newVersion="4.112.1.2"/>
<publisherPolicy apply="no"/>
</dependentAssembly>
I modified my PATH to make the 11gr2 Client's bin directory first on my path:
set PATH="C:\path\to\11gr2\BIN;%PATH%"
No matter what I do, however, the executable loads the 4.121.2.0 dll from the GAC at runtime. Here's what it says when I attach a debugger:
'MyApp.exe' (Managed (4.0.30319)): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_32\Oracle.DataAccess\v4.0_4.121.2.0_89b483f429c47342\Oracle.DataAccess.dll'
I've read through Microsoft's documentation on assembly binding (here and here). I've also read the StackOverflow answers that seem to be related to my issue (here and here), but nothing has worked.
How do I force .NET to load the correct DLL version at runtime from the GAC?
EDIT:
Wernfried's answer leads me to think I may be looking at this the wrong way. Here's exactly what's happening:
I run my application with ORACLE_HOME=C:\ORACLE\ora12c, everything works as normal (database accesses succeed, application is happy)
I run my application with ORACLE_HOME=C:\ORACLE\ora11gr2 (the required version). Application crashes with following exception:
Oracle.DataAccess.Client.OracleException ORA-12557: TNS:protocol adapter not loadable.
<stacktrace follows>
Following the stacktrace, I discovered that the error occurred in the call my application made to create a database connection. I've checked my connection string and verified that it is correct (and that it is the same connection string that was succeeding with 12c). I then discovered that version of the Oracle.DataAccess dll I was calling was the 12c one, not the 11gr2 one. From this, I concluded that I needed to modify the call to load the dll to "force" the 11gr2 one. If I'm barking up the wrong tree, please let me know!

As far as I know, ODP.NET provider 4.112.1.2 works only with Oracle Client 11.2, resp. ODP.NET provider 4.121.2.0 requires Oracle 12.1 Client.
Do you have both versions of Oracle Client installed on your machine?
In order to use one or the other you must also set your PATH environment variable accordingly. PATH must include folder of Oracle client binaries you like to use in your application.
Note, the architectures (i.e. 32-bit vs. 64-bit) have to be all the same at your application, the Oracle Client and the ODP.NET provider.
But why do you like to force a particular version of ODP.NET? I recommend to use this reference
<Reference Include="Oracle.DataAccess">
<SpecificVersion>False</SpecificVersion>
<Private>False</Private>
</Reference>
then your application will load automatically the correct version of ODP.NET no matter what is installed on your machine (or the machine of your customer).
Anyway, in case you like to run test and force particular version of ODP.NET you can use dynamic binding. For this your code like this:
using (OracleConnection con = new OracleConnection(connString))
{
con.Open();
...
}
has to be re-written like this one:
var DLL = default(Assembly);
DLL = Assembly.LoadFrom(#"C:\Path\To\11gr2\Oracle.DataAccess.dll");
// resp for GAC:
// DLL = Assembly.Load(String.Format("Oracle.DataAccess, Version={0}.{1}.*.*, Culture=neutral, PublicKeyToken=89b483f429c47342", 1, 112));
var type = DLL.GetType("Oracle.DataAccess.Client.OracleConnection", true, false);
using ( dynamic con = Activator.CreateInstance(type, connString) ) {
con.Open();
...
}

I believe I have it fixed.
What got it working for me was to unset the ORACLE_HOME environment variable, and to put C:\Path\to\11gr2\bin at the beginning of my path, like so:
set PATH=C:\Path\to\11gr2\bin;%PATH%

Related

XMSFactoryFactory.GetInstance(XMSC.CT_WMQ) returns Fatal error: Failed to initialize XMSFactoryFactory

I'm trying to connect to an IBM message queue using .net and MQ client v8.0.0.5 but I keep receiving the following error:
Fatal error. Failed to initialize XMSFactoryFactory
Could not load file or assembly 'IBM.XMS.Client.Impl, Version=8.0.0.5,
Culture=neutral, PublicKeyToken=d2666ab12fca862b' or one of its
dependencies.
The system cannot find the file
specified.":"IBM.XMS.Client.Impl, Version=8.0.0.5, Culture=neutral,
PublicKeyToken=d2666ab12fca862b
Here's what I've done so far:
Installed MQ Client v8.0.0.5 (x64) on my machine.
Referenced the following assemblies:
amqmdnet.dll
amqmdnsp.dll
amqmdxcs.dll
IBM.XMS.dll
IBM.XMS.Admin.dll
IBM.XMS.Client.Impl.dll
IBM.XMS.NLS.dll
IBM.XMS.Provider.dll
IBM.XMS.Util.dll
Now I also have version v7.5.0.4 installed on my machine and that is having no issues connecting to the queue.
One more thing I noticed is there are no assemblies for v8.0.0.5 in the GAC but the assemblies for v7.5.0.4 are present. Can that be the reason?
Unfortunately, I cannot remove v7.5.0.4 until have both the versions working normally.
Yes, MQ v8.0.0.5 XMS .NET assemblies not being in the GAC is most likely the cause.
You can look at the alternative of using redirection, update app.config file to use the correct version of assemblies your application requires. Look into your MQ installation directory for a file called NonPrimaryRedirect.config. This file contains sample configuration required for application to look for a specific version of MQ/XMS .NET assembly. Copy the contents of this file to your application's app.config file and try. You must ensure all href attributes point to correct path.

Unable to connect to SQlite using mono

In my program I have this simple code:
using System;
using System.Data;
using Mono.Data.SqliteClient;
....
IDbConnection cnx = new SqliteConnection("URI=file:reestr.db");
cnx.Open();
....
And this is how I compile it:
$ mcs Test.cs -r:System.Data.dll -r:mono.data.sqliteclient.dll
It compiles ok. But when I run it with ./Test.exe, I get this error messages:
Missing method .ctor in assembly ....
Unhandled Exception:
System.IO.FileNotFoundException: Could not load file or assembly 'Mono.Data.SqliteClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756' or one of its dependencies.
File name: 'Mono.Data.SqliteClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756'
I'm not sure what I'm doing wrong here and how to repair it.
PS. I'm using Ubuntu as my OS.
It appears that Mono.Data.SqliteClient can not find the native SQLite binaries:
Prerequisites If you do not have SQLite, download it. There are
binaries for Windows and Linux. You can put the .dll or .so along side
your application binaries, or in a system-wide library path.
Ref: http://www.mono-project.com/docs/database-access/providers/sqlite/
To obtain pre-compiled native binaries (or source) for your platform:
http://www.sqlite.org/download.html
Also if you have the SQLite native shared libraries installed, are they available via dlopen? If not, you can assign the LD_LIBRARY_PATH env. var so Mono can find them at runtime.
Linux Shared Library Search Path From the dlopen(3) man page, the
necessary shared libraries needed by the program are searched for in
the following order:
A colon-separated list of directories in the user’s LD_LIBRARY_PATH
environment variable. This is a frequently-used way to allow native
shared libraries to be found by a CLI program. The list of libraries
cached in /etc/ld.so.cache. /etc/ld.so.cache is created by editing
/etc/ld.so.conf and running ldconfig(8). Editing /etc/ld.so.conf is
the preferred way to search additional directories, as opposed to
using LD_LIBRARY_PATH, as this is more secure (it’s more difficult to
get a trojan library into /etc/ld.so.cache than it is to insert it
into LD_LIBRARY_PATH). /lib, followed by /usr/lib.
Ubuntu Notes:
$ sudo apt-get install sqlite
$ ls -1 /usr/lib/libsqlite*
/usr/lib/libsqlite.so.0
/usr/lib/libsqlite.so.0.8.6
$ export LD_LIBRARY_PATH=/usr/lib:$LD_LIBRARY_PATH
$ mono ./Test.exe
I solve the problem in my Mac in this way. Right Click in Mono.Data.Sqlite on References and click in Local Copy. This make mono copy dll to debug folder and your application will find the library.
OBS: Sorry for my bad english.

Oracle .Net ManagedDataAccess Error: Could not load type 'OracleInternal.Common.ConfigBaseClass' from assembly

I have a project that works locally, on our dev server, and on our production server.
When I try to run it on the test server, I get the error below, and I don't know what to do about it beyond stare at my screen blankly. Hints? Process to trace the issue to its source?
I've installed the NuGet package for Oracle 12.2, etc.
Could not load type 'OracleInternal.Common.ConfigBaseClass' from
assembly 'Oracle.ManagedDataAccess, Version=4.121.2.0,
Culture=neutral, PublicKeyToken=89b483f429c47342'. Description: An
unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the
error and where it originated in the code.
Exception Details: System.TypeLoadException: Could not load type
'OracleInternal.Common.ConfigBaseClass' from assembly
'Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral,
PublicKeyToken=89b483f429c47342'.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[TypeLoadException: Could not load type
'OracleInternal.Common.ConfigBaseClass' from assembly
'Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral,
PublicKeyToken=89b483f429c47342'.]
Oracle.ManagedDataAccess.EntityFramework.EntityFrameworkProviderSettings.Oracle.ManagedDataAccess.EntityFramework.EFProviderSettings.IEFProviderSettings.get_TracingEnabled()
+0 Oracle.ManagedDataAccess.EntityFramework.EFProviderSettings.InitializeProviderSettings()
+111 Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices..ctor()
+629 Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices..cctor()
+28
[TypeInitializationException: The type initializer for
'Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices'
threw an exception.]
Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices.get_Instance()
+24
The Web.Config has the following blocks in it:
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</configSections>
AND
<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<dataSource alias="PVMDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=pdxcludds108.pacificorp.us)(PORT=11086))(CONNECT_DATA=(SERVICE_NAME=DDS1086.PACIFICORP.US))) " />
</dataSources>
</version>
</oracle.manageddataaccess.client>
<connectionStrings>
<add name="OracleDbContext" providerName="Oracle.ManagedDataAccess.Client" connectionString="User Id=USERID;Password=WORKINGPASSWORD;Data Source=PVMDataSource" />
<add name="PVMEntities" connectionString="metadata=res://*/Models.PVMModel.csdl|res://*/Models.PVMModel.ssdl|res://*/Models.PVMModel.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string="DATA SOURCE=pdxcludds108.pacificorp.us:11086/DDS1086.PACIFICORP.US;PASSWORD=XXXXXXX;PERSIST SECURITY INFO=True;USER ID=XXX"" providerName="System.Data.EntityClient" />
</connectionStrings>
NOTE: There are other projects working on this server, they're just using a different version of the Oracle client for .Net. None of the others is using only the Managed driver. I am looking for a way to dig into this error, some hint as to where that type is sourced and loaded from.
There is a conflict between Oracle.ManagedDataAccess from NuGet and the one that is installed (by Oracle client installation) on a server and that is registered in GAC.
Unregister Oracle.ManagedDataAccess from GAC and you will get rid of the error: Run command line and navigate to the directory:
{Oracle home}\product\{version}\client_64\ODP.NET\managed\x64
There you should find OraProvCfg.exe file. Run the following command to unregister Oracle.ManagedDataAccess from GAC:
OraProvCfg /action:ungac /providerPath:Oracle.ManagedDataAccess
You have to remove the Oracle.ManagedDataAccess assembly in your GAC (C:\Windows\Microsoft.NET\assembly...)
Use the command tool gacutil to remove the assembly:
C:\Program Files (x86)\Microsoft SDKs\Windows\YOUR_VERSION\bin\NETFX
4.6.1 Tools> gacutil /u Oracle.ManagedDataAccess
Was able to fix it by replacing references in the project to Oracle.ManagedDataAccess and Oracle.ManagedDataAccess.EntityFramework from those installed by the package manager to those installed by the oracle client installer. The versions are the same but the build number is different on those DLLs
As others said you need to remove Oracle.ManagedDataAccess from GAC.
I run {Oracle home}\product\12.1.0\dbhome_1\ODP.NET\managed\x64\unconfigure.bat and {Oracle home}\product\12.1.0\dbhome_1\ODP.NET\managed\x836\unconfigure.bat and it worked
We had the exact same problem as Dylan above. The issue appears to be with that specific Oracle version (4.121.2.0).
The solution was simple: Just go into Nuget and move up to the next version of your Nuget package for the Oracle.ManagedDataAccess.Client, 4.122.1.0.
Once we did that we could have mixed Oracle client or no-client environments or servers with or without the GAC Oracle installed, keep older apps that still use the GAC, and add new projects that use the Nuget packages. Its always a bad idea in these blogs to ask people to uninstall legacy stuff - like remove the Oracle dll in the GAC on a server - when you have environments with many legacy dependancies that still might reference it.
If removing the DLL from the GAC is not an option, consider getting the next version of oracle.managedData.access 12.2.1 and just put them on the server in the bin directory.
Afterwards you need to add an assemblyBinding to your web.config file.
This way you get arround pulling the 12.1.2 version from the GAC during runtime that will case the error.
You do not need to recompile your app against the new version.
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-12.1.2.0" newVersion="12.2.1.0" />
</dependentAssembly>
There is definitely something weird with this issue. I was developing an app on my local server which ran fine but got this error when I uploaded the app to our server. The server has oracle client installed. After looking at this thread I copied the two DLLs (Oracle.ManagedDataAccess.dll & Oracle.ManagedDataAccess.EntityFramework.dll) from within oracle client and replaced the versions in my app bin directory. That fixed the issue.
In my scenario, i have a console application consuming a class library database utility.
I had to reference the Oracle.ManagedDataAccess also on the console application so it can find the dll on runtime.
I don't know if this is the best approach, but worked for me.
good afternoon
I want to share how I solved this same error:
I started by starting visual studio 2019 cmd as administrator.
I ran the following command line in cmd: gacutil -u Oracle.ManagedDataAccess
Basically this command line will remove the Oracle reference from the GAC (Global Assembly Cache), this way it will only get the reference from the package that is in the project (which nuget installs) and not from the oracle client.
You need to install the Oracle Client drivers. The .NET packages don't contain them; they provide a translation from the managed world to the unmanaged. The drivers are in the unmanaged world and need to be installed properly.

How should I be using Npgsql in Appharbor?

I've developed a quick and simple app on my local machine using SQLite to get started. Now that I'm in the middle of working out how to upload to AppHarbor, I'm a bit stuck on getting the link to ElephantSQL to work.
I used the Application PostgreSQL Sample Application to determine that I needed to use the PostgreSQLConfiguration class for my FluentNHibernate configuration and install the Npgsql package to my solution (I got version 2.0.12.1).
When I push the code up to AppHarbor, it builds and deploys happily. When the server starts to spin up the AppDomain, it throws the error Could not load file or assembly 'policy.2.0.Npgsql' or one of its dependencies. Modules which are not in the manifest were streamed in. (Exception from HRESULT: 0x80131043). This isn't logged in the Errors section of the AppHarbor dashboard (perhaps this is a missing feature or a bug?) so I had to turn off CustomErrors to figure out what was going on.
What have I missed?
Additional - I tried downgrading to package version 2.0.11. This did not include the policy.2.0.Npgsql.dll file and when trying to load the app, it fails with the error Unable to find the requested .Net Framework Data Provider. It may not be installed..
I got it working by going down to version 2.0.11 and made sure that the DbProviderFactories configuration section had the correct version number in the type attribute.
<DbProviderFactories>
<add name="Npgsql Data Provider" invariant="Npgsql" description=".Net Framework Data Provider for PostgreSQL Server" type="Npgsql.NpgsqlFactory, Npgsql, Version=2.0.11.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7" />
</DbProviderFactories>
I was running npgsql 2.0.13 beta (December 2013) on AppHarbor and was getting hosed by this issue for a little while, till I discovered that it's not needed if you're running the latest assembly and don't care about bindingRedirects - it's a dll generated by the .net AL.exe/assembly linker tool to roll up the contents of the policy.2.0.Npgsql.config file (check out https://github.com/npgsql/Npgsql/blob/master/src/policyFileBuild.bat to see how that's compiled).
MY CONFIGURATION:
VS2012
.net 4.5
MVC4
Entity Framework 6 (installed via nuget package restore)
npgsql - 2.0.13.91 (installed via nuget package restore)
THE HACKY FIX:
By Deleting it from the build as a post build event (Project Menu --> Properties --> Build Events --> Post Event Command Line), you can bypass the error (which I don't know why doesn't work on AppHarbor).
So add this nonsense:
del $(TargetDir)policy.2.0.Npgsql.dll /F
del $(TargetDir)policy.2.0.Npgsql.config /F
dir $(TargetDir)
del $(TargetDir)_PublishedWebsites\<appname/>\bin\policy.2.0.Npgsql.dll
del $(TargetDir)_PublishedWebsites\<appname/>\bin\policy.2.0.Npgsql.config
dir $(TargetDir)_PublishedWebsites\<appname/>\bin\
This is probably over-kill, but note that the dir dos command statement gives you feedback on the contents of your directories to make sure the files have actually been deleted. This is viewable from Show Log of build activities in AppHarbor.
Regarding the 2 sets of deletes on dll and config from that god awful msbuild packaging routine (/output directory and the /output/_PublishedWebsites) - IMHO - it's better to be thorough if you're killing stuff, but it may be sufficient to simply delete only from _publishedwebsites...
When it gets built in AppHarbor, this will chuck it from the targeted deployment. You might have to wait for a few minutes for the deploy to complete, but it's absence from the deploy will unblock you.
I think this nuget package is missing the policy.2.0.Npgsql.dll file. Can you install the package for 2.0.12 version from official nuget Npgsql package? It has the missing file.
I hope it helps.

Can't get sql server compact 3.5 / 4 to work with ASP .NET MVC 2

I'm using Visual Studio 2008 Pro.
I'm probably missing something very obvious here, but I've been trying to get the CTP for Sql Server compact 4 to work in my asp.net mvc application. I can find next to no instruction on how to set this up or a working example application. My goal is a private install so I can just include it in my web app without having to do sql server setup on my domain hosting. This is really just me shooting the breeze and trying to figure this out. I don't plan to host a market or anything with this.
So, I've copied all the dll's that install in the base 4.0 direction (c:\Program Files\Sql Server compact\v4.0) to a lib folder in my application. I've set the copy to output direction option to 'Copy if Newer'. I then reference the System.Data.SqlServerCE dll and set 'Copy Local' to True.
I created an sdf file via Sql Studio Express. An important note is that I did not see an option for creating a CE 4.0 version of this file, so it was created using CE 3.5. I create a few tables, add a few rows to those tables, copy the *.sdf file to my App_Data directory. It's worth mentioning that, from inside VS 2008, this file never appears in my project, but it does exist in the physical location of the App_Data directory. I'm not sure why this is.
Next, I just try making a basic connection to my sdf file via:
SqlCeConnection conn = new SqlCeConnection("DataSource=rpg.sdf");
This yields the error below:
Unable to load the native components of SQL Server Compact corresponding to the ADO.NET provider of version 8402. Install the correct version of SQL Server Compact. Refer to KB article 974247 for more details.
I figure from here, I'd just try getting Sql CE 3.5 to work. I upgrade my local installation of Sql CE 3.5 to sp2. I copy the dlls at the base location (c:\Program Files\Sql Server compact\v3.5), including removing and readding the version of the System.Data.SqlServerCE dll from my project references.
The curious thing here is when I right click and look at the properties of the referenced SqlServerCE dll, it always says it's version 4.0.0.1.
Guys, I really could use some direction here. I have searched stack overflow, the help docs, books online, and googled. I really haven't found anything that takes this from the very top for either CE 3.5 or 4.0 and tells me exactly what dll's to add, where to put them, how to reference them, how to add the .sdf file to my project, connect to it, and query from it. I did come across a few mentions of an IBuySpy portal sample app that was supposed to use Sql CE 3.5, but can't actually navigate the msdn download maze to get to it. Ideally, I want to setup a private deploy for CE 4.0.
I'm all ears. Suggestions, points, whatever would be highly appreciated. Thank you!
YES I DID SEE THE KB. IT DIDN'T HELP
See it here: http://support.microsoft.com/kb/974247
RESULTS FROM CORFLAG
Okay, tried that and these are my results:
C:\Development\Mvc2MessingAround\Mvc2MessingAround\bin\Lib>corflags System.Data.
SqlServerCe.dll
Microsoft (R) .NET Framework CorFlags Conversion Tool. Version 3.5.21022.8
Copyright (c) Microsoft Corporation. All rights reserved.
Version : v2.0.50727
CLR Header: 2.5
PE : PE32
CorFlags : 9
ILONLY : 1
32BIT : 0
Signed : 1
I would have sworn I installed the x86 version of both versions of Sql CE (3.5/4). The installer might have gotten confused somehow because my processor is 64bit capable, but i'm running Windows xp sp 3 32 bit. The results seem to indicate it's 64 bit. Is that the case?
ADDED DETAILS
To date the configurations below have been tried on 2 machines. Both are Windows xp sp3 32 bit with a 64 bit capable processor. The development environment on both is VS 2008 Pro. The results on machine 2 come after a fresh install of the Sql CE 4 Ctp.
CONFIGURATION #1
myapp\bin\
System.Data.SqlServerCe.dll
myapp\bin\private
amd64
x86
myapp\bin\private\x86
sqlceca40.dll
sqlcecompact40.dll
sqlceer40EN.dll
sqlceme40.dll
sqlceqp40.dll
sqlcese40.dll
myapp\bin\private\amd64
sqlceca40.dll
sqlcecompact40.dll
sqlceer40EN.dll
sqlceme40.dll
sqlceqp40.dll
sqlcese40.dll
Error:
An exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in System.Data.SqlServerCe.DLL but was not handled in user code
Additional information: Unable to load the native components of SQL Server Compact corresponding to the ADO.NET provider of version 8402. Install the correct version of SQL Server Compact. Refer to KB article 974247 for more details.
Code:
SqlCeConnection conn = new SqlCeConnection();
CONFIGURATION 2
Same as #1, but with System.Data.SqlServerCE.Entity.dll at myapp\bin direction.
The page errors before hitting the code above. This is the message:
Could not load file or assembly 'System.Data.SqlServerCe.Entity' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.BadImageFormatException: Could not load file or assembly 'System.Data.SqlServerCe.Entity' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
I've checked the project settings in VS 2008 Pro and the .Net 3.5 framework is set as the target.
CONFIGURATION 3
Same as #1, except the System.Data.SqlServerCE.dll is referenced from the myapp\bin\private folder.
Results are the same as CONFIGURATION #1 (error message is 100% same and the error occurrs on the same line of code).
CORRECT CONFIGURATION
Per Erik's instructions (had I followed them more carefully), the setup should be
myapp\bin
x86
amd64
System.Data.SqlServerCE.dll
Reference the System.Data.SqlServerCE.dll directly from the bin folder for the code. My folly was thinking the Private folder needed to be included, but it doesn't. Do not put the System.Data.SqlServerCE.Entity.dll in the bin folder unless you are using a .net 4.0 solution. I don't think that dll works w/ 3.5.
Helpful link:
Link
SQL CE 3.5 does not work with ASP.NET, you must use 4.0 CTP.
Download from here.
Install the runtime.
Copy the following directory contents (including the x86 and amd64 folders) to the bin folder of your ASP.NET app:
C:\Program Files\Microsoft SQL Server Compact Edition\v4.0\Private
UPDATE: Use System.Data.SqlServerCe.dll from the Desktop folder to avoid Medium Trust issues
myapp\bin\
System.Data.SqlServerCe.dll
myapp\bin\x86
sqlceca40.dll
sqlcecompact40.dll
sqlceer40EN.dll
sqlceme40.dll
sqlceqp40.dll
sqlcese40.dll
myapp\bin\amd64
sqlceca40.dll
sqlcecompact40.dll
sqlceer40EN.dll
sqlceme40.dll
sqlceqp40.dll
sqlcese40.dll
Add a reference to the System.Data.SqlServerCe.dll file you just put in your /bin folder.
Place the SQL Compact sdf file in your App_Data folder.
Add connection string:
<connectionStrings>
<add name ="NorthWind"
connectionString="data source=|DataDirectory|\Nw40.sdf" />
</connectionStrings>
Connect! :-)
using System.Data.SqlServerCe;
protected void Page_Load(object sender, EventArgs e)
{
using (SqlCeConnection conn = new SqlCeConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
conn.Open();
using (SqlCeCommand cmd = new SqlCeCommand("SELECT TOP (1) [Category Name] FROM Categories", conn))
{
string valueFromDb = (string)cmd.ExecuteScalar();
Response.Write(string.Format("{0} Time {1}", valueFromDb, DateTime.Now.ToLongTimeString()));
}
}
}
If your using a connection string that uses a providerName and you haven't installed the SDK, then you also need to add this to you web.config (or app.config)
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Data.SqlServerCe" publicKeyToken="89845dcd8080cc91" culture="neutral"/>
<bindingRedirect oldVersion="4.0.0.0-4.0.0.1" newVersion="4.0.0.1"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0"/>
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.1, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
</DbProviderFactories>
</system.data>
NOTE: the "remove" is needed in case you installed the SDK, as that will put this info in your machine.config
OK, here's a guess, since you're fishing for them.
Run corflags.exe on the assembly you copied to your references directory. What type of machine are you building for? If you're on a 64-bit machine and you're compiling to x64 or anyCpu, make sure that corflags tells you that your references are not 32-bit only references. Maybe it's "falling back" to an the wrong version in your GAC or something. If it tells you that the referenced assembly is 32-bit only, either compile your project as a 32-bit project or find a 64-bit version of the DLL?
If you are installing the SQL CE provider using NuGet, the simplest solution is to add a post-build step to copy these from the NuGet package NativeBinaries folder
The key for me was realizing that the version of System.Data.SqlServerCe.Entity.dll in the Private directory (C:\Program Files\Microsoft SQL Server Compact Edition\v4.0\Private) is 4.0.0.1, where the version beneath the Desktop directory (C:\Program Files\Microsoft SQL Server Compact Edition\v4.0\Desktop\System.Data.SqlServerCe.Entity) is 4.0.0.0. The version of System.Data.SqlServerCe.dll in the Private directory is 4.0.0.0.
I think it was a mistake on the part of Microsoft to distribute an updated SqlServerCe.Entity.dll without a corresponding update to SqlServer.dll.
I build an asp.net web api and hosted it on azure and faced some issues with sql server compact I fix it by:
first remove all system.data.sqlserverce.dll and any dll use it then
installed these tow packages :
Install-Package SqlServerCompact then rebuild
Install-Package EntityFramework.SqlServerCompact -Version 4.3.6 then rebuild
after I did it just worked fine for me + install any NuGet package that depends on system.data.sqlserverce.dll they all just work great
I hope this will help some one
reference

Categories

Resources