自定義UiPath Activity實踐

開發環境準備:

自定義Activity分兩種,CodeActivity和NativeActivity。簡單的區分就是CodeActivity只是執行一段代碼,NativeActivity的效果就像內置Activities一樣,它們實際上就是不同Activity的父類,實現的時候選擇繼承哪個類,你的Activity就是屬於哪個分類。
我們這裏是實現CodeActivity,NativeActivity請看開源代碼的實現。
功能是把特定分隔符連接的字符串分割開,然後隨機返回其中的某一個。應用在給選擇框一個隨機的值。因爲主要是學習的目的,所以實際上並沒有跟選擇框有太大的關聯,只是對字符做了處理而已。

自定義Activity分兩步,首先通過C#語言來編寫你的Activity邏輯,編譯生成.dll文件,然後通過NuGet Package Explorer打包。

下面跟着提示一步一步創建C#項目:

  1. Launch Microsoft Visual Studio.
  2. Click 文件 > 創建 > 項目 (shortcut: Ctrl + Shift + N). The New Project window is displayed.
  3. Click Visual C#. The list of all dependencies using C# is displayed.
  4. 給你的Activity取個名字, 這裏是 “SelectRandomItem”。
  5. 選擇類庫(.NET Framework) and click OK. 這樣才能把項目導出爲 .dll文件。
  6. Click 項目 > 添加引用….
  7. 分別搜索 System.ActivitiesSystem.ComponentModel.Composition 引用,並勾選。
  8. Click the OK button.這樣就可以在代碼中使用 System.ActivitiesSystem.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 RandomChoiceText
{
    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文件所在位置,準備下一步打包使用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章