Archivo de la categoría: Uncategorized

Net Microframework – Volver a Empezar

Después de un periodo de sombra… parece ser que el tirón de IoT vuelve a poner en escena  a Microframework y Gadgeteer.

Para los que sintáis curiosidad os dejo un enlace a un «overview» en ch9 posteado hace poquitas horas.

Para los asiduos y seguidores mas que sorprenderos, vale la pena escuchar a Salvador Ramírez (microframework team), creo que aclara direcciones y planes de futuro.

NET-Micro-Framework

Que lo disfrutéis!

PepLluis,

Binding’s a la antigua : Remix (Enlazar textbox a la ‘column’ de una tabla)

Continuando con los remix, un antiguo pero recurrente ejemplo solicitado a menudo para enlazar datos a través de binding.

' Respondiendo a como añadir o modificar registros
' de una tabla de SQL con bindings y al viejo estilo
'
' Utilizaremos las columnas de Nombre y Teléfono 
' de la tabla ‘Shippers’
' Después de insertar un nuevo registro, usaremos el
' botón de actualizar para actualizar la BD.

Imports System.Data
Imports System.Data.SqlClient
Public Class miContenedor
'
'Constructores para tabla ‘Shippers’ 
' ...con su correspondiente BindingSource
Private MiConexion As New SqlConnection(“Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Temp\Northwind\NORTHWND.MDF” +
“;Integrated Security=True;Connect Timeout=30;User Instance=True”)
Private MiDataSet As New DataSet()
Private MiAdaptador As New SqlDataAdapter(“SELECT * FROM Shippers”, MiConexion)
Private MiEnlazador As New BindingSource
Private Sub Load(ByVal sender As System.ObjectByVal e As System.EventArgsHandles MyBase.Load
'
' Panel con los textbox para la entrada/modificación
    Dim Nombre As New TextBox
    Dim Telefono As New TextBox
    Dim marcoDatos = New FlowLayoutPanel
    marcoDatos.Dock = DockStyle.Top
    marcoDatos.Controls.AddRange(New Control() {Nombre, Telefono})
    Me.Controls.AddRange(New Control() {marcoDatos})
    '
    ' Panel conteniendo los botones de control
    Dim Avanza As New Button
    Dim Retrocede As New Button
    Dim Insertar As New Button
    Dim Actualizar As New Button
    Dim Controles As New FlowLayoutPanel
    Controles.Dock = DockStyle.Bottom
    Retrocede.Text = “<- Re”
    Avanza.Text = “Av ->”
    Insertar.Text = “Insertar”
    Actualizar.Text = “Actualizar”
    Controles.Controls.AddRange(New Control() {Retrocede, Avanza, Insertar, Actualizar})
    Me.Controls.AddRange(New Control() {Controles})
    '
    ' Asignar el eventos a las funciones
    AddHandler Retrocede.Click, AddressOf retroceder
    AddHandler Avanza.Click, AddressOf Avanzar
    AddHandler Insertar.Click, AddressOf Nuevo
    AddHandler Actualizar.Click, AddressOf Actualizacion
    '
    ' Conexión,relleno y asignacion del enlace al datos
    MiConexion.Open()
    MiAdaptador.Fill(MiDataSet)
    MiEnlazador.DataSource = MiDataSet.Tables(0)
    Dim Micommandbuilder As New SqlCommandBuilder(Me.MiAdaptador)
    '
    ' Enlace de los TextBox a sus omologos en la tabla
    Dim EnlaceNombre As New Binding(“Text”, MiEnlazador, “CompanyName”)
    Nombre.DataBindings.Add(EnlaceNombre)
    Dim EnlaceDireccion As New Binding(“Text”, MiEnlazador, “Phone”)
    Telefono.DataBindings.Add(EnlaceDireccion)
End Sub
 
' Avanzar un registro dentro del ‘recordset’ :-)
Sub Avanzar()
      MiEnlazador.MoveNext()
End Sub
 
' Retroceder un registro
Sub retroceder()
      MiEnlazador.MovePrevious()
End Sub
 
'Añadir un registro
Sub Nuevo()
      MiEnlazador.AddNew()
End Sub
 
' Actualizar el registro en curso o el recien creado
Sub Actualizacion()
      MiEnlazador.EndEdit()
      MiAdaptador.Update(CType(Me.MiEnlazador.DataSource, DataTable))
End Sub
Saludos,
Pep Lluis,

Principales Mandatos del Puerto Serie :: Remix

El cambio de blog ha provocado que algunos de los post mas famosos no puedan visualizarse correctamente. algunos de vosotros me habéis pedido un «Remix» aquí tenéis uno de los mas visitados!

' Principales mandatos para utilizar el puerto serie:
Serie = My.Computer.Ports.OpenSerialPort("COM1")  'Constructor
'
'Definir las características de la comunicación
Serie.BaudRate = 19200        'velocidad de comunicaciones
Serie.DataBits = 8            'Longitud para Byte de datos
Serie.Parity = Parity.Even    'paridad(enumeracion parity)
Serie.StopBits = StopBits.Two 'Bits parada después datos
'
'Abrir/Control/Liberar Puerto
Serie.Open()            'Abrir el puerto Serie
Serie.Close()           'Cerrar el Puerto Serie
Serie.Dispose()         'Liberar objecto
Dim SiNo As Integer
SiNo = Serie.IsOpen     'El Puerto esta abierto?
Dim Puerto As String
Puerto = Serie.PortName 'Nombre del puerto
'
'Manejo y Control de señales
Dim Estado As Boolean     'True=Activa / False=Inactiva
Estado = Serie.CDHolding  'Estado de la señal carrier detect
Estado = Serie.CtsHolding 'Señal Clear to Send
Estado = Serie.DsrHolding 'Señal Data Set Ready
Serie.DtrEnable = True    'Activar de Data Terminal Ready
Serie.RtsEnable = True    'Activar Request To Send
'
'Control Transmission/Recepcion
Serie.ReadBufferSize = 1024  'Definir tamaño buffer recepcion
Serie.WriteBufferSize = 1024 'Definir tamaño buffer envio
Serie.ReadTimeout = 10       'Fuera de tiempo en receción
Serie.WriteTimeout = 10      'Fuera de tiempo en transmisión
Serie.Handshake = Handshake.XOnXOff 'Control recepcion/envio
Serie.DiscardInBuffer()             'Borrar buffer de entrada
Serie.DiscardOutBuffer()            'Borrar buffer de salida
'
'Enviar datos
Contador = Serie.BytesToWrite 'Bytes en espera de ser escritos
Serie.Write("Hola Mundo")     'Enviar una cadena de caracteres
Serie.WriteLine("Hola Mundo"'Enviar una linea
'
'Leer datos
Dim Contador as Integer
Contador = Serie.BytesToRead  'Bytes en espera de ser leidos
Serie.ReadByte()              'Leer un byte
Serie.ReadChar()              'Leer un char
Serie.ReadLine()              'Leer una linea
Serie.ReadExisting()          'Leer datos existentes en buffer
PepLluis :-)

wpf Snnipeds

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;

using System.Data;
using System.Data.SqlClient;

using System.Windows.Forms;

/// for
/// foreach
/// switch
/// invoke
/// Serial Port
/// Timer

namespace wpfTest1
{
    /// <summary>
    /// Lógica de interacción para MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        static System.IO.Ports.SerialPort my_Serial = new System.IO.Ports.SerialPort();
        DispatcherTimer dispatcherTimer;
        DataGridView dgv = new System.Windows.Forms.DataGridView();
        Label dataRcv;
        Label frameR;
        DataSet ds;
        /// Main Windows
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
            initwinFormsParts();
            initSerialPortCombo();
            initSerialPort();
            initGradients();
            initDispatcherTimer();
            cmbSerialPort.SelectionChanged += cmbSerialPort_SelectionChanged;
        }

        #region windForms integration sample
        /// <summary>
        /// windForms integration sample
        /// </summary>
        void initwinFormsParts()
        {
            dataRcv = new System.Windows.Forms.Label();
            dataRcv.ForeColor = System.Drawing.Color.Red;
            dataRcv.Text = «dataRcv»;
            frameR = new System.Windows.Forms.Label();
            frameR.Top = dataRcv.Top + dataRcv.Height + 5;
            frameR.ForeColor = System.Drawing.Color.White;
            frameR.Text = «received data»;
            formsHost.Child = dataRcv;
            formsHost2.Child = frameR;
            formsHost3.Child = dgv;
        }
        #endregion

        #region snippet initialize serialPorts
        /// <summary>
        /// snippet for serialPorts
        /// </summary>
        Boolean serialPortFound = false;
        void initSerialPort()
        {
            try
            {
                my_Serial.PortName = cmbSerialPort.SelectedValue.ToString();
                my_Serial.DataReceived += receiveData;
                my_Serial.Open();
                serialPortFound = true;
            }
            catch (Exception)
            {
                serialPortFound = false;
            }
        }

        void cmbSerialPort_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            serialPortFound = false;
            my_Serial.Close();
            initSerialPort();
        }
        void initSerialPortCombo()
        {
            cmbSerialPort.ItemsSource = System.IO.Ports.SerialPort.GetPortNames();
            cmbSerialPort.SelectedIndex = 0;
        }
        #endregion

        #region snippet initialize dispatcherTimer
        /// <summary>
        /// snippet initialize dispatcherTimer
        /// </summary>
        void initDispatcherTimer()
        {
            dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 50);
            dispatcherTimer.Start();
        }
        #endregion

        #region Snippet initialize red / green gradient
        Brush blueGradien;
        LinearGradientBrush redGradien = new LinearGradientBrush();
        LinearGradientBrush greenGradien = new LinearGradientBrush();
        /// <summary>
        /// Snippet for red / green gradient
        /// </summary>
        void initGradients()
        {
            blueGradien = txLed.Fill;
            // reg Gradient
            redGradien.StartPoint = new Point(1,0.5);
            redGradien.EndPoint = new Point(0,0.5);
            redGradien.GradientStops.Add(new GradientStop(Colors.Black, 0));
            redGradien.GradientStops.Add(new GradientStop(Colors.Red, 1));
            greenGradien.StartPoint = new Point(1, 0.5);
            greenGradien.EndPoint = new Point(0, 0.5);
            greenGradien.GradientStops.Add(new GradientStop(Colors.Black, 0));
            greenGradien.GradientStops.Add(new GradientStop(Colors.Green, 1));
        }
        #endregion

        #region SerialPort write/read
        /// <summary>
        /// send data if serial port found
        /// </summary>
        /// <param name=»sender»></param>
        /// <param name=»e»></param>
        int writesNum;
        void sendData(object sender, RoutedEventArgs e)
        {
            if (serialPortFound)
            {
                my_Serial.Write(«\n» + DateTime.Now.ToString() + » Hello From my wpf app !!\r»);
                writesNum++;
            }
            else
            {
                dataRcv.Text = my_Serial.PortName + » Is not Available»;
            }
        }

        /// <summary>
        /// serial port data Received
        /// </summary>
        /// <param name=»sender»></param>
        /// <param name=»e»></param>
        string buffer;
        string frame;
        int tramNum;
        int buffNum;
        int diffMem;
        void receiveData(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            RxLed.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate { RxLed.Fill = greenGradien; }));
            buffNum++;
            buffer += my_Serial.ReadExisting();
            dataRcv.Invoke(new Action(() => dataRcv.Text = «(Numero de Recepcions : » + buffNum.ToString() + «) » + buffer));
            diffMem = writesNum – tramNum;
            int posI = buffer.IndexOf(«\n»);
            int posF = buffer.IndexOf(«\r»);
            if (posF > 0)
            {
                frame = buffer.Substring(posI + 1, posF – 1);
                buffer = buffer.Substring(posF + 1, buffer.Length – (posF + 1));
                frameR.Invoke(new Action(() => frameR.Text = «Sense: » + dispatcherTimer.Interval.TotalMilliseconds.ToString() + «ms (Trama º: » + tramNum.ToString() + «, de: » + writesNum.ToString() + «,dif: » +diffMem.ToString()+») » + frame));
                tramNum++;
            }
            RxLed.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate { RxLed.Fill = blueGradien; }));
        }
        #endregion

        #region dispatcherTimer task
        /// <summary>
        /// dispatcherTimer task
        /// </summary>
        /// <param name=»sender»></param>
        /// <param name=»e»></param>
        int stable = 0;
        void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            if ((bool)chkConti.IsChecked)
            {
                txLed.Fill = redGradien;
                refresh(RxLed);
                // autosense sendData interval
                if ((writesNum – tramNum) != diffMem)
                {
                    dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, (int)dispatcherTimer.Interval.TotalMilliseconds + 10);
                }
                else
                {
                    stable++;
                    if (stable > 50 && dispatcherTimer.Interval.Milliseconds > 10)
                    {
                        stable = 0;
                        dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, (int)dispatcherTimer.Interval.TotalMilliseconds – 5);
                    }
                }
                sendData(null, null);
                txLed.Fill = blueGradien;
                refresh(RxLed);
            }
        }
        #endregion

        #region Button task’s
        /// <summary>
        /// simulate a task calling process function prototipe
        /// </summary>
        /// <param name=»sender»></param>
        /// <param name=»e»></param>
        int numerofReentrys = 0;
        async void simulateTaskButton_Click(object sender, RoutedEventArgs e)
        {
            numerofReentrys++;
            wndMain.Title = «wndMain – in process : » + numerofReentrys.ToString();
            refresh(wndMain);
            Task newProc = Task.Factory.StartNew(process);
            await newProc;
            myButton.Content = «End Process»;
            numerofReentrys–;
            if (numerofReentrys > 0)
            {
                wndMain.Title = «wndMain – in process : » + numerofReentrys.ToString();
            }
            else
            {
                wndMain.Title = «wndMain – No process pending»;
            }
            refresh(wndMain);
        }
        /// <summary>
        /// Create new form
        /// </summary>
        /// <param name=»sender»></param>
        /// <param name=»e»></param>
        private void CreateForm_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.Form _myForm = new System.Windows.Forms.Form();
            System.Windows.Forms.ComboBox txt = new System.Windows.Forms.ComboBox();
            System.Windows.Forms.Label lbl = new System.Windows.Forms.Label();
            txt.Top = 100; txt.Left = 100;
            txt.Text = «Hola»;
            txt.Items.Add(«Uno»);
            txt.Items.Add(«Dos»);
            txt.Visible = true;
            lbl.Text = «HOLA!!!»;
            txt.SelectedIndexChanged += txt_SelectedIndexChanged;
            _myForm.Name = DateTime.Now.ToString();
            _myForm.Controls.Add(txt);
            _myForm.Controls.Add(lbl);
            _myForm.Show();
        }
        /// <summary>
        /// enumButton click
        /// </summary>
        /// <param name=»sender»></param>
        /// <param name=»e»></param>
        private void enumForm_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FormCollection fmrs = System.Windows.Forms.Application.OpenForms;
            foreach (System.Windows.Forms.Form Ofmrs in fmrs)
            {
                MessageBoxResult result = System.Windows.MessageBox.Show(Ofmrs.Name);
            }
        }
        /// <summary>
        /// saveButton click
        /// </summary>
        /// <param name=»sender»></param>
        /// <param name=»e»></param>
        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            SqlAdap.Update(ds, «Sample»);
        }
        #endregion

        #region «common functions»
        /// <summary>
        /// simulate process iteration
        /// </summary>
        void process()
        {
            for (int index = 0; index < 10000; index++)
            {
                myButton.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate { myButton.Content = index.ToString(); }));
                System.Windows.Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
            }
        }

        /// <summary>
        /// refresh wpf element
        /// </summary>
        /// <param name=»element»></param>
        private Action _delegate = delegate() { };
        private void refresh(UIElement element)
        {
            this.Dispatcher.Invoke(DispatcherPriority.Render, _delegate);
            if (System.Windows.Application.Current != null)
            {
                System.Windows.Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
            }
        }
        /// <summary>
        /// catch for combo box selection chaged
        /// </summary>
        /// <param name=»sender»></param>
        /// <param name=»e»></param>
        void txt_SelectedIndexChanged(object sender, EventArgs e)
        {
            System.Windows.Forms.MessageBox.Show(«Hey!!»);
        }
        #endregion

        #region dataLayer to populate datagrid from Azure db/local file
        string Server = «tcp:afj66tfey7.database.windows.net,1433»;
        string DbName = «testCase»;
        string UserName = «Master@afj66tfey7«;
        string UserPwd = «Password13»;

        SqlConnection SqlConn;
        SqlDataAdapter SqlAdap;
        /// <summary>
        /// dataLayer to populate datagrid from Azure db/local file
        /// </summary>
        /// <param name=»sender»></param>
        /// <param name=»e»></param>
        void populateData(object sender, RoutedEventArgs e)
        {
            if ((bool)chkData.IsChecked)
            {
                SqlConn = new SqlConnection(«Server=» + Server + «;Database=» + DbName +
                    «;User ID=» + UserName + «;Password=» + UserPwd +
                    «;Trusted_Connection=False;Encrypt=True;Connection Timeout=30»);
                chkData.Content = «switch to local Data»;
            }
            else
            {
                SqlConn = new SqlConnection(@»Data Source=(LocalDB)\v11.0;AttachDbFilename=» +
                    System.Environment.CurrentDirectory.ToString() +
                     @»\testCase.mdf;Integrated Security=True;Connect Timeout=30″);
                chkData.Content = «switch to Azure Data»;
            }
            try
            {
                if (SqlConn.State == ConnectionState.Closed)
                {
                    SqlConn.Open();
                }
                SqlAdap = new SqlDataAdapter(«Select * From Sample», SqlConn);
                ds = new DataSet();
                SqlCommandBuilder builder = new SqlCommandBuilder(SqlAdap);
                SqlAdap.Fill(ds, «Sample»);
                dgv.DataSource = ds.Tables[«Sample»].DefaultView;
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        #endregion

    }
}

Subproceso Anulado (ThreadAbordException)

Siguiendo casualmente algunos enlaces referentes a la ejecución de forms en diferentes hilos, algunos escenarios y de forma esporádica lanzan errores inesperados haciendo referencia a “thread abord exception” y “subproceso anulado” me decidí investigar un poquito más y…

Se deben diferenciar dos tipos

a) Unhandled exceptions descritas en : http://msdn.microsoft.com/es-es/library/system.windows.forms.application.threadexception(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

b) Las “threatAbordException” son mucho más sencillas de resolver, eso si no debéis caer en el error de intentar capturarlos en un “exception” genérico J

»’ <summary>

»’ 

»’ </summary>

»’ <remarks></remarks>

Sub Loading()

    Try

        Application.Run(New frmLoading)

    Catch ex As ThreadAbortException

        ‘ Nothing to do :-))

    End Try

End Sub

 

Espero que os sea útil, si es que es vuestro caso J
PepLluis,

Mis Top Ten :-)

Me complace compartir con vosotros el numero de visitantes de este blog.

En los ultimos 6 Meses de las casi 40k Visitas… los 10 paises mas asiduos han sido :

Mexico (MX)

8,227

Spain (ES)

5,090

Peru (PE)

3,163

Argentina (AR)

3,074

Colombia (CO)

2,783

Chile (CL)

2,084

Ecuador (EC)

1,395

United States (US)

1,223

Venezuela (VE)

1,050

Bolivia (BO)

749


Como sabeis el exito no se mide por la cantidad, si no por la utilidad que los lectores puedan encontrar en lo que aquí explico.
Gracias por leerme… espero que con vuestras visitas continueis animandome a escribir. 🙂

Saludos!
PepLluis,

Un buen momento para saber como progresa Roslyn

Nuestra visión de compilador continua siendo el proceso por el que el código entra por un extremo, produciendo los binarios que salen por el otro. No dejes de conocer "Roslyn" pues vas a ver como los compiladores de Visual Basic y C # como API’s. Estas API’s van a permitir tener una vista previa de la próxima generación de modelos de objetos y de idiomas para la generación de código, el análisis y la refactorización, y el soporte para el uso de secuencias de comandos interactivos para Visual Basic y C #.

http://msdn.microsoft.com/es-es/roslyn

Saludos,
PepLluis,