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
Related
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 :)
I was trying to learn how to use powershell within C#
I was following this tutorial
However when I run it I get this error:
Unhandled exception. System.InvalidProgramException: Common Language Runtime detected an invalid program.
at System.Management.Automation.PowerShell.Create()
at desktopAdmin365.Program.Main(String[] args) in C:\Users\ncox\source\repos\desktopAdmin365\Program.cs:line 11
C:\Users\ncox\source\repos\desktopAdmin365\bin\Debug\netcoreapp3.0\desktopAdmin365.exe (process 17464) exited with code -532462766.
I am sure I'm missing something when including references/dependencies from the solutions explorer but I am not having any luck with google finding out which one
Here is the code
using System;
using System.Management.Automation;
using System.Collections.ObjectModel;
namespace desktopAdmin365
{
class Program
{
static void Main(string[] args)
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("param($param1) $d = get-date; $s = 'test string value'; " +
"$d; $s; $param1; get-service");
}
}
}
}
If you look at your dependencies in the project, you'll likely see a warning about the package being restored using .NETFramework and possibly not being compatible.
Your project is .NET core, so you might need to install Powershell Core instead.
https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-windows?view=powershell-6
Alternatively, switch to a .net framework solution and it will work.
I've recently got a Raspberry Pi (3B+ and 4) and have been trying to get a .Net Core application working using the System.Device.Gpio package, having followed along with a post on Scott Hanselman's blog. I'm publishing from my dev machine and scp'ing the files over to the pi.
If I do a SCD (Self Contained Deployment) by using dotnet publish -r linux-arm and copy the many many files over to the Pi, I can run the application and the LED blinks as expected.
However, I'm trying to do a dotnet publish to create a FDD (Framework Depdendent Deployment), but copying those files over and doing dotnet ./BlinkLed.dll causes a System.PlatformNotSupportedException to be thrown by new GpioController(PinNumberingScheme.Board).
My understanding was that the only difference between a FDD and a SCD is that the former requires an installed .Net Core runtime, I can't see anything mentioned about some apps only working in a SCD in the documentation. I've installed this on the Pi, and can dotnet ./<SomeDll> for a simple hello world application that prints to the console, it just doesn't seem to work if I try to use the System.Device.Gpio package. As I'm trying to set up a decent remote debugging experience it would be ideal if I can do a FDD as it generates far fewer files, meaning that there's less to copy to the Pi each publish/debug cycle.
The Program.cs looks like this:
using System;
using System.Device.Gpio;
using System.Threading;
namespace LedBlink
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello LedBlink!");
using(var gpioController = new GpioController(PinNumberingScheme.Board)) // <-- This is where the exception is thrown
{
var pin = 11;
gpioController.OpenPin(pin, PinMode.Output);
try
{
for (var i = 0; i < 3; i++)
{
gpioController.Write(pin, PinValue.High);
Thread.Sleep(500);
gpioController.Write(pin, PinValue.Low);
Thread.Sleep(500);
}
}
finally
{
gpioController.ClosePin(pin);
}
}
}
}
}
So to summarise, my app works if I do a Self Contained Deployment, but not if I do a Framework Dependent Deployment, and I'd like to do a Framework Dependent Deployment.
Hopefully someone has a little time to explain how to use V8.Net with Mono.
I'm trying to use V8.Net with mono 3.10 on my ubuntu machine. So far I did the following:
create an example project with the content on codeplex
using System;
using V8.Net;
namespace testv8
{
class MainClass
{
public static void Main (string[] args)
{
var v8Engine = new V8Engine();
Handle result = v8Engine.Execute("/* Some JavaScript Code Here*/","My V8.NET Console");
Console.WriteLine(result.AsString); // (or "(string)result")
Console.WriteLine("Press any key to continue ...");
Console.ReadKey();
Console.WriteLine ("Hello World!");
}
}
}
add V8.Net.dll and V8.NetSharedTypes to the references
I copied the content of the folder /Release/NET 4.0/x64 to /bin/Debug/x64 of my build directory
When I try to run the example, I get the following error: A system.DllNotFoundException was thrown.
I changed the Build type from Debug to ( Debug | Any cpu ). If I understood correct the library should now choose the correct dll.
6 When I rerun the program in this mode.
The program stops at:
Loaded assembly: /Build/v8dotnet/testv8/testv8/bin/test/x64/V8.Net.Proxy.Interface.x64.dll [External]
The call stack shows:
V8.Net.V8NetProxy.CreatehandleProxyTest().
Hopefully you can give me some input to get it running.
Short note: there is some progress on making V8.Net available with Mono for different platforms (Win, Linux, and Mac).
More info is available on the following sites:
Mono Github Branch
V8.Net Mono Issues
Update: Mono is no longer supported. .Net Standard is now supported instead, which is cross-platform also.
NuGet: https://www.nuget.org/packages/V8.Net/
CodePlex is now closed down. The new source is here: https://github.com/rjamesnw/v8dotnet
I am trying to build a project in Raspberry Pi which communicates with my Azure server via Signalr. I have used SignalR in .NET client side in a mono project while working on a Xamarin project and was successful.
For the test purpose, I have written a small block of code.
using System;
using Microsoft.AspNet.SignalR.Client;
namespace testSignalr1
{
class Program
{
static void Main()
{
var hubConnection = new HubConnection("******");
var serverHub = hubConnection.CreateHubProxy("HubTest");
serverHub.On("broadcastMessage", message => System.Console.WriteLine(message));
hubConnection.Start().Wait();
serverHub.Invoke("TestMethod").Wait();
System.Console.Read();
}
}
}
I am compiling this using mcs mono compiler.
sudo mcs test.cs /r: /usr/lib/mono/4.5/Microsoft.AspNet.SignalR.Client.dll
The program actually compiles successfully. But when it is run, I get the following exception
Could not load type 'Microsoft.AspNet.SignalR.Client.HubConnection' from assembly 'Microsoft.AspNet.SignalR.Client'
The Microsoft.AspNet.SignalR.Client.dll I am using is the one in lib folder in this Git Project which demonstrates SingalR in RaspBerry Pi
This seems to be the mono compiled version of SignalR. I cannot figure out where I am going wrong. Thank You in Advance
ssh into the raspberry pi and type sudo apt-get install mono-complete this worked for me. I had the same issue when only installed the mono-runtime.