Archivo de la categoría: SomeCode

Totalizadores y Contadores en una tabla de mi BD

Algunos de vosotros estáis preguntando como es posible totalizar ciertos valores ya sea de estadística o control en una de las tablas de nuestra aplicación.

Aquí os propongo una de las formas de implementarlo :
(Aunque no olvideis que existen otras formas de realizarlo, eso si quizas no tan accesibles :-))

En el lado de SQL podéis ejecutar este ‘script’ para generar la tabla…

CREATE TABLE [dbo].[Contadores](

      [Peras] [int] NOT NULL DEFAULT ((0)),

      [Naranjas] [int] NOT NULL DEFAULT ((0)),

      [Manzanas] [int] NOT NULL DEFAULT ((0))

) ON [PRIMARY]

Ahora solo tendréis que realizar el correspondiente ‘Update’ desde vuestra aplicación incrementando la columna que deseáis contabilizar. Esta pregunta es frecuente cuando se realizan aplicaciones tipo albaranes/facturas u otro tipo, en la que se requiere seguir o registrar una numeración aunque en ese caso no debéis olvidar bloquear el registro y más a lo sumo en aplicaciones que varios usuarios estén utilizando esa numeración.

    Private cn As New SqlClient.SqlConnection( _

          «Data Source=MiSrv\SQLEXPRESS;» + _

          «Initial Catalog=MiBd;» + _

          «Integrated Security=True»)

    Private da As New SqlClient.SqlDataAdapter( _

          «Select * from Contadores», cn)

 

    Private Sub Button1_Click() Handles Button1.Click

        ‘En este caso simulamos incrementar el contador de Manzanas

        da.UpdateCommand = New SqlClient.SqlCommand( _

          «Update Contadores SET Manzanas = Manzanas + 1», cn)

        cn.Open()

        da.UpdateCommand.ExecuteNonQuery()

        cn.Close()

    End Sub

 

Espero que os sea útil,
Buen fin de semana.
Pep Lluis,

Como comunicarme con una Bascula

‘Respondiendo a la pregunta :

‘ ¿Cómo puedo establecer comunicación con una bascula que tiene un RS232?

‘En este ejemplo podremos ver diferentes formas de enviar una petición

‘ a una bascula, simulando que nos responde al enviar el carácter ‘P’

‘ y visualizar su respuesta en una etiqueta llamada ‘Recibidos’

 

Public Class Form1

    ‘Constructores

    Private BasculaCom As New System.IO.Ports.SerialPort        ‘Puerto conectado a la báscula

    Private Recibidos As New Label                              ‘Etiqueta para visualizar la recepción

    Private Peticion As New Button                              ‘Botón para disparar el envío

    Delegate Sub MostrarRecepcion(ByVal Texto As String)        ‘Delegado para asignar el valor recibido

 

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ‘ Ajustar los parámetros de comunicaciones

        ‘ adaptándolos a las especificaciones o configuración

        ‘ de la bascula en concreto.

        BasculaCom.PortName = «COM1»                            ‘Conectaremos la bascula al puerto COM1

        BasculaCom.BaudRate = 9600                              ‘La velocidad de intercambio será de 9600

        BasculaCom.Parity = IO.Ports.Parity.None                ‘No verificaremos la paridad

        BasculaCom.StopBits = 1                                 ‘Final de Byte con 1 bit de Stop

        BasculaCom.Open()                                       ‘Abrir las comunicaciones con la bascula

       

        ‘ marco

        Dim marcoDGV = New FlowLayoutPanel                      ‘Conformar los controles del form

        marcoDGV.BorderStyle = BorderStyle.Fixed3D

        marcoDGV.Width = Me.Width

        marcoDGV.Height = Me.Height

        ‘ Añadir el marco con el Label y el Buton

        Recibidos.Text = «-«

        Peticion.Text = «Enviar p»

        marcoDGV.Controls.AddRange(New Control() {Peticion, Recibidos})

        Me.Controls.Add(marcoDGV)

 

        ‘Dirigir los eventos a las funciones para procesarlos

        AddHandler Peticion.Click, AddressOf EnviarUnaP         ‘Ejecución de ‘EnviarUnaP’ al pulsar el boton

        AddHandler BasculaCom.DataReceived, AddressOf Recibir   ‘Ejecución de ‘Recibir’ al recibir respuesta de la bascula

    End Sub

   

    ‘ Enviar una solicitud a la bascula

    Sub EnviarUnaP()

        ‘enviar una p

        BasculaCom.Write(«P»)

        ‘tambien puede ver/probar…

        BasculaCom.WriteLine(«P»)

        BasculaCom.Write(Chr(80))

        ‘… etc

    End Sub

 

    ‘al recibir de la bascula los bytesToRead indicara

    ‘un valor superior a 0, indicando el numero de caracteres

    Sub Recibir()

        ‘Dim NumeroDeBytesEnBuffer As Integer = BasculaCom.BytesToRead

        MostrarRececibidos(BasculaCom.ReadExisting)

    End Sub

   

    ‘ Mostrar los bytes recibidos en el Label recibidos

    Private Sub MostrarRececibidos(ByVal [texto] As String)

        If Recibidos.InvokeRequired Then

            Dim delegado As New MostrarRecepcion(AddressOf MostrarRececibidos)

            Me.Invoke(delegado, New Object() {[texto]})

        Else

            Me.Recibidos.Text = [texto]

        End If

    End Sub

 

End Class

 

Visual Studio 2010 – Zoom & Block Selection

        

Es emocionante explorar las nuevas características de Visual Studio 2010 en su versión Beta 2, a nivel básico una de las primeras sorpresas en el editor largamente anunciada es la incorporación de WPF, aunque parezca a simple vista un detalle de poco interés, debo confesar que una vez empiezas a trabajar con él te acostumbras de tal forma que cuando vuelves a utilizar el anterior (IDE 2008) te sientes como raro y se te antoja como frio y poco agradable.

Realmente el nuevo editor pasa desapercibido si no fuera por la aparición de un combo en la parte inferior derecha en la que al estilo de los mejores procesadores de texto nos deja seleccionar el % de zoom sobre la fuente que tengamos seleccionada.

Algo divertido que ya nos anunciaba Lisa Feigenbaum cuando nos presentaba la beta 1 en pasado año en el ‘Spanish tour 2008’ era la combinación de la tecla ‘Control’ con la rueda del Ratón… es divertido aumentar/disminuir el tamaño con solo rodar el ‘scroll’.

Fui uno de los que pensaron que eran de ese tipo de adornos que no son prácticos, pero debo rectificar y aseguraros de que es todo lo contrario.

Recordad: CTRL+Rueda Mouse (Avanza/Retrocede) J

Otra Característica simpática es la de edición simultánea de líneas múltiples. Ello nos permite seleccionar varias líneas o una selección de columna concreta abarcando varias líneas y escribir directamente en todas ellas.

Lo conseguiréis pulsando la tecla: Efectuando la selección mientras se mantiene la tecla ‘Alternativa’ pulsada.

También podéis conseguirlo manteniendo pulsadas las teclas [Mayúsculas]+[Alternativa] y seleccionando las líneas con las teclas de Cursor [Arriba]/[Abajo]/[Derecha]/[Izquierda]

…un par de facilidades más sobre VS2010!
Pep Lluis,

 

It’s exciting to explore the new features of Visual Studio 2010 in its Beta 2 version, at the basic level one of the first surprises in the editor and long announced is the incorporation of WPF, though it may seem at first glance a detail of little interest, I must confess that once you start working with him you get used, when you return to use the previous (2008 IDE) feel as rare and it strikes you as cold and little nice.

Actually the new editor goes unnoticed if you not see outside combo in the bottom right (like best word processors-styleJ) leaving us to select the % zoom applied.

Something fun that already we announced by Lisa Feigenbaum when we had the beta 1 last year in the ‘ Spanish tour 2008 ‘ was the combination of the key control with the mouse scroll… is funny increase / decrease the size, only shooting the scroll. I was one of those who thought were “ornaments are not practical”, but I must rectify and sure that is the very opposite.

Remember: CTRL+ Mouse Scroll (Up / Down)

Other nice feature is the simultaneous editing of multiple lines. This allows us to select multiple lines or a particular column selection spanning multiple lines and write directly to all of them. Just means undertaking the selection while keeping the [Alternative] down. You can also do so by holding down [Shift] [Alternative] keys and select the lines with the cursor keys [up] / [down] / [Right] / [Left]

… a couple of facilities more on VS2010!

Pep Lluis,

 

 

 

Gráficos de estadísticas en mi aplicación.

Es otra de las preguntas que se repite :

“En mis aplicaciones de VB6 utilizaba MS Chart para poder incrustar sencillos graficos a mi aplicación… he estado buscando en los ‘ocx’ y los componentes .NET en Visual Studio 2008 y no doy en encontrar si existe MS Chart para .NET”
Javier.

Bueno… la respuesta es muy fácil, solo tienes que descargar / instalar el Add-on de MS Chart para Visual Studio 2008. Creo recordar que necesitas tener instalado el SP1, después de instalarlo en la pestaña ‘Data’ del ‘toolbox’ te aparecerá ‘Chart’ y ya sabes… solo tienes que arrastrar y soltar J

MSChart_VisualStudioAddOn.exe

Espero que te sea de utilidad.

Se puede cambiar la velocidad del puerto serie?

‘ Repondiendo a la pregunta sobre si
‘ Se puede cambiar la velocidad de Transmsion/Recepcion dinamicamente

‘..     Dim MiPuerto As New System.IO.Ports.SerialPort
‘..     MiPuerto = My.Computer.Ports.OpenSerialPort(«COM1»)

‘En este ejemplo enviamos una trama “Hola” a una velocidad diferente
‘cada vez que invoquemos el procedimiento EnviarTrama

‘Evidentemente podeis asociarlo a un combo, de manera que utilice la
‘velocidad asociada a la selección del mismo

… Sub EnviarTrama …
        Select Case MiPuerto.BaudRate
            Case 19200
                MiPuerto.BaudRate = 9600
            Case 9600
                MiPuerto.BaudRate = 4800
            Case 9600
                MiPuerto.BaudRate = 2400
            Case Else
                MiPuerto.BaudRate = 19200
        End Select
        MiPuerto.WriteLine(«Hola… enviando a :» + MiPuerto.BaudRate.ToString)

Saludos;
Pep Lluis,

‘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,