Debug IronPython in hosted/embedded C# - c#

I'm developing asp.net core application + IronPython.
But I've faced with the debugging issue...
So for example I have following code:
Dictionary<string, object> options = new Dictionary<string, object>();
options["Debug"] = true;
ScriptEngine engine = Python.CreateEngine(options);
// output redirect
var eIO = engine.Runtime.IO;
var errors = new MemoryStream();
eIO.SetErrorOutput(errors, Encoding.Default);
var result = new MemoryStream();
eIO.SetOutput(result, Encoding.Default);
// execute script
ScriptScope scope = engine.CreateScope();
scope.SetVariable("testGlobalVar", 10);
engine.ExecuteFile(ScriptPath, scope);
in python file
some = "Test"
print(Test)
print("We have ->", testGlobalVar)
It works fine, but I don't know how to set breakpoint in python file and debug it step by step in Visual Studio, Pycharm(whatever), when running it via C#.
I found this question but it's almost completely useless. I'm setting breakpoint in python file and nothing happens.

Since it works well without debug mode as you mentioned. I think the reason for why the breakpoint won't be hit in debug mode is debugger can't find it.
Please Go=>Debug=>Options=>Uncheck Enable Just My Code to check if it helps.
Note:
Set the .net core app as startup project
If the uncheck Enable Just My Code not help, I suggest you go tools->Import/Export Settings->reset all settings, then uncheck the Enable Just My Code again.
After that, the breakpoint can be hit like below:
In addition: I use the .net console app to reproduce and test, but I think it has similar behavior like web-app. Any update feel free to contact me :)

Related

C# SSIS pkg.Execute(null,null,dtsEvents,null,null) returns "Failed" with no events

I'm just dummy in using SSIS&*.dtsx files from C#. Now I have WindowsForms project and OnClick handler with this code:
.....
string pkgLocation;
Package pkg;
Microsoft.SqlServer.Dts.Runtime.Application app;
DTSExecResult pkgResults;
DTSEvents dtsEvents=new DTSEvents();
pkgLocation = System.Windows.Forms.Application.StartupPath+ #"\" + #"3StreamsImport.dtsx";
app = new Microsoft.SqlServer.Dts.Runtime.Application();
app.PackagePassword = "abudfv";
app.EnableDump = true;
app.DumpOnAnyError = true;
pkg = app.LoadPackage(pkgLocation, dtsEvents,true);
try {
pkgResults = pkg.Execute(null,null,dtsEvents,null,null);
}catch(System.Runtime.InteropServices.COMException ex) {
Console.WriteLine(ex.StackTrace);
}
.......
"3Streamsimport.dtsx" file was created with SqlServer management studio for SqlServer 2016 and is working fine from standard Еxecute Package Utility. Loading package in my code passes fine too. But executing fails allways! dtsEvents is instanceof object that implements all from IDTSEvents interface.
Dear ALL, who can help with definitions of ways to solve the problem?
It's been a while since I tried, so I don't know if later versions have improved anything, but I was never able to get an SSIS package to execute from C# the way you are trying to do.
What I eventually did was create a job that executed the package, and used C# to start the job. It worked fine.
Solved! All C# code is fine. As addition I'm implemented IDTSLogging. After changing "exectute" call to
pkgResults = pkg.Execute(null,null,dtsEvents,new DTSLogging(),null);
all events are firing smoothly. I don'nt know/ why, but it is working.
Now about DTSX- file: It was my mistake in project and the proper copy was simply in other place! :-(
Sorry :-(

VBScript GetObject() not working if called from C# WPF application

I have the following VBScript code in MyScript.vbs:
Dim myApp
Set myApp = GetObject(,"ViewDraw.Application")
I call it from a PowerShell command line, like so:
cscript MyScript.vbs //I
This works as expected; myApp is set to the process I'm looking for and I'm able to interact with it.
Here's some C# code that attempts to do the same thing:
var script = new Process();
script.StartInfo.FileName = "cscript";
script.StartInfo.Arguments = #"<MyWorkingFolder>\MyScript.vbs //I";
script.StartInfo.CreateNoWindow = true;
script.StartInfo.RedirectStandardOutput = true;
script.StartInfo.UseShellExecute = false;
script.Start();
//Read anything sent out by program
string output = script.StandardOutput.ReadToEnd();
script.WaitForExit();
VBScriptResult result = new VBScriptResult();
result.returnCode = script.ExitCode;
result.stdOut = output;
return result;
When I execute the C# code, the VBScript fails on the GetObject() call. There have been similar SO questions, and I've tried their suggestions. One suggestion was to explicitly call either the 32bit or 64bit version of cscript. Neither worked, however.
This hasn't always been an issue. The code is a couple of years old now and has worked in the past. It's possible that an update to Visual Studio 2017 somehow caused this problem. I'm currently running version 15.3.5.
I've been stuck on this issue for a week now, so any help is greatly appreciated!
The problem is with Visual Studio 2017, probably a result of taking update 15.3 or later. The same code works fine in VS 2015 Update 3.

C# code completion with NRefactory 5

I just found out about NRefactory 5 and I would guess, that it is the most suitable solution for my current problem. At the moment I'm developing a little C# scripting application for which I would like to provide code completion. Until recently I've done this using the "Roslyn" project from Microsoft. But as the latest update of this project requires .Net Framework 4.5 I can't use this any more as I would like the app to run under Win XP as well. So I have to switch to another technology here.
My problem is not the compilation stuff. This can be done, with some more effort, by .Net CodeDomProvider as well. The problem ist the code completion stuff. As far as I know, NRefactory 5 provides everything that is required to provide code completion (parser, type system etc.) but I just can't figure out how to use it. I took a look at SharpDevelop source code but they don't use NRefactory 5 for code completion there, they only use it as decompiler. As I couldn't find an example on how to use it for code completion in the net as well I thought that I might find some help here.
The situation is as follows. I have one single file containing the script code. Actually it is not even a file but a string which I get from the editor control (by the way: I'm using AvalonEdit for this. Great editor!) and some assemblies that needs to get referenced. So, no solution files, no project files etc. just one string of source code and the assemblies.
I've taken a look at the Demo that comes with NRefactory 5 and the article on code project and got up with something like this:
var unresolvedTypeSystem = syntaxTree.ToTypeSystem();
IProjectContent pc = new CSharpProjectContent();
// Add parsed files to the type system
pc = pc.AddOrUpdateFiles(unresolvedTypeSystem);
// Add referenced assemblies:
pc = pc.AddAssemblyReferences(new CecilLoader().LoadAssemblyFile(
System.Reflection.Assembly.GetAssembly(typeof(Object)).Location));
My problem is that I have no clue on how to go on. I'm not even sure if it is the right approach to accomplish my goal. How to use the CSharpCompletionEngine? What else is required? etc. You see there are many things that are very unclear at the moment and I hope you can bring some light into this.
Thank you all very much in advance!
I've just compiled and example project that does C# code completion with AvalonEdit and NRefactory.
It can be found on Github here.
Take a look at method ICSharpCode.NRefactory.CSharp.CodeCompletion.CreateEngine. You need to create an instance of CSharpCompletionEngine and pass in the correct document and the resolvers. I managed to get it working for CTRL+Space compltition scenario. However I am having troubles with references to types that are in other namespaces. It looks like CSharpTypeResolveContext does not take into account the using namespace statements - If I resolve the references with CSharpAstResolver, they are resolved OK, but I am unable to correctly use this resolver in code completition scenario...
UPDATE #1:
I've just managed to get the working by obtaining resolver from unresolved fail.
Here is the snippet:
var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
var resolver3 = unresolvedFile.GetResolver(cmp, loc); // get the resolver from unresolvedFile
var engine = new CSharpCompletionEngine(doc, mb, new CodeCompletionBugTests.TestFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext );
Update #2:
Here is the complete method. It references classes from unit test projects, sou you would need to reference/copy them into your project:
public static IEnumerable<ICompletionData> DoCodeComplete(string editorText, int offset) // not the best way to put in the whole string every time
{
var doc = new ReadOnlyDocument(editorText);
var location = doc.GetLocation(offset);
string parsedText = editorText; // TODO: Why there are different values in test cases?
var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs");
syntaxTree.Freeze();
var unresolvedFile = syntaxTree.ToTypeSystem();
var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
IProjectContent pctx = new CSharpProjectContent();
var refs = new List<IUnresolvedAssembly> { mscorlib.Value, systemCore.Value, systemAssembly.Value};
pctx = pctx.AddAssemblyReferences(refs);
pctx = pctx.AddOrUpdateFiles(unresolvedFile);
var cmp = pctx.CreateCompilation();
var resolver3 = unresolvedFile.GetResolver(cmp, location);
var engine = new CSharpCompletionEngine(doc, mb, new CodeCompletionBugTests.TestFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext );
engine.EolMarker = Environment.NewLine;
engine.FormattingPolicy = FormattingOptionsFactory.CreateMono();
var data = engine.GetCompletionData(offset, controlSpace: false);
return data;
}
}
Hope it helps,
Matra
NRefactory 5 is being used in SharpDevelop 5. The source code for SharpDevelop 5 is currently available in the newNR branch on github. I would take a look at the CSharpCompletionBinding class which has code to display a completion list window using information from NRefactory's CSharpCompletionEngine.

NUnit is not failing test with dynamic keyword of .Net 4.0

I am using NUnit with Visual Studio Express Edition 2010 for C#, Now, normally test works fine. But whenever I try to use Massive.cs, which is open source api to access database. Test fails from that file only. Now, if I run the application, api is working fine. I have created a different library file to access data base.
I seriously don't understand the error. It is just giving error that object reference is not set to an object. But if I run the code, it works fine. I am using dynamic keyword as shown in link of api above. Does that making problem with NUnit ?
Is there any other way to test in this type of Scenarios?
Here are the further details of the code,
Test class is like this
dynamic item = new Item();
item.Insert(new { Name = "Maggi", Description = "Its 2 Min Nuddles", IsDelete = false });
var items = item.All();
Assert.AreEqual("Maggi", items.FirstOrDefault().Name);
Now, I have put test here. Which gives error like shown in image,
Now if I run code in console application, then code is working fine, code snippet is given below
dynamic item = new Item();
item.Insert(new { Name = "Maggi", Description = "Its 2 Min Nuddles", IsDelete = false });
var result = item.All();
foreach (var i in result)
{
Console.WriteLine(i.Name + i.Description);
}
Console.Read();
Here, code is working and same thing is not working with NUnit Test. Please have a look and help me out. Please let me know if any further information is needed from my side.
Most probable explanation is that you haven't set up your connection string in the test project.
If you are using NUnit, just put it in app.config of your test project.
Solved... There is a issue with NUnit Testing. It was not taking config file pefectly. So, I made two changes. Changes I have done in Project setting.
First change is to change Application Base to bin\debug just give application base as this and then config file to .config to .exe.config and things are up and running. :)

IronPython and Nodebox in C#

My plan:
I'm trying to setup my C# project to communicate with Nodebox to call a certain function which populates a graph and draws it in a new window.
Current situation: [fixed... see Update2]
I have already included all python-modules needed, but im still getting a
Library 'GL' not found
it seems that the pyglet module needs a reference to GL/gl.h, but can't find it due to IronPython behaviour.
Requirement:
The project needs to stay as small as possible without installing new packages. Thats why i have copied all my modules into the project-folder and would like to keep it that or a similar way.
My question:
Is there a certain workaround for my problem or a fix for the library-folder missmatch.
Have read some articles about Tao-Opengl and OpenTK but can't find a good solution.
Update1:
Updated my sourcecode with a small pyglet window-rendering example. Problem is in pyglet and referenced c-Objects. How do i include them in my c# project to be called? No idea so far... experimenting alittle now. Keeping you updated.
SampleCode C#:
ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null);
ScriptRuntime runtime = new ScriptRuntime(setup);
ScriptEngine engine = Python.GetEngine(runtime);
ScriptSource source = engine.CreateScriptSourceFromFile("test.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);
SampleCode Python (test.py):
from nodebox.graphics import *
from nodebox.graphics.physics import Vector, Boid, Flock, Obstacle
flock = Flock(50, x=-50, y=-50, width=700, height=400)
flock.sight(80)
def draw(canvas):
canvas.clear()
flock.update(separation=0.4, cohesion=0.6, alignment=0.1, teleport=True)
for boid in flock:
push()
translate(boid.x, boid.y)
scale(0.5 + boid.depth)
rotate(boid.heading)
arrow(0, 0, 15)
pop()
canvas.size = 600, 300
def main(canvas):
canvas.run(draw)
Update2:
Line 139 [pyglet/lib.py] sys.platform is not win32... there was the error. Fixed it by just using the line:
from pyglet.gl.lib_wgl import link_GL, link_GLU, link_WGL
Now the following Error:
'module' object has no attribute '_getframe'
Kind of a pain to fix it. Updating with results...
Update3:
Fixed by adding following line right after first line in C#-Code:
setup.Options["Frames"] = true;
Current Problem:
No module named unicodedata, but in Python26/DLLs is only a *.pyd file`. So.. how do i implement it now?!
Update4:
Fixed by surfing: link text and adding unicodedata.py and '.pyd to C# Projectfolder.
Current Problem:
'libGL.so not found'... guys.. im almost giving up on nodebox for C#.. to be continued
Update5:
i gave up :/ workaround: c# communicating with nodebox over xml and filesystemwatchers. Not optimal, but case solved.
-X:Frames enables the frames option as runtime (it slows code down a little to have access to the Python frames all the time).
To enable frames when hosting you just need to do:
ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(new Dictionary<string, object>() {
{ "Frames", true }
});
Instead of the null that you're passing now. That's just creating a new dictionary for the options dictionary w/ the contents "Frames" set to true. You can set other options in there as well and in general the -X:Name option is the same here as it is for the command line.

Categories

Resources