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

    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.