Exemplo n.º 1
1
 public static void SetCtrlEnable(Form parentForm, Control ctrl, bool value)
 {
     if (parentForm.InvokeRequired)
     {
         SetCtrlEnableHandler method = new SetCtrlEnableHandler(SetCtrlEnableMethod);
         parentForm.BeginInvoke(method, new object[] { ctrl, value });
     }
     else
     {
         SetCtrlEnableMethod(ctrl, value);
     }
 }
		private void ExecuteInThread(ThreadStart run)
		{
			Exception uncaughtException = null;
			var thread = new Thread(() =>
			{
				try
				{
					run();
				}
				catch (Exception e)
				{
					uncaughtException = e;
				}

				Application.DoEvents();
				Application.Exit();
			});

			var form = new Form();
			if (form.Handle == IntPtr.Zero)
			{
				throw new InvalidOperationException("Control handle could not be obtained");
			}
			var invoke = form.BeginInvoke((MethodInvoker)thread.Start);

			Application.Run();
			form.EndInvoke(invoke);
			if (uncaughtException != null)
			{
				preserveStackTrace.Invoke(uncaughtException, null);
				throw uncaughtException;
			}
		}
Exemplo n.º 3
0
 public static void ShowForm(Form form, bool show)
 {
     if (form.InvokeRequired)
     {
         form.BeginInvoke(new Action(() =>
         {
             if (show)
             {
                 form.Show();
                 form.BringToFront();
                 form.WindowState = FormWindowState.Normal;
             }
             else
             {
                 form.Hide();
                 form.WindowState = FormWindowState.Minimized;
             }
         }));
     }
     else
     {
         if (show)
         {
             form.Show();
             form.BringToFront();
             form.WindowState = FormWindowState.Normal;
         }
         else
         {
             form.Hide();
             form.WindowState = FormWindowState.Minimized;
         }
     }
 }
Exemplo n.º 4
0
        private static void DownloadUpdate(Form form, UpdateItem updateItem)
        {
            if (form.InvokeRequired)
            {
                form.BeginInvoke(new MethodInvoker(() => DownloadUpdate(form, updateItem)));
                return;
            }

            new UpdaterDownloadWindow(updateItem).ShowDialog(form);
        }
Exemplo n.º 5
0
 private void PerformSetVisualState(SWF.Form form, SWF.FormWindowState state)
 {
     if (form.InvokeRequired == true)
     {
         form.BeginInvoke(new PerformSetVisualStateDelegate(PerformSetVisualState),
                          new object [] { form, state });
         return;
     }
     form.WindowState = state;
 }
Exemplo n.º 6
0
 public static void UIThread(this Form @this, Action <object[]> action, params object[] args)
 {
     if (@this.InvokeRequired)
     {
         @this.BeginInvoke(action, args);
     }
     else
     {
         action.Invoke(args);
     }
 }
Exemplo n.º 7
0
 /// <summary>Executes Action asynchronously on the UI thread, without blocking the calling thread.</summary>
 /// <param name="this"></param>
 /// <param name="action"></param>
 public static void UIThread(this Form @this, Action action)
 {
     if (@this.InvokeRequired)
     {
         @this.BeginInvoke(action);
     }
     else
     {
         action.Invoke();
     }
 }
Exemplo n.º 8
0
        public static void AttachForm(Form form)
        {
            Action<string> handler = msg => form.BeginInvoke((Action)(() =>
            {
                form.Text = msg;
                form.Refresh();
            }));

            MessageSanded += handler;
            form.Closed += (s, e) => MessageSanded -= handler;
        }
 public void BeginInvokeOnMainThread(Action action)
 {
     if (_mainForm.IsHandleCreated)
     {
         _mainForm.BeginInvoke(action);
     }
     else
     {
         action();
     }
 }
Exemplo n.º 10
0
        static void DoFade(Form form, double fromOpacity, double toOpacity, double durationMsec, Action endCallback)
        {
            form.BeginInvoke(new Action(delegate
            {
                Fade(form, fromOpacity, toOpacity, durationMsec);

                if (endCallback != null)
                {
                    endCallback();
                }
            }));
        }
Exemplo n.º 11
0
 public static void SetCtrlTag(Form parentForm, Control ctrl, string value)
 {
     if (parentForm.InvokeRequired)
     {
         SetCtrlTagHandler method = new SetCtrlTagHandler(SetCtrlTagMethod);
         parentForm.BeginInvoke(method, new object[] { ctrl, value });
     }
     else
     {
         SetCtrlTagMethod(ctrl, value);
     }
 }
Exemplo n.º 12
0
 public static void ChangeComboBoxValue(Form parentForm, ComboBox ctrl)
 {
     if (parentForm.InvokeRequired)
     {
         ChangeComboBoxValueHandler method = new ChangeComboBoxValueHandler(ChangeComboBoxValueMethod);
         parentForm.BeginInvoke(method, new object[] { ctrl });
     }
     else
     {
         ChangeComboBoxValueMethod(ctrl);
     }
 }
Exemplo n.º 13
0
 public static void AddCtrlValue(Form parentForm, Control ctrl, string value)
 {
     if (parentForm.InvokeRequired)
     {
         AddCtrlValueHandler method = new AddCtrlValueHandler(AddCtrlValueMethod);
         parentForm.BeginInvoke(method, new object[] { ctrl, value });
     }
     else
     {
         AddCtrlValueMethod(ctrl, value);
     }
 }
Exemplo n.º 14
0
 protected override void Dispose(bool disposing)
 {
     if (this.Created)
     {
         owneForm.BeginInvoke(new Action(() =>
         {
             owneForm.Controls.Remove(this);
             foreach (Control item in this.disableControls)
             {
                 item.Visible = true;
             }
             base.Dispose(disposing);
         }));
     }
 }
Exemplo n.º 15
0
        /// <summary>
        /// Colse the SplashForm
        /// </summary>
        public static void Close()
        {
            if (_SplashThread == null || _SplashForm == null)
            {
                return;
            }

            try
            {
                _SplashForm.BeginInvoke(new MethodInvoker(_SplashForm.Close));
            }
            finally
            {
                _SplashThread = null;
                _SplashForm   = null;
            }
        }
Exemplo n.º 16
0
 public void DanglingWindowMessage()
 {
     using (OuterTest nuf = new OuterTest())
     {
         Form f = new Form();
         f.Show();
         System.Threading.EventWaitHandle w = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
         System.Threading.ThreadPool.QueueUserWorkItem(delegate(object o)
         {
             f.BeginInvoke(new MethodInvoker(delegate()
             {
                 MessageBox.Show("", "Blah");
             }));
             w.Set();
         });
         w.WaitOne();
         Assert.Throws<FormsTestAssertionException>(() => nuf.Verify());
     }
 }
Exemplo n.º 17
0
 public static void StopFlash(Form form)
 {
     try
     {
         if (form.InvokeRequired)
         {
             form.BeginInvoke(new Action<Form>(WindowFlasher.StopFlash), new object[]
             {
                 form
             });
         }
         else
         {
             InternalFlash(form, FlashFlags.FLASHW_STOP);
         }
     }
     catch (Exception ex)
     {
         Logger.Log.Error("Error trying to stop flashing the window.", ex);
     }
 }
Exemplo n.º 18
0
 public static void Flash(Form form)
 {
     if (form.InvokeRequired)
     {
         form.BeginInvoke(new Action<Form>(WindowFlasher.Flash), new object[]
         {
             form
         });
     }
     else
     {
         InternalFlash(form, FlashFlags.FLASHW_ALL);
         System.Timers.Timer timer = new System.Timers.Timer
         {
             AutoReset = false,
             Interval = 2000.0
         };
         timer.Elapsed += (s, ea) => StopFlash(form);
         timer.Start();
     }
 }
Exemplo n.º 19
0
    private static async Task<Report> CrawlDate(Form ui, Request request)
    {
      var completed = new ManualResetEvent(false);
      Report r = null;

      Action initAction = () =>
      {
        var crawler = new SkyCrawler();
        crawler.Load += async delegate
        {
          r = await crawler.Analyze(request);

          var dates = request.From.ToDateString() + "-" + request.To.ToDateString();
          string path = Path.Combine("e:\\Flights", request.Source + "-" + request.Dectination,
            dates + ".xml");
          Directory.CreateDirectory(Path.GetDirectoryName(path));

          r.ToXml(path);
          crawler.Close();
          completed.Set();

          if (r.Data.Length > 0)
          {
            Console.Out.WriteLine("{0} -> {1}: {2}", dates, request.Dectination, r.Data[0].Price);
          }
        };
        crawler.Show();
      };

      await Task.Factory.FromAsync(
        ui.BeginInvoke(initAction),
        x => { ui.EndInvoke(x);  });

      return await Task.Factory.StartNew(() =>
      {
        completed.WaitOne();
        return r;
      });      
    }
Exemplo n.º 20
0
        public void Play( Form on )
        {
            var screens = Screen.AllScreens;
            var screens_left  = screens.Min( screen => screen.Bounds.Left  );
            var screens_right = screens.Max( screen => screen.Bounds.Right );
            var screens_width = screens_right-screens_left;

            var bestScreen = screens.OrderByDescending( screen => {
                var area = screen.Bounds;
                area.Intersect( on.Bounds );
                return area.Width*area.Height;
            }).First();

            var balances = new[]{1.5f,1.5f};
            if ( screens.Length==3 && DisplayBalances.ContainsKey(bestScreen.DeviceName) ) balances = DisplayBalances[bestScreen.DeviceName];

            var path   = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\.Default\"+Name+@"\.Current").GetValue(null) as string;
            var stream = new WaveStream(path);
            var buffer = new AudioBuffer() { AudioBytes=(int)stream.Length, AudioData=stream, Flags=BufferFlags.EndOfStream };

            var voice = new SourceVoice( XAudio2, stream.Format );
            voice.SubmitSourceBuffer( buffer );
            voice.SetChannelVolumes( balances.Length, balances );
            voice.BufferEnd += (sender,ctx) => {
                try {
                    on.BeginInvoke(new Action(()=>{
                        voice.Dispose();
                        buffer.Dispose();
                        stream.Dispose();
                    }));
                } catch ( InvalidOperationException ) {
                    // herp derp on must be disposed/gone
                }
            };
            voice.Start();
        }
Exemplo n.º 21
0
    static void Main()
    {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);

      var progressForm = new Form();
      progressForm.Load += async (sender, args) =>
      {
        var enumerable = Tasks().ToArray();
        int c = 0;
        foreach (var request in enumerable)
        {
          c++;
          progressForm.BeginInvoke((Action) (() =>
          {
            progressForm.Name = progressForm.Text = string.Format("{0} of {1}", c, enumerable.Length);
          }));

          await CrawlDate(progressForm, request);
        }
        progressForm.Close();
      };
      Application.Run(progressForm);
    }
Exemplo n.º 22
0
        public void uploadFile(Form attachedForm, FileType type, string fullFileName, string fileName, 
            byte[] fileContent, byte[] parseData, Dictionary<string,string> paramKeyValues)
        {
            new Thread(delegate()
            {
                byte[] respData;
                string json;
                WebHeaderCollection headers;
                string url = getUrl(Action.uploadfile);
                url += "/" + type.ToString();
                if (paramKeyValues != null && paramKeyValues.Count > 0)
                {
                    int i = 0;
                    foreach (KeyValuePair<string,string> pair in paramKeyValues)
                    {
                        if (i == 0)
                            url += "?";
                        else
                            url += "&";
                        url += pair.Key + "=" + pair.Value;
                        i++;
                    }
                }

                UploadFileData uploadFileData = new UploadFileData();
                uploadFileData.ShortName = fileName;
                uploadFileData.Uploader = HTTPAgent.Username;
                uploadFileData.Md5 = Utility.MD5File(fullFileName);
                uploadFileData.FileContent = fileContent;
                uploadFileData.ParseData = parseData;
                byte[] sendBytes = uploadFileData.ToBytes();

                HttpStatusCode statusCode = HTTPRequest.MakeRequest(url, "POST",
                    Constants.JSON_MIME, Constants.RAW_MIME,
                    sendBytes, out respData, out headers);
                if (statusCode == HttpStatusCode.Accepted)
                {
                    FileDescription description;
                    if (respData != null)
                    {
                        json = Encoding.UTF8.GetString(respData);
                        description = Utility.JsonDeserialize<FileDescription>(json);
                        if (onUploadFileSuccessfully != null)
                        {
                            attachedForm.BeginInvoke(onUploadFileSuccessfully, type, description, parseData);
                        }
                    }
                }
                else
                {
                    ErrorMessage errMsg = null;
                    if (respData != null)
                    {
                        json = Encoding.UTF8.GetString(respData);
                        errMsg = Utility.JsonDeserialize<ErrorMessage>(json);
                    }

                    if (onUploadFileFailed != null)
                        attachedForm.BeginInvoke(onUploadFileFailed, fullFileName, statusCode, errMsg);
                }

            }).Start();
        }
Exemplo n.º 23
0
 public static void FocusWindow(Form f)
 {
     if (f.InvokeRequired)
     {
         f.BeginInvoke(new MethodInvoker(delegate { Program.FocusWindow(f); }));
         return;
     }
     f.Visible = true;
     if (f.WindowState == FormWindowState.Minimized)
         f.WindowState = FormWindowState.Normal;
     f.Activate();
 }
Exemplo n.º 24
0
 public static void postFunctionCall(Form form, PostFuncVoid postFuncVoid)
 {
     try
     {
         form.BeginInvoke(new PostFuncVoid(postFuncVoid.Invoke));
     }
     catch
     {
         ErrMsg("WDS_Common", "Invoking Invoke(new PostFuncVoid(postFuncVoid)) failed");
     }
 }
Exemplo n.º 25
0
        static void Main()
        {
            task.Prepare();

            var targetFunction = new Series()
            {
                ChartType = SeriesChartType.Line,
                Color = Color.Red,
                BorderWidth = 2
            };
            for (int i = 0; i < task.Inputs.Length; i++)
                targetFunction.Points.Add(new DataPoint(task.Inputs[i][0], task.Answers[i][0]));

            computedFunction = new Series()
            {
                ChartType = SeriesChartType.Line,
                Color = Color.Green,
                BorderWidth = 2
            };

            history = new HistoryChart
                    {
                        Max = task.MaxError,
                        DotsCount=200,
                        Lines =
                        {
                            new HistoryChartValueLine
                            {
                                DataFunction = { Color = Color.Blue }
                            }
                        },
                        Dock = DockStyle.Bottom
                    };

            form = new Form()
            {
                Text = task.GetType().Name,
                Size = new Size(800, 600),
                FormBorderStyle = FormBorderStyle.FixedDialog,
                Controls =
                {
                    new Chart
                    {
                        ChartAreas =
                        {
                            new ChartArea
                            {
                                AxisX=
                                {
                                    Minimum = task.Inputs.Min(z=>z[0]),
                                    Maximum = task.Inputs.Max(z=>z[0])
                                },
                                AxisY=
                                {
                                    Minimum = Math.Min(-1.5,task.Answers.Min(z=>z[0])),
                                    Maximum = Math.Max(1.5, task.Answers.Max(z=>z[0]))
                                }
                            }
                        },
                        Series = { targetFunction, computedFunction },
                        Dock= DockStyle.Top
                    },
                    history
                }
            };

            task.UpdateCharts += (s, a) => form.BeginInvoke(new Action(UpdateCharts));
            new Action(task.Learn).BeginInvoke(null, null);
            Application.Run(form);
        }
		private void ExecuteInThread(ThreadStart run)
		{
			var thread = new Thread(() =>
			{
				try
				{
					run();
				}
				catch (Exception e)
				{
					uncaughtException = e;
				}

				Application.DoEvents();
				Application.Exit();
			});

			var form = new Form();
			if (form.Handle == IntPtr.Zero)
			{
				throw new InvalidOperationException("Control handle could not be obtained");
			}
			form.BeginInvoke((MethodInvoker)delegate { thread.Start(); });

			Application.Run();
		}
Exemplo n.º 27
0
        //Obsługa danych przychodzących od odbiornika GPS
        private void DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            serialPort.Read(receivedData, 0, 512);
            StringBuilder stringBuilder = new StringBuilder();

            i = 0;
            while (true)
            {   //Wykrycie poszukiwanej sekwencji
                if (receivedData[i] == 'G' && receivedData[i + 1] == 'G' && receivedData[i + 2] == 'A')
                {
                    i += 3;
                    MoveData(receivedData, time);
                    MoveData(receivedData, latitude);
                    MoveData(receivedData, deg1);
                    MoveData(receivedData, longitude);
                    MoveData(receivedData, deg2);
                    MoveData(receivedData, status);
                    MoveData(receivedData, satellitesNumber);
                    MoveData(receivedData, horizontalDilution);
                    MoveData(receivedData, altitude);
                    break;
                }
                if (i == 509)
                {
                    break;
                }
                i++;
            }

            String strLatitude         = new string(latitude);
            String strDeg1             = new string(deg1);
            String strLongitude        = new string(longitude);
            String strDeg2             = new string(deg2);
            String strStatus           = new string(status);
            String strSatellitesNumber = new string(satellitesNumber);
            String strAltitude         = new string(altitude);

            stringBuilder.Append("Czas: " + time[0].ToString() + time[1].ToString() + ":" + time[2].ToString() + time[3].ToString() + ":" + time[4].ToString() + time[5].ToString());
            stringBuilder.Append(Environment.NewLine);
            stringBuilder.Append("Szerokość: " + strLatitude + " " + strDeg1);
            stringBuilder.Append(Environment.NewLine);
            stringBuilder.Append("Dlugość " + strLongitude + " " + strDeg2);
            stringBuilder.Append(Environment.NewLine);
            int statusInt = Int32.Parse(strStatus);

            if (statusInt == 1)
            {
                state = " - fix GPS";
            }
            if (statusInt == 0)
            {
                state = " - brak fixa";
            }

            stringBuilder.Append("Status fixa: " + strStatus + " " + state);
            stringBuilder.Append(Environment.NewLine);
            stringBuilder.Append("Liczba Satelitów: " + strSatellitesNumber);
            stringBuilder.Append(Environment.NewLine);
            stringBuilder.Append("Wysokość (m n.p.m.): " + strAltitude);
            stringBuilder.Append(Environment.NewLine);
            latit         = Double.Parse(strLatitude, System.Globalization.CultureInfo.InvariantCulture);
            longit        = Double.Parse(strLongitude, System.Globalization.CultureInfo.InvariantCulture);
            minLatitude   = (int)Math.Floor(latit);
            minLongitude  = (int)Math.Floor(longit);
            latitudeA     = minLatitude;
            longitudeA    = minLongitude;
            minLatitude  %= 100;
            latitudeA    /= 100;
            minLongitude %= 100;
            longitudeA   /= 100;

            stringBuilder.Append("Szerokość geograficzna: " + latitudeA + " stopni " + minLatitude + "'" + (latit - (int)latit) * 60 + "\"");
            stringBuilder.Append(Environment.NewLine);
            stringBuilder.Append("Dlugosc geograficzna: " + longitudeA + " stopni " + minLongitude + "'" + (longit - (int)longit) * 60 + "\"");
            stringBuilder.Append(Environment.NewLine);

            if (stringBuilder.ToString() != null)
            {
                forms.BeginInvoke(new SetTextCallback((string text) => { dataTextBox.Text = text; }), new object[] { stringBuilder.ToString() });
            }
        }
        public ConsultaSimplesEstrutura(
            Form tela,
            Action<ModeloCliente> telaCliente,
            Action<ModeloProcesso> telaProcesso,
            RadioButton opcaoPesquisaCliente,
            RadioButton opcaoPesquisaProcesso,
            NumberTextBox codigoCliente,
            TextBoxBase nomeCliente,
            TextBoxBase cpfCliente,
            TextBoxBase rgCliente,
            NumberTextBox codigoProcesso,
            TextBoxBase numeroProcesso,
            TextBoxBase cabecaProcesso,
            ButtonBase botaoPesquisar,
            ButtonBase botaoFichaCadastral,
            ButtonBase botaoProcuracaoINSS,
            DataGridView gridPesquisa
            )
        {
            ClientePesquisa = new Cliente();
            ProcessoPesquisa = new Processo();
            GridPesquisa = gridPesquisa;
            Tela = tela;
            TelaCliente = telaCliente;
            TelaProcesso = telaProcesso;

            opcaoPesquisaCliente.CheckedChanged += (sender, args) =>
            {
                GridPesquisa.DataSource = null;
                TipoConsulta = opcaoPesquisaCliente.Checked ? eTipoConsulta.Cliente : eTipoConsulta.Processo;
            };
            opcaoPesquisaProcesso.CheckedChanged += (sender, args) =>
            {
                GridPesquisa.DataSource = null;
                TipoConsulta = opcaoPesquisaProcesso.Checked ? eTipoConsulta.Processo : eTipoConsulta.Cliente;
            };

            codigoCliente.GotFocus += (sender, args) => tela.BeginInvoke(new Action(() => codigoCliente.SelectAll()));
            codigoCliente.PropertyChanged += (sender, args) =>
            {
                if (args.PropertyName == "Value")
                {
                    ClientePesquisa.Id = codigoCliente.Value;
                }
            };
            ClientePesquisa.IdAlterado += (antigo, novo) => codigoCliente.Value = novo;

            nomeCliente.TextChanged += (sender, args) => ClientePesquisa.Nome = nomeCliente.Text;
            ClientePesquisa.NomeAlterado += (antigo, novo) => nomeCliente.Text = novo;

            cpfCliente.TextChanged += (sender, args) => ClientePesquisa.Cpf = cpfCliente.Text;
            ClientePesquisa.CpfAlterado += (antigo, novo) => cpfCliente.Text = novo;

            rgCliente.TextChanged += (sender, args) => ClientePesquisa.Rg = rgCliente.Text;
            ClientePesquisa.RgAlterado += (antigo, novo) => rgCliente.Text = novo;

            codigoProcesso.GotFocus += (sender, args) => tela.BeginInvoke(new Action(() => codigoProcesso.SelectAll()));
            codigoProcesso.PropertyChanged += (sender, args) =>
            {
                if (args.PropertyName == "Value")
                {
                    ProcessoPesquisa.Id = codigoProcesso.Value;
                }
            };
            ProcessoPesquisa.IdAlterado += (antigo, novo) => codigoProcesso.Text = novo.ToString();

            numeroProcesso.TextChanged += (sender, args) => ProcessoPesquisa.NumeroProcesso = numeroProcesso.Text;
            ProcessoPesquisa.NumeroProcessoAlterado += (antigo, novo) => numeroProcesso.Text = novo;

            cabecaProcesso.TextChanged += (sender, args) => ProcessoPesquisa.Cabeca.Nome = cabecaProcesso.Text;
            ProcessoPesquisa.Cabeca.NomeAlterado += (antigo, novo) => cabecaProcesso.Text = novo;

            botaoPesquisar.Click += new EventHandler(botaoPesquisar_Click);
            botaoFichaCadastral.Click += new EventHandler(botaoFichaCadastral_Click);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Closes the splash screen window.
        /// </summary>
        /// <remarks>Documented by Dev02, 2008-06-26</remarks>
        private void CloseSplash()
        {
            //remove event handlers
            Application.Idle -= new EventHandler(Application_Idle);
            Application.EnterThreadModal -= new EventHandler(Application_EnterThreadModal);

            if (splashThread == null || splashForm == null)
                return;

            //fade in mainForm
            if (mainForm != null)
            {
                mainForm.BeginInvoke(new MethodInvoker(delegate()
                {
                    if (enableFadingMain)
                        FadeForm(mainForm, 0.05);
                    mainForm.Opacity = 1;
                }));
            }

            //fade out splashform
            splashForm.BeginInvoke(new MethodInvoker(delegate()
            {
                if (enableFadingSplash)
                    FadeForm(splashForm, -0.10);
                splashForm.Close();
                splashForm = null;
                splashThread = null;
            }));
        }
Exemplo n.º 30
0
        public static void CheckForUpdates(Form form, bool verbose)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(Uri.EscapeUriString(string.Format("http://trizbort.genstein.net/webservice.php?op=updatecheck&current={0}", Application.ProductVersion)));
                var response = (HttpWebResponse)request.GetResponse();

                string responseText;
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    responseText = reader.ReadToEnd();
                }

                var latestVersion = new Version(responseText.Split('\n')[0].Replace("\r", string.Empty).Trim());
                if (latestVersion.Major < 0)
                {
                    latestVersion = new Version(0, 0, 0, 0);
                }
                if (latestVersion.Minor < 0)
                {
                    latestVersion = new Version(latestVersion.Major, 0, 0, 0);
                }
                if (latestVersion.Build < 0)
                {
                    latestVersion = new Version(latestVersion.Major, latestVersion.Minor, 0, 0);
                }
                if (latestVersion.Revision < 0)
                {
                    latestVersion = new Version(latestVersion.Major, latestVersion.Minor, latestVersion.Build, 0);
                }
                var currentVersion = Assembly.GetExecutingAssembly().GetName().Version;
                if (currentVersion < latestVersion)
                {
                    form.BeginInvoke((MethodInvoker)delegate()
                    {
                        Show(currentVersion, latestVersion, verbose);
                    });
                }
                else if (verbose)
                {
                    form.BeginInvoke((MethodInvoker)delegate() { MessageBox.Show(form, string.Format("Your version of Trizbort is {0}", currentVersion == latestVersion ? "up to date." : "more recent than the latest version!"), Application.ProductName, MessageBoxButtons.OK); });
                }
            }
            catch (Exception ex)
            {
                if (verbose)
                {
                    MessageBox.Show(form, string.Format("An error occurred whilst checking for the latest version of Trizbort.\n\n{0}", ex.Message), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Exemplo n.º 31
0
 public CenterDialog(Form owner)
 {
     _owner = owner;
     owner.BeginInvoke(new MethodInvoker(FindDialog));
 }
        public ConsultaProcessoClienteEstrutura(
            Form tela,
            Action<Modelo.Processo.ModeloProcesso> fichaProcesso,
            Label navegacao,
            NumberTextBox codigoCliente,
            TextBoxBase nomeCliente,
            TextBoxBase codigoProcesso,
            TextBoxBase numeroProcesso,
            TextBoxBase numeroOrdemProcesso,
            TextBoxBase varaProcesso,
            TextBoxBase cabecaProcesso,
            TextBoxBase tipoAcaoProcesso,
            TextBoxBase reuProcesso,
            TextBoxBase dataAjuizamentoProcesso,
            ListBox responsaveisProcesso,
            TextControl objetivoProcesso,
            TextControl andamentoProcesso,
            ButtonBase botaoPesquisar,
            ButtonBase botaoAnterior,
            ButtonBase botaoProximo,
            ButtonBase botaoFichaCompleta
            )
        {
            ListaProcessos = new List<Processo>();
            ClientePesquisa = new Cliente();

            codigoCliente.GotFocus += (sender, args) => tela.BeginInvoke(new Action(() => codigoCliente.SelectAll()));
            codigoCliente.PropertyChanged += (sender, args) =>
            {
                if (args.PropertyName == "Value")
                {
                    ClientePesquisa.Id = codigoCliente.Value;
                }
            };
            ClientePesquisa.IdAlterado += (antigo, novo) => codigoCliente.Value = novo;

            nomeCliente.TextChanged += (sender, args) => ClientePesquisa.Nome = nomeCliente.Text;
            ClientePesquisa.NomeAlterado += (antigo, novo) => nomeCliente.Text = novo;

            botaoPesquisar.Click += new EventHandler(botaoPesquisar_Click);

            botaoAnterior.Click += (sender,args) => IndiceProcessoAtual--;
            botaoProximo.Click += (sender, args) => IndiceProcessoAtual++;

            botaoFichaCompleta.Click+= (sender,args)=>{
                Processo ProcessoAtual = ListaProcessos[IndiceProcessoAtual];
                if (ProcessoAtual == null) return;

                fichaProcesso(ListaProcessos[IndiceProcessoAtual]);
            };

            CarregarProcesso = new Action(() =>
            {
                if (ListaProcessos.Count > IndiceProcessoAtual)
                {
                    Processo ProcessoAtual = ListaProcessos[IndiceProcessoAtual];
                    if (ProcessoAtual == null) return;
                    ProcessoAtual.ObterColecoes();
                    codigoProcesso.Text = ProcessoAtual.Id.ToString();
                    cabecaProcesso.Text = ProcessoAtual.Cabeca.Nome;
                    numeroProcesso.Text = ProcessoAtual.NumeroProcesso;
                    numeroOrdemProcesso.Text = ProcessoAtual.NumeroOrdem;
                    reuProcesso.Text = ProcessoAtual.Reu;
                    varaProcesso.Text = ProcessoAtual.Vara;
                    var tiposAcao = TiposAcao.Listar();
                    foreach (TipoAcao tpAcao in tiposAcao)
                    {
                        if (tpAcao.Id == ProcessoAtual.TipoAcao.Id)
                        {
                            tipoAcaoProcesso.Text = tpAcao.Descricao;
                            break;
                        }
                    }
                    dataAjuizamentoProcesso.Text = ProcessoAtual.DataAjuizamentoAcao.HasValue ? ProcessoAtual.DataAjuizamentoAcao.Value.ToString("ddMMyyyy") : null;
                    responsaveisProcesso.Items.Clear();
                    responsaveisProcesso.Items.AddRange(ProcessoAtual.Responsaveis.Select((r)=>r.Advogado).ToArray());
                    CarregarObjetivo(ProcessoAtual, objetivoProcesso);
                    GetRegistroAndamento(ProcessoAtual, andamentoProcesso);
                }
                if (ListaProcessos.Count > 0)
                {
                    navegacao.Text = String.Format("{0} de {1}", IndiceProcessoAtual + 1, ListaProcessos.Count);
                }
                else
                {
                    navegacao.Text = "0 de 0";
                }
            });

            LimparCampos = new Action(() =>
            {
                codigoProcesso.Text = String.Empty;
                cabecaProcesso.Text = String.Empty;
                numeroProcesso.Text = String.Empty;
                numeroOrdemProcesso.Text = String.Empty;
                reuProcesso.Text = String.Empty;
                varaProcesso.Text = String.Empty;
                tipoAcaoProcesso.Text = String.Empty;
                dataAjuizamentoProcesso.Text = String.Empty;
            });
        }
Exemplo n.º 33
0
 public static void postFunctionCall(Form form, PostFuncInt postFuncInt, int funcArg)
 {
     try
     {
         form.BeginInvoke(new PostFuncInt(postFuncInt.Invoke), new object[] { funcArg });
     }
     catch
     {
         ErrMsg("WDS_Common", "Invoking Invoke(new PostFuncInt(postFuncInt), new object[] { funcArg }) failed");
     }
 }
Exemplo n.º 34
0
        public void uploadTaskReport(Form attachedForm, long taskID, Report report, object context)
        {
            new Thread(delegate()
            {
                string json = "";
                byte[] respData;
                WebHeaderCollection headers;
                string url = getUrl(Action.getreports, taskID);
                HttpStatusCode statusCode = HTTPRequest.MakeRequest(url, "POST",
                    Constants.JSON_MIME, Constants.JSON_MIME,
                    Encoding.UTF8.GetBytes(Utility.JsonSerialize<Report>(report)), out respData, out headers);
                if (statusCode == HttpStatusCode.OK)
                {
                    if (onUploadReportSuccessfully != null)
                    {
                        report = new Report();
                        if (respData != null)
                        {
                            json = Encoding.UTF8.GetString(respData);
                            report = Utility.JsonDeserialize<Report>(json);
                        }
                        attachedForm.BeginInvoke(onUploadReportSuccessfully, taskID, report, context);
                    }
                }
                else
                {
                    if (onUploadReportFailed != null)
                    {
                        attachedForm.BeginInvoke(onUploadReportFailed, taskID, statusCode);
                    }
                }

            }).Start();
        }
Exemplo n.º 35
0
 public static void postFunctionCall(Form form, PostFuncString postFuncString, string funcArg)
 {
     try
     {
         form.BeginInvoke(new PostFuncString(postFuncString.Invoke), new object[] { funcArg });
     }
     catch
     {
         ErrMsg("WDS_Common", "Invoking Invoke(new PostFuncString(postFuncString), new object[] { funcArg }) failed");
     }
 }
Exemplo n.º 36
0
        public static void FocusWindow(Form f)
        {
            if (f.InvokeRequired)
            {
                f.BeginInvoke(new MethodInvoker(() => FocusWindow(f)));

                return;
            }

            f.Visible = true; // just in case it's hidden right now   

            if (f.WindowState == FormWindowState.Minimized)
                f.WindowState = FormWindowState.Normal;

            f.Activate();
        }
Exemplo n.º 37
0
        private static void PromptWithUpdate(Form form, UpdateItem bestUpdate, UpdateItem currentVersion, bool interactive)
        {
            if (form.InvokeRequired)
            {
                form.BeginInvoke(new MethodInvoker(() => PromptWithUpdate(form, bestUpdate, currentVersion, interactive)));
                return;
            }

            if (bestUpdate != currentVersion)
            {
                DialogResult dialogResult;

                if (OSVersion.HasTaskDialogs)
                {
                    TaskDialog td = new TaskDialog();
                    td.PositionRelativeToWindow = true;
                    td.Content =
                        "Your Version: " + currentVersion.Version.ToString() +
                        "\nServer Version: " + bestUpdate.Version.ToString() + "\n\n" + "\n" + bestUpdate.Message;
                    td.MainInstruction = "Process Hacker update available";
                    td.WindowTitle = "Update available";
                    td.MainIcon = TaskDialogIcon.SecurityWarning;
                    td.Buttons = new TaskDialogButton[]
                    {
                        new TaskDialogButton((int)DialogResult.Yes, "Download"),
                        new TaskDialogButton((int)DialogResult.No, "Cancel"),
                    };

                    dialogResult = (DialogResult)td.Show(form);
                }
                else
                {
                    dialogResult = MessageBox.Show(
                        form,
                        "Your Version: " + currentVersion.Version.ToString() +
                        "\nServer Version: " + bestUpdate.Version.ToString() + "\n\n" + bestUpdate.Message +
                        "\n\nDo you want to download the update now?",
                        "Update available", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation
                        );
                }

                if (dialogResult == DialogResult.Yes)
                {
                    DownloadUpdate(form, bestUpdate);
                }

            }
            else if (interactive)
            {
                if (OSVersion.HasTaskDialogs)
                {
                    TaskDialog td = new TaskDialog();
                    td.PositionRelativeToWindow = true;
                    td.Content =
                        "Your Version: " + currentVersion.Version.ToString() +
                        "\nServer Version: " + bestUpdate.Version.ToString();
                    td.MainInstruction = "Process Hacker is up-to-date";
                    td.WindowTitle = "No updates available";
                    td.MainIcon = TaskDialogIcon.SecuritySuccess;
                    td.CommonButtons = TaskDialogCommonButtons.Ok;
                    td.Show(form);
                }
                else
                {
                    MessageBox.Show(
                        form,
                        "Process Hacker is up-to-date.",
                        "No updates available", MessageBoxButtons.OK, MessageBoxIcon.Information
                        );
                }
            }
        }