dotNet4Java Examples

The following examples demonstrate how to use the dotNet4Java to produce a software by combining Java Source Codes with .Net framework and other .Net libraries.

How to write a simple Hello World using .Net Console

import com.dotNet4Java.IClrObject; import com.dotNet4Java.TClrActivator; import com.dotNet4Java.TClrObject; import com.dotNet4Java.api.EClrError; import com.dotNet4Java.api.core.DotNetNativeTypes; /** * Java Class equivalent of .Net Console Static type 'System.Console' */ class Console extends TClrObject { private static IClrObject staticType; private Console(DotNetNativeTypes.ClrObject clrObject) { super(clrObject); } private static IClrObject getStaticConsole() { if (staticType == null) { staticType = TClrActivator.createStaticInstance("System.Console"); } return staticType; } public static void WriteLine(String value) throws EClrError { getStaticConsole().invokeVoidMethod("WriteLine", new String[]{"System.String"}, new Object[]{value}); } public static void WriteLine() throws EClrError { getStaticConsole().invokeVoidMethod("WriteLine"); } public static void ReadKey() throws EClrError { getStaticConsole().invokeVoidMethod("ReadKey"); } } public class ConsoleApp { public static void main(String[] arg) { try { Console.WriteLine(" Hello! Welcome to dotNet4Java. "); Console.WriteLine("=================================================="); Console.WriteLine("The program displays the string Hello World!"); Console.WriteLine(); Console.WriteLine("Hello World!"); Console.WriteLine("Press any key to exit."); } catch (EClrError eClrError) { eClrError.printStackTrace(); } } }

How to use AppDomain to Load .Net Assemblies

Exported from Notepad++
import com.dotNet4Java.*; public class LoadAssemblyUsingAppDomain { static void DisplayAssemblyInfo(IClrAssembly AAssembly) throws Exception { if (AAssembly == null) { System.out.println("Assembly cannot be loaded"); } else { System.out.println("Assembly has been loaded"); System.out.println("Assembly FullName: " + AAssembly.getFullName()); System.out.println("Global Assembly Cache: " + AAssembly.getGlobalAssemblyCache()); System.out.println("Location: " + AAssembly.getLocation()); System.out.println("Image Runtime Version: " + AAssembly.getImageRuntimeVersion()); System.out.println("Number of Types: " + AAssembly.getTypes().length); System.out.println(); System.out.println(); } } static void loadAssemblyByAssemblyString() throws Exception { System.out.println("Loading System.Data.dll using full Assembly String"); IClrAssembly m_assembly = TClrAppDomain.getCurrentDomain().load("System.Data, Version=2.0.0.0, " + "Culture=neutral, PublicKeyToken=b77a5c561934e089"); DisplayAssemblyInfo(m_assembly); } public static void main(String[] arg) { System.out.println("Hello! Welcome to dotNet4Java"); System.out.println("=================================================="); System.out.println("The program demonstrate how to use AppDomain to Load .Net Assemblies"); System.out.println(); try { loadAssemblyByAssemblyString(); } catch (Exception eClrError) { eClrError.printStackTrace(); } } }

How to use Activator to Create instance of a .Net Object

Exported from Notepad++
import com.dotNet4Java.*; import com.dotNet4Java.api.EClrError; public class CreateInstanceUsingActivator { static void displayObjectTypeInfo(Object AObject) throws EClrError { if (AObject == null) { System.out.println("Object has not been instantiated"); } else { IClrType m_type = TClrType.getObjectType(AObject); System.out.println("Object has been instantiated"); System.out.println("Assembly FullName: " + m_type.getAssembly().getFullName()); System.out.println("FullName: " + m_type.getFullName()); System.out.println("ToString: " + m_type.toString()); System.out.println(); System.out.println(); } } static void loadAssembly() throws EClrError { TClrAssembly.load("System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); } static void createInstanceUsingTypeName() throws EClrError { IClrObject sqlConnection = TClrActivator.createInstance("System.Data.SqlClient.SqlConnection"); displayObjectTypeInfo(sqlConnection.toObject()); } static void createInstanceUsingType() throws EClrError { IClrType sqlConnectionType = TClrAssembly.findType("System.Data.SqlClient.SqlConnection"); IClrObject sqlConnection = TClrActivator.createInstance(sqlConnectionType); displayObjectTypeInfo(sqlConnection.toObject()); } static void createInstanceUsingTypeWithNoConstructorParameters() throws EClrError { //Create Instance with a parameter Object[] objects = new Object[]{"Data Source=myServerAddress;Initial Catalog=myDataBase;" + "User ID=myDomain\\myUsername;Password=myPassword;"}; //<Change Me> //Assembly has been loaded in CreateInstance2, no need to reload assembly IClrType sqlConnectionType = TClrAssembly.findType("System.Data.SqlClient.SqlConnection"); IClrObject sqlConnection = TClrActivator.createInstance(sqlConnectionType, objects); displayObjectTypeInfo(sqlConnection); } public static void main(String[] arg) { System.out.println(" Hello! Welcome to dotNet4Java "); System.out.println("=================================================="); System.out.println("The program demonstrate how to use Activator Class"); System.out.println("to create an instance of a .Net Object. "); System.out.println(); try { loadAssembly(); createInstanceUsingTypeName(); createInstanceUsingType(); createInstanceUsingTypeWithNoConstructorParameters(); } catch (EClrError eClrError) { eClrError.printStackTrace(); } } }

How to load external .Net dLL and access types

Exported from Notepad++
import com.dotNet4Java.*; import com.dotNet4Java.Enums.AssemblyLoadType; import com.dotNet4Java.api.EClrError; /* Assuming you have .Net library project below built as Mathematics.Dll namespace Mathematics { public class Mathematics { public int Add(int a, int b) { return a + b; } public int Subtract(int a, int b) { return a - b; } public bool Equal(int a, int b) { return a == b; } } } */ //Corresponding Java class type of Mathematics type in the Mathematics.dll /** * Class to list the type names in the Mathematics.dll as well as load the .net dll */ class MathematicsAssembly { private final static String assemblyId = "1"; private final static String assemblyPath = "C:\\Temp\\Mathematics.dll"; //<Change Me> public static final MathematicsAssembly INSTANCE = new MathematicsAssembly(); static { TClrAssembly.register(assemblyId, assemblyPath, AssemblyLoadType.fileLocation); } public final String MathematicsTypeName = "Mathematics.Mathematics"; public final String IntegerTypeName = "System.Int32"; private IClrAssembly MathematicsAssembly; public IClrAssembly getAssembly() throws EClrError { if (MathematicsAssembly == null) { MathematicsAssembly = TClrAssembly.getRegisteredAssembly(assemblyId); } return MathematicsAssembly; } } /** * Java Class equivalent of the .Net type 'Mathematics' in Mathematics.dll */ class Mathematics extends TClrObject { public Mathematics() throws EClrError { super(MathematicsAssembly.INSTANCE.MathematicsTypeName, (Object[]) null); } public int Add(int a, int b) throws EClrError { return invokeIntMethod("Add", new String[]{MathematicsAssembly.INSTANCE.IntegerTypeName, MathematicsAssembly.INSTANCE.IntegerTypeName}, new Object[]{a, b}); } public int Subtract(int a, int b) throws EClrError { return invokeIntMethod("Subtract", new String[]{MathematicsAssembly.INSTANCE.IntegerTypeName, MathematicsAssembly.INSTANCE.IntegerTypeName}, new Object[]{a, b}); } public boolean Equal(int a, int b) throws EClrError { return invokeBooleanMethod("Equal", new String[]{MathematicsAssembly.INSTANCE.IntegerTypeName, MathematicsAssembly.INSTANCE.IntegerTypeName}, new Object[]{a, b}); } } public class LoadInvokeExternalDotNetDLL { static Mathematics mathematics; static void createMathematicsObjectInstance() throws EClrError { mathematics = new Mathematics(); } static void accessMathematicsObjectMethods() throws EClrError { System.out.println("Add(30, 50): " + mathematics.Add(30, 50)); System.out.println("Subtract(30, 50): " + mathematics.Subtract(30, 50)); System.out.println("Equal(30, 50): " + mathematics.Equal(30, 50)); System.out.println("Equal(50, 50): " + mathematics.Equal(50, 50)); } public static void main(String[] arg) { System.out.println(" Hello! Welcome to dotNet4Java. "); System.out.println("=================================================="); System.out.println("This program demonstrate how to use dotNet4Java to"); System.out.println("load and invoke .Net Library and Types "); System.out.println(); try { createMathematicsObjectInstance(); accessMathematicsObjectMethods(); } catch (EClrError eClrError) { eClrError.printStackTrace(); } } }

How to use ClrObject interface to connect to SQL Server

import com.dotNet4Java.*; public class UsingClrObject { static void createDotNetSqlConnectionObject() throws Exception { IClrObject sqlConnection = new TClrObject(TClrActivator.createInstance("System.Data.SqlClient.SqlConnection")); try { //<Change Me> String connectionString = "Data Source=MyDataSourceName;Initial Catalog=MyDBName;User ID=MyUserName;Password=MyPasswd"; System.out.println("Connecting to SQL Connection using : " + connectionString); System.out.println(); sqlConnection.setPropertyValue("ConnectionString", connectionString); System.out.println("SqlConnection.ConnectionString = " + sqlConnection.getPropertyValueAsString("ConnectionString")); System.out.println(); sqlConnection.invokeVoidMethod("Open"); System.out.println("Connection Opened"); System.out.println(); sqlConnection.invokeVoidMethod("Close"); System.out.println("Connection Closed"); } finally { sqlConnection.close(); } } public static void main(String[] arg) { System.out.println(" Hello! Welcome to dotNet4Java. "); System.out.println("=================================================="); System.out.println("This program demonstrates how to use IClrObject to connect to Sql Server."); System.out.println(); try { TClrAssembly.loadWithPartialName("System.Data"); System.out.println("The Assembly [System.Data] has been loaded."); System.out.println(); createDotNetSqlConnectionObject(); } catch (Exception eClrError) { eClrError.printStackTrace(); } } }

How to use .Net Collections in Java

Exported from Notepad++
import com.dotNet4Java.TClrArray; import com.dotNet4Java.TClrObject; import com.dotNet4Java.api.EClrError; /** * .Net Sorted List equivalent in Java */ class SortedList extends TClrObject { static String SortedList_TypeName = "System.Collections.SortedList"; static String Object_TypeName = "System.Object"; static String Integer_TypeName = "System.Int32"; public SortedList() throws EClrError { super(SortedList_TypeName, new Object[]{}); } public int getCount() throws EClrError { return getPropertyValueAsInt("Count"); } public Object get(Object key) throws EClrError { return getPropertyIndexValue("Item", new String[]{Object_TypeName}, new Object[]{key}); } public void set(Object key, Object value) throws EClrError { setPropertyIndexValue("Item", TClrArray.of(Object_TypeName), TClrArray.of(key), value); } public Object GetByIndex(int index) throws EClrError { return invokeMethod("GetByIndex", TClrArray.of(Integer_TypeName), TClrArray.of(index)); } public Object GetKey(int index) throws EClrError { return invokeMethod("GetKey", TClrArray.of(Integer_TypeName), TClrArray.of(index)); } public int Add(Object key, Object value) throws EClrError { return invokeIntMethod("Add", TClrArray.of(Object_TypeName, Object_TypeName), TClrArray.of(key, value)); } } public class Collections { static void printKeysAndValues(SortedList myList) throws EClrError { System.out.println("\t-KEY-\t-VALUE-"); for (int i = 0; i < myList.getCount(); i++) { System.out.println(String.format("\t%s:\t%s", myList.GetKey(i), myList.GetByIndex(i))); } System.out.println(); } public static void main(String[] arg) { System.out.println(" Hello! Welcome to dotNet4Java "); System.out.println("=================================================="); System.out.println("The following code example shows how to add elements to a SortedList object."); System.out.println(); try { // Creates and initializes a new SortedList. SortedList mySL = new SortedList(); mySL.Add("one", "The"); mySL.Add("two", "quick"); mySL.Add("three", "brown"); mySL.Add("four", "fox"); // Displays the SortedList. System.out.println("The SortedList contains the following:"); printKeysAndValues(mySL); } catch (EClrError eClrError) { eClrError.printStackTrace(); } } }

How to use .Net Generic Dictionary in Java

import com.dotNet4Java.*; import com.dotNet4Java.api.EClrError; import com.dotNet4Java.api.util.ClrUtils; /** * Java equivalent of the .Net Dictionary generic class Dictionary<,> */ class Dictionary<TKey, TValue> extends TClrGenericObject { public Dictionary(String[] genericTypeNames) throws EClrError { super("System.Collections.Generic.Dictionary`2", genericTypeNames, ClrUtils.emptyParams()); } public int getCount() throws EClrError { return getPropertyValueAsInt("Count"); } public TValue get(TKey key) throws Exception { return (TValue) getPropertyIndexValue("Item", new String[]{getTypeParameters()[0].getFullName()}, new Object[]{key}); } public void set(TKey key, TValue value) throws Exception { setPropertyIndexValue("Item", TClrArray.of(getTypeParameters()[0].getFullName()), TClrArray.of(key), value); } public boolean ContainsKey(TKey key) throws Exception { return invokeBooleanMethod("ContainsKey", TClrArray.of(getTypeParameters()[0].getFullName()), TClrArray.of(key)); } public boolean TryGetValue(TKey key, TRefObject<TValue> value) throws Exception { return invokeBooleanMethod("TryGetValue", TClrArray.of(getTypeParameters()[0].getFullName(), getTypeParameters()[1].makeByRefType().getFullName()), TClrArray.of(key, value)); } public TKey GetKey(int index) throws EClrError { return (TKey) invokeMethod("GetKey", TClrArray.of("System.Int32"), TClrArray.of(index)); } public int Add(TKey key, TValue value) throws Exception { return invokeIntMethod("Add", TClrArray.of(getTypeParameters()[0].getFullName(), getTypeParameters()[1].getFullName()), TClrArray.of(key, value)); } public void Remove(TKey key) throws Exception { invokeVoidMethod("Remove", TClrArray.of(getTypeParameters()[0].getFullName()), TClrArray.of(key)); } public DictionaryEnumerator<TKey, TValue> GetEnumerator() throws EClrError { Object enumerator = invokeMethod("GetEnumerator"); return enumerator == null ? null : new DictionaryEnumerator<>(enumerator); } } /** * Java equivalent of the .Net Dictionary<TKey,TValue>.Enumerator class */ class DictionaryEnumerator<TKey, TValue> extends TClrObject { public DictionaryEnumerator(Object enumerator) throws EClrError { super(enumerator); } public DictionaryKeyValuePair<TKey, TValue> getCurrent() throws EClrError { return new DictionaryKeyValuePair<TKey, TValue>(getPropertyValue("Current")); } public boolean MoveNext() throws EClrError { return invokeBooleanMethod("MoveNext"); } } /** * Java equivalent of the .Net KeyValuePair<TKey,TValue> class */ class DictionaryKeyValuePair<TKey, TValue> extends TClrObject { public DictionaryKeyValuePair(Object enumerator) throws EClrError { super(enumerator); } public TKey getKey() throws EClrError { return (TKey) getPropertyValue("Value"); } public TValue getValue() throws EClrError { return (TValue) getPropertyValue("Value"); } } public class GenericDictionary { public static void main(String[] arg) { System.out.println(" Hello! Welcome to dotNet4Java "); System.out.println("=================================================="); System.out.println("This following example demonstrates how to use .Net Dictionary."); System.out.println(); try { // Create a new dictionary of strings, with string keys. Dictionary<String, String> OpenWith = new Dictionary<>(new String[]{"System.String", "System.String"}); // Add some elements to the dictionary. There are no // duplicate keys, but some of the values are duplicates. OpenWith.Add("txt", "notepad.exe"); OpenWith.Add("bmp", "paint.exe"); OpenWith.Add("dib", "paint.exe"); OpenWith.Add("rtf", "wordpad.exe"); // The Add method throws an exception if the new key is // already in the dictionary. try { OpenWith.Add("txt", "winword.exe"); } catch (EClrError error) { //ArgumentException System.out.println("An element with TKey = \"txt\" already exists."); } // The Item property is another name for the indexer, so you // can omit its name when accessing elements. System.out.println(String.format("For key = \"rtf\", value = %s.", OpenWith.get("rtf"))); // The indexer can be used to change the value associated // with a key. OpenWith.set("rtf", "winword.exe"); System.out.println(String.format("For key = \"rtf\", value = %s.", OpenWith.get("rtf"))); // If a key does not exist, setting the indexer for that key // adds a new key/value pair. OpenWith.set("doc", "winword.exe"); // The indexer throws an exception if the requested key is // not in the dictionary. try { System.out.println(String.format("For key = \"tif\", value =%s.", OpenWith.get("tif"))); } catch (EClrError error) { //(KeyNotFoundException) System.out.println("TKey = \"tif\" is not found."); } // When a program often has to try keys that turn out not to // be in the dictionary, TryGetValue can be a more efficient // way to retrieve values. TRefObject<String> TValue = new TRefObject<>(null); //if (OpenWith.TryGetValue("tif", TValue)) if (OpenWith.TryGetValue("rtf", TValue)) System.out.println(String.format("For key = \"tif\", value = %s.", TValue.argValue)); else System.out.println("TKey = \"tif\" is not found."); // ContainsKey can be used to test keys before inserting them. if (!OpenWith.ContainsKey("ht")) { OpenWith.Add("ht", "hypertrm.exe"); System.out.println(String.format("TValue added for key = \"ht\": %s", OpenWith.get("ht"))); } // When you use when loop to enumerate dictionary elements from GetEnumerator, // the elements are retrieved as KeyValuePair objects. System.out.println(); var OpenWithEnumerator = OpenWith.GetEnumerator(); while (OpenWithEnumerator.MoveNext()) { System.out.println(String.format("TKey = %s, TValue = %s", OpenWithEnumerator.getCurrent().getKey(), OpenWithEnumerator.getCurrent().getValue())); } // Use the Remove method to remove a key/value pair. System.out.println("Remove(\"doc\")"); OpenWith.Remove("doc"); if (!OpenWith.ContainsKey("doc")) System.out.println("TKey \"doc\" is not found."); } catch (Exception eClrError) { eClrError.printStackTrace(); } } }

How to raise and handle .Net Events in Java

Exported from Notepad++
import com.dotNet4Java.IClrObject; import com.dotNet4Java.TClrActivator; import com.dotNet4Java.TClrAssembly; import com.dotNet4Java.TClrObject; import com.dotNet4Java.api.EClrError; import com.dotNet4Java.api.core.DotNetNativeTypes; class EventHandler implements AutoCloseable { IClrObject sqlConnection; String connectionString; void loadAssembly() throws EClrError { //Load .Net Assembly from GAC with just partial name TClrAssembly.loadWithPartialName("System.Data"); } void createSQLConnectionTypeInstance() throws EClrError { //Create Instance of System.Data.SqlClient.SqlConnection object sqlConnection = new TClrObject(TClrActivator.createInstance("System.Data.SqlClient.SqlConnection")); sqlConnection.registerEventCallBack("StateChange", stateChangeEventHandler); } void openAndCloseSQLConnection() throws EClrError { //<Change Me> connectionString = "Data Source=MyDataSourceName;Initial Catalog=MyDBName;User ID=MyUserName;Password=MyPasswd"; sqlConnection.setPropertyValue("ConnectionString", connectionString); sqlConnection.invokeVoidMethod("Open"); System.out.println("Connection Opened"); System.out.println(); sqlConnection.invokeVoidMethod("Close"); System.out.println("Connection Closed"); } /* ====== C# EVENT HANDLERS ==== //C# Delegate of SqlConnection.StateChange event public delegate void StateChangeEventHandler(object sender, StateChangeEventArgs e); public enum ConnectionState { Closed = 0, Open = 1, Connecting = 2, Executing = 4, Fetching = 8, Broken = 16, } public sealed class StateChangeEventArgs { public ConnectionState CurrentState { get; } public ConnectionState OriginalState { get; } } */ // ====== JAVA EVENT HANDLERS EQUIVALENT ==== void writeStateChange(int State) { switch (State) { case 0: System.out.print("Closed"); break; case 1: System.out.print("Open"); break; case 2: System.out.print("Connecting"); break; case 4: System.out.print("Executing"); break; case 8: System.out.print("Fetching"); break; case 16: System.out.print("Broken"); break; default: System.out.println(); } } // Event Handler DotNetNativeTypes.IClrEventHandler stateChangeEventHandler = (sender, e) -> { IClrObject m_eventArgs = new TClrObject(e); int m_currentState = m_eventArgs.getPropertyValueAsInt("CurrentState"); int m_originalState = m_eventArgs.getPropertyValueAsInt("OriginalState"); System.out.print("Current State : "); writeStateChange(m_currentState); System.out.print("Original State : "); writeStateChange(m_originalState); }; @Override public void close() throws Exception { if (sqlConnection != null) { sqlConnection.unRegisterEventCallBack("StateChange", stateChangeEventHandler); sqlConnection.close(); } } } public class AdvancedEventHandler { public static void main(String[] arg) { System.out.println(" Hello! Welcome to dotNet4Java. "); System.out.println("===================================================="); System.out.println("This program demonstrates how to handle .Net events from Java."); System.out.println(); try { EventHandler eventHandler = new EventHandler(); try { eventHandler.loadAssembly(); eventHandler.createSQLConnectionTypeInstance(); eventHandler.openAndCloseSQLConnection(); } finally { eventHandler.close(); } } catch (EClrError eClrError) { eClrError.printStackTrace(); } catch (Exception exception) { exception.printStackTrace(); } } }

How to encrypt and decrypt sample data using the .Net RijndaelManaged

Exported from Notepad++
import com.dotNet4Java.TClrArray; import com.dotNet4Java.TClrObject; import com.dotNet4Java.api.EClrError; import com.dotNet4Java.api.Enums.BitwiseEnum; import com.dotNet4Java.api.core.DotNetNativeTypes; import com.dotNet4Java.api.util.ClrUtils; class RijndaelManaged extends TClrObject { public RijndaelManaged() throws EClrError { super("System.Security.Cryptography.RijndaelManaged", ClrUtils.emptyParams()); } public void setKey(int[] key) throws EClrError { setPropertyValue("Key", key); } public void setIV(int[] iv) throws EClrError { setPropertyValue("IV", iv); } public int[] getKey() throws EClrError { return (int[]) getPropertyValue("Key"); } public int[] getIV() throws EClrError { return (int[]) getPropertyValue("IV"); } public ICryptoTransform CreateEncryptor(int[] key, int[] iv) throws EClrError { DotNetNativeTypes.ClrObject cryptoTransform = invokeClrObjectMethod("CreateEncryptor", TClrArray.of("System.Byte[]", "System.Byte[]"), TClrArray.of(key, iv)); return cryptoTransform == null ? null : new ICryptoTransform(cryptoTransform); } public ICryptoTransform CreateDecryptor(int[] key, int[] iv) throws EClrError { DotNetNativeTypes.ClrObject cryptoTransform = invokeClrObjectMethod("CreateDecryptor", TClrArray.of("System.Byte[]", "System.Byte[]"), TClrArray.of(key, iv)); return cryptoTransform == null ? null : new ICryptoTransform(cryptoTransform); } public void GenerateKey() throws EClrError { invokeVoidMethod("GenerateKey"); } public void GenerateIV() throws EClrError { invokeVoidMethod("GenerateIV"); } } /** * Java equivalent of the C# ICryptoTransform interface */ class ICryptoTransform extends TClrObject{ public ICryptoTransform(DotNetNativeTypes.ClrObject clrObject) { super(clrObject); } } /** * Java equivalent of the C# MemoryStream Class */ class MemoryStream extends TClrObject { public MemoryStream()throws EClrError { super("System.IO.MemoryStream", new Object[]{}); } public MemoryStream(int[] cipherText) throws EClrError { super("System.IO.MemoryStream", new Object[]{cipherText}, new String[]{"System.Byte[]"}); } public int[] ToArray() throws EClrError { return (int[]) invokeMethod("ToArray"); } public void Close() throws EClrError { invokeVoidMethod("Close"); } } /** * Java equivalent of the C# CryptoStreamMode enumeration type */ enum CryptoStreamMode implements BitwiseEnum<CryptoStreamMode> { Read(0x0), Write(0x1); private final int _flags; CryptoStreamMode(int flags) { _flags = flags; } @Override public int getFlags() { return _flags; } } /** * Java equivalent of the C# CryptoStream Class */ class CryptoStream extends TClrObject { public CryptoStream(MemoryStream msEncrypt, ICryptoTransform encryptor, CryptoStreamMode mode) throws EClrError { super("System.Security.Cryptography.CryptoStream", new Object[]{msEncrypt, encryptor, mode}); } public void Close() throws EClrError { invokeVoidMethod("Close"); } } /** * Java equivalent of the C# StreamWriter Class */ class StreamWriter extends TClrObject { public StreamWriter(CryptoStream csEncrypt) throws EClrError { super("System.IO.StreamWriter", new Object[] {csEncrypt}); } public void Write(String plainText) throws EClrError { invokeVoidMethod("Write", new String[]{"System.String"}, new Object[]{plainText}); } public void Close() throws EClrError { invokeVoidMethod("Close"); } } /** * Java equivalent of the C# StreamReader Class */ class StreamReader extends TClrObject { public StreamReader(CryptoStream csDecrypt) throws EClrError { super("System.IO.StreamReader", new Object[]{csDecrypt}); } public void Close() throws EClrError { invokeVoidMethod("Close"); } public String ReadToEnd() throws EClrError { return invokeStringMethod("ReadToEnd"); } } public class RijndaelSecurity { // Note: The int[] should have been byte[] but Java and .Net byte types are different. So all the bytes in .Net are represented as integer static int[] encryptStringToBytes(String plainText, int[] Key, int[] IV) throws EClrError { // Check arguments. if (plainText.length() <= 0) throw new EClrError("plainText argument is empty"); if (Key == null || Key.length <= 0) throw new EClrError("Key argument is empty or null"); if (IV == null || IV.length <= 0) throw new EClrError("IV argument is empty or null"); // Create an RijndaelManaged object with the specified key and IV. RijndaelManaged rijAlg = new RijndaelManaged(); rijAlg.setKey(Key); rijAlg.setIV(IV); // Create a decrytor to perform the stream transform. ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.getKey(), rijAlg.getIV()); // Create the streams used for encryption. MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); StreamWriter swEncrypt = new StreamWriter(csEncrypt); //Write all data to the stream. swEncrypt.Write(plainText); swEncrypt.Close(); // Return the encrypted bytes from the memory stream. int[] result = msEncrypt.ToArray(); msEncrypt.Close(); csEncrypt.Close(); swEncrypt.Close(); return result; } static String decryptStringFromBytes(int[] cipherText, int[] Key, int[] IV) throws EClrError { // Check arguments. if (cipherText == null || cipherText.length <= 0) throw new EClrError("cipherText argument is empty or null"); if (Key == null || Key.length <= 0) throw new EClrError("Key argument is empty or null"); if (IV == null || IV.length <= 0) throw new EClrError("IV argument is empty or null"); // Create an RijndaelManaged object with the specified key and IV. RijndaelManaged rijAlg = new RijndaelManaged(); rijAlg.setKey(Key); rijAlg.setIV(IV); // Create a decryptor to perform the stream transform. ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.getKey(), rijAlg.getIV()); // Create the streams used for decryption. MemoryStream msDecrypt = new MemoryStream(cipherText); CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); StreamReader srDecrypt = new StreamReader(csDecrypt); // Read the decrypted bytes from the decrypting stream and place them in a string. String result = srDecrypt.ReadToEnd(); msDecrypt.Close(); csDecrypt.Close(); srDecrypt.Close(); return result; } public static void main(String[] arg) { try { String original = "Here is some data to encrypt!"; // Create a new instance of the RijndaelManaged class. // This generates a new key and initialization vector (IV). RijndaelManaged myRijndael = new RijndaelManaged(); myRijndael.GenerateKey(); myRijndael.GenerateIV(); // Encrypt the string to an array of bytes. int[] encrypted = encryptStringToBytes(original, myRijndael.getKey(), myRijndael.getIV()); // Decrypt the bytes to a string. String roundtrip = decryptStringFromBytes(encrypted, myRijndael.getKey(), myRijndael.getIV()); //Display the original data and the decrypted data. System.out.println(String.format("Original: %s", original)); System.out.println(String.format("Round Trip: %s", roundtrip)); System.out.println("Press any key to continue....."); } catch (EClrError eClrError) { eClrError.printStackTrace(); } } }

How to use .Net ArrayList in Java

Exported from Notepad++
import com.dotNet4Java.TClrArray; import com.dotNet4Java.TClrObject; import com.dotNet4Java.api.EClrError; import com.dotNet4Java.api.util.ClrUtils; /** * Java equivalent of the C# ArrayList Class */ class ArrayList extends TClrObject { public ArrayList() throws EClrError { super("System.Collections.ArrayList", ClrUtils.emptyParams()); } public int getCount() throws EClrError { return getPropertyValueAsInt("Count"); } public int getCapacity() throws EClrError { return getPropertyValueAsInt("Capacity"); } public Object get(int index) throws EClrError { return getPropertyIndexValue("Item", index); } public void set(int index, Object value) throws EClrError { setPropertyIndexValue("Item", TClrArray.of("System.String"), TClrArray.of(index), value); } public int Add(Object value) throws EClrError { return invokeIntMethod("Add", TClrArray.of("System.Object"), TClrArray.of(value)); } } public class ArrayListExample { public static void main(String[] arg) { System.out.println(" Hello! Welcome to dotNet4Java "); System.out.println("=================================================="); System.out.println(" This program prints out ArrayList values. "); System.out.println(); try { ArrayList AArrayList = new ArrayList(); AArrayList.Add("Hello"); AArrayList.Add("World"); AArrayList.Add("!"); System.out.println("Array List"); System.out.println(" Count: " + AArrayList.getCount()); System.out.println(" Capacity: " + AArrayList.getCapacity()); System.out.print(" Values:"); System.out.println(); for (int i = 0; i < AArrayList.getCount(); i++) { System.out.println("\t " + AArrayList.get(i)); } } catch (EClrError eClrError) { eClrError.printStackTrace(); } } }