Python.Net PythonEngine.Initialize() crashes application without throwing exception - python.net

My application (C#, VS2017) previously targeted Python 3.5.1. I have updated the system to Python 3.7.1 and have this is causing PythonEngine.Initialize() to crash the application without throwing an exception.
One internet suggestion was to set the Python env in VS, however this causes VS2017 to close when opening Python/environments. I switched to VS2019 and encountered the same issue with the stripped down code here:
using System.Windows.Forms;
using Python.Runtime;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
try
{
PythonEngine.Initialize();
}
catch (Exception e)
{
string ex = e.ToString();
}
}
}
}
Python.Net was installed successfully using:
pip install pythonnet

UPDATE Dec 2022
There are 2 optional environment strings you can use to locate the python dll.
PYTHONNET_PYDLL explicitly set the dll name
PYTHONNET_PYVER explicitly set just the version string part of the dll name
Compiling with WINDOWS, OSX or LINUX defined is not required anymore
Here's my PythonNet init function.
Note that running "pip install pythonnet" only installs the ability to load & use CLR types & assemblies from Python. To embed PythonNet in a C# app, you actually don't need to install pythonnet on the Python side.
This function uses some globals set at startup.
Program.PythonHome -- points to the Python root folder I'm using
Program.ScriptsDir -- my own app python scripts dir
Program.ApplicationName -- just my own app name
I also call PythonEngine.BeginAllowThreads(); as I'm calling from multiple threads.
public static void InitPython(Microsoft.Extensions.Logging.ILogger logger)
{
string py_home = Program.PythonHome;
string py_path = $"{py_home};";
// will be different on linux/mac
string[] py_paths = {"DLLs", "lib", "lib/site-packages", "lib/site-packages/win32"
, "lib/site-packages/win32/lib", "lib/site-packages/Pythonwin" };
foreach (string p in py_paths)
{
py_path += $"{py_home}/{p};";
}
try
{
PythonEngine.PythonPath = $"{Program.ScriptsDir};{py_path}";
PythonEngine.PythonHome = Program.PythonHome;
PythonEngine.ProgramName = Program.ApplicationName;
PythonEngine.Initialize();
PythonEngine.BeginAllowThreads();
logger.LogInformation("Python Version: {v}, {dll}", PythonEngine.Version.Trim(), Runtime.PythonDLL);
logger.LogInformation("Python Home: {home}", PythonEngine.PythonHome);
logger.LogInformation("Python Path: {path}", PythonEngine.PythonPath);
}
catch (System.TypeInitializationException e)
{
throw new Exception($"FATAL, Unable to load Python, dll={Runtime.PythonDLL}", e);
}
catch (Exception e)
{
throw new Exception($"Python initialization Exception, {e.Message}", e);
}
}

Related

VS2022 - Hot reload applying changes successfully but not reflecting in app for a simple console app

I have a simple .net 6.0 console with the following code running on visual studio 2022. I change the Console.WriteLine text while the app is running and I get a log message from hot reload saying "Changes were successfully applied.". But nothing happens on my app. What am I doing wrong? I tried with and without debugger as per suggestions on other stack overflow threads. But no luck it still does not work. Here's my code.
using System;
namespace TestVS2022
{
public static class Program
{
public static void Main(string[] args)
{
while (true)
{
System.Console.WriteLine($"Hello World.");
Thread.Sleep(1000);
}
}
}
}

"mono app.exe" gives error "File does not contain a valid CIL image."

I've made the following as a simple test.
using System;
namespace test
{
class App
{
static void Main(string[] args)
{
Console.WriteLine("test");
Console.ReadLine();
}
}
}
Then compiled and moved the entire bin folder to my pi and tried to run it using "mono app.exe" but I get the error in the title. How do I run compiled .Net core executables using mono on raspberry pi?
Realized that mono is .NET framework.
I installed .NET core runtime and it worked.
I followed this guide

Velocity Unable To find Resources

This question is already asked but i am trying the same thing that is in accepted answer
protected static final String RESOURCE_LOADER = classpath.resource.loader.class";
static {
System.out.println("Velocity Initialization Started");
velocityEngine = new VelocityEngine();
velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityEngine.setProperty(RESOURCE_LOADER,ClasspathResourceLoader.class.getName());
try {
velocityEngine.init();
} catch (Exception e) {
LOG.error("Failed to load velocity templates e={}", e);
}
}
my velocity file is in
src/main/resources/velocity/templates/command/name.vm
i am getting templates by following command
template = velocityEngine.getTemplate("velocity/templates/command/GenericState.vm");
It works locally but when bundled in jar it does not work , I have examined the jar it consist of velocity folder
i am using velocity to generated java code
I am having maven project setup and maven is creating jar
try this way it should work.
velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "class,file");
velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute");
velocityEngine.setProperty("runtime.log.logsystem.log4j.logger", "VELLOGGER");
velocityEngine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
velocityEngine.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
velocityEngine.init();

Cannot access RavenDB Management Studio

Try:
I created a new project in VS2012
I installed via the NuGet package RavenDB Embedded -Pre
I installed Ninject.MVC3
Added a module for ninject RavenDB:
Public class RavenDBNinjectModule : NinjectModule
{
public override void Load()
{
Bind<IDocumentStore>().ToMethod(context =>
{
NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8080);
var documentStore = new EmbeddableDocumentStore { Url="http://localhost:8080/", DataDirectory="~/App_Data", UseEmbeddedHttpServer = true };
return documentStore.Initialize();
}).InSingletonScope();
Bind<IDocumentSession>().ToMethod(context => context.Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope();
}
}
In my class "NinjectWebCommon" ...
private static void RegisterServices(IKernel kernel)
{
kernel.Load(new RavenDBNinjectModule());
}
When running the application, the following url was generated ("http://localhost:1423")
Verify that the file "Raven.Studio.xap" was the root of my application
I tried accessing "http://localhost:8080" but the following screen is displayed:
What am I doing wrong?
As it turned out, the issue is that documentStore.Initialize never get called, because that no one did ask Ninject to resolve IDocumentStore.
You are setting the Url property, which means that you aren't running in embedded mode, but in server mode.
Remove the Url property, and everything will work for you.
I found the problem!
Since he had used IDocumentSession in no time, the ninject had not created the instance of IDocumentStore and thus not run the Initialize method

Could not load middleware layer 'com.sap.mw.jco.rfc.MiddlewareRFC'

I'm using Sap Jco to connect to SAP database with the front end being Java(JSF), When I connect to SAP with:
try {
mConnection =JCO.createClient("400", // SAP client
"c3026902", // userid
"********", // password
"EN", // language
"iwdf5020", // host name
"00"); // system number
mConnection.connect();
}
catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
Problem I'm facing is when run the application for the first time, data is displayed but when I re-run it says "Could not load middleware layer 'com.sap.mw.jco.rfc.MiddlewareRFC' "
Can any one help me in resolving the issue?????
This sounds like the API cannot load the native driver files.
The SAP Java Connector consists of a native runtime part, that does the actuall communication and a Java API that wraps this functionality with a java api.
The Java API is inside the sapjco.jar and the native drivers are e.g on windows inside librfc32.dll and sapjcorfc.dll.
Place these dll's into your system path (e.g. windows: C:\WiNDOWS\system32) and it should run.
Cheers
Sebastian
Are your DLLs located in the Windows system32 folder? If so, are you probably using the wrong architecture? (x64 DLL on 32 bit or vice versa)
Also, are the DLLs the same version as the java api? If you have SAP GUI installed there could be older DLLs around.
Defining SAP connection:
For the Version 3,0 of the sapjco library there exists plenty of useful information. To create a connection following the instructions in:
http://www.browseye.com/linkShare.html?url=http://help.sap.com/saphelp_nwpi711/helpdata/en/46/fb807cc7b46c30e10000000a1553f7/content.htm?bwsCriterion=%22Setting%20Up%20Connection%22&bwsMatch=1&bwsCriterion=%22Setting%20Up%20Connection%22&bwsMatch=1
There are a few thing that you should take into account:
Place the dll file in the same place that the jar.
The dll must be the right version for your operating system and architecture otherwise you will get a native library error.
Example of code to create a connection to the server.
public class StepByStepClient
{
static String DESTINATION_NAME1 = "ABAP_AS_WITHOUT_POOL";
static String DESTINATION_NAME2 = "ABAP_AS_WITH_POOL";
static
{
Properties connectProperties = new Properties();
connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, "ls4065");
connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, "85");
connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, "800");
connectProperties.setProperty(DestinationDataProvider.JCO_USER, "homofarber");
connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, "laska");
connectProperties.setProperty(DestinationDataProvider.JCO_LANG, "en");
createDestinationDataFile(DESTINATION_NAME1, connectProperties);
connectProperties.setProperty(DestinationDataProvider.JCO_POOL_CAPACITY, "3");
connectProperties.setProperty(DestinationDataProvider.JCO_PEAK_LIMIT, "10");
createDestinationDataFile(DESTINATION_NAME2, connectProperties);
}
static void createDestinationDataFile(String destinationName, Properties connectProperties)
{
File destCfg = new File(destinationName+".jcoDestination");
try
{
FileOutputStream fos = new FileOutputStream(destCfg, false);
connectProperties.store(fos, "for tests only !");
fos.close();
}
catch (Exception e)
{
throw new RuntimeException("Unable to create the destination files", e);
}
}
public static void step1Connect() throws JCoException
{
JCoDestination destination = JCoDestinationManager.getDestination(DESTINATION_NAME1);
System.out.println("Attributes:");
System.out.println(destination.getAttributes());
System.out.println();
}
}
In SAPJco 3.0 connections are build from the info contained in a “Destination”.
The documentation example use a properties file to save the “Destination”. However it is a non-secure way to keep connection info. As is indicated on the documentation in the hightlighted paragraph you can see on next link.
http://help.sap.com/saphelp_nwpi711/helpdata/en/48/5fb9f9b523501ee10000000a421937/content.htm?bwsCriterion=%22In%20practice%20you%20should%20avoid%20this%20for%20security%20reasons.%22&bwsMatch=1
You can keep connection info on a database or any other storage system if you create a custom “DestinationDataProvider” In the Examples provided with the SAPJco library there is an example of how to create a custom DestinationDataProvider.