elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [SOURCE-CODE] Obtener releases de GitHub y comprobar actualizaciones...
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [SOURCE-CODE] Obtener releases de GitHub y comprobar actualizaciones...  (Leído 3,296 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
[SOURCE-CODE] Obtener releases de GitHub y comprobar actualizaciones...
« en: 6 Mayo 2018, 02:43 am »

Estuve observando este código aleatorio en GitHub: https://github.com/HearthSim/HDT-Voice/blob/master/HDT-Voice/HDTPlugin/Github.vb y a raíz de eso se me ocurrió la idea de implementar un sistema reutilizable y sofisticado (o al menos yo creo que lo es) para obtener las releases de GitHub, con lo que poder determinar si existe una nueva release y por ende nuestro programa debe actualizarse...

Para comenzar la implementación de dicho sistema declaré las siguientes clases: GitHubRelease, GitHubAsset y GitHubAuthor las cuales servirán para representar información de una release, un asset y un author/uploader. Y por último declaré una clase con nombre GitHubUtil en donde declaré varias funciones sincrónicas y asincrónicas para implementar las siguientes funcionalidades: obtener todas las releases de un repositorio, obtener la última release, obtener una release con versión específica, y comprobar si existe una versión más reciente (para actualizar nuestro programa).

Estoy seguro que les servirá para sus aplicaciones de código abierto y le podrán sacar varias utilidades con diferentes fines que se ajusten a sus necesidades...

Aquí lo tienen todo:

Código
  1. Imports System
  2. Imports System.Collections.Generic
  3. Imports System.Collections.ObjectModel
  4. Imports System.Collections.Specialized
  5. Imports System.ComponentModel
  6. Imports System.IO
  7. Imports System.Net
  8. Imports System.Net.Mime
  9. Imports System.Runtime.Serialization.Json
  10. Imports System.Text
  11. Imports System.Threading
  12. Imports System.Threading.Tasks
  13. Imports System.Web
  14. Imports System.Xml

GitHubRelease.vb
Código
  1. ''' <summary>
  2. ''' Represents a release on GitHub.
  3. ''' </summary>
  4. ''' <seealso href="https://github.com"/>
  5. Public NotInheritable Class GitHubRelease
  6.  
  7.    ''' <summary>
  8.    ''' Gets the GitHub's unique identifier for this release.
  9.    ''' </summary>
  10.    Public ReadOnly Property Id As String
  11.  
  12.    ''' <summary>
  13.    ''' Gets the release name.
  14.    ''' </summary>
  15.    Public ReadOnly Property Name As String
  16.  
  17.    ''' <summary>
  18.    ''' Gets the release tag name.
  19.    ''' </summary>
  20.    Public ReadOnly Property TagName As String
  21.  
  22.    ''' ----------------------------------------------------------------------------------------------------
  23.    ''' <summary>
  24.    ''' Gets the release version.
  25.    ''' </summary>
  26.    ''' ----------------------------------------------------------------------------------------------------
  27.    ''' <remarks>
  28.    ''' The version is derived from <see cref="GitHubRelease.TagName"/>, which should follow semantic versioning guidelines.
  29.    ''' <para></para>
  30.    ''' See for more info about semantic versioning:
  31.    ''' <para></para>
  32.    ''' <see href="https://semver.org/"/>
  33.    ''' <para></para>
  34.    ''' <see href="https://help.github.com/articles/about-releases/"/>
  35.    ''' <para></para>
  36.    ''' <see href="https://git-scm.com/book/en/v2/Git-Basics-Tagging"/>
  37.    ''' </remarks>
  38.    ''' ----------------------------------------------------------------------------------------------------
  39.    Public ReadOnly Property Version As Version
  40.        Get
  41.            ' Remove prefixes and suffixes from tagname, like: "v1.0", "1.0-alpha" or "1.0-beta".
  42.            Dim str As String = Me.TagName.ToLower().
  43.                                           Trim("abcdefghijklmnopqrstuvwxyz !·$%&/()=?\|@#~'^*¨;:,.{}[]+".ToArray())
  44.  
  45.            Dim result As Version = Nothing
  46.            Version.TryParse(str, result)
  47.            Return result
  48.        End Get
  49.    End Property
  50.  
  51.    ''' <summary>
  52.    ''' Gets the body, in MarkDown format.
  53.    ''' </summary>
  54.    Public ReadOnly Property Body As String
  55.  
  56.    ''' <summary>
  57.    ''' Gets the commition target.
  58.    ''' </summary>
  59.    Public ReadOnly Property TargetCommitish As String
  60.  
  61.    ''' <summary>
  62.    ''' Gets an <see cref="Uri"/> that points to the release page.
  63.    ''' </summary>
  64.    Public ReadOnly Property UriRelease As Uri
  65.  
  66.    ''' <summary>
  67.    ''' Gets an <see cref="Uri"/> that points to the assets page of this release.
  68.    ''' </summary>
  69.    Public ReadOnly Property UriAssets As Uri
  70.  
  71.    ''' <summary>
  72.    ''' Gets an <see cref="Uri"/> that points to the tarball of this release.
  73.    ''' </summary>
  74.    Public ReadOnly Property UriTarball As Uri
  75.  
  76.    ''' <summary>
  77.    ''' Gets an <see cref="Uri"/> that points to the zipball of this release.
  78.    ''' </summary>
  79.    Public ReadOnly Property UriZipball As Uri
  80.  
  81.    ''' <summary>
  82.    ''' Gets an <see cref="Uri"/> that points to the release page for a web-browser.
  83.    ''' </summary>
  84.    Public ReadOnly Property UriHtml As Uri
  85.  
  86.    ''' <summary>
  87.    ''' Gets a value that determine whether this release is a draft.
  88.    ''' </summary>
  89.    Public ReadOnly Property IsDraft As Boolean
  90.  
  91.    ''' <summary>
  92.    ''' Gets a value that determine whether this release is a pre-release.
  93.    ''' </summary>
  94.    Public ReadOnly Property IsPreRelease As Boolean
  95.  
  96.    ''' <summary>
  97.    ''' Gets the creation datetime.
  98.    ''' </summary>
  99.    Public ReadOnly Property DateCreated As Date
  100.  
  101.    ''' <summary>
  102.    ''' Gets the published datetime.
  103.    ''' </summary>
  104.    Public ReadOnly Property DatePublished As Date
  105.  
  106.    ''' <summary>
  107.    ''' Gets the author of this release.
  108.    ''' </summary>
  109.    Public ReadOnly Property Author As GitHubAuthor
  110.  
  111.    ''' <summary>
  112.    ''' Gets the assets of this release.
  113.    ''' </summary>
  114.    Public ReadOnly Property Assets As ReadOnlyCollection(Of GitHubAsset)
  115.  
  116.    ''' <summary>
  117.    ''' Prevents a default instance of the <see cref="GitHubRelease"/> class from being created.
  118.    ''' </summary>
  119.    Private Sub New()
  120.    End Sub
  121.  
  122.    ''' <summary>
  123.    ''' Initializes a new instance of the <see cref="GitHubRelease"/> class.
  124.    ''' </summary>
  125.    ''' <param name="xml">
  126.    ''' An <see cref="XElement"/> that contains the fields to parse.
  127.    ''' <para></para>
  128.    ''' See: <see href="https://api.github.com/repos/{user}/{repo}/releases"/>
  129.    ''' </param>
  130.    Public Sub New(ByVal xml As XElement)
  131.        Me.Id = xml.<id>.Value
  132.        Me.Name = xml.<name>.Value
  133.        Me.TagName = xml.<tag_name>.Value
  134.        Me.Body = xml.<body>.Value
  135.        Me.TargetCommitish = xml.<target_commitish>.Value
  136.        Me.UriRelease = New Uri(xml.<url>.Value, UriKind.Absolute)
  137.        Me.UriAssets = New Uri(xml.<assets_url>.Value, UriKind.Absolute)
  138.        Me.UriHtml = New Uri(xml.<html_url>.Value, UriKind.Absolute)
  139.        Me.UriTarball = New Uri(xml.<tarball_url>.Value, UriKind.Absolute)
  140.        Me.UriZipball = New Uri(xml.<zipball_url>.Value, UriKind.Absolute)
  141.        Me.IsDraft = xml.<draft>.Value
  142.        Me.IsPreRelease = xml.<prerelease>.Value
  143.        Me.DateCreated = Date.Parse(xml.<created_at>.Value, CultureInfo.GetCultureInfo("en-US").DateTimeFormat)
  144.        Me.DatePublished = Date.Parse(xml.<published_at>.Value, CultureInfo.GetCultureInfo("en-US").DateTimeFormat)
  145.        Me.Author = New GitHubAuthor(xml.<author>.SingleOrDefault())
  146.  
  147.        Dim assets As New Collection(Of GitHubAsset)
  148.        Dim elements As IEnumerable(Of XElement) = xml.<assets>.<item>
  149.        For Each element As XElement In elements
  150.            Dim asset As New GitHubAsset(element)
  151.            assets.Add(asset)
  152.        Next
  153.        Me.Assets = New ReadOnlyCollection(Of GitHubAsset)(assets)
  154.    End Sub
  155.  
  156.    ''' <summary>
  157.    ''' Returns a <see cref="String"/> that represents this release.
  158.    ''' </summary>
  159.    ''' <returns>
  160.    ''' A <see cref="String"/> that represents this release.
  161.    ''' </returns>
  162.    Public Overrides Function ToString() As String
  163.        Dim kvPairs As New NameValueCollection(EqualityComparer(Of String).Default) From {
  164.            {NameOf(Me.Id), Me.Id},
  165.            {NameOf(Me.TagName), Me.TagName},
  166.            {NameOf(Me.Name), Me.Name},
  167.            {NameOf(Me.TargetCommitish), Me.TargetCommitish},
  168.            {NameOf(Me.IsDraft), Me.IsDraft},
  169.            {NameOf(Me.IsPreRelease), Me.IsPreRelease},
  170.            {NameOf(Me.DateCreated), Me.DateCreated.ToString("MM/dd/yyyy HH:mm:ss")},
  171.            {NameOf(Me.DatePublished), Me.DatePublished.ToString("MM/dd/yyyy HH:mm:ss")},
  172.            {NameOf(Me.UriHtml), Me.UriHtml.AbsoluteUri}
  173.        }
  174.  
  175.        Return String.Format("{{{0}}}", String.Join(", ", (From key In kvPairs.AllKeys, value In kvPairs.GetValues(key)
  176.                                                           Select String.Format("{0}={1}", key, value))))
  177.    End Function
  178.  
  179.    ''' <summary>
  180.    ''' Implements the operator &lt;&gt;.
  181.    ''' </summary>
  182.    ''' <param name="release1">
  183.    ''' The first <see cref="GitHubRelease"/>.
  184.    ''' </param>
  185.    ''' <param name="release2">
  186.    ''' The second <see cref="GitHubRelease"/>.
  187.    ''' </param>
  188.    ''' <returns>
  189.    ''' The result of the operator.
  190.    ''' </returns>
  191.    Public Shared Operator <>(ByVal release1 As GitHubRelease, ByVal release2 As GitHubRelease) As Boolean
  192.  
  193.        Return (release1.Id <> release2.Id)
  194.  
  195.    End Operator
  196.  
  197.    ''' <summary>
  198.    ''' Implements the operator =.
  199.    ''' </summary>
  200.    ''' <param name="release1">
  201.    ''' The first <see cref="GitHubRelease"/>.
  202.    ''' </param>
  203.    ''' <param name="release2">
  204.    ''' The second <see cref="GitHubRelease"/>.
  205.    ''' </param>
  206.    ''' <returns>
  207.    ''' The result of the operator.
  208.    ''' </returns>
  209.    Public Shared Operator =(ByVal release1 As GitHubRelease, ByVal release2 As GitHubRelease) As Boolean
  210.  
  211.        Return (release1.Id = release2.Id)
  212.  
  213.    End Operator
  214.  
  215. End Class

GitHubAsset.vb
Código
  1. ''' <summary>
  2. ''' Represents an asset of a release on GitHub.
  3. ''' </summary>
  4. ''' <seealso href="https://github.com"/>
  5. Public NotInheritable Class GitHubAsset
  6.  
  7.    ''' <summary>
  8.    ''' Gets the GitHub's unique identifier for this asset.
  9.    ''' </summary>
  10.    Public ReadOnly Property Id As String
  11.  
  12.    ''' <summary>
  13.    ''' Gets the name of this asset.
  14.    ''' </summary>
  15.    Public ReadOnly Property Name As String
  16.  
  17.    ''' <summary>
  18.    ''' Gets the label of this asset.
  19.    ''' </summary>
  20.    Public ReadOnly Property Label As String
  21.  
  22.    ''' <summary>
  23.    ''' Gets the state of this asset.
  24.    ''' </summary>
  25.    Public ReadOnly Property State As String
  26.  
  27.    ''' <summary>
  28.    ''' Gets the size of this asset, in bytes.
  29.    ''' </summary>
  30.    Public ReadOnly Property Size As Long
  31.  
  32.    ''' <summary>
  33.    ''' Gets a value indicating how many times this asset was downloaded.
  34.    ''' </summary>
  35.    Public ReadOnly Property DownloadCount As Integer
  36.  
  37.    ''' <summary>
  38.    ''' Gets the content-type of this asset.
  39.    ''' </summary>
  40.    Public ReadOnly Property ContentType As ContentType
  41.  
  42.    ''' <summary>
  43.    ''' Gets an <see cref="Uri"/> that points to the page of this asset.
  44.    ''' </summary>
  45.    Public ReadOnly Property UriAsset As Uri
  46.  
  47.    ''' <summary>
  48.    ''' Gets an <see cref="Uri"/> that points to the download page of this asset.
  49.    ''' </summary>
  50.    Public ReadOnly Property UriDownload As Uri
  51.  
  52.    ''' <summary>
  53.    ''' Gets the creation datetime.
  54.    ''' </summary>
  55.    Public ReadOnly Property DateCreated As Date
  56.  
  57.    ''' <summary>
  58.    ''' Gets the uploaded datetime.
  59.    ''' </summary>
  60.    Public ReadOnly Property DateUploaded As Date
  61.  
  62.    ''' <summary>
  63.    ''' Gets the uploader of this asset.
  64.    ''' </summary>
  65.    Public ReadOnly Property Uploader As GitHubAuthor
  66.  
  67.    ''' <summary>
  68.    ''' Prevents a default instance of the <see cref="GitHubAsset"/> class from being created.
  69.    ''' </summary>
  70.    Private Sub New()
  71.    End Sub
  72.  
  73.    ''' <summary>
  74.    ''' Initializes a new instance of the <see cref="GitHubAsset"/> class.
  75.    ''' </summary>
  76.    ''' <param name="xml">
  77.    ''' An <see cref="XElement"/> that contains the fields to parse.
  78.    ''' <para></para>
  79.    ''' See: <see href="https://api.github.com/repos/{user}/{repo}/releases"/>
  80.    ''' </param>
  81.    Public Sub New(ByVal xml As XElement)
  82.        Me.Id = xml.<id>.Value
  83.        Me.Name = xml.<name>.Value
  84.        Me.Label = xml.<label>.Value
  85.        Me.State = xml.<state>.Value
  86.        Me.Size = xml.<size>.Value
  87.        Me.ContentType = New ContentType(xml.<content_type>.Value)
  88.        Me.DownloadCount = xml.<download_count>.Value
  89.        Me.DateCreated = Date.Parse(xml.<created_at>.Value, CultureInfo.GetCultureInfo("en-US").DateTimeFormat)
  90.        Me.DateUploaded = Date.Parse(xml.<updated_at>.Value, CultureInfo.GetCultureInfo("en-US").DateTimeFormat)
  91.        Me.UriAsset = New Uri(xml.<url>.Value, UriKind.Absolute)
  92.        Me.UriDownload = New Uri(xml.<browser_download_url>.Value, UriKind.Absolute)
  93.        Me.Uploader = New GitHubAuthor(xml.<uploader>.Single())
  94.    End Sub
  95.  
  96.    ''' <summary>
  97.    ''' Returns a <see cref="String"/> that represents this asset.
  98.    ''' </summary>
  99.    ''' <returns>
  100.    ''' A <see cref="String"/> that represents this asset.
  101.    ''' </returns>
  102.    Public Overrides Function ToString() As String
  103.        Dim kvPairs As New NameValueCollection(EqualityComparer(Of String).Default) From {
  104.            {NameOf(Me.Id), Me.Id},
  105.            {NameOf(Me.Name), Me.Name},
  106.            {NameOf(Me.Label), Me.Label},
  107.            {NameOf(Me.State), Me.State},
  108.            {NameOf(Me.Size), Me.Size},
  109.            {NameOf(Me.ContentType), Me.ContentType.ToString()},
  110.            {NameOf(Me.DownloadCount), Me.DownloadCount},
  111.            {NameOf(Me.DateCreated), Me.DateCreated.ToString("MM/dd/yyyy HH:mm:ss")},
  112.            {NameOf(Me.DateUploaded), Me.DateUploaded.ToString("MM/dd/yyyy HH:mm:ss")},
  113.            {NameOf(Me.UriDownload), Me.UriDownload.AbsoluteUri}
  114.        }
  115.  
  116.        Return String.Format("{{{0}}}", String.Join(", ", (From key In kvPairs.AllKeys, value In kvPairs.GetValues(key)
  117.                                                           Select String.Format("{0}={1}", key, value))))
  118.    End Function
  119.  
  120.    ''' <summary>
  121.    ''' Implements the operator &lt;&gt;.
  122.    ''' </summary>
  123.    ''' <param name="asset1">
  124.    ''' The first <see cref="GitHubAsset"/>.
  125.    ''' </param>
  126.    ''' <param name="asset2">
  127.    ''' The second <see cref="GitHubAsset"/>.
  128.    ''' </param>
  129.    ''' <returns>
  130.    ''' The result of the operator.
  131.    ''' </returns>
  132.    Public Shared Operator <>(ByVal asset1 As GitHubAsset, ByVal asset2 As GitHubAsset) As Boolean
  133.  
  134.        Return (asset1.Id <> asset2.Id)
  135.  
  136.    End Operator
  137.  
  138.    ''' <summary>
  139.    ''' Implements the operator =.
  140.    ''' </summary>
  141.    ''' <param name="asset1">
  142.    ''' The first <see cref="GitHubAsset"/>.
  143.    ''' </param>
  144.    ''' <param name="asset2">
  145.    ''' The second <see cref="GitHubAsset"/>.
  146.    ''' </param>
  147.    ''' <returns>
  148.    ''' The result of the operator.
  149.    ''' </returns>
  150.    Public Shared Operator =(ByVal asset1 As GitHubAsset, ByVal asset2 As GitHubAsset) As Boolean
  151.  
  152.        Return (asset1.Id = asset2.Id)
  153.  
  154.    End Operator
  155.  
  156. End Class

GitHubAuthor.vb
Código
  1. ''' <summary>
  2. ''' Represents the author of a release or the uploader of an asset on GitHub.
  3. ''' </summary>
  4. ''' <seealso href="https://github.com"/>
  5. Public NotInheritable Class GitHubAuthor
  6.  
  7.    ''' <summary>
  8.    ''' Gets the GitHub's unique identifier for this author.
  9.    ''' </summary>
  10.    Public ReadOnly Property Id As String
  11.  
  12.    ''' <summary>
  13.    ''' Gets the author name.
  14.    ''' </summary>
  15.    Public ReadOnly Property Name As String
  16.  
  17.    ''' <summary>
  18.    ''' Gets the type of user.
  19.    ''' </summary>
  20.    Public ReadOnly Property [Type] As String
  21.  
  22.    ''' <summary>
  23.    ''' Gets a value that determine whether this author is a site administrator.
  24.    ''' </summary>
  25.    Public ReadOnly Property IsSiteAdministrator As Boolean
  26.  
  27.    ''' <summary>
  28.    ''' Gets the unique identifier of the Gravatar.
  29.    ''' <para></para>
  30.    ''' See for more info: <see href="https://gravatar.com/"/>
  31.    ''' </summary>
  32.    Public ReadOnly Property GravatarId As String
  33.  
  34.    ''' <summary>
  35.    ''' Gets an <see cref="Uri"/> that points to the author page.
  36.    ''' </summary>
  37.    Public ReadOnly Property UriAuthor As Uri
  38.  
  39.    ''' <summary>
  40.    ''' Gets an <see cref="Uri"/> that points to the avatar page of this author.
  41.    ''' </summary>
  42.    Public ReadOnly Property UriAvatar As Uri
  43.  
  44.    ''' <summary>
  45.    ''' Gets an <see cref="Uri"/> that points to the followers page of this author.
  46.    ''' </summary>
  47.    Public ReadOnly Property UriFollowers As Uri
  48.  
  49.    ''' <summary>
  50.    ''' Gets an <see cref="Uri"/> that points to the subscriptions page of this author.
  51.    ''' </summary>
  52.    Public ReadOnly Property UriSubscriptions As Uri
  53.  
  54.    ''' <summary>
  55.    ''' Gets an <see cref="Uri"/> that points to the organizations page of this author.
  56.    ''' </summary>
  57.    Public ReadOnly Property UriOrganizations As Uri
  58.  
  59.    ''' <summary>
  60.    ''' Gets an <see cref="Uri"/> that points to the repositories page of this author.
  61.    ''' </summary>
  62.    Public ReadOnly Property UriRepositories As Uri
  63.  
  64.    ''' <summary>
  65.    ''' Gets an <see cref="Uri"/> that points to the received events page of this author.
  66.    ''' </summary>
  67.    Public ReadOnly Property UriReceivedEvents As Uri
  68.  
  69.    ''' <summary>
  70.    ''' Gets an <see cref="Uri"/> that points to the author page for a web-browser.
  71.    ''' </summary>
  72.    Public ReadOnly Property UriHtml As Uri
  73.  
  74.    ''' <summary>
  75.    ''' Prevents a default instance of the <see cref="GitHubAuthor"/> class from being created.
  76.    ''' </summary>
  77.    Private Sub New()
  78.    End Sub
  79.  
  80.    ''' <summary>
  81.    ''' Initializes a new instance of the <see cref="GitHubAuthor"/> class.
  82.    ''' </summary>
  83.    ''' <param name="xml">
  84.    ''' An <see cref="XElement"/> that contains the fields to parse.
  85.    ''' <para></para>
  86.    ''' See: <see href="https://api.github.com/repos/{user}/{repo}/releases"/>
  87.    ''' </param>
  88.    Public Sub New(ByVal xml As XElement)
  89.        Me.Id = xml.<id>.Value
  90.        Me.Name = xml.<login>.Value
  91.        Me.Type = xml.<type>.Value
  92.        Me.IsSiteAdministrator = xml.<site_admin>.Value
  93.        Me.GravatarId = xml.<gravatar_id>.Value
  94.        Me.UriAuthor = New Uri(xml.<url>.Value, UriKind.Absolute)
  95.        Me.UriAvatar = New Uri(xml.<avatar_url>.Value, UriKind.Absolute)
  96.        Me.UriSubscriptions = New Uri(xml.<subscriptions_url>.Value, UriKind.Absolute)
  97.        Me.UriOrganizations = New Uri(xml.<organizations_url>.Value, UriKind.Absolute)
  98.        Me.UriRepositories = New Uri(xml.<repos_url>.Value, UriKind.Absolute)
  99.        Me.UriReceivedEvents = New Uri(xml.<received_events_url>.Value, UriKind.Absolute)
  100.        Me.UriHtml = New Uri(xml.<html_url>.Value, UriKind.Absolute)
  101.    End Sub
  102.  
  103.    ''' <summary>
  104.    ''' Returns a <see cref="String"/> that represents this author.
  105.    ''' </summary>
  106.    ''' <returns>
  107.    ''' A <see cref="String"/> that represents this author.
  108.    ''' </returns>
  109.    Public Overrides Function ToString() As String
  110.        Dim kvPairs As New NameValueCollection(EqualityComparer(Of String).Default) From {
  111.            {NameOf(Me.Id), Me.Id},
  112.            {NameOf(Me.Name), Me.Name},
  113.            {NameOf(Me.Type), Me.Type},
  114.            {NameOf(Me.IsSiteAdministrator), Me.IsSiteAdministrator},
  115.            {NameOf(Me.UriHtml), Me.UriHtml.AbsoluteUri}
  116.        }
  117.  
  118.        Return String.Format("{{{0}}}", String.Join(", ", (From key In kvPairs.AllKeys, value In kvPairs.GetValues(key)
  119.                                                           Select String.Format("{0}={1}", key, value))))
  120.    End Function
  121.  
  122.    ''' <summary>
  123.    ''' Implements the operator &lt;&gt;.
  124.    ''' </summary>
  125.    ''' <param name="author1">
  126.    ''' The first <see cref="GitHubAuthor"/>.
  127.    ''' </param>
  128.    ''' <param name="author2">
  129.    ''' The second <see cref="GitHubAuthor"/>.
  130.    ''' </param>
  131.    ''' <returns>
  132.    ''' The result of the operator.
  133.    ''' </returns>
  134.    Public Shared Operator <>(ByVal author1 As GitHubAuthor, ByVal author2 As GitHubAuthor) As Boolean
  135.  
  136.        Return (author1.Id <> author2.Id)
  137.  
  138.    End Operator
  139.  
  140.    ''' <summary>
  141.    ''' Implements the operator =.
  142.    ''' </summary>
  143.    ''' <param name="author1">
  144.    ''' The first <see cref="GitHubAuthor"/>.
  145.    ''' </param>
  146.    ''' <param name="author2">
  147.    ''' The second <see cref="GitHubAuthor"/>.
  148.    ''' </param>
  149.    ''' <returns>
  150.    ''' The result of the operator.
  151.    ''' </returns>
  152.    Public Shared Operator =(ByVal author1 As GitHubAuthor, ByVal author2 As GitHubAuthor) As Boolean
  153.  
  154.        Return (author1.Id = author2.Id)
  155.  
  156.    End Operator
  157.  
  158. End Class

GitHubUtil.vb
Código
  1. Public NotInheritable Class GitHubUtil
  2.  
  3. #Region " Constructors "
  4.  
  5.    ''' <summary>
  6.    ''' Prevents a default instance of the <see cref="GitHubUtil"/> class from being created.
  7.    ''' </summary>
  8.    Private Sub New()
  9.    End Sub
  10.  
  11. #End Region
  12.  
  13. #Region " Public Methods "
  14.  
  15.    ''' <summary>
  16.    ''' Asynchronously gets the releases from the specified repository on GitHub.
  17.    ''' </summary>
  18.    ''' <param name="userName">
  19.    ''' The user name.
  20.    ''' </param>
  21.    ''' <param name="repositoryName">
  22.    ''' The repository name.
  23.    ''' </param>
  24.    ''' <returns>
  25.    ''' A <see cref="Task(Of ReadOnlyCollection(Of GitHubRelease))"/> containing the releases.
  26.    ''' </returns>
  27.    ''' <exception cref="HttpException">
  28.    ''' JSON validation error.
  29.    ''' </exception>
  30.    Public Shared Async Function GetReleasesAsync(ByVal userName As String, ByVal repositoryName As String) As Task(Of ReadOnlyCollection(Of GitHubRelease))
  31.  
  32.        Dim uri As New Uri(String.Format("https://api.github.com/repos/{0}/{1}/releases", userName, repositoryName), UriKind.Absolute)
  33.  
  34.        Dim request As HttpWebRequest =  DirectCast(WebRequest.Create(uri), HttpWebRequest)
  35.        request.UserAgent = userName
  36.  
  37.        Using response As WebResponse = Await request.GetResponseAsync(),
  38.              sr As New StreamReader(response.GetResponseStream()),
  39.              xmlReader As XmlDictionaryReader = JsonReaderWriterFactory.CreateJsonReader(sr.BaseStream, Encoding.UTF8, New XmlDictionaryReaderQuotas, Nothing)
  40.  
  41.            Dim xml As XElement = XElement.Load(xmlReader)
  42.            If (xml.IsEmpty) Then
  43.                Dim errMsg As String = String.Format("JSON validation error. ""{0}""", uri.ToString())
  44.                Throw New HttpException(HttpStatusCode.NotFound, errMsg)
  45.            End If
  46.  
  47.            Dim releases As New Collection(Of GitHubRelease)
  48.            Dim elements As IEnumerable(Of XElement) = xml.<item>
  49.            For Each element As XElement In elements
  50.                Dim release As New GitHubRelease(element)
  51.                releases.Add(release)
  52.            Next
  53.  
  54.            Return New ReadOnlyCollection(Of GitHubRelease)(releases)
  55.  
  56.        End Using
  57.  
  58.    End Function
  59.  
  60.    ''' <summary>
  61.    ''' Gets the releases from the specified repository on GitHub.
  62.    ''' </summary>
  63.    ''' <param name="userName">
  64.    ''' The user name.
  65.    ''' </param>
  66.    ''' <param name="repositoryName">
  67.    ''' The repository name.
  68.    ''' </param>
  69.    ''' <returns>
  70.    ''' A <see cref="ReadOnlyCollection(Of GitHubRelease)"/> collection containing the releases.
  71.    ''' </returns>
  72.    Public Shared Function GetReleases(ByVal userName As String, ByVal repositoryName As String) As ReadOnlyCollection(Of GitHubRelease)
  73.  
  74.        Dim t As Task(Of ReadOnlyCollection(Of GitHubRelease)) = Task.Run(Function() GitHubUtil.GetReleases(userName, repositoryName))
  75.        t.Wait(Timeout.Infinite)
  76.  
  77.        Return t.Result
  78.  
  79.    End Function
  80.  
  81.    ''' <summary>
  82.    ''' Asynchronously gets a release that matches the specified version from the specified repository on GitHub.
  83.    ''' </summary>
  84.    ''' <param name="userName">
  85.    ''' The user name.
  86.    ''' </param>
  87.    ''' <param name="repositoryName">
  88.    ''' The repository name.
  89.    ''' </param>
  90.    ''' <param name="version">
  91.    ''' The version of the release.
  92.    ''' </param>
  93.    ''' <returns>
  94.    ''' The resulting <see cref="GitHubRelease"/>.
  95.    ''' </returns>
  96.    Public Shared Async Function GetReleaseAsync(ByVal userName As String, ByVal repositoryName As String, ByVal version As Version) As Task(Of GitHubRelease)
  97.  
  98.        Return (From release As GitHubRelease In Await GetReleasesAsync(userName, repositoryName)
  99.                Where release.Version = version).
  100.                DefaultIfEmpty(Nothing).
  101.                SingleOrDefault()
  102.  
  103.    End Function
  104.  
  105.    ''' <summary>
  106.    ''' Gets a release that matches the specified version from the specified repository on GitHub.
  107.    ''' </summary>
  108.    ''' <param name="userName">
  109.    ''' The user name.
  110.    ''' </param>
  111.    ''' <param name="repositoryName">
  112.    ''' The repository name.
  113.    ''' </param>
  114.    ''' <param name="version">
  115.    ''' The version of the release.
  116.    ''' </param>
  117.    ''' <returns>
  118.    ''' The resulting <see cref="GitHubRelease"/>.
  119.    ''' </returns>
  120.    Public Shared Function GetRelease(ByVal userName As String, ByVal repositoryName As String, ByVal version As Version) As GitHubRelease
  121.  
  122.        Dim t As Task(Of GitHubRelease) = Task.Run(Function() GitHubUtil.GetRelease(userName, repositoryName, version))
  123.        t.Wait(Timeout.Infinite)
  124.  
  125.        Return t.Result
  126.  
  127.    End Function
  128.  
  129.    ''' <summary>
  130.    ''' Asynchronously gets the latest release from the specified repository on GitHub.
  131.    ''' </summary>
  132.    ''' <param name="userName">
  133.    ''' The user name.
  134.    ''' </param>
  135.    ''' <param name="repositoryName">
  136.    ''' The repository name.
  137.    ''' </param>
  138.    ''' <returns>
  139.    ''' The resulting <see cref="GitHubRelease"/>.
  140.    ''' </returns>
  141.    ''' <exception cref="HttpException">
  142.    ''' JSON validation error.
  143.    ''' </exception>
  144.    Public Shared Async Function GetLatestReleaseAsync(ByVal userName As String, ByVal repositoryName As String) As Task(Of GitHubRelease)
  145.  
  146.        Dim uri As New Uri(String.Format("https://api.github.com/repos/{0}/{1}/releases/latest", userName, repositoryName), UriKind.Absolute)
  147.  
  148.        Dim request As HttpWebRequest = WebRequest.Create(uri)
  149.        request.UserAgent = userName
  150.  
  151.        Using response As WebResponse = Await request.GetResponseAsync(),
  152.              sr As New StreamReader(response.GetResponseStream()),
  153.              xmlReader As XmlDictionaryReader = JsonReaderWriterFactory.CreateJsonReader(sr.BaseStream, Encoding.UTF8, New XmlDictionaryReaderQuotas, Nothing)
  154.  
  155.            Dim xml As XElement = XElement.Load(xmlReader)
  156.            If (xml.IsEmpty) Then
  157.                Dim errMsg As String = String.Format("JSON validation error. ""{0}""", uri.ToString())
  158.                Throw New HttpException(HttpStatusCode.NotFound, errMsg)
  159.            End If
  160.  
  161.            Return New GitHubRelease(xml)
  162.        End Using
  163.  
  164.    End Function
  165.  
  166.    ''' <summary>
  167.    ''' Gets the latest release from the specified repository on GitHub.
  168.    ''' </summary>
  169.    ''' <param name="userName">
  170.    ''' The user name.
  171.    ''' </param>
  172.    ''' <param name="repositoryName">
  173.    ''' The repository name.
  174.    ''' </param>
  175.    ''' <returns>
  176.    ''' The resulting <see cref="GitHubRelease"/>.
  177.    ''' </returns>
  178.    Public Shared Function GetLatestRelease(ByVal userName As String, ByVal repositoryName As String) As GitHubRelease
  179.  
  180.        Dim t As Task(Of GitHubRelease) = Task.Run(Function() GitHubUtil.GetLatestReleaseAsync(userName, repositoryName))
  181.        t.Wait(Timeout.Infinite)
  182.  
  183.        Return t.Result
  184.  
  185.    End Function
  186.  
  187.    ''' <summary>
  188.    ''' Asynchronously gets a value that determine whether exists a new version available of the specified reository on GitHub.
  189.    ''' </summary>
  190.    ''' <param name="userName">
  191.    ''' The user name.
  192.    ''' </param>
  193.    ''' <param name="repositoryName">
  194.    ''' The repository name.
  195.    ''' </param>
  196.    ''' <param name="currentVersion">
  197.    ''' The current version.
  198.    ''' </param>
  199.    ''' <returns>
  200.    ''' <see langword="True"/> if exists a new version available on GitHub; otherwise, <see langword="False"/>.
  201.    ''' </returns>
  202.    Public Shared Async Function IsUpdateAvailableAsync(ByVal userName As String, ByVal repositoryName As String, ByVal currentVersion As Version) As Task(Of Boolean)
  203.  
  204.        Dim latestRelease As GitHubRelease = Await GitHubUtil.GetLatestReleaseAsync(userName, repositoryName)
  205.        Return (latestRelease.Version > currentVersion)
  206.  
  207.    End Function
  208.  
  209.    ''' <summary>
  210.    ''' Gets a value that determine whether exists a new version available of the specified reository on GitHub.
  211.    ''' </summary>
  212.    ''' <param name="userName">
  213.    ''' The user name.
  214.    ''' </param>
  215.    ''' <param name="repositoryName">
  216.    ''' The repository name.
  217.    ''' </param>
  218.    ''' <param name="currentVersion">
  219.    ''' The current version.
  220.    ''' </param>
  221.    ''' <returns>
  222.    ''' <see langword="True"/> if exists a new version available on GitHub; otherwise, <see langword="False"/>.
  223.    ''' </returns>
  224.    Public Shared Function IsUpdateAvailable(ByVal userName As String, ByVal repositoryName As String, ByVal currentVersion As Version) As Boolean
  225.  
  226.        Dim t As Task(Of Boolean) = Task.Run(Function() GitHubUtil.IsUpdateAvailableAsync(userName, repositoryName, currentVersion))
  227.        t.Wait(Timeout.Infinite)
  228.  
  229.        Return t.Result
  230.  
  231.    End Function
  232.  
  233. #End Region
  234.  
  235. End Class


« Última modificación: 6 Mayo 2018, 23:13 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: [SOURCE-CODE] Obtener releases de GitHub y comprobar actualizaciones...
« Respuesta #1 en: 6 Mayo 2018, 02:44 am »

Ejemplo para obtener todas las releases de un repositorio:

Código
  1. Dim releases As ReadOnlyCollection(Of GitHubRelease) = Await GitHubUtil.GetReleasesAsync("ElektroStudios", "SmartBotKit")
  2.  
  3. For Each release As GitHubRelease In releases
  4.    Console.WriteLine("RELEASE: {0}", release.ToString())
  5.  
  6.    For Each asset As GitHubAsset In release.Assets
  7.        Console.WriteLine("ASSET  : {0}", asset.ToString())
  8.    Next asset
  9.    Console.WriteLine()
  10. Next release

Ejemplo para obtener la release más reciente de un repositorio:

Código
  1. Dim release As GitHubRelease = Await GitHubUtil.GetLatestReleaseAsync("ElektroStudios", "SmartBotKit")
  2. Console.WriteLine("RELEASE: {0}", release.ToString())
  3. Console.WriteLine()
  4.  
  5. Console.WriteLine("BODY:")
  6. Console.WriteLine(release.Body)
  7. Console.WriteLine()
  8.  
  9. For Each asset As GitHubAsset In release.Assets
  10.    Console.WriteLine("ASSET: {0}", asset.ToString())
  11. Next asset

La salida de ejecución sería más o menos algo parecido a esto:
Citar
RELEASE: {Id=10754481, Version=1.3, Name=v1.3, TargetCommitish=master, IsDraft=False, IsPreRelease=False, DateCreated=04/27/2018 15:17:07, DatePublished=04/27/2018 15:22:06, UriHtml=https://github.com/ElektroStudios/SmartBotKit/releases/tag/1.3}

BODY:
Complete plugin collection.
SmartBotKit.Core.dll changes:
...

ASSET: {Id=6997992, Name=SmartBotKit.v1.3.zip, Label=, State=uploaded, Size=70959, ContentType=application/x-zip-compressed, DownloadCount=15, DateCreated=04/27/2018 15:22:03, DateUploaded=04/27/2018 15:22:04, UriDownload=https://github.com/ElektroStudios/SmartBotKit/releases/download/1.3/SmartBotKit.v1.3.zip}

ASSET: {Id=7125513, Name=test.txt, Label=, State=uploaded, Size=4, ContentType=text/plain, DownloadCount=1, DateCreated=05/06/2018 02:10:23, DateUploaded=05/06/2018 02:11:15, UriDownload=https://github.com/ElektroStudios/SmartBotKit/releases/download/1.3/test.txt}

Ejemplo para obtener una release con versión (tag_name) especifica de un repositorio:

Código
  1. Dim release As GitHubRelease = Await GitHubUtil.GetReleaseAsync("ElektroStudios", "SmartBotKit", New Version("1.3"))
  2. Console.WriteLine("RELEASE: {0}", release.ToString())
  3. Console.WriteLine()
  4.  
  5. Console.WriteLine("BODY:")
  6. Console.WriteLine(release.Body)
  7. Console.WriteLine()
  8.  
  9. For Each asset As GitHubAsset In release.Assets
  10.    Console.WriteLine("ASSET: {0}", asset.ToString())
  11. Next asset

Ejemplo para comprobar si existe una actualización disponible de un repositorio, y descargarlo:

Código
  1. Public Async Sub CheckForUpdate()
  2.  
  3.    Dim user As String = "ElektroStudios"
  4.    Dim repo As String = "SmartBotKit"
  5.    Dim currentVersion As Version = Assembly.GetExecutingAssembly().GetName().Version
  6.  
  7.    Dim isUpdateAvailable As Boolean = Await GitHubUtil.IsUpdateAvailableAsync(user, repo, currentVersion)
  8.    If (isUpdateAvailable) Then
  9.        MessageBox.Show("New version detected!", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information)
  10.  
  11.        ' Get the latest release.
  12.        Dim latestRelease As GitHubRelease = Await GitHubUtil.GetLatestReleaseAsync(user, repo)
  13.  
  14.        Using wc As New WebClient() ' Download the assets.
  15.            For Each asset As GitHubAsset In latestRelease.Assets
  16.                Dim fullpath As String = Path.Combine(Path.GetTempPath(), asset.Name)
  17.                Await wc.DownloadFileTaskAsync(asset.UriDownload, fullpath)
  18.                Console.WriteLine("File downloaded: {0}", fullpath)
  19.                ' Your own update logic goes here...
  20.            Next asset
  21.        End Using
  22.  
  23.    End If
  24.  
  25. End Sub


« Última modificación: 6 Mayo 2018, 03:38 am por Eleкtro » En línea



**Aincrad**


Desconectado Desconectado

Mensajes: 682



Ver Perfil WWW
Re: [SOURCE-CODE] Obtener releases de GitHub y comprobar actualizaciones...
« Respuesta #2 en: 11 Mayo 2018, 21:52 pm »

Exelente, me parece fantastico . . .  yo hice algo parecido con pastebin . puede obtener actualizaciones y descargarlas también con pastebin & mediafire. bueno voy a hacer un ejemplo para el foro y lo publico cuando tenga tiempo XD.

gracias por el aporte me servirá de mucho cuando logre poner una bendita carpeta en mi repositorio de  GitHub . :,V      :,V         :,V         :rolleyes:

En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: [SOURCE-CODE] Obtener releases de GitHub y comprobar actualizaciones...
« Respuesta #3 en: 12 Mayo 2018, 05:23 am »

gracias por el aporte me servirá de mucho cuando logre poner una bendita carpeta en mi repositorio de  GitHub . :,V      :,V         :,V         :rolleyes:

Gracias por el comentario.

No recuerdo si ya te comenté lo siguiente en otro post, pero por si no lo hice, te recomiendo usar GitHub Desktop para administrar tus repos:

Es muy sencillo de utilizar y así evitarías tener que aprenderte y usar los comandos de la consola de git.

saludos
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: [SOURCE-CODE] Obtener releases de GitHub y comprobar actualizaciones...
« Respuesta #4 en: 27 Mayo 2018, 06:38 am »

Recientemente he descubierto la librería Octokit para .NET, la cual al parecer está mantenida oficialmente por GitHub (o eso dice el autor):

También está disponible para Ruby y Objective-C:

¿Qué se puede hacer con dicha librería?, pues parece ser que practicamente de todo, desde hacer un commit, hasta obtener las releases de un repositorio como yo hice por mi cuenta en el post principal de este tema... así que os comento lo de la librería como alternativa para el que le interese, aunque en mi humilde opinión es demasiado basto ya que es un cliente completo de GitHub... para ser usado en otro tipo de escenarios más complejos y sofisticados, no para obtener unas releases y ya.

Saludos
« Última modificación: 27 Mayo 2018, 06:41 am por Eleкtro » En línea



Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines