Use UWP in WPF Application Throws Error "generating manifest" - c#

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/

Related

JsReport using C# .NET core and Vs

I am trying to learn JsReport using c# and .NET core and visual studio. I have installed the required nuget packages (jsreport.binary and jsreport.Local). I am trying to replicate the code found Here. The problem is that I keep getting the following error.
***Severity Code Description Project File Line Suppression State
Error MSB3021 Unable to copy file "C:\Users\jmodiba\source\repos\js\js\obj\Debug\net6.0\apphost.exe" to "bin\Debug\net6.0\js.exe". Access to the path 'bin\Debug\net6.0\js.exe' is denied. js C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets 5097***
here is the code,
using jsreport.Binary;
using jsreport.Local;
using jsreport.Types;
var rs = new LocalReporting().UseBinary(JsReportBinary.GetBinary()).AsUtility().Create();
await rs.RenderAsync(new RenderRequest()
{
Template = new Template()
{
Recipe = Recipe.ChromePdf,
Engine = Engine.None,
Content = "Hello from pdf"
}
});
I managed to find the problem. My antivirus kept on moving the .exe file created to quarantine. Once I created an exception in the antivirus setting my code ran correctly.

Does SevenZipSharp work with .NETCore on Windows?

I have a .NETCore app which I am trying to add 7 zip functionality to.
Compiling gives this warning:
warning NU1701: Package 'SevenZipSharp 0.64.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework 'net5.0'. This package may not be fully compatible with your project.
So I presume the project is .NETCore v5.0. Can I run SevenZipSharp in this project?
Running the app gives an error at the call to CompressFiles: SevenZip.SevenZipLibraryException: 'Can not load 7-zip library or internal COM error! Message: failed to load library.'
public void ZipQOB(string sevenZipDllPath, string zippedQobPath, string unzippedQobFiles)//List<string> sourceFiles)
{
// throw exception if paths passed in are null, does 7zipsharp throw exceptions in this case?
try
{
if (System.IO.File.Exists(sevenZipDllPath) && System.IO.Directory.Exists(zippedQobPath))// && System.IO.Directory.Exists(unzippedQOBFiles))
{
string path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "7z.dll");
//SevenZipCompressor.SetLibraryPath(sevenZipDllPath);
SevenZipCompressor.SetLibraryPath(path);
SevenZipCompressor sevenZipCompressor = new()
{
CompressionLevel = SevenZip.CompressionLevel.Ultra,
CompressionMethod = CompressionMethod.Lzma
};
string[] files = System.IO.Directory.GetFiles(unzippedQobFiles);
sevenZipCompressor.CompressFiles(zippedQobPath + #"\zip.QOB", files);
//System.IO.Path.ChangeExtension(zippedQobPath, ".QOB");
}
This question How do I use 7zip in a .NET Core app running on Linux? mentions a CLI wrapper ported from .NET Framework to .NET Core, but I can't find any details - is this something I would have to write and how?
I have already tried things suggested elsewhere, I altered the project build setting to:
Platform Target = AnyCPU,
ticked Prefer 32-bit
Should I just look at a different option as this page seems lists some stating .netcore compatible: https://github.com/topics/7zip?l=c%23
Many thanks for any help :)

C# DocX Create File

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.

C# Windows Services using WinSCP assembly mismatch as object reference not set to an instance of an object

I am writing a code to upload a file to an sftp server via WinSCP.
Everything else in my code works except when i started to include WinSCP into the code. The Assembly setup fails as it shows error where Object Reference not set to an instance of an object.
This is running on Windows Services using VS 2010 included with WinSCP .net references.
Below is the code that sets up the assembly , i am not able to use NuGet as that requires higher version of Visual Studio.
So i have to create this assembly which i got from WinSCP web itself however i do not understand what i am missing here.
try
{
Assembly executingAssembly = Assembly.GetExecutingAssembly();
string resName = executingAssembly.GetName().Name + "." + "WinSCP.exe";
using (Stream resource = Assembly.GetExecutingAssembly().GetManifestResourceStream(resName))
using (Stream file = new FileStream(executablePath, FileMode.Create, FileAccess.Write))
{
resource.CopyTo(file);
}
}
catch (System.Exception ex)
{
WriteToFile("Cant setup assembly : " + ex.Message);
Result should be that when the assembly successfully created , then the upload sessions will be able to go through as at the moment the upload sessions i am receiving an error "The version of C:\Windows\TEMP\WinSCP.tmp311D.exe () does not match version of this assembly somedir\WinSCPnet.DLL (5.15.2.0)."
A small assistance will be very helpful.
I found the problem. Apparently, I already have the assembly, that is why the error mentioned that I have the wrong assembly version. But, the main reason it couldn't match is because
The temp WinSCP is created in a folder where my program does not have access to.
I copy-pasted the WinSCP exe instead of Adding via "Add Item" in VS.
I then hard code the executable path to the WinSCP.exe to fix assembly looking into the wrong folder.
My problem has been solved.

How to deploy a .net dll, which invokes UWP OCR API in it?

I have a .NET-wrapper library based on .NET Framework v4.6.1, which invokes UWP OCR API. It contains only one class with one function in it, code is below
public static async Task<string> ExtractText(Stream stream, string language)
{
using (IRandomAccessStream uwpStream = new InMemoryRandomAccessStream())
{
byte[] input = new byte[stream.Length];
stream.Read(input, 0, input.Length);
uwpStream.AsStreamForWrite().Write(input, 0, input.Length);
uwpStream.AsStreamForWrite().Flush();
uwpStream.Seek(0);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(uwpStream);
SoftwareBitmap bitmap = await decoder.GetSoftwareBitmapAsync();
OcrEngine engine = OcrEngine.TryCreateFromLanguage(new
Language(language));
uwpStream.Dispose();
if (engine != null)
{
OcrResult result = await engine.RecognizeAsync(bitmap);
return result.Text;
}
else
{
throw new NullReferenceException("Language is not supported");
}
}
}
Project has links to following UWP libraries: Windows.WinMD, Windows.Foundation.FoundationContract.winmd, Windows.Foundation.UniversalApiContract.winmd. I found their location via object browser in Visual Studio, copied them from their original location to subfolder in my project and then linked them.
My app runs ok on my local machine and UWP OCR Engine works fine.
Then I deploy my library and an application, which uses it, on my virtual machine, which has Windows Server 2012 R2 on it with installed .NET Framework and installed Windows 10 SDK.
My program fails during runtime with the exception:
Could not find Windows Runtime type "Windows.Graphics.Imaging.SoftwareBitmap"
To solve the problem I tried to reinstall Windows 10 SDK on my virtual server and checked that versions match exact versions on my development machine.
It seems like some of the .winmd libraries does not load in runtime.
I expect my program to run successfully on another machine in release mode.
It works on development machine fine.
However, I am new to UWP, so maybe initial information is not enough to solve the problem, but I'm ready to provide more.
Any help would be appreciated
I was able to make my UWP OCR work on Windows Server 2019
It seems like Windows Server 2012 R2 does not support all the functional of Windows 10 SDK
At least my program could not load all the .winmd files required in runtime
Migration to Windows Server 2019 makes it work without any problems

Categories

Resources