DinkToPdf Net Core not able to load DLL files - c#

I am trying to generate PDFs from HTML SQL server database using DinkToPdf library.
In the startup file I have added:
var context = new CustomAssemblyLoadContext();
context.LoadUnmanagedLibrary(Path.Combine(Directory.GetCurrentDirectory(), "libwkhtmltox.dll"));
The line gives me this error on launching the web app:
DllNotFoundException: Unable to load DLL 'C:\Program Files\IIS Express\libwkhtmltox.dll' or one of its dependencies: The specified module could not be found. (Exception from HRESULT: 0x8007007E)
System.Runtime.Loader.AssemblyLoadContext.InternalLoadUnmanagedDllFromPath(string unmanagedDllPath)
DllNotFoundException: Unable to load DLL 'C:\Program Files\IIS Express\libwkhtmltox.dll' or one of its dependencies: The specified module could not be found. (Exception from HRESULT: 0x8007007E)

Just in case anyone else is having the same issue I was able to solve it by installing Microsoft Visual C++ 2015 Redistributable.

It is mentioned in library's git repo that you should download binaries and include them in your source code:
Copy native library to root folder of your project. From there .NET Core loads native library when native method is called with P/Invoke. You can find latest version of native library here. Select appropriate library for your OS and platform (64 or 32 bit).
What was breaking things was that I was going to that url and right click on each file and select save link as(chrome). This leads to a broken file being downloaded:
DON'T DO THAT
you have to open each file within github and then use that Download button.
The healthy file is much bigger than what you would get if you go the wrong way!
ridiculous but the problem may be caused by this ...

On Asp.Net Core application I use it like this to get the current directory on runtime
#if DEBUG
//windows
string filePath = $#"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\libwkhtmltox.dll";
#else
//linux
string filePath = #$"{(($#"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}/libwkhtmltox.so").Replace(#"\", #"/"))}";
#endif
CustomAssemblyLoadContext context = new CustomAssemblyLoadContext();
context.LoadUnmanagedLibrary(filePath);
serviceCollection.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
#endregion

I found some work-arounds. They are not perfect but worth a try, and they did do help and I was able to generate PDFs from SQl Server. I put the .dll files in the following folder and it worked.
C:\Program Files\IIS Express
and the loaded the .dll files with
Path.Combine(Directory.GetCurrentDirectory(), "libwkhtmltox.dll");
The other way I went for the whole Path
context.LoadUnmanagedLibrary(Path.GetFullPath(#"C:\Users\User\source\repos\WebSolution\WebApp\libwkhtmltox.dll"));
Both of them worked. However, I urge Net Core developers to work on the GetCurrentDir very well. Or a Method to load from the Project or Solution Folder
Path.Combine(Directory.GetCurrentDirectory(), "libwkhtmltox.dll");

if you are using asp.net core on Linux then you need to install required packages by using following command
apt-get update \
&& apt-get install -y --no-install-recommends \
zlib1g \
fontconfig \
libfreetype6 \
libx11-6 \
libxext6 \
libxrender1 \
&& curl -o /usr/lib/libwkhtmltox.so \
--location \
https://github.com/rdvojmoc/DinkToPdf/raw/v1.0.8/v0.12.4/64%20bit/libwkhtmltox.so

Related

Running in VS2019 Admin Cmd window -- gacutil.exe error: "Failure adding assembly to the cache. The system cannot find the file specified."

Running in VS2019 Admin Cmd window -- gacutil.exe error: "Failure adding assembly to the cache. The system cannot find the file specified."
GAC util path: C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools\gacutil.exe
Command line: gacutil.exe -i "DuraSysOrdFuncs.dll" -r FILEPATH "C:\Windows\DuraSysOrdFuncs.dll" ""
I picked this version of GACUtil just because the C# library was built with a target framework of .Net 4.7. It isn't clear to me that it much matters.
Doesn't matter what I put in the 3rd parameter of -r. Doesn't matter where I put my assembly on my local disk. Same error message.
I'm trying to put this in GAC because I need to call it from an SSIS package running on SQL Server 2016. I have opened Sysinternals ProcMon per a suggestion of #HansPassant in a different post. Not familiar with tool so haven't found the file location error. . . if that is the actual issue.
Any input much appreciated
The answer, as the commenters noted, and as ProcMon indicates, is to just include the path for the .net assembly you're registering: gacutil.exe -i "C:\YourAssemblyFileLocation\YourDLL.Dll" That's all it takes. . .you don't normally need -r parameters, etc. Thanks!
You can use powershell to register assemblies into GAC. It doesn't need any specific installation.
Set-location "C:\Temp"
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall("C:\Temp\myGacLibrary.dll")
If you need to get the name and PublicKeyToken, refer How do I find the PublicKeyToken for a particular dll?

NuGet pack "The DateTimeOffset specified cannot be converted into a Zip file timestamp"

When I want to pack my library as a NuGet package, I get the below error
The DateTimeOffset specified cannot be converted into a Zip file timestamp
I'm using the below command to pack my project:
dotnet msbuild /t:pack /p:Configuration=Release /p:SourceLinkCreate=true
The problem is; some DLL files have invalid dates for a zip file (like 31/12/1979).
You can overcome this issue by updating all the invalid DLL files modification date.
Here's the Powershell script that updates all the invalid DLLs.
gci -path "C:\" -rec -file *.dll | Where-Object {$_.LastWriteTime -lt (Get-Date).AddYears(-20)} | % { try { $_.LastWriteTime = '01/01/2020 00:00:00' } catch {} }
It sets all the invalid DLL dates to 01/01/2000.
Change the path parameter for your computer.
My GitHub repositories are on my C drive so I'm running this -path C:\.
Seems that in most of cases (basing on research in github issues) the problem was related to Microsoft.Extensions.* packages. In my case update to newer version of Microsoft.Extensions.* (from 3.1.0 to 3.1.4) fixed the problem. For reference :
https://github.com/dotnet/extensions/issues/2750
and mentioned in comments :
https://github.com/NuGet/Home/issues/7001
I made a console app to fix invalid dates in a drive (cross-platform). It sets the LastModificationDate to 01/01/2000. You can just run it without any arguments. It will run in all your drives. Also you can specify a directory to search in.
Source-code on GitHub:
https://github.com/ebicoglu/FileBulkDateChanger
Usage:
FileBulkDateChanger.exe
or
FileBulkDateChanger.exe C:\
For MAC/Linux,
dotnet FileBulkDateChanger.dll
Run this tool and forget about this issue :)

HtmlParser. Failed to load file or assembly

Bug Report
System.TypeInitializationException
HResult = 0x80131534
Message = Initializer type "AngleSharp.Configuration" threw an exception.
Source = AngleSharp
Stack trace:
in AngleSharp.Configuration.get_Default ()
in AngleSharp.BrowsingContext.NewFrom [TService] (TService instance)
in AngleSharp.Html.Parser.HtmlParser..ctor ()
in rsh.Parser_test..ctor () in Z: \ vs \ csharp \ prb \ rsh \ rsh \ Parser_test.cs: line 19
in rsh.Form1..ctor () in Z: \ vs \ csharp \ prb \ rsh \ rsh \ Form1.cs: line 18
in rsh.Program.Main () in Z: \ vs \ csharp \ prb \ rsh \ rsh \ Program.cs: line 19
Internal exception 1:
FileNotFoundException: Failed to load file or assembly
"System.Text.Encoding.CodePages, Version = 4.0.2.0, Culture = neutral, PublicKeyToken = b03f5f7f11d50a3a" or one of their dependencies. Cannot find the specified file.
Can you reproduce the problem in a MWE?
no
Are you running the latest version of AngleSharp?
Version - 0.10.1
Did you check the FAQs to see if that helps you?
used google search. did not help
Are you reporting to the correct repository? (there are multiple AngleSharp libraries, e.g., AngleSharp.Css for CSS support)
see screen
Did you perform a search in the issues?
Searched for phrase: "Failed to load file or assembly"
Description
I get the error "Failed to load file or assembly" during application launch
Steps to Reproduce
Error occurs when starting the application
Environment details: [OS, .NET Runtime, ...]
Win 7x64.
VS - 2017
.NET Framework 4.6.1
Code
using AngleSharp.Html.Parser;
namespace rsh
{
class Parser_test
{
HtmlParser domParser;
public Parser_test()
{
domParser = new HtmlParser();
}
}
}
I installed:
"System.Text.Encoding.CodePages".
Error remained.
Additional reasoning - link
Pic.1
Pic.2
Pic.3
Pic.4
Update-1
Based on - stackoverflow.com/a/40775352/10530657
Completed
Update-Package -reinstall.
Closed, opened Visual Studio.
Opened in Visual Studio 2015.
No result.
Update-2
Installed "AngleSharp - 0.9.11".
The error is gone.
Update-3
Installed - System.Text.Encoding.CodePages
Pic.5
Update-4
Collected the console project,
The project gives an error.
Maybe someone will have the opportunity to check on their side.
Or send me a project that works.
Maybe this will help identify the cause of the error.
The project is made on the basis of documentation "AngleSharp"- documentation . link
Link to the project - link
Question
How to make the error not appear in "AngleSharp - 0.10.01"?
i had the same problem
your project > rightClick > manage nuget packages >
search : System.Text.Encoding.CodePages
install that .
long:
anglesharp nuget details:
.net framework 4.6 requires "System.Text.Encoding.CodePages".
just installing angleSharp, doesn't install the required package automatically. you need to install from nuget package manager.
I had the same exception, and it took me a few minutes to realize....
If you have AngleSharp in a class library, you also need to install it in whatever is consuming the class library.
Oops.

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.

Can't build NUnit testing project under Mono and Linux

I have a complex solution (developed under Windows, deployed under GNU\Linux) with a number of unit-testing projects, using NUnit 2.9.3.
Here's a reference from project:
<Reference Include="nunit.framework, Version=2.9.3.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\Program Files\NUnit 2.9.3\bin\net-4.0\nunit.framework.dll</HintPath>
</Reference>
I downloaded and built NUnit 2.9.3 from source:
$ xbuild solutions/MonoDevelop/NUnit.Framework.sln /p:Configuration=Release
and installed into GAC:
$ gacutil /i solutions/MonoDevelop/bin/Release/nunit.framework.dll
$ gacutil /l nunit.framework
The following assemblies are installed into the GAC:
nunit.framework, Version=2.9.3.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77
Number of items = 1
and deleted local mono nunit installation:
$ rm /usr/lib/mono/2.0/nunit*
$ rm /usr/lib/mono/4.0/nunit*
but when I try to build my solution:
$ xbuild MySolution.sln | grep error
: error CS0006: Metadata file `/usr/lib/mono/2.0/nunit.framework.dll' could not be found
What do I wrong?
Build tools do not normally resolve assemblies from the GAC (except possibly as a last resort). On .NET they they "assembly folders" registered in the registry. On Mono they use "pkgconfig". You may have removed the nunit assemblies but you did not remove or fix the pkgconfig ("pc") file that tells xbuild and MonoDevelop where to find the dll.
This kind of stuff is why it's a bad idea to alter things installed by packages. You should either uninstall the package properly, or use the appropriate environment variables to override packaged stuff.
In this case, I would suggest you create a pc file for your new nunit assemblies, and put it into the /usr/local/lib/pkgconfig directory (/usr/local is the prefix for installing stuff you build from source), or put it somewhere else and have that somewhere else included in the PKG_CONFIG_PATH environment variable.
See also:
The MonoDevelop FAQ entry
And for some general background on configuring Mono environments, see:
Parallel Mono Environments
How not to break Mono installations
What I will try is to copy the NUnit 2.9.3 to my source file folder such as (solution folder)\lib. Then add this reference locally and make sure the tag matches this local path.
When that is configured, I think xbuild should use this local copy directly instead of reading GAC or other preconfigured paths. If not, I will report a bug to Mono team.
The /pkg option of the mono compiler worked fine for me ...
dmcs test.cs /r:System.Configuration.dll /r:System.dll /pkg:nunit
FWIW, I installed nunit using the apt-get package manager (on Ubuntu) ...
sudo apt-get install nunit

Categories

Resources