public static void InvokeHelper(this Control control, Action action)
        {
            IAsyncResult asyc = null;

            asyc = control?.BeginInvoke(new MethodInvoker(() =>
            {
                action?.Invoke();
                control?.EndInvoke(asyc);
            }));
        }
Example #2
0
 /// <summary>
 ///   Extensions Methods to Simplify WinForms Thread Invoking, start the action synchrony
 /// </summary>
 /// <param name="uiElement">Type of the Object that will get the extension</param>
 /// <param name="action">A delegate for the action</param>
 /// <param name="timeoutTicks">Timeout to finish action, default is 1/10 of a second</param>
 public static void SafeInvokeNoHandleNeeded([NotNull] this Control uiElement, [NotNull] Action action,
                                             long timeoutTicks = TimeSpan.TicksPerSecond / 10)
 {
     if (uiElement.IsDisposed)
     {
         return;
     }
     if (uiElement.InvokeRequired)
     {
         var result = uiElement.BeginInvoke(action);
         result.AsyncWaitHandle.WaitOne(new TimeSpan(timeoutTicks));
         result.AsyncWaitHandle.Close();
         //TODO: Check if this would be ok, it was commented out
         if (result.IsCompleted)
         {
             uiElement.EndInvoke(result);
         }
     }
     else
     {
         action();
     }
 }
Example #3
0
 public async void StartCountAsync()
 {
     await Task.Run(() =>
     {
         for (int i = 0; i < _maxNumber; i++)
         {
             _index = i;
             if (IndexValueChanged != null)
             {
                 if (_parent == null || !_parent.InvokeRequired)
                 {
                     IndexValueChanged(this, new IndexValueChangedEventArgs(_index));
                 }
                 else
                 {
                     // use BeginInvoke
                     _parent.BeginInvoke(IndexValueChanged, this, new IndexValueChangedEventArgs(_index));
                 }
             }
             Thread.Sleep(100);
         }
     });
 }
Example #4
0
        public static void RegisterMessageHandler(Control control, MessageHandler handler)
        {
            handlers.Add(handler);

            System.EventHandler <SimpleTCP.Message> lambda
                = (sender, msg) =>
                {
                try
                {
                    control.BeginInvoke(
                        new UIHandler(() => handler.HandleMessage(msg.MessageString))
                        );
                }
                catch
                {
                    // do nothing
                }
                };

            lambdas.Add(lambda);

            Program.client.DelimiterDataReceived += lambda;
        }
Example #5
0
        public static void SetPropertyValue(Control ctrl, string propertyName, object value, params object[] args)
        {
            if (ctrl.InvokeRequired)
            {
                SetPropertyDelegate del = new SetPropertyDelegate(CrossThreadUI.SetPropertyValue);
                if (CrossThreadUI.ExecSync)
                {
                    ctrl.Invoke(del, ctrl, propertyName, value, args);
                }
                else
                {
                    ctrl.BeginInvoke(del, ctrl, propertyName, value, args);
                }
            }
            else
            {
                Type         ctrlType = ctrl.GetType();
                PropertyInfo pi       = ctrlType.GetProperty(propertyName, Binding);

                // Make sure the object "Value" matches the property's Type.
                if (!value.GetType().IsAssignableFrom(pi.PropertyType))
                {
                    throw new ArgumentException("Value Type does not match property Type.", "value");
                }

                if (pi != null)
                {
                    try
                    { pi.SetValue(ctrl, ((pi.PropertyType.FullName == "System.String") ? value.ToString() : value), args); }
                    catch { throw; }
                }
                else
                {
                    throw new ArgumentException("Specified control does not expose a '" + propertyName + "' property.", "propertyName");
                }
            }
        }
        /// <summary>
        /// Animates a <see cref="Control"/> by adjusting the width and height whilst maintaining center position.
        /// </summary>
        /// <param name="control">A <see cref="Control"/></param>
        /// <param name="from">A starting position, if null, it will use the current opacity value</param>
        /// <param name="to">The final result, if null, it will be set to 1.0</param>
        /// <param name="duration">The duration for animation to complete</param>
        /// <param name="easingFunction">A defined <see cref="EasingFunction"/> to interpolate the animation values</param>
        public static void AnimateScale(this Control control, double duration, Size?from, Size?to, ScaleMode scaleMode, EasingFunction easingFunction = null)
        {
            if (control != null)
            {
                if (!from.HasValue)
                {
                    from = new Size(control.Width, control.Height);
                }

                if (!to.HasValue)
                {
                    to = new Size(control.Width, control.Height);
                }

                // ensure the UI thread updates the UI components
                Action <Size> invoker = new Action <Size>((value) =>
                {
                    scaleMode.Apply(control, value);
                });

                double _fromFactor = 0.0;
                double _toFactor   = 1.0;

                DoubleAnimation doubleAnimation = new DoubleAnimation(_fromFactor, _toFactor, easingFunction ?? ControlPropertyAnimator.DefaultEasingFunction, duration);
                doubleAnimation.TimelineTick += (sender, args) =>
                {
                    double currentValue = doubleAnimation.Current;
                    // create a size object based from the current factor

                    Size _size = new Size((int)(to.Value.Width * currentValue), (int)(to.Value.Height * currentValue));
                    control.BeginInvoke(invoker, _size);
                };

                control.Size = from.Value;
                doubleAnimation.Begin();
            }
        }
Example #7
0
        private bool OpenTempFileInBrowser(GeckoWebBrowser browser, string filePath)
        {
            var  order = (ThumbnailOrder)browser.Tag;
            bool navigationHappened = true;

            using (var waitHandle = new AutoResetEvent(false))
            {
                order.WaitHandle = waitHandle;
                _syncControl.BeginInvoke(new Action <string>(path =>
                {
                    if (!_isolator.NavigateIfIdle(browser, path))
                    {
                        navigationHappened = false;                         // some browser is busy, try again later.
                    }
                }), filePath);
                waitHandle.WaitOne(10000);
            }
            if (_disposed || !navigationHappened)
            {
                return(false);
            }
            if (!order.Done)
            {
                Logger.WriteEvent("HtmlThumbNailer ({1}): Timed out on ({0})", order.ThumbNailFilePath,
                                  Thread.CurrentThread.ManagedThreadId);
#if DEBUG
                if (!_thumbnailTimeoutAlreadyDisplayed)
                {
                    _thumbnailTimeoutAlreadyDisplayed = true;
                    _syncControl.Invoke((Action)(() => Debug.Fail("(debug only) Make thumbnail timed out (won't show again)")));
                }
#endif
                return(false);
            }
            return(true);
        }
Example #8
0
        public static void SafeInvoke(Control uiElement, Action updater, bool forceSynchronous)
        {
            if (uiElement == null)
            {
                throw new ArgumentNullException("uiElement");
            }

            if (uiElement.InvokeRequired)
            {
                if (forceSynchronous)
                {
                    uiElement.Invoke((Action) delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
                }
                else
                {
                    uiElement.BeginInvoke((Action) delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
                }
            }
            else
            {
                if (uiElement.IsDisposed)
                {
                    //throw new ObjectDisposedException("Control is already disposed.");
                    return;
                }

                try
                {
                    updater();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine(ex.ToString());
                }
            }
        }
Example #9
0
        public static IAsyncResult BeginInvoke(Control c, Delegate f, params object[] p)
        {
            try
            {
                if (IsInvokable(c))
                {
                    return(c.BeginInvoke(f, p));
                }
            }
            catch (ObjectDisposedException e)
            {
                if (IsInvokable(c))
                {
                    throw;
                }
                log.Error(e);
            }
            catch (InvalidAsynchronousStateException e)
            {
                if (IsInvokable(c))
                {
                    throw;
                }
                log.Error(e);
            }
            catch (InvalidOperationException e)
            {
                if (IsInvokable(c))
                {
                    throw;
                }
                log.Error(e);
            }

            return(null);
        }
        public static void BeginInvoke(Control control, Func del)
        {
            if (control == null)
            {
                throw new ArgumentNullException("control");
            }
            if (del == null)
            {
                throw new ArgumentNullException("del");
            }

            // Check if we need to use the controls invoke method to do cross-thread operations.
            if (!control.IsDisposed)
            {
                if (control.InvokeRequired)
                {
                    control.BeginInvoke(del);
                }
                else
                {
                    del();
                }
            }
        }
Example #11
0
        /// <summary>
        /// Execute a method on the control's owning thread. Taken from:
        /// http://stackoverflow.com/questions/714666/is-it-appropriate-to-extend-control-to-provide-consistently-safe-invoke-begininvo
        /// </summary>
        /// <param name="uiElement">The control that is being updated.</param>
        /// <param name="updater">The method that updates uiElement.</param>
        /// <param name="forceSynchronous">True to force synchronous execution of
        /// updater.  False to allow asynchronous execution if the call is marshalled
        /// from a non-GUI thread.  If the method is called on the GUI thread,
        /// execution is always synchronous.</param>
        ///
        /// Usage:
        /// this.SafeInvoke((Action)delegate { SetFrame(doubles); }, false);
        /// or
        /// this.lblTimeDisplay.SafeInvoke(() => this.lblTimeDisplay.Text = this.task.Duration.ToString(), false);
        public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous)
        {
            if (uiElement == null)
            {
                throw new ArgumentNullException("uiElement");
            }

            if (uiElement.InvokeRequired)
            {
                if (forceSynchronous)
                {
                    uiElement.Invoke((Action) delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
                }
                else
                {
                    uiElement.BeginInvoke((Action) delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
                }
            }
            else
            {
                if (!uiElement.IsHandleCreated)
                {
                    // Do nothing if the handle isn't created already.  The user's responsible
                    // for ensuring that the handle they give us exists.
                    return;
                }

                if (uiElement.IsDisposed)
                {
                    // Do nothing.
                    //throw new ObjectDisposedException("Control is already disposed.");
                }

                updater();
            }
        }
Example #12
0
        private void ControlSetSignal(Control ctrl, Signal signal)
        {
            if (ctrl.InvokeRequired)
            {
                ctrl.BeginInvoke(new ControlSetSignalDelegate(ControlSetSignal), ctrl, signal);
            }
            else
            {
                switch (signal.SignalType)
                {
                case SignalTypeEnum.Analog:
                    (ctrl as NumericUpDown).Value = (signal.Data != null) ? (ushort)signal.Data : 0;
                    break;

                case SignalTypeEnum.Digital:
                    (ctrl as PictureBox).Image = signal.Data == null ? Resource1.D_Unknown : ((bool)signal.Data ? Resource1.D_ON : Resource1.D_OFF);
                    break;

                case SignalTypeEnum.Serial:
                    (ctrl as RichTextBox).Text = (signal.Data != null) ? signal.Data.ToString() : "";
                    break;
                }
            }
        }
Example #13
0
        public RocketServer()
        {
            // Create sync control
            syncControl = new Control();
            syncControl.CreateControl();

            // Setup housekeeping timer
            updateTimer          = new System.Windows.Forms.Timer();
            updateTimer.Interval = 1;
            updateTimer.Tick    += updateTimer_Tick;
            updateTimer.Start();

            // Setup server
            server       = new TcpListener(IPAddress.Any, 1338);
            listenThread = new Thread(() =>
            {
                try
                {
                    server.Start();
                    while (true)
                    {
                        // blocks until a client has connected to the server
                        TcpClient client = server.AcceptTcpClient();

                        // Notify main thread
                        syncControl.BeginInvoke(new MethodInvoker(delegate { NewConnection(client); }));
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Rocket Server Error.\nDetails: " + ex.Message, "Rocket Server Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            });
            listenThread.IsBackground = true;
            listenThread.Start();
        }
Example #14
0
 static public void SafeInvoke(this Control control, Action action, bool synchronous = false)
 {
     if (control.IsDisposed == false)
     {
         if (control.InvokeRequired)
         {
             if (synchronous)
             {
                 control.Invoke((Action) delegate { SafeInvoke(control, action, synchronous); });
             }
             else
             {
                 control.BeginInvoke((Action) delegate { SafeInvoke(control, action, synchronous); });
             }
         }
         else if (control.IsHandleCreated == false)
         {
             IntPtr h = control.Handle;
         }
         // we're on the controls thread, make sure it has a handle before invoking action on it
         // may want to restore default handle creation?
         action.Invoke();
     }
 }
Example #15
0
 /// <summary>
 /// invokes target if control.InvokeRequired
 /// Although if control.InvokeRequired the exection
 /// </summary>
 /// <param name="control"></param>
 /// <param name="target"></param>
 /// <returns></returns>
 public static void okThreadSync(this Control control, EventHandler target)
 {
     if (control != null && false == control.IsDisposed)
     {
         try
         {
             if (control.InvokeRequired)
             {
                 IAsyncResult asyncResult = control.BeginInvoke(target);
                 asyncResult.AsyncWaitHandle.WaitOne();
             }
             else
             {
                 target.Invoke(null, null);
             }
         }
         catch (Exception ex)
         {
             System.Diagnostics.Debug.WriteLine(ex.Message);
             //   DI.log.ex(ex, "in okThreadSync");
         }
     }
     //return null;
 }
Example #16
0
 /// <summary>
 /// Handles focus change events
 /// </summary>
 protected override void OnFocus(FocusEventArgs e)
 {
     if (e.Phase == Phase.Sinking && e.IsLostFocus && AutoValidate != AutoValidate.Disable)
     {
         var element = e.Element;
         var control = SciterControls.FindControl(element);
         if (control != null && control.CausesValidation)
         {
             var failed = !control.PerformValidation();
             if (failed && AutoValidate == AutoValidate.EnablePreventFocusChange)
             {
                 e.Handled = true;
                 e.Cancel  = true;
                 var ar = default(IAsyncResult);
                 ar = Control.BeginInvoke((EventHandler) delegate
                 {
                     Control.EndInvoke(ar);
                     control.SetFocus();
                 });
             }
         }
     }
     base.OnFocus(e);
 }
Example #17
0
        //-- Updating properties of controls using delegates and invocation (avoiding cross-thread call exception)
        public static void UpdateProperty <T>(this Control ctrlToUpdate, string propertyName, T newValue)
        {
            PropertyInfo pInfo = ctrlToUpdate.GetType().GetProperty(propertyName);

            if (pInfo == null)
            {
                throw new NullReferenceException("The type (" + ctrlToUpdate.GetType().ToString() + ") does not contain the required property (" + propertyName + ").");
            }

            if (pInfo.PropertyType != typeof(T))
            {
                throw new InvalidOperationException("The property '" + propertyName + "' cannot be updated with this type (" + newValue.GetType().ToString() + ").");
            }

            if (ctrlToUpdate.InvokeRequired)
            {
                //-- Can also use Invoke here (calling thread will wait for return).
                ctrlToUpdate.BeginInvoke(new GenericEventHandler <T>(x => pInfo.SetValue(ctrlToUpdate, x, null)), new object[] { newValue });
            }
            else
            {
                pInfo.SetValue(ctrlToUpdate, newValue, null);
            }
        }
Example #18
0
        public static void InvokeOnUiThreadIfRequired(this Control control, Action action)
        {
            if (control.Disposing || control.IsDisposed || !control.IsHandleCreated)
            {
                return;
            }

            if (control.InvokeRequired)
            {
                control.BeginInvoke((Action)(() =>
                {
                    if (control.Disposing || control.IsDisposed || !control.IsHandleCreated)
                    {
                        return;
                    }

                    action();
                }));
            }
            else
            {
                action.Invoke();
            }
        }
Example #19
0
        /// <summary>
        /// Schedules an action to be executed on the message loop associated with the control.
        /// </summary>
        /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
        /// <param name="state">State passed to the action to be executed.</param>
        /// <param name="action">Action to be executed.</param>
        /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
        /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
        public override IDisposable Schedule <TState>(TState state, Func <IScheduler, TState, IDisposable> action)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            if (_control.IsDisposed)
            {
                return(Disposable.Empty);
            }

            var d = new SingleAssignmentDisposable();

            _control.BeginInvoke(new Action(() =>
            {
                if (!_control.IsDisposed && !d.IsDisposed)
                {
                    d.Disposable = action(this, state);
                }
            }));

            return(d);
        }
Example #20
0
 // extension method to make Control.BeginInvoke easier to use
 public static IAsyncResult BeginInvoke(this Control control, Action action)
 {
     return(control.BeginInvoke(action));
 }
 public static void BeginInvoke(this Control c, MethodInvoker code)
 {
     c.BeginInvoke(code);
 }
Example #22
0
        private void AddToNumActive(int k)
        {
            Action action = () => uiThreadNumActive += k;

            invokeControl.BeginInvoke(action);
        }
 private void Synchronize(Action action)
 {
     m_Control.BeginInvoke(action);
 }
Example #24
0
        private void FiddlerApplication_AfterSessionComplete(Fiddler.Session oSession)
        {
            //保存
            {
                Utility.Configuration.ConfigurationData.ConfigConnection c = Utility.Configuration.Config.Connection;

                if (c.SaveReceivedData)
                {
                    try {
                        if (c.SaveResponse && oSession.fullUrl.Contains("/kcsapi/"))
                        {
                            // 非同期で書き出し処理するので取っておく
                            // stringはイミュータブルなのでOK
                            string url  = oSession.fullUrl;
                            string body = oSession.GetResponseBodyAsString();

                            Task.Run((Action)(() => {
                                SaveResponse(url, body);
                            }));
                        }
                        else if (oSession.fullUrl.Contains("/kcs/") &&
                                 ((c.SaveSWF && oSession.oResponse.MIMEType == "application/x-shockwave-flash") || c.SaveOtherFile))
                        {
                            string saveDataPath = c.SaveDataPath;                             // スレッド間の競合を避けるため取っておく
                            string tpath        = string.Format("{0}\\{1}", saveDataPath, oSession.fullUrl.Substring(oSession.fullUrl.IndexOf("/kcs/") + 5).Replace("/", "\\"));
                            {
                                int index = tpath.IndexOf("?");
                                if (index != -1)
                                {
                                    if (Utility.Configuration.Config.Connection.ApplyVersion)
                                    {
                                        string over   = tpath.Substring(index + 1);
                                        int    vindex = over.LastIndexOf("VERSION=", StringComparison.CurrentCultureIgnoreCase);
                                        if (vindex != -1)
                                        {
                                            string version = over.Substring(vindex + 8).Replace('.', '_');
                                            tpath  = tpath.Insert(tpath.LastIndexOf('.', index), "_v" + version);
                                            index += version.Length + 2;
                                        }
                                    }

                                    tpath = tpath.Remove(index);
                                }
                            }

                            // 非同期で書き出し処理するので取っておく
                            byte[] responseCopy = new byte[oSession.ResponseBody.Length];
                            Array.Copy(oSession.ResponseBody, responseCopy, oSession.ResponseBody.Length);

                            Task.Run((Action)(() => {
                                try {
                                    lock (this) {
                                        // 同時に書き込みが走るとアレなのでロックしておく

                                        Directory.CreateDirectory(Path.GetDirectoryName(tpath));

                                        //System.Diagnostics.Debug.WriteLine( oSession.fullUrl + " => " + tpath );
                                        using (var sw = new System.IO.BinaryWriter(System.IO.File.OpenWrite(tpath))) {
                                            sw.Write(responseCopy);
                                        }
                                    }

                                    Utility.Logger.Add(1, string.Format("通信からファイル {0} を保存しました。", tpath.Remove(0, saveDataPath.Length + 1)));
                                } catch (IOException ex) {                                      //ファイルがロックされている; 頻繁に出るのでエラーレポートを残さない
                                    Utility.Logger.Add(3, "通信内容の保存に失敗しました。 " + ex.Message);
                                }
                            }));
                        }
                    } catch (Exception ex) {
                        Utility.ErrorReporter.SendErrorReport(ex, "通信内容の保存に失敗しました。");
                    }
                }
            }


            if (oSession.fullUrl.Contains("/kcsapi/") && oSession.oResponse.MIMEType == "text/plain")
            {
                // 非同期でGUIスレッドに渡すので取っておく
                // stringはイミュータブルなのでOK
                string url  = oSession.fullUrl;
                string body = oSession.GetResponseBodyAsString();
                UIControl.BeginInvoke((Action)(() => { LoadResponse(url, body); }));
            }



            if (ServerAddress == null)
            {
                string url = oSession.fullUrl;

                int idxb = url.IndexOf("/kcsapi/");

                if (idxb != -1)
                {
                    int idxa = url.LastIndexOf("/", idxb - 1);

                    ServerAddress = url.Substring(idxa + 1, idxb - idxa - 1);
                }
            }
        }
Example #25
0
        public HResult Invoke(IMFAsyncResult result)
        {
            IMFMediaEvent  mediaEvent     = null;
            MediaEventType mediaEventType = MediaEventType.MEUnknown;
            bool           getNext        = true;

            try
            {
                _basePlayer.mf_MediaSession.EndGetEvent(result, out mediaEvent);
                mediaEvent.GetType(out mediaEventType);
                mediaEvent.GetStatus(out HResult errorCode);

                if (_basePlayer._playing)
                {
                    if (mediaEventType == MediaEventType.MEError ||
                        (_basePlayer._webcamMode && mediaEventType == MediaEventType.MEVideoCaptureDeviceRemoved) ||
                        (_basePlayer._micMode && mediaEventType == MediaEventType.MECaptureAudioSessionDeviceRemoved))
                    //if (errorCode < 0)
                    {
                        _basePlayer._lastError = errorCode;
                        errorCode = Player.NO_ERROR;
                        getNext   = false;
                    }

                    if (errorCode >= 0)
                    {
                        if (!getNext || mediaEventType == MediaEventType.MESessionEnded)
                        {
                            if (getNext)
                            {
                                _basePlayer._lastError = Player.NO_ERROR;
                                if (!_basePlayer._repeat)
                                {
                                    getNext = false;
                                }
                            }

                            Control control = _basePlayer._display;
                            if (control == null)
                            {
                                FormCollection forms = Application.OpenForms;
                                if (forms != null && forms.Count > 0)
                                {
                                    control = forms[0];
                                }
                            }
                            if (control != null)
                            {
                                control.BeginInvoke(CallEndOfMedia);
                            }
                            else
                            {
                                _basePlayer.AV_EndOfMedia();
                            }
                        }
                    }
                    else
                    {
                        _basePlayer._lastError = errorCode;
                    }
                }
                else
                {
                    _basePlayer._lastError = errorCode;
                }
            }
            finally
            {
                if (getNext && mediaEventType != MediaEventType.MESessionClosed)
                {
                    _basePlayer.mf_MediaSession.BeginGetEvent(this, null);
                }
                if (mediaEvent != null)
                {
                    Marshal.ReleaseComObject(mediaEvent);
                }

                if (_basePlayer.mf_AwaitCallback)
                {
                    _basePlayer.mf_AwaitCallback = false;
                    _basePlayer.WaitForEvent.Set();
                }
                _basePlayer.mf_AwaitDoEvents = false;
            }
            return(0);
        }
Example #26
0
        public static IAuthorization Authorize(
            Control parent,
            ClientSecrets clientSecrets,
            string[] scopes,
            IDataStore dataStore)
        {
            // N.B. Do not dispose the adapter (and embedded GoogleAuthorizationCodeFlow)
            // as it might be needed for token refreshes later.
            var oauthAdapter = new GoogleAuthAdapter(
                new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = clientSecrets,
                Scopes        = scopes,
                DataStore     = dataStore
            },
                Resources.AuthorizationSuccessful);

            Exception caughtException = null;

            using (var dialog = new AuthorizeDialog())
            {
                Task.Run(async() =>
                {
                    try
                    {
                        // Try to authorize using OAuth.
                        dialog.authorization = await OAuthAuthorization.TryLoadExistingAuthorizationAsync(
                            oauthAdapter,
                            CancellationToken.None)
                                               .ConfigureAwait(true);

                        if (dialog.authorization != null)
                        {
                            // We have existing credentials, there is no need to even
                            // show the "Sign In" button.
                            parent.BeginInvoke((Action)(() => dialog.Close()));
                        }
                        else
                        {
                            // No valid credentials present, request user to authroize
                            // by showing the "Sign In" button.
                            parent.BeginInvoke((Action)(() => dialog.ToggleSignInButton()));
                        }
                    }
                    catch (Exception)
                    {
                        // Something went wrong trying to load existing credentials.
                        parent.BeginInvoke((Action)(() => dialog.ToggleSignInButton()));
                    }
                });

                dialog.signInButton.Click += async(sender, args) =>
                {
                    // Switch to showing spinner so that a user cannot click twice.
                    dialog.ToggleSignInButton();

                    try
                    {
                        dialog.authorization = await OAuthAuthorization.CreateAuthorizationAsync(
                            oauthAdapter,
                            CancellationToken.None)
                                               .ConfigureAwait(true);
                    }
                    catch (Exception e)
                    {
                        caughtException = e;
                    }

                    dialog.Close();
                };

                dialog.ShowDialog(parent);

#pragma warning disable CA1508 // Avoid dead conditional code
                if (caughtException != null)
                {
                    throw caughtException;
                }
                else
                {
                    return(dialog.authorization);
                }
#pragma warning restore CA1508 // Avoid dead conditional code
            }
        }
Example #27
0
 public IAsyncResult BeginInvoke(Delegate method, object[] args)
 {
     return(_editorHostPanel.BeginInvoke(method, args));
 }
Example #28
0
 public override void invoke(MainAction mainAction, bool wait)
 {
     _mainControl.BeginInvoke(new Invoker(mainAction.run));
 }
        void HttpProxy_AfterSessionComplete(Session session)
        {
            Utility.Configuration.ConfigurationData.ConfigConnection c = Utility.Configuration.Config.Connection;

            string baseurl = session.Request.PathAndQuery;

            //debug
            //Utility.Logger.Add( 1, baseurl );


            // request
            if (baseurl.Contains("/kcsapi/"))
            {
                string url  = baseurl;
                string body = session.Request.BodyAsString;

                //保存
                if (c.SaveReceivedData && c.SaveRequest)
                {
                    Task.Run((Action)(() => {
                        SaveRequest(url, body);
                    }));
                }


                UIControl.BeginInvoke((Action)(() => { LoadRequest(url, body); }));
            }



            //response
            //保存

            if (c.SaveReceivedData)
            {
                try {
                    if (!Directory.Exists(c.SaveDataPath))
                    {
                        Directory.CreateDirectory(c.SaveDataPath);
                    }


                    if (c.SaveResponse && baseurl.Contains("/kcsapi/"))
                    {
                        // 非同期で書き出し処理するので取っておく
                        // stringはイミュータブルなのでOK
                        string url  = baseurl;
                        string body = session.Response.BodyAsString;

                        Task.Run((Action)(() => {
                            SaveResponse(url, body);
                        }));
                    }
                    else if (baseurl.Contains("/kcs/") &&
                             ((c.SaveSWF && session.Response.MimeType == "application/x-shockwave-flash") || c.SaveOtherFile))
                    {
                        string saveDataPath = c.SaveDataPath;                         // スレッド間の競合を避けるため取っておく
                        string tpath        = string.Format("{0}\\{1}", saveDataPath, baseurl.Substring(baseurl.IndexOf("/kcs/") + 5).Replace("/", "\\"));
                        {
                            int index = tpath.IndexOf("?");
                            if (index != -1)
                            {
                                if (Utility.Configuration.Config.Connection.ApplyVersion)
                                {
                                    string over   = tpath.Substring(index + 1);
                                    int    vindex = over.LastIndexOf("VERSION=", StringComparison.CurrentCultureIgnoreCase);
                                    if (vindex != -1)
                                    {
                                        string version = over.Substring(vindex + 8).Replace('.', '_');
                                        tpath  = tpath.Insert(tpath.LastIndexOf('.', index), "_v" + version);
                                        index += version.Length + 2;
                                    }
                                }

                                tpath = tpath.Remove(index);
                            }
                        }

                        // 非同期で書き出し処理するので取っておく
                        byte[] responseCopy = new byte[session.Response.Body.Length];
                        Array.Copy(session.Response.Body, responseCopy, session.Response.Body.Length);

                        Task.Run((Action)(() => {
                            try {
                                lock (this) {
                                    // 同時に書き込みが走るとアレなのでロックしておく

                                    Directory.CreateDirectory(Path.GetDirectoryName(tpath));

                                    //System.Diagnostics.Debug.WriteLine( oSession.fullUrl + " => " + tpath );
                                    using (var sw = new System.IO.BinaryWriter(System.IO.File.OpenWrite(tpath))) {
                                        sw.Write(responseCopy);
                                    }
                                }

                                Utility.Logger.Add(1, string.Format("通信からファイル {0} を保存しました。", tpath.Remove(0, saveDataPath.Length + 1)));
                            } catch (IOException ex) {                                  //ファイルがロックされている; 頻繁に出るのでエラーレポートを残さない
                                Utility.Logger.Add(3, "通信内容の保存に失敗しました。 " + ex.Message);
                            }
                        }));
                    }
                } catch (Exception ex) {
                    Utility.ErrorReporter.SendErrorReport(ex, "通信内容の保存に失敗しました。");
                }
            }



            if (baseurl.Contains("/kcsapi/") && session.Response.MimeType == "text/plain")
            {
                // 非同期でGUIスレッドに渡すので取っておく
                // stringはイミュータブルなのでOK
                string url  = baseurl;
                string body = session.Response.BodyAsString;
                UIControl.BeginInvoke((Action)(() => { LoadResponse(url, body); }));

                // kancolle-db.netに送信する
                if (Utility.Configuration.Config.Connection.SendDataToKancolleDB)
                {
                    Task.Run((Action)(() => DBSender.ExecuteSession(session)));
                }
            }


            if (ServerAddress == null && baseurl.Contains("/kcsapi/"))
            {
                ServerAddress = session.Request.Headers.Host;
            }
        }
Example #30
0
 public static void InvokeThread(this Control control, Action action)
 {
     control.BeginInvoke(new MethodInvoker(action));
 }
Example #31
0
 public void setControlEnabled(Control set_me, bool to_me)
 {
     if(set_me.InvokeRequired) {
             set_me.BeginInvoke(new setControlEnabledDelegate(setControlEnabled), new Object[] {set_me,to_me});
         } else {
             lock(set_me) {
                 set_me.Enabled = to_me;
             }
         }
 }