Provide C#'s namespace from IronPython - mono

I want to write Tomboy add-on using IronPython and I'm stuck and very beginning -- I need to provide C#'s namespace.
I mean, here's howto in writing Tomboy add-on's http://live.gnome.org/Tomboy/HowToCreateAddins
Let's start with creating the plugin
file called InsertDateTime.cs with the
following content:
using Tomboy;
namespace Tomboy.InsertDateTime
{
public class InsertDateTimeAddin : NoteAddin
{
public override void Initialize ()
{
}
public override void Shutdown ()
{
}
public override void OnNoteOpened ()
{
}
}
}
Can I do that with IronPython? Thank you.

From Python you can import the clr module and then call clr.AddReference('AssemblyName') where assembly name is a partial or full assembly name - maybe in your case it's Tomboy, it's whatever you'd compile against with C#. Then you can do "import Tomboy" or "from Tomboy import NoteAddin".
If you're hosting IronPython via the hosting APIs you can instead do scriptRuntime.LoadAssembly(typeof(NoetAddin).Assembly); so that you don't have to do it in Python. That can be particularly useful to avoid various loader context issues depending on how the assembly gets loaded.

Related

How to convert an existing customized SwapChainPanel from C++/CX to C++/WinRT

I'm attempting to convert my existing C++/CX code to C++/WinRT in order to figure out whether that would enable me to compile that code using Clang. However, I'm stuck early on.
The C++/CX code that I need to convert is used to build a Direct3D component (based on SwapChainPanel) that is eventually utilized in a Windows UWP app that is written in C#. The problem I'm facing is that I just don't manage to convert my customized SwapChainPanel to C++/WinRT.
The code looks as follows:
namespace Why::Does::This::Not::Work
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class BaseView : public Windows::UI::Xaml::Controls::SwapChainPanel
{
protected private:
BaseView();
// Lots of other stuff
};
}
namespace Why::Does::This::Not::Work
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class CustomView sealed : public BaseView
{
public:
CustomView();
// ...
event AnimationEventHandler^ AnimationStarted;
private protected:
// Lots of private protected stuff
};
}
namespace Why::Does::This::Not::Work
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class AnimationEventArgs sealed
{
public:
AnimationEventArgs() {}
AnimationEventArgs(int start, int end)
{
Start = start;
End = end;
}
property int Start;
property int End;
};
[Windows::Foundation::Metadata::WebHostHidden]
public delegate void AnimationEventHandler(Platform::Object^ sender, AnimationEventArgs^ e);
}
As far as I'm able to interpret the documentation I need to do what is described under If you're authoring a runtime class to be referenced in your XAML UI in the documentation.
So, it seems to me that I'd need to author an IDL file in order to generate the COM stuff that is required. However, I cannot even make the skeleton IDL compile:
namespace Why
{
namespace Does
{
namespace This
{
namespace Not
{
namespace Work
{
runtimeclass CustomView : Windows::UI::Xaml::Controls::SwapChainPanel
{
CustomView();
}
}
}
}
}
}
When attempting to compile the above code all I'm getting is
error MIDL2025: [msg]syntax error [context]: expecting { near ":"
error MIDL2026: [msg]cannot recover from earlier syntax errors; aborting compilation
I apologize if you view this as a stupid question. I have read the corresponding documentation but I just fail to comprehend what is really going on when utilizing C++/WinRT. I have plenty of experience with C++ but zero with COM which means it is everything else than straight forward to understand C++/WinRT.
If someone can lend me a hand translating the above C++/CX code to C++/WinRT that would be highly appreciated. Please don't just point me to the documentation, that just doesn't help.
EDIT:
Modifying the sample IDL code as follows successfully compiled it:
namespace Why
{
namespace Does
{
namespace This
{
namespace Not
{
namespace Work
{
[default_interface]
runtimeclass CustomView : Windows.UI.Xaml.Controls.SwapChainPanel
{
CustomView();
}
}
}
}
}
}
However, exposing a user control to another language, in my case C#, such as the one inheriting from SwapChainPanel is dramatically more complex than doing the same thing in C++/CX. There's an IDL to deal with that is not easy to handle because there don't seem to be any complex samples around. That IDL generates several header files that I'm not really sure about what to do with because the documentation is lacking and samples are sparse. C++/WinRT is not for the faint-hearted and its complexity compared to C++/CX is simpy much higher.
It seems to me that to really understand C++/WinRT it is a necessity to have a good grasp of COM because compared to C++/CX, C++/WinRT does a poor job of hiding those COM related internals. This is especially the case when dealing with DirectX. Add to this an IDL that in itself is hard to deal with and a documentation of it that might suffice to get simple samples up and running but does not help much when porting a full fledged C++/CX app.
Doing what we do with C++/CX in C++/WinRT is just not economical for and we will stay on C++/CX until C++/WinRT becomes much more user friendly. Eliminating the need for the IDL (see https://wpdev.uservoice.com/forums/110705-universal-windows-platform/suggestions/36095386-get-rid-of-idl-for-c-winrt-components) would help too.
Without the prospect of being able to compile our code using Clang I would not even think about moving away from C++/CX. Microsoft shouldn't wonder that the adoption of C++/WinRT is slow. If they seriously want to change that they have to lower the entry barrier considerably.
Fully qualified type names in IDL use the period (.) as the namespace separator. A working IDL file would look like this:
namespace Why
{
namespace Does
{
namespace This
{
namespace Not
{
namespace Work
{
runtimeclass CustomView : Windows.UI.Xaml.Controls.SwapChainPanel
{
CustomView();
}
}
}
}
}
}
There's fairly complete documentation at Microsoft Interface Definition Language 3.0 reference. Even with that, it's often challenging to make any sense out of MIDL error messages.

redefine static methods with ByteBuddy

Can homebody help me please to give me a hint how to redefine static methods using byte-buddy 1.6.9 ?
I have tried this :
public class Source {
public static String hello(String name) {return null;}
}
public class Target {
public static String hello(String name) {
return "Hello" + name+ "!";
}
}
String helloWorld = new ByteBuddy()
.redefine(Source.class)
.method(named("hello"))
.intercept(MethodDelegation.to(Target.class))
.make()
.load(getClass().getClassLoader())
.getLoaded()
.newInstance()
.hello("World");
I got following Exception :
Exception in thread "main" java.lang.IllegalStateException: Cannot inject already loaded type: class delegation.Source
Thanks
Classes can only be loaded once by each class loader. In order to replace a method, you would need to use a Java agent to hook into the JVM's HotSwap feature.
Byte Buddy provides a class loading strategy that uses such an agent, use:
.load(Source.class.getClassLoader(),
ClassReloadingStrategy.fromInstalledAgent());
This does however require you to install a Java agent. On a JDK, you can do so programmatically, by ByteBuddyAgent.install() (included in the byte-buddy-agent artifact). On a JVM, you have to specify the agent on the command line.

How to implement Java interfaces in Frege?

I have been trying out Frege and one of the first things I would like to do is implement a Java interface.
How is that done?
Here's my example in Java:
package mypkg;
import frege.repl.FregeRepl;
import frege.runtime.Concurrent;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class FregeMain implements BundleActivator {
public FregeMain() {
}
#Override
public void start( BundleContext context ) throws Exception {
System.out.println( "Frege Bundle activated" );
new Thread( () -> FregeRepl.main( new String[ 0 ] ) ).start();
}
#Override
public void stop( BundleContext context ) throws Exception {
System.out.println( "Frege stopping. Goodbye!" );
Concurrent.shutDownIfExists();
}
}
To implement this in Frege, I would need to know:
how to declare something that will be visible as a class called mypkg.FregeMain implementing BundleActivator in JVM bytecode (notice that this is important as the OSGi framework will scan the jar for classes implementing that interface, and call them automatically).
How to implement a Runnable (as a Haskell lambda, probably) and pass it on to the Thread constructor. Also same issue: implement a Java interface, but this time with an anonymous class or lambda.
I tried to understand the Calling Java from Frege post, but probably due to my lack of experience in Frege/Haskell, I just don't understand most of that.
Thanks for any input.
The simplest way to implement Java interface in Frege is possibly to use an inline module definition. Some thorough examples are in https://github.com/Frege/FregeFX/blob/master/fregefx/src/main/frege/fregefx/JavaFxUtils.fr

How to specify HttpWebRequest.Headers["Range"] in a PCL?

I'm writing a progressive downloader as a Portable Class Library (Profile=24). It will support partial downloads of target files in chunks of bytes. HttpClient not being available, I'm going with HttpWebRequest, which has the AddRange method for partial downloads. But the method doesn't seem to be available from inside the PCL. So I set HttpWebRequest.Headers["Range"], but doing so throws the following ArgumentException:
"The 'Range' header must be modified using the appropriate property or method.\r\nParameter name: name"
That "appropriate property" seems to be HttpWebRequest.AddRange, but as I said it doesn't seem to be exposed from inside PCL. So I'm quite confused: what would be the right way of specifying the HttpWebRequest.Headers["Range"] in a PCL?
Thanks,
Simon
I didn't find the answer, but the following interface workaround worked for me:
Instead of creating the HttpWebRequest in my portable code, I defined the following custom interfaces:
public interface IMyRequest {
[...]
void AddRange(long from, long to);
}
public interface IMyRequestFactory {
IMyRequest Create(string url);
}
Then, in my non-portable code, I created classes that implemented those interfaces:
public class MyRequestImp : IMyRequest {
private readonly HttpWebRequest request;
public MyRequestImp (string url) {
request = (HttpWebRequest)WebRequest.Create(url);
}
[...]
public void AddRange(long from, long to) {
request.AddRange(from, to);
}
}
public class MyRequestFactoryImp: IMyRequestFactory {
public IMyRequest Create(string url) {
return new MyRequestImp(url);
}
}
At some point at initialization time, my non-portable code is passing a MyRequestFactoryImp object to my portable library through the IMyRequestFactory interface. Since the HttpWebRequest was created outside the PCL, you have access to the full functionalities of the class.

Can you apply aspects in PostSharp without using attributes?

I know with Castle Windsor, you can register aspects (when using method interception in Windsor as AOP) using code instead of applying attributes to classes. Is the same possible in Postsharp? It's a preference things, but prefer to have aspects matched to interfaces/objects in one place, as opposed to attributes all over.
Update:
Curious if I can assign aspects to interfaces/objects similiar to this:
container.Register(
Component
.For<IService>()
.ImplementedBy<Service>()
.Interceptors(InterceptorReference.ForType<LoggingAspect>()).Anywhere
);
If you could do this, you would have the option of NOT having to place attributes on assemblies/class/methods to apply aspects. I can then have one code file/class that contains which aspects are applied to which class/methods/etc.
Yes. You can either use multicasting (http://www.sharpcrafters.com/blog/post/Day-2-Applying-Aspects-with-Multicasting-Part-1.aspx , http://www.sharpcrafters.com/blog/post/Day-3-Applying-Aspects-with-Multicasting-Part-2.aspx) or you can use aspect providers (http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-12-e28093-Aspect-Providers-e28093-Part-1.aspx , http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-13-e28093-Aspect-Providers-e28093-Part-2.aspx).
Example:
using System;
using PostSharp.Aspects;
using PostSharp.Extensibility;
[assembly: PostSharpInterfaceTest.MyAspect(AttributeTargetTypes = "PostSharpInterfaceTest.Interface1", AttributeInheritance = MulticastInheritance.Multicast)]
namespace PostSharpInterfaceTest
{
class Program
{
static void Main(string[] args)
{
Example e = new Example();
Example2 e2 = new Example2();
e.DoSomething();
e2.DoSomething();
Console.ReadKey();
}
}
class Example : Interface1
{
public void DoSomething()
{
Console.WriteLine("Doing something");
}
}
class Example2 : Interface1
{
public void DoSomething()
{
Console.WriteLine("Doing something else");
}
}
interface Interface1
{
void DoSomething();
}
[Serializable]
class MyAspect : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
Console.WriteLine("Entered " + args.Method.Name);
}
}
}
I recommend that if you have complex requirements for determining which types get certain aspects that you consider creating an aspect provider instead.
Have a look at LOOM.NET, there you have a post compiler and a runtime weaver. With the later one you are able to archive exactly what you want.
It should be possible to use the PostSharp XML configuration. The XML configuration is the unification of the Plug-in and Project models in the project loader.
Description of .psproj could be found at http://www.sharpcrafters.com/blog/post/Configuring-PostSharp-Diagnostics-Toolkits.aspx.
Note, that I've only seen examples how PostSharp Toolkits use this XML configuration.
But it should work for custom aspects the same way.
Warning: I've noticed that installation of a PostSharp Toolkit from Nuget overwrites existing psproj file. So do not forget to back up it.