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

 

 


Tema destacado: Como proteger una cartera - billetera de Bitcoin


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [SRC] Cargar Idioma desde BD "SharpDevelop 2.2 & SQLite"
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [SRC] Cargar Idioma desde BD "SharpDevelop 2.2 & SQLite"  (Leído 3,047 veces)
Maurice_Lupin


Desconectado Desconectado

Mensajes: 356

GPS


Ver Perfil WWW
[SRC] Cargar Idioma desde BD "SharpDevelop 2.2 & SQLite"
« en: 5 Mayo 2012, 23:52 pm »

Me base en un ejemplo de vb6 que encontre con google:
http://www.recursosvisualbasic.com.ar/htm/trucos-codigofuente-visual-basic/227-aplicacion-multilenguaje-con-ado.htm

Adapte el codigo a vb.net con el framework 2.0 y SQLite

Herramientas:

-   Sharpdevelop 2.2 para el .NET Framework 2.0
-   SQLite-1.0.66.0 (driver Ado.net 2.0)

Links:

http://www.icsharpcode.net/OpenSource/SD/Download/

SQLite-1.0.66.0-setup (descarguen el Setup)
http://sourceforge.net/projects/sqlite-dotnet2/files/SQLite%20for%20ADO.NET%202.0/1.0.66.0/

Una vez instalado sólo hay que Referenciar la DLL "System.Data.SQLite.dll" al proyecto.



Al final dejo el link del proyecto.
Código
  1.    ' Metodo para cambiar la propiedad "Text"
  2.    ' a todos los controles del Form
  3.    Public Sub changeCaptions( Lista As Object)
  4. Dim myControl As Object
  5.  
  6. If (TypeOf(Lista) Is Form) Then
  7. setCaption( CType(lista, Form) )
  8. End If
  9.  
  10. If Not( (TypeOf(Lista) Is ToolStripButton) Or _
  11.    (TypeOf(Lista) Is ToolStripMenuItem) ) Then
  12. ' Labels, Buttons, Textboxs
  13. For Each myControl In Lista.Controls
  14. setCaption( myControl )
  15. changeCaptions( myControl)
  16. Next
  17. End If
  18.  
  19. If (TypeOf(Lista) Is ToolStrip) Or _
  20.   (TypeOf(Lista) Is MenuStrip) Then
  21. For Each myControl In Lista.Items
  22. If (TypeOf(myControl) Is ToolStripButton) Or _
  23.   (TypeOf(myControl) Is ToolStripMenuItem) Then
  24. setCaption( myControl )
  25. changeCaptions(myControl)
  26. End If
  27. Next
  28. End If
  29.  
  30. If (TypeOf(Lista) Is ToolStripMenuItem)
  31. For Each myControl In Lista.DropDownItems
  32. If (TypeOf(myControl) Is ToolStripMenuItem) Then
  33. setCaption( CType(myControl, ToolStripMenuItem) )
  34. changeCaptions(myControl)
  35. End If
  36. Next
  37. End If
  38.    End Sub
  39.  
  40.    Private Sub setCaption(ob As Object)
  41.     Dim texto As String = selectCaption(dt, ob.Name)
  42.     If texto <> "" Then
  43.     ob.Text = selectCaption(dt, ob.Name)
  44.     'msgbox( ob.Text )
  45.     End If    
  46.    End Sub
  47.  
  48.    Private Function selectCaption(dt As DataTable, nomC As String) As String
  49.     Dim s As String = ""    
  50.     Dim foundRows() As DataRow
  51. foundRows = dt.Select("NombreControl Like '" & nomC & "%'")
  52. If foundRows.Length = 1 Then s = BlobToString(foundRows(0).Item(2))  
  53. Return s
  54.    End Function  
  55.  

proyecto en google Docs

Saludos  ;D


« Última modificación: 5 Mayo 2012, 23:54 pm por Maurice_Lupin » En línea

Un error se comete al equivocarse.
Keyen Night


Desconectado Desconectado

Mensajes: 496


Nothing


Ver Perfil
Re: [SRC] Cargar Idioma desde BD "SharpDevelop 2.2 & SQLite"
« Respuesta #1 en: 6 Mayo 2012, 01:30 am »

Muy bueno, esto es necesario, nuestros programas tienen más oportunidad de progresar mientras más público tengan y eso es igual a tener la aplicación disponible en más lenguajes.

Hace tiempo necesite que una aplicación cubriera varios lenguajes, era por archivos locales, pero sigue el mismo principio; se basaba en un Diccionario String, String que como Key guardaba el nombre del control, como llegar a el y la propiedad a asignarle el Value del Diccionario, quiero decir, como que Key podría ser por ejemplo:

Form1\Contenedor\Button1*Text y Value Texto en Español

De modo que cuando se cargaba el Diccionario que estaba serializado en un archivo, se usaba Split para separar la ruta que lleva al control, usando Find desde la raíz hasta encontrar el Control deseado Form1.Find para obtener el control Contenedor y Contenedor.Find para obtener Button1 luego se asignaba con Reflection la propiedad Text.

Para los textos que no guardaban relación con un Control los guardaba con un Key #0001 por ejemplo y seguía #0002, #0003 de modo que al cargar el Diccionario y aplicar las propiedades se ignorara todo lo que comienza con #.

Tenía muchos Form e infinidad de Controles por lo qué me ayude con este código que generá el Diccionario:

Una que lista todos los controles de un Form y otra que le da el nombre al control en la forma que te mencione antes.

Código
  1.    Public Function GenerateTreeName(ByVal x As Control) As String
  2.  
  3.        GenerateTreeName = x.Name
  4.  
  5.        Do While x.Parent IsNot Nothing
  6.            x = x.Parent
  7.            GenerateTreeName = x.Name & "\" & GenerateTreeName
  8.        Loop
  9.  
  10.    End Function
  11.  
  12.    Public Function ListControls(ByVal x As Control) As List(Of Control)
  13.  
  14.        ListControls = New List(Of Control)
  15.  
  16.        Dim Parents As New List(Of Control)
  17.  
  18.        For Each y As Control In x.Controls
  19.            If y.HasChildren Then
  20.                Parents.Add(y)
  21.            End If
  22.            ListControls.Add(y)
  23.        Next
  24.  
  25.        For Each y As Control In Parents
  26.            ListControls.AddRange(ListControls(y))
  27.        Next
  28.  
  29.    End Function

Realmente me pareció la mejor forma y que resume código de manera increíble.


« Última modificación: 6 Mayo 2012, 02:10 am por Keyen Night » En línea

La Fé Mueve Montañas...
                                    ...De Dinero

La programación es más que un trabajo es más que un hobby es una pasión...
Maurice_Lupin


Desconectado Desconectado

Mensajes: 356

GPS


Ver Perfil WWW
Re: [SRC] Cargar Idioma desde BD "SharpDevelop 2.2 & SQLite"
« Respuesta #2 en: 6 Mayo 2012, 20:17 pm »

Keyen Night, mi problema fue que al intentar acceder a los elementos de un ToolStrip o MenuStrip utilizando el tipo Control me daba error.

La colección MenuStrip1.Controls no contiene los ToolStripMenuItem sino la colección MenuStrip1.Items, el error que me daba es que los ToolStripMenuItem no son del tipo Control.

Al menos que si hayas logrado acceder a los elementos de un MenuStrip o de un ToolStrip usando el tipo Control, me encantaria ver tu codigo  ;D

Saludos y gracias por el comentario.
En línea

Un error se comete al equivocarse.
Keyen Night


Desconectado Desconectado

Mensajes: 496


Nothing


Ver Perfil
Re: [SRC] Cargar Idioma desde BD "SharpDevelop 2.2 & SQLite"
« Respuesta #3 en: 6 Mayo 2012, 21:26 pm »

Eso me paso también con TabPageControl, eso ya está resuelto en código, es una Clase llamada LanguageFile, estructura y serializa las propiedades que tengas que almacenar en un archivos que contiene información del lenguaje, el autor, y la parte de los datos con contiene el diccionario serializado. Cuando se quiere cambiar de idioma se crea un objeto LanguageFile que apunta hacia un archivo '*.lng', se llama al Sub Apply, el diccionario se deserializa, y se recorre siguiendo el  cada control con Find a través de todos los Parent, una vez que lo encuentra, lee la parte que dice *PROPIEDAD y dependiendo el tipo, lee y asigna el Value del diccionario, de manera distinta, ya que en tiempo de ejecución Reflection te brinda todas las herramientas para jugar con las propiedades de forma no administrada.

Aquí está el código, coloco en la siguiente lista cosas que le faltarían hacerle que me han dado flojera :xD

Desventajas:
  • Obtener objetos Form por su nombre, por ahora se le debe decir a Apply cuales son los Form disponibles y su nombre.
  • Brindar soporte para todos los tipos de array, por ahora solo tiene para Columns y TabPages.

En Value '#D#' queda comprendido como un salto de línea.

Se podría hacer algo con Flags para saber cuando la propiedad a asignar es del tipo Array y tomar las precauciones al colocar Value como valor de la propiedad. Pero como por ahora no me ha servido para lo que quiero me ha dado flojera actualizarla :silbar:

Para el Caso del Tool/MenuStrip se podría crear un Flag especial de modo que en Apply se le trate de una forma particular, probablemente me pondré a hacer eso :laugh: de los Flags resultaría muy útil.

Código
  1. Imports System.Runtime.Serialization, System.IO
  2. Imports System.Globalization, System.Reflection
  3. Imports System.Runtime.Serialization.Formatters.Binary
  4. Imports System.Text
  5.  
  6. <Serializable()> _
  7. Public Class LanguageFile
  8.  
  9.    Implements ISerializable
  10.  
  11.    Public Event Applied()
  12.  
  13. #Region " Delegados "
  14.  
  15.    Public Delegate Sub SetProperty_Delegate( _
  16.                   ByVal ObjectControl As Control, _
  17.                   ByVal ObjectName As String, _
  18.                   ByVal ObjectValue As Object)
  19.  
  20.    Public Sub SetProperty( _
  21.                          ByVal ObjectControl As Control, _
  22.                          ByVal ObjectName As String, _
  23.                          ByVal ObjectValue As Object)
  24.        If ObjectControl.InvokeRequired Then
  25.            ObjectControl.Invoke(New SetProperty_Delegate(AddressOf SetProperty), _
  26.                                 New Object() {ObjectControl, ObjectName, ObjectValue})
  27.        Else
  28.            ObjectControl.GetType.GetProperty(ObjectName).SetValue( _
  29.                                              ObjectControl, _
  30.                                              ObjectValue, _
  31.                                              Nothing)
  32.        End If
  33.    End Sub
  34.  
  35.    Public Delegate Function GetProperty_Delegate( _
  36.                      ByVal ObjectControl As Control, _
  37.                      ByVal ObjectName As String) As Object
  38.  
  39.    Public Function GetProperty(ByVal ObjectControl As Control, _
  40.                          ByVal ObjectName As String) As Object
  41.        If ObjectControl.InvokeRequired Then
  42.            Return ObjectControl.Invoke(New GetProperty_Delegate(AddressOf GetProperty), _
  43.                                 New Object() {ObjectControl, ObjectName})
  44.        Else
  45.            Return ObjectControl.GetType.GetProperty(ObjectName).GetValue( _
  46.                                              ObjectControl, _
  47.                                              Nothing)
  48.        End If
  49.    End Function
  50.  
  51. #End Region
  52.  
  53. #Region " Private Fields "
  54.  
  55.    Private _
  56.    _ShortName As String, _
  57.    _Dic As Dictionary(Of String, String), _
  58.    _Author As String
  59.  
  60. #End Region
  61.  
  62. #Region " Serializable "
  63.  
  64.    Protected Sub GetObjectData(ByVal info As System.Runtime.Serialization.SerializationInfo, ByVal context As System.Runtime.Serialization.StreamingContext) Implements System.Runtime.Serialization.ISerializable.GetObjectData
  65.  
  66.        For Each x As FieldInfo In Me.GetType.GetFields(BindingFlags.NonPublic Or _
  67.                                                        BindingFlags.Instance)
  68.            If x.Name.StartsWith("_") Then
  69.                info.AddValue(x.Name, x.GetValue(Me))
  70.            End If
  71.        Next
  72.  
  73.        'info.AddValue("_ShortName", _ShortName)
  74.        'info.AddValue("_Author", _Author)
  75.        'info.AddValue("_Dic", _Dic)
  76.  
  77.    End Sub
  78.  
  79.    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
  80.  
  81.        For Each x As FieldInfo In Me.GetType.GetFields(BindingFlags.NonPublic Or _
  82.                                                        BindingFlags.Instance)
  83.            If x.Name.StartsWith("_") Then
  84.                x.SetValue(Me, info.GetValue(x.Name, x.FieldType))
  85.            End If
  86.        Next
  87.  
  88.        '_ShortName = info.GetValue("_ShortName", GetType(String))
  89.        '_Author = info.GetValue("_Author", GetType(String))
  90.        '_Dic = info.GetValue("_Dic", GetType(Dictionary(Of String, String)))
  91.  
  92.    End Sub
  93.  
  94. #End Region
  95.  
  96. #Region " Public Constructors "
  97.  
  98.    Public Sub New(ByVal Buffer As Byte())
  99.  
  100.        If Buffer.Length > (1024 ^ 2) Then
  101.            Throw New OverflowException()
  102.        Else
  103.            Dim MStream As New MemoryStream
  104.  
  105.            MStream.Write(Buffer, 0, Buffer.Length)
  106.  
  107.            MStream.Seek(0, SeekOrigin.Begin)
  108.  
  109.            Dim BFormatter As New BinaryFormatter
  110.  
  111.            Dim [Me] As LanguageFile = BFormatter.Deserialize(MStream)
  112.  
  113.            MStream.Close()
  114.            MStream.Dispose()
  115.            MStream = Nothing
  116.  
  117.            _Dic = [Me]._Dic
  118.            _ShortName = [Me]._ShortName
  119.            _Author = [Me].Author
  120.  
  121.            Erase Buffer
  122.  
  123.        End If
  124.  
  125.    End Sub
  126.  
  127.    Public Sub New(ByVal LanguageFile As String)
  128.  
  129.        If File.Exists(LanguageFile) Then
  130.            Dim LF As New FileInfo(LanguageFile)
  131.            If LF.Length > (1024 ^ 2) Then
  132.                Throw New OverflowException(LanguageFile)
  133.            Else
  134.                Dim MStream As New MemoryStream
  135.                Dim FStream As New FileStream(LanguageFile, FileMode.Open, FileAccess.Read)
  136.                Dim FBuffer As Byte() = New Byte(LF.Length - 1) {}
  137.  
  138.                FStream.Read(FBuffer, 0, LF.Length)
  139.  
  140.                FStream.Close()
  141.                FStream.Dispose()
  142.                FStream = Nothing
  143.  
  144.                MStream.Write(FBuffer, 0, FBuffer.Length)
  145.                MStream.Seek(0, SeekOrigin.Begin)
  146.  
  147.                Dim BFormatter As New BinaryFormatter
  148.  
  149.                Dim [Me] As LanguageFile = BFormatter.Deserialize(MStream)
  150.  
  151.                MStream.Close()
  152.                MStream.Dispose()
  153.                MStream = Nothing
  154.  
  155.                _Dic = [Me]._Dic
  156.                _ShortName = [Me]._ShortName
  157.                _Author = [Me].Author
  158.  
  159.                Erase FBuffer
  160.  
  161.            End If
  162.        Else
  163.            Throw New FileNotFoundException(LanguageFile)
  164.        End If
  165.  
  166.    End Sub
  167.  
  168.    Public Sub New(ByVal LanguageFile As String, _
  169.                   ByVal Dic As Dictionary(Of String, String), _
  170.                   ByVal ShortName As String, _
  171.                   ByVal Author As String)
  172.        _Dic = Dic
  173.        _ShortName = ShortName
  174.        _Author = Author
  175.  
  176.        Dim FStream As New FileStream(LanguageFile, FileMode.Create, FileAccess.Write)
  177.        Dim MStream As New MemoryStream
  178.        Dim BFormatter As New BinaryFormatter
  179.        Dim FBuffer As Byte()
  180.  
  181.        BFormatter.Serialize(MStream, Me)
  182.  
  183.        FBuffer = New Byte(MStream.Length - 1) {}
  184.  
  185.        MStream.Seek(0, SeekOrigin.Begin)
  186.  
  187.        MStream.Read(FBuffer, 0, MStream.Length)
  188.  
  189.        MStream.Close()
  190.        MStream.Dispose()
  191.        MStream = Nothing
  192.  
  193.        FStream.Write(FBuffer, 0, FBuffer.Length)
  194.  
  195.        FStream.Close()
  196.        FStream.Dispose()
  197.        FStream = Nothing
  198.  
  199.        Erase FBuffer
  200.  
  201.    End Sub
  202.  
  203. #End Region
  204.  
  205. #Region " ReadOnly Properties "
  206.  
  207.    Public ReadOnly Property GetString() As Dictionary(Of String, String)
  208.        Get
  209.            Return _Dic
  210.        End Get
  211.    End Property
  212.  
  213.    Public ReadOnly Property Author() As String
  214.        Get
  215.            Return _Author
  216.        End Get
  217.    End Property
  218.  
  219.    Public ReadOnly Property Culture() As CultureInfo
  220.        Get
  221.            Return New CultureInfo(_ShortName)
  222.        End Get
  223.    End Property
  224.  
  225. #End Region
  226.  
  227. #Region " Public Sub "
  228.  
  229.    Public Sub Apply()
  230.  
  231.        For Each x As KeyValuePair(Of String, String) In _Dic
  232.            If Not x.Key.StartsWith("#") Then
  233.  
  234.                Dim Tree As String = x.Key.Split("*")(0)
  235.                Dim PropertyName As String = x.Key.Split("*")(1)
  236.                Dim Controls As String() = Tree.Split("\")
  237.                Dim CurrentControl As Control = Nothing
  238.  
  239.                If Controls.Length = 1 Then
  240.                    Select Case Controls(0)
  241.                        Case "Form1"
  242.                            'SetProperty(Form1, PropertyName, x.Value)
  243.                        Case "Form2"
  244.                            'SetProperty(Form2, PropertyName, x.Value)
  245.                    End Select
  246.                Else
  247.                    Select Case Controls(0)
  248.                        Case "Form1"
  249.                            'CurrentControl = Form1
  250.                        Case "Form2"
  251.                            'CurrentControl = Form2
  252.                    End Select
  253.                    For y As Integer = 1 To Controls.Length - 1
  254.                        CurrentControl = CurrentControl.Controls.Find(Controls(y), False)(0)
  255.                    Next
  256.                    If PropertyName.StartsWith("Columns") Then
  257.                        Dim Index As Integer = PropertyName.Replace("Columns(", "").Replace(")", "")
  258.                        CType(GetProperty(CurrentControl, "Columns")(Index), ColumnHeader).Text = x.Value
  259.                    ElseIf PropertyName.StartsWith("TabPages") Then
  260.                        Dim Index As Integer = PropertyName.Replace("TabPages(", "").Replace(")", "")
  261.                        CType(GetProperty(CurrentControl, "TabPages")(Index), TabPage).Text = x.Value
  262.                    Else
  263.                        SetProperty(CurrentControl, PropertyName, x.Value.Replace("#D#", Environment.NewLine))
  264.                    End If
  265.                End If
  266.  
  267.            End If
  268.        Next
  269.  
  270.        RaiseEvent Applied()
  271.  
  272.    End Sub
  273.  
  274. #End Region
  275.  
  276. End Class
« Última modificación: 6 Mayo 2012, 22:22 pm por Keyen Night » En línea

La Fé Mueve Montañas...
                                    ...De Dinero

La programación es más que un trabajo es más que un hobby es una pasión...
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
"""BUSCO EJEMPLO VB PARA ENVIAR MAILS""""
Programación Visual Basic
gera 1 6,291 Último mensaje 1 Septiembre 2005, 00:14 am
por programatrix
De donde puedo descargar utilidades: "Formas", "Estilos", "Motivos", D
Diseño Gráfico
Ad0nis 2 8,274 Último mensaje 2 Septiembre 2006, 15:48 pm
por Ad0nis
[Ayuda] modificar "start page" en "internet explorer" con "batch"
Scripting
taton 7 16,536 Último mensaje 20 Septiembre 2006, 01:45 am
por taton
No logro cargar "php_mysql.dll" con PHP5
PHP
Nigtz 0 2,288 Último mensaje 22 Junio 2008, 15:53 pm
por Nigtz
recursos visual basic, """"""proceso inmortal"""""
Análisis y Diseño de Malware
Dark4ngel 7 13,206 Último mensaje 3 Noviembre 2011, 10:42 am
por Dark4ngel
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines