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 :)
Related
The method call in C# is like this -
public void GetKey()
{
WSManConnectionInfo connectioninfo = new WSManConnectionInfo();
var ss = new NetworkCredential("xxx.yyyy\\Administrator", "PassFail2Hehe");
connectioninfo.ComputerName = "<some IP Address>";
connectioninfo.Credential = new PSCredential(ss.UserName, ss.SecurePassword);
//Runspace runspace = RunspaceFactory.CreateRunspace(connectioninfo);
//runspace.Open();
using (PowerShell ps = PowerShell.Create())
{
var re = ps.AddScript("Get-Service");
var results = re.Invoke();
}
}
I am using the NuGet package 'Microsoft.PowerShell.5.ReferenceAssemblies 1.1.0', as it is showing as the recommended package in Visual Studio 2019 for resolving the types of "Runspace", "PowerShell" etc.
However, I am getting the exception when the instance of "Runspace" or "PowerShell" is created. The exception is like this - "Common Language Runtime detected an invalid program."
I found this post and realized that I was getting the warning indeed for the NuGet package -
"Package 'Microsoft.PowerShell.5.ReferenceAssemblies 1.1.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."
As per suggested in the post, I installed Powershell Core 7.1.3, but the warning and exceptions were not resolved. Then I switched to ".Net Standard 2.0", since it the project was a class library, but nothing changed. The same warning message and exception.
How can I make remote PowerShell call using ".Net Core 5.0" (or ".Net Standard 2.0") ?
If you want to target .Net 5, the correct nuget package to use is Microsoft.PowerShell.SDK
I'm trying to get pythonnet to work in my .Net Core app running on Linux.
I've made a reference to Python.Runtime.dll (which I got from nuget) in my .Net Core project.
My code is:
using System;
using Python.Runtime;
namespace pythonnet_w
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Start");
using (**Py.GIL()**) {
// blabla
}
Console.WriteLine("End");
}
}
}
I get this runtime error:
Unhandled Exception: System.MissingMethodException: Method not found: 'System.Reflection.Emit.AssemblyBuilder
System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName, System.Reflection.Emit.AssemblyBuilderAccess)'.
at Python.Runtime.CodeGenerator..ctor()
at Python.Runtime.DelegateManager..ctor()
at Python.Runtime.PythonEngine.Initialize(IEnumerable`1 args, Boolean setSysArgv)
at Python.Runtime.PythonEngine.Initialize(Boolean setSysArgv)
at Python.Runtime.PythonEngine.Initialize()
at Python.Runtime.Py.GIL()
at pythonnet_w.Program.Main(String[] args) in D:\Development\~.Net libraries (3.part)\phytonnet\.Net Core test (phytonnet)\c#\pythonnet_test\Program.cs:line 10
/usr/sbin/pythonnet_w: line 5: 19487 Aborted dotnet "/usr/share/pythonnet_wit/pythonnet_w.dll"
Tried to find a solution in these threads but without any luck:
How do I run a py file in C#?
Call Python from .NET
UPDATE:
I tried to open \pythonnet-master\src\runtime**Python.Runtime.csproj** in Visual Studio to see if I can compile it to .Net or .Core, but I can only compile to .Net framework.
I found this article "How to port from .net framework to .net standard"
Is that what I have to do?
I finally had success by using a self-compiled Python.Runtime.dll as of version 2.4.0. There are two options to create a working DLL:
Remove the other target framework net461 from the respective project file (leaving only netstandard2.0).
Run dotnet build using the appropriate options
For option 2, the following works(in Windows, Mac and Linux):
Clone the pythonnet repo (https://github.com/pythonnet/pythonnet)
In the pythonnet folder, cd src\runtime
Run dotnet build -c ReleaseWinPY3 -f netstandard2.0 Python.Runtime.15.csproj in Windows(in Mac/Linux, replace ReleaseWinPY3 with ReleaseMonoPY3 because the former use python37 and the later use python3.7)
Set DYLD_LIBRARY_PATH in Mac or LD_LIBRARY_PATH in linux(Windows skip):
export DYLD_LIBRARY_PATH=/Library/Frameworks/Python.framework/Versions/3.7/lib
Use the built DLL bin\netstandard2.0\Python.Runtime.dll as DLL reference in your Visual Studio .NET Core project (mine targets netcoreapp2.2, netcoreapp3.1 is also tested ok), e.g. in conjunction with the following code,
using System;
using Python.Runtime;
namespace Python_CSharp
{
class Program
{
static void Main(string[] args)
{
using (Py.GIL())
{
dynamic os = Py.Import("os");
dynamic dir = os.listdir();
Console.WriteLine(dir);
foreach (var d in dir)
{
Console.WriteLine(d);
}
}
}
}
}
You can host the IronPython interpreter right in your .NET application. For example, using NuGet, you can download the right package and then embed the script execution (actually the IronPython engine) right into your application.
Ref:
https://medium.com/better-programming/running-python-script-from-c-and-working-with-the-results-843e68d230e5
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/
As stated in official document, I am trying to implement UseOwin in the Startup.cs.I am trying to use/port IAppBuilder (Microsoft.Owin.Builder.AppBuilder) inside IApplicationBuilder (Microsoft.AspNetCore.Builder.IApplicationBuilder). I had legacy code written using IAppBuilder running fine on .Net Framework 4.5.
I have seen couple of examples about using IAppBuilder in IAplicationBuilder e.g. example 1 example 2. These attempts were about .netcore 1.1 and not .net core 2.0. May be this is the reason i am unable to port.
Please share your thoughts whether i am trying to achieve something not possible at the moment in .net core 2.0 or there is some error in my code.
Note:
I am using dotnetcore 2.0 with Visual Studio 2017
Error
I am getting following error.
return owinAppBuilder.Build,
Task>>(); TypeLoadException: Could not load type
'System.Security.Cryptography.DpapiDataProtector' from assembly
'System.Security, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'.
My attempt
app.UseOwin(setup => setup(next =>
{
var owinAppBuilder = new AppBuilder();
var aspNetCoreLifetime =
(IApplicationLifetime)app.ApplicationServices.GetService(typeof(IApplicationLifetime));
new AppProperties(owinAppBuilder.Properties)
{
OnAppDisposing = aspNetCoreLifetime?.ApplicationStopping ?? CancellationToken.None,
DefaultApp = next,
AppName = "test"
};
// Only required if CORS is used, configure it as you wish
var corsPolicy = new System.Web.Cors.CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true,
AllowAnyOrigin = true,
SupportsCredentials = true
};
//corsPolicy.GetType()
// .GetProperty(nameof(corsPolicy.ExposedHeaders))
// .SetValue(corsPolicy, tusdotnet.Helpers.CorsHelper.GetExposedHeaders());
owinAppBuilder.UseCors(new Microsoft.Owin.Cors.CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(corsPolicy)
}
});
PublicClientId = "self";
OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new Microsoft.Owin.PathString("/Login"),
Provider = new MyServiceProvider(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
AllowInsecureHttp = true,
RefreshTokenProvider = new MyRefreshTokenProvider(),
};
owinAppBuilder.UseOAuthBearerTokens(OAuthOptions);
//owinAppBuilder.UseTus(context => new DefaultTusConfiguration
//{
// // Excluded for brevity, use the same configuration as you would normally do
//});
return owinAppBuilder.Build<Func<IDictionary<string, object>, Task>>();
}));
Microsoft.Owin and related packages do not have targets for .NET Core, no for .NET Standard. All they have is dlls targeting full .NET. You can reference such libraries from your project targeting .NET Core, but they are not guaranteed to work, as you see yourself, because API (set of classes\methods\signatures) of full .NET and .NET Core are different. Visual Studio even will show a warning when you are doing that, for example:
Package 'Microsoft.Owin 3.1.0' was restored using
'.NETFramework,Version=v4.6.1' instead of the project target framework
'.NETCoreApp,Version=v2.0'. This package may not be fully compatible
with your project.
There is Microsoft.AspNetCore.Owin package and you can use OWIN middleware in .NET Core app as your first link describes, but almost all it provides is UseOwin extension method. There is no AppBuilder type there and so on, and there are no Microsoft.AspNetCore.Owin.Cors packages or similar. So you have to either implement all that yourself (no reason to, because you can use the same functionality provided by asp.net core framework) or wait for OWIN packages that target .NET Standard\Core and do that (didn't check, maybe they even exist already).
So, your code uses packages which are indeed not compatible with your target framework, as exception you have at runtime shows. So another answer (for some reason downvoted) is technically correct.
If you still want to use those packages reliably - you need to target full .NET Framework and not .NET Core. To do that, open your .csproj file and change
<TargetFramework>netcoreapp2.0</TargetFramework>
To some .NET framework version that supports .NET Standard 2.0, for example:
<TargetFramework>net47</TargetFramework>
Then go to nuget package manager and, if you have microsoft.aspnetcore.all package (or other packages targeting .NET Core) - uninstall it, you don't need it anyway. Then install Microsoft.AspNetCore package and all other asp.net core packages you need (if not installed already). Rebuild, run and it will work just fine.
That works because all (most?) AspNetCore packages target .NET Standard, not .NET Core, and you can use them in projects targeting full .NET Framework.
Note that by doing that you have asp.net Core project, but not on .NET Core, with all consequences that come from that (cannot run with dotnet run, on linux need to run with mono, and so on).
The Microsoft.Owin components will not work on dotnet core 2.0, they only work on .NET 4.5+
Using nuget in Visual Studio 2013, I installed Ghostscript.NET into my project on my Windows x64 PC.
Just to make sure I wasn't crazy, I checked it:
PM> Install-Package Ghostscript.NET
'Ghostscript.NET 1.2.0' already installed.
Project already has a reference to 'Ghostscript.NET 1.2.0'.
PM>
The project is used by multiple developers. It targets Any CPU, and needs to remain that way.
Here is my code:
public static void GhostscriptNetProcess(String fileName, String outputPath)
{
var version = GhostscriptVersionInfo.GetLastInstalledVersion();
var source = (fileName.IndexOf(' ') == -1) ? fileName : String.Format("\"{0}\"", fileName);
var output_file = (outputPath.IndexOf(' ') == -1) ? outputPath : String.Format("\"{0}\"", outputPath);
var gsArgs = new List<String>();
gsArgs.Add("-q");
gsArgs.Add("-dNOPAUSE");
gsArgs.Add("-dNOPROMPT");
gsArgs.Add("-sDEVICE=pdfwrite");
gsArgs.Add(String.Format(#"-sOutputFile={0}", output_file));
gsArgs.Add("-f");
gsArgs.Add(source);
var processor = new GhostscriptProcessor(version, false);
processor.Process(gsArgs.ToArray());
}
Whenever I attempt to debug the application, I get the following error message:
GhostscriptLibraryNotInstalledException was unhandled
An unhandled exception of type 'Ghostscript.NET.GhostscriptLibraryNotInstalledException' occurred in Ghostscript.NET.dll
Additional information: This managed library is running under 32-bit process and requires 32-bit Ghostscript native library installation on this machine! To download proper Ghostscript native library please visit: http://www.ghostscript.com/download/gsdnld.html
Looking up the Ghostscript.NET.GhostscriptLibraryNotInstalledException did not provide any useful information, though this post on CodeProject indicated that the debugger is running in 32-bit mode whereas I have the 64-bit version installed.
That's all well and good know, but how do I go about testing the new code I wrote that uses Ghostscript?
If you are testing with MS Test you have to set the processor architecture in which the tests are run, because Ghostscript.Net verifies the process architecture (Environment.Is64BitProcess) to search for the ghostscript installation in the registry.
In Menu > Test > Test Settings > Default Processor Architecture > X64.
Have you actually installed Ghostscript ?
Ghostscript.NET is merely a .NET interface to Ghostscript, it looks to me like the message:
"This managed library is running under 32-bit process and requires 32-bit Ghostscript native library installation on this machine! To download proper Ghostscript native library please visit: http://www.ghostscript.com/download/gsdnld.html"
is trying to tell you that you don;t have a 32-bit version of Ghostscript installed. It even tells you where to go to download a copy.
So have you installed Ghostscript ? Have you installed the 32-bit version of Ghostscript ?