AYUDA .NET

Octokit .NET (Cómo funciona para desarrolladores)

Actualizado julio 1, 2024
Compartir:

Primeros pasos con Octokit.NET

Configuración de Octokit.NET en proyectos .NET

Para empezar a utilizar Octokit.NET en sus proyectos, primero debe instalar el paquete. Puede añadirlo a través de NuGet, que es el método más sencillo. En Visual Studio, puede utilizar el gestor de paquetes NuGet. Busca Octokit e instálalo en tu proyecto.

Un ejemplo de código básico: Acceso a la información de usuario de GitHub

He aquí un sencillo ejemplo de cómo utilizar Octokit.NET para recuperar información sobre un usuario de GitHub. Este ejemplo asume que usted ya ha configurado su proyecto con Octokit.NET.

using Octokit;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Create a new instance of the GitHubClient class
        var client = new GitHubClient(new ProductHeaderValue("YourAppName"));
        // Retrieve user information
        var user = await client.User.Get("octocat");
        // Output the user's name
        Console.WriteLine("User Name: " + user.Name);
    }
}
using Octokit;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Create a new instance of the GitHubClient class
        var client = new GitHubClient(new ProductHeaderValue("YourAppName"));
        // Retrieve user information
        var user = await client.User.Get("octocat");
        // Output the user's name
        Console.WriteLine("User Name: " + user.Name);
    }
}
Imports Octokit
Imports System
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' Create a new instance of the GitHubClient class
		Dim client = New GitHubClient(New ProductHeaderValue("YourAppName"))
		' Retrieve user information
		Dim user = Await client.User.Get("octocat")
		' Output the user's name
		Console.WriteLine("User Name: " & user.Name)
	End Function
End Class
VB   C#

Este fragmento de código crea un nuevo cliente de GitHub y recupera información para un usuario específico, octocat, por su nombre de repositorio. A continuación, imprime el nombre del usuario en la consola. Demuestra el acceso autenticado a la API de GitHub, utilizando el nombre de usuario del usuario, y también puede acceder a repositorios públicos sin autenticación.

Características de Octokit.NET

Búsqueda en repositorios

Puedes buscar repositorios de GitHub por criterios utilizando Octokit.NET. A continuación se explica cómo realizar una búsqueda:

using Octokit;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var client = new GitHubClient(new ProductHeaderValue("YourAppName"));
        var searchRepositoriesRequest = new SearchRepositoriesRequest("machine learning")
        {
            Language = Language.CSharp
        };
        var result = await client.Search.SearchRepo(searchRepositoriesRequest);
        foreach (var repo in result.Items)
        {
            Console.WriteLine(repo.FullName);
        }
    }
}
using Octokit;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var client = new GitHubClient(new ProductHeaderValue("YourAppName"));
        var searchRepositoriesRequest = new SearchRepositoriesRequest("machine learning")
        {
            Language = Language.CSharp
        };
        var result = await client.Search.SearchRepo(searchRepositoriesRequest);
        foreach (var repo in result.Items)
        {
            Console.WriteLine(repo.FullName);
        }
    }
}
Imports Octokit
Imports System
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		Dim client = New GitHubClient(New ProductHeaderValue("YourAppName"))
		Dim searchRepositoriesRequest As New SearchRepositoriesRequest("machine learning") With {.Language = Language.CSharp}
		Dim result = Await client.Search.SearchRepo(searchRepositoriesRequest)
		For Each repo In result.Items
			Console.WriteLine(repo.FullName)
		Next repo
	End Function
End Class
VB   C#

Este código busca repositorios relacionados con el "aprendizaje automático" escritos en C#. Muestra los nombres completos de los repositorios.

Gestión de repositorios bifurcados

Para gestionar repositorios bifurcados, puede listar y crear bifurcaciones. He aquí cómo listar las bifurcaciones de un repositorio:

using Octokit;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var client = new GitHubClient(new ProductHeaderValue("YourAppName"));
        var forks = await client.Repository.Forks.GetAll("octocat", "Hello-World");
        foreach (var fork in forks)
        {
            Console.WriteLine("Fork ID: " + fork.Id + " - Owner: " + fork.Owner.Login);
        }
    }
}
using Octokit;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var client = new GitHubClient(new ProductHeaderValue("YourAppName"));
        var forks = await client.Repository.Forks.GetAll("octocat", "Hello-World");
        foreach (var fork in forks)
        {
            Console.WriteLine("Fork ID: " + fork.Id + " - Owner: " + fork.Owner.Login);
        }
    }
}
Imports Octokit
Imports System
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		Dim client = New GitHubClient(New ProductHeaderValue("YourAppName"))
		Dim forks = Await client.Repository.Forks.GetAll("octocat", "Hello-World")
		For Each fork In forks
			Console.WriteLine("Fork ID: " & fork.Id & " - Owner: " & fork.Owner.Login)
		Next fork
	End Function
End Class
VB   C#

Este ejemplo lista todas las bifurcaciones del repositorio "Hola-Mundo" propiedad de octocat.

Límites de la tasa de manipulación

Comprender y manejar los límites de velocidad es crucial cuando se interactúa con la API de GitHub. Octokit.NET proporciona herramientas para comprobar sus límites de tarifa:

using Octokit;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var client = new GitHubClient(new ProductHeaderValue("YourAppName"));
        var rateLimit = await client.Miscellaneous.GetRateLimits();
        Console.WriteLine("Core Limit: " + rateLimit.Resources.Core.Limit);
    }
}
using Octokit;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var client = new GitHubClient(new ProductHeaderValue("YourAppName"));
        var rateLimit = await client.Miscellaneous.GetRateLimits();
        Console.WriteLine("Core Limit: " + rateLimit.Resources.Core.Limit);
    }
}
Imports Octokit
Imports System
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		Dim client = New GitHubClient(New ProductHeaderValue("YourAppName"))
		Dim rateLimit = Await client.Miscellaneous.GetRateLimits()
		Console.WriteLine("Core Limit: " & rateLimit.Resources.Core.Limit)
	End Function
End Class
VB   C#

Este fragmento de código comprueba y muestra el límite principal de uso de tu API de GitHub, ayudándote a gestionar las solicitudes sin superar los límites de velocidad.

Soporte de extensiones reactivas

Octokit.NET admite extensiones reactivas (Rx) para la programación reactiva. He aquí un ejemplo básico:

using Octokit.Reactive;
using System;

var client = new ObservableGitHubClient(new ProductHeaderValue("YourAppName"));
var subscription = client.User.Get("octocat").Subscribe(
    user => Console.WriteLine("User Name: " + user.Name),
    error => Console.WriteLine("Error: " + error.Message)
);
// Unsubscribe when done
subscription.Dispose();
using Octokit.Reactive;
using System;

var client = new ObservableGitHubClient(new ProductHeaderValue("YourAppName"));
var subscription = client.User.Get("octocat").Subscribe(
    user => Console.WriteLine("User Name: " + user.Name),
    error => Console.WriteLine("Error: " + error.Message)
);
// Unsubscribe when done
subscription.Dispose();
Imports Octokit.Reactive
Imports System

Private client = New ObservableGitHubClient(New ProductHeaderValue("YourAppName"))
Private subscription = client.User.Get("octocat").Subscribe(Sub(user) Console.WriteLine("User Name: " & user.Name), Sub([error]) Console.WriteLine("Error: " & [error].Message))
' Unsubscribe when done
subscription.Dispose()
VB   C#

Este ejemplo muestra cómo recuperar información de usuario de forma asíncrona y gestionarla de forma reactiva.

Trabajar con etiquetas

Para trabajar con etiquetas Git a través de Octokit.NET, puede recuperar etiquetas de un repositorio:

using Octokit;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var client = new GitHubClient(new ProductHeaderValue("YourAppName"));
        var tags = await client.Repository.GetAllTags("octocat", "Hello-World");
        foreach (var tag in tags)
        {
            Console.WriteLine("Tag Name: " + tag.Name);
        }
    }
}
using Octokit;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var client = new GitHubClient(new ProductHeaderValue("YourAppName"));
        var tags = await client.Repository.GetAllTags("octocat", "Hello-World");
        foreach (var tag in tags)
        {
            Console.WriteLine("Tag Name: " + tag.Name);
        }
    }
}
Imports Octokit
Imports System
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		Dim client = New GitHubClient(New ProductHeaderValue("YourAppName"))
		Dim tags = Await client.Repository.GetAllTags("octocat", "Hello-World")
		For Each tag In tags
			Console.WriteLine("Tag Name: " & tag.Name)
		Next tag
	End Function
End Class
VB   C#

Este código lista todas las etiquetas del repositorio "Hola-Mundo" propiedad de octocat.

Integración de Octokit.NET con IronPDF

Octokit .NET (Cómo funciona para desarrolladores): Figura 1 - IronPDF

IronPDF es una conocida biblioteca .NET que permite a los desarrolladores crear, manipular y representar archivos PDF directamente en aplicaciones C# y .NET. Es una potente herramienta para generar informes PDF a partir de HTML, facturas o cualquier documento que necesite un formato de maquetación fijo. Cuando se combina con Octokit.NET, que interactúa con la API de GitHub, el potencial de automatización de los procesos de documentación, especialmente los que implican repositorios de código, aumenta significativamente.

Caso práctico de fusión de IronPDF con Octokit.NET

Un caso práctico de integración de IronPDF con Octokit.NET es la generación automática de un informe en PDF de la documentación de un proyecto almacenada en un repositorio de GitHub. Por ejemplo, puede recuperar todos los archivos markdown de un repositorio específico, convertirlos en un documento PDF y, a continuación, distribuir este documento entre las partes interesadas o los clientes que puedan preferir una versión compilada de la documentación o las notas de la versión.

Ejemplo de código del caso de uso

Vamos a crear una aplicación sencilla que demuestre esta integración. La aplicación realizará las siguientes tareas:

  1. Autentícate y conéctate a GitHub utilizando Octokit.NET.
  2. Obtener archivos de un repositorio especificado.
  3. Convierta estos archivos de Markdown a PDF utilizando IronPDF.
  4. Guarde el PDF en el equipo local.

    Así es como se podría escribir esto en C#:

using Octokit;
using IronPdf;
using System;
using System.Threading.Tasks;
using System.Linq;

class Program
{
    static async Task Main(string[] args)
    {
        // GitHub client setup
        var client = new GitHubClient(new ProductHeaderValue("YourAppName"));
        var tokenAuth = new Credentials("your_github_token"); // Replace with your GitHub token
        client.Credentials = tokenAuth;
        // Repository details
        var owner = "repository_owner";
        var repo = "repository_name";
        // Fetch repository content
        var contents = await client.Repository.Content.GetAllContents(owner, repo);
        // Initialize the PDF builder
        var pdf = new ChromePdfRenderer();
        // Convert each markdown file to PDF
        foreach (var content in contents.Where(c => c.Name.EndsWith(".md")))
        {
            pdf.RenderHtmlAsPdf(content.Content).SaveAs($"{content.Name}.pdf");
            Console.WriteLine($"Created PDF for: {content.Name}");
        }
    }
}
using Octokit;
using IronPdf;
using System;
using System.Threading.Tasks;
using System.Linq;

class Program
{
    static async Task Main(string[] args)
    {
        // GitHub client setup
        var client = new GitHubClient(new ProductHeaderValue("YourAppName"));
        var tokenAuth = new Credentials("your_github_token"); // Replace with your GitHub token
        client.Credentials = tokenAuth;
        // Repository details
        var owner = "repository_owner";
        var repo = "repository_name";
        // Fetch repository content
        var contents = await client.Repository.Content.GetAllContents(owner, repo);
        // Initialize the PDF builder
        var pdf = new ChromePdfRenderer();
        // Convert each markdown file to PDF
        foreach (var content in contents.Where(c => c.Name.EndsWith(".md")))
        {
            pdf.RenderHtmlAsPdf(content.Content).SaveAs($"{content.Name}.pdf");
            Console.WriteLine($"Created PDF for: {content.Name}");
        }
    }
}
Imports Octokit
Imports IronPdf
Imports System
Imports System.Threading.Tasks
Imports System.Linq

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' GitHub client setup
		Dim client = New GitHubClient(New ProductHeaderValue("YourAppName"))
		Dim tokenAuth = New Credentials("your_github_token") ' Replace with your GitHub token
		client.Credentials = tokenAuth
		' Repository details
		Dim owner = "repository_owner"
		Dim repo = "repository_name"
		' Fetch repository content
		Dim contents = Await client.Repository.Content.GetAllContents(owner, repo)
		' Initialize the PDF builder
		Dim pdf = New ChromePdfRenderer()
		' Convert each markdown file to PDF
		For Each content In contents.Where(Function(c) c.Name.EndsWith(".md"))
			pdf.RenderHtmlAsPdf(content.Content).SaveAs($"{content.Name}.pdf")
			Console.WriteLine($"Created PDF for: {content.Name}")
		Next content
	End Function
End Class
VB   C#

En este ejemplo, tras configurar el cliente de GitHub y especificar tus credenciales, obtienes contenido de un repositorio. Para cada archivo markdown del repositorio, IronPDF convierte el contenido en un archivo PDF, que luego se guarda localmente. Este sencillo pero eficaz flujo de trabajo puede ampliarse para incluir filtros más complejos, formateo o incluso procesamiento por lotes de archivos para repositorios más grandes.

Conclusión

Octokit .NET (Cómo funciona para los desarrolladores): Figura 2 - Licencias

La integración de Octokit.NET con IronPDF ofrece un enfoque perfecto para automatizar y agilizar los flujos de trabajo de documentos dentro de sus proyectos de GitHub. Aprovechando estas herramientas, puede mejorar la eficacia del tratamiento de la documentación, haciéndola fácilmente accesible en formatos que satisfagan diversas necesidades profesionales. IronPDF, en particular, proporciona una plataforma sólida para la manipulación de PDF, y vale la pena señalar que ofrecen pruebas gratuitas para empezar. Si decide implantarlo en su proyecto, las licencias empiezan a partir de 749 dólares.

< ANTERIOR
Mathnet.Numerics C# (Cómo funciona para desarrolladores)
SIGUIENTE >
Specflow C# (Cómo funciona para desarrolladores)

¿Listo para empezar? Versión: 2024.9 acaba de salir

Descarga gratuita de NuGet Descargas totales: 10,516,730 View Licenses >