sdk
latest
false
Important :
Veuillez noter que ce contenu a été localisé en partie à l’aide de la traduction automatique. La localisation du contenu nouvellement publié peut prendre 1 à 2 semaines avant d’être disponible.
UiPath logo, featuring letters U and I in white

Guide du développeur

Dernière mise à jour 30 oct. 2025

Writing the code for a custom activity

Pour mieux comprendre comment écrire le code d'une activité personnalisée, nous allons créer une activité simple qui demande à l'utilisateur deux nombres, puis génère le carré de leur somme.
  1. Lancer Microsoft Visual Studio.
  2. Select File > New >Project… (shortcut: Ctrl + Shift + N). The New Project window is displayed.
  3. Sélectionnez C# dans le menu déroulant Langues . La liste de toutes les dépendances utilisant C# s'affiche.
  4. Select Class Library (.NET Framework). This helps us export the custom activity as a .dll file. Select Next to go to the Configure your new project window.


  5. Fill in the Project name field with the desired activity name. In our case, we can use "MathSquareOfSum".
  6. Sélectionnez .NET Framework 4.6.1 dans le menu déroulant Framework . Cela garantit que la bibliothèque est compatible avec UiPath Studio.
    Attention : dans les projets hérités depuis Windows, UiPath Studio prend en charge les activités créées avec .NET Framework 4.5.2 à 4.6.1. Pour plus d'informations sur la migration des activités vers .NET pour une utilisation dans des projets avec la compatibilité Windows, voir Migration des activités vers .NET 6.


  7. Select Create to go to the code designer and start writing the activity code.
  8. Dans le panneau Explorateur de solutions , cliquez avec le bouton droit sur la branche Références et sélectionnez Ajouter une référence... (Add Reference...). La fenêtre Gestionnaire de références ( Reference Manager) s'affiche.
  9. Recherchez les références System.Activities et System.ComponentModel.Composition et ajoutez-les. Assurez-vous de cocher la case devant chacun d'eux et cliquez sur OK. Cela nous permet d’utiliser les classes des références susmentionnées.




  10. Maintenant, nous devons nous assurer que notre code utilise les références nouvellement ajoutées. Cela se fait en ajoutant les lignes suivantes dans le concepteur de code :
    using System.Activities;
    using System.ComponentModel;using System.Activities;
    using System.ComponentModel;
    Notre projet devrait maintenant ressembler à ceci :


  11. Ajoutez les paramètres d'entrée et de sortie. Dans notre cas, le code devrait ressembler à ceci :
    //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)
            {
            }
    L'attribut <DisplayName(" ")> est le libellé qui s'affiche avant le champ de saisie dans le panneau Propriétés (Properties) de Studio. L'attribut <Description(" ")> est le texte de l'info-bulle affichée au survol de la souris.


    The <ReguiredArgument> attribute is needed if you want a declared element to be mandatory for input. If it is not filled in, a caution icon appears in the title bar of the activity.
  12. Add the functionality in the <Execute( )> overridden function. In our case, it looks like this:
    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);
    }

(Optional) Building a Designer Interface

Si vous ne souhaitez pas que votre activité ait une interface de concepteur, vous pouvez passer à la section construction de la bibliothèque.

Important :

Pour créer une interface de concepteur, le composant Windows Workflow Foundation doit être installé dans Visual Studio. Si vous n'avez pas sélectionné le composant dans le programme d'installation Visual Studio, vous pouvez l'ajouter comme suit :

  • Dans Visual Studio, cliquez sur le menu Outils et sélectionnez Obtenir les outils et fonctionnalités.... La fenêtre Visual Studio Installer s'affiche.
  • Basculez sur l'onglet Composants individuels ( Individual Components ) et recherchez le composant Windows Workflow Foundation . Il se trouve sous la section Activités de développement (Development activities ).
  • Cochez la case devant le composant Windows Workflow Foundation et cliquez sur Modifier ( Modify). Le composant requis est installé.


  1. Right-click the project from the Properties panel (in our case, the project is MathSquareOfSum). The context menu shows up.
  2. From the Add item, select New Item.... The Add New Item window is displayed.
  3. Select Workflow under the Installed category on the left panel. All related elements are displayed.
  4. Select Activity Designer and click Add to include the item in the project.


    L'élément Concepteur d'activités est ajouté et le fichier .xaml correspondant est immédiatement ouvert. Il devrait ressembler à ceci :


  5. Replace the existing Activity Designer code with the following:
    <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>
    La nouvelle mise en page définie pour l'activité devrait maintenant ressembler à ceci :


  6. Right-click the activity (in our case ActMathSquareOfSum), and from the Add menu, select Class.... The Add New Item window is displayed.
  7. The Class item is already selected. All that is needed now is to rename it to DesignerMetadata.cs, and select Add. The new class is now added to the activity and opens up in a new tab.


  8. Add the following content in the newly-created DesignerMetadata class:
    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());
            }
        }
    }
  • (Optional) Building a Designer Interface

Cette page vous a-t-elle été utile ?

Obtenez l'aide dont vous avez besoin
Formation RPA - Cours d'automatisation
Forum de la communauté UiPath
Uipath Logo
Confiance et sécurité
© 2005-2025 UiPath Tous droits réservés.