自定义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文件所在位置,准备下一步打包使用。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理