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.
Related
My solution uses the latest version of .net which is 4.8. However, I see the following error message that complaints about a version 4.0 in Azure Pipelines. Can someone let me know how I could resolve this please ?
The error message indicates I need to install 4.0 but I don't think that's the solution. I also opened up the file Microsoft.Common.CurrentVersion.targets and line 1221 has the following. However, I know it is not advisable to edit this file.
<!-- By default if there is no root path set then the task will assume it is Program Files\Reference Assemblies\Microsoft\Framework-->
<GetReferenceAssemblyPaths
Condition="'$(TargetFrameworkMoniker)' != '' and ('$(_TargetFrameworkDirectories)' == '' or '$(_FullFrameworkReferenceAssemblyPaths)' == '')"
TargetFrameworkMoniker="$(TargetFrameworkMoniker)"
RootPath="$(TargetFrameworkRootPath)"
TargetFrameworkFallbackSearchPaths="$(TargetFrameworkFallbackSearchPaths)"
BypassFrameworkInstallChecks="$(BypassFrameworkInstallChecks)"
>
<Output TaskParameter="ReferenceAssemblyPaths" PropertyName="_TargetFrameworkDirectories"/>
<Output TaskParameter="FullFrameworkReferenceAssemblyPaths" PropertyName="_FullFrameworkReferenceAssemblyPaths"/>
<Output TaskParameter="TargetFrameworkMonikerDisplayName" PropertyName="TargetFrameworkMonikerDisplayName" Condition="'$(TargetFrameworkMonikerDisplayName)' == ''"/>
</GetReferenceAssemblyPaths>
The error message:
C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(1221,5): Error MSB3644: The reference assemblies for .NETFramework,Version=v4.0 were not found. To resolve this, install the Developer Pack (SDK/Targeting Pack) for this framework version or retarget your application. You can download .NET Framework Developer Packs at https://aka.ms/msbuild/developerpacks
Note: There are many similar post in SO that suggest to install VS2019. However, I am getting this message while running the application on Azure Pipelines.
Update
From your description, you are using the Microsoft host agent and the pipeline pop out issue 'cannot found NETFramework,Version=v4.0'.
Your environment looks like this:
https://github.com/actions/virtual-environments/blob/main/images/win/Windows2019-Readme.md#net-framework
or
https://github.com/actions/virtual-environments/blob/main/images/win/Windows2022-Readme.md#net-framework
You can see that the Microsoft host agent does not have the environment you mentioned.
Although you can install what you need at the beginning of the pipeline startup, I do not recommend this practice. Because when you choose microsoft host agent, every time you start the pipeline, you will be assigned a brand new azure VM machine, which means you need to install the relevant environment every time.
The recommended approach is to use a self-host agent. Please create a self-host agent based on your local machine (or another machine with the relevant environment), the steps are as follows:
https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/v2-windows?view=azure-devops
Provided above are the installation steps of windows self host agent, the steps should be very simple, if you encounter any problems please let me know.
And after that, you can run your pipeline based on that self host agent like this:
pool:
name: <your agent pool name>
If you are using classic pipeline, just click and select:
(If you run successfully on local, then the agent based on local machine should also be no problem.)
And if this is still unable to solve your issue, could you please remove the in-private information and share the YAML file or JSON file, and let me know at which step you encountered this issue?
When I try to run a c# program on my linux controller I get the following error:
Process terminated. Couldn't find a valid ICU package installed on the system. Set the configuration flag System.Globalization.Invariant to true if you want to run with no globalization support.
at System.Environment.FailFast(System.String)
at System.Globalization.GlobalizationMode.GetGlobalizationInvariantMode()
at System.Globalization.GlobalizationMode..cctor()
at System.Globalization.CultureData.CreateCultureWithInvariantData()
at System.Globalization.CultureData.get_Invariant()
at System.Globalization.CultureInfo..cctor()
at System.StringComparer..cctor()
at System.StringComparer.get_OrdinalIgnoreCase()
at Microsoft.Data.Sqlite.SqliteConnectionStringBuilder..cctor()
I want to install an ICU package to get rid of this error. So I downloaded a package from this site:
Internationnal Components for Unicode
When I installed the package on the controller I still got the message. Is there any proper way to install an ICU package on the linux controller so I can get rid of this message?
P.S. (turning globalization invariant on is not an option because my code (SQL-Server) does not allow it to be on...)
you can disable ICU usage putting this in your .csproj:
<PropertyGroup>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
before running your project, delete manually /bin and /obj
EDIT 04/06/18 => Updated question with last status
So I have this working .Net 4.6 Stateful Service that currently run on my Windows Service Fabric cluster deployed on Azure.
Starting from 09/2017, I should be able to move to Linux: https://blogs.msdn.microsoft.com/azureservicefabric/2017/09/25/service-fabric-6-0-release/
So I'm trying to deploy it on Linux so I can save costs.
First things first, I've migrated all my code from .Net 4.6 to .Net Core 2.0. Now I can compile my binaries without issues. I've basically created new .Net Core projects and then moved all my source code from .Net 4.6 projects to the new .Net Core ones.
Then I've updated my Service Fabric application. I removed my previous SF services from my sfproj, then I've added my new .Net Core ones.
Looks like there is a warning (nothing on the output window though), but it's here anyway if I try to create a new empty Statful service using .Net core 2.0 through the template provided by Service Fabric Tools 2.0 (beta):
So I'm going to live with it.
On my dev machine, I've modified the 2 csproj projects that contain my Stateful services so they can run locally as Windows executables. I've used the win7-x64 runtimeIdentifier.
Running my SF cluster locally on my Windows machine is fine.
Then I've slightly changed the previous csproj files for Linux. I used the ubuntu.16.10-x64 runtimeIdentifier.
Also I've changed the ServiceManifest.xml file to target the linux-compatible binary:
<!-- Code package is your service executable. -->
<CodePackage Name="Code" Version="1.9.6">
<EntryPoint>
<ExeHost>
<Program>entryPoint.sh</Program>
</ExeHost>
</EntryPoint>
</CodePackage>
entryPoint.sh is a basic script that eventually executes:
dotnet $DIR/MyService.dll
Then I've successfully deployed to my secured SF Linux cluster from Visual Studio. Unfortunately I have the following errors for both my stateful services:
Error event: SourceId='System.Hosting',
Property='CodePackageActivation:Code:EntryPoint'. There was an error
during CodePackage activation.The service host terminated with exit
code:134
Looks like my binary crashes when starting. So here are my questions:
Is the approach right to deploy a C# .Net Core SF stateful service on Linux from Visual Studio?
EDIT: looking inside the LinuxsyslogVer2v0 table, I get the following error:
starthost.sh[100041]: Unhandled Exception:
System.IO.FileLoadException: Could not load file or assembly
'System.Threading.Thread, Version=4.1.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'. The located assembly's manifest
definition does not match the assembly reference. (Exception from
HRESULT: 0x80131040)
I found the following bug report: https://github.com/dotnet/sdk/issues/1502
Unfortunately, I still get the error without using MSBuild (using dotnet deploy).
EDIT: further clarification:
My boss want me to run on Linux because starting from D1v2 machines, it's half the price compared to Windows machines (no license etc.)
My .NET Core 2.0 services successfully run on Windows. So the .NET Core port should be fine.
So, this was a real pain in the ass to get it working properly. But it works. Well, kind of.
First, Reliable Services are still in preview on Linux: https://github.com/Microsoft/service-fabric/issues/71
Full Linux support should come very soon (actually it should be available already according to the previous link...).
Now for the details about how to procede, here is some information to help others, because there is just nothing about that on Microsoft documentation and I literally lost 3 days trying to make it work.
1. Do use .NET Core 2.0 for your projects.
It is supported on Linux. On preview for now, but it works.
2. Do use the right RID for your projects.
As of today (April 2018), the right RID to use is ubuntu.16.04-x64.
Edit the csproj files of your Reliable Service projects and set the RID like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<IsServiceFabricServiceProject>True</IsServiceFabricServiceProject>
<RuntimeIdentifier>ubuntu.16.04-x64</RuntimeIdentifier>
<Platforms>AnyCPU;x64</Platforms>
</PropertyGroup>
The fun part is, you should be able to provide multiple RIDs using the RuntimeIdentifiers parameter (with a S at the end) like that:
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<IsServiceFabricServiceProject>True</IsServiceFabricServiceProject>
<RuntimeIdentifiers>win7x64;ubuntu.16.04-x64</RuntimeIdentifiers>
<Platforms>AnyCPU;x64</Platforms>
</PropertyGroup>
So you could build Windows binaries and Linux binaries at the same time.
But it simply doesn't work. When building the project from Visual Studio, I end up with the following directory only:
bin/Debug/netcoreapp2.0/
Only DLLs, no valid entry point. No win7-x64 folder, no ubuntu.16.04-x64, no nothing.
This is a bug, supposed to be fixed, but it's not (I use Visual Studio 15.6.2 all up-to-date as of today). See https://github.com/dotnet/core/issues/1039
3. You need a valid Entry Point for your service.
On Windows it's an executable file (*.exe). On Linux it's not. I ended up getting the Linux C# example and copied/pasted the entry point. https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-create-your-first-linux-application-with-csharp
So basically I now have on my ServiceManifest.xml file of each Reliable Service the following EntryPoint :
<?xml version="1.0" encoding="utf-8"?>
<ServiceManifest Name="XXXX"
Version="1.0.0"
xmlns="http://schemas.microsoft.com/2011/01/fabric"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ServiceTypes>
<!-- This is the name of your ServiceType.
This name must match the string used in RegisterServiceType call in Program.cs. -->
<StatefulServiceType ServiceTypeName="YYY" HasPersistedState="true" />
</ServiceTypes>
<!-- Code package is your service executable. -->
<CodePackage Name="Code" Version="1.0.0">
<EntryPoint>
<ExeHost>
<Program>entryPoint.sh</Program>
</ExeHost>
</EntryPoint>
</CodePackage>
entryPoint.sh is as follows:
#!/usr/bin/env bash
check_errs()
{
# Function. Parameter 1 is the return code
if [ "${1}" -ne "0" ]; then
# make our script exit with the right error code.
exit ${1}
fi
}
DIR=`dirname $0`
echo 0x3f > /proc/self/coredump_filter
source $DIR/dotnet-include.sh
dotnet $DIR/NAME_OF_YOUR_SERVICE_DLL.dll $#
check_errs $?
dotnet-include.sh is as follows:
#!/bin/bash
. /etc/os-release
linuxDistrib=$ID
if [ $linuxDistrib = "rhel" ]; then
source scl_source enable rh-dotnet20
exitCode=$?
if [ $exitCode != 0 ]; then
echo "Failed: source scl_source enable rh-dotnet20 : ExitCode: $exitCode"
exit $exitCode
fi
fi
Both are inside the PackageRoot folder. I specified for both their properties so the Build Action is "Content" and the Copy to Output Directory is "Copy always".
4. Do NOT build using MSBuild !!
Yeah it is supposed to build Linux packages too, or at least it seems so, because MSBuild is able to produce the following files when you right click on your project and click "Build":
Don't trust the apparent success of the operation, it will miserably FAIL to properly execute when deployed. Some *.so files missing and other issues. MSBuild is buggy as hell and misbehaves regarding dependencies.
See for instance this bug report: https://github.com/dotnet/sdk/issues/1502
Still not fixed after almost a year...
Or https://github.com/dotnet/core/issues/977 (got this one, too).
5. Do write some PowerShell script to build the stuff by yourself.
I ended up reinventing the wheel using the following script to build my package:
# Creating binaries for service 1
cd DIRECTORY_OF_MY_SERVICE_1
dotnet publish -c Release -r ubuntu.16.04-x64
# Creating binaries for service 2
cd ..\DIRECTORY_OF_MY_SERVICE_2
dotnet publish -c Release -r ubuntu.16.04-x64
# Creating binaries for service 3
cd ..\DIRECTORY_OF_MY_SERVICE_3
dotnet publish -c Release -r ubuntu.16.04-x64
# Copying ApplicationManifest.xml
cd ..
mkdir PKG\ServiceFabricApplication
echo F|xcopy "ServiceFabricApplication\ApplicationPackageRoot\ApplicationManifest.xml" "PKG\ServiceFabricApplication\ApplicationManifest.xml" /sy
# Copying Service1 files
mkdir "PKG\ServiceFabricApplication\Service1Pkg"
mkdir "PKG\ServiceFabricApplication\Service1Pkg\Code"
xcopy "Service1\PackageRoot\*" "PKG\ServiceFabricApplication\Service1Pkg" /sy /D
xcopy "Service1\bin\Release\netcoreapp2.0\ubuntu.16.04-x64\publish\*" "PKG\ServiceFabricApplication\Service1Pkg\Code" /sy
# Copying Service2 files
mkdir "PKG\ServiceFabricApplication\Service2Pkg"
mkdir "PKG\ServiceFabricApplication\Service2Pkg\Code"
xcopy "Service2\PackageRoot\*" "PKG\ServiceFabricApplication\Service2Pkg" /sy /D
xcopy "Service2\bin\Release\netcoreapp2.0\ubuntu.16.04-x64\publish\*" "PKG\ServiceFabricApplication\Service2Pkg\Code" /sy
# Copying Service3 files
mkdir "PKG\ServiceFabricApplication\Service3Pkg"
mkdir "PKG\ServiceFabricApplication\Service3Pkg\Code"
xcopy "Service3\PackageRoot\*" "PKG\ServiceFabricApplication\Service3Pkg" /sy /D
xcopy "Service3\bin\Release\netcoreapp2.0\ubuntu.16.04-x64\publish\*" "PKG\ServiceFabricApplication\Service3Pkg\Code" /sy
# Compresses the package
Write-host "Compressing package..."
Copy-ServiceFabricApplicationPackage -ApplicationPackagePath .\PKG\ServiceFabricApplication -CompressPackage -SkipCopy
sfproj file is a Visual Studio / MSBuild related project, so you need to build everything by yourself.
The script above produces the same content as the pkg folder created by MSBuild when building your sfproj using Visual Studio. It copies everything on a PKG folder at the root of your solution.
The package structure is detailed here: https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/service-fabric/service-fabric-package-apps.md
6. Now it's time to deploy!
At this point I didn't trusted Visual Studio anymore, so I built my own PowerShell script:
. .\ServiceFabricApplication\Scripts\Deploy-FabricApplication.ps1 -ApplicationPackagePath '.\PKG\ServiceFabricApplication' -PublishProfileFile '.\ServiceFabricApplication\PublishProfiles\Cloud.xml' -DeployOnly:$false -ApplicationParameter:#{} -UnregisterUnusedApplicationVersionsAfterUpgrade $false -OverrideUpgradeBehavior 'None' -OverwriteBehavior 'SameAppTypeAndVersion' -SkipPackageValidation:$false -ErrorAction Stop
It reuses the Deploy-FabricApplication.ps1 script provided by the Service Fabric project template inside the sfproj project. This script parses the Cloud.xml PublishProfile and deploys to your service fabric cluster.
So you specifies the rights values on both PublishProfiles/Cloud.xml and ApplicationParameters/Cloud.xml then execute the script.
It only works if you have the certificate used to secure the cluster installed on your machine, of course.
Do note the first dot '.' is important, because if you don't use it, you'll have the following error:
Get-ServiceFabricClusterManifest : Cluster connection instance is null
See https://stackoverflow.com/a/38104087/870604
Oh, and as there are bugs on the Service Fabric SDK too, you might want to shutdown your local SF cluster too...
https://github.com/Azure/service-fabric-issues/issues/821
7. Now it's time for another deception.
It simply doesn't work, the service crashes on startup. After searching hours inside the LinuxsyslogVer2v0 Azure Storage table (the log table for Linux, located in one of the two Azure Storage Accounts created automatically with the SF cluster), I found that Microsoft own Nuget Packages were buggy too.
Specifically, the Nuget package Microsoft.Azure.Devices doesn't work on version 1.6.0. An issue with a reference of a dll not found or whatever. I rollbacked to a previous version, namely 1.5.1, and it was fixed.
At this point I didn't had anymore energy to create another Github issue about that. Sorry MS, I'm not your QA team, I'm getting tired.
8. Build again using the first PowerShell script, deploy using the second PowerShell script, and you're done.
You've finally deployed C# Reliable Services using .NET Core 2.0 from Visual Studio (kind of, as it's buggy and I used PowerShell) on Windows to a Linux SF Cluster.
Now I still have issues with my ASP.NET Core service, but it will be a story for another day.
Conclusion: TL;DR
The whole thing is a mess. Bugs everywhere. In the SDK, in the tools, in some of Microsoft Nuget Packages. Awful experience. But it is supported (in preview for now) and you can make it work. Hope this post will help...
I was having similar issues, but I believe this is the issue:
In this release, .NET Core 2.0 services are only supported on Service Fabric for Windows. Full cross-platform support for .NET Core 2.0 services on Windows and Linux is coming soon.
From the Service Fabric 6.1 Release Notes
So no Linux as long as you are targeting .net core 2.0.
I have success deploy to Linux service fabric with this help
Open all the service .csproj files and update the RuntimeIdentifier as shown below
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<IsServiceFabricServiceProject>True</IsServiceFabricServiceProject>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
</PropertyGroup>
Update the ServiceManifest.xml to remove .exe extension as shown below
<CodePackage Name="Code" Version="1.0.0">
<EntryPoint>
<ExeHost>
<Program>Web1</Program>
</ExeHost>
</EntryPoint>
</CodePackage>
See https://blogs.msdn.microsoft.com/premier_developer/2018/05/27/running-net-core-2-0-applications-in-a-linux-service-fabric-cluster-on-azure/
*Visual Studio 15.7.3
In trying to build NuGet3, I'm getting the following error:
~/Projects/NuGet3-dev/src/NuGet.CommandLine/project.json(22,46): error: The dependency fx/Microsoft.Build.Framework >= 14.0.0 could not be resolved.
I have no idea why it wouldn't be resolved, since according to
gacutil -l
I have it:
Microsoft.Build.Framework, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
I looked at everything I could find about this issue, but it's almost entirely Visual Studio and Windows based resolutions, and nothing seems to apply to my situation...
How to make this resolve?
(Assuming you are working on https://github.com/NuGet/NuGet.CommandLine ...)
How to resolve?
Use Windows. This project is not designed to be built on Mono. It is integrated with Windows tooling.
Under POSIX systems (thought, some true operating system):
In short, the dependency is resolved using DNX or dotnet (said M$ .Net Core), and its restore command.
The fx/ stands for framework, just drop the prefix, it should be the same. I sow these kind of notations disappear, when passing to DNX. Just try and install it using the DNX process.
since MSBuild targets and props for DNX are not available, the xbuild script from Mono won't work.
You'll have to use one of
the "deprecated" dnvm.sh script and dnx/dnu commands to restore and then build each sub project.
Note: that yet isn't anymore available at download, and the call to dnvm update-self relaces the script by a "404" ...
The "Microsoft .NET Core Shared Framework Host", "dotnet" (that I don't use)
It should mostly work, if you've got Dnx, try this command line, from the src sub-dir of the NuGet3 source code:
(for d in *; do (cd $d && dnu restore && dnu build); done)2>&1|tee build-all.log
For me, using Debian-8, there are build failures:
NuGet.CommandLine.XPlat
NuGet.Configuration, but it succeeds for the "net451" framework
NuGet.Packaging.Core
NuGet.Packaging
NuGet.Protocol.Core.v3, but it's OK #dnxcore50 (don't ask me why) ...
YANote: If code cannot be transformed anywhere but by M$, this is cannot be source code for me : I cannot not use it as a source. This is a secret code, a private code ... something to throw away, and that probably no one cares.
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