SDK
Mais recente
falso
Imagem de fundo do banner
Guia do desenvolvedor
Última atualização 23 de mar de 2024

Como criar as configurações de projeto de atividades

Usando o pacote UiPath.Activities.API do feed oficial (https://pkgs.dev.azure.com/uipath/Public.Feeds/_packaging/UiPath-Official/nuget/v3/index.json), você pode criar e adicionar suas próprias configurações de projeto de atividades personalizadas no Studio. Para obter informações sobre como usar a API, consulte Studio Activities SDK.
Observação: o pacote UiPath.Activities.API deve ser usado como uma dependência de desenvolvimento no seu projeto personalizado. Leia mais sobre Dependências de desenvolvimento.

As configurações do projeto de atividades abrangem um conjunto de opções que podem ser ajustadas globalmente para o projeto diretamente da janela Configurações do Projeto.



Criar Configurações de Atividade

O exemplo a seguir cria uma série de configurações para uma atividade de reprodutor de música.

Adicionar a Guia e Seção

using UiPath.Studio.Activities.Api;
using UiPath.Studio.Activities.Api.Settings;
namespace MyCustomActivityPack
{
    public static class SettingsCreator
    {
        // This is the key used to reference a tab, even across packages.
        internal const string CategoryKey = "DemoTabUniqueKey";
        // This is the key used to reference the setting, even across packages.
        internal const string CommentTextKey = CategoryKey + ".Comment";
        internal const string PresetKey = CategoryKey + ".Preset";
        internal const string ShuffleKey = CategoryKey + ".Shuffle";
        public static void CreateSettings(IWorkflowDesignApi workflowDesignApi)
        {
            var settingsApi = workflowDesignApi.Settings;
            // Add the category (a tab in the settings page)
            var category = new SettingsCategory()
            {
                Description = "Settings Sample",
                Header = "Settings Sample",
                Key = CategoryKey
            };
            settingsApi.AddCategory(category);
            AddMusicPlayerSection(settingsApi, category);
            AddMiscSettings(settingsApi, category);using UiPath.Studio.Activities.Api;
using UiPath.Studio.Activities.Api.Settings;
namespace MyCustomActivityPack
{
    public static class SettingsCreator
    {
        // This is the key used to reference a tab, even across packages.
        internal const string CategoryKey = "DemoTabUniqueKey";
        // This is the key used to reference the setting, even across packages.
        internal const string CommentTextKey = CategoryKey + ".Comment";
        internal const string PresetKey = CategoryKey + ".Preset";
        internal const string ShuffleKey = CategoryKey + ".Shuffle";
        public static void CreateSettings(IWorkflowDesignApi workflowDesignApi)
        {
            var settingsApi = workflowDesignApi.Settings;
            // Add the category (a tab in the settings page)
            var category = new SettingsCategory()
            {
                Description = "Settings Sample",
                Header = "Settings Sample",
                Key = CategoryKey
            };
            settingsApi.AddCategory(category);
            AddMusicPlayerSection(settingsApi, category);
            AddMiscSettings(settingsApi, category);

Isso adiciona uma guia e seção à janela Configurações do Projeto de Atividades. A descrição da guia fica visível ao passar o mouse sobre a ferramenta de dicas da guia:



Adicionar Configurações

  • Seção de configurações expansível:

    private static SettingsSection AddMusicPlayerSection(IActivitiesSettingsService settingsApi, SettingsCategory category)
            {
                var section = new SettingsSection()
                {
                    Description = "Settings for a music player",
                    IsExpanded = true, //set this to control default expansion
                    Title = "Music Player Settings",
                    // the key of a section has to be unique only within the category
                    Key = "Player"
                };
                settingsApi.AddSection(category, section);
                AddSimpleBoolean(settingsApi, section);
                AddSingleChoice(settingsApi, section);
                return section;
            }private static SettingsSection AddMusicPlayerSection(IActivitiesSettingsService settingsApi, SettingsCategory category)
            {
                var section = new SettingsSection()
                {
                    Description = "Settings for a music player",
                    IsExpanded = true, //set this to control default expansion
                    Title = "Music Player Settings",
                    // the key of a section has to be unique only within the category
                    Key = "Player"
                };
                settingsApi.AddSection(category, section);
                AddSimpleBoolean(settingsApi, section);
                AddSingleChoice(settingsApi, section);
                return section;
            }

Isso resulta em:



  • Botão Seletor para valores booleanos:

    private static void AddSimpleBoolean(IActivitiesSettingsService settingsApi, SettingsSection section)
            {
                var booleanSetting = new SingleValueEditorDescription<bool>
                {
                    DefaultValue = true,
                    Description = "If active, the playlist is shuffled",
                    // The value returned by GetDisplayValue should be localized
                    GetDisplayValue = b => b ? "On" : "Off",
                    Key = ShuffleKey,
                    Label = "Shuffle"
                };
                settingsApi.AddSetting(section, booleanSetting);
            }private static void AddSimpleBoolean(IActivitiesSettingsService settingsApi, SettingsSection section)
            {
                var booleanSetting = new SingleValueEditorDescription<bool>
                {
                    DefaultValue = true,
                    Description = "If active, the playlist is shuffled",
                    // The value returned by GetDisplayValue should be localized
                    GetDisplayValue = b => b ? "On" : "Off",
                    Key = ShuffleKey,
                    Label = "Shuffle"
                };
                settingsApi.AddSetting(section, booleanSetting);
            }

Isso resulta em:



  • Lista de valores de múltipla escolha:

    private static void AddSingleChoice(IActivitiesSettingsService settingsApi, SettingsSection category)
            {
                var booleanSetting = new SingleValueSelectorDescription
                {
                    DefaultValue = "pop",
                    Values = new[] { "classic", "pop", "rock" },
                    Description = "Sample single choice setting",
                    // The value returned by GetDisplayValue should be localized
                    GetDisplayValue = choice => choice + " music",
                    Key = PresetKey,
                    Label = "Mixer Preset"
                };
                settingsApi.AddSetting(category, booleanSetting);
            }private static void AddSingleChoice(IActivitiesSettingsService settingsApi, SettingsSection category)
            {
                var booleanSetting = new SingleValueSelectorDescription
                {
                    DefaultValue = "pop",
                    Values = new[] { "classic", "pop", "rock" },
                    Description = "Sample single choice setting",
                    // The value returned by GetDisplayValue should be localized
                    GetDisplayValue = choice => choice + " music",
                    Key = PresetKey,
                    Label = "Mixer Preset"
                };
                settingsApi.AddSetting(category, booleanSetting);
            }

Isso resulta em:



  • Campo de entrada de texto com validação:

    private static void AddSimpleString(IActivitiesSettingsService settingsApi, SettingsSection section)
            {
                var simpleStringSetting = new SingleValueEditorDescription<string>()
                {
                    Description = "A free text comment that can't contain the word 'invalid'",
                    // The GetDisplayValue obtains a localized screen representation of the underlying setting value.
                    GetDisplayValue = LocalizeSimpleSettingValue,
                    IsReadOnly = false,
                    DefaultValue = "There is no comment",
                    Label = "Comment",
                    Validate = ValidateSimpleStringSetting,
                    Key = CommentTextKey
                };
                // Add the setting to the section.
                // A setting may also be directly added on a category. It will appear as a setting without a section (top level setting)
                settingsApi.AddSetting(section, simpleStringSetting);
            }
    private static string LocalizeSimpleSettingValue(string s) => $"A localized value of <code>{s}</code>";
    private static string ValidateSimpleStringSetting(string arg)
            {
                if (arg?.ToLowerInvariant().Contains("invalid") == true)
                {
                    return "The sample string setting is invalid if it contains the <code>invalid</code> keyword";
                }
                return string.Empty;
            }private static void AddSimpleString(IActivitiesSettingsService settingsApi, SettingsSection section)
            {
                var simpleStringSetting = new SingleValueEditorDescription<string>()
                {
                    Description = "A free text comment that can't contain the word 'invalid'",
                    // The GetDisplayValue obtains a localized screen representation of the underlying setting value.
                    GetDisplayValue = LocalizeSimpleSettingValue,
                    IsReadOnly = false,
                    DefaultValue = "There is no comment",
                    Label = "Comment",
                    Validate = ValidateSimpleStringSetting,
                    Key = CommentTextKey
                };
                // Add the setting to the section.
                // A setting may also be directly added on a category. It will appear as a setting without a section (top level setting)
                settingsApi.AddSetting(section, simpleStringSetting);
            }
    private static string LocalizeSimpleSettingValue(string s) => $"A localized value of <code>{s}</code>";
    private static string ValidateSimpleStringSetting(string arg)
            {
                if (arg?.ToLowerInvariant().Contains("invalid") == true)
                {
                    return "The sample string setting is invalid if it contains the <code>invalid</code> keyword";
                }
                return string.Empty;
            }

Isso resulta em:



Obter ID de Processo e Logs

Usando métodos aplicados à IExecutorRuntimereferência , você pode obter informações sobre a ID do processo que está sendo executado pelo Robô, além dos logs de execução. Os seguintes métodos podem ser usados:
  • IRunningJobInformation- Coleta informações sobre o processo que está sendo executado e suporta as seguintes propriedades:
    • JobID- Recupera a ID do processo
    • ProcessName - recupera o nome do processo
    • ProcessVersion- Recupera a versão do processo
    • WorkflowFilePath- Recupera o caminho completo do processo
    • InitiatedBy- Recupera a fonte de uma Tarefa (Robô, Studio, Orchestrator, etc)
    • FolderId - Recupera o ID da pasta do processo
    • FolderName - recupera o nome da pasta do processo
    • TenantId - Recupera a ID do tenant
    • TenantKey - Recupera a chave do tenant
    • TenantName - Recupera o nome do tenant
    • RobotName - recupera o nome do robô
    • LicenseType - Recupera o tipo de licença do robô
    • RuntimeGovernanceEnabled - Fornece informações se a governança de Runtime está habilitada ou não
    • InternalArguments - Recupera quaisquer argumentos internos do processo
    • OrganizationId - Recupera a ID da organização
    • PictureInPictureMode - recupera o tipo de Picture no modo Picture usado. Os seguintes valores estão disponíveis:
      • Main - o processo é executado na sessão principal do Windows
      • PictureInPictureSession - o processo é executado na sessão do PiP
      • PictureInPictureDesktop - o processo é executado no modo de área de trabalho virtual do PiP
    • LogMessage - Gera logs de execução do Robot de acordo com um Nível de log que você especificar. Leia mais sobre logs nesta página. As seguintes propriedades são compatíveis:
    • EventType- o nível de registro a recuperar
    • Message- a mensagem a ser exibida
O seguinte código exemplifica o uso do métodoLogMessage:
public class MyLogMessageActivity : CodeActivity
{
    protected override void Execute(CodeActivityContext context)
    {
        var executorRuntime = context.GetExtension<IExecutorRuntime>();
        var jobInfo = executorRuntime.RunningJobInformation;
        executorRuntime.LogMessage(new LogMessage
        {
            EventType = TraceEventType.Warning,
            Message = $"Job {jobInfo.JobId}: My log message from workflow {jobInfo.WorkflowFilePath}"
        });
    }
}public class MyLogMessageActivity : CodeActivity
{
    protected override void Execute(CodeActivityContext context)
    {
        var executorRuntime = context.GetExtension<IExecutorRuntime>();
        var jobInfo = executorRuntime.RunningJobInformation;
        executorRuntime.LogMessage(new LogMessage
        {
            EventType = TraceEventType.Warning,
            Message = $"Job {jobInfo.JobId}: My log message from workflow {jobInfo.WorkflowFilePath}"
        });
    }
}

Adicionar o Projeto ao Studio

Para tornar as configurações visíveis no Studio na janela Configurações do Projeto de Atividades, é necessário publicar suas atividades personalizadas em um pacote NuGet e disponibilizá-lo em um feed definido no Studio, versão 2019.10.1 ou superior.

Criar o Pacote NuGet



  1. Inicie o Explorador de Pacotes NuGet.
  2. Clique em Criar um novo pacote (Ctrl + N). Uma janela bipartida será exibida com os metadados do pacote e o conteúdo do pacote. Precisamos adicionar todas as dependências na seção final.
  3. Clique com o botão direito do mouse na seção Conteúdo do Pacote. O menu de contexto é exibido.
  4. Clique em Adicionar pasta lib. Observe que um novo item lib será criado na seção Conteúdo do Pacote.
  5. Clique com o botão direito do mouse em lib e selecione Adicionar Arquivo Existente....
  6. Carregue o assembly externo (.dll) do seu projeto.
  7. Clique em Editar > Editar Metadados. A seção Metadados do Pacote será exibida.
  8. Preencha os campos conforme prefira para melhor descrever seu projeto.
  9. Preencha o campo Id e certifique-se de incluir a palavra-chave "Atividades" para que o pacote possa ser exibido na janela Gerenciar Pacotes no Studio.
  10. Click File > Save. In our case, the .nupkg file is created.
    Note: Be sure to create an intuitive folder structure for your activities. All empty folders inside the custom activity get removed when used with Orchestrator.

Instalar o Pacote NuGet no UiPath Studio

Após o arquivo .nupkg ser criado, adicione-o a um feed personalizado no Studio, conforme explicado aqui.

Abra a janela Gerenciar Pacotes e instale o pacote. Certifique-se de que o feed personalizado está habilitado no Studio.

Exemplo de configurações

Em conjunto, a guia, seção e configurações criadas acima estarão visíveis na janela Configurações do Projeto de Atividades:



Basta seguir o link abaixo para baixar o exemplo, que também contém um exemplo de Criação de assistentes personalizados.

Was this page helpful?

Obtenha a ajuda que você precisa
Aprendendo RPA - Cursos de automação
Fórum da comunidade da Uipath
Logotipo branco da Uipath
Confiança e segurança
© 2005-2024 UiPath. All rights reserved.