Jarvis.Toolkit
1.2.1.2
See the version list below for details.
dotnet add package Jarvis.Toolkit --version 1.2.1.2
NuGet\Install-Package Jarvis.Toolkit -Version 1.2.1.2
<PackageReference Include="Jarvis.Toolkit" Version="1.2.1.2" />
<PackageVersion Include="Jarvis.Toolkit" Version="1.2.1.2" />
<PackageReference Include="Jarvis.Toolkit" />
paket add Jarvis.Toolkit --version 1.2.1.2
#r "nuget: Jarvis.Toolkit, 1.2.1.2"
#:package Jarvis.Toolkit@1.2.1.2
#addin nuget:?package=Jarvis.Toolkit&version=1.2.1.2
#tool nuget:?package=Jarvis.Toolkit&version=1.2.1.2
Jarvis.Toolkit
Biblioteca de utilidades para .NET com extensões, validações, serviços HTTP, criptografia, autenticação, e-mail, notificações push e muito mais.
Instalação
dotnet add package Jarvis.Toolkit
Extensões
String
// Extrair conteúdo
"123.456.789-00".GetOnlyNumbers(); // "12345678900"
"abc123".GetOnlyLetters(); // "abc"
// Verificações
"texto".IsNullOrEmpty(); // false
"texto".NotNullOrEmptyOrWhiteSpace(); // true
// Capitalização
"hello world".FirstCharToUpper(); // "Hello world"
"hello world".AllFirstCharToUpper(); // "Hello World"
// Máscara
"12345678900".SetMask(MaskType.CPF); // "123.456.789-00"
"12345678".SetMask(MaskType.CEP); // "12345-678"
"1234567890".SetMask("(##) ####-####"); // "(12) 3456-7890"
// Remover acentos e caracteres especiais
"café".RemoveAccentuation(); // "cafe"
"a@b#c".RemoveSpecialCharacters(); // "abc"
// Truncar e nomes
"texto longo".Truncate(5); // "texto..."
"João Carlos Silva".GetFirstAndLastName(); // "João Silva"
// Valor padrão
string nulo = null;
nulo.IfNullOrEmpty("padrão"); // "padrão"
Data e Hora
// Validações
"25/12/2024".IsDate(); // true
"14:30".IsTime(); // true
// Conversões (formato brasileiro dd/MM/yyyy)
DateTime.Now.ToDate(); // "01/02/2026"
DateTime.Now.ToDateTime(); // "01/02/2026 14:30"
DateTime.Now.ToTime(); // "14:30"
"25/12/2024".ToDate(); // DateTime
// ISO
DateTime.Now.ToISODate(); // "2026-02-01"
DateTime.Now.ToISODateTime(); // "2026-02-01 14:30:00"
// Fuso horário Brasil
DateTime.UtcNow.ToDateTimeBr(); // converte UTC para horário de Brasília
DateTimeBr.Now; // DateTime agora em horário de Brasília
// Idade
new DateTime(1990, 5, 15).Age(); // 35
new DateTime(1990, 5, 15).AgeWithMonths(); // "35 anos e 8 meses"
// Dia da semana / Mês (pt-BR)
DateTime.Now.ToDay(); // "Sábado"
DateTime.Now.ToMonth(); // "Fevereiro"
// Verificações e limites
DateTime.Now.IsWeekend(); // true/false
DateTime.Now.FirstDayOfMonth();
DateTime.Now.LastDayOfMonth();
DateTime.Now.EndOfDay();
Objeto
object obj = null;
obj.IsNull(); // true
obj.NotNull(); // false
// Conversões
"123".ToInt(); // 123
"3.14".ToDouble(); // 3.14
"guid-string".ToGuid(); // Guid
"123".ToIntNullable(); // int?
// Condicionais
valor.If(condicao, novoValor);
condicao.IfElse(valorTrue, valorFalse);
item.IsNullOrNotEnabled(); // verifica propriedade "Ativo"
Número
(-5).IfNegative(0); // 0
(0).IfZero(1); // 1
(-5).IfNegativeOrZero(1); // 1
valor.MinValue(0); // não permite menor que 0
valor.MaxValue(100); // não permite maior que 100
valor.RangeValue(0, 100); // limita entre 0 e 100
Formatação (pt-BR)
1234.56.ToMoney(); // "R$ 1.234,56"
0.1575.ToPercent(); // "15,75%"
1234.56.ToNumber(); // "1.234,56"
// Converter de string formatada para número
"R$ 1.234,56".ToNumber<double>(); // 1234.56
"15,75%".ToNumber<double>(); // 15.75
Validação
"12345678900".IsCPF(); // true/false
"00038166000105".IsCNPJ(); // true/false
"12345678".IsCEP(); // true/false
"user@email.com".IsEmail(); // true/false
"11999887766".IsPhoneNumber(); // true/false
"12345678900".IsChavePix(); // true/false (CPF, CNPJ, email, telefone ou EVP)
Serialização JSON
// Serializar
var json = objeto.Serialize();
var json = objeto.Serialize(writeIndented: true);
// Deserializar
var obj = json.Deserialize<Produto>();
var obj = json.TryDeserialize<Produto>(); // retorna default em caso de erro
Mapeamento de Objetos
// Mapear propriedades por nome
var model = source.MapTo<TargetModel>();
// Com controle
var result = source.MapTo(target);
result.Set(x => x.Nome, s => s.FullName);
// Mapear lista
var result = sources.MapListTo(new TargetModel());
// Ignorar propriedades nulas
var result = source.MapToIgnoreNull(target);
// Atributos de controle
[MapIgnoreSource] // ignora ao mapear como target
[MapIgnoreTarget] // ignora ao mapear como source
Coleções e Listas
// Paginação
var pagina = lista.Page(pageNumber: 2, pageSize: 10);
var total = lista.TotalPages(pageSize: 10);
// Verificações
lista.IsNullOrEmpty();
lista.IsEmpty();
lista.EmptyIfNull(); // retorna vazio em vez de null
// Operações
lista.ForEach(x => x.Ativo = true);
lista.Randomize();
lista.Split(3); // divide em 3 grupos
lista.Partition(10); // divide em páginas de 10
lista.WithIndex(); // ForeachResult com Index, IsFirstItem, IsLastItem
// Filtros opcionais (ignora se valor é null)
lista.WhereOptional(x => x.Status, statusFiltro);
lista.InRange(x => x.Valor, min, max);
IQueryable
// Paginação (compatível com EF Core)
query.Page(pageNumber, pageSize);
query.TotalPages(pageSize);
// Filtros opcionais (ignora se valor é null)
query.WhereOptional(x => x.Status, statusFiltro);
query.InRange(x => x.Valor, min, max);
query.Contains(x => x.Nome, textoBusca);
Enum
myEnum.ToInt(); // 1
1.ToEnum<MeuEnum>(); // MeuEnum.Valor
"Valor".ToEnum<MeuEnum>(); // MeuEnum.Valor
// Display attribute
myEnum.GetName(); // [Display(Name = "...")]
myEnum.GetDescription(); // [Display(Description = "...")]
// Listar
Enum<MeuEnum>.AsEnumerable();
Enum<MeuEnum>.FilterExcluded(); // ignora itens com [Exclude]
Enum<MeuEnum>.ToGenericList();
Criptografia e Hash
// AES
var encrypted = "texto".AESEncrypt("chave16chars!!!");
var decrypted = encrypted.AESDecrypt("chave16chars!!!");
// SHA1 / MD5
var sha1 = "texto".SHA1Hash();
var md5 = "texto".MD5Hash();
// Base64
var base64 = "texto".ToBase64();
var original = base64.FromBase64();
// URL Slug
"Meu Título Aqui".ToUrlSlug(); // "meu-titulo-aqui"
// Ofuscar ID
Guid.NewGuid().ObfuscateId(); // string ofuscada
"ofuscado".DeobfuscateId(); // Guid original
JarvisUrlEncryptor
Gera tokens criptografados (AES-256) para URLs contendo um Guid, válidos somente para o dia informado. O token é URL-safe (Base64 com - e _).
var secret = "minha-chave-secreta";
// Gerar token válido somente para hoje
var token = JarvisUrlEncryptor.Encrypt(meuGuid, DateTime.Today, secret);
// Use na URL: /minha-rota?token=xxxx
// Descriptografar e validar (retorna null se o token for de outro dia ou inválido)
Guid? guid = JarvisUrlEncryptor.Decrypt(token, DateTime.Today, secret);
if (guid == null)
{
// Token inválido, expirado ou corrompido
}
HTML
"texto".Bold(); // <b>texto</b>
"texto".Italic(); // <i>texto</i>
"texto".Paragraph(); // <p>texto</p>
"texto".Link("https://..."); // <a href='https://...'>texto</a>
Claims
// Ler claims do ClaimsPrincipal
var id = User.Id();
var name = User.Name();
var roles = User.Roles();
var email = User.Email();
var isAuth = User.IsAuthenticated();
URI e Query String
var query = QueryItem.Object("nome", "João")
.AddObject("idade", 30)
.AddDate("data", DateTime.Now);
var url = query.ToUri("https://api.exemplo.com/buscar");
// https://api.exemplo.com/buscar?nome=Jo%c3%a3o&idade=30&data=2026-02-01
Atributos de Validação
[CPF(ErrorMessage = "CPF inválido")]
public string CPF { get; set; }
[CNPJ(ErrorMessage = "CNPJ inválido")]
public string CNPJ { get; set; }
[CPF_CNPJ(ErrorMessage = "Documento inválido")]
public string Documento { get; set; }
[CEP(ErrorMessage = "CEP inválido")]
public string CEP { get; set; }
[PhoneNumber(ErrorMessage = "Telefone inválido")]
public string Telefone { get; set; }
[ChavePix(ErrorMessage = "Chave PIX inválida")]
public string ChavePix { get; set; }
[MinValue(1, ErrorMessage = "Mínimo 1")]
public int Quantidade { get; set; }
[MaxValue(100, ErrorMessage = "Máximo 100")]
public int Porcentagem { get; set; }
[NotEmptyGuid(ErrorMessage = "Selecione um item")]
public Guid ItemId { get; set; }
[NotEmptyList(ErrorMessage = "Lista não pode ser vazia")]
public List<int> Itens { get; set; }
[RequiredList(ErrorMessage = "Lista obrigatória")]
public List<int> ItensObrigatorios { get; set; }
// Atributos de mapeamento
[MapIgnoreSource] // ignora propriedade na origem
[MapIgnoreTarget] // ignora propriedade no destino
// Atributo de enum
[Exclude] // exclui campo de listagens (FilterExcluded)
Modelos e Respostas
ModelResponse
// Resposta simples
return ModelResponse.Success("Operação realizada");
return ModelResponse.Error("Falha na operação");
// Resposta tipada
return ModelResponse<Produto>.Success(produto);
return ModelResponse<Produto>.Error("Não encontrado");
JsonResponse
return JsonResponse.Success(item, "Salvo com sucesso");
return JsonResponse.Error("Algo deu errado");
return JsonResponse.NotAuthenticated();
return JsonResponse.NotAuthorized();
return JsonResponse.Blocked();
// Deserializar item
var produto = response.Deserialize<Produto>();
HttpResponse
return HttpResponse<Produto>.Success(produto);
return HttpResponse<Produto>.Error("Falha");
return HttpResponse<Produto, ErroDTO>.Error(erroDto);
PaginationResponse
var paginacao = new PaginationResponse<Produto>
{
PageNumber = 1,
PageSize = 10,
TotalItems = 100,
Items = produtos
};
paginacao.TotalPages; // 10
paginacao.HasNextPage; // true
TokenResponse
var token = new TokenResponse
{
Token = "jwt...",
RefreshToken = "refresh...",
ExpiresToken = DateTime.UtcNow.AddHours(1)
};
token.IsValid; // true se não expirou
Ranges
// DateRange
var range = new DateRange("01/01/2024", "31/12/2024");
range.TotalDays; // 366
range.Dates; // lista de todos os dias
DateRange.Today;
DateRange.ThisMonth;
DateRange.ThisYear;
// TimeRange
var horario = new TimeRange("08:00", "17:00");
horario.TotalHours; // 9
// DateTimeRange
var periodo = new DateTimeRange("01/01/2024 08:00", "31/12/2024 17:00");
CPF e CNPJ (Classes)
CPF cpf = "12345678900";
cpf.Masked; // "123.456.789-00"
cpf.Unmasked; // "12345678900"
cpf.DV; // "00"
cpf.IsValid; // true/false
var novoCpf = CPF.Generate();
CNPJ cnpj = "00038166000105";
cnpj.Masked; // "00.038.166/0001-05"
cnpj.IsValid; // true/false
var novoCnpj = CNPJ.Generate();
GenericItem e GenericList
var item = new GenericItem<int>(1, "Opção 1");
var lista = new GenericList<int> { item };
var item2 = new GenericItem<int, Produto>(1, "Opção", produto);
CardModel
var card = new CardModel<int>
{
Id = 1,
Title = "Título",
Subtitle = "Subtítulo",
Description = "Descrição",
Image = "url"
};
Serviços
HTTP Client
var http = new JarvisHttpClient("https://api.exemplo.com");
// GET
var produto = await http.GetAsync<Produto>("/produtos/1");
var response = await http.GetJsonAsync<Produto>("/produtos/1");
// POST / PUT / DELETE
var response = await http.PostJsonAsync<Produto>("/produtos", novoProduto);
var response = await http.PutJsonAsync<Produto>("/produtos/1", produto);
var response = await http.DeleteJsonAsync<Produto>("/produtos/1");
// Download / Upload
var bytes = await http.DownloadAsync("/arquivo.pdf");
var result = await http.UploadAsync<FileResult>("/upload", fileBytes, "foto.jpg");
// Configurar headers
http.Client.BaseAddress("https://api.exemplo.com")
.BearerAuthorization(jwtToken)
.AddHeader("X-Custom", "valor");
Consulta CEP
var endereco = await ViaCEP.FindAsync("01001000");
var endereco = await OpenCEP.FindAsync("01001000");
var endereco = await AwesomeCEP.FindAsync("01001000");
// Busca por endereço (ViaCEP)
var resultados = await ViaCEP.FindAsync("SP", "São Paulo", "Paulista");
E-mail (SMTP)
var mail = new JarvisMailClient("smtp.gmail.com", 587, "user@gmail.com", "senha");
// Enviar e-mail
var result = await mail.SendAsync(
to: "destino@email.com",
subject: "Assunto",
body: "<p>Corpo HTML</p>"
);
// Template com placeholders
var template = new JarvisMailTemplate("<p>Olá {nome}!</p>");
template.Replace("{nome}", "João");
OneSignal (Push Notifications)
var onesignal = new JarvisOneSignalClient("app-id", "api-key");
// Enviar notificação
var body = new JarvisOneSignalBody
{
Title = "Título",
Message = "Mensagem",
Segments = new[] { JarvisOneSignalSegments.All }
};
var response = await onesignal.SendAsync(body);
Arquivo (File)
// Upload/download com progresso
var client = new JarvisFileClient();
client.ProgressChanged += (s, e) => Console.WriteLine($"{e.Percent}%");
client.Completed += (s, e) => Console.WriteLine("Concluído");
// Operações de arquivo
var result = JarvisFile.FromBase64(base64String, "foto.jpg");
var base64 = JarvisFile.ToBase64("caminho/arquivo.pdf");
Local Storage
var config = new JarvisLocalStorageConfiguration
{
FilePath = "C:/dados",
EnableEncryption = true,
EncryptionKey = "minha-chave-16!!"
};
using var storage = new JarvisLocalStorageClient(config);
storage.Store("chave", meuObjeto);
var obj = storage.Get<MeuTipo>("chave");
storage.Exists("chave"); // true
storage.Keys(); // lista de chaves
Autenticação
JarvisAuthenticationUser
var user = new JarvisAuthenticationUser("Cookies")
{
Id = "1",
Name = "João",
Email = "joao@email.com",
Roles = new List<string> { "Admin" }
};
user.SetItem(meuObjeto); // serializa objeto como claim Item
user.AddOther("custom_claim", "valor");
JarvisClaimTypes
JarvisClaimTypes.Id // claim de ID
JarvisClaimTypes.Name // claim de nome
JarvisClaimTypes.Email // claim de e-mail
JarvisClaimTypes.Role // claim de role
JarvisClaimTypes.ClientId // claim de client ID
JarvisClaimTypes.JwtName // "unique_name" (JWT)
JarvisClaimTypes.JwtRole // "role" (JWT)
JWT Options
var options = new JarvisJwtOptions
{
Issuer = "minha-app",
Audience = "minha-api",
SecretKey = "chave-secreta-32-chars!!!!!!!!!",
Expiration = TimeSpan.FromHours(1)
};
Utilitários
Gerador
var senha = JarvisGenerator.Password(8, PasswordType.Mixed);
var senhaDiaria = JarvisGenerator.DailyPassword(); // 6 dígitos baseado na data
var cpf = JarvisGenerator.CPF();
var cnpj = JarvisGenerator.CNPJ();
var texto = JarvisGenerator.LoremIpsum(100);
Password (PBKDF2/SHA256)
var hash = JarvisPassword.Hash("minha-senha");
var valido = JarvisPassword.Verify("minha-senha", hash); // true
Haversine (Distância Geográfica)
var km = JarvisHaversine.ToKilometers(lat1, lng1, lat2, lng2);
var metros = JarvisHaversine.ToMeters(coord1, coord2);
var milhas = JarvisHaversine.ToMiles(coord1, coord2);
Timer
var elapsed = JarvisTimer.Elapsed(() => MinhaOperacao());
var ms = JarvisTimer.ElapsedMilliseconds(() => MinhaOperacao());
var ms = await JarvisTimer.ElapsedMilliseconds(async () => await MinhaOperacaoAsync());
Log
JarvisLog.Debug("mensagem");
JarvisLog.Info("mensagem");
JarvisLog.Warn("mensagem");
JarvisLog.Error("mensagem");
JarvisLog.Exception(ex);
Matemática
JarvisMath.Percent(10, 100); // 10.0 (10%)
JarvisMath.CalculatePercentage(200, 15); // 30.0 (15% de 200)
JarvisMath.AddPercentage(100, 10); // 110.0
JarvisMath.SubtractPercentage(100, 10); // 90.0
Cor
JarvisColor.Combine("#FF0000", "#0000FF"); // combina cores pela média RGB
JarvisColor.HexToRgb("#FF5500"); // "255, 85, 0"
JarvisColor.HexToRgba("#FF5500", 0.5); // "255, 85, 0, 0.5"
Conversões de Unidade
JarvisConverter.MmToPixels(10, 96); // milímetros para pixels
JarvisConverter.PixelsToMm(100, 96); // pixels para milímetros
Diretórios e Arquivos (Helper)
JarvisDirectoryHelper.CreateIfNotExists("C:/minha-pasta");
JarvisDirectoryHelper.GetOrCreate("dados", "C:/base");
JarvisDirectoryHelper.GetOrCreateHidden("dados-ocultos");
JarvisFileHelper.SetHiddenAttribute("C:/arquivo.txt", true);
Estados e Meses (Brasil)
EstadosBrasil.Lista(); // dicionário "SP" => "São Paulo"
EstadosBrasil.Siglas(); // ["AC", "AL", ..., "TO"]
EstadosBrasil.Nomes(); // ["Acre", "Alagoas", ..., "Tocantins"]
MesesAno.Lista(); // ["Janeiro", ..., "Dezembro"]
Structs
// Meses do ano
var meses = new Months(2024);
meses.January; // 01/01/2024
meses.December; // 01/12/2024
// DateTime Brasil
DateTimeBr.Now; // agora em horário de Brasília
DateTimeBr.Today; // hoje em horário de Brasília
// Enum tipado
var valores = Enum<MeuEnum>.AsEnumerable();
Converters JSON
// Converters para System.Text.Json
var options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringDateConverter()); // "yyyy-MM-dd"
options.Converters.Add(new JsonStringDateTimeConverter()); // "yyyy-MM-dd HH:mm:ss"
options.Converters.Add(new JsonStringDoubleConverter()); // aceita string ou número
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 is compatible. net5.0-windows was computed. net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 is compatible. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.1 is compatible. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.1
- System.ComponentModel.Annotations (>= 5.0.0)
- System.Drawing.Common (>= 10.0.5)
- System.Net.Http.Json (>= 10.0.5)
-
net10.0
- No dependencies.
-
net5.0
- No dependencies.
-
net6.0
- No dependencies.
-
net7.0
- No dependencies.
-
net8.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages (9)
Showing the top 5 NuGet packages that depend on Jarvis.Toolkit:
| Package | Downloads |
|---|---|
|
Jarvis.Blazor
Biblioteca de componentes para Blazor. |
|
|
Jarvis.Components.Web.Mvc.Core
Biblioteca de componentes para WEB MVC Core. |
|
|
Jarvis.Maui
Biblioteca de componentes para Maui. |
|
|
Jarvis.WebApi
Biblioteca de componentes para API Web. |
|
|
Jarvis.Blazor.Mud
Biblioteca de componentes para MudBlazor. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.2.1.3 | 59 | 3/25/2026 |
| 1.2.1.2 | 155 | 3/16/2026 |
| 1.2.1.1 | 105 | 3/8/2026 |
| 1.2.1 | 122 | 3/8/2026 |
| 1.2.0.9 | 113 | 3/4/2026 |
| 1.2.0.8 | 91 | 3/2/2026 |
| 1.2.0.7 | 97 | 2/27/2026 |
| 1.2.0.6 | 259 | 2/3/2026 |
| 1.2.0.5 | 120 | 2/1/2026 |
| 1.2.0.4 | 182 | 1/28/2026 |
| 1.2.0.3 | 117 | 1/21/2026 |
| 1.2.0.2 | 156 | 1/8/2026 |
| 1.2.0.1 | 339 | 11/28/2025 |
| 1.2.0 | 286 | 11/24/2025 |
| 1.1.9.9 | 223 | 11/24/2025 |
| 1.1.9.8 | 220 | 11/15/2025 |
| 1.1.9.7 | 352 | 11/13/2025 |
| 1.1.9.6 | 235 | 10/18/2025 |
| 1.1.9.5 | 343 | 9/4/2025 |
| 1.1.9.4 | 294 | 8/28/2025 |