How to use dotNET Assemblies

There are many many dotNET assemblies available. To use an assembly inside an Invoke Code Activity you can install it in the Global Assembly Cache (GAC) and import it, or you can use it directly, the way I present here.

Create the Assembly

Let us start with an own tiny assembly. This assembly contains only one function, with the name test. This function has one parameter and delivers a string.

//-Begin----------------------------------------------------------------

using System;

public class TestLibrary {

  public string Test(string Name = "World") {
    return "Hello " + Name;
  }

}

//-End------------------------------------------------------------------

image

  • We compile this file to a DLL, if we work with Windows - Legacy compatibility mode (x86), with the command: c:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:anycpu -out:TestLibrary.dll -target:library TestLibrary.cs.

  • If we work with Windows compatibility mode (x64) it is necessary to create an additional CS projekt file in the same directory, in this case TestLibrary.csproj as below. To compile the source to a DLL we call the command: dotnet build.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>

    <TargetFrameworks>net5.0-windows7.0</TargetFrameworks>

    <OutputType>Library</OutputType>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>none</DebugType>
    <Optimize>true</Optimize>

  </PropertyGroup>

</Project>

Use the Assembly

Copy the assembly TestLibrary.dll into your UiPath project directory. To use the function of this assembly in your Invoke Code Activity it is necessary to do three steps:

  1. Load the assembly with the method LoadFrom.
  2. Get an object that represents the class with GetType.
  3. Create an instance of the class with CreateInstance.

After this steps we can use the function of the assembly in our code.

System.Reflection.Assembly TestLibrary = System.Reflection.Assembly.LoadFrom(@"TestLibrary.dll");
System.Type Class = TestLibrary.GetType("TestLibrary");
dynamic Instance = System.Activator.CreateInstance(Class);

string Result = Instance.Test("Stefan");
System.Console.WriteLine(Result);

Result = Instance.Test();
System.Console.WriteLine(Result);

image

In this example I try it one time with a parameter and one time without a parameter.

image

Conclusion

On this way it is possible to use dotNET assemblies directly in the code sequence of the Invoke Code Activity.

9 Likes

Thanks for a great guide, @StefanSchnell! Just wanted to add that you can skip GetType() if you use Assembly.CreateInstance Method (System.Reflection) | Microsoft Docs instead.

So instead of:

System.Type Class = TestLibrary.GetType("TestLibrary");
dynamic Instance = System.Activator.CreateInstance(Class);

you can write:

dynamic Instance = TestLibrary.CreateInstance("TestLibrary");
2 Likes

Thank you @ptrobot :slightly_smiling_face: