How to use .NET DLLs in Java Applet?

Java Application With WPF Interface Java applet using .NET
Purpose

In many projects a lot of custom business logic can be written in .NET languages like C#, VB.NET or F#. While trying to implement custom Java Applet that will be easily hosted in the users browsers, enabling to reuse that logic within those applications by running them locally on target machines with native performance might prove useful. Additionally, the possibility of using C# in Java applets provides us with unlimited access to all the existing and third-party .NET frameworks and components that can be utilized in the Java-based applet project.

Reusing the .NET code in Java Applet might be beneficial because of significant cost and time savings in any project.

Overview

Starting with Javonet 1.3, it is possible to host and use Javonet within Java Applet through Web Browser.

Diagram below depicts conceptual scheme of how Javonet runs in Java Applets:

overview

Solution Summary

Developer should create Java Applet code as a JAR file. All custom .NET DLLs to be used (those that are not included in .NET Framework) should be included within that Java applet JAR archive.

Web page with Java Applet tag should be created. Java Applet tag should firstly specify main class from Java Applet jar file in the “CODE” attribute and, secondly, comma separated Java Applet JAR file, Javonet JAR file and all other dependent JAR files (if needed) in the “ARCHIVE” attribute.

 <applet code="JavonetAppletMain.class" 
 	archive="applet.jar,javonet_1.4hf10.jar" 
 	width="500" 
 	height ="300">

While the user enters the Java Applet Page, the browser will load Applet by calling main class from Java Applet JAR file. Applet should extract custom DLLs and save them in a temporary directory on one’s Hard Drive. Subsequently, the Applet should set new temporary directory as a current directory in java user.dir property and then activate Javonet.

Javonet will save the license file to the temporary directory and will be set to work. Java Applet main class should add references to custom .NET dlls stored in user’s temp directory and perform any operations needed. Javonet will have full access to user’s local .NET framework and custom DLLs from temporary directory.

Optional: instead of temporary directory in enterprise environment, developer can consider using any fixed dedicated directory like “c:\appletTools\”.

Prerequisites:

In order to run the solution, following conditions must be met:

  • Java Applet must be exported to JAR file;
  • Java Applet JAR file must be signed (a self-signed jar is an option);
  • Javonet JAR file must be signed (a self-signed jar is an option);
  • Certificate used to sign JARs must be included in trusted root certificates on target machine;
  • User must allow to grant full permissions for Java Applet, so the applet will have access to user’s local files, .NET framework and temporary directory with read/write permissions;
  • Javonet license must allow for multiple activations equal to expected amount of users accessing the Java Applet. (it is possible for a developer to test on FREE or developer’s license on his own machine, but running the code from another machine will require multiple activations – this can be requested while placing order for commercial Javonet license).
Project Content

This sample project consists of all the items required to build and run the solution. The sample is exported as a Eclipse project, however it can be used in any other IDE or, alternatively, get compiled from the command line.

contents

The project contains single “JavonetAppletMain” class, which is the Java applet implementation. In the project folder you will also find the following items:

  • appletPage.html sample HTML page which hosts the Java Applet;
  • Javonet.ValueTypesSample.dll sample custom .NET DLL which provides a method to sum two integers;
  • Keystore.p12 certificates keystore in PKCS#12 format which holds the sample self-signed certificate that can be used to sign the sample applet JAR file and Javonet JAR file;
  • projectBuilder.xml the ANT file for automating the project build process.
Implementation Details

In “JavonetAppletMain” class you will find three methods and a constructor. The constructor is responsible for initializing and activating Javonet, as well as extracting custom .NET DLLs and adding them as reference in Javonet.

	public JavonetAppletMain()
	{
    	try {
    		System.out.println("Javonet: Creating temp directory for .NET DLLs");
			//We are creating temporary directory were Javonet license file will be stored
			//This directory can be used to extract and store our .NET dlls which should
			//be loaded by applet
			Path p = Files.createTempDirectory("Javonet");
			System.out.println("Temp Directory: " + p.toAbsolutePath());
			
			System.out.println(String.format("Javonet: Setting temp %s directory as current dir", p.toAbsolutePath().toString()));
			//We overwrite default current directory so .NET side will use our temp directory
			//instead of default for applets path which is set to users desktop
			setCurrentDirectory(p.toAbsolutePath().toString());		    	        
			
			System.out.println("Javonet: Activating Javonet...");
			//Activate Javonet
			Javonet.activate("your@mail.com", "your-javonet-license-key",JavonetFramework.v40);
			
			System.out.println("Javonet: Extracting .NET DLLs to local temp directory...");
			//Extract Custom .NET DLLs from your JAR file
			String myLibPath = extractDotNetLib("Javonet.ValueTypesSample.dll",p.toAbsolutePath().toString());
			
			System.out.println("Javonet: Loading .NET DLLs references...");
			//Add Reference to extracted Custom .NET DLL
			Javonet.addReference(myLibPath);
			
			System.out.println("Javonet: Loaded and initialized.");
			
		} catch (JavonetException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

The helper method “extractDotNetLib” provides the functionality required to extract custom .NET DLLs from applet JAR archive and place them in temporary directory, so that .NET framework can load those DLLs during execution.

Another helper method called “setCurrentDirectory” replaces the default user.dir property value. It changes the value from default path, pointing to user’s desktop, to the local temporary folder path. The Javonet license and custom .NET DLLs will be stored in that folder during the execution of an applet.

The main part of the project is located in “init()” method, and is invoked once the applet has been initialized and loaded in the browser. In this method we create three sample labels; then, using the Timer class, we schedule the execution of our logic, which uses .NET code through Javonet.

In each execution of a timer we load, .NET “Random” class generates the random integer and then uses our custom class from custom .NET DLL Javonet.ValueTypesSample.dll in order to add the sample random integer to 5. The result of these operations is presented in the labels content in the browser.

	public void init() {
		setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
		final Label label = new Label("Look at me, I'm a Java Applet using .NET!");
     add(label);
        
		final Label label2 = new Label("Hello world!");
     add(label2);
        
		final Label label3 = new Label("Hello world!");
     add(label3);
        
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			  @Override
			  public void run() {
				  try 
			    	{				
						//Sample code using .NET Framework Random Class
						NObject objRandom = Javonet.New("System.Random");
						int value = objRandom.invoke("Next",10,20);

						//Display result on Java Applet labels
						label2.setText(".NET generated random number: "+value+"!");
						
						//Sample code using custom class "Sample" from extracted DLL file
						NObject sampleObj = Javonet.New("Sample");
						Integer result = sampleObj.invoke("AddInt",value,5);
						
						//Display result calculated using custom .NET DLL
						label3.setText("Random number + 5 calculated using custom .NET dll: "+result+"!");
					} 
			    	catch (JavonetException e) 
			    	{
						// TODO Auto-generated catch block
						e.printStackTrace();
						label3.setText(e.toString()); 
					}
			  }
			}, 500, 500);
	}

The methods and objects used in the sample only begin to scratch the surface of possibilities that will be within your reach, if you use anything written in .NET within your Java applets.

How to Build the Sample Project

To build the sample project you can rely on the prepared self-signed certificate and ANT build script. The solution can be compiled by running the ANT script, which will automate the compilation of the project, creation of the JAR file, packing custom .NET DLLs into that JAR archive and signing both the applet and Javonet JARs.

Before building the solution make sure that you have downloaded the latest Javonet library from our Download section, and that you have replaced the email and license key in the “activate” method with your own.

After these steps are completed, Right Click “projectBuilder.xml” file and choose Run As > Ant Build. Make sure that your build is executed using the Java Runtime located in “JDK” folder. Otherwise the error of missing jarsigner might occur. To choose the target Java Runtime select “Run As” > “Ant Build…” and go to “JRE” tab.

When the compilation is completed, following output in the console should appear:

Output of building Java Applet with .NET DLLs

The “applet.jar” should be updated.

How to Run the Sample Project

To run the sample project just copy the “applet.jar”, “appletPage.html” and Javonet JAR files into the Web Server. If you are using the self-signed keys or keys stored in sample keystore.p12, please add those keys as trusted root certificates in your Java configuration panel.

  1. Go to Control Panel
  2. Open Java console
  3. Go to Security tab
  4. Open “Manage Certificates…”
  5. Click “Import”
  6. Select the “keystore.p12”
  7. In the password pop-up type “javonet”
  8. Press Ok

Once the certificate is trusted, open the appletPage.html in the browser.

How to Generate Custom Self-Signed Certificate

To create your own self-sign certificate you can use the JDK “keytool” application running following command from command line:

“c:\{JDK_PATH}\bin\keytool.exe” -genkey -keystore keystore.p12 -deststoretype PKCS12 -alias javonet -storepass javonet -validity 360