C# DocX Create File - c#

I want to create, write and read a word file with C#. I was using the DocX Library.
I've tried it in Visual Studio and Visual Studio Code as well and got the following Error:
System.IO.FileNotFoundException: 'Could not load file or assembly 'System.IO.Packaging, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Das System kann die angegebene Datei nicht finden.'
at Xceed.Document.NET.Document.PrepareDocument(Document& document, DocumentTypes documentType) at Xceed.Words.NET.DocX.Create(String filename, DocumentTypes documentType) at ConsoleApp1.Program.Main(String[] args) in Program.cs:line 13
On english: The system can't find the given file.
I was using the latest version of DocX: 2.2.0
If you have an alternative library I could also possibly use it, I just need to be able to write, read and delete word files (.docx).
My Code:
using System;
using Xceed.Words.NET;
using Xceed.Document.NET;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string fileName = #"C:\Test\Test.docx";
var doc = DocX.Create(fileName);
doc.InsertParagraph("Hello Word");
doc.Save();
Console.WriteLine("Hello World!");
}
}
}

There's an issue here in that the DocX NuGet package doesn't install all of the DLLs required for use with the latest versions of .NET.
From the Xceed Words (commercial release) help documentation.
To use .NET 5 or .NET 6, you will also need 2 new DLLs, available on NuGet: System.IO.Packaging and System.Drawing.Common.
If your application is targeting .NET 6.0 (the default if you're using a recent download of Visual Studio 2022 say) then you should open up NuGet Package Manager for the Solution and install the above mentioned packages.
(Click on Browse, enter the exact naming and install the ones by Microsoft).
I have run your code with the Microsoft packages installed alongside the DocX package and it works.

Related

MySQL .NET connector throwing "System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Security.Permissions" [duplicate]

I am using Visual Studio Code, and I'm trying to connect to my MySql server (5.5). I have downloaded the latest (6.10.6) MySql connector and installed it. I had to research to add references in VS Code, but I managed it. Now my .csproj file looks like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Reference Include="Lib\MySql.Data.dll">
<HintPath>MySql.Data</HintPath>
<SpecificVersion>False</SpecificVersion>
</Reference>
</ItemGroup>
</Project>
I have copied the content of C:\Program Files (x86)\MySQL\MySQL Connector Net 6.10.6\Assemblies\v4.5.2 to myProject\Lib. At compile time there are no errors, all green. But when I try to connect using this code
using System.Data;
using System.Security.Permissions;
using MySql.Data;
using MySql.Data.MySqlClient;
public static bool Connect(){
string str = "server=192.168.0.160;user=usr;database=DB;port=3306;password=pass";
MySqlConnection connection = new MySqlConnection(str);
connection.Open();
System.Console.WriteLine(connection.State);
return true;
}
it fails, and produces this error:
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in MySql.Data.dll: 'Could not load file or assembly 'System.Security.Permissions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system can't find the file.'
I do not know why, as the using directive is not signaling an error.
The assembly System.Security.Permissions is currently not available for .NET core applications so my guess is you are using an older version of MySQL Database Provider that is not compatible with .NET core 2.
According the official documentation .NET core 2.0 is only supported from version 6.10.
Try installing the latest version from: https://dev.mysql.com/downloads/connector/net/6.10.html
Edit
If you already have that version and it is still not working, might be that you are missing some references. Why don't you try using the official NuGet instead of referencing the dll in the GAC, here is the command:
Install-Package MySql.Data -Version 6.10.6
If you are using VS Code, you can use the NuGet package manager extension to manage the packages directly from the editor: https://marketplace.visualstudio.com/items?itemName=jmrog.vscode-nuget-package-manager
Edit 2
Seems it might be a bug as I found this question .NET Core 2 with MySql.Data results in permission error and the accepted answer recommends updating to version 8.
So try to update to version 8.0.10-rc and let the problem be gone, here is the NuGet command:
Install-Package MySql.Data -Version 8.0.10-rc
Can't just upgrade the MySQL connector because there may be compatibility issues between newer connectors and legacy databases.

Error on SSIS Script Task to load data from MongoDB to SQL Server: Could not load file or assembly MongoDB.Driver.Core

I want to create a Script Task to load data from MongoDB to SQL Server.
I am using Visual Studio 2017 and target SQL Server version is 2017.
The default target .NET Version of the script task based on the above is 4.5, therefore I got the 2.3 version, which was the latest to target 4.5
In order to get the dlls, I first used NuGet to download the packages and then copied the following dlls:
MongoDB.Driver.dll
MongoDB.Driver.Core.dll
MongoDB.Bson.dll
I followed instructions from here:
http://codeingaddiction.blogspot.com/2011/06/how-to-add-strong-name-to-existing-dll_16.html
In order to produce strong named dlls.
Finally, I added the dlls on GAC on the following path
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools
I then created a script task and manually added the 3 dlls.
My test code is the following:
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Core;
using MongoDB.Bson.Serialization;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
public override void PreExecute()
{
base.PreExecute();
}
public override void PostExecute()
{
base.PostExecute();
}
public override void CreateNewOutputRows()
{
MongoClient client = new MongoClient("mongodb://dgm-mongodbdev-01.development.dc.opap:27017");
IMongoDatabase database = client.GetDatabase("sportsbetting-staging");
IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("event");
collection.Find<BsonDocument>(null).Limit(3);
Console.WriteLine(collection);
}
}
Trying to build gives the following error:
Severity Code Description Project File Line Suppression State
Error The type 'IAsyncCursorSource<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'MongoDB.Driver.Core, Version=2.3.0.157, Culture=neutral, PublicKeyToken=null'.
MongoDb Core Driver does not have any additional dependencies that I may have missed. For 4.5 version of .NET the only dependency is MongoDB.Bson which is added as a reference.
The only article I have found for SSIS script task is this:
https://arcanecode.com/2014/01/14/importing-mongodb-data-using-ssis-2012/
Which is obsolete because it used the version 1.x of the driver.
Any ideas? The message seems misleading because it seems clear that I am not missing any dependency.
Finally, my answer was provided on the following post:
How to fix "Referenced assembly does not have a strong name" error?
Apparently,
MongoDB.Driver.Core.dll
MongoDB.Driver.dll
Have reference to
MongoDB.Bson.dll
Therefore, the public key token had to be added on the il files before re-assembling

How to fix the compiler error CS0009 - An attempt was made to load a program with an incorrect format?

I'm trying to reference the Microsoft ActiveX Data Objects 6.1 Library (ADODB) using the csc.exe C# compiler but I'm getting the error:
fatal error CS0009: Metadata file 'c:\Program Files\Common Files\system\ado\msado15.dll' could not be opened -- 'An attempt was made to load a program with an incorrect format. '
I have simplified the files to try tracking the problem.
Batch file Compile.bat:
#ECHO OFF
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\csc.exe -nologo -r:"C:\Program Files\Common Files\system\ado\msado15.dll" Code.cs
PAUSE >NUL
C# file Code.cs:
class Program {
static void Main() {
ADODB.Connection ADODBConnection = new ADODB.Connection();
System.Console.WriteLine((ADODBConnection == null).ToString());
}
}
I have tried copying the dll to the same folder and referencing it but got the same error.
I also have the compilers versions ...\v2.0.50727\csc.exe and ...\v3.5\csc.exe and the libraries versions msado20.tlb, msado21.tlb, msado25.tlb, msado26.tlb, msado27.tlb, msado28.tlb and msado60.tlb.
When I try the same on Visual Studio 2017 (.NET Framework 4 Console Application) it works. It creates ConsoleApp1\ConsoleApp1\obj\Debug\Interop.ADODB.dll and references that instead but I don't know where it gets it from. I have tried searching for it in different folders.
I found the file that Visual Studio uses from this thread (by searching online for Interop.ADODB.dll file location) and later this link:
C:\Program Files\Microsoft.NET\Primary Interop Assemblies\adodb.dll
Working Compile.bat:
#ECHO OFF
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\csc.exe -nologo -r:"%ProgramFiles%\Microsoft.NET\Primary Interop Assemblies\adodb.dll" Code.cs
PAUSE >NUL

Use UWP in WPF Application Throws Error "generating manifest"

I want to use the OCR component of UWP in an WPF C# app.This is done by using a C# class library in other projects. On build I get the following error shown below. How can I get this to compile?
Error 1 Problem generating manifest. Could not load file or assembly
'{MyAppPath}\Windows.winmd' or one of its dependencies. Attempt to
load a program with an incorrect format.
The picture shows the references:
The files are:
System.Runtime.WindowsRuntime: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
System.Runtime.InteropServices.WindowsRuntime: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.6.1\Facades\System.Runtime.InteropServices.WindowsRuntime.dll
Windows: C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Windows.winmd
The Code I want to use (not in a finsished state, I just want it to compile)
using System;
using Windows.Graphics.Imaging;
using Windows.Media.Ocr;
using Windows.Storage;
namespace tegBase
{
public class Scan
{
public static async void OcrAusfuehren()
{
var fileName = #"C:\a.jpg";
StorageFile file = await StorageFile.GetFileFromPathAsync(fileName);
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
SoftwareBitmap b;
b = await decoder.GetSoftwareBitmapAsync();
OcrEngine ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages();
var s = await ocrEngine.RecognizeAsync(b);
Windows.Media.Ocr.OcrResult c = s;
Console.WriteLine(c.Text);
}
}
}
Update:
I tried to reproduce the error on another PC, there however, the UnionMetadata folder is empty. So I took the winmd from 10.0.16299.0, but it lead to the same result.
I also tried changing the target framework from .net 4.5.1 to 4.6.1, which also did not solve the problem. On a sidenote: changing it to 4.7.1 was not possible, as VS said it was not installed. Installing 4.7.1 was also not possible, with the installer message beeing: Higher Version already installed.
You need to download the UWP software development kit (SDK) and migrate the package to package references. This must be done in order to use all the UWP libraries within a WPF/WinForms/Console application. Please visit this website for a step-by-step tutorial: https://www.thomasclaudiushuber.com/2019/04/26/calling-windows-10-apis-from-your-wpf-application/

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.

Categories

Resources