Question / Problem:
Can List<T> and LINQ methods be used from KTA .NET script activities?
Answer / Solution:
Generic Lists and LINQ extension methods are commonly used in .NET development, and developers are used to having them work in new code with no extra steps. But this is because most project templates already include the necessary reference and using clause. These can be used in KTA script activities with a few extra steps.
Take this example of a script using LINQ that can be added to a script activity in KTA:
var str = (string)sp.InputVariables["TestString"]; var invalidChars = "t".ToCharArray(); //List<char> charList=invalidChars.ToList(); var filtered=new string(str .Where(x => !invalidChars.Contains(x)) .ToArray()); sp.OutputVariables["Result"] = filtered;
Missing using statement
If you try to validate the script activity it will show this error:
Error CS1061: ‘string’ does not contain a definition for ‘Where’ and no extension method ‘Where’ accepting a first argument of type ‘string’ could be found (are you missing a using directive or an assembly reference?)
A developer might then recognize, that they need to add the using statement to the beginning of the script:
Missing assembly reference
But even with the using statement in place, trying to validate the script produces this error:
Error CS0234: The type or namespace name ‘Linq’ does not exist in the namespace ‘System’ (are you missing an assembly reference?)
This is because the actual assembly that defines the LINQ methods needs to be referenced. Per Microsoft documentation: The System.Linq namespace is in the System.Core assembly (in System.Core.dll).
Adding a reference accessible to script activities
In KTA Designer, under Integration, click on .NET Assemblies, and add a new Local assembly with Reference Path set to “System.Core.dll" (no path). Then add the assembly as a reference in the process that contains the script activity.
The assembly is added in the properties of the process. In KTA 7.5 and earlier this is on the Advanced tab. In 7.6 and later it is on the “History, reporting, and execution” tab.
Now clicking Validate in the script activity will succeed.
Applying the Same Logic
Now try uncommenting the commented out line:
Validating the script now makes it clear we are again have the same problem. Per Microsoft documentation: List<T> is in the System.Collections.Generic namespace which is in System.Collections.dll. Just like before, add the using statement for the namespace into the script and add the local assembly reference to the system and process.