SDK
最新
False
横幅背景图像
开发者指南
上次更新日期 2024年3月23日

使用代码创建活动(旧版)

重要提示:此页面上的信息涉及针对已弃用的 .NET Framework 的活动。 有关为最新版 Studio 创建目标为 .NET 的活动的信息,请参阅使用代码创建活动
An activity is the building block of a process automation. UiPath Studio comes with various built-in dedicated activities (such as PDF, mail, Excel, SAP, and more) you can install through the Package Manager, depending on your needs. You can read The UiPath Activities Guide for more details and examples, as well as how to Manage Activities Packages . Additionally, you can create custom activities to better automate processes based on your needs.

创建自定义活动需要采取两个主要步骤:

  1. 编写自定义活动代码。
  2. 在 UiPath 中添加外部程序集 (.dll)。
备注:

创建自定义活动需要以下组件:

编写自定义活动代码

为了更好地理解如何为自定义活动编写代码,我们将创建一个简单的活动,它要求用户输入两个数字,然后输出两个数字之和的平方。

  1. 启动 Microsoft Visual Studio。
  2. 单击 “文件”>“新建”>“项目…” (快捷键:Ctrl + Shift + N)。 系统将显示“ 新建项目” 窗口。
  3. 从“ 语言” 下拉菜单中选择“ C# ”。 系统将显示使用 C# 的所有依赖项的列表。
  4. 选择 “类库 (.NET Framework)”。 这有助于我们将自定义活动导出为 .dll 文件。 单击 “下一步” 转到“ 配置新项目 ” 窗口。


  5. 在“ 项目名称” 字段中填写所需的活动名称。 在本例中,我们可以使用“MathSquareOfSum”。
  6. 从“ 框架 ”下拉菜单中选择“ .NET Framework 4.6.1 ”。 这可确保该库与 UiPath Studio 兼容。
注意: 在 Windows - 旧版项目中,UiPath Studio 支持使用 .NET Framework 4.5.2 至 4.6.1 创建的活动。 有关如何将活动迁移到 .NET 以在具有 Windows 兼容性的项目中使用的信息,请参阅将 活动迁移到 .NET 6


  1. 单击“ 创建 ”以转到代码设计器并开始编写活动代码。
  2. 在“ 解决方案资源管理器 ”面板中,右键单击“ 引用 ”分支,然后选择“ 添加引用…”。 系统将显示“ 引用管理器 ”窗口。


  3. 搜索 System.ActivitiesSystem.ComponentModel.Composition 引用并添加它们。 请务必选中每个选项前面的复选框,然后单击“ 确定”。 这样做使我们能够使用上述参考中的类。




  4. 现在,我们需要确保代码使用新添加的引用。 这可以通过在代码设计器中添加以下行来完成:

    using System.Activities;
    using System.ComponentModel;using System.Activities;
    using System.ComponentModel;

    我们的项目现在应如下所示:



  5. 添加输入和输出参数。 在本例中,代码应如下所示:

    //Note that these attributes are localized so you need to localize this attribute for Studio languages other than English
     
    //Dots allow for hierarchy. App Integration.Excel is where Excel activities are.
    [Category("Category.Where.Your.Activity.Appears.In.Toolbox")]
    [DisplayName("Human readable name instead of class name")]
    [Description("The text of the tooltip")]
     public class MathSqSum : CodeActivity
    {
     
        //Note that these attributes are localized so you need to localize this attribute for Studio languages other than English
                 [Category("Input")]
            [DisplayName("First Number")]
            [Description("Enter the first number")]
            [RequiredArgument]
            public InArgument<int> FirstNumber { get; set; }
            [Category("Input")]
            [DisplayName("Second Number")]
            [Description("Enter the second number")]
            [RequiredArgument]
            public InArgument<int> SecondNumber { get; set; }
            [Category("Output")]
            public OutArgument<int> ResultNumber { get; set; }
            protected override void Execute(CodeActivityContext context)
            {
            }//Note that these attributes are localized so you need to localize this attribute for Studio languages other than English
     
    //Dots allow for hierarchy. App Integration.Excel is where Excel activities are.
    [Category("Category.Where.Your.Activity.Appears.In.Toolbox")]
    [DisplayName("Human readable name instead of class name")]
    [Description("The text of the tooltip")]
     public class MathSqSum : CodeActivity
    {
     
        //Note that these attributes are localized so you need to localize this attribute for Studio languages other than English
                 [Category("Input")]
            [DisplayName("First Number")]
            [Description("Enter the first number")]
            [RequiredArgument]
            public InArgument<int> FirstNumber { get; set; }
            [Category("Input")]
            [DisplayName("Second Number")]
            [Description("Enter the second number")]
            [RequiredArgument]
            public InArgument<int> SecondNumber { get; set; }
            [Category("Output")]
            public OutArgument<int> ResultNumber { get; set; }
            protected override void Execute(CodeActivityContext context)
            {
            }
<DisplayName(" ")> 属性是 Studio 中“ 属性 ”面板中输入字段之前显示的标签。 <Description(" ")> 属性是鼠标悬停时显示的工具提示文本。


如果您希望输入时必须声明已声明的元素,则需要 <ReguiredArgument> 属性。 如果未填写,则活动的标题栏中将显示蓝色警告图标。


12. 在覆盖的 <Execute( )> 函数中添加功能。 在本例中,如下所示:
protected override void Execute(CodeActivityContext context)
{
    var firstNumber = FirstNumber.Get(context);
  var secondNumber = SecondNumber.Get(context);
  
  var result = (int)Math.Pow(firstNumber + secondNumber, 2);
  ResultNumber.Set(context, result);
}protected override void Execute(CodeActivityContext context)
{
    var firstNumber = FirstNumber.Get(context);
  var secondNumber = SecondNumber.Get(context);
  
  var result = (int)Math.Pow(firstNumber + secondNumber, 2);
  ResultNumber.Set(context, result);
}

构建设计器界面(可选)

如果您不希望活动具有设计器界面,则可以跳至构建库部分。

重要提示:

为了构建设计器界面,您需要在 Visual Studio 中安装 Windows 工作流基础 组件。 如果尚未从 Visual Studio 安装程序中选择组件,则可以按如下方式添加:

  • 在 Visual Studio 中,单击“ 工具 ” 菜单,然后选择 “获取工具和功能…”。 系统将显示“Visual Studio 安装程序”窗口。
  • 切换到“ 单个组件 ”选项卡,然后搜索 Windows Workflow Foundation 组件。 它位于“ 开发活动 ”部分下。
  • 选中 Windows Workflow Foundation 组件前面的复选框,然后单击“ 修改”。 所需组件已安装。


13. 在“ 属性 ”面板中右键单击项目(在本例中,项目为 MathSquareOfSum)。 系统将显示上下文菜单。



14. 从“ 添加 项目”中,选择 “新建项目...”。 系统将显示“ 添加新项目” 窗口。

15. 单击左侧面板上“ 已安装 ” 类别下的“工作流”。 系统将显示所有相关元素。

16. 选择“ 活动设计器 ”,然后单击“ 添加 ”以将该项目添加到项目中。



系统随即会添加“ 活动设计器 ”项目,并会立即打开相应的 .xaml 文件。 它应该如下所示:


17. 将现有的 活动设计器 代码替换为以下内容:

<sap:ActivityDesigner x:Class="MathSquareOfSum.MathSqSumDesigner"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:s="clr-namespace:System;assembly=mscorlib"
    xmlns:sap="clr-namespace:System.Activities.Presentation;assembly=System.Activities.Presentation"
    xmlns:sapc="clr-namespace:System.Activities.Presentation.Converters;assembly=System.Activities.Presentation"
    xmlns:sapv="clr-namespace:System.Activities.Presentation.View;assembly=System.Activities.Presentation">
    <a href="sap:ActivityDesigner.Resources">sap:ActivityDesigner.Resources</a>
        <ResourceDictionary>
            <sapc:ArgumentToExpressionConverter x:Key="ArgumentToExpressionConverter" />
        </ResourceDictionary>
    </sap:ActivityDesigner.Resources>
    <DockPanel Width="300">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="90"></ColumnDefinition>
                <ColumnDefinition Width="210"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <TextBlock Grid.Row="0" Grid.Column="0" Text="First Number"></TextBlock>
            <sapv:ExpressionTextBox Grid.Row="0" Grid.Column="1"  OwnerActivity="{Binding Path=ModelItem}" ExpressionType="s:Int32" HintText="Enter first number" Expression="{Binding Path=ModelItem.FirstNumber, Converter={StaticResource ArgumentToExpressionConverter},ConverterParameter=In, Mode=TwoWay}" />
            <TextBlock Grid.Row="1" Grid.Column="0" Text="Second Number"></TextBlock>
            <sapv:ExpressionTextBox Grid.Row="1" Grid.Column="1"  OwnerActivity="{Binding Path=ModelItem}" ExpressionType="s:Int32" HintText="Enter second number" Expression="{Binding Path=ModelItem.SecondNumber, Converter={StaticResource ArgumentToExpressionConverter},ConverterParameter=In, Mode=TwoWay}" />
            <TextBlock Grid.Row="2" Grid.Column="0" Text="Result"></TextBlock>
            <sapv:ExpressionTextBox Grid.Row="2" Grid.Column="1"  OwnerActivity="{Binding Path=ModelItem}" ExpressionType="s:Int32" HintText="The sum of the numbers" UseLocationExpression="True" Expression="{Binding Path=ModelItem.ResultNumber, Converter={StaticResource ArgumentToExpressionConverter},ConverterParameter=Out, Mode=TwoWay}" />
        </Grid>
    </DockPanel>
</sap:ActivityDesigner><sap:ActivityDesigner x:Class="MathSquareOfSum.MathSqSumDesigner"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:s="clr-namespace:System;assembly=mscorlib"
    xmlns:sap="clr-namespace:System.Activities.Presentation;assembly=System.Activities.Presentation"
    xmlns:sapc="clr-namespace:System.Activities.Presentation.Converters;assembly=System.Activities.Presentation"
    xmlns:sapv="clr-namespace:System.Activities.Presentation.View;assembly=System.Activities.Presentation">
    <a href="sap:ActivityDesigner.Resources">sap:ActivityDesigner.Resources</a>
        <ResourceDictionary>
            <sapc:ArgumentToExpressionConverter x:Key="ArgumentToExpressionConverter" />
        </ResourceDictionary>
    </sap:ActivityDesigner.Resources>
    <DockPanel Width="300">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="90"></ColumnDefinition>
                <ColumnDefinition Width="210"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <TextBlock Grid.Row="0" Grid.Column="0" Text="First Number"></TextBlock>
            <sapv:ExpressionTextBox Grid.Row="0" Grid.Column="1"  OwnerActivity="{Binding Path=ModelItem}" ExpressionType="s:Int32" HintText="Enter first number" Expression="{Binding Path=ModelItem.FirstNumber, Converter={StaticResource ArgumentToExpressionConverter},ConverterParameter=In, Mode=TwoWay}" />
            <TextBlock Grid.Row="1" Grid.Column="0" Text="Second Number"></TextBlock>
            <sapv:ExpressionTextBox Grid.Row="1" Grid.Column="1"  OwnerActivity="{Binding Path=ModelItem}" ExpressionType="s:Int32" HintText="Enter second number" Expression="{Binding Path=ModelItem.SecondNumber, Converter={StaticResource ArgumentToExpressionConverter},ConverterParameter=In, Mode=TwoWay}" />
            <TextBlock Grid.Row="2" Grid.Column="0" Text="Result"></TextBlock>
            <sapv:ExpressionTextBox Grid.Row="2" Grid.Column="1"  OwnerActivity="{Binding Path=ModelItem}" ExpressionType="s:Int32" HintText="The sum of the numbers" UseLocationExpression="True" Expression="{Binding Path=ModelItem.ResultNumber, Converter={StaticResource ArgumentToExpressionConverter},ConverterParameter=Out, Mode=TwoWay}" />
        </Grid>
    </DockPanel>
</sap:ActivityDesigner>

新定义的活动布局现在应如下所示:



18. 右键单击活动(在本例中 为 ActMathSquareOfSum),然后从“ 添加 ” 菜单中选择 “类...”。 系统将显示“ 添加新项目” 窗口。

19. 已选择“ ”项目。 现在只需将其重命名为 DesignerMetadata.cs ,然后单击“ 添加”。 新类现已添加到活动中,并在新选项卡中打开。


20. 在新创建的“ 设计器 元数据”类中添加以下内容:

using MathSquareOfSum;
using System.Activities.Presentation.Metadata;
using System.ComponentModel;
namespace ActMathSquareOfSum
{
    public class DesignerMetadata : IRegisterMetadata
    {
        public void Register()
        {
            AttributeTableBuilder attributeTableBuilder = new AttributeTableBuilder();
            attributeTableBuilder.AddCustomAttributes(typeof(MathSqSum), new DesignerAttribute(typeof(MathSqSumDesigner)));
            MetadataStore.AddAttributeTable(attributeTableBuilder.CreateTable());
        }
    }
}using MathSquareOfSum;
using System.Activities.Presentation.Metadata;
using System.ComponentModel;
namespace ActMathSquareOfSum
{
    public class DesignerMetadata : IRegisterMetadata
    {
        public void Register()
        {
            AttributeTableBuilder attributeTableBuilder = new AttributeTableBuilder();
            attributeTableBuilder.AddCustomAttributes(typeof(MathSqSum), new DesignerAttribute(typeof(MathSqSumDesigner)));
            MetadataStore.AddAttributeTable(attributeTableBuilder.CreateTable());
        }
    }
}

构建库

请务必在尝试构建项目之前测试项目是否存在错误。

从“ 构建 ”菜单中,选择“ 构建解决方案”。 MathSquareOfSum.dll 库现已构建并保存在以下位置:
%UserProfile%\source\repos\MathSquareOfSum\MathSquareOfSum\bin\Debug

构建库后,“ 输出 ”面板应显示如下所示的消息:



创建 NuGet 包

  1. 启动 NuGet 包资源管理器,然后单击 “新建包 (Ctrl + N)”。 系统将显示一个拆分窗口,其中显示 包元数据包内容。 我们需要在后一部分中添加所有依赖项。
  2. 在“ 包内容 ” 部分中右键单击。 系统将显示上下文菜单。
  3. 单击 “添加库文件夹” 请注意,系统会在“ 包内容 ”部分中创建一个新的库项目。


  4. 右键单击“ ”,然后选择“ 添加现有文件…”



  5. 加载上面创建的外部程序集 (.dll)。 在本例中, MathSquareOfSum.dll 文件位于 %UserProfile%\source\repos\MathSquareOfSum\MathSquareOfSum\bin\Debug 文件夹中。
  6. 选择文件后,访问“ 编辑 ”菜单,然后选择“ 编辑元数据”。 左侧面板现在配备了可编辑的元数据字段。


  7. 根据需要填写字段,以更好地描述自定义活动。
  8. 填写“ ID ” 字段。 在本例中,它可以是 UiPath.MathSquare.Activities,其中第一个值 UiPath代表创建包的团队。 如果未涉及特定团队,则可以将第一个值留空。



  9. 单击“ 包元数据 ”部分左上角的绿色复选标记按钮,以保存所有更改。
  10. 从“ 文件 ” 菜单中,选择“ 另存为...”。 系统将显示一个资源管理器窗口,允许您选择新文件的位置。
  11. 将文件保存在 UiPath 存储本地包的文件夹中(在 2021.4 之前的版本中为C:\Program Files (x86)\UiPath\Studio\Packages ,在版本 2021.4 及更高版本中为 C:\Program Files\UiPath\Studio\Packages )。 UiPath.MathSquare.Activities.1.0.0.nupkg 文件现已在包文件夹内的 UiPath.MathSquare.Activities 文件夹中创建。

在 Studio 中加载 NuGet 包

  1. 从 Studio 访问 包管理器
  2. 由于我们将 NuGet 包保存在本地包文件夹中,因此该活动应在 本地 订阅源中可用。


  3. 搜索活动,单击“ 安装 ”,然后单击“ 保存”。 新活动现已安装,可以在自动化项目中使用。

此页面是否有帮助?

获取您需要的帮助
了解 RPA - 自动化课程
UiPath Community 论坛
Uipath 白色徽标
信任与安全
© 2005-2024 UiPath. All rights reserved.