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

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


  Mostrar Mensajes
Páginas: 1 ... 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 [520] 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 ... 1236
5191  Programación / Scripting / MOVIDO: Este año, la YAPC::EU 2015, en Granada (la de España) en: 4 Junio 2015, 20:46 pm
El tema ha sido movido a Programación General.

http://foro.elhacker.net/index.php?topic=436448.0
5192  Programación / .NET (C#, VB.NET, ASP) / Re: Modificar ejecutable VisualBasic en la instalación en: 3 Junio 2015, 21:27 pm
Hasta ahí bien, pero viene el problema. Los ordenadores comparten el mismo programa pero no las mismas restricciones, de forma que copiando los valores de registro de un ordenador con el programa desactivado y pegándolos en el ordenador bloqueado consiguen desactivar la aplicación...

Si el problema es ese entonces la primera solución que te ofrecí de usar Settings no te serviría, ya que el archivo de configuración sigue esta estructura, donde el hash sería el mismo en cada PC:
Código:
c:\Users\<username>\AppData\Local o Roaming\<companyname>\<appdomainname>_<eid>_<hash>\<verison>

Ejemplo real:
Código:
C:\Users\Administrador\AppData\Local\ElektroStudios\MasterMusik_Reports.exe_Url_q2a441mf5bc330sftjmvcdv30vohiv0o\2.0.0.0\user.config

De todas formas para otras cosas te puede interesar, aquí puedes conocer más detalles de su arquitectura, aunque es un artículo bastante antiguo:
Using My.Settings in Visual Basic 2005



A ver si lo he entendido bien, sino corrígeme.

Tu tienes algo PARECIDO a este ejemplo, en el código fuente:

Código
  1. Dim value As Integer = 0
  2.  
  3. Select Case value
  4.  
  5.    Case Is = 0
  6.        ' Activar aplicaciones.
  7.  
  8.    Case Is = 1
  9.        ' Denegar aplicaciones.
  10.  
  11.    Case Else
  12.        ' ...
  13.  
  14. End Select
(muy resumido)

¿Pero cómo decides si Value debe ser 0 o 1 al distribuirr y ejecutar el programa?, es decir, si el programa lo ejecutase yo en mi PC, ¿cómo se decide si se deben activar esas cosas que mencionas?, ¿se decide por un número?, ¿pero entonces cómo se decide el número que yo debo tener, no era aleatorio?, que lio, estoy algo espeso y no lo llego a pillar del todo.

De todas formas, ¿podrías mantener una conexión con los PCs de esas aulas? (mediante sockets), en ese caso lo que podrías hacer es administrar las activaciones de forma remota basándote en el HWID (Hardware ID) de cada equipo conectado,
de lo contrario, y si tienes acceso físico a esas aulas, entonces también puedes obtener manualmente el HWID de cada PC ejecutando un programa específico en ese PC que devuelva el HWID, es decir, obtienes los HWID de cada PC, luego creas una lista/array con los HWID predefinidos en tu código fuente y así administras las activaciones al distribuir la app, simplemente comprobando si el HWID dle equipo actual corresponde con algún HWID de la lista que compilaste.

Te dejo unas funciones que tal vez te podrían servir para pensar en algún enfoque, estas funciones sirven para obtener el identificador del procesador y de la placa base de un PC, y para cifrar un string mediante el algoritmo AES:

Código
  1.    ''' <remarks>
  2.    ''' *****************************************************************
  3.    ''' Title : Get CPU Identifier
  4.    ''' Author: Elektro
  5.    ''' Date  : 03-June-2015
  6.    '''
  7.    ''' Required Namespaces:
  8.    ''' <see cref="System.Management"/>
  9.    '''
  10.    ''' Usage Example:
  11.    ''' Dim Value as String = GetCpuId()
  12.    ''' *****************************************************************
  13.    ''' </remarks>
  14.    ''' <summary>
  15.    ''' Gets the motherboard ID of the current computer machine.
  16.    ''' </summary>
  17.    ''' <returns>The motherboard ID.</returns>
  18.    Public Shared Function GetCpuId() As String
  19.  
  20.        Using wmi As New ManagementObjectSearcher("select ProcessorID from Win32_Processor")
  21.  
  22.            Using query As ManagementObjectCollection = wmi.Get
  23.  
  24.                Return DirectCast(query(0), ManagementObject).Properties("ProcessorID").Value.ToString
  25.  
  26.            End Using
  27.  
  28.        End Using
  29.  
  30.    End Function

Código
  1.    ''' <remarks>
  2.    ''' *****************************************************************
  3.    ''' Title : Get Motherboard Identifier
  4.    ''' Author: Elektro
  5.    ''' Date  : 03-June-2015
  6.    '''
  7.    ''' Required Namespaces:
  8.    ''' <see cref="System.Management"/>
  9.    '''
  10.    ''' Usage Example:
  11.    ''' MsgBox(GetMotherboardId)
  12.    ''' *****************************************************************
  13.    ''' </remarks>
  14.    ''' <summary>
  15.    ''' Gets the motherboard ID of the current computer machine.
  16.    ''' </summary>
  17.    ''' <returns>The motherboard ID.</returns>
  18.    Public Shared Function GetMotherboardId() As String
  19.  
  20.        Using wmi As New ManagementObjectSearcher("select SerialNumber from Win32_BaseBoard")
  21.  
  22.            Using query As ManagementObjectCollection = wmi.Get
  23.  
  24.                Return DirectCast(query(0), ManagementObject).Properties("SerialNumber").Value.ToString
  25.  
  26.            End Using
  27.  
  28.        End Using
  29.  
  30.    End Function

Código
  1.    ''' <remarks>
  2.    ''' *****************************************************************
  3.    ''' Title : AES Encryptor
  4.    ''' Author: Elektro
  5.    ''' Date  : 03-June-2015
  6.    '''
  7.    ''' Required Namespaces:
  8.    ''' <see cref="System.IO"/>
  9.    ''' <see cref="System.Security.Cryptography"/>
  10.    ''' <see cref="System.Text"/>
  11.    '''
  12.    ''' Usage Example:
  13.    ''' Dim encrypted As String = AESEncryptor("Hello World!", key:="My Encryption Key", size:=128)
  14.    ''' *****************************************************************
  15.    ''' </remarks>
  16.    ''' <summary>
  17.    ''' Encrypts an string using AES algorithm.
  18.    ''' </summary>
  19.    ''' <param name="str">The string to encrypt.</param>
  20.    ''' <param name="key">The encryption key.</param>
  21.    ''' <param name="size">The key size. 128, 192 or 256 bits.</param>
  22.    ''' <param name="salt">The key salt.</param>
  23.    ''' <param name="mode">The encryption mode.</param>
  24.    ''' <returns>The encrypted string.</returns>
  25.    Public Function AESEncryptor(ByVal str As String,
  26.                                 ByVal key As String,
  27.                                 ByVal size As Integer,
  28.                                 Optional ByVal salt As Byte() = Nothing,
  29.                                 Optional ByVal mode As CipherMode = CipherMode.ECB) As String
  30.  
  31.        If (size <> 128) AndAlso (size <> 192) AndAlso (size <> 256) Then
  32.            Throw New ArgumentException(message:="Key size for this algorithm should be 128, 192 or 256.", paramName:="keySize")
  33.  
  34.        ElseIf (salt IsNot Nothing) AndAlso (salt.Length < 8) Then
  35.            Throw New ArgumentException(message:="Salt should contain at least 8 bytes.", paramName:="salt")
  36.  
  37.        ElseIf salt Is Nothing Then
  38.            salt = {&H49, &H76, &H61, &H6E, &H20, &H4D, &H65, &H64}
  39.  
  40.        End If
  41.  
  42.        Using crypto As Aes = Aes.Create()
  43.  
  44.            Dim pdb As Rfc2898DeriveBytes = New Rfc2898DeriveBytes(key, salt:=salt)
  45.  
  46.            crypto.KeySize = size ' 128, 192 or 256 Bits.
  47.            crypto.Key = pdb.GetBytes(cb:=(size \ 8)) ' 16, 24, or 32 or Bytes (128, 192 or 256 Bits).
  48.            crypto.IV = pdb.GetBytes(cb:=16) ' 16 Bytes (128 Bits).
  49.            crypto.Mode = mode
  50.  
  51.            Using ms As New MemoryStream()
  52.  
  53.                Using cs As New CryptoStream(ms, crypto.CreateEncryptor(), CryptoStreamMode.Write)
  54.  
  55.                    Dim strBytes As Byte() = Encoding.Unicode.GetBytes(str)
  56.                    cs.Write(strBytes, 0, strBytes.Length)
  57.                    cs.Close()
  58.  
  59.                End Using
  60.  
  61.                Return Convert.ToBase64String(ms.ToArray)
  62.  
  63.            End Using
  64.  
  65.        End Using
  66.  
  67.    End Function
  68.  
  69.    ''' <remarks>
  70.    ''' *****************************************************************
  71.    ''' Title : AES Decryptor
  72.    ''' Author: Elektro
  73.    ''' Date  : 03-June-2015
  74.    '''
  75.    ''' Required Namespaces:
  76.    ''' <see cref="System.IO"/>
  77.    ''' <see cref="System.Security.Cryptography"/>
  78.    ''' <see cref="System.Text"/>
  79.    '''
  80.    ''' Usage Example:
  81.    ''' Dim decrypted As String = AESDecryptor("JRVQnb2q7f3BtIDaq5Tdcqu2+2GYGEMLyQrBT9mMjgw=", key:="My Encryption Key", size:=128)
  82.    ''' *****************************************************************
  83.    ''' </remarks>
  84.    ''' <summary>
  85.    ''' Decrypts a previously encrypted string using AES algorithm.
  86.    ''' </summary>
  87.    ''' <param name="str">The encrypted string to decrypt.</param>
  88.    ''' <param name="key">The key used for encryption.</param>
  89.    ''' <param name="size">The key size used for encryption. 128, 192 or 256 bits.</param>
  90.    ''' <param name="salt">The key salt used for encryption.</param>
  91.    ''' <param name="mode">The encryption mode.</param>
  92.    ''' <returns>The decrypted string.</returns>
  93.    Public Function AESDecryptor(ByVal str As String,
  94.                                 ByVal key As String,
  95.                                 ByVal size As Integer,
  96.                                 Optional ByVal salt As Byte() = Nothing,
  97.                                 Optional ByVal mode As CipherMode = CipherMode.ECB) As String
  98.  
  99.        If (size <> 128) AndAlso (size <> 192) AndAlso (size <> 256) Then
  100.            Throw New ArgumentException(message:="Key size for this algorithm should be 128, 192 or 256.", paramName:="keySize")
  101.  
  102.        ElseIf (salt IsNot Nothing) AndAlso (salt.Length < 8) Then
  103.            Throw New ArgumentException(message:="Salt should contain at least 8 bytes.", paramName:="salt")
  104.  
  105.        ElseIf salt Is Nothing Then
  106.            salt = {&H49, &H76, &H61, &H6E, &H20, &H4D, &H65, &H64}
  107.  
  108.        End If
  109.  
  110.        Using crypto As Aes = Aes.Create()
  111.  
  112.            Dim pdb As New Rfc2898DeriveBytes(key, salt)
  113.  
  114.            crypto.KeySize = size ' 128, 192 or 256 Bits.
  115.            crypto.Key = pdb.GetBytes(cb:=(size \ 8)) ' 16, 24, or 32 or Bytes (128, 192 or 256 Bits).
  116.            crypto.IV = pdb.GetBytes(cb:=16) ' 16 Bytes (128 Bits).
  117.            crypto.Mode = mode
  118.  
  119.            Using ms As New MemoryStream()
  120.  
  121.                Using cs As New CryptoStream(ms, crypto.CreateDecryptor(), CryptoStreamMode.Write)
  122.  
  123.                    Dim cipherBytes As Byte() = Convert.FromBase64String(str)
  124.                    cs.Write(cipherBytes, 0, cipherBytes.Length)
  125.                    cs.Close()
  126.  
  127.                End Using
  128.  
  129.                Return Encoding.Unicode.GetString(ms.ToArray)
  130.  
  131.            End Using
  132.  
  133.        End Using
  134.  
  135.    End Function

Saludos
5193  Foros Generales / Foro Libre / Re: Explica tu avatar en: 3 Junio 2015, 17:41 pm
Yo he llevado muchos avatares en todos estos años, algunos absurdos cómo memes o gifs, pero ahora me he acostumbrado a llevar este, que identifica una de mis aficiones o pasiones, es el logo de Microsoft Visual Studio:



Aunque no lo parezca, no es un antifáz, es la etapa moderna/actual del logo que han tenido siempre, aunque publicamente tampoco se sabe mucho cual es el significado de ese logo, se dice que está relacionado con el símbolo de infinito, aquí pueden ver las anteriores fases del logo:






Saludos
5194  Foros Generales / Foro Libre / Re: Kebab en: 3 Junio 2015, 17:32 pm
En el video llevan todos el gorrito ese, pero ninguno tiene guantes y por ahí pasan 200 manos... me ha dado bastante asco.

Aunque no se si lo de llevar guantes es obligatorio auqí en España en este tipo de "fabricas", pero desde el procesado de la carne hasta que llega a tu boca todo es anti-higiénico, por no decir que muchos restaurantes de kebabs están llenos de moscas volando por las tapas (sin tapadera además, los muy cutres y cerdos), en más de una ocasión he salido nada más entrar en este tipo de establecimientos, y creo que despues de ver esto no volveré a comer un Kebab de esos.

Saludos
5195  Programación / Scripting / Re: Batch, ¿Software libre? en: 3 Junio 2015, 17:15 pm
hay tantos expertos que lo califican com. virus(perteneciendo a los malwares) como expertos expertos que lo niegan.

Yo personalmente si lo califico de virus, dependiendo de si lo sabes programar bien.

He leido y releido tantos autores que lo defienden como virus, y he aprendido hacer ahi desde cosas sencillas como bucles que no dejen de abrirte pestañas programas paginas web o la misma disketera del pc automaticamente, borrar todo sin perdir permiso al usuario y tantas cosas asi basicas, como cosas mas avanzadas como crear gusanos en batch. En resumen, con batch puedes alterar el normal funcionamiento del ordenador, cualidad que tiene todo virus segun wikipedia.

No te ofendas, pero todo eso que has leido proviene de Lammers, o gente a la que Microsoft les paga, no se jaja.

Te lo comento por experiencia en Batch:
[Batch] Virulator 1.0c - By Elektro

A duras penas Batch se puede considerar cómo un lenguaje de programación, ya que es una herramienta muy limitada, según Microsoft es una herramienta diseñada y destinada a cumplir tareas básicas del sistema, y el desarrollo de un virus no es una tarea básico. Batch es un "lenguaje" de procesamiento por lotes, ¿entiendes lo que es eso?, ni siquiera es un lenguaje orientado a objetos y con el que poder manipular la API del SO, ya me dirás tú que cosas vas a hacer con Batch, cosas básicas, muy básicas y además mal hechas, por sus limitaciones siempre resulta mucho más tedioso un código desarrollado en Batch que en cualquier otro lenguaje de hoy en día, por ende, debido a su naturaleza limitada, Batch ni siquira tiene capacidad para definir un Array, ni manejar Sockets, ni nada que realmente sea útil.

Saber programar bien no excluye la realidad que acabo de comentar, Batch es inutil, puedes alterar el comportamiento del PC ...claro, los brazos y las piernas de Batch precisamente son las aplicaciones externas de Microsoft que están instaladas en el sistema (ping.exe, attrib.exe, xcopy.exe, y cientos de aplicaciones más), los mal llamados "comandos de Batch" cómo si formasen parte del lenguaje, pero no, son comandos EXTERNOS (exceptuando los comandos internos, como del, echo, etc), y esa es la especie de "framework" de Batch la cual sin ello sería una herramienta más inutil todavía, un lenguaje de verdad no necesita apoyarse en aplicaciones externas para elaborar la mayoria de las tareas que necesites llevar a cabo.

Por no decir que carece de cualquier tipo de sistema de depuración, y es imposible implementar algunas características de los Virus cómo la persistencia o la propagación (a menos que utilices herramientas EXTERNAS para ello), de verdad, cualquier persona que realmente desarrolle Virus se ofendería por decir que con Batch se puede desarrollar un virus.

Si te interesa la idea de desarrollar una bomba lógica en Batch me parece estupendo, aun debes practicar y manejar otros lenguajes para entender conceptos y sus diferencias, te vendría bien,
pero deja de pensar que en Batch puedes hacer virus y deja de leer a esos "expertos", por qué te llevará por el camibo equivocado, el del lammerismo.

Aquí en el foro, en la sección de diseño y análisis de Malware tienes expertos de verdad, personas que desarrollan RATS, Crypters, y quizás Virus tipo el virus de la policia (xD), te sugiero que busques la opinión de ellos respecto a este tema para despejarte todas tus dudas.

Saludos!
5196  Foros Generales / Dudas Generales / Re: como descargar juegos gratis de playstore en: 2 Junio 2015, 10:09 am
LLevas un dia en el Foro y yá vienes diciendo que tenemos demasiadas Reglas,

XDDDD

Creo que ya se te dijo todo y no tiene sentido que este tema siga abierto, amigo... compórtate sin llamar demasiado la atención, aquí se viene a aprender, divertirse, ayudar... pero siempre respetando las reglas.

Saludos!
5197  Programación / .NET (C#, VB.NET, ASP) / Re: Modificar ejecutable VisualBasic en la instalación en: 2 Junio 2015, 10:05 am
¿Por qué tienes pegas con almacenar la configuración en un archivo?, una solución sería hacer lo que te comentó @nolasco281, pero usando la infraestructura Settings para que la aletoriedad se produzca una única vez por instalación.

Ej:
Código
  1. If Not My.Settings.IsRandomized Then
  2.  My.Settings.RandomValue = ' Generar valor aleatorio
  3.  My.Settings.IsRandomized = True
  4. End If
  5.  
  6. lbl.text = My.Settings.RandomValue.ToString

Teniendo en cuenta que esos datos se guardan en un archivo de configuración pero es la solución menos compleja, de lo contrario las opciones que te quedan son llamar a la app mediante argumentos para pasarle un número específico (para esto debes controlar los argumentos desde la app, e iniciar la app desde la consola o un acceso directo para pasarle dicho número), automatizar la compilación de la app en tiempo de ejecución desde el instalador (editando previamente "X" valor estático del código fuente antes de compilar, para aplicar dicha aletoriedad por instalación, claro está), o automatizar el parcheo de "X" bytes de la app compilada para modificar el valor, para esto primero debes localizar los bytes que hacen referencia a ese valor "aleatorio" en un editor hexadecimal o como veas.

En realidad ninguna de esas alternativas es dificil mientras sepas cómo hacerlo.

Saludos
5198  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets) en: 2 Junio 2015, 09:56 am
Una Class para administrar un archivo de recursos de .Net ( file.resx )

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 16-March-2015
  4. ' ***********************************************************************
  5. ' <copyright file="ResXManager.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Option Statements "
  11.  
  12. Option Strict On
  13. Option Explicit On
  14. Option Infer Off
  15.  
  16. #End Region
  17.  
  18. #Region " Usage Examples "
  19.  
  20. 'Imports System.IO
  21. 'Imports System.Text
  22.  
  23. 'Public Class Form1
  24.  
  25. '    Private Sub Test() Handles MyBase.Shown
  26.  
  27. '        Dim resX As New ResXManager(Path.Combine(Application.StartupPath, "MyResources.resx"))
  28. '        With resX
  29.  
  30. '            ' Create or replace the ResX file.
  31. '            .Create(replace:=True)
  32.  
  33. '            ' Add a string resource.
  34. '            .AddResource(Of String)("String Resource", "Hello World!", "String Comment")
  35. '            ' Add a bitmap resource.
  36. '            .AddResource(Of Bitmap)("Bitmap Resource", SystemIcons.Information.ToBitmap, "Bitmap Comment")
  37. '            ' Add a binary resource.
  38. '            .AddResource(Of Byte())("Binary Resource", File.ReadAllBytes("C:\file.mp3"), "Binary Comment")
  39.  
  40. '        End With
  41.  
  42. '        ' *******************************************************************************************************
  43.  
  44. '        ' Get the string resource.
  45. '        Dim stringResource As ResXManager.Resource(Of String) =
  46. '            resX.FindResource(Of String)("String Resource", StringComparison.OrdinalIgnoreCase)
  47.  
  48. '        ' Get the bitmap resource.
  49. '        Dim bitmapResource As ResXManager.Resource(Of Bitmap) =
  50. '            resX.FindResource(Of Bitmap)("Bitmap Resource", StringComparison.OrdinalIgnoreCase)
  51.  
  52. '        ' Get the binary resource.
  53. '        Dim binaryResource As ResXManager.Resource(Of Byte()) =
  54. '            resX.FindResource(Of Byte())("Binary Resource", StringComparison.OrdinalIgnoreCase)
  55.  
  56. '        ' *******************************************************************************************************
  57.  
  58. '        ' Get the string data.
  59. '        Dim stringData As String = stringResource.Data
  60.  
  61. '        ' Get the bitmap data.
  62. '        Dim bitmapData As Bitmap = bitmapResource.Data
  63.  
  64. '        ' Get the binary data.
  65. '        Dim binaryData As Byte() = binaryResource.Data
  66.  
  67. '        ' *******************************************************************************************************
  68.  
  69. '        ' Get all the resources at once.
  70. '        Dim resources As IEnumerable(Of ResXManager.Resource) = resX.Resources
  71.  
  72. '        ' Get all the resources of specific Type at once.
  73. '        Dim stringResources As IEnumerable(Of ResXManager.Resource(Of String)) = resX.FindResources(Of String)()
  74.  
  75. '        ' *******************************************************************************************************
  76.  
  77. '        ' Get all the resource datas at once from Resource collection.
  78. '        Dim resourceDatas As IEnumerable(Of Object) =
  79. '            From res As ResXManager.Resource In resX.Resources
  80. '            Select res.Data
  81.  
  82. '        ' Get all the resource datas of specific Type at once from Resource collection.
  83. '        Dim stringResourceDatas As IEnumerable(Of String) =
  84. '            From res As ResXManager.Resource In resX.Resources
  85. '            Where res.Type Is GetType(String)
  86. '            Select DirectCast(res.Data, String)
  87.  
  88. '        ' *******************************************************************************************************
  89.  
  90. '        ' Treat the string data as you like.
  91. '        MessageBox.Show(stringData, String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information)
  92.  
  93. '        ' Treat the bitmap data as you like.
  94. '        Me.Icon = Icon.FromHandle(bitmapData.GetHicon)
  95.  
  96. '        ' Treat the binary data as you like.
  97. '        File.WriteAllBytes("C:\new file.mp3", binaryData)
  98.  
  99. '        ' *******************************************************************************************************
  100.  
  101. '        ' Iterate all the resources.
  102. '        For Each res As ResXManager.Resource In resX.Resources
  103.  
  104. '            Dim sb As New StringBuilder
  105.  
  106. '            sb.AppendLine(String.Format("Name...: {0}", res.Name))
  107. '            sb.AppendLine(String.Format("Comment: {0}", res.Comment))
  108. '            sb.AppendLine(String.Format("Type...: {0}", res.Type.ToString))
  109. '            sb.AppendLine(String.Format("Data...: {0}", res.Data.ToString))
  110.  
  111. '            MsgBox(sb.ToString)
  112. '        Next
  113.  
  114. '        ' Iterate all the resources of specific Type.
  115. '        For Each res As ResXManager.Resource(Of String) In resX.FindResources(Of String)()
  116.  
  117. '            Dim sb As New StringBuilder
  118.  
  119. '            sb.AppendLine(String.Format("Name...: {0}", res.Name))
  120. '            sb.AppendLine(String.Format("Comment: {0}", res.Comment))
  121. '            sb.AppendLine(String.Format("Type...: {0}", res.Type.ToString))
  122. '            sb.AppendLine(String.Format("Data...: {0}", res.Data.ToString))
  123.  
  124. '            MsgBox(sb.ToString)
  125. '        Next
  126.  
  127. '        ' *******************************************************************************************************
  128.  
  129. '        ' Remove a resource.
  130. '        resX.RemoveResource("Binary Resource")
  131.  
  132. '        '  GC.Collect()
  133.  
  134. '    End Sub
  135.  
  136. 'End Class
  137.  
  138. #End Region
  139.  
  140. #Region " Imports "
  141.  
  142. Imports System.ComponentModel
  143. Imports System.ComponentModel.Design
  144. Imports System.IO
  145. Imports System.Resources
  146.  
  147. #End Region
  148.  
  149. ''' <summary>
  150. ''' Manages a .Net managed resource file.
  151. ''' </summary>
  152. Public NotInheritable Class ResXManager
  153.  
  154. #Region " Properties "
  155.  
  156.    ''' <summary>
  157.    ''' Gets the .Net managed resource file path.
  158.    ''' </summary>
  159.    ''' <value>The .Net managed resource filepath.</value>
  160.    Public ReadOnly Property FilePath As String
  161.        Get
  162.            Return Me.filePath1
  163.        End Get
  164.    End Property
  165.    ''' <summary>
  166.    ''' The .Net managed resource file path.
  167.    ''' </summary>
  168.    Private ReadOnly filePath1 As String
  169.  
  170.    ''' <summary>
  171.    ''' Gets the resources contained in the .Net managed resource file.
  172.    ''' </summary>
  173.    ''' <value>The resources.</value>
  174.    Public ReadOnly Property Resources As IEnumerable(Of Resource)
  175.        Get
  176.            Return GetResources()
  177.        End Get
  178.    End Property
  179.  
  180. #End Region
  181.  
  182. #Region " Types "
  183.  
  184. #Region " Resource "
  185.  
  186.    ''' <summary>
  187.    ''' Defines a resource of a .Net managed resource file.
  188.    ''' </summary>
  189.    <Serializable>
  190.    Public NotInheritable Class Resource
  191.  
  192. #Region " Properties "
  193.  
  194.        ''' <summary>
  195.        ''' Gets the resource name.
  196.        ''' </summary>
  197.        ''' <value>The resource name.</value>
  198.        Public ReadOnly Property Name As String
  199.            Get
  200.                Return Me.name1
  201.            End Get
  202.        End Property
  203.        Private ReadOnly name1 As String
  204.  
  205.        ''' <summary>
  206.        ''' Gets the resource data.
  207.        ''' </summary>
  208.        ''' <value>The resource data.</value>
  209.        Public ReadOnly Property Data As Object
  210.            Get
  211.                Return Me.data1
  212.            End Get
  213.        End Property
  214.        Private ReadOnly data1 As Object
  215.  
  216.        ''' <summary>
  217.        ''' Gets the resource type.
  218.        ''' </summary>
  219.        ''' <value>The resource type.</value>
  220.        Public ReadOnly Property Type As Type
  221.            Get
  222.                Return Data.GetType
  223.            End Get
  224.        End Property
  225.  
  226.        ''' <summary>
  227.        ''' Gets the resource comment.
  228.        ''' </summary>
  229.        ''' <value>The resource comment.</value>
  230.        Public ReadOnly Property Comment As String
  231.            Get
  232.                Return comment1
  233.            End Get
  234.        End Property
  235.        Private ReadOnly comment1 As String
  236.  
  237.        ''' <summary>
  238.        ''' Represents a <see cref="Resource"/> instance that is <c>Nothing</c>.
  239.        ''' </summary>
  240.        ''' <value><c>Nothing</c></value>
  241.        <EditorBrowsable(EditorBrowsableState.Advanced)>
  242.        Public Shared ReadOnly Property Empty As Resource
  243.            Get
  244.                Return Nothing
  245.            End Get
  246.        End Property
  247.  
  248. #End Region
  249.  
  250. #Region " Constructors "
  251.  
  252.        ''' <summary>
  253.        ''' Initializes a new instance of the <see cref="Resource"/> class.
  254.        ''' </summary>
  255.        ''' <param name="name">The resource name.</param>
  256.        ''' <param name="data">The resource data.</param>
  257.        ''' <param name="comment">The resource comment.</param>
  258.        Public Sub New(ByVal name As String,
  259.                       ByVal data As Object,
  260.                       ByVal comment As String)
  261.  
  262.            Me.name1 = name
  263.            Me.data1 = data
  264.            Me.comment1 = comment
  265.  
  266.        End Sub
  267.  
  268.        ''' <summary>
  269.        ''' Prevents a default instance of the <see cref="Resource"/> class from being created.
  270.        ''' </summary>
  271.        Private Sub New()
  272.        End Sub
  273.  
  274. #End Region
  275.  
  276. #Region " Hidden Methods "
  277.  
  278.        ''' <summary>
  279.        ''' Determines whether the specified System.Object instances are considered equal.
  280.        ''' </summary>
  281.        <EditorBrowsable(EditorBrowsableState.Never)>
  282.        Public Shadows Function Equals(ByVal obj As Object) As Boolean
  283.            Return MyBase.Equals(obj)
  284.        End Function
  285.  
  286.        ''' <summary>
  287.        ''' Serves as a hash function for a particular type.
  288.        ''' </summary>
  289.        <EditorBrowsable(EditorBrowsableState.Never)>
  290.        Public Shadows Function GetHashCode() As Integer
  291.            Return MyBase.GetHashCode
  292.        End Function
  293.  
  294.        ''' <summary>
  295.        ''' Gets the System.Type of the current instance.
  296.        ''' </summary>
  297.        ''' <returns>The exact runtime type of the current instance.</returns>
  298.        <EditorBrowsable(EditorBrowsableState.Never)>
  299.        Public Shadows Function [GetType]() As Type
  300.            Return MyBase.GetType
  301.        End Function
  302.  
  303.        ''' <summary>
  304.        ''' Returns a String that represents the current object.
  305.        ''' </summary>
  306.        <EditorBrowsable(EditorBrowsableState.Never)>
  307.        Public Shadows Function ToString() As String
  308.            Return MyBase.ToString
  309.        End Function
  310.  
  311. #End Region
  312.  
  313.    End Class
  314.  
  315. #End Region
  316.  
  317. #Region " Resource(Of T) "
  318.  
  319.    ''' <summary>
  320.    ''' Defines a resource of a .Net managed resource file.
  321.    ''' </summary>
  322.    <Serializable>
  323.    Public NotInheritable Class Resource(Of T)
  324.  
  325. #Region " Properties "
  326.  
  327.        ''' <summary>
  328.        ''' Gets the resource name.
  329.        ''' </summary>
  330.        ''' <value>The resource name.</value>
  331.        Public ReadOnly Property Name As String
  332.            Get
  333.                Return Me.name1
  334.            End Get
  335.        End Property
  336.        Private ReadOnly name1 As String
  337.  
  338.        ''' <summary>
  339.        ''' Gets the resource data.
  340.        ''' </summary>
  341.        ''' <value>The resource data.</value>
  342.        Public ReadOnly Property Data As T
  343.            Get
  344.                Return Me.data1
  345.            End Get
  346.        End Property
  347.        Private ReadOnly data1 As T
  348.  
  349.        ''' <summary>
  350.        ''' Gets the resource type.
  351.        ''' </summary>
  352.        ''' <value>The resource type.</value>
  353.        Public ReadOnly Property Type As Type
  354.            Get
  355.                Return GetType(T)
  356.            End Get
  357.        End Property
  358.  
  359.        ''' <summary>
  360.        ''' Gets the resource comment.
  361.        ''' </summary>
  362.        ''' <value>The resource comment.</value>
  363.        Public ReadOnly Property Comment As String
  364.            Get
  365.                Return comment1
  366.            End Get
  367.        End Property
  368.        Private ReadOnly comment1 As String
  369.  
  370. #End Region
  371.  
  372. #Region " Constructors "
  373.  
  374.        ''' <summary>
  375.        ''' Initializes a new instance of the <see cref="Resource(Of T)"/> class.
  376.        ''' </summary>
  377.        ''' <param name="name">The resource name.</param>
  378.        ''' <param name="data">The resource data.</param>
  379.        ''' <param name="comment">The resource comment.</param>
  380.        Public Sub New(ByVal name As String,
  381.                       ByVal data As T,
  382.                       ByVal comment As String)
  383.  
  384.            Me.name1 = name
  385.            Me.data1 = data
  386.            Me.comment1 = comment
  387.  
  388.        End Sub
  389.  
  390.        ''' <summary>
  391.        ''' Prevents a default instance of the <see cref="Resource(Of T)"/> class from being created.
  392.        ''' </summary>
  393.        Private Sub New()
  394.        End Sub
  395.  
  396. #End Region
  397.  
  398. #Region " Hidden Methods "
  399.  
  400.        ''' <summary>
  401.        ''' Determines whether the specified System.Object instances are considered equal.
  402.        ''' </summary>
  403.        <EditorBrowsable(EditorBrowsableState.Never)>
  404.        Public Shadows Function Equals(ByVal obj As Object) As Boolean
  405.            Return MyBase.Equals(obj)
  406.        End Function
  407.  
  408.        ''' <summary>
  409.        ''' Serves as a hash function for a particular type.
  410.        ''' </summary>
  411.        <EditorBrowsable(EditorBrowsableState.Never)>
  412.        Public Shadows Function GetHashCode() As Integer
  413.            Return MyBase.GetHashCode
  414.        End Function
  415.  
  416.        ''' <summary>
  417.        ''' Gets the System.Type of the current instance.
  418.        ''' </summary>
  419.        ''' <returns>The exact runtime type of the current instance.</returns>
  420.        <EditorBrowsable(EditorBrowsableState.Never)>
  421.        Public Shadows Function [GetType]() As Type
  422.            Return MyBase.GetType
  423.        End Function
  424.  
  425.        ''' <summary>
  426.        ''' Returns a String that represents the current object.
  427.        ''' </summary>
  428.        <EditorBrowsable(EditorBrowsableState.Never)>
  429.        Public Shadows Function ToString() As String
  430.            Return MyBase.ToString
  431.        End Function
  432.  
  433. #End Region
  434.  
  435.    End Class
  436.  
  437. #End Region
  438.  
  439. #End Region
  440.  
  441. #Region " Constructors "
  442.  
  443.    ''' <summary>
  444.    ''' Initializes a new instance of the <see cref="ResXManager"/> class.
  445.    ''' </summary>
  446.    ''' <param name="resxFilePath">The .Net managed resource filepath.</param>
  447.    Public Sub New(ByVal resxFilePath As String)
  448.        Me.filePath1 = resxFilePath
  449.    End Sub
  450.  
  451.    ''' <summary>
  452.    ''' Prevents a default instance of the <see cref="ResXManager"/> class from being created.
  453.    ''' </summary>
  454.    Private Sub New()
  455.    End Sub
  456.  
  457. #End Region
  458.  
  459. #Region " Public Methods "
  460.  
  461.    ''' <summary>
  462.    ''' Creates the .Net managed resource file.
  463.    ''' </summary>
  464.    ''' <param name="replace">if set to <c>true</c>, replaces any existent file.</param>
  465.    ''' <exception cref="System.Exception"></exception>
  466.    Public Sub Create(Optional ByVal replace As Boolean = False)
  467.  
  468.        If Not replace AndAlso File.Exists(Me.filePath1) Then
  469.            Throw New Exception(String.Format("Resource file already exists: {0}", Me.filePath1))
  470.            Exit Sub
  471.        End If
  472.  
  473.        Dim resXWritter As ResXResourceWriter = Nothing
  474.        Try
  475.            resXWritter = New ResXResourceWriter(Me.filePath1)
  476.            Using resXWritter
  477.                resXWritter.Generate()
  478.            End Using
  479.  
  480.        Catch ex As Exception
  481.            Throw
  482.  
  483.        Finally
  484.            If resXWritter IsNot Nothing Then
  485.                resXWritter.Close()
  486.            End If
  487.  
  488.        End Try
  489.  
  490.    End Sub
  491.  
  492.    ''' <summary>
  493.    ''' Adds a resource into the .Net managed resource file.
  494.    ''' </summary>
  495.    ''' <param name="name">The resource name.</param>
  496.    ''' <param name="data">The resource data.</param>
  497.    ''' <param name="comment">The resource comment.</param>
  498.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  499.    ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
  500.    Public Sub AddResource(ByVal name As String,
  501.                           ByVal data As Object,
  502.                           Optional ByVal comment As String = Nothing)
  503.  
  504.        Me.AddResource(replace:=False, name:=name, data:=data, comment:=comment)
  505.  
  506.    End Sub
  507.  
  508.    ''' <summary>
  509.    ''' Adds a specified resource of the specified type into the .Net managed resource file.
  510.    ''' </summary>
  511.    ''' <typeparam name="T"></typeparam>
  512.    ''' <param name="name">The resource name.</param>
  513.    ''' <param name="data">The resource data.</param>
  514.    ''' <param name="comment">The resource comment.</param>
  515.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  516.    ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
  517.    Public Sub AddResource(Of T)(ByVal name As String,
  518.                                 ByVal data As T,
  519.                                 Optional ByVal comment As String = Nothing)
  520.  
  521.        Me.AddResource(replace:=False, name:=name, data:=data, comment:=comment)
  522.  
  523.    End Sub
  524.  
  525.    ''' <summary>
  526.    ''' Replaces a resource by the specified name inside the .Net managed resource file.
  527.    ''' </summary>
  528.    ''' <param name="name">The resource name.</param>
  529.    ''' <param name="data">The resource data.</param>
  530.    ''' <param name="comment">The resource comment.</param>
  531.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  532.    ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
  533.    Public Sub ReplaceResource(ByVal name As String,
  534.                               ByVal data As Object,
  535.                               Optional ByVal comment As String = Nothing)
  536.  
  537.        Me.AddResource(replace:=True, name:=name, data:=data, comment:=comment)
  538.  
  539.    End Sub
  540.  
  541.    ''' <summary>
  542.    ''' Replaces a resource by the specified name of the specified type inside the .Net managed resource file.
  543.    ''' </summary>
  544.    ''' <typeparam name="T"></typeparam>
  545.    ''' <param name="name">The resource name.</param>
  546.    ''' <param name="data">The resource data.</param>
  547.    ''' <param name="comment">The resource comment.</param>
  548.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  549.    ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
  550.    Public Sub ReplaceResource(Of T)(ByVal name As String,
  551.                                     ByVal data As T,
  552.                                     Optional ByVal comment As String = Nothing)
  553.  
  554.        Me.AddResource(replace:=True, name:=name, data:=data, comment:=comment)
  555.  
  556.    End Sub
  557.  
  558.    ''' <summary>
  559.    ''' Finds a resource by the specified name of specified type inside the .Net managed resource file.
  560.    ''' </summary>
  561.    ''' <typeparam name="T"></typeparam>
  562.    ''' <param name="name">The resource name.</param>
  563.    ''' <param name="stringComparison">The <see cref="StringComparison"/> to compare the resource name.</param>
  564.    ''' <returns>The resource.</returns>
  565.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  566.    ''' <exception cref="System.ArgumentException">Resource with the specified name is not found.;name</exception>
  567.    ''' <exception cref="System.ArgumentException">The specified Type differs from the resource Type.;T</exception>
  568.    Public Function FindResource(Of T)(ByVal name As String,
  569.                                       Optional ByVal stringComparison As StringComparison =
  570.                                                      StringComparison.OrdinalIgnoreCase) As Resource(Of T)
  571.  
  572.        If Not File.Exists(Me.filePath1) Then
  573.            Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
  574.            Exit Function
  575.        End If
  576.  
  577.        ' Read the ResX file.
  578.        Dim resX As ResXResourceReader = Nothing
  579.        Dim res As Resource(Of T) = Nothing
  580.        Try
  581.            resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
  582.            Using resX
  583.  
  584.                For Each entry As DictionaryEntry In resX
  585.  
  586.                    If entry.Key.ToString.Equals(name, stringComparison) Then
  587.  
  588.                        Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)
  589.  
  590.                        res = New Resource(Of T)(name:=node.Name,
  591.                                                 data:=DirectCast(node.GetValue(DirectCast(Nothing, ITypeResolutionService)), T),
  592.                                                 comment:=node.Comment)
  593.                        Exit For
  594.  
  595.                    End If
  596.  
  597.                Next entry
  598.  
  599.            End Using ' resX
  600.  
  601.            Return res
  602.  
  603.        Catch ex As Exception
  604.            Throw
  605.  
  606.        Finally
  607.            If resX IsNot Nothing Then
  608.                resX.Close()
  609.            End If
  610.  
  611.        End Try
  612.  
  613.    End Function
  614.  
  615.    ''' <summary>
  616.    ''' Finds a resource by the specified name inside the .Net managed resource file.
  617.    ''' </summary>
  618.    ''' <param name="name">The resource name.</param>
  619.    ''' <param name="stringComparison">The <see cref="StringComparison"/> to compare the resource name.</param>
  620.    ''' <returns>The resource.</returns>
  621.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  622.    ''' <exception cref="System.ArgumentException">Resource with the specified name is not found.;name</exception>
  623.    ''' <exception cref="System.ArgumentException">The specified Type differs from the resource Type.;T</exception>
  624.    Public Function FindResource(ByVal name As String,
  625.                                 Optional ByVal stringComparison As StringComparison =
  626.                                                StringComparison.OrdinalIgnoreCase) As Resource
  627.  
  628.        If Not File.Exists(Me.filePath1) Then
  629.            Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
  630.            Exit Function
  631.        End If
  632.  
  633.        ' Read the ResX file.
  634.        Dim resX As ResXResourceReader = Nothing
  635.        Dim res As Resource = Nothing
  636.        Try
  637.            resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
  638.            Using resX
  639.  
  640.                For Each entry As DictionaryEntry In resX
  641.  
  642.                    If entry.Key.ToString.Equals(name, stringComparison) Then
  643.  
  644.                        Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)
  645.  
  646.                        res = New Resource(name:=node.Name,
  647.                                           data:=node.GetValue(DirectCast(Nothing, ITypeResolutionService)),
  648.                                           comment:=node.Comment)
  649.                        Exit For
  650.  
  651.                    End If
  652.  
  653.                Next entry
  654.  
  655.            End Using ' resX
  656.  
  657.            Return res
  658.  
  659.        Catch ex As Exception
  660.            Throw
  661.  
  662.        Finally
  663.            If resX IsNot Nothing Then
  664.                resX.Close()
  665.            End If
  666.  
  667.        End Try
  668.  
  669.    End Function
  670.  
  671.    ''' <summary>
  672.    ''' Finds the resources of the specified type inside the .Net managed resource file.
  673.    ''' </summary>
  674.    ''' <typeparam name="T"></typeparam>
  675.    ''' <returns>The resource.</returns>
  676.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  677.    ''' <exception cref="System.ArgumentException">Resource with the specified name is not found.;name</exception>
  678.    ''' <exception cref="System.ArgumentException">The specified Type differs from the resource Type.;T</exception>
  679.    Public Iterator Function FindResources(Of T)() As IEnumerable(Of Resource(Of T))
  680.  
  681.        If Not File.Exists(Me.filePath1) Then
  682.            Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
  683.            Exit Function
  684.        End If
  685.  
  686.        ' Read the ResX file.
  687.        Dim resX As ResXResourceReader = Nothing
  688.        Try
  689.            resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
  690.            Using resX
  691.  
  692.                For Each entry As DictionaryEntry In resX
  693.  
  694.                    Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)
  695.  
  696.                    If node.GetValue(DirectCast(Nothing, ITypeResolutionService)).GetType Is GetType(T) Then
  697.  
  698.                        Yield New Resource(Of T)(name:=node.Name,
  699.                                           data:=DirectCast(node.GetValue(DirectCast(Nothing, ITypeResolutionService)), T),
  700.                                           comment:=node.Comment)
  701.  
  702.                    End If
  703.  
  704.                Next entry
  705.  
  706.            End Using ' resX
  707.  
  708.        Catch ex As Exception
  709.            Throw
  710.  
  711.        Finally
  712.            If resX IsNot Nothing Then
  713.                resX.Close()
  714.            End If
  715.  
  716.        End Try
  717.  
  718.    End Function
  719.  
  720.    ''' <summary>
  721.    ''' Removes a resource by the specified name from the .Net managed resource file.
  722.    ''' </summary>
  723.    ''' <param name="name">The resource name.</param>
  724.    ''' <param name="stringComparison">The <see cref="StringComparison"/> to compare the resource name.</param>
  725.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  726.    ''' <exception cref="System.ArgumentException">Any resource found matching the specified name.;name</exception>
  727.    Public Sub RemoveResource(ByVal name As String,
  728.                              Optional ByVal stringComparison As StringComparison =
  729.                                             StringComparison.OrdinalIgnoreCase)
  730.  
  731.        If Not File.Exists(Me.filePath1) Then
  732.            Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
  733.            Exit Sub
  734.        End If
  735.  
  736.        If Me.FindResource(name, stringComparison) Is Nothing Then
  737.            Throw New ArgumentException("Any resource found matching the specified name.", "name")
  738.            Exit Sub
  739.        End If
  740.  
  741.        Dim resources As New List(Of ResXDataNode)
  742.        Dim resX As ResXResourceReader = Nothing
  743.        Dim resXWritter As ResXResourceWriter = Nothing
  744.  
  745.        Try
  746.            resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
  747.            Using resX
  748.  
  749.                For Each entry As DictionaryEntry In resX
  750.  
  751.                    If Not entry.Key.ToString.Equals(name, stringComparison) Then
  752.  
  753.                        Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)
  754.                        resources.Add(New ResXDataNode(name:=node.Name, value:=node.GetValue(DirectCast(Nothing, ITypeResolutionService))) With {.Comment = node.Comment})
  755.  
  756.                    End If
  757.  
  758.                Next entry
  759.  
  760.            End Using
  761.  
  762.            ' Add the resource in the ResX file.
  763.            ' Note: This will replace the current ResX file.
  764.            resXWritter = New ResXResourceWriter(Me.filePath1)
  765.            Using resXWritter
  766.  
  767.                ' Add the retrieved resources into the ResX file.
  768.                If resources IsNot Nothing Then
  769.                    For Each resourceItem As ResXDataNode In resources
  770.                        resXWritter.AddResource(resourceItem)
  771.                    Next resourceItem
  772.                End If
  773.  
  774.                resXWritter.Generate()
  775.  
  776.            End Using ' resXWritter
  777.  
  778.        Catch ex As Exception
  779.            Throw
  780.  
  781.        Finally
  782.            If resX IsNot Nothing Then
  783.                resX.Close()
  784.            End If
  785.  
  786.            If resXWritter IsNot Nothing Then
  787.                resXWritter.Close()
  788.            End If
  789.  
  790.            resources.Clear()
  791.  
  792.        End Try
  793.  
  794.    End Sub
  795.  
  796. #End Region
  797.  
  798. #Region " Private Methods "
  799.  
  800.    ''' <summary>
  801.    ''' Adds or replaces a resource into the .Net managed resource file.
  802.    ''' </summary>
  803.    ''' <param name="replace">if set to <c>true</c>, the resource will be replaced.</param>
  804.    ''' <param name="name">The resource name.</param>
  805.    ''' <param name="data">The resource data.</param>
  806.    ''' <param name="comment">The resource comment.</param>
  807.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  808.    ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
  809.    Private Sub AddResource(ByVal replace As Boolean,
  810.                            ByVal name As String,
  811.                            ByVal data As Object,
  812.                            ByVal comment As String)
  813.  
  814.        If Not File.Exists(Me.filePath1) Then
  815.            Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
  816.            Exit Sub
  817.        End If
  818.  
  819.        Dim resources As New List(Of ResXDataNode)
  820.        Dim resX As ResXResourceReader = Nothing
  821.        Dim resXWritter As ResXResourceWriter = Nothing
  822.  
  823.        Try
  824.            resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
  825.            Using resX
  826.  
  827.                For Each entry As DictionaryEntry In resX
  828.  
  829.                    If Not replace AndAlso entry.Key.ToString.Equals(name, StringComparison.OrdinalIgnoreCase) Then
  830.                        Throw New ArgumentException("A resource with the same name already exists in the table.", "name")
  831.  
  832.                    Else
  833.                        Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)
  834.                        resources.Add(New ResXDataNode(name:=node.Name, value:=node.GetValue(DirectCast(Nothing, ITypeResolutionService))) With {.Comment = node.Comment})
  835.  
  836.                    End If
  837.  
  838.                Next entry
  839.  
  840.            End Using
  841.  
  842.            ' Add the resource in the ResX file.
  843.            ' Note: This will replace the current ResX file.
  844.            resXWritter = New ResXResourceWriter(Me.filePath1)
  845.            Using resXWritter
  846.  
  847.                ' Add the retrieved resources into the ResX file.
  848.                If resources IsNot Nothing Then
  849.                    For Each resourceItem As ResXDataNode In resources
  850.                        resXWritter.AddResource(resourceItem)
  851.                    Next resourceItem
  852.                End If
  853.  
  854.                ' Add the specified resource into the ResX file.
  855.                resXWritter.AddResource(New ResXDataNode(name, data) With {.Name = name, .Comment = comment})
  856.                resXWritter.Generate()
  857.  
  858.            End Using ' resXWritter
  859.  
  860.        Catch ex As Exception
  861.            Throw
  862.  
  863.        Finally
  864.            If resX IsNot Nothing Then
  865.                resX.Close()
  866.            End If
  867.  
  868.            If resXWritter IsNot Nothing Then
  869.                resXWritter.Close()
  870.            End If
  871.  
  872.            resources.Clear()
  873.  
  874.        End Try
  875.  
  876.    End Sub
  877.  
  878.    ''' <summary>
  879.    ''' Gets all the resources contained in the .Net managed resource file.
  880.    ''' </summary>
  881.    ''' <returns>IEnumerable(Of Resource).</returns>
  882.    Private Iterator Function GetResources() As IEnumerable(Of Resource)
  883.  
  884.        ' Read the ResX file.
  885.        Using resX As New Resources.ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
  886.  
  887.            For Each entry As DictionaryEntry In resX
  888.  
  889.                Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)
  890.  
  891.                Yield New Resource(name:=node.Name,
  892.                                   data:=node.GetValue(DirectCast(Nothing, ITypeResolutionService)),
  893.                                   comment:=node.Comment)
  894.  
  895.            Next entry
  896.  
  897.        End Using ' resX
  898.  
  899.    End Function
  900.  
  901. #End Region
  902.  
  903. #Region " Hidden Methods "
  904.  
  905.    ''' <summary>
  906.    ''' Determines whether the specified System.Object instances are considered equal.
  907.    ''' </summary>
  908.    <EditorBrowsable(EditorBrowsableState.Never)>
  909.    Public Shadows Function Equals(ByVal obj As Object) As Boolean
  910.        Return MyBase.Equals(obj)
  911.    End Function
  912.  
  913.    ''' <summary>
  914.    ''' Serves as a hash function for a particular type.
  915.    ''' </summary>
  916.    <EditorBrowsable(EditorBrowsableState.Never)>
  917.    Public Shadows Function GetHashCode() As Integer
  918.        Return MyBase.GetHashCode
  919.    End Function
  920.  
  921.    ''' <summary>
  922.    ''' Gets the System.Type of the current instance.
  923.    ''' </summary>
  924.    ''' <returns>The exact runtime type of the current instance.</returns>
  925.    <EditorBrowsable(EditorBrowsableState.Never)>
  926.    Public Shadows Function [GetType]() As Type
  927.        Return MyBase.GetType
  928.    End Function
  929.  
  930.    ''' <summary>
  931.    ''' Returns a String that represents the current object.
  932.    ''' </summary>
  933.    <EditorBrowsable(EditorBrowsableState.Never)>
  934.    Public Shadows Function ToString() As String
  935.        Return MyBase.ToString
  936.    End Function
  937.  
  938. #End Region
  939.  
  940. End Class
5199  Programación / Scripting / Re: Batch, ¿Software libre? en: 1 Junio 2015, 13:11 pm
¿Qué tendrá que ver Batch, con el Malware?, ¿Malware desarrollado en Batch... Bombas lógicas?, Batch nada tiene que ver con los virus de verdad. ( Intenta publicar futuras dudas sobre Scripting en la sección apropiada. )

Batch con el software libre tampoco tiene nada que ver, de hecho, Batch no tiene que ver con nada, es un lenguaje aislado de los demás (el patito feo), una herramienta manca e inutil para cualquier propósito del programador corriente.

Si empaquetas un script del que tú eres el autor (ya sea .bat, .py, .rb, o el que sea, un archivo de texto plano) y distribuyes ese .exe, estás ligado a la licencia + los términos y condiciones del software que utilizaste para empaquetar, si es de licencia libre, pues estás distribuyendo software libre.

Para determinar en que lenguaje ha sido desarrollado un binario puedes analizar las secciones del formato PE (Portable Executable), hay herramientas cómo PeID y TridNet que llevan a cabo esta tarea con una base de firmas para disminuir el porcentaje de error de la comprobación.

Saludos!
5200  Sistemas Operativos / Windows / Re: [Ayuda] Error al re-instalar Windows 7 en: 1 Junio 2015, 06:34 am
Es extraño que la instalación de Windows te de ese error, ya que el mínimo real de espacio requerido por la instalación son alrededor de 12 GB que es lo que ocupa el sistema de archivos de Windows en su totalidad (dependiendo de si instalas o no actualizaciones, y de si estás utilizando una versión modificada/capada de Windows),
el mínimo recomendado por Microsoft para Windows 7 de 32 Bits son 16 GB, y para Windows 7 de 64 Bits son 20 GB, por lo tanto no debería darte problemas con una partición de 30 GB cómo indicas.

Windows 7 system requirements

Yo, cuando instalo una máquina Virtual con Windows 7/8.1 x64, se instala perfectamente con tan solo 20 GB de espacio libre,
pero eso en una máquina virtual, para un disco físico es una muy mala idea instalar Windows 7 con solo 30 GB de espacio como estás intentando, ya que un tercio se lo come la instalación de Windows, el otro tercio se lo comen los programas que instales y todos los archivos temporales generados por dichos programas y por los servicios de Windows cómo el Prefetch o los puntos de restauración de sistema, o el pagefile, etc, así que te quedará un tercio o menos de espacio para tus cosas con lo que te vas a sentir muy limitado ...por no decir que en todo momento es recomendable y se precisa entre un 15%-20% de espacio libre para que el S.O vaya fluido al evitar el exceso de fragmentación del sistema de archivos, así que yo te recomendaría que lo instalases cómo te ha comantado @Saberuneko con un mínimo de +60 GB de espacio libre.

Te sugiero utilizar la aplicación Partition Wizard (hay varias con el mismo nombre, me refiero a la de MiniTool) para redimensionar el tamaño de la partición de forma sencilla e intuitiva.

MiniTool Partition Wizard

Saludos!
Páginas: 1 ... 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 [520] 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines