Quick Start Guide

  1. Installing javOnet
  2. UPDATED v1.3 Activating javOnet
  3. Adding References to .NET Libraries
  4. Invoking Static Methods
  5. Creating Instance and Calling Instance Methods
  6. NEW v1.1 Calling Generic Methods
  7. Get/Set Values for Static Fields and Properties
  8. Get/Set Values for Instance Fields and Properties
  9. Passing Reference-Type Arguments
  10. NEW v1.2 Passing Arguments by Reference with “ref” and “out” Keywords
  11. Arrays: Using Value-Type and Reference-Type Arrays
  12. Subscribing to .NET Events
  13. Disposing of a .NET Object
  14. Using the javOnet Fluent Interface
  15. Extending .NET class in JAVA and wrapping .NET methods
  16. Handling .NET Exceptions
  17. Accessing the .NET AppConfig File (connectionStrings and appSettings)

Installing javOnet

Note: Before using javOnet, make sure you have .NET 3.5 and JDK 1.6 or newer installed.

As javOnet is single file solution, all you need to start using it is to download the latest javOnet jar file into your JAVA project, and add a reference to this file in your build path.

How to add the javOnet JAR reference in Eclipse?

  1. Right click on your JAVA project in “Package Explorer”.
  2. Open Build Path > Configure Build Path, choose “Add JARs.
  3. Select the javOnet jar file.

Activating javOnet

Before using javOnet, you must first activate your licence. Your license can be activated in your code using static method activate

To activate javOnet in your code

Note: The “Javonet.activate(…)” method must be called before you use any other javOnet features.

Example

public static void main(String[] args) throws JavonetException { Javonet.activate("your@email.com", "YOUR-LICENSE-KEY");
//Todo: Your javOnet powered application code }

Activation must be called only once at the start-up of your application. During the first activation, javOnet contacts our servers and generates a javonet.lic file in your application directory. All subsequent calls simply verify this file.

How to activate javOnet using a proxy?

Starting with javOnet v1.3, the activation method allows for new optional arguments which can be used to configure Javonet to activate the license using a local proxy server.

Using these new arguments proxy details, used by Javonet while performing activation, can be specified. Javonet supports any HTTP proxy:

  • Without authentication
  • With authentication
  • With authentication based on Active Directory accounts

In environment where proxy settings are required to access internet these activate method overloads can be used:

activate(String email, String licenceKey, String proxyHost)
activate(String email, String licenceKey, String proxyHost, String proxyUsername, String proxyPassword)
activate(String email, String licenceKey, String proxyHost, String proxyUsername, String proxyPassword, String proxyDomain)

Specify the hostname and port or IP address in standard formats in the proxyHost field.

  • hostname:port
  • ip_address:port

Note: In environments where proxy settings are required to access the Internet, use these activate method overloads:

public static void main(String[] args) throws JavonetException {
	Javonet.activate("your@email.com", "YOUR-LICENSE-KEY","myProxyServerHost:80","proxyUserName", "proxyPassword");
	//Todo: Your javOnet powered application code
}
Activating javOnet through an XML configuration file

There are many benefits to activating and setting up javOnet using an XML configuration file. It simplifies distribution of your application to your team, lets you update the javOnet license more quickly, and avoids hardcoded activation details.

During the first application use, javOnet searches for, and then automatically uses the XML configuration file to activate your application.

Simply name the file “javonet.xml” and place it in the root directory of your JAVA application .

Sample javOnet XML configuration file

<?xml version="1.0" encoding="ISO-8859-1" ?>
<javonet>
<activation>
<username>YOUR NAME</username>
<email>your@email.com</email>
<licencekey>YOUR-LICENSE-KEY</licencekey>
</activation>
</javonet>

Starting with version 1.3, javOnet supports proxy settings for activations. These settings can be defined as activate method arguments or as an optional tag in your XML configuration file using the following syntax:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<javonet>
<activation>
      <username>YOUR NAME</username>
      <email>your@email.com</email>
      <licencekey>YOUR-LICENSE-KEY</licencekey>
      <proxy>
           <host>HOST_NAME:PORT</host>
           <username>OPTIONAL_USER_NAME</username>
           <password>OPTIONAL_USER_PASSWORD</password>
           <domain>OPTIONAL_USER_DOMAIN:PORT</domain>
      </proxy>
</activation>
</javonet>

Adding References to .NET Libraries

JavOnet allows you to use any .NET library. As with any regular .NET application, you need to reference the libraries you are planning to use. You can reference any custom DLL file on your computer or registered in GAC, as well as any library from the .NET Framework.

To add a reference, call the Javonet.addReference(“library_path_or_name”) method.

Example

public static void main(String[] args) throws JavonetException {
	Javonet.activate("YOUR NAME", "your@email.com", "YOUR-LICENSE-KEY");

	Javonet.addReference("System.Windows.Forms","System.Drawing");
	Javonet.addReference("yourDotNet.dll");
}

In the addReference argument, you can provide the local DLL file name, the full path or the name of the library registered in GAC. If you plan to reference more than one library, you can pass all of them as arguments, or call addReference several times.

Note: By default javOnet references mscorlib from the .NET framework.

Invoking Static Methods

To invoke the static method, first get the particular .NET type and call invoke providing method arguments.

Example how to call static method “Show” on “MessageBox”

	Javonet.getType("MessageBox").invoke("Show","Hello Javonet!");

The invoke method allows you to call any .NET static or instance method with or without arguments. Value-type arguments are automatically translated to appropriate .NET types, and you can also pass referenced arguments as explained later in this guide.

Creating Instance and Calling Instance Methods

JavOnet lets you create instances of any .NET type. To store reference of a particular .NET object, the javOnet-created NObject JAVA type can be used by variables of any .NET object.

To create an instance of a .NET object, call the Javonet.New method. Once called, you’ve created a reference to that object that could be assigned to NObject variable, which you can then use to perform any operations on that object.

Example

Here’s how to call “Next” method on instance of .NET “Random” class:

	NObject objRandom = Javonet.New("System.Random");
	Integer value = objRandom.invoke("Next",10,20);

	System.out.println(value);

JavOnet calls are very similar to regular .NET or Java calls, with a little bit of reflection style. Value-type results are automatically converted into JAVA types so you can safely assign them to JAVA variables. Reference-type results must be assigned to NObject variable.

Any calls to .NET objects using javOnet can be shortened and simplified using our Fluent interface. To find out more, click here.

Calling Generic Methods

With javOnet you can very easly invoke any generic instance or static method. To call a generic method, you need to provide types that will be used during the method invocation. Those types can be passed as an instance of NType objects initialized with particular .NET types. Let’s assume you have following .NET object you want to use from JAVA:

class GenericSample 
{
    public void MyGenericMethod<T>(T arg1) 
    {
          return;
    }
    public K MyGenericMethodWithTwoTypes<T,K>(T arg1) 
    {
          //Some operation
          return null;
    }
}
// Sample .NET usage
GenericSample genSample = new GenericSample();
genSample.MyGenericMethod<String>("sample");
genSample.MyGenericMethodWithTwoTypes<String,Int32>("sample");

If you want to call MyGenericMethod with type String, you need to use following piece of JAVA code in javOnet:

// (..) initialize javonet + load your .NET dll
NObject genSample = Javonet.New("GenericSample"); //Create new instance of GenericSample class
//Invoke generic method with one type
genSample.generic(Javonet.getType("String")).invoke("MyGenericMethod","sample");
//Invoke generic method with two types
genSample.generic(Javonet.getType("String"),Javonet.getType("Int32")).invoke("MyGenericMethodWithTwoTypes","sample");
  1. Create an instance of our GenericSample class.
  2. Using the generic method, initialize the generic method invocation by passing one or many generic types of arguments.
  3. Invoke your method with a sample argument.

Javonet.getType(typeName) returns an instance of NType object attached to a specific .NET type. The instruction NType myType = Javonet.getType(“String”) is the Java equivalent of the .NET Type myType = typeof(String).

Get/Set Values for Static Fields and Properties

With javOnet you can easily get or set a value for any static field or property on a .NET class or structure by calling the “get” or “set” method on reference to .NET type. Conversely, .NET instance types can be stored in JAVA variables using the dedicated JAVA type called NType.

As with the methods, value-typed results are automatically translated into JAVA types and reference results are returned as NObject objects.

Example

	NType dateTimeClass = Javonet.getType("DateTime");

	NObject nowDateObj= dateTimeClass.get("Now");

	String currentDateString = nowDateObj.invoke("ToString");

In this example we retrieve the value of the static Now field on .NET DateTime class, and store it in the NObject variable named nowDateObj. We then use this object to call ToString method.

Similarly, you can call set on any .NET static field or property:

//Your .NET class
	public class JavonetSample
	{
		public static int MyStaticField { get; set; }
	}
//Usage in JAVA
	NType sampleType = Javonet.getType("JavonetSample");
	sampleType.set("MyStaticField", 10);
	Integer val = sampleType.get("MyStaticField");

Get/Set Values for Instance Fields and Properties

To set or get values of instance fields, get or create an instance of the .NET object, and call get or set methods on NObject containing this object.

Example

//Your .NET class
	public class JavonetSample
	{
		public int MyInstanceField { get; set; }
	}
//Usage in JAVA
	NObject sampleObj = Javonet.New("JavonetSample");
	sampleObj.set("MyInstanceField", 10);
	Integer val = sampleObj.get("MyInstanceField");

Passing Reference-Type Arguments

With javOnet, you can very easily pass any .NET object argument to any .NET method, or substitute a .NET field or property. Instances of .NET objects can be stored in your JAVA application using the special NObject type variable. When passing the NObject object to the .NET method, just pass it as a reference.

	NObject size = Javonet.New("System.Drawing.Size");
	size.set("Width", 500);
	size.set("Height", 100);

	NObject label = Javonet.New("System.Windows.Forms.Label")
	label.set("Size", size);

As you see you can create an instance of the Size object, set its “Width” and “Height” properties, and pass it into the Size property on the Label object. This way you can pass the object as an argument to any method.

Example

	NObject nowDateObj= Javonet.getType("DateTime").get("Now");

	NObject date = Javonet.New("DateTime",1980,1,1);
	NObject datesDiff = nowDateObj.invoke("Subtract",date);

Here the “Now” field gets a value from DateTime. Then we create a new DateTime value, passing a date of 1980-01-01 as constructor arguments, then we subtract these dates. The datesDiff variable will store an instance of the TimeSpan object that holds the difference between now and 1980-01-01.

Passing Arguments by Reference with “ref” and “out” Keywords

Microsoft .NET allows you to create methods that expect arguments to be passed by reference. Passing by reference is introduced by explicitly setting ref or out keywords before argument type within the method definition. For example, void MyMethod(ref int arg1).

Note: Passing arguments by reference should not be confused with passing reference-type arguments described in the previous section. If you need just to pass another .NET object in method arguments, please see the previous section.

JavOnet allows you to pass by reference both .NET objects (NObject) or primitive types (String, Integer, Float, Boolean etc..). You can also pass arrays of these types like NObject[] or String[].

While passing variables by reference, the value of that variable might be modified within the method body. Read more about .NET ref and out keywords here:

JavOnet allows you to invoke methods expecting “ref” or “out” arguments by providing two dedicated types: NRef and NOut. To pass the variable by reference, you must wrap the variable with the NRef or NOut class. For NObject and NObject[], you can wrap them with NRef or NOut directly. However because JAVA does not support passing by reference primitive types, both variables (like String, Integer, Boolean etc.) or arrays of them should be wrapped with the “AtomicReference” class, and then wrapped with NRef or NOut object.

Example .NET object with expecting “ref” argument method

class RefExample
{
	public void Method(ref int i)
	{
		i = i + 44;
	}
}

Example of a “ref” argument method from JAVA using javOnet

 NObject refEx = Javonet.New("RefExample");
 //Wrap Java integer in AtomicReference to allow passing by reference
 AtomicReference<Integer> myInt = new AtomicReference<Integer>(10);

 refEx.invoke("Method",new NRef(myInt));

 System.out.println(myInt.get());
 //Output will display number "55" because int passed by reference has been modified within the method body.

Example of a Int32.TryParse (string arg, out int number) method from JAVA

 String strNumber = "4";
 AtomicReference<Integer> myInt=new AtomicReference<Integer>();

 //NOut constructor with argument type is used because myInt has NULL value. Without specifying explicitly 
 //argument type .NET would not be able to locate proper method to execute.
 if (Javonet.getType("Int32").invoke("TryParse",strNumber,new NOut(myInt,"System.Int32")))
 {
 	System.out.println(myInt.get());
 }

Example of an “out” argument method to populate an array of custom .NET objects

 
class Item 
{ 
     public String ItemName { get; set; } 
} 
class PopulateItems 
{ 
     public void Populate(out Item[] items) 
     { 
           items = new Item[5]; 
           for (int i=0; i<=5; i++) 
           { 
                items[i]=new Item(); 
                items[i].ItemName="Item"+i.ToString(); 
           } 
     }
}

Example of a populate method passing items in an array with an “out” argument

The populate method expects to pass an items array with an “out” argument. Therefore the items array does not need to be initialized before calling the method, and after execution, the passed variable will be filled with items.

 
NObject populator = Javonet.New("PopulateItems"); 
NObject[] items; 

populator.invoke("Populate", new NOut(items));

//After execution of this method local items array variable will contain five items generated within Populate method body.

Arrays: Using Value-Type and Reference-Type Arrays

With javOnet, you can use any value-type or reference-type arrays. Arrays can be retrieved from field or property values, returned as method invocation results, or passed as arguments or set to fields and properties. All array operations can be performed both on instance and static elements.

Using arrays is very simple. Value-typed arrays are translated into regular arrays of corresponding JAVA types. Reference-typed arrays are represented as array of NObject objects.

Example

//Sample .NET class
    public class Item
    {
        public string ItemName { get; set; }
    }
    public class Sample
    {
        public string[] GetItems()
        {
            return new string[] { "item1", "item2", "item3" };
        }
        public Item[] GetRefItems()
        {
            return new []{ new Item("Item1"),new Item("Item2"), new Item("Item3")};
        }
        public void DisplayArray(string[] items)
        {
            Console.Out.WriteLine("Displaying value-typed array");
            foreach (var item in items)
                Console.Out.WriteLine(item);
        }
        public void DisplayArray(Item[] items)
        {
            Console.Out.WriteLine("Displaying ref-typed array");
            foreach (var item in items)
                Console.Out.WriteLine(item.ItemName);
        }
    }
//Usage in JAVA
	//Retrieving array of strings
	NObject sampleObj = Javonet.New("Sample");
	String[] items = sampleObj.invoke("GetItems");
	for (int i=0; i<items.length;i++)
	{
		System.out.println(items[i]);
	}

	//Passing array of strings
	String[] stringArray = new String[] {"Item1","Item2","Item3"};
	sampleObj.invoke("DisplayArray",new Object[] {stringArray});

	//Retrieving array of .NET objects
	NObject[] refArray = sampleObj.invoke("GetRefItems");
	for (int i=0; i<refArray.length;i++)
	{
		System.out.println(refArray[i].get("ItemName"));
	}

	//Passing array of .NET objects
	sampleObj.invoke("DisplayArray",new Object[] {refArray});

Subscribing to .NET Events

Subscribe to any .NET event with javOnet. Event subscription works the same way as listening JAVA events. The performance of event subscription is extremely high and allows you to interact with .NET code like it was native JAVA code. When the event occurs, your JAVA listener callback is called in a separate thread.

The simplest way to subscribe an event is to use an anonymous JAVA class.

Example

To create a .NET button and listen for a “Click” event:

	NObject button = Javonet.New("System.Windows.Forms.Button");
	button.set("Text", "Click me!");

	button.addEventListener("Click",new INEventListener() {
		public void eventOccurred(Object[] arguments) {
			System.out.println(".NET event occured");
		}
	});

The anonymous class should implement special INEventListener interface. Alternatively you can write a separate class as the event listener by extending NEventListener and overriding the eventOccurred method, or by implementing the INEventListener interface.

//Your custom JAVA listener class for .NET events

	public class MyEventListener implements INEventListener
	{
		@Override
		public void eventOccurred(Object[] arguments) {
			System.out.println(".NET Event Occurred");
		}

	}

//Usage of your listener class

	NObject button = Javonet.New("System.Windows.Forms.Button");
	button.set("Text", "Click me!");

	MyEventListener listener = new MyEventListener();
	button.addEventListener("Click",listener);

Disposing of a .NET Object

You can integrate the JAVA garbage collector with your .NET objects using javOnet. When you create an .NET object and store it in a JAVA variable, it will be handled in .NET process as long as your variable lives in the JAVA memory.

When JAVA collects the NObject object, this event is passed to .NET, and the corresponding .NET object is disposed and collected. If the .NET object implements the IDisposable interface, then the appropriate disposal procedure is followed.

You can also force object disposal by calling the “Dispose” method on the “NObject” object. javOnet exposes the dedicated “Dispose” method for closing all objects and releasing .NET memory. This method should be called only at the end of your JAVA application.

Using the javOnet Fluent Interface

javOnet offers a robust fluent interface that lets you simplify and shorten operations on .NET objects.

Example

//Regular code
	NObject nowDateObj= Javonet.getType("DateTime").get("Now");

	NObject date = Javonet.New("DateTime",1980,1,1);
	NObject datesDiff = nowDateObj.invoke("Subtract",date);

	String dateDiffStr = datesDiff.invoke("ToString");

	System.out.println(dateDiffStr); 

//Fluent code
	String dateDiffStr = Javonet.getType("DateTime")
		.<NObject>get("Now")
		.<NObject>invoke("Subtract",Javonet.New("DateTime",1980,1,1))
		.invoke("ToString");
	System.out.println(dateDiffStr);

Extending the .NET Class in JAVA and Wrapping .NET Methods

You can extend any .NET class by extending the JAVA class with the “NObject” type and then call the constructor base constructor by passing the name of the .NET type and arguments for its constructor as an argument.

Example

Here’s an example of how to extend the.NET System.Windows.Forms.Form class and wrap the ShowDialog method.

public class MyExtendedForm extends NObject {

	public MyExtendedForm() throws JavonetException
	{
		super("System.Windows.Forms.Form");
	}

	public void ShowDialog() throws JavonetException
	{
		this.invoke("ShowDialog");
	}
}

Handling .NET Exceptions

Any .NET exception can be handled in your JAVA code. All javOnet methods that operate on .NET objects throw a JavonetException when exceptions occur. You can catch .NET exceptions by catching the JavonetExceptions, and then perform the appropriate exception handling logic.

	try 
	{
		NObject sampleObj = Javonet.New("Sample");
		Integer result = sampleObj.invoke("AddInt",4,5);

		System.out.println(result);
	}
	catch (JavonetException je)
	{
		//Todo: Your exception handling code
	}

Accessing the .NET AppConfig File (connectionStrings and appSettings)

If your .NET logic uses App.Config files, reads information from connectionStrings sections, appSettings or needs any other data from configuration, you can use javOnet to load this file.

To do this, use the following method in your application. This method should be called just after activating javOnet and before any other operation. Simply add the BindConfig method to your application and call it by passing the path to your config file with config file name as an argument.

Example

public static void main(String[] args) throws JavonetException, IOException {
        Javonet.activate("your@mail.com", "your-javonet-license-key");

        String path = new File( "." ).getCanonicalPath()+"\\";
        BindConfig(path+"app.config");
}

private static void BindConfig(String configFile) throws JavonetException {
        Javonet.getType("AppDomain").getRef("CurrentDomain").invoke("SetData","APP_CONFIG_FILE", configFile);
}
  • Łukasz Ładyński

    Cool!

Top