EDIT: Ok, I noticed I changed the output folder of the project and put the DLL into the old output folder. After putting it in the right output folder Open() works! I get another exception later, but I guess I can fix that...
I am working on a program that is running on .NET on Windows and on Mono on Linux/Mac. I'm trying to add a very simple SQLite logger to it. I added the Mono.Data.Sqlite.dll (of Mono 3.10) to the project references in Visual Studio 2013 and copied a sqlite3.dll (http://www.sqlite.org/2014/sqlite-dll-win32-x86-3080701.zip) into the debug folder (where the program exe is created).
This is my test code:
using Mono.Data.Sqlite;
using System.Data;
namespace Program.Logging
{
class MyLogger
{
public void TestMethod()
{
string connectionString = "URI=file:SqliteTest.db";
IDbConnection dbcon;
dbcon = (IDbConnection)new SqliteConnection(connectionString);
dbcon.Open();
}
}
}
But when I try to run the code I get this error at dbcon.Open():
An unhandled exception of type 'System.EntryPointNotFoundException'
occurred in Mono.Data.Sqlite.dll
Additional information: Der Einstiegspunkt "sqlite3_next_stmt" wurde
nicht in der DLL "sqlite3" gefunden. (The entry point
"sqlite3_next_stmt" was not found in the DLL "sqlite3".)
What am I doing wrong?
EDIT:
string connectionString = "Data Source=file:SqliteTest.db";
An unhandled exception of type 'System.ArgumentException' occurred in
mscorlib.dll. Additional information: URI-Formate werden nicht
unterstützt. (URI formats aren't supported.)
string connectionString = "URI=file:SqliteTest.db,version3";
An unhandled exception of type 'System.ArgumentException' occurred in
Mono.Data.Sqlite.dll. Additional information: Invalid ConnectionString
format for parameter "version3"
It appears you are using the wrong connection string format. The documentation specifies the connection string formats:
[1.1 profile and the old assembly]
URI=file:/path/to/file
[2.0 profile in the new assembly]
Data Source=file:/path/to/file
Since you are targeting sqlite3, I guess you should be using the 2.0 profile format.
string connectionString = "Data Source=file:SqliteTest.db";
They also mention that in the 1.1 profile, sqlite version 2 is used by default, you would have to specify the version if you want to use if you use the old format.
string connectionString = "URI=file:SqliteTest.db,version=3";
Related
I'm trying to learn a bit more about System.Reflection using the official microsoft docs. Specifically I'm trying to run the following example:
// Loads an assembly using its file name.
Assembly a = Assembly.LoadFrom("MyExe.exe");
// Gets the type names from the assembly.
Type[] types2 = a.GetTypes();
foreach (Type t in types2)
{
Console.WriteLine(t.FullName);
}
So I made a new console app using dotnet new console -o=customconsole. I then removed ImplicitUsings from my project file (because I don't like that), and came up with the following code:
using System;
using System.Reflection;
namespace get_type_from_assembly
{
internal class Program
{
static void Main(string[] args)
{
// load assembly using full file name
Assembly a = Assembly.LoadFrom("C:\\Users\\bobmarley\\desktop\\temp\\csharp-reflection\\get-type-from-assembly\\bin\\Debug\\net6.0\\console-custom.exe");
// get type names from assembly
Type[] types2 = a.GetTypes();
foreach (Type t in types2)
{
Console.WriteLine(t.FullName);
}
}
}
}
Then I tried to run the generated executable using dotnet run --project=customconsole. I got the following runtime error:
Unhandled exception. System.BadImageFormatException: Bad IL format. The format of the file 'C:\Users\bobmarley\desktop\temp\csharp-reflection\get-type-from-assembly\bin\Debug\net6.0\console-custom.exe' is invalid.
at System.Runtime.Loader.AssemblyLoadContext.LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, String ilPath, String niPath, ObjectHandleOnStack retAssembly)
at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)
at System.Reflection.Assembly.LoadFrom(String assemblyFile)
at get_type_from_assembly.Program.Main(String[] args) in C:\Users\bobmarley\desktop\temp\csharp-reflection\get-type-from-assembly\Program.cs:line 11
make: *** [Makefile:5: run] Error 1
I'm not sure why this occurs, because I checked and the executable does exist in the specified path. What is happening here and how can I fix it?
A likely reason is that the your project and the loaded assembly target different platforms, i.e. x86 vs x64, In my experience that is a common reason for BadImageFormatException. Another possible reasons is that one targets .net core while the other targets .net framework.
Dynamically loading an assembly will require that it is compatible with your project. If you want to read arbitrary assemblies you probably want some tool that can extract whatever information you are after from the CIL code directly, without actually loading it.
It is simple and silly.
This is the code:
static void Main(string[] args)
{
using (var connection = new SqliteConnection("" +
new SqliteConnectionStringBuilder
{
DataSource = "hello.db"
}))
{
connection.Open();
}
}
It does not work. It can't be simpler, but it still doesn't work. The Internet seems quiet about that problem.
It throws an exception on Open(); Exception is this:
Exception has occurred: CLR/System.NullReferenceException An unhandled
exception of type 'System.NullReferenceException' occurred in
Microsoft.Data.Sqlite.dll: 'Object reference not set to an instance of
an object.' at Microsoft.Data.Sqlite.SqliteConnection.Open() at
archive.Program.Main(String[] args) in
D:\projects\test\Program.cs:line 55
What is going on?
Please note - I am working on a piece of code that was using System.Data.Sqlite and old, 'normal' .net
When I moved to Microsoft.Data.Sqlite (and .net core), it protests.
You need to reference Microsoft.EntityFrameworkCore.SqlLite NuGet package for this to work, if you don't and you only have reference to Microsoft.Data.Sqlite.Core you will get this error.
Getting following exception when loading :
speechRecognizer = new Microsoft.CognitiveServices.Speech.SpeechRecognizer(config);
Inner exception : InnerException = {"Unable to load DLL
'Microsoft.CognitiveServices.Speech.csharp.bindings.dll': The
specified module could not be found. (Exception from HRESULT:
0x8007007E)"}
Microsoft.CognitiveServices.Speech.Internal.carbon_csharpPINVOKE.SpeechConfig_FromSubscription(String
jarg1, String jarg2) at
Microsoft.CognitiveServices.Speech.Internal.SpeechConfig.FromSubscription(String
subscription, String region) at
Microsoft.CognitiveServices.Speech.SpeechConfig.FromSubscription(String
subscriptionKey, String region) |ERROR|The type initializer for
'SWIGExceptionHelper' threw an exception. 2019-01-03
16:02:50.2178|ERROR|The type initializer for
'Microsoft.CognitiveServices.Speech.Internal.carbon_csharpPINVOKE'
threw an exception.
As the exception says, you are missing "Microsoft.CognitiveServices.Speech.csharp.bindings.dll" . You have to include the dll in the project and mark it as part of the deploy. Make sure it appears in the deployed folder in the IIS , copy it manually as last option.
I was developing my app using SQLite, on "Debug" mode, worked perfectly.
When I try to "Release" it (Compiling "Native"), the problem started, looks like UWP doesn't support Reflexion.
I'm currently using this packages:
SQLite.Core.UAP
SQLite.Net-PCL
For example, if I try to do this:
private void CreateDatabase()
{
var dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "StoredEvents.sqlite");
SQLiteConnection SQLiteConn = new SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), dbPath, false);
SQLiteConn.CreateTable<StoredEvents>();
}
These are some of the error:
ILTransform_0027: Method 'CreateLambda' within 'System.Linq.Expressions.Expression' could not be found.
Error at SerializationAssemblyGenerator.Program.AddKnownContractsLists(McgCodeTypeDeclaration container, ContractTables tables)
Severity Code Description Project File Line Suppression State
Error at SerializationAssemblyGenerator.Program.GenerateDataContractSerializerHelperCode(IEnumerable`1 contracts, IEnumerable`1 jsonContracts, IEnumerable`1 wcfSerializers)
ILTransform_0000: MCG : warning MCG0006: Unresolved P/Invoke method '_TPM_Init!tpm.dll' in assembly 'TSS.UWP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it is not available in UWP applications. Please either use an another API , or use [DllImport(ExactSpelling=true)
How should I refactor the code?
Should I use a different Library?
I had the same issue when i was updating my apps from Silverlight to UWP. I read an article somewhere ( Tried to find it but was unable to ) which says SQLlite for UWP is available for Windows 10 deployment.
The above is a VS Extension. You can get there from Tools ->> Extensions & Updates
Below is how my References look like.
Also I noticed that you are not closing your db connection. Always better to use it inside a using statement. your CreateTables() will look something like below.
private void CreateDatabase()
{
var dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "StoredEvents.sqlite");
using (SQLiteConnection SQLiteConn = new SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), dbPath, false))
{
SQLiteConn.CreateTable<StoredEvents>();
}
}
I have a mature C# application that has always been run on Windows that is being ported to Linux (on Mono), and I am running into an error that I cannot resolve regarding PluralizationServices in System.Data.Entity.Design.
The line of code causing the problems is as follows:
PluralizationService pluralizationService = PluralizationService.CreateService(System.Globalization.CultureInfo.InvariantCulture);
Although this has never caused any problems on the Windows application running under Microsoft.NET, when the program is running under Mono I get the following error:
Unhandled Exception:
System.IO.FileNotFoundException: Could not load file or assembly 'System.Data.Entity.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies.
File name: 'System.Data.Entity.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
I found here someone else who seemed to be having a similar problem had simply copied the .NET version of the .dll over to their Mono project, and it resolved the issue for them. I tried the same, however I then encountered the following error:
Unhandled Exception:
System.TypeInitializationException: An exception was thrown by the type initializer for MudSharp.Framework.LanguageHelpers ---> System.InvalidProgramException: Invalid IL code in System.Data.Entity.Design.PluralizationServices.PluralizationService:CreateService (System.Globalization.CultureInfo): method body is empty.
I'm using Mono 3.10 on Ubuntu. I can't find any suggestion that Mono doesn't support these functions, and I'm simply unsure how to proceed with debugging this issue.
Any help would be appreciated.
Looks like latter versions of Mono do support the PluralizationService - see function support status.
However, the PluralizationService currently only supports English.
Have you tried this:
PluralizationService pluralizationService = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en-us"));`
FYI, looks easy enough to extend to other languages using the EntityModelSchemaGenerator class.
Plurally is a Mono-compatible replacement to the Entity Framework pluralization services.
use Plurally test library source code jsonclassgenerator
IDE: Xamarin Studio 6.1.3
framework: Mono / .NET 4.5
add NuGet package: Newtonsoft.Json, Plurally
JsonClassGenerator.cs line 10,39
use Plurally.Pluralizer
using Plurally;
private Pluralizer pluralizationService = new Pluralizer(new CultureInfo("en-us"));
JsonType.csline 8
using Plurally;
Xamasoft.JsonClassGenerator.JsonClassGenerator GenerateClasses Result
{
"UserAccount": "",
"UserPassword": "",
"ExtraInfo": ""
}
// Generated by Xamasoft JSON Class Generator
// http://www.xamasoft.com/json-class-generator
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace CommonModels
{
public class loginArgs
{
public string UserAccount { get; set; }
public string UserPassword { get; set; }
public string ExtraInfo { get; set; }
}
}