Пример #1
0
        private void GetUserAdmin()
        {
            menuStrip1.Invoke(new Action(() => menuStrip1.Enabled           = false));
            buttonSignIn.Invoke(new Action(() => buttonSignIn.Enabled       = false));
            textBoxLogin.Invoke(new Action(() => textBoxLogin.Enabled       = false));
            textBoxPassword.Invoke(new Action(() => textBoxPassword.Enabled = false));
            IEnumerable <DALServerDB.Infrastructure.User> user1 = repUs.FindAll(p => p.Login == textBoxLogin.Text && p.IsAdmin == true);

            if (user1 != null)
            {
                User = user1.FirstOrDefault(x => DALServerDB.Models.Crypter.GetCrypt(x.Password) == textBoxPassword.Text);
            }
            if (User == null)
            {
                MessageBox.Show(Environment.NewLine + "user not found!!!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                menuStrip1.Invoke(new Action(() => menuStrip1.Enabled           = true));
                buttonSignIn.Invoke(new Action(() => buttonSignIn.Enabled       = true));
                textBoxLogin.Invoke(new Action(() => textBoxLogin.Enabled       = true));
                textBoxPassword.Invoke(new Action(() => textBoxPassword.Enabled = true));
                return;
            }
            if (User.IsAdmin)
            {
                this.Invoke(new Action(() =>
                {
                    FormMain form = new FormMain(User, Connection);
                    form.Owner    = this;
                    this.Hide();
                    form.ShowDialog();
                }));
            }
        }
Пример #2
0
 public static void StartAnomalyDetection(TextBox warningTextBox)
 {     
     if (DoneSettingNormalUsage)
     {
         if (CPUMonitor.CPUCounter > NormalCPU)
         {
             if (warningTextBox.Text.Length == 0)
             {
                 warningTextBox.Invoke(new Action(() =>
                 {
                     warningTextBox.Text = "CPU Usage: " + CPUMonitor.CPUCounter.ToString("F2") + "%";
                     CPUMonitor.CPUWarnings = warningTextBox.Text;
                 }));
             }
             else
             {
                 warningTextBox.Invoke(new Action(() =>
                 {
                 warningTextBox.AppendText("\r\nCPU Usage: " + CPUMonitor.CPUCounter.ToString("F2") + "%");
                     CPUMonitor.CPUWarnings = warningTextBox.Text;
                 }));
             }
         }
     }
 }
Пример #3
0
 public override void Write(string message)
 {
     if (!m_bDisable)
     {
         _target.Invoke(_invokeWrite, new object[] { message });
     }
 }
Пример #4
0
 public void AddLog(string text)
 {
     if (Logger.InvokeRequired)
     {
         Action <string> invoker = new Action <string>(AddLog);
         Logger.Invoke(invoker, text);
     }
     else
     {
         Logger.Text += Environment.NewLine + text;
     }
 }
Пример #5
0
    public void do_calc()
    {
        string[] ql = { "4+6", "11-5", "3*7", "9/3" };
        foreach (String q in ql)
        {
            if (!textBox1.IsHandleCreated)
            {
                IntPtr dummy = textBox1.Handle; // force the Control to be created.
            }
            textBox1.Invoke(new MethodInvoker(delegate { textBox1.Text = q; }));
            evaluate_click(button1, new EventArgs());
        }
        Thread.Sleep(1000); // Make it possible to see the GUI for a short while.
        QueryAnswer answer = session.executeQuery("shutdown");

        session.disconnect();
        process.WaitForExit(10000); // wait 10 seconds.
        if (!process.HasExited)
        {
            try {
                process.Kill();
            } catch (System.InvalidOperationException)
            {
            }
        }
        Environment.Exit(0);
    }
 public void OnDataReceived(IAsyncResult asyn)
 {
     try
     {
         CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState;
         //end receive...
         int iRx = 0;
         iRx = theSockId.thisSocket.EndReceive(asyn);
         char[] chars          = new char[iRx + 1];
         System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
         int           charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
         System.String szData  = new System.String(chars);
         //txtDataRx.Text = txtDataRx.Text + szData;
         txtDataRx.Invoke(new MethodInvoker(delegate
         {
             txtDataRx.Text = txtDataRx.Text + szData;
         }));
         WaitForData();
     }
     catch (ObjectDisposedException)
     {
         System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
     }
     catch (SocketException se)
     {
         MessageBox.Show(se.Message);
     }
 }
Пример #7
0
 /// <summary>
 /// Sets textbox text
 /// </summary>
 /// <param name="tb"></param>
 /// <param name="text"></param>
 private static void SetTextBoxSafe(TextBox tb, string text)
 {
     if (tb.InvokeRequired)
         tb.Invoke(new Action(() => tb.Text = text));
     else
         tb.Text = text;
 }
Пример #8
0
 private void updateRegisterState(TextBox txt, Register register)
 {
     txt.Invoke((MethodInvoker)(() =>
     {
         txt.Text = _vm.cpu.Registers[register].ToString();
     }));
 }
Пример #9
0
        public static async void ProcessMonitoring(TextBox usageTextBox, TextBox listTextBox)
        {
            int changed = ProcessCounter;
            string[] data;
            while (true)
            {
                await Task.Delay(1000);
                CurrentNumberProcesses();
                usageTextBox.Invoke(new Action(() =>
                {
                    usageTextBox.Text = ProcessCounter + "";
                }));

                if (changed != ProcessCounter)
                {
                    changed = ProcessCounter;
                    listTextBox.Invoke(new Action(() =>
                    {
                        data = ReadProcesses();

                        foreach (string pData in data)
                        {
                            if (listTextBox.Text.Length < 0)
                                listTextBox.Text = pData;
                            else
                                listTextBox.AppendText($"\r\n{pData}");
                        }
                    }));
                }
            }
        }
Пример #10
0
 public static void AddControlText(System.Windows.Forms.TextBox ctlSelf, string Value)
 {
     if (ctlSelf.InvokeRequired)
     {
         ctlSelf.Invoke(new MethodInvoker(delegate
         {
             if (ctlSelf.Text.Length > 0)
             {
                 ctlSelf.Text += Environment.NewLine;
             }
             ctlSelf.Text          += Value;
             ctlSelf.SelectionStart = ctlSelf.Text.Length;
             ctlSelf.ScrollToCaret();
         }));
     }
     else
     {
         if (ctlSelf.Text.Length > 0)
         {
             ctlSelf.Text += Environment.NewLine;
         }
         ctlSelf.Text          += Value;
         ctlSelf.SelectionStart = ctlSelf.Text.Length;
         ctlSelf.ScrollToCaret();
     }
 }
Пример #11
0
        //Function will read and display current CPU usage
        public static async void CPUMonitoring(TextBox usageTextBox, TextBox warningTextBox)
        {

            PerformanceCounter cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";

            while (true)
            {
                //First value always returns a 0
                var unused = cpuCounter.NextValue();
                await Task.Delay(1000);

                usageTextBox.Invoke(new Action(() =>
                {
                    CPUCounter = cpuCounter.NextValue();
                    usageTextBox.Text = CPUCounter.ToString("F2") + "%";
                }));
                CPUCalculations();
                CPUAnomalies.StartAnomalyDetection(warningTextBox);

                if (mainMenu.done)
                    break;
            }
        }
Пример #12
0
 public void setTextBoxValue(System.Windows.Forms.TextBox field, string value)
 {
     if (field.InvokeRequired)
     {
         field.Invoke(new MethodInvoker(delegate { field.Text = value; }));
     }
 }
Пример #13
0
        static void Main()
        {

            var form = new Form { Width = 800, Height = 600};
            textBox = new TextBox() { Dock = DockStyle.Fill, Multiline = true, Text = "Interact with the mouse or the keyboard...\r\n", ReadOnly = true};
            form.Controls.Add(textBox);
            form.Visible = true;

            // setup the device
            Device.RegisterDevice(UsagePage.Generic, UsageId.GenericMouse, DeviceFlags.None);
            Device.MouseInput += (sender, args) => textBox.Invoke(new UpdateTextCallback(UpdateMouseText), args);

            Device.RegisterDevice(UsagePage.Generic, UsageId.GenericKeyboard, DeviceFlags.None);
            Device.KeyboardInput += (sender, args) => textBox.Invoke(new UpdateTextCallback(UpdateKeyboardText), args);

            Application.Run(form);
        }
Пример #14
0
 private string GetTextBoxText(TextBox textbox)
 {
     string returnValue = null;
     if (textbox.InvokeRequired)
         textbox.Invoke((MethodInvoker)
                        delegate { returnValue = GetTextBoxText(textbox); });
     else
         return textbox.Text;
     return returnValue;
 }
Пример #15
0
 public static void add_text(TextBox tb, object s)
 {
     if (tb.InvokeRequired)
         tb.Invoke(new Action<TextBox, object>(add_text), new object[] { tb, s });
     else
     {
         tb.AppendText(s.ToString());
         tb.ScrollToCaret();
     }
 }
Пример #16
0
        private void test()
        {
            for (int i = 2; i <= 150; i++) //go through numbers 2 - 150
            {
                bool isPrime = true;
                for (int y = 2; y < i; y++) //go through all numbers preceeding the current number
                {
                    if (i % y == 0)         //if this happens (numbers evenly divide), it is not a prime number
                    {
                        isPrime = false;
                        break;
                    }
                }
                if (isPrime)
                {
                    Thread.Sleep(1000);

                    //Console.WriteLine(i);
                    textDisplay.Invoke((Action) delegate
                    {
                        textDisplay.Text = i.ToString();
                    }
                                       );
                }

                /*
                 * if (true) //Calculation to determine if prime number
                 * {
                 *  Thread.Sleep(1000);
                 *
                 *  //Console.WriteLine(i);
                 *  textDisplay.Invoke((Action)delegate
                 *  {
                 *      textDisplay.Text = i.ToString();
                 *  }
                 *  );
                 *
                 * }*/

                /*
                 * Thread.Sleep(100);
                 *
                 * //Console.WriteLine(i);
                 * textDisplay.Invoke((Action)delegate
                 * {
                 *  textDisplay.Text = i.ToString();
                 * }
                 * );
                 * //textDisplay.Text = i.ToString();
                 * //inUse = false;*/
            }
            inUse = false;
            //calculationFinished?.invoke();
            calculationFinished.Invoke(); //used to reenable the button
        }
Пример #17
0
 private void UpdateUI(TextBox tb, int data)
 {
     if (textBox1.InvokeRequired)
     {
         tb.Invoke(new UpdateStatus(UpdateUI), new object[] {tb, data });
     }
     else
     {
         tb.Text += data + Resources.TextSeparator;
     }
 }
Пример #18
0
 private void WriteToLog(string message)
 {
     if (textBox1.InvokeRequired)
     {
         textBox1.Invoke(new WriteToLogDelegate(WriteToLog), new object[] { message });
     }
     else
     {
         textBox1.AppendText(message + "\r\n");
     }
 }
Пример #19
0
 public void showdata(string mac, string ip, float nhietdo, float doam, float nguon, TextBox text)
 {
     text.Invoke(new EventHandler(delegate
     {
         if (index == 2)
         {
             text.Text = "Sensor " + ip + "(" + mac + ")\r\nNhiet do : " + nhietdo + "\r\nDo am : " + doam + "\r\nNang luong : " + nguon;
             mypanel.Show();
         }
     }));
 }
Пример #20
0
 public static string GetTextBoxText(TextBox box)
 {
     if (box.InvokeRequired)
     {
         Func<TextBox, string> deleg = new Func<TextBox, string>(GetTextBoxText);
         return box.Invoke(deleg, new object[] { box }).ToString();
     }
     else
     {
         return box.Text;
     }
 }
Пример #21
0
 private void bw_capture_DoWork(object sender, DoWorkEventArgs e)
 {
     while (true)
     {
         capturing();
         Thread.Sleep(5000);
         StopCapture();
         count++;
         txtFilename.Invoke(new MethodInvoker(delegate { txtFilename.Text = @"C:\" + count.ToString() + ".avi"; }));
         bw_upload.RunWorkerAsync();
     }
 }
Пример #22
0
 private void SetTextBoxValue(string value, TextBox ctr)
 {
     Action<string> setValueAction = text => ctr.AppendText(value);//Action<T>本身就是delegate类型,省掉了delegate的定义
     if (ctr.InvokeRequired)
     {
         ctr.Invoke(setValueAction, value);
     }
     else
     {
         setValueAction(value);
     }
 }
Пример #23
0
 public static void updateTextBox(string strText, TextBox tbToUse)
 {
     if (tbToUse.InvokeRequired)
     {
         updateTextBoxCallback utbCallback = new updateTextBoxCallback(updateTextBox);
         tbToUse.Invoke(utbCallback, new object[] { strText, tbToUse });
     }
     else
     {
         tbToUse.Text = strText + Environment.NewLine + tbToUse.Text;
     }
 }
Пример #24
0
 public static void SetText(System.Windows.Forms.TextBox ctrl, string text)
 {
     if (ctrl.InvokeRequired)
     {
         object[] params_list = new object[] { ctrl, text };
         ctrl.Invoke(new SetTextDelegate(SetText), params_list);
     }
     else
     {
         ctrl.AppendText(text);
     }
 }
Пример #25
0
 public void PrintText(TextBox textbox, string text)
 {
     if (textbox.InvokeRequired)
     {
         textbox.Invoke(new PrintTextCallback(PrintText), textbox, text);
     }
     else
     {
         textbox.Text += text;
         textbox.SelectionStart = textbox.Text.Length;
         textbox.ScrollToCaret();
     }
 }
Пример #26
0
 public static void StartAnomalyDetection(TextBox warningTextBox)
 {
     if (DoneSettingNormalUsage)
     {
         if(true)
         {
             if(warningTextBox.Text.Length == 0)
             {
                 warningTextBox.Invoke(new Action(() =>
                 {
                     warningTextBox.Text = $"Warning! RAM Usage: {RAMMonitor.RAMCounter} MB";
                 }));
             } else
             {
                 warningTextBox.Invoke(new Action(() =>
                 {
                     warningTextBox.AppendText($"\r\nWarning! RAM Usage: {RAMMonitor.RAMCounter} MB");
                 }));
             }
         }
     }
 }
Пример #27
0
        public void ThrowWarning(TextBox warningTextBox, string postfix)
        {
            if (NormalUsage > CurrentUsage)
            {
                if (warningTextBox.Text.Length == 0)
                {
                    warningTextBox.Invoke(new Action(() =>
                    {
                        warningTextBox.Text = "Usage: " + tools.DoFormat(CurrentUsage) + postfix;
                        WarningUsage = warningTextBox.Text;
                    }));
                }
                else
                {
                    warningTextBox.Invoke(new Action(() =>
                    {
                        warningTextBox.AppendText("\r\nUsage: " + tools.DoFormat(CurrentUsage) + postfix);
                        WarningUsage = warningTextBox.Text;
                    }));
                }
            }

        }
Пример #28
0
        public static void SetText(System.Windows.Forms.TextBox ctrl, string text)
        {
            if (ctrl.InvokeRequired)
            {
                object[] params_list = new object[] { ctrl, text };

                ctrl.Invoke(new SetTextDelegate(SetText), params_list);
            }
            else
            {
                ctrl.Text = ctrl.Text + text;
                ctrl.Select(ctrl.Text.Length, 0);
                ctrl.ScrollToCaret();
            }
        }
 private void AddLog(TextBox textBox, string str)
 {
     if (textBox.InvokeRequired)
     {
         AddLogCallBack addLogCallBack = AddLog;
         textBox.Invoke(addLogCallBack, new object[] { textBox, str });
     }
     else
     {
         str = DateTime.Now.ToString("hh:mm") + " " + str + @"
     ";
         textBoxLog.AppendText(str);
         textBoxLog.ScrollToCaret();
     }
 }
Пример #30
0
 public void DisplayData(string msg, TextBox listBox1)
 {
     listBox1.Invoke(new EventHandler(delegate
     {
         //listBox1.Font = new Font("Tahoma", 10, FontStyle.Regular);
         //if (count > 720)
         //{
         //    listBox1.Text = string.Empty;
         //    count = 0;
         //}
         listBox1.Text += msg + "\r\n";
         listBox1.SelectionStart = listBox1.Text.Length;
         listBox1.ScrollToCaret();
     }));
 }
Пример #31
0
        public static void SetFont(TextBox textBox, Font font)
        {
            MethodInvoker miSetFont = delegate
            {
                textBox.Font = font;
            };

            if (textBox.InvokeRequired)
            {
                textBox.Invoke(miSetFont);
            }
            else
            {
                miSetFont();
            }
        }
Пример #32
0
        public static void SetText(TextBox textBox, string text)
        {
            MethodInvoker miSetText = delegate
            {
                textBox.Text = text;
            };

            if (textBox.InvokeRequired)
            {
                textBox.Invoke(miSetText);
            }
            else
            {
                miSetText();
            }
        }
Пример #33
0
        internal static void SetText(TextBox control, string text)
        {
            MethodInvoker miSetText = delegate
            {
                control.Text = text;
            };

            if (control.InvokeRequired)
            {
                control.Invoke(miSetText);
            }
            else
            {
                miSetText();
            }
        }
Пример #34
0
        public static void SetForeColor(TextBox textBox, Color color)
        {
            MethodInvoker miSetForeColor = delegate
            {
                textBox.ForeColor = color;
            };

            if (textBox.InvokeRequired)
            {
                textBox.Invoke(miSetForeColor);
            }
            else
            {
                miSetForeColor();
            }
        }
Пример #35
0
 private void Log(string line)
 {
     if (txtLog.InvokeRequired)
     {
         try
         {
             txtLog.Invoke(new LogDelegate(Log), line);
         }
         catch { }
     }
     else
     {
         txtLog.Text          += line + Environment.NewLine;
         txtLog.SelectionStart = txtLog.Text.Length;
         txtLog.ScrollToCaret();
     }
 }
Пример #36
0
 /// <summary>
 /// CardRemovedEventHandler
 /// </summary>
 private void iCard_OnCardRemoved(object sender, string reader)
 {
     if (this.InvokeRequired)
     {
         btnConnect.Invoke(new EnableButtonDelegate(EnableButton), new object[] { btnConnect, false });
         btnDisconnect.Invoke(new EnableButtonDelegate(EnableButton), new object[] { btnDisconnect, false });
         btnTransmit.Invoke(new EnableButtonDelegate(EnableButton), new object[] { btnTransmit, false });
         txtboxATR.Invoke(new SetTextBoxTextDelegate(SetText), new object[] { txtboxATR, string.Empty });
     }
     else
     {
         btnConnect.Enabled    = false;
         btnDisconnect.Enabled = false;
         btnTransmit.Enabled   = false;
         txtboxATR.Text        = string.Empty;
     }
 }
        /// <summary>
        /// Appends text to a textbox in a multi-threaded environment.  This method does not append a linefeed at the end of the text.
        /// </summary>
        /// <param name="tb">The NAME of the textbox to be written to.</param>
        /// <param name="text">The TEXT to be appeneded to the textbox (without linefeed).</param>
        public static void appendText(TextBox tb, String text)
        {
            // Stop if TextBox reference is null
            if (tb == null) return;

            // Stop if the text reference is null
            if (text == null) return;

            if (tb.InvokeRequired)
            {
                AppendTextCallback a = new AppendTextCallback(appendText);
                tb.Invoke(a, new object[] { tb, text });
            }
            else
            {
                tb.AppendText(text);
            }
        }
Пример #38
0
        public static string GetText(TextBox textBox)
        {
            string returnValue = string.Empty;

            MethodInvoker miGetText = delegate
            {
                returnValue = textBox.Text;
            };

            if (textBox.InvokeRequired)
            {
                textBox.Invoke(miGetText);
            }
            else
            {
                miGetText();
            }

            return returnValue;
        }
Пример #39
0
        public static async void RAMMonitoring(TextBox usageTextBox)
        {
            PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");

            while (true)
            {
                await Task.Delay(1000);

                usageTextBox.Invoke(new Action(() =>
               {
                   RAMCounter = ramCounter.NextValue();
                   usageTextBox.Text = RAMCounter + "MB";
               }));

                RAMCalculations();

                if (mainMenu.done)
                    break;
            }
        }
Пример #40
0
        public static void UpdateTextBox(TextBox txt, string text)
        {
            if (text == null)
                return;

            try
            {
                if (txt.InvokeRequired)
                {
                    UpdateTextBoxCallback d = UpdateTextBox;
                    txt.Invoke(d, txt, text);
                    return;
                }

                txt.Text = text;
            }
            catch
            {
                // This catch is simply here to avoid the OCCASIONAL crash of the application when closing it by pressing the stop button in visual studio while it is running tasks
            }
        }
Пример #41
0
        public async Task StartAsync()
        {
            var operation = new LongOperation(() =>
            {
                Thread.Sleep(2000);
                return(0);
            });

            operation.Log = text =>
            {
                if (log.InvokeRequired)
                {
                    log.Invoke((MethodInvoker) delegate { log.Text += text + Environment.NewLine; });
                }
                else
                {
                    log.Text += text + Environment.NewLine;
                }
            };

            await operation.StartAsync();
        }
Пример #42
0
        public static void SetTextTB(System.Windows.Forms.TextBox textbox, string text, bool AppendMode)
        {
            if (textbox == null)
            {
                return;
            }

            if (textbox.InvokeRequired)
            {
                SetTextTBCallback d = SetTextTB;
                textbox.Invoke(d, new object[] { textbox, text, AppendMode });
            }
            else
            {
                if (AppendMode)
                {
                    textbox.Text = text + textbox.Text;
                }
                else
                {
                    textbox.Text = text;
                }
            }
        }
Пример #43
0
        //Algoritmo genético:
        private void GeneticAlgorithm()
        {
            Random rand                 = new Random((int)DateTime.Now.Ticks); // gerador de num. aleatório
            int    iterationCount       = 0;                                   //Inicializa variável que armazena o valor da geração atual
            int    noProgressIterations = 0;
            double bestDist             = 0;
            bool   allEqual             = false;                //Inicia a variável de convergência em falso

            Path.Clear();                                       //Limpa a lista caminho
            Population.Clear();                                 //Limpa a lista de população
            // get population size
            try
            {
                //Obtém o número de população
                NPop = Math.Max(10, Math.Min(100000, int.Parse(populationSizeBox.Text)));
            }
            catch
            {
                //Se anteriormente houve uma exceção, estabelecer população em um valor constante
                NPop = 100;
            }

            //get iterations num.
            try
            {
                //Obtém o número de gerações
                NGer = Math.Max(100, Math.Min(1000000000, int.Parse(iterationsBox.Text)));
            }
            catch
            {
                //Se anteriormente houve uma exceção, estabelecer número de gerações em um valor constante
                NGer = 100;
            }

            try
            {
                //Obtém chance de mutação
                NMut = Math.Max(0, Math.Min(100, double.Parse(mutationChanceBox.Text)));
            }
            catch
            {
                //Se anteriormente houve uma exceção, estabelecer chance de mutação em um valor constante
                NMut = 0;
            }

            //Atualiza itens da interface, que estão em outra Thread
            this.Invoke((MethodInvoker) delegate
            {
                //Atualiza valores das textbox:
                //---------------------------------------------
                populationSizeBox.Text = NPop.ToString();
                iterationsBox.Text     = NGer.ToString();
                mutationChanceBox.Text = NMut.ToString();
                //---------------------------------------------

                //Impede a alteração dos valores das textbox até o término da execução:
                //---------------------------------------------
                iterationsBox.ReadOnly     = true;
                populationSizeBox.ReadOnly = true;
                mutationChanceBox.ReadOnly = true;
                citiesCountBox.ReadOnly    = true;
                //---------------------------------------------
            });

            //Enquanto i for menor que o valor populacional...
            for (int i = 0; i < NPop; i++)
            {
                Individuo indv = new Individuo(Map, rand);  //Criar um novo indivíduo com genes aleatórios
                Population.Add(indv);                       //Adicionar o indivíduo à população
            }

            //Enquanto não tiver atingido o número máximo de gerações...
            while (iterationCount < NGer)
            {
                //Ordena os indivíduos da população de acordo com seu fitness (menor distância do percurso)
                Population.Sort((x, y) => x.distance.CompareTo(y.distance));

                //Cria uma lista para os piores indivíduos da população (1/3)
                List <Individuo> PopulationWorst = new List <Individuo>();
                //Cria uma lista para os melhores indívuos da população (2/3)
                //Esses indivíduos serão os pais da nova geração
                List <Individuo> PossibleParents = new List <Individuo>();

                //Calcular o valor aproximado de dois terços da população
                int parentFraction = (Population.Count * 2) / 3;

                //Povoar a lista dos piores indivíduos com os piores indivíduos (1/3 da população)
                PopulationWorst = Population.GetRange(parentFraction, NPop - parentFraction);
                //Povoar a lista dos possíveis pais com os melhores indivíduos (2/3 da população)
                PossibleParents = Population.GetRange(0, parentFraction);
                //Atualizar a população atual para conter apenas os melhores indivíduos da atualidade
                Population = Population.GetRange(0, parentFraction);

                //Cria uma lista para aqueles que já foram pais
                List <Individuo> Parents = new List <Individuo>();
                //Cria uma lista para os filhos que serão gerados
                List <Individuo> Children = new List <Individuo>();

                //Enquanto o número de filhos for menor do que a quantidade de piores indivíduos da população...
                while (Children.Count < PopulationWorst.Count)
                {
                    int parentCount = PossibleParents.Count;    //Obter o número de indivíduos que ainda podem ser pais

                    if (parentCount > 1)                        //Se o número de possíveis pais for maior que 1
                    {
                        int randFather;                         //Posição da população correspondente ao pai
                        int randMother;                         //Posição da população correspondente à mãe
                        do
                        {
                            randFather = rand.Next(parentCount); //Gera uma posição aleatória na população para o pai
                            randMother = rand.Next(parentCount); //Gera uma posição aleatória na população para a mãe
                        }while (randFather == randMother);       //Se as posições de pai e mãe forem as mesmas, repetir o processo

                        //Obtém o indivíduo pai correspondente à posição da população gerada aleatoriamente
                        Individuo father = PossibleParents[randFather];
                        //Obtém o indivíduo mãe correspondente à posição da população gerada aleatoriamente
                        Individuo mother = PossibleParents[randMother];

                        Parents.Add(father);                               //Adiciona o pai à lista daqueles que já tiveram filhos
                        Parents.Add(mother);                               //Adiciona a mãe à lista daqueles que já tiveram filhos
                        PossibleParents.Remove(father);                    //Remove o pai da lista de possíveis pais
                        PossibleParents.Remove(mother);                    //Remove a mãe da lista de possíveis pais

                        Individuo child;                                   //Declara o indivíduo filho
                        child = Individuo.Offspring(father, mother, rand); //Gera o filho de acordo com os genes do pai e da mãe
                        Children.Add(child);                               //Adiciona a criança à lista de filhos
                    }
                    else
                    {
                        //Se não houver mais pais mas ainda faltar filhos
                        Individuo new_child = new Individuo(Map, rand);
                        Children.Add(new_child);            //Adicione um filho que será um novo indivíduo aleatório
                    }
                }

                //Adicione à lista de filhos os piores indivíduos da população
                //(É possível que existam filhos piores do que os piores indivíduos da população anterior)
                Children.AddRange(PopulationWorst);
                //Ordenar a lista de filhos de acordo com a função de fitness (distância do percurso)
                Children.Sort((x, y) => x.distance.CompareTo(y.distance));
                //Manter apenas os melhores indivíduos entre essa população (1/3 do total)
                //Children = Children.Take<Individuo>(NPop - parentFraction).ToList();
                Children = Children.GetRange(0, NPop - parentFraction);
                //Adiciona esses filhos novamente à população total
                Population.AddRange(Children);

                if (NMut > 0)       //Se a chance de mutação for maior que 0
                {
                    //Para cada indivíduo na população...
                    foreach (Individuo indv in Population)
                    {
                        //Se esse indivíduo for o melhor indivíduo da população atual...
                        if (indv == Population.First())
                        {
                            //Passe para o próximo indivíduo, esse aqui é muito bom para sofrer mutação
                            //Just too good for it
                            continue;
                        }
                        //Obtém um número aleatório entre 0.0 e 1.0
                        double chance = rand.NextDouble();
                        //Multiplicar esse número por 100, para colocá-lo na faixa de 0.0 à 100.0
                        chance *= 100;
                        //Se o valor estiver abaixo do valor de mutação definido pelo usuário...
                        if (chance <= NMut)
                        {
                            indv.Mutate(rand);          //Realizar a mutação no indivíduo
                            indv.RecalculateDistance(); //Recalcular o fitness desse indivíduo
                        }
                    }
                }

                iterationCount++;                       //Incrementa o valor da geração atual

                this.Invoke((MethodInvoker) delegate
                {
                    //Atualiza o valor do textbox que exibe a melhor distância
                    pathLengthBox.Text = Population[0].distance.ToString("#0.0");
                    //Atualiza o valor da label, que está em outra Thread
                    label6.Text = iterationCount.ToString();
                });

                if (bestDist <= Population[0].distance)
                {
                    noProgressIterations++;
                }
                else
                {
                    noProgressIterations = 0;
                }

                //Define que a melhor distância é aquela do indivíduo na primeira posição
                bestDist = Population[0].distance;
                //Se todos os indivíduos da população tiverem esse mesmo valor, todos são iguais
                allEqual = Population.All(o => o.distance == bestDist);

                if (allEqual)
                {
                    ResetarPopulacao(Population, rand);
                }
                else if (noProgressIterations >= Math.Max(NGer * 0.025, 20))
                {
                    if (noProgressIterations > NGer * 0.2)
                    {
                        //Early Convergence
                        break;
                    }
                    else
                    {
                        ResetarPopulacao(Population, rand);
                    }
                }
            }

            //Reordena a população de acordo com a função de fitness (distância do percurso)
            //Population.Sort((x, y) => x.distance.CompareTo(y.distance));;

            //Declara uma matriz de Número de cidades x 2 que armazenará o melhor caminho
            double[,] path = new double[NCities, 2];

            //Adiciona os genes do melhor indivíduo da população à lista do melhor caminho
            Path.AddRange(Population[0].genes);
            //Converte essa lista em uma matriz que será utilizada para desenhar o caminho
            path = ListToMatrix(Path);
            //Obtém as coordenadas do ponto de início/fim, que correspondem ao primeiro item do caminho
            double[,] start_end = new double[, ] {
                { Path[0].X, Path[0].Y }
            };

            //atualiza mapa com o caminho a ser percorrido:
            mapControl.UpdateDataSeries("path", path);
            //Atualiza o mapa com o ponto de início e fim
            mapControl.UpdateDataSeries("start_end", start_end);

            //calcula o caminho total percorrido:
            double caminho = Population[0].distance;

            pathLengthBox.Invoke((MethodInvoker) delegate
            {
                //Atualiza o valor do textbox que exibe a melhor distância
                pathLengthBox.Text = caminho.ToString("#0.0");
            });

            this.Invoke((MethodInvoker) delegate
            {
                //Permite que as textbox sejam modificadas novamente
                iterationsBox.ReadOnly     = false;
                populationSizeBox.ReadOnly = false;
                mutationChanceBox.ReadOnly = false;
                citiesCountBox.ReadOnly    = false;
            });
            //Anula a Thread que executa o algoritmo genético
            GA_Thread = null;
        }
Пример #44
0
 public void AppendToTextArea(string text)
 {
     textArea.Invoke(new AppendTextDelegate(AppendTextHelper), new object[] { textArea, text });
 }
        private void BtnImport_OnClick(object sender, EventArgs args)
        {
            WorkAsync(new WorkAsyncInfo
            {
                Message = "Importing the option sets...",
                Work    = (w, e) =>
                {
                    cmbOptionSet.Invoke((MethodInvoker) delegate
                    {
                        selectedAttributeLogicalName = (string)cmbOptionSet.SelectedValue;
                    });

                    txtResult.Invoke((MethodInvoker) delegate
                    {
                        txtResult.Clear();
                    });

                    OptionMetadataCollection existingOptions = Helper.GetOptionSetEntries(Service, selectedEntityLogicalName, selectedAttributeLogicalName);

                    ExecuteMultipleRequest multipleRequest = new ExecuteMultipleRequest();
                    multipleRequest.Settings = new ExecuteMultipleSettings();
                    multipleRequest.Settings.ContinueOnError = false;
                    multipleRequest.Settings.ReturnResponses = true;
                    multipleRequest.Requests = new OrganizationRequestCollection();

                    foreach (Model.ImportDataRow row in importData)
                    {
                        if (existingOptions.Any(_ => _.Value == row.Value))
                        {
                            //merge
                            List <KeyValuePair <int, string> > labels = new List <KeyValuePair <int, string> >();
                            OptionMetadata metadata = existingOptions.FirstOrDefault(_ => _.Value == row.Value);
                            if (metadata.Label != null && metadata.Label.LocalizedLabels != null)
                            {
                                // initit labels collection with original labels
                                foreach (LocalizedLabel item in metadata.Label.LocalizedLabels)
                                {
                                    labels.Add(new KeyValuePair <int, string>(item.LanguageCode, item.Label));
                                }

                                // override the existing labels
                                if (!row.IsLabel1031Null() && labels.Any(_ => _.Key == 1031))
                                {
                                    labels.Remove(labels.First(_ => _.Key == 1031));
                                    labels.Add(new KeyValuePair <int, string>(1031, row.Label1031));
                                }//if

                                if (!row.IsLabel1033Null() && labels.Any(_ => _.Key == 1033))
                                {
                                    labels.Remove(labels.First(_ => _.Key == 1033));
                                    labels.Add(new KeyValuePair <int, string>(1033, row.Label1033));
                                }//if

                                if (!row.IsLabel1036Null() && labels.Any(_ => _.Key == 1036))
                                {
                                    labels.Remove(labels.First(_ => _.Key == 1036));
                                    labels.Add(new KeyValuePair <int, string>(1036, row.Label1036));
                                }//if

                                if (!row.IsLabel1040Null() && labels.Any(_ => _.Key == 1040))
                                {
                                    labels.Remove(labels.First(_ => _.Key == 1040));
                                    labels.Add(new KeyValuePair <int, string>(1040, row.Label1040));
                                }//if

                                if (!row.IsLabel3082Null() && labels.Any(_ => _.Key == 3082))
                                {
                                    labels.Remove(labels.First(_ => _.Key == 3082));
                                    labels.Add(new KeyValuePair <int, string>(3082, row.Label3082));
                                }//if

                                // create insert request
                                multipleRequest.Requests.Add(Helper.CreateUpdateOptionValueRequest(Service,
                                                                                                   languageCodeOfUser,
                                                                                                   selectedEntityLogicalName,
                                                                                                   selectedAttributeLogicalName,
                                                                                                   labels,
                                                                                                   row.Value));
                            }//if
                        }
                        else
                        {
                            List <KeyValuePair <int, string> > labels = new List <KeyValuePair <int, string> >();
                            if (!row.IsLabel1031Null())
                            {
                                labels.Add(new KeyValuePair <int, string>(1031, row.Label1031));
                            }

                            if (!row.IsLabel1033Null())
                            {
                                labels.Add(new KeyValuePair <int, string>(1033, row.Label1033));
                            }

                            if (!row.IsLabel1036Null())
                            {
                                labels.Add(new KeyValuePair <int, string>(1036, row.Label1036));
                            }

                            if (!row.IsLabel1040Null())
                            {
                                labels.Add(new KeyValuePair <int, string>(1040, row.Label1040));
                            }

                            if (!row.IsLabel3082Null())
                            {
                                labels.Add(new KeyValuePair <int, string>(3082, row.Label3082));
                            }

                            // create insert request
                            multipleRequest.Requests.Add(Helper.CreateInsertOptionValueRequest(Service,
                                                                                               languageCodeOfUser,
                                                                                               selectedEntityLogicalName,
                                                                                               selectedAttributeLogicalName,
                                                                                               labels,
                                                                                               row.Value));
                        }
                    }//foreach

                    //multipleRequest.Requests.Add(new PublishAllXmlRequest());

                    ExecuteMultipleResponse response = (ExecuteMultipleResponse)Service.Execute(multipleRequest);

                    txtResult.Invoke((MethodInvoker) delegate
                    {
                        if (!response.IsFaulted)
                        {
                            txtResult.Text = "Successfully performed the import - please publish the entity.";
                        }
                        else
                        {
                            foreach (ExecuteMultipleResponseItem responseItem in response.Responses)
                            {
                                txtResult.Text = responseItem.Fault.Message + Environment.NewLine + txtResult.Text;
                            }//foreach
                        }
                    });
                },
                ProgressChanged = e =>
                {
                },
                PostWorkCallBack = e =>
                {
                },
                AsyncArgument = null,
                IsCancelable  = true,
                MessageWidth  = 340,
                MessageHeight = 150
            });
        }
Пример #46
0
        private void UpdateTextbox(TextBox txt, string s)
        {
            if (txt.InvokeRequired)
            {
                txt.Invoke(new Action<TextBox, string>(UpdateTextbox), new object[] { txt, s });
            }

            else
            {
                txt.Text = s;
            }
        }
Пример #47
0
 private void SetTextBox(TextBox textBox, string text)
 {
     textBox.Invoke(new SetTextDelegate(SetTextHelper), new object[] { textBox, text });
 }
Пример #48
0
 public static void AddMainThreadHintText(TextBox txt, string msg)
 {
     if (txt.InvokeRequired)
     {
         AddMainThreadHintTextDelegate msgCallback = new AddMainThreadHintTextDelegate(WindowFormDelegate.AddMainThreadHintText);
         txt.Invoke(msgCallback, new object[] { txt, msg });
     }
     else
     {
         txt.Text += msg;
     }
 }
Пример #49
-1
        public static void CreateMessage(TextBox box, string msg, bool timer = true, bool appendText = true)
        {
            //set timer string depending on parameter
            string timerLinespacing = "  ";
            string theTime;
            string newline = "\r\n";
            if (timer) { theTime = DateTime.Now.ToString("HH:mm:ss tt"); }
            else { theTime = ""; }

            if (appendText)
            {
                if (box.InvokeRequired)
                {
                    box.Invoke(new MethodInvoker(delegate { box.Text += theTime + timerLinespacing + msg + newline; }));
                }
                else
                {
                    box.Text += theTime + timerLinespacing + msg + newline;
                }
            }
            else
            {
                if (box.InvokeRequired)
                {
                    box.Invoke(new MethodInvoker(delegate { box.Text = msg + newline; }));
                }
                else
                {
                    box.Text = msg + newline;
                }
            }
        }