乐趣区

自定义UiPath Activity实践

开发环境准备:

Microsoft Visual Studio with the .NET C# desktop development workload installed.

NuGet Package Explorer.

自定义 Activity 分两种,CodeActivity 和 NativeActivity。简单的区分就是 CodeActivity 只是执行一段代码,NativeActivity 的效果就像内置 Activities 一样,它们实际上就是不同 Activity 的父类,实现的时候选择继承哪个类,你的 Activity 就是属于哪个分类。我们这里是实现 CodeActivity,NativeActivity 请看开源代码的实现。功能是把特定分隔符连接的字符串分割开,然后随机返回其中的某一个。应用在给选择框一个随机的值。因为主要是学习的目的,所以实际上并没有跟选择框有太大的关联,只是对字符做了处理而已。
自定义 Activity 分两步,首先通过 C# 语言来编写你的 Activity 逻辑,编译生成.dll 文件,然后通过 NuGet Package Explorer 打包。
下面跟着提示一步一步创建 C# 项目:

Launch Microsoft Visual Studio.
Click 文件 > 创建 > 项目 (shortcut: Ctrl + Shift + N). The New Project window is displayed.
Click Visual C#. The list of all dependencies using C# is displayed.
给你的 Activity 取个名字, 这里是“SelectRandomItem”。
选择类库 (.NET Framework) and click OK. 这样才能把项目导出为 .dll 文件。
Click 项目 > 添加引用….
分别搜索 System.Activities 和 System.ComponentModel.Composition 引用,并勾选。
Click the OK button. 这样就可以在代码中使用 System.Activities 和 System.ComponentModel.Composition 这两个基础组件了。

下面是已添加注释的实现代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

using System.Activities;
using System.ComponentModel;

namespace SelectRandomItem
{
public class SelectRandomItem : CodeActivity
{
// 参数类型,输入或者输出,或者两者都是
[Category(“Input”)]
// 必须参数
[RequiredArgument]
public InArgument<String> FullText {get; set;}

[Category(“Input”)]
// 参数默认值
[DefaultValue(“\r\n”)]
public InArgument<String> Separator {get; set;}

[Category(“Output”)]
public OutArgument<String> ChoiceResult {get; set;}

/**
* Execute 是 CodeActivity 必须重载的方法
* 处理逻辑根据 Separator 指定的分割符分割 FullText
* 然后随机返回其中一个
*
**/
protected override void Execute(CodeActivityContext context)
{
// 所有的参数取值、赋值都是通过 context
var fullText = FullText.Get(context);
var separator = Separator.Get(context);
string[] items = Regex.Split(fullText, separator, RegexOptions.IgnoreCase);
Random ran = new Random();
var result = items[ran.Next(items.Length)];
ChoiceResult.Set(context, result);
}
}

}

然后点击 生成 > 生成 SelectRandomItem。在输出栏找到 SelectRandomItem.dll 文件所在位置,准备下一步打包使用。

退出移动版