Writing some test scripts in IronPython, I want to verify whether a window is displayed or not. I have the pid of the main app's process, and want to get a list of window titles that are related to the pid.
I was trying to avoid using win32api calls, such as FindWindowEx, since (to my knowledge) you cannot access win32api directly from IronPython. Is there a way to do this using built-in .net classes? Most of the stuff I have come across recommends using win32api, such as below.
.NET (C#): Getting child windows when you only have a process handle or PID?
UPDATE: I found a work-around to what I was trying to do. Answer below.
As of IronPython 2.6 the ctypes module is supported. This module provides C compatible data types, and allows calling functions in DLLs. Quick example:
import ctypes
buffer = ctypes.create_string_buffer(100)
ctypes.windll.kernel32.GetWindowsDirectoryA(buffer, len(buffer))
print buffer.value
The article below shows how to access the win32api indirectly from IronPython. It uses CSharpCodeProvider CompileAssemblyFromSource method to compile an assembly in memory from the supplied C# source code string. IronPython can then import the assembly.
Dynamically compiling C# from IronPython
It's like asking if you can swim without going in to the water. If you need information from windows, the only option is to use the win32api. There are lots of examples to find on how to do so.
If you don't like this answer, just leave a comment in your question and I will remove this answer, so your question will remain in the unanswered questions list.
Related
Before I put my question, I want to say that I have already searched on stackoverflow and several other websites about the problem, but the answers I found were not very satisfying in detail.
My problem is, I need to get a JSON data from an attribute in a HTML tag. I thought that it would be easier to achieve this using Python, and it was quite easy in fact. The code works like a charm. The problem is, I need to use this function in a C# class, so I need to use IronPython. When I import to code to my C# project and use IronPython to run call it, I get an error telling me 'No module named lxml'. According to other questions and posts on the internet on this topic, it is because lxml is not compatible with IronPython.
So I was wondering if it is possible to somehow make it compatible using some other libraries, or by using a replacement for IronPython. I would also very appreciate if you could direct me to any information about libraries I can use instead of lxml.
Here is the piece of code I use the lxml library:
tree = html.fromstring(page.content)
# Get the data-items value from the html
dt = tree.xpath('//*[#id="list-container"]/div[3]/div//table/#data-items')
Also I wonder if xml.etree.ElementTree is compatible with IronPython, and if it is, is there any way I can use both the xpath method and ElementTree instead of lxml and its functions
I have a script in MATLAB that writes a CSV, the CSV is read by a c# script which writes a few more CSVs that I go back and read in MATLAB.
Is there any way to automate this so I don't have to call the c# code by hand each time?
It's very easy to call into .net from Matlab. The official documentation is at http://www.mathworks.co.uk/help/matlab/matlab_external/load-a-global-net-assembly.html You should be aware that Matlab is case-sensitive (even when it comes to specifying the assembly path) and that it is also limited in the kinds of objects it can pass back and forth across the boundary.
If you pass an array into your C# dll from Matlab, it will appear to be an array of bare objects rather than an array of numbers. In Matlab, you may need to use the char and cell methods to convert strings and arrays back into the form you are expecting.
To answer the title question, e.g. "Is it possible to call C# functions from MATLAB": yes, it is. Mathworks provides decent documentation on calling .NET assemblies from MATLAB on their website. Of course, there are limitations and some awkward quirks to take into account but basically you can create instances of .NET classes and interact with .NET applications from MATLAB.
To advise on automating this process, you could perhaps dive into the MATLAB COM Automation Service?
In the extension of this: it's also possible to call MATLAB functions in a .NET application. The other way around, sort of speak. This will be no problem with basic data types, but when it gets a bit more advances it can put you through some gnarly COM challenges, though.
Being able to create javascript code on the fly is pretty cool.
That is by using
HtmlPage.Window.Eval("alert('Hello World')");
But is there a way to do the same thing, with a C# method? Lets say something like
void MethodEval("MessageBox.Show('Hello World')");
Is it even possible, without having to recompile your code?
It's possible using tricks posted by others. However, it's usually a very bad idea.
.Net code typically runs in a more trusted context than a javascript browser sandbox, and has access to a much richer, and therefore potentially damaging, api.
Instead you use the System.Addin namespace to provide a very strict interface for extensions, plugins, and the like. If you're just trying to use a more "fluid" or functional programming environment you can use fun features like lamdba expressions and closures to pass functionality around internally.
You can do it right now. The ag DLR (Silverlight Dynamic Languages Runtime) can host javascript.
While Javascript cannot be hosted with the DLR outside the browser Ruby and Python can. Here's an example of a C# snippet using the DLR and hosting a piece of Python of code to demonstrate.
using IronPython.Hosting;
PythonEngine pythonEngine = new PythonEngine();
string script = #"import clr
clr.AddReference(""System.Windows.Forms"")
import System.Windows.Forms as WinForms
WinForms.MessageBox.Show(""Hello"", ""Hello World"")";
pythonEngine.Execute(script);
This is possible, but a little more tricky, using Microsoft's .NET framework.
The C# compiler is part of the base runtime, so you can compile an in-memory assembly, and execute code in there on the fly.
Here is a good MSDN blog post describing the basic process.
I have used this before to make a scripting engine for a C# project. With a little work wrapping this, you can make this quite easy to use. An open source project I've worked on has a project dedicated to this: Pluto.Scripting
We had examples and tests in that project which show dynamic compilation and execution of C#, VB.NET, and Boo.
If you don't mind Boo, you can use its interpreter.
Actually I kept on getting an error "unexpected indent" so changing the code to
PythonEngine pythonEngine = new PythonEngine();
string script = #"import clr; clr.AddReference(""System.Windows"");";
script += #"import System.Windows as Wins;";
script += #"Wins.MessageBox.Show(""Hello World"");";
pythonEngine.Execute(script);
Worked! interesting... Thanks
Why do you need this feature ? Shouldnt your code know its paths and include that logic ? If you cant forsee such use cases - then perhaps its not needed. The only real benefit is it opens an opportunity to be abused and attacked. It sounds like your in directly creating a potential for an exploit - its a shame because managed runtimes like Java/CLR dont allow code injection but you are bringing all that goodness back in...
How do you extract an RT_RCDATA section from a Win32 executable (preferably in C#)?
The only way I know how to do this currently is opening up the EXE in Visual Studio. I'd love to be able to do this entirely in C# if possible.
Thanks!
P/Invoke LoadResource will be your safest bet.
Otherwise you'll have to write your own P/E processor eg. PE Processor example. The processor isn't the end of the world, but as you can see much more involved than a P/Invoke.
Almost forgot,as far as tools go, most P/E browsers will do this for you. Eg. P/E Explorer, which is available but not really being developed. I've also used IDA Pro for stuff like this. A quick IDA plugin would do this easily.
I assume that you are trying to read a resource of type RCDATA from an executable (be aware that "executable section" means a different thing - it refers to the .text, .data, .rdata, etc parts of the PE file). If you want to read it from the current assembly, here is a tutorial showing how: Accessing Embedded Resources using GetManifestResourceStream, using the GetManifestResourceNames and GetManifestResourceStream methods.
If you don't want to read it from the current executable, you can use a method similar to the one shown here.
These methods have the advantage over PInvoke that they are 100% .NET and you don't have to fiddle with marshaling the arguments to/from platform data types and making sure that you validated all the return values.
Is there such a thing as an x86 assembler that I can call through C#? I want to be able to pass x86 instructions as a string and get a byte array back. If one doesn't exist, how can I make my own?
To be clear - I don't want to call assembly code from C# - I just want to be able to assemble code from instructions and get the machine code in a byte array.
I'll be injecting this code (which will be generated on the fly) to inject into another process altogether.
As part of some early prototyping I did on a personal project, I wrote quite a bit of code to do something like this. It doesn't take strings -- x86 opcodes are methods on an X86Writer class. Its not documented at all, and has nowhere near complete coverage, but if it would be of interest, I would be willing to open-source it under the New BSD license.
UPDATE:
Ok, I've created that project -- Managed.X86
See this project:
https://github.com/ZenLulz/MemorySharp
This project wraps the FASM assembler, which is written in assembly and as a compiled as Microsoft coff object, wrapped by a C++ project, and then again wrapped in C#. This can do exactly what you want: given a string of x86/x64 assembly, this will produce the bytes needed.
If you require the opposite, there is a port of the Udis86 disassembler, fully ported to C#, here:
https://github.com/spazzarama/SharpDisasm
This will convert an array of bytes into the instruction strings for x86/x64
Take a look at Phoenix from Microsoft Research.
Cosmos also has some interesting support for generating x86 code:
http://www.gocosmos.org/blog/20080428.en.aspx
Not directly from C# you can't. However, you could potentially write your own wrapper class that uses an external assembler to compile code. So, you would potentially write the assembly out to a file, use the .NET Framework to spin up a new process that executes the assembler program, and then use System.IO to open up the generated file by the assembler to pull out the byte stream.
However, even if you do all that, I would be highly surprised if you don't then run into security issues. Injecting executable code into a completely different process is becoming less and less possible with each new OS. With Vista, I believe you would definitely get denied. And even in XP, I think you would get an access denied exception when trying to write into memory of another process.
Of course, that raises the question of why you are needing to do this. Surely there's got to be a better way :).
Take a look at this: CodeProject: Using unmanaged code and assembly in C#.
I think you would be best off writing a native Win32 dll. You can then write a function in assembler that is exported from the dll. You can then use C# to dynamically link to the dll.
This is not quite the same as passing in a string and returning a byte array. To do this you would need an x86 assembler component, or a wrapper around masm.exe.
i don't know if this is how it works but you could just shellexecute an external compiler then loading the object generated in your byte array.