‘Flag Attribute for Enum’s

        

// Utilizar VStudio 2010 Beta 2, con este código.

‘// El propósito de este código es mostrar el uso 
‘// de los indicadores de enumeraciones utilizando
‘// conversiones hexadecimales (por ejemplo!).
‘//
‘// (c)(r) 🙂 PepLluis 2009

‘// Para entender este ejemplo, imagina que
‘// necesitas controlar algún dispositivo, ya sea
‘// a través de Ethernet, USB o Puerto Serie, para
‘// Supervisar or controlar las operaciones de
‘// paro o marcha, trabando solo con dos bytes…
‘// el primero de ellos mapeando los bits de
‘// salida y el segundo los de entrada, después
‘// de esto solo necesitaras enviar el byte de
‘// salida al dispositivo o supervisar la entrada
‘// cuando se produzca un cambio en su valor.

‘// Este ejemplo además muestra el uso de
‘// la continuación implícita de línea y los
‘// inicializadores para poder añadir todos los
‘// Controles necesarios en el form, en un solo
‘// golpe.
.

‘// Los comentarios y el código están en Ingles
‘// por tema de difusión, no dudes en pedírmelos
‘// en Castellano, si lo consideras oportuno

‘// Test this code with Visual Studio 2010 Beta 2.

‘// the purpose of this code is just show and play ‘// with flag’s enumerations and play using
‘// hexadecimals conversions.
‘//
‘// (C)(R) 🙂 PepLluis 2009

‘// To understand this sample… imagine you need
‘// control some devices using Ethernet, USB or
‘// Serial Ports to supervise and set/reset their
‘// status with start/stop operations, just two
‘// bytes… the first one to map input bits
‘// and the second to map output bits, after
‘// this you only need send output byte to device
‘// or supervise received byte when value change.

‘// this sample also show how use implicit line
‘// continuation and initializers to add controls
‘// in one shot in load event (for example).

 

 

Y aqui el Codigo…

‘Define input channel
<FlagsAttribute()> Public Enum InputChannel
    PowerAlarm = 1
    LowVoltage = 2
    HighVoltage = 4
    OverCurrent = 8
    PowerGood = 16
    ShortCircuit = 32
    WithoutLoad = 64
    OutOfService = 128
End Enum

» Define output channel
<FlagsAttribute()> Public Enum OutputChannel
    Engine_Axis1 = 1
    Engine_Axis2 = 2
    Engine_Axis3 = 4
    Smoke_Vent = 8
    Refrigerator = 16
    Blast_Furnace = 32
    TransPort_Belt = 64
    Emergency_Stop = 128
End Enum

‘// You can add dynamically items to enum and no changes are needed inside code… just rebuild

Public Class FlagsEnumerationSample
    Private Sub When_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ‘Title
        Me.Text = «Playing with Flag’s Enum’s»
        ‘Add all labels and textbox in one shot
        Me.Controls.AddRange({New Label With {.Name = «lblHexcaptn»,
                                              .AutoSize = True,
                                              .Location = New Point(5, 10),
                                              .Text = «Output Value:»},
                              New Label With {.Name = «lblHexValue»,
                                              .AutoSize = True,
                                              .Location = New Point(75, 10),
                                              .Text = «0x00», .Height = 20},
                              New Label With {.Name = «lblInputVal»,
                                              .AutoSize = True,
                                              .Location = New Point(140, 10),
                                              .Text = «Input Value : 0x»},
                              New TextBox With {.Name = «txtInputVal»,
                                                .MaxLength = 2,
                                                .Width = 20,
                                                .Location = New Point(220, 8),
                                                .Text = «00»}
                            })

        ‘Add one customized button for every item in enumeration
        Dim NextPos As Integer = 30                                             ‘Point for this button (30=initial top pos)
        For Each elem In [Enum].GetValues(GetType(OutputChannel))               ‘iterate output enum
            Me.Controls.Add(New CustomButton(New Point(20, NextPos), elem))     ‘add new button with new point position for elem
            AddHandler Me.Controls(elem.ToString).Click, AddressOf OutPutOnOff  ‘When button is click put output on/off
            NextPos += Me.Controls(elem.ToString).Height                        ‘Calculate next point location for next elem
        Next

        NextPos = 30                                                            ‘Initial top pos for first element
        For Each elem In [Enum].GetValues(GetType(InputChannel))                ‘Iterate input enum
            Me.Controls.Add(New CustomLabel(New Point(160, NextPos), elem))     ‘Add customized label for any bit input in enum
            NextPos += Me.Controls(elem.ToString).Height                        ‘Calculate location for next label
        Next
        ‘Simulate input value… refresh labels when textbox value change
        AddHandler Me.Controls(«txtInputVal»).TextChanged, AddressOf InputsOnOff

        Me.Height = NextPos + 50                                                ‘Fix form height, after last control + 50
    End Sub

    Private Outputs As Byte = 0                                                 ‘Output channel (Byte)
   
    ‘Change On/Off output bit status of sender
    ‘remark : TAG property of button is used as bit weight
    Sub OutPutOnOff(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If Outputs And CType(sender, Button).Tag Then                           ‘Flic /Flac output bit
            Outputs = Outputs Xor CType(sender, Button).Tag                     ‘Set Off if On
            sender.BackColor = Color.GreenYellow                                ‘GreenYellow if Off
        Else
            Outputs = Outputs Or CType(sender, Button).Tag                      ‘Set On if Off
            sender.BackColor = Color.Red                                        ‘Reed if On
        End If
        Me.Controls(«lblHexValue»).Text = «0x» + Hex(Outputs)
    End Sub

    Private Inputs As Byte? = 0                                                 ‘Input channel (Byte)
    ‘Change color of label when bit is On or Off
    ‘remark : TAG property of label is used as bit weight
    Sub InputsOnOff()
        Try
            Inputs = «&h0» + Me.Controls(«txtInputVal»).Text                    ‘Read & convert text as Hex value
        Catch ex As Exception
            Me.Controls(«txtInputVal»).Text = «»                                ‘Wrong format… clear textbox
        End Try

        For Each Elem In [Enum].GetNames(GetType(InputChannel))                 ‘for each item in enum
            If Inputs And CType(Me.Controls(Elem), Label).Tag Then              ‘Red Color if bit is On, Green if off
                Me.Controls(Elem).BackColor = Color.Red
            Else
                Me.Controls(Elem).BackColor = Color.GreenYellow
            End If
        Next
    End Sub
End
Class


‘ Just My customizes Button to select and display outputs
Class CustomButton
    Inherits Button
   
    ‘ Create using
       _location inside form
       _elem     particular item of enumeration
    Sub New(ByVal _location As Point, ByVal _elem As [Enum])
        Me.Tag = CType(_elem, OutputChannel)                    ‘My Bit weight
        Me.Name = _elem.ToString                                ‘My Name
        Me.Text = Me.Name                                       ‘Name to Show
        Me.Width = 100                                          ‘Wide
        Me.Location = _location                                 ‘Set Position
        Me.BackColor = Color.GreenYellow                        ‘Initial Color
    End Sub
End
Class


‘ Just My customized Label to display Inputs
Class CustomLabel
    Inherits Label
   
    ‘ Create using
       _location pos inside form
       _elem     particular item of enumeration
    Sub New(ByVal _location As Point, ByVal _elem As [Enum])
        Me.Tag = CType(_elem, InputChannel)                     ‘My Bit weight
        Me.Name = _elem.ToString                                ‘My Name
        Me.Text = Me.Name                                       ‘Name to Show
        Me.Width = 100                                          ‘Wide
        Me.Location = _location                                 ‘Position
        Me.TextAlign = ContentAlignment.MiddleCenter            ‘Align
        Me.BackColor = Color.GreenYellow                        ‘Initial color
        Me.BorderStyle = Windows.Forms.BorderStyle.FixedSingle  ‘Set Border
    End Sub
End
Class

Salud,
Pep Lluis,

Enumerando el uso de las enumeraciones

‘ A menudo dejamos de utilizar las enumeraciones por falta de comprensión.

‘ Recibo algunas preguntas en tanto a cómo utilizarlas, el presente ejemplo intenta
‘ clarificar su uso, así como dar algunas perspectivas nuevas, dando a conocer
‘ algunas características poco conocidas.

‘ Por definición, una enumeración corresponde a una integral asociada a un contenido como constante

‘ En la Sub New, destacar…
   .destacar como en ‘Nombres’ obtenemos el tipo de la enumeración ‘Electrodomésticos’
   .el uso de [enum].GetNames en forma de array para añadir todos los ítems sin necesidad de iteraciones
   .Para hacer mas legible el código utilizando una expresión declarativa de la misma

   .Identificar su correspondencia

 

‘ Si mañana tengo una escapada hablaremos del atributo para uso como flag : <FlagsAttribute>

Class EnumeracionSimple
    Inherits Form

    Enum Electrodomesticos
        Horno
        Nevera
        Encimera
        Campana
        Batidora
        Plancha
        Secadora
        Balanza
    End Enum

    Sub New()
        AñadirComboConEnumeracion() ‘Un combo con los ítems de la enumeración
        CodigoMasLeible(7)
        Identificando(2)

    End Sub

 

    ‘Un combo con los ítems de la enumeración
    Sub AñadirComboConEnumeracion()
        ‘Al crear la clase
        Dim MiCombo As New ComboBox               ‘Crear ComboBox
        Dim Nombres = GetType(Electrodomesticos)  ‘Obtener el tipo de la enum
        ‘Un combobox con toda la enumeración
        MiCombo.Items.AddRange([Enum].GetNames(Nombres).ToArray)    ‘Añadir todos sus nombres
        MiCombo.Dock = DockStyle.Fill                               ‘Dock
        Me.Controls.Add(MiCombo)                                    ‘Añadir el Combo al Form
    End Sub

    ‘Clarificando cada caso en la selección
    Sub CodigoMasLeible(ByVal Seleccion As Integer)
        Select Case Seleccion
            Case Electrodomesticos.Balanza
                MsgBox(«Hola desde Balanza»)
            Case Electrodomesticos.Batidora
                MsgBox(«Hola desde Batidora»)
            Case Electrodomesticos.Encimera
                MsgBox(«Hola desde Encimera»)
        End Select
    End Sub

    ‘Identificando la selección
    Sub Identificando(ByVal Electodomestico As Integer)
        MessageBox.Show(«Su nombre es  : « + CType(Electodomestico, Electrodomesticos).ToString)
    End Sub
End
Class

Lisa Feigenbaum :: [WEBCAST] A Lap around Visual Basic in Visual Studio 2010

Come learn about what’s coming in the next release of Visual Basic. Code faster with language features like implicit line continuation, auto-implemented properties, statement lambdas, interoperability with dynamic languages, simplified Office application deployment, and more! Understand, navigate, and test code more easily than ever with the latest code-focused tools. Take advantage of multi-monitor support, zoom, and rich extensibility in the newly designed IDE. In this demo-packed session, we’ll show how to use all of these new capabilities to boost your development experience with Visual Studio 2010!

Bio:
Lisa Feigenbaum is a Community Program Manager for Visual Studio Managed Languages. She has been a member of the Visual Basic team since 2004. Before her current role, Lisa was the Program Manager for the Visual Basic Editor and Debugger. You can find Lisa on Channel9 or read her posts on the VB team blog http://blogs.msdn.com/vbteam. Before joining Microsoft, Lisa earned an M.Sc. and B.A. in Applied Mathematics from Harvard University.

NOTA: Para los que no podais asistir al CodeCamp aclarar que esta sesión será un comunicación online con Redmond y se hará en inglés.
Nivel: 200

On : 18th October 2009, 17:15PM (GMT+1)
Toll free: +1 (866) 500-6738
Toll: +1 (203) 480-8000
Participant code: 3116969
Attendee URL:  https://www.livemeeting.com/cc/microsoft/join?id=MeetLisa&role=attend&pw=Attend

 World Wide Access Telephone Numbers
Spain, Madrid Microsoft IT 91 391 98 00 

 

Interview – Lisa Feigenbaum – Entrevista (Visual Basic, C# & Visual Studio 2010)

        

Este verano Octavio Hernández (C# MVP) y Pep Lluis Bano (VB MVP ) tuvimos la suerte de entrevistar a Lisa para un artículo publicado en la revista DotNetMania. El texto en español está disponible como un archivo adjunto al final de este post, así como en el resumen.

This past summer I was interviewed by C# MVP Octavio Hernandez and VB MVP Pep Lluis Bano for an article that was published in the Spanish magazine DotNetMania . The Spanish text is available as an attachment at the end of this post, as well as in summary.

 

 

Click : Interview on Visual Basic and C# in Visual Studio with DotNetMania

Que lo disfruteis!
Pep Lluis,

Un Listado muy chapado a la antigua

Muchos de los que nos acostumbramos al uso de ‘Printer.Print’ en visual Basic 6, padecemos de ciertas dificultades para adaptarnos al nuevo uso de ‘PrintDocument’.

Con la intención de responder a numerosas preguntas sobre el tema y facilitar esas transiciones que finalmente nos aportan un montón de beneficios, me complace compartir con vosotros este pequeño ejemplo de cómo generar un listado usando el ‘moderno’ PrintDocument, dandole un estilo muy chapado a la antigua J.

Espero que os sea útil!

©Pep Lluis

‘Este ejemplo se ha compilado con la versión Beta 1 del compilador FW 4.0, aunque no tendréis dificultad alguna en adaptar el concepto a cualquier versión anterior del framework.

Imports System.Drawing.Printing

Public Class Form1
    ‘Crear el PrintDocument
    Private ListadoDeArticulos As New PrintDocument
    ‘Simulación tabla de Artículos
    Private Articulos As New DataTable(«Articulos»)

    Private Sub Form1_Load() Handles MyBase.Load

        ‘Función de imprimir paginas
        AddHandler ListadoDeArticulos.PrintPage, AddressOf Me.ImprimirListado

       
        ‘ Simular tabla Artículos
       
        Articulos.Columns.Add(«Codigo»)
        Articulos.Columns.Add(«Descripcion»)
        Articulos.Columns.Add(«Precio»)
        Articulos.Rows.Add(«001», «Resistencia 100ohms», «0,15»)
        Articulos.Rows.Add(«002», «Transistor 2n2234», «1,00»)
        Articulos.Rows.Add(«003», «Microprocesador Z80», «5,40»)
        Articulos.Rows.Add(«004», «UART 16C450», «3,45»)
        Articulos.Rows.Add(«005», «Resistencia 200ohms», «0,12»)
        Articulos.Rows.Add(«006», «Transistor 2n2222», «1,22»)
        

       ‘ Lanzar la ejecución del listado
        ListadoDeArticulos.Print()

    End Sub

 

    ‘Seleccionar la fuente para el listado
    Dim Fuente_Pagina As New Font(«Lucida Console», 10)
    ‘Fijar los márgenes Derecho / Izquierdo
    Dim Margen_Izquierdo As Single = 0
    Dim Margen_Superior As Single = 0
    ‘Controlar la posición Vertical/NºPagina
    Dim PosicionLinea As Single = 0
    Dim ContadorLinea As Single = 0
    Dim Numero_Pagina As Single = 1
    ‘Memorizar la posición en curso dentro del Dataset
    Dim Puntero As Single = 0

   
    ‘ Imprimir el Listado de Artículos
   
    Sub ImprimirListado(ByVal sender As Object, ByVal Pagina As PrintPageEventArgs)

        ‘Ajustes para el Control de Pagina
        Dim Lineas_Pagina As Single = Pagina.MarginBounds.Height / Fuente_Pagina.GetHeight(Pagina.Graphics)
        ContadorLinea = 0
        Margen_Izquierdo = Pagina.MarginBounds.Left
        Margen_Superior = Pagina.MarginBounds.Top

        ‘Cabecera del Listado
        ImprimirUnaLinea(Pagina, «Electronica NAVI»)
        ImprimirUnaLinea(Pagina, «Listado de Artículos sin ningún orden ni concierto»)
        ImprimirUnaLinea(Pagina, «Vic (Barcelona) a fecha : « + DateTime.Now + » ,Pagina : « + Numero_Pagina.ToString)
        ImprimirUnaLinea(Pagina, «»)
        ImprimirUnaLinea(Pagina, «Código Descripción                                               Precio»)
        ImprimirUnaLinea(Pagina, «—— ——————————————————— ——–«)
        Dim Articulo As DataRow
        Dim Linea As String = Space(80)
       
        ‘Recorrer la tabla de artículos / imprimir una línea por fila
        For Indice As Single = Puntero To Articulos.Rows.Count – 1
            Articulo = Articulos.Rows(Indice)
            If ContadorLinea < Lineas_Pagina Then
                ‘posicionar la columna según item/articulo
                Mid(Linea, 2) = Articulo.Item(«Codigo»)
                Mid(Linea, 8) = Articulo.Item(«Descripcion»)
                Mid(Linea, 66) = Articulo.Item(«Precio»)
                ‘imprimir la linea
                ImprimirUnaLinea(Pagina, Linea)
            Else
                Exit For
            End If
        Next
        ‘Memorizar la posicion del primer artículo/siguiente Pagina
        Puntero = Articulos.Rows.IndexOf(Articulo)
       
        ‘Comprobar si existen artículos para listar
        If Puntero < Articulos.Rows.Count – 1 Then
            Numero_Pagina += 1          ‘Incrementar numero de página
            Pagina.HasMorePages = True  ‘SI tengo más paginas a imprimir
        Else
            ImprimirUnaLinea(Pagina, «—— ——————————————————— ——–«)
            Numero_Pagina = 1           ‘Numero de pagina a 1 (Para el proximo listado)
            Pagina.HasMorePages = False ‘No Tengo mas paginas para imprimir
        End If
    End Sub
   
    ‘ Imprimir una linea
   

   ‘Lambda para con el cálculo de la posición de la línea
    Dim Pos = Function() As Single
                Return Margen_Superior + ContadorLinea * Fuente_Pagina.GetHeight(Pagina.Graphics)
             
End Function

    Sub ImprimirUnaLinea(ByVal Pagina As PrintPageEventArgs, ByVal Linea As String)
        ‘Imprimir la línea con la fuente seleccionada y en Negro
        Pagina.Graphics.DrawString(Linea, Fuente_Pagina, Brushes.Black, Margen_Izquierdo, Pos())
        ‘Incrementar el contador de líneas
        ContadorLinea += 1
    End Sub

End Class

PD. Me gustara recibir vuestros comentarios, opiniones y aportaciones.