Todas las entradas de: 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,

Microsoft Maker Garage

Sabes poco acerca del movimiento?

A medida que avanzan mis conversaciones entorno al «Internet de las cosas» percibo un incremento de extrañeza en mis interlocutores, cuando utilizo términos de «Maker» «Faire» «Spaces» «Garage»… tan raro es?

No dejes que te lo cuenten y apasiónate por los escenarios que inspiraran la materialización, socializando nuestras ideas, logros y genialidades.
Empieza aquí : http://youtu.be/h7B4_s4hvvc

Espero vuestros retos!,
PepLluis

Microframework y Gadgeteer en la UPM y el DotNetClub

Sergio nos deja un resumen de lo mas significativo de la reunión mantenida con los chicos de la UPM.

Agradecer tanto al DotNetClub como a los «dos representantes» de DPE en Microsoft, su paciencia, dedicación y entrega, sin duda fueron ingredientes esenciales para poder pasar un gran rato.
Para ser precisos casi dos horas y media 🙁  Perdon por el tostón!!

haz clic para ver el Resumen de la charla : http://maktub82blog.azurewebsites.net/charla-de-microframework-y-gadgeteer-con-pep-llus/

Nos vemos pronto y prometo cacharrear mas. (pero lo prepararemos antes) jajajaja!
PepLluis,

Tour around Microframework and Gadgeteer «The Maker Garage»

El próximo miércoles 5 de febrero en la Universidad Politécnica de Madrid y en colaboración con los dotNetClubs, nos sumergiremos en un interesante recorrido a través de la creatividad y las actuales tendencias del «maker garaje», «device science fair» o los famosos «maker spaces».

Todo ello desde una especial perspectiva, donde Microframework y Gadgeteer se dibujan como una potente alternativa, donde lo relevante no es la electrónica o la programación. Veremos cómo gadgeteer define la línea donde confluyen ambas disciplinas y nos descubre una verdadera herramienta para dar rienda suelta a nuestra imaginación.

dotnetclub_UniPolMadrid.png 

Estaremos el miércoles 5 a las 17:00 horas en las instalaciones de la UPM.
El evento durará una hora y media.

No te lo pierdas!!

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,

Controlando un robot con WinRT, WinForms y Surface Pro

Tal y como os contábamos en noviembre, la BCNCONDEV fue un buen escenario para sacar ese tiempo extra que nos hace falta para juguetear con alguno de esos artilugios que nos chiflan.

Tuvimos la suerte de compartir cancha con Pablo, para darnos la suficiente cuerda y retarnos a mover el Magic Robot con los sensores de la Surface… para los incrédulos hemos recuperado este video como muestra de nuestra gesta!

Gracias Pablo! por tu aportación.

Enlaces relacionados:

http://msmvps.com/blogs/peplluis/archive/2013/11/20/pete-brown-s-gadgeteer-robot-from-a-windows-form.aspx

http://msmvps.com/blogs/peplluis/archive/2013/11/09/the-barcelona-developers-conference-is-back.aspx

http://msmvps.com/blogs/peplluis/archive/2013/11/12/barcelona-developers-con-retro-makers-y-robotics.aspx

Code and Christmas :-)

Private card As Func(Of DateTime, String) =

Function(x As DateTime) If(x = New DateTime(DateTime.Now.Year, 12, 24), «Merry Christmas»,

                        If(x = New DateTime(DateTime.Now.Year, 12, 31), «Happy New Year»,

                        «No Card for today»))

 

Func<DateTime, string> card = (DateTime x) =>

         x == new DateTime(DateTime.Now.Year, 12, 24) ? «Merry Christmas» :

         x == new DateTime(DateTime.Now.Year, 12, 31) ? «Happy New Year» :

         «No Card for today»;

 

Merry Christmas to everybody!
PepLluis,