コード例 #1
0
        private void ConfigureWindowsStoreStartup()
        {
            if (cbStartWithWindows.Enabled)
            {
                cbStartWithWindows.Enabled           = false;
                lblWindowsStoreStartupStatus.Text    = "Configuring startup...";
                lblWindowsStoreStartupStatus.Visible = true;

                bool             enable = cbStartWithWindows.Checked;
                StartupTaskState state  = StartupTaskState.Error;

                TaskEx.Run(() =>
                {
                    state = IntegrationHelpers.ConfigureStartupWindowsStore(enable);
                },
                           () =>
                {
                    if (!IsDisposed)
                    {
                        if (state == StartupTaskState.Error)
                        {
                            lblWindowsStoreStartupStatus.Text = "Startup configuration failed. Check debug log for more info.";
                        }
                        else if (state == StartupTaskState.DisabledByUser)
                        {
                            lblWindowsStoreStartupStatus.Text = "The startup has been disabled by the user.";
                        }
                        else
                        {
                            lblWindowsStoreStartupStatus.Visible = false;
                            cbStartWithWindows.Enabled           = true;
                        }
                    }
                });
            }
        }
コード例 #2
0
ファイル: IRCBot.cs プロジェクト: MaxLeiter/ShareX_IRC_Bot
        private void CheckGithubIssues(string message, string channel)
        {
            Match githubIssuesLink = Regex.Match(message, @".*?((?:https?://)?(?:www.)?github.com/.+?/.+?/issues/\d+).*",
                                                 RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

            if (githubIssuesLink.Success)
            {
                TaskEx.Run(() =>
                {
                    string title = BotHelpers.GetWebpageTitle(githubIssuesLink.Groups[1].Value);

                    if (!string.IsNullOrEmpty(title))
                    {
                        IRC.SendMessage(title, channel);
                    }
                });

                return;
            }

            Match githubIssuesID = Regex.Match(message, @".*#(\d+).*", RegexOptions.Compiled);

            if (githubIssuesID.Success)
            {
                TaskEx.Run(() =>
                {
                    string url   = "https://github.com/ShareX/ShareX/issues/" + githubIssuesID.Groups[1].Value;
                    string title = BotHelpers.GetWebpageTitle(url);

                    if (!string.IsNullOrEmpty(title))
                    {
                        IRC.SendMessage($"{url} · {title}", channel);
                    }
                });
            }
        }
コード例 #3
0
        public async Task <List <Node> > Run_2()
        {
            if (this.Graph == null || this.Graph.Count == 0 || this.Source == null)
            {
                throw new Exception("Cannot run Dijkstra without proper graph and source node.");
            }

            this.Initialize();
            this.Source.Visited = true;
            this.visitedNodes   = new List <Node>();
            Node u = this.Source;

            while (visitedNodes.Count < this.Graph.Count)
            {
                u.Visited = true;
                this.visitedNodes.Add(u);
                var tasks = new List <Task <Node> >();
                var task1 = TaskEx.Run(() => PartialResult(mangs[0], u, visitedNodes));
                var task2 = TaskEx.Run(() => PartialResult(mangs[1], u, visitedNodes));
                tasks.Add(task1);
                tasks.Add(task2);
                var results = await TaskEx.WhenAll(tasks.ToArray());

                Node min = new Node();
                min.Distance = double.MaxValue;
                for (int i = 0; i < results.Length; i++)
                {
                    if (min.Distance > results[i].Distance)
                    {
                        min = results[i];
                    }
                }
                u = min;
            }
            return(visitedNodes);
        }
コード例 #4
0
    async Task test()
    {
        await TaskEx.Run(() =>
        {
            try
            {
                Debug.Log("hello world");

                //   AndroidJavaClass mainActivityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
                //   AndroidJavaObject activity = mainActivityClass.GetStatic<AndroidJavaObject>("currentActivity");

                //       AndroidJavaObject context = activity.Call<AndroidJavaObject>("getApplicationContext");

                //       AndroidJavaClass techninierUtil = new AndroidJavaClass("com.techninier.telcomanager.TechninierUtils");
                //    AndroidJavaObject instance = techninierUtil.Call<AndroidJavaObject>("instance");
                //    instance.Call("setContext", context);
                //    Debug.Log("Carrier Name=" + instance.Call<string>("AccessCarrierName"));
            }
            catch (Exception e)
            {
                ExceptionUtils.Instance.LogPrintErrorMessage(e, SynchContext);
            }
        });
    }
コード例 #5
0
        /// <summary>
        /// “awaitable” の自作の例。
        /// Task をラッピングして、同期化(ブロッキング)してしまう。
        ///
        /// サンプル以外の価値があまりないけども。
        /// </summary>
        static async Task BlockingAwaitSample()
        {
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("処理 A-{0} スレッドID: {1}",
                                  i,
                                  Thread.CurrentThread.ManagedThreadId);

                // Task で非同期処理をしているように見せかけて・・・
                await TaskEx.Run(() =>
                {
                    Console.WriteLine("非同期 {0} スレッドID: {1}",
                                      i,
                                      Thread.CurrentThread.ManagedThreadId);

                    Thread.Sleep(100);
                })
                .ToBlocking(); // ここで同期化(ブロッキング)しちゃってるという。

                Console.WriteLine("処理 B-{0} スレッドID: {1}",
                                  i,
                                  Thread.CurrentThread.ManagedThreadId);
            }
        }
コード例 #6
0
        public void Capture(TaskSettings taskSettings = null, bool autoHideForm = false)
        {
            if (taskSettings == null)
            {
                taskSettings = TaskSettings.GetDefaultTaskSettings();
            }

            if (taskSettings.CaptureSettings.IsDelayScreenshot && taskSettings.CaptureSettings.DelayScreenshot > 0)
            {
                TaskEx.Run(() =>
                {
                    int sleep = (int)(taskSettings.CaptureSettings.DelayScreenshot * 1000);
                    Thread.Sleep(sleep);
                },
                           () =>
                {
                    CaptureInternal(taskSettings, autoHideForm);
                });
            }
            else
            {
                CaptureInternal(taskSettings, autoHideForm);
            }
        }
コード例 #7
0
        public override void Prepare(Screenshot screenshot)
        {
            base.Prepare(screenshot);

            if (Config != null)
            {
                ShapeManager = new ShapeManager(this);
                ShapeManager.WindowCaptureMode = Config.DetectWindows;
                ShapeManager.IncludeControls   = Config.DetectControls;

                if (Mode == RectangleRegionMode.Annotation)
                {
                    ShapeManager.CurrentShapeTypeChanged += ShapeManager_CurrentShapeTypeChanged;

                    ShapeManager_CurrentShapeTypeChanged(ShapeManager.CurrentShapeType);
                }

                if (Mode == RectangleRegionMode.OneClick || ShapeManager.WindowCaptureMode)
                {
                    IntPtr handle = Handle;

                    TaskEx.Run(() =>
                    {
                        WindowsRectangleList wla = new WindowsRectangleList();
                        wla.IgnoreHandle         = handle;
                        wla.IncludeChildWindows  = ShapeManager.IncludeControls;
                        ShapeManager.Windows     = wla.GetWindowInfoListAsync(5000);
                    });
                }

                if (Config.UseCustomInfoText || Mode == RectangleRegionMode.ScreenColorPicker)
                {
                    bmpBackgroundImage = new Bitmap(backgroundImage);
                }
            }
        }
コード例 #8
0
ファイル: FileHelpers.cs プロジェクト: Kearsoft/AdrotatorV2
        public override async Task <Stream> OpenStreamAsync(string name)
        {
#if WINRT
            var package = Windows.ApplicationModel.Package.Current;

            try
            {
                var storageFile = await package.InstalledLocation.GetFileAsync(name);

                var randomAccessStream = await storageFile.OpenReadAsync();

                return(randomAccessStream.AsStreamForRead());
            }
            catch (IOException)
            {
                // The file must not exist... return a null stream.
                return(null);
            }
#else
            await TaskEx.Run(() => { });

            throw new NotImplementedException();
#endif
        }
コード例 #9
0
        private void EtwTracingHelper(string eventName, string[] attributes, Action doAction,
                                      Action <Dictionary <string, string> > assertAction)
        {
            Dictionary <string, string> valuesFromEvent = new Dictionary <string, string>();
            Action <TraceEvent>         eventDelegate   = delegate(TraceEvent data)
            {
                if (data.EventName == eventName)
                {
                    foreach (var attributeName in attributes)
                    {
                        valuesFromEvent[attributeName] = data.PayloadByName(attributeName).ToString();
                    }
                    _eventSession.Source.StopProcessing();
                }
            };

            _eventSession.Source.Dynamic.All += eventDelegate;

#if NET45
            var task = Task.Run(() => _eventSession.Source.Process());
#else
            var task = TaskEx.Run(() => _eventSession.Source.Process());
#endif
            doAction();

            task.Wait();

            try
            {
                assertAction(valuesFromEvent);
            }
            finally
            {
                _eventSession.Source.Dynamic.All -= eventDelegate;
            }
        }
コード例 #10
0
        public void TestCallbackException(IJavascriptCallback errorCallback, IJavascriptCallback errorCallbackResult)
        {
            const int taskDelay = 500;

            TaskEx.Run(async() =>
            {
                await TaskEx.Delay(taskDelay);

                using (errorCallback)
                {
                    JavascriptResponse result = await errorCallback.ExecuteAsync("This callback from C# was delayed " + taskDelay + "ms");
                    string resultMessage;
                    if (result.Success)
                    {
                        resultMessage = "Fatal: No Exception thrown in error callback";
                    }
                    else
                    {
                        resultMessage = "Exception Thrown: " + result.Message;
                    }
                    await errorCallbackResult.ExecuteAsync(resultMessage);
                }
            });
        }
コード例 #11
0
 public async Task AddScriptChange(LUStruct[] items)
 {
     await TaskEx.Run(() =>
     {
         List <LUStruct> NeedsFired = new List <LUStruct>();
         foreach (LUStruct item in items)
         {
             if (item.Action == LUType.Unload)
             {
                 item.ID.CloseAndDispose(false);
             }
             else if (item.Action == LUType.Load)
             {
                 try
                 {
                     item.ID.Start(false);
                     NeedsFired.Add(item);
                 }
                 catch (Exception ex) { m_log.Error("[" + m_ScriptEngine.ScriptEngineName + "]: LEAKED COMPILE ERROR: " + ex); }
             }
             else if (item.Action == LUType.Reupload)
             {
                 try
                 {
                     item.ID.Start(true);
                     NeedsFired.Add(item);
                 }
                 catch (Exception ex) { m_log.Error("[" + m_ScriptEngine.ScriptEngineName + "]: LEAKED COMPILE ERROR: " + ex); }
             }
         }
         foreach (LUStruct item in NeedsFired)
         {
             item.ID.FireEvents();
         }
     });
 }
コード例 #12
0
        private void DoCapture(ScreenCaptureDelegate capture, CaptureType captureType, TaskSettings taskSettings = null, bool autoHideForm = true)
        {
            if (taskSettings == null)
            {
                taskSettings = TaskSettings.GetDefaultTaskSettings();
            }

            if (taskSettings.CaptureSettings.IsDelayScreenshot && taskSettings.CaptureSettings.DelayScreenshot > 0)
            {
                TaskEx.Run(() =>
                {
                    int sleep = (int)(taskSettings.CaptureSettings.DelayScreenshot * 1000);
                    Thread.Sleep(sleep);
                },
                           () =>
                {
                    DoCaptureWork(capture, captureType, taskSettings, autoHideForm);
                });
            }
            else
            {
                DoCaptureWork(capture, captureType, taskSettings, autoHideForm);
            }
        }
コード例 #13
0
        public void StartSuggestThread()
        {
            if (_cts != null && !_cts.IsCancellationRequested)
            {
                throw new InvalidOperationException("Already started");
            }

            var cts = new CancellationTokenSource();

            TaskEx.Run(async() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    if (Searcher.Spellchecker.IsLoaded && TextInputStateCurrent != null && !IsSuggestUpToDate() && trySuggest())
                    {
                        continue;
                    }

                    await TaskEx.Delay(100);
                }
            });

            _cts = cts;
        }
コード例 #14
0
        private void ComDeviceInfoManager_RemovedDevices(object sender, ComDeviceInfoManagerEventArgs e)
        {
            List <string> devices = new List <string>();

            foreach (var item in e.ComDevices)
            {
                var res = IcpDeviceManagers.FindAll(dev => dev.GetComPort() == item.Port);
                IcpDeviceManagers.RemoveAll(dev => dev.GetComPort() == item.Port);

                TaskEx.Run(() =>
                {
                    foreach (var it in res)
                    {
                        it.CloseConnection();

                        foreach (var i in it.IcpDeviceDict)
                        {
                            devices.Add(i.Value.Name);
                        }
                    }
                }).ContinueWith(delegate { RemovedDevicesCallback(devices.ToArray()); });
            }
            //ComDevicesRemoved?.Invoke(this, new ComDeviceControllerEventArgs(devices.ToArray()));
        }
コード例 #15
0
        async public Task <EtaResponse <List <Offer> > > GetOfferListAsync(EtaApiQueryStringParameterOptions options)
        {
            if (options == null)
            {
                options = new EtaApiQueryStringParameterOptions();
                options.AddParm("from", EtaSDK.Utils.UNIXTime.GetTimestamp(DateTime.Now));
                options.AddParm("to", EtaSDK.Utils.UNIXTime.GetTimestamp(DateTime.Now.AddDays(14)));

                options.AddParm(EtaApiConstants.EtaApi_Latitude, "55.77012");
                options.AddParm(EtaApiConstants.EtaApi_Longitude, "12.46320");
                options.AddParm(EtaApiConstants.EtaApi_LocationDetermined, UNIXTime.GetTimestamp(DateTime.Now));
                options.AddParm(EtaApiConstants.EtaApi_Geocoded, "0");
                options.AddParm(EtaApiConstants.EtaApi_Accuracy, "0");
                options.AddParm(EtaApiConstants.EtaApi_Ditance, "10000");

                //options.AddParm(EtaApiConstants.EtaApi_OfferId, "");
                options.AddParm("store", "5d6dBY"); // 5d6dBY
                options.AddParm("type", "suggested");
            }

            var eta = await ApiRawAsync("/api/v1/offer/list/", options);

            if (eta.HasErrors)
            {
                return(new EtaResponse <List <Offer> >(eta.Uri, eta.Error));
            }

            var jsonstr = eta.Result;

            var result = await TaskEx.Run <EtaResponse <List <Offer> > >(() =>
            {
                return(ParseOffers(eta.Uri, jsonstr));
            });

            return(result);
        }
コード例 #16
0
 public async Task SortByDateAsync()
 {
     await TaskEx.Run(() => { this.Sessions = this.Sessions.OrderBy(x => x.Start); });
 }
コード例 #17
0
        public static async Task ForEach <T>(IEnumerable <T> sequence, Func <T, Task> factory, CancellationToken cancellationToken, ParallelOptions options)
        {
            var exceptions = new List <Exception>();
            var tasks      = new List <Task>(options.MaxDegreeOfParallelism);

            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }
            foreach (var element in sequence)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }
#if NET40
                tasks.Add(TaskEx.Run(async() =>
                {
                    try
                    {
                        await factory(element).ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        exceptions.Add(e);
                    }
                }));
#else
                tasks.Add(Task.Run(async() =>
                {
                    try
                    {
                        await factory(element).ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        exceptions.Add(e);
                    }
                }));
#endif
                if (exceptions.Count > 0)
                {
                    break;
                }
                if (tasks.Count == tasks.Capacity)
                {
#if NET40
                    await TaskEx.WhenAny(tasks).ConfigureAwait(false);
#else
                    await Task.WhenAny(tasks).ConfigureAwait(false);
#endif
                    tasks.RemoveAll(task => task.IsCompleted);
                }
            }
#if NET40
            await TaskEx.WhenAll(tasks).ConfigureAwait(false);
#else
            await Task.WhenAll(tasks).ConfigureAwait(false);
#endif
            if (exceptions.Any())
            {
                if (exceptions.Count == 1)
                {
                    throw exceptions.First();
                }
                throw new AggregateException(exceptions);
            }
        }
コード例 #18
0
 public static Task <T> Run <T>(Func <Task <T> > func)
 {
     return(TaskEx.Run(func));
 }
コード例 #19
0
 public static Task Run(Func <Task> func)
 {
     return(TaskEx.Run(func));
 }
コード例 #20
0
 public static Task Run(Action func)
 {
     return(TaskEx.Run(func));
 }
コード例 #21
0
ファイル: ScreenRecordForm.cs プロジェクト: andre-d/ShareXYZ
        public void StartRecording(ScreenRecordOutput outputType, TaskSettings taskSettings, ScreenRecordStartMethod startMethod = ScreenRecordStartMethod.Region)
        {
            string debugText;

            if (outputType == ScreenRecordOutput.FFmpeg)
            {
                debugText = string.Format("Starting FFmpeg recording. Video encoder: \"{0}\", Audio encoder: \"{1}\", FPS: {2}",
                                          taskSettings.CaptureSettings.FFmpegOptions.VideoCodec.GetDescription(), taskSettings.CaptureSettings.FFmpegOptions.AudioCodec.GetDescription(),
                                          taskSettings.CaptureSettings.ScreenRecordFPS);
            }
            else
            {
                debugText = string.Format("Starting Animated GIF recording. GIF encoding: \"{0}\", FPS: {1}",
                                          taskSettings.CaptureSettings.GIFEncoding.GetDescription(), taskSettings.CaptureSettings.GIFFPS);
            }

            DebugHelper.WriteLine(debugText);

            if (taskSettings.CaptureSettings.RunScreencastCLI)
            {
                if (!Program.Settings.VideoEncoders.IsValidIndex(taskSettings.CaptureSettings.VideoEncoderSelected))
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_There_is_no_valid_CLI_video_encoder_selected_,
                                    "ShareXYZ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].IsValid())
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_CLI_video_encoder_file_does_not_exist__ +
                                    Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].Path,
                                    "ShareXYZ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            if (outputType == ScreenRecordOutput.GIF && taskSettings.CaptureSettings.GIFEncoding == ScreenRecordGIFEncoding.FFmpeg)
            {
                outputType = ScreenRecordOutput.FFmpeg;
                taskSettings.CaptureSettings.FFmpegOptions.VideoCodec        = FFmpegVideoCodec.gif;
                taskSettings.CaptureSettings.FFmpegOptions.UseCustomCommands = false;
            }

            if (outputType == ScreenRecordOutput.FFmpeg)
            {
                if (!TaskHelpers.CheckFFmpeg(taskSettings))
                {
                    return;
                }

                if (!taskSettings.CaptureSettings.FFmpegOptions.IsSourceSelected)
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_FFmpeg_video_and_audio_source_both_can_t_be__None__,
                                    "ShareXYZ - " + Resources.ScreenRecordForm_StartRecording_FFmpeg_error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            Rectangle captureRectangle = Rectangle.Empty;

            switch (startMethod)
            {
            case ScreenRecordStartMethod.Region:
                TaskHelpers.SelectRegion(out captureRectangle, taskSettings);
                break;

            case ScreenRecordStartMethod.ActiveWindow:
                if (taskSettings.CaptureSettings.CaptureClientArea)
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowClientRectangle();
                }
                else
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowRectangle();
                }
                break;

            case ScreenRecordStartMethod.LastRegion:
                captureRectangle = Program.Settings.ScreenRecordRegion;
                break;
            }

            captureRectangle = CaptureHelpers.EvenRectangleSize(captureRectangle);

            if (IsRecording || !captureRectangle.IsValid() || screenRecorder != null)
            {
                return;
            }

            Program.Settings.ScreenRecordRegion = captureRectangle;

            IsRecording = true;

            Screenshot.CaptureCursor = taskSettings.CaptureSettings.ScreenRecordShowCursor;

            string trayText = "ShareXYZ - " + Resources.ScreenRecordForm_StartRecording_Waiting___;

            TrayIcon.Text    = trayText.Truncate(63);
            TrayIcon.Icon    = Resources.control_record_yellow.ToIcon();
            cmsMain.Enabled  = false;
            TrayIcon.Visible = true;

            string path = "";

            float duration = taskSettings.CaptureSettings.ScreenRecordFixedDuration ? taskSettings.CaptureSettings.ScreenRecordDuration : 0;

            regionForm = ScreenRegionForm.Show(captureRectangle, StopRecording, startMethod == ScreenRecordStartMethod.Region, duration);
            regionForm.RecordResetEvent = new ManualResetEvent(false);

            TaskEx.Run(() =>
            {
                try
                {
                    if (outputType == ScreenRecordOutput.FFmpeg)
                    {
                        path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, taskSettings.CaptureSettings.FFmpegOptions.Extension));
                    }
                    else
                    {
                        path = Program.ScreenRecorderCacheFilePath;
                    }

                    ScreencastOptions options = new ScreencastOptions()
                    {
                        FFmpeg          = taskSettings.CaptureSettings.FFmpegOptions,
                        ScreenRecordFPS = taskSettings.CaptureSettings.ScreenRecordFPS,
                        GIFFPS          = taskSettings.CaptureSettings.GIFFPS,
                        Duration        = duration,
                        OutputPath      = path,
                        CaptureArea     = captureRectangle,
                        DrawCursor      = taskSettings.CaptureSettings.ScreenRecordShowCursor
                    };

                    screenRecorder = new ScreenRecorder(outputType, options, captureRectangle);

                    if (regionForm != null && regionForm.RecordResetEvent != null)
                    {
                        trayText      = "ShareXYZ - " + Resources.ScreenRecordForm_StartRecording_Click_tray_icon_to_start_recording_;
                        TrayIcon.Text = trayText.Truncate(63);

                        this.InvokeSafe(() =>
                        {
                            tsmiStart.Text  = Resources.AutoCaptureForm_Execute_Start;
                            cmsMain.Enabled = true;
                        });

                        if (taskSettings.CaptureSettings.ScreenRecordAutoStart)
                        {
                            int delay = (int)(taskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                            if (delay > 0)
                            {
                                regionForm.InvokeSafe(() => regionForm.StartCountdown(delay));

                                regionForm.RecordResetEvent.WaitOne(delay);
                            }
                        }
                        else
                        {
                            regionForm.RecordResetEvent.WaitOne();
                        }

                        if (regionForm.AbortRequested)
                        {
                            abortRequested = true;
                        }
                    }

                    if (!abortRequested)
                    {
                        trayText      = "ShareXYZ - " + Resources.ScreenRecordForm_StartRecording_Click_tray_icon_to_stop_recording_;
                        TrayIcon.Text = trayText.Truncate(63);
                        TrayIcon.Icon = Resources.control_record.ToIcon();

                        this.InvokeSafe(() =>
                        {
                            tsmiStart.Text = Resources.AutoCaptureForm_Execute_Stop;
                        });

                        if (regionForm != null)
                        {
                            regionForm.InvokeSafe(() => regionForm.StartRecordingTimer(duration > 0, duration));
                        }

                        screenRecorder.StartRecording();

                        if (regionForm != null && regionForm.AbortRequested)
                        {
                            abortRequested = true;
                        }
                    }
                }
                catch (Exception e)
                {
                    DebugHelper.WriteException(e);
                }
                finally
                {
                    if (regionForm != null)
                    {
                        if (regionForm.RecordResetEvent != null)
                        {
                            regionForm.RecordResetEvent.Dispose();
                        }

                        regionForm.InvokeSafe(() => regionForm.Close());
                        regionForm = null;
                    }
                }

                try
                {
                    if (!abortRequested && screenRecorder != null)
                    {
                        TrayIcon.Text = "ShareXYZ - " + Resources.ScreenRecordForm_StartRecording_Encoding___;
                        TrayIcon.Icon = Resources.camcorder_pencil.ToIcon();

                        this.InvokeSafe(() =>
                        {
                            cmsMain.Enabled = false;
                        });

                        if (outputType == ScreenRecordOutput.GIF)
                        {
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            screenRecorder.EncodingProgressChanged += progress => TrayIcon.Text = string.Format("ShareXYZ - {0} ({1}%)", Resources.ScreenRecordForm_StartRecording_Encoding___, progress);
                            GIFQuality gifQuality = taskSettings.CaptureSettings.GIFEncoding == ScreenRecordGIFEncoding.OctreeQuantizer ? GIFQuality.Bit8 : GIFQuality.Default;
                            screenRecorder.SaveAsGIF(path, gifQuality);
                        }
                        else if (outputType == ScreenRecordOutput.FFmpeg && taskSettings.CaptureSettings.FFmpegOptions.VideoCodec == FFmpegVideoCodec.gif)
                        {
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            screenRecorder.FFmpegEncodeAsGIF(path);
                        }

                        if (taskSettings.CaptureSettings.RunScreencastCLI)
                        {
                            VideoEncoder encoder  = Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected];
                            string sourceFilePath = path;
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, encoder.OutputExtension));
                            screenRecorder.EncodeUsingCommandLine(encoder, sourceFilePath, path);
                        }
                    }
                }
                finally
                {
                    if (screenRecorder != null)
                    {
                        if ((outputType == ScreenRecordOutput.GIF || taskSettings.CaptureSettings.RunScreencastCLI ||
                             (outputType == ScreenRecordOutput.FFmpeg && taskSettings.CaptureSettings.FFmpegOptions.VideoCodec == FFmpegVideoCodec.gif)) &&
                            !string.IsNullOrEmpty(screenRecorder.CachePath) && File.Exists(screenRecorder.CachePath))
                        {
                            File.Delete(screenRecorder.CachePath);
                        }

                        screenRecorder.Dispose();
                        screenRecorder = null;

                        if (abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                }
            },
                       () =>
            {
                if (TrayIcon.Visible)
                {
                    TrayIcon.Visible = false;
                }

                if (!abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path) && TaskHelpers.ShowAfterCaptureForm(taskSettings))
                {
                    WorkerTask task = WorkerTask.CreateFileJobTask(path, taskSettings);
                    TaskManager.Start(task);
                }

                abortRequested = false;
                IsRecording    = false;
            });
        }
コード例 #22
0
 /// <summary>
 /// Find node asynchronously
 /// </summary>
 public async Task <INode> FindNodeAsync(string tag)
 {
     return(await TaskEx.Run(() => FindNode(tag)));
 }
コード例 #23
0
 /// <summary>
 /// Explores a folder asynchronously
 /// </summary>
 public async Task <IEnumerable <INode> > ExploreFolderAsync(string tag)
 {
     return(await TaskEx.Run(() => ExploreFolder(tag)));
 }
コード例 #24
0
ファイル: MainWindow.xaml.cs プロジェクト: kririae/Etupirka
        /*	private Task<byte[]> getDataAsync(string url)
         *  {
         *      return NetworkUtility.GetData(url);
         *  }
         */
        private async void UpdateOfflineDatabase_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var controller = await this.ShowProgressAsync("更新しています", "Initializing...");

                controller.SetCancelable(true);
                await TaskEx.Delay(1000);

                controller.SetMessage("Downloading...");
                string url = Properties.Settings.Default.databaseSyncServer;
                url = url.TrimEnd('/') + "/" + "esdata.gz";
                if (controller.IsCanceled)
                {
                    await controller.CloseAsync();

                    await this.ShowMessageAsync("データベースを更新する", "失敗しました");

                    return;
                }
                var data = await TaskEx.Run(() => { return(NetworkUtility.GetData(url)); });

                if (controller.IsCanceled)
                {
                    await controller.CloseAsync();

                    await this.ShowMessageAsync("データベースを更新する", "失敗しました");

                    return;
                }

                controller.SetMessage("Decompressing...");
                var s = await TaskEx.Run(() => { return(Encoding.UTF8.GetString(Utility.Decompress(data))); });

                if (controller.IsCanceled)
                {
                    await controller.CloseAsync();

                    await this.ShowMessageAsync("データベースを更新する", "失敗しました");

                    return;
                }

                controller.SetMessage("Updating database...");
                bool re = await TaskEx.Run(() => { return(Utility.im.update(s.Split('\n'))); });

                await controller.CloseAsync();

                if (re)
                {
                    await this.ShowMessageAsync("データベースを更新する", "成功しました");
                }
                else
                {
                    await this.ShowMessageAsync("データベースを更新する", "失敗しました");
                }
            }
            catch
            {
                return;
            }
        }
コード例 #25
0
ファイル: SsdpDeviceLocatorBase.cs プロジェクト: noex/RSSDP
        public async Task <IEnumerable <DiscoveredSsdpDevice> > SearchAsync(string searchTarget, TimeSpan searchWaitTime)
        {
            if (searchTarget == null)
            {
                throw new ArgumentNullException("searchTarget");
            }
            if (searchTarget.Length == 0)
            {
                throw new ArgumentException("searchTarget cannot be an empty string.", "searchTarget");
            }
            if (searchWaitTime.TotalSeconds < 0)
            {
                throw new ArgumentException("searchWaitTime must be a positive time.");
            }
            if (searchWaitTime.TotalSeconds > 0 && searchWaitTime.TotalSeconds <= 1)
            {
                throw new ArgumentException("searchWaitTime must be zero (if you are not using the result and relying entirely in the events), or greater than one second.");
            }

            ThrowIfDisposed();

            if (_SearchResults != null)
            {
                throw new InvalidOperationException("Search already in progress. Only one search at a time is allowed.");
            }
            _SearchResults = new List <DiscoveredSsdpDevice>();

            // If searchWaitTime == 0 then we are only going to report unexpired cached items, not actually do a search.
            if (searchWaitTime > TimeSpan.Zero)
            {
                BroadcastDiscoverMessage(searchTarget, SearchTimeToMXValue(searchWaitTime));
            }

            await TaskEx.Run(() =>
            {
                lock (_SearchResultsSynchroniser)
                {
                    foreach (var device in GetUnexpiredDevices().Where((d) => NotificationTypeMatchesFilter(d)))
                    {
                        if (this.IsDisposed)
                        {
                            return;
                        }

                        DeviceFound(device, false);
                    }
                }
            }).ConfigureAwait(false);

            if (searchWaitTime != TimeSpan.Zero)
            {
                await TaskEx.Delay(searchWaitTime);
            }

            IEnumerable <DiscoveredSsdpDevice> retVal = null;

            try
            {
                lock (_SearchResultsSynchroniser)
                {
                    retVal         = _SearchResults;
                    _SearchResults = null;
                }

                var expireTask = RemoveExpiredDevicesFromCacheAsync();
            }
            finally
            {
                var server = _CommunicationsServer;
                try
                {
                    if (server != null)                     // In case we were disposed while searching.
                    {
                        server.StopListeningForResponses();
                    }
                }
                catch (ObjectDisposedException) { }
            }

            return(retVal);
        }
コード例 #26
0
        // Must be called before show form
        public void Prepare(Image img)
        {
            Image = img;

            if (IsEditorMode)
            {
                Rectangle rect = CaptureHelpers.GetActiveScreenBounds0Based();

                if (Image.Width > rect.Width || Image.Height > rect.Height)
                {
                    rect = ScreenRectangle0Based;
                }

                ImageRectangle = new Rectangle(rect.X + rect.Width / 2 - Image.Width / 2, rect.Y + rect.Height / 2 - Image.Height / 2, Image.Width, Image.Height);

                using (Image background = ImageHelpers.DrawCheckers(ScreenRectangle0Based.Width, ScreenRectangle0Based.Height))
                    using (Graphics g = Graphics.FromImage(background))
                    {
                        g.DrawImage(Image, ImageRectangle);

                        backgroundBrush = new TextureBrush(background)
                        {
                            WrapMode = WrapMode.Clamp
                        };
                    }
            }
            else if (Config.UseDimming)
            {
                using (Bitmap darkBackground = (Bitmap)Image.Clone())
                    using (Graphics g = Graphics.FromImage(darkBackground))
                        using (Brush brush = new SolidBrush(Color.FromArgb(30, Color.Black)))
                        {
                            g.FillRectangle(brush, 0, 0, darkBackground.Width, darkBackground.Height);

                            backgroundBrush = new TextureBrush(darkBackground)
                            {
                                WrapMode = WrapMode.Clamp
                            };
                        }

                backgroundHighlightBrush = new TextureBrush(Image)
                {
                    WrapMode = WrapMode.Clamp
                };
            }
            else
            {
                backgroundBrush = new TextureBrush(Image)
                {
                    WrapMode = WrapMode.Clamp
                };
            }

            ShapeManager = new ShapeManager(this);
            ShapeManager.WindowCaptureMode = Config.DetectWindows;
            ShapeManager.IncludeControls   = Config.DetectControls;

            if (Mode == RegionCaptureMode.OneClick || ShapeManager.WindowCaptureMode)
            {
                IntPtr handle = Handle;

                TaskEx.Run(() =>
                {
                    WindowsRectangleList wla = new WindowsRectangleList();
                    wla.IgnoreHandle         = handle;
                    wla.IncludeChildWindows  = ShapeManager.IncludeControls;
                    ShapeManager.Windows     = wla.GetWindowInfoListAsync(5000);
                });
            }

            if (Config.UseCustomInfoText || Mode == RegionCaptureMode.ScreenColorPicker)
            {
                bmpBackgroundImage = new Bitmap(Image);
            }
        }
コード例 #27
0
        public async void StartRecording(TaskSettings TaskSettings)
        {
            if (TaskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.AVICommandLine)
            {
                if (!Program.Settings.VideoEncoders.IsValidIndex(TaskSettings.CaptureSettings.VideoEncoderSelected))
                {
                    MessageBox.Show("There is no valid CLI video encoder selected.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else if (!Program.Settings.VideoEncoders[TaskSettings.CaptureSettings.VideoEncoderSelected].IsValid())
                {
                    MessageBox.Show("There is a problem with the CLI video encoder file path.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            SelectRegion();
            Screenshot.CaptureCursor = TaskSettings.CaptureSettings.ShowCursor;

            if (IsRecording || CaptureRectangle.IsEmpty || screenRecorder != null)
            {
                return;
            }

            IsRecording = true;

            TrayIcon.Icon    = Resources.control_record_yellow.ToIcon();
            TrayIcon.Visible = true;

            string path = "";

            try
            {
                using (ScreenRegionManager screenRegionManager = new ScreenRegionManager())
                {
                    screenRegionManager.Start(CaptureRectangle);

                    await TaskEx.Run(() =>
                    {
                        if (TaskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.AVI)
                        {
                            path = Path.Combine(TaskSettings.CaptureFolder, TaskHelpers.GetFilename(TaskSettings, "avi"));
                        }
                        else
                        {
                            path = Program.ScreenRecorderCacheFilePath;
                        }

                        float duration = TaskSettings.CaptureSettings.ScreenRecordFixedDuration ? TaskSettings.CaptureSettings.ScreenRecordDuration : 0;

                        screenRecorder = new ScreenRecorder(TaskSettings.CaptureSettings.ScreenRecordFPS, duration, CaptureRectangle, path,
                                                            TaskSettings.CaptureSettings.ScreenRecordOutput);

                        int delay = (int)(TaskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                        if (delay > 0)
                        {
                            Thread.Sleep(delay);
                        }

                        screenRegionManager.ChangeColor();

                        this.InvokeSafe(() => TrayIcon.Icon = Resources.control_record.ToIcon());

                        screenRecorder.StartRecording();
                    });
                }

                if (screenRecorder != null && TaskSettings.CaptureSettings.ScreenRecordOutput != ScreenRecordOutput.AVI)
                {
                    TrayIcon.Icon = Resources.camcorder__pencil.ToIcon();

                    await TaskEx.Run(() =>
                    {
                        switch (TaskSettings.CaptureSettings.ScreenRecordOutput)
                        {
                        case ScreenRecordOutput.GIF:
                            path = Path.Combine(TaskSettings.CaptureFolder, TaskHelpers.GetFilename(TaskSettings, "gif"));
                            screenRecorder.SaveAsGIF(path, TaskSettings.ImageSettings.ImageGIFQuality);
                            break;

                        case ScreenRecordOutput.AVICommandLine:
                            VideoEncoder encoder = Program.Settings.VideoEncoders[TaskSettings.CaptureSettings.VideoEncoderSelected];
                            path = Path.Combine(TaskSettings.CaptureFolder, TaskHelpers.GetFilename(TaskSettings, encoder.OutputExtension));
                            screenRecorder.EncodeUsingCommandLine(encoder, path);
                            break;
                        }
                    });
                }
            }
            finally
            {
                if (screenRecorder != null)
                {
                    if (TaskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.AVICommandLine &&
                        !string.IsNullOrEmpty(screenRecorder.CachePath) && File.Exists(screenRecorder.CachePath))
                    {
                        File.Delete(screenRecorder.CachePath);
                    }

                    screenRecorder.Dispose();
                    screenRecorder = null;
                }

                if (TrayIcon.Visible)
                {
                    TrayIcon.Visible = false;
                }
            }

            if (!string.IsNullOrEmpty(path) && File.Exists(path))
            {
                if (TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.UploadImageToHost))
                {
                    UploadManager.UploadFile(path, TaskSettings);
                }
                else
                {
                    if (TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.CopyFilePathToClipboard))
                    {
                        ClipboardHelpers.CopyText(path);
                    }

                    TaskHelpers.ShowResultNotifications(path, TaskSettings, path);
                }
            }

            IsRecording = false;
        }
コード例 #28
0
 public async Task SortByTitleAsync()
 {
     await TaskEx.Run(() => { this.Sessions = this.Sessions.OrderBy(x => x.Title); });
 }
コード例 #29
0
        /// <summary>
        ///     Shows the built-in UI while the updates are managed.
        /// </summary>
        public void ShowUserInterface()
        {
            if (_isTaskRunning)
            {
                return;
            }

            _isTaskRunning = true;
            var searchDialog = new UpdateSearchDialog {
                Updater = UpdateManagerInstance
            };

            searchDialog.CancelButtonClicked += UpdateSearchDialogCancelButtonClick;

            var newUpdateDialog = new NewUpdateDialog {
                Updater = UpdateManagerInstance
            };
            var noUpdateDialog = new NoUpdateFoundDialog {
                Updater = UpdateManagerInstance
            };

            var progressIndicator = new Progress <UpdateDownloadProgressChangedEventArgs>();
            var downloadDialog    = new UpdateDownloadDialog {
                Updater = UpdateManagerInstance
            };

            downloadDialog.CancelButtonClicked += UpdateDownloadDialogCancelButtonClick;

#if PROVIDE_TAP
            try
            {
                // TAP
                TaskEx.Run(async delegate
                {
                    if (!UseHiddenSearch)
                    {
                        _context.Post(searchDialog.ShowModalDialog, null);
                    }

                    try
                    {
                        _updatesAvailable = await UpdateManagerInstance.SearchForUpdatesAsync();
                    }
                    catch (OperationCanceledException)
                    {
                        return;
                    }
                    catch (Exception ex)
                    {
                        if (UseHiddenSearch)
                        {
                            _context.Send(
                                o =>
                                Popup.ShowPopup(SystemIcons.Error, _lp.UpdateSearchErrorCaption, ex,
                                                PopupButtons.Ok), null);
                        }
                        else
                        {
                            searchDialog.Fail(ex);
                            _context.Post(searchDialog.CloseDialog, null);
                        }
                        return;
                    }

                    if (!UseHiddenSearch)
                    {
                        _context.Post(searchDialog.CloseDialog, null);
                        await TaskEx.Delay(100);
                        // Prevents race conditions that cause that the UpdateSearchDialog can't be closed before further actions are done
                    }

                    if (_updatesAvailable)
                    {
                        var newUpdateDialogReference = new DialogResultReference();
                        _context.Send(newUpdateDialog.ShowModalDialog, newUpdateDialogReference);
                        if (newUpdateDialogReference.DialogResult == DialogResult.Cancel)
                        {
                            return;
                        }
                    }
                    else if (!_updatesAvailable && UseHiddenSearch)
                    {
                        return;
                    }
                    else if (!_updatesAvailable && !UseHiddenSearch)
                    {
                        var noUpdateDialogResultReference = new DialogResultReference();
                        if (!UseHiddenSearch)
                        {
                            _context.Send(noUpdateDialog.ShowModalDialog, noUpdateDialogResultReference);
                        }
                        return;
                    }

                    _context.Post(downloadDialog.ShowModalDialog, null);

                    try
                    {
                        progressIndicator.ProgressChanged += (sender, args) =>
                                                             downloadDialog.ProgressPercentage = (int)args.Percentage;

                        await UpdateManagerInstance.DownloadPackagesAsync(progressIndicator);
                    }
                    catch (OperationCanceledException)
                    {
                        return;
                    }
                    catch (Exception ex)
                    {
                        downloadDialog.Fail(ex);
                        _context.Send(downloadDialog.CloseDialog, null);
                        return;
                    }
                    _context.Send(downloadDialog.CloseDialog, null);

                    bool isValid = false;
                    try
                    {
                        isValid = UpdateManagerInstance.ValidatePackages();
                    }
                    catch (FileNotFoundException)
                    {
                        _context.Send(o => Popup.ShowPopup(SystemIcons.Error, _lp.PackageValidityCheckErrorCaption,
                                                           _lp.PackageNotFoundErrorText,
                                                           PopupButtons.Ok), null);
                    }
                    catch (ArgumentException)
                    {
                        _context.Send(o => Popup.ShowPopup(SystemIcons.Error, _lp.PackageValidityCheckErrorCaption,
                                                           _lp.InvalidSignatureErrorText, PopupButtons.Ok), null);
                    }
                    catch (Exception ex)
                    {
                        _context.Send(o => Popup.ShowPopup(SystemIcons.Error, _lp.PackageValidityCheckErrorCaption,
                                                           ex, PopupButtons.Ok), null);
                    }

                    if (!isValid)
                    {
                        _context.Send(o => Popup.ShowPopup(SystemIcons.Error, _lp.InvalidSignatureErrorCaption,
                                                           _lp.SignatureNotMatchingErrorText,
                                                           PopupButtons.Ok), null);
                    }
                    else
                    {
                        UpdateManagerInstance.InstallPackage();
                    }
                });
            }
            finally
            {
                _isTaskRunning = false;
            }
#else
            try
            {
                //EAP
                UpdateManagerInstance.UpdateSearchFinished            += SearchFinished;
                UpdateManagerInstance.UpdateSearchFinished            += searchDialog.Finished;
                UpdateManagerInstance.UpdateSearchFailed              += searchDialog.Failed;
                UpdateManagerInstance.PackagesDownloadProgressChanged += downloadDialog.ProgressChanged;
                UpdateManagerInstance.PackagesDownloadFinished        += downloadDialog.Finished;
                UpdateManagerInstance.PackagesDownloadFailed          += downloadDialog.Failed;

                Task.Factory.StartNew(() =>
                {
                    UpdateManagerInstance.SearchForUpdatesAsync();
                    if (!UseHiddenSearch)
                    {
                        var searchDialogResultReference = new DialogResultReference();
                        _context.Send(searchDialog.ShowModalDialog, searchDialogResultReference);
                        _context.Send(searchDialog.CloseDialog, null);
                        if (searchDialogResultReference.DialogResult == DialogResult.Cancel)
                        {
                            return;
                        }
                    }
                    else
                    {
                        _searchResetEvent.WaitOne();
                    }

                    if (_updatesAvailable)
                    {
                        var newUpdateDialogResultReference = new DialogResultReference();
                        _context.Send(newUpdateDialog.ShowModalDialog, newUpdateDialogResultReference);
                        if (newUpdateDialogResultReference.DialogResult == DialogResult.Cancel)
                        {
                            return;
                        }
                    }
                    else if (!_updatesAvailable && UseHiddenSearch)
                    {
                        return;
                    }
                    else if (!_updatesAvailable && !UseHiddenSearch)
                    {
                        _context.Send(noUpdateDialog.ShowModalDialog, null);
                        _context.Send(noUpdateDialog.CloseDialog, null);
                        return;
                    }

                    UpdateManagerInstance.DownloadPackagesAsync();

                    var downloadDialogResultReference = new DialogResultReference();
                    _context.Send(downloadDialog.ShowModalDialog, downloadDialogResultReference);
                    _context.Send(downloadDialog.CloseDialog, null);
                    if (downloadDialogResultReference.DialogResult == DialogResult.Cancel)
                    {
                        return;
                    }

                    bool isValid = false;
                    try
                    {
                        isValid = UpdateManagerInstance.ValidatePackages();
                    }
                    catch (FileNotFoundException)
                    {
                        _context.Send(o => Popup.ShowPopup(SystemIcons.Error, _lp.PackageValidityCheckErrorCaption,
                                                           _lp.PackageNotFoundErrorText,
                                                           PopupButtons.Ok), null);
                    }
                    catch (ArgumentException)
                    {
                        _context.Send(o => Popup.ShowPopup(SystemIcons.Error, _lp.PackageValidityCheckErrorCaption,
                                                           _lp.InvalidSignatureErrorText, PopupButtons.Ok), null);
                    }
                    catch (Exception ex)
                    {
                        _context.Send(o => Popup.ShowPopup(SystemIcons.Error, _lp.PackageValidityCheckErrorCaption,
                                                           ex, PopupButtons.Ok), null);
                    }

                    if (!isValid)
                    {
                        _context.Send(o => Popup.ShowPopup(SystemIcons.Error, _lp.InvalidSignatureErrorCaption,
                                                           _lp.SignatureNotMatchingErrorText,
                                                           PopupButtons.Ok), null);
                    }
                    else
                    {
                        try
                        {
                            UpdateManagerInstance.InstallPackage();
                        }
                        catch (Win32Exception ex)
                        {
                            // TODO: Localize
                            _context.Send(o => Popup.ShowPopup(SystemIcons.Error, "Error while starting the installer.",
                                                               ex,
                                                               PopupButtons.Ok), null);
                        }
                        catch (Exception ex)
                        {
                            _context.Send(o => Popup.ShowPopup(SystemIcons.Error, _lp.InstallerInitializingErrorCaption,
                                                               ex,
                                                               PopupButtons.Ok), null);
                        }
                    }
                });
            }
            finally
            {
                _isTaskRunning = false;
            }
#endif
        }
コード例 #30
0
ファイル: Index.cs プロジェクト: molokovskikh/af_analitf-net
        private async Task DoAction(string phase, string action, string comment = null)
        {
            var cert   = Settings.Value.GetCert(Settings.Value.SbisCert);
            var parts  = Util.ParseSubject(cert);
            var result = await client.JsonRpc("СБИС.ПодготовитьДействие", new {
                Документ = new {
                    Идентификатор = CurrentItem.Value.Message.Идентификатор,
                    Этап          = new {
                        Название = phase,
                        Действие = new {
                            Название    = action,
                            Комментарий = comment,
                            Сертификат  = new {
                                ФИО       = parts.GetValueOrDefault("SN") + " " + parts.GetValueOrDefault("G"),
                                Должность = parts.GetValueOrDefault("T"),
                                ИНН       = parts.GetValueOrDefault("ИНН")
                            }
                        }
                    }
                }
            });

            var attachments = result["result"]["Этап"][0]["Вложение"].ToObject <Attach[]>();
            var crypt       = new Diadoc.Api.Cryptography.WinApiCrypt();
            var signs       = new List <Attach>();

            foreach (var attachment in attachments)
            {
                var file = await client.GetAsync(attachment.Файл.Ссылка);

                file.EnsureSuccessStatusCode();
                var content = await file.Content.ReadAsByteArrayAsync();

                var signature = await TaskEx.Run(() => crypt.Sign(content, cert.RawData));

                signs.Add(new Attach {
                    Идентификатор = attachment.Идентификатор,
                    Подпись       = new[] { new FileRef(signature) }
                });
            }
            result = await client.JsonRpc("СБИС.ВыполнитьДействие", new {
                Документ = new {
                    Идентификатор = CurrentItem.Value.Message.Идентификатор,
                    Этап          = new {
                        Название = phase,
                        Вложение = signs.ToArray(),
                        Действие = new {
                            Название = action,
                        }
                    }
                }
            });

            var doc = result["result"].ToObject <Doc>();

            foreach (var item in items.Where(x => x.Message.Идентификатор == doc.Идентификатор))
            {
                item.Message.Состояние = doc.Состояние;
                item.Status            = doc.Состояние?.Название;
            }
        }