public override void OnError(string deviceAddress,
                              int error, int errorType, string message)
 {
     base.OnError(deviceAddress, error, errorType, message);
     Log.Info("DFU", $"Dfu failcode {error}, type {errorType}, msg: {message}");
     Failed?.Invoke(this, message);
 }
Beispiel #2
0
        private async void OnSave()
        {
            var editingAccDocumentItem = Mapper.Map <EditableAccDocumentItem, AccDocumentItem>(AccDocumentItem);

            try
            {
                if (EditMode)
                {
                    await _accDocumentItemsService.UpdateAccDocumentItemAsync(editingAccDocumentItem);
                }
                else
                {
                    await _accDocumentItemsService.AddAccDocumentItemAsync(editingAccDocumentItem);
                }
                Done?.Invoke();
            }
            catch (Exception ex)
            {
                Failed?.Invoke(ex);
            }
            finally
            {
                AccDocumentItem = null;
            }
        }
        public void PushDelete(Entity entity, int serverId, Action callback, Failed failed)
        {
            // get...
            string url = GetEntityUrlForPush(entity, serverId);

            ExecuteODataOperation(ODataOperation.Delete, url, null, callback, failed);
        }
Beispiel #4
0
        public async void Download(FileDTO file)
        {
            var directory = "Downloads";

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            var destination = Path.Combine(directory, $"{file.Id.ToString()}{Path.GetExtension(file.Name)}");

            for (int part = 1; part <= file.Parts; part++)
            {
                var filePartResponse = await _httpManager.GetAsync <FilePartDTO>($"api/Files/{file.Id}/DownloadPart/{part}");

                if (filePartResponse.Error != null)
                {
                    Failed?.Invoke(filePartResponse.Error.ErrorDescription);
                    return;
                }

                using (var fs = new FileStream(destination, FileMode.Append, FileAccess.Write, FileShare.Write))
                {
                    fs.Write(filePartResponse.Data.Content, 0, filePartResponse.Data.Content.Length);
                    //fs.BeginWrite(
                    //    filePartResponse.Data.Content,
                    //    0,
                    //    filePartResponse.Data.Content.Length,
                    //    new AsyncCallback((a) => { PartDownloaded(part); }),
                    //    null);
                    PartDownloaded(part);
                }
            }
        }
Beispiel #5
0
        private async void OnSave()
        {
            var editingRelatedPerson = Mapper.Map <EditableRelatedPerson, RelatedPerson>(RelatedPerson);

            try
            {
                if (EditMode)
                {
                    await _relatedPeopleService.UpdateRelatedPersonAsync(editingRelatedPerson);
                }
                else
                {
                    await _relatedPeopleService.AddRelatedPersonAsync(editingRelatedPerson);
                }
                Done?.Invoke();
            }
            catch (Exception ex)
            {
                Failed?.Invoke(ex);
            }
            finally
            {
                RelatedPerson = null;
            }
        }
Beispiel #6
0
        public static void ClamScanAllFiles()
        {
            UpdateProgress2?.Invoke("Asking database for files", null, 0, 0);

            #if DEBUG
            stopwatch.Restart();
            #endif

            if (!dbCore.DbOps.GetNotAvFiles(out List <DbFile> files))
            {
                Failed?.Invoke("Could not get files from database.");
            }
            #if DEBUG
            stopwatch.Stop();
            Console.WriteLine("Core.ClamScanAllFiles(): Took {0} seconds to get files from database",
                              stopwatch.Elapsed.TotalSeconds);
            stopwatch.Restart();
            #endif
            int counter = 0;
            foreach (DbFile file in files)
            {
                UpdateProgress2?.Invoke($"Scanning file {counter} of {files.Count}", null, counter, files.Count);

                ClamScanFileFromRepo(file);

                counter++;
            }
            #if DEBUG
            stopwatch.Stop();
            Console.WriteLine("Core.ClamScanAllFiles(): Took {0} seconds scan all pending files",
                              stopwatch.Elapsed.TotalSeconds);
            #endif

            Finished?.Invoke();
        }
Beispiel #7
0
 public override int GetHashCode()
 {
     unchecked
     {
         return((Failed.GetHashCode() * 397) ^ (int)Type);
     }
 }
        internal void SendRequest(RestRequestArgs args, Action<XElement> success, Failed failed)
        {
            if (args == null)
                throw new ArgumentNullException("args");
            if (success == null)
                throw new ArgumentNullException("success");
            if (failed == null)
                throw new ArgumentNullException("failed");

            // create a request state...
            RequestState state = new RequestState()
            {
                Owner = this,
                Args = args,
                Success = success,
                Failed = failed
            };

            // are we authenticated?  if we're not, we need to call that first...
            if (!(IsAuthenticated))
            {
                // call the authenticate routine, and ask it to call the state we just setup
                // if authentication works...
                ApiService.Authenticate(new Action(state.DoRequest), failed);
            }
            else
            {
                // call the method directly...
                state.DoRequest();
            }
        }
Beispiel #9
0
 private void Fail()
 {
     App.Current.Dispatcher.Invoke(() =>
     {
         Failed?.Invoke(this, new EventArgs());
     });
 }
Beispiel #10
0
        public static bool InitVirusTotal(string key)
        {
            VirusTotal vt     = null;
            FileReport report = null;

            try
            {
                Task.Run(async() =>
                {
                    vt = new VirusTotal(key);

                    report =
                        await vt.GetFileReportAsync("b82758fc5f737a58078d3c60e2798a70d895443a86aa39adf52dec70e98c2bed");
                }).Wait();
            }
            catch (Exception ex)
            {
                Failed?.Invoke(ex.InnerException?.Message);

                return(false);
            }

            if (report == null ||
                report.MD5 != "0bf60adb1435639a42b490e7e80d25c7")
            {
                return(false);
            }

            vTotal = vt;
            Context.VirusTotalEnabled = true;

            return(true);
        }
        private static void HandleDownloadException(string url, WebException ex, Failed failed)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("Failed to download '{0}'.", url);
            builder.Append("\r\n");

            // do we have a response...
            if (ex.Response != null)
            {
                try
                {
                    Stream stream = ex.Response.GetResponseStream();
                    if (stream == null)
                        throw new InvalidOperationException("'stream' is null.");
                    using (stream)
                    {
                        builder.Append("Response data: ");

                        // reader...
                        using (StreamReader reader = new StreamReader(stream))
                            builder.Append(reader.ReadToEnd());
                    }
                }
                catch (Exception readEx)
                {
                    builder.AppendFormat("An exception occurred when reading error data: " + readEx.Message);
                }
            }
            else
                builder.Append("(No response)");

            // defer to the context...
            failed(new InvalidOperationException(builder.ToString(), ex));
        }
        private async void OnSaveAdd()
        {
            var editingSL = Mapper.Map <EditableSL, SL>(SL);

            foreach (var sLStandardDescriptions in SLStandardDescriptionListViewModel.SLStandardDescriptions)
            {
                sLStandardDescriptions.SLId = SL.SLId;
            }
            editingSL.SLStandardDescriptions = SLStandardDescriptionListViewModel.SLStandardDescriptions;
            try
            {
                if (EditMode)
                {
                    await _sLsService.UpdateSLAsync(editingSL);
                }
                else
                {
                    await _sLsService.AddSLAsync(editingSL);
                }
                Done?.Invoke();
            }
            catch (Exception ex)
            {
                Failed?.Invoke(ex);
            }
            finally
            {
                AddSLRequested(new SL());
            }
        }
Beispiel #13
0
        public static async Task <Result <S> > ToResult <S>(this HttpResponseMessage response) where S : class
        {
            var json = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                var success = JsonConvert.DeserializeObject <S>(json);

                return(new Result <S>(success, json, response.StatusCode));
            }
            try
            {
                var failed = JsonConvert.DeserializeObject <Failed>(json);

                failed = failed ?? new Failed();

                return(new Result <S>(failed, json, response.StatusCode));
            }
            catch (Exception)
            {
                var failed = new Failed {
                    Message = response.StatusCode.ToString()
                };
                return(new Result <S>(failed, json, response.StatusCode));
            }
        }
Beispiel #14
0
 private void BackgroundLoop()
 {
     try
     {
         while (!tracker.IsDisposed)
         {
             if (tracker.TryPopResult(out var bodyFrame))
             {
                 using (bodyFrame)
                 {
                     BodyFrameReady?.Invoke(this, new BodyFrameReadyEventArgs(bodyFrame));
                 }
             }
             else
             {
                 Thread.Sleep(1);
             }
         }
     }
     catch (ObjectDisposedException)
     { }
     catch (Exception exc)
     {
         Failed?.Invoke(this, new FailedEventArgs(exc));
     }
 }
Beispiel #15
0
        // ダウンロード完了
        private void OnDownloadCompleted(Task <DownloadOperation> prevTask)
        {
            if (prevTask.IsFaulted)
            {
                Debug.WriteLine("キャッシュ失敗");
                Failed?.Invoke(this, EventArgs.Empty);
                return;
            }

            Debug.WriteLine("キャッシュ完了");

            if (prevTask.Result != null)
            {
                var op = DownloadOperation;
                if (op.Progress.Status == BackgroundTransferStatus.Completed)
                {
                    if (op.Progress.TotalBytesToReceive == op.Progress.BytesReceived)
                    {
                        Debug.WriteLine("キャッシュ済み: " + op.ResultFile.Name);
                        Completed?.Invoke(this, EventArgs.Empty);
                    }
                    else
                    {
                        Debug.WriteLine("キャッシュキャンセル: " + op.ResultFile.Name);
                        Canceled?.Invoke(this, EventArgs.Empty);
                    }
                }
                else
                {
                    Debug.WriteLine($"キャッシュ失敗: {op.ResultFile.Name} ");
                    Failed?.Invoke(this, EventArgs.Empty);
                }
            }
        }
Beispiel #16
0
        internal static async Task PersistFailedMessage(EmailDto dto, Exception ex)
        {
            using (var dbContext = CreateDbContext())
            {
                var trail = await dbContext.Emails.FindAsync(dto.Id);

                if (trail.Status != EmailStatus.FailedToSend)
                {
                    var message = new Failed
                    {
                        Id              = dto.Id,
                        Receiver        = dto.Receiver,
                        Sender          = dto.Sender,
                        Subject         = dto.Subject,
                        Body            = dto.Body,
                        CreatedDateTime = DateTime.UtcNow,
                        Error           = ex?.ToString()
                    };

                    await dbContext.AddAsync(message);

                    trail.Status = EmailStatus.FailedToSend;
                    await dbContext.SaveChangesAsync();
                }
            }
        }
        private static void HandleDownloadResult(IAsyncResult result)
        {
            // unpackage the state...
            object[]        state   = (object[])result.AsyncState;
            HttpWebRequest  request = (HttpWebRequest)state[0];
            Action <string> success = (Action <string>)state[1];
            Failed          failed  = (Failed)state[2];

            // unwind...
            try
            {
                // get the response...
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
                using (Stream stream = response.GetResponseStream())
                {
                    // read the html out...
                    StreamReader reader = new StreamReader(stream);
                    string       html   = reader.ReadToEnd();

                    // callback the html...
                    success(html);
                }
            }
            catch (WebException ex)
            {
                HandleDownloadException(request.RequestUri.ToString(), ex, failed);
            }
            catch (Exception ex)
            {
                // callback the error...
                failed(ex);
            }
        }
        public async void OnSave()
        {
            var editingStock = Mapper.Map <EditableStock, Stock>(Stock);

            try
            {
                if (EditMode)
                {
                    await _stocksService.UpdateStockAsync(editingStock);
                }

                else
                {
                    await _stocksService.AddStockAsync(editingStock);
                }

                Done?.Invoke();
            }
            catch (Exception ex)
            {
                Failed?.Invoke(ex);
            }
            finally
            {
                Stock = null;
            }
        }
Beispiel #19
0
    /// <summary>
    /// 异步加载场景
    /// </summary>
    /// <param name="levelName">场景名称(不带扩展名)</param>
    /// <param name="url">指定场景url</param>
    /// <param name="begin">开始加载事件</param>
    /// <param name="failed">失败事件</param>
    /// <param name="loading">进度事件</param>
    /// <param name="finish">完成事件</param>
    public void LoadOTALevelAsync(string levelName, string url, Begin begin, Failed failed, Loading loading, Finished finish)
    {
        if (m_Loading)
        {
            EB.Debug.LogLoadLevel("[SceneRootEntry]LoadOTALevelAsync: Loading is in progress.");
            return;
        }

        OnBegin    = begin;
        OnFailed   = failed;
        OnFinished = finish;
        OnLoading  = loading;

        m_LevelAssetIndex = 0;
        m_Loading         = true;

        OnBegin?.Invoke();

        if (m_SceneRoot != null)
        {
            OnLoading?.Invoke(m_LevelAssets.Length, m_LevelAssets.Length);
            OnFinished?.Invoke(this);
            ClearLoading();
        }
        else
        {
            //加载相应的场景JSON配置信息
            GM.AssetManager.FetchSceneDescriptionFile(levelName, url, LoadedSceneDescription);
        }
    }
Beispiel #20
0
        private async void OnSave()
        {
            var editingSLStandardDescription = Mapper.Map <EditableSLStandardDescription, SLStandardDescription>(SLStandardDescription);

            try
            {
                if (EditMode)
                {
                    await _sLStandardDescriptionsService.UpdateSLStandardDescriptionAsync(editingSLStandardDescription);
                }
                else
                {
                    await _sLStandardDescriptionsService.AddSLStandardDescriptionAsync(editingSLStandardDescription);
                }
                Done?.Invoke();
            }
            catch (Exception ex)
            {
                Failed?.Invoke(ex);
            }
            finally
            {
                SLStandardDescription = null;
            }
        }
        public void Clean()
        {
            if (baseDirectory == null)
            {
                throw new ArgumentException("A directory have to be selected");
            }

            try
            {
                Starting?.Invoke(this, EventArgs.Empty);

                var taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
                Task.Factory.StartNew(() => ParseDirectory(baseDirectory),
                                      CancellationToken.None,
                                      TaskCreationOptions.None,
                                      taskScheduler).ContinueWith((t) =>
                {
                    Completed?.Invoke(this, EventArgs.Empty);
                }, taskScheduler);
            }
            catch (Exception ex)
            {
                Failed?.Invoke(this, ex);
            }
        }
        private async void OnSave()
        {
            var editingTypeDocument = Mapper.Map <EditableTypeDocument, TypeDocument>(TypeDocument);

            if (await _typeDocumentsService.HasTitle(editingTypeDocument.TypeDocumentTitle))
            {
                Information?.Invoke("عنوان تکراری می باشد");
            }
            else
            {
                try
                {
                    if (EditMode)
                    {
                        await _typeDocumentsService.UpdateTypeDocumentAsync(editingTypeDocument);
                    }
                    else
                    {
                        await _typeDocumentsService.AddTypeDocumentAsync(editingTypeDocument);
                    }
                    Done?.Invoke();
                }
                catch (Exception ex)
                {
                    Failed?.Invoke(ex);
                }
                finally
                {
                    TypeDocument = null;
                }
            }
        }
        /// <inheritdoc />
        public void Update(float delta)
        {
            if (finished || Objectives.Count == 0)
            {
                return;
            }

            var win   = true;
            var loose = false;

            foreach (IObjective objective in Objectives)
            {
                // Update objective
                objective.Update(delta);

                // Check Objective state
                win   = win && objective.Complete;
                loose = loose || objective.Fail;
            }

            // Game Complete
            if (!finished && win)
            {
                Completed?.Invoke(this, EventArgs.Empty);
                finished = true;
            }

            // Game Over
            if (!finished && loose)
            {
                Failed?.Invoke(this, EventArgs.Empty);
                finished = true;
            }
        }
Beispiel #24
0
        public void Deploy(
            IAuthenticated azure,
            DeploymentOptions options,
            IEnumerable <AzureResource> resources)
        {
            foreach (AzureResource resource in resources)
            {
                Task.Factory.StartNew(async() =>
                {
                    try
                    {
                        Started?.Invoke(this, new DeploymentEventArgs(resource));

                        await CreateResourceAsync(azure, options, resource.Type);

                        Finished?.Invoke(this, new DeploymentEventArgs(resource));
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"Error creating resource of type {resource.Type}: {ex}");
                        Failed?.Invoke(this, new DeploymentErrorEventArgs(resource, ex));
                    }
                });
            }
        }
        public override void ResponseReceived(byte[] parameter)
        {
            switch ((CommandResponse)parameter[0])
            {
            case CommandResponse.Failed:
                LogService.Error(
                    string.Format((string)Application.Current.Resources["GatheringComputerInformationFailed"],
                                  Encoding.UTF8.GetString(parameter, 1, parameter.Length - 1)));
                Failed?.Invoke(this, EventArgs.Empty);
                break;

            case CommandResponse.Successful:
                var serializer          = new Serializer(typeof(Shared.Commands.ComputerInformation.ComputerInformation));
                var computerInformation =
                    serializer.Deserialize <Shared.Commands.ComputerInformation.ComputerInformation>(parameter, 1);
                computerInformation.Timestamp = computerInformation.Timestamp.ToLocalTime();
                LogService.Receive(
                    string.Format(
                        (string)Application.Current.Resources["ComputerInformationSuccessfullyReceived"],
                        computerInformation.ProcessTime));
                ComputerInformationReceived?.Invoke(this, computerInformation);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Beispiel #26
0
        public IActionResult Sort_API()
        {
            //tbname,字段规则
            string orderStr = DataConvert.CStr(RequestEx["orderStr"]).Trim(',');

            if (string.IsNullOrEmpty(orderStr))
            {
                return(Content(Failed.ToString()));
            }
            string[] orderArr = orderStr.Split(',');
            foreach (string item in orderArr)
            {
                int id    = DataConvert.CLng(item.Split(':')[0]);
                int order = DataConvert.CLng(item.Split(':')[1]);
                switch (TbName.ToLower())
                {
                case "commonmodel":
                    DBCenter.UpdateSQL(TableName, "OrderID=" + order, "GeneralID=" + id);
                    break;

                case "product":
                    DBCenter.UpdateSQL(TableName, "OrderID=" + order, "ID=" + id);
                    break;

                case "modelfield":
                    DBCenter.UpdateSQL(TableName, "OrderID=" + order, "FieldID=" + id);
                    break;
                }
            }
            return(Content(Success.ToString()));
        }
        public void EarliestFirstSystemMessageList_must_properly_prepend_reversed_message_lists_to_the_front()
        {
            var create0 = new Failed(null, null, 0);
            var create1 = new Failed(null, null, 1);
            var create2 = new Failed(null, null, 2);
            var create3 = new Failed(null, null, 3);
            var create4 = new Failed(null, null, 4);
            var create5 = new Failed(null, null, 5);

            var fwdList = ENil + create5 + create4 + create3;
            var revList = LNil + create0 + create1 + create2;

            var list = fwdList + revList;

            (list.Head == create0).ShouldBeTrue();
            (list.Tail.Head == create1).ShouldBeTrue();
            (list.Tail.Tail.Head == create2).ShouldBeTrue();
            (list.Tail.Tail.Tail.Head == create3).ShouldBeTrue();
            (list.Tail.Tail.Tail.Tail.Head == create4).ShouldBeTrue();
            (list.Tail.Tail.Tail.Tail.Tail.Head == create5).ShouldBeTrue();

            ((ENil + LNil).Equals(ENil)).ShouldBeTrue();
            (((ENil + create0) + LNil).Head == create0).ShouldBeTrue();
            ((ENil + (LNil + create0)).Head == create0).ShouldBeTrue();
        }
Beispiel #28
0
        public async Task HandleLines()
        {
            try
            {
                var strm = NativeClient.GetStream();
                using var reader = new StreamReader(strm, Encoding.UTF8);
                string line;
                while ((line = await reader.ReadLineAsync()) != null)
                {
                    LineReceived?.Invoke(this, line);
                }
            }
            catch (IOException ex)
            {
                //Logger?.Log?.Error("HandleLines::IOException", ex);
                Failed?.Invoke(this, new MessageEventArgs(ex.Message));
            }
            catch (InvalidOperationException ex)
            {
                Logger?.Log?.Error("HandleLines::InvalidOperationException", ex);
                Failed?.Invoke(this, new MessageEventArgs(ex.Message));
            }

            Disconnected?.Invoke(this, null !);

            await Task.Delay(1000);
        }
        private async void OnSave()
        {
            var editingCurrency = Mapper.Map <EditableCurrency, Currency>(Currency);

            try
            {
                if (EditMode)
                {
                    await _currenciesService.UpdateCurrencyAsync(editingCurrency);
                }
                else
                {
                    await _currenciesService.AddCurrencyAsync(editingCurrency);
                }
                Done?.Invoke();
            }
            catch (Exception ex)
            {
                Failed.Invoke(ex);
            }
            finally
            {
                Currency = null;
            }
        }
Beispiel #30
0
        private void HandleFailed(Failed f) //Called handleFailure in Akka JVM
        {
            CurrentMessage = f;
            var failedChild         = f.Child;
            var failedChildIsNobody = failedChild.IsNobody();

            Sender = failedChildIsNobody ? _systemImpl.DeadLetters : failedChild;
            //Only act upon the failure, if it comes from a currently known child;
            //the UID protects against reception of a Failed from a child which was
            //killed in preRestart and re-created in postRestart

            ChildRestartStats childStats;

            if (TryGetChildStatsByRef(failedChild, out childStats))
            {
                var statsUid = childStats.Child.Path.Uid;
                if (statsUid == f.Uid)
                {
                    var handled = _actor.SupervisorStrategyInternal.HandleFailure(this, failedChild, f.Cause, childStats, ChildrenContainer.Stats);
                    if (!handled)
                    {
                        ExceptionDispatchInfo.Capture(f.Cause).Throw();
                    }
                }
                else
                {
                    Publish(new Debug(_self.Path.ToString(), _actor.GetType(), "Dropping Failed(" + f.Cause + ") from old child " + f.Child + " (uid=" + statsUid + " != " + f.Uid + ")"));
                }
            }
            else
            {
                Publish(new Debug(_self.Path.ToString(), _actor.GetType(), "Dropping Failed(" + f.Cause + ") from unknown child " + failedChild));
            }
        }
Beispiel #31
0
        public async void Upload(FileMessageRequest file, Guid roomId)
        {
            file.Size     = File.OpenRead(file.Path).Length;
            file.PartSize = BufferSize;
            file.Parts    = (int)Math.Ceiling(file.Size / (double)BufferSize);

            var response = await _httpManager.PostAsync <FileDTO>($"api/Rooms/{roomId.ToString()}/FileMessages", file);

            if (response.Error != null)
            {
                Failed?.Invoke(response.Error.ErrorDescription);
                return;
            }

            var position = 0;
            var part     = 1;

            while (position < file.Size)
            {
                byte[] buffer;
                if (position + BufferSize > file.Size)
                {
                    buffer = new byte[(int)file.Size - position];
                }
                else
                {
                    buffer = new byte[BufferSize];
                }

                using (BinaryReader reader = new BinaryReader(new FileStream(file.Path, FileMode.Open, FileAccess.Read)))
                {
                    reader.BaseStream.Seek(position, SeekOrigin.Begin);
                    if (position + BufferSize > file.Size)
                    {
                        reader.Read(buffer, 0, (int)file.Size - position);
                    }
                    else
                    {
                        reader.Read(buffer, 0, BufferSize);
                    }
                }

                var request = new FilePartDTO
                {
                    Content    = buffer,
                    PartNumber = part
                };

                var resp = await _httpManager.PostAsync <bool>($"api/Files/{response.Data.Id}", request);

                if (resp.Error != null)
                {
                    Failed?.Invoke(resp.Error.ErrorDescription);
                    return;
                }

                position += BufferSize;
            }
        }
        public RecordService CreateRecorder(RecordProps props)
        {
            if (_recorder != null)
            {
                return(this);
            }

            var options = new RecorderOptions
            {
                RecorderApi = props.WndHandle.HasValue
          ? RecorderApi.WindowsGraphicsCapture
          : RecorderApi.DesktopDuplication,
                IsHardwareEncodingEnabled = _configService.Config.IsHardwareEncodingEnabled,
                IsLowLatencyEnabled       = _configService.Config.IsLowLatencyEnabled,
                IsMp4FastStartEnabled     = _configService.Config.IsMp4FastStartEnabled,
                DisplayOptions            = new DisplayOptions
                {
                    Top               = props.Sides.Top,
                    Bottom            = props.Sides.Bottom,
                    Left              = props.Sides.Left,
                    Right             = props.Sides.Right,
                    WindowHandle      = props.WndHandle ?? IntPtr.Zero,
                    MonitorDeviceName = props.MonitorName
                },
                AudioOptions = new AudioOptions
                {
                    IsAudioEnabled        = _configService.Config.EnableSounds || _configService.Config.EnableMicrophone,
                    IsOutputDeviceEnabled = _configService.Config.EnableSounds,
                    IsInputDeviceEnabled  = _configService.Config.EnableMicrophone,
                    AudioOutputDevice     = props.AudioOutputDevice,
                    AudioInputDevice      = props.AudioInputDevice,
                    Bitrate  = AudioBitrate.bitrate_128kbps,
                    Channels = AudioChannels.Stereo
                },
                VideoOptions = new VideoOptions
                {
                    BitrateMode      = BitrateControlMode.Quality,
                    Quality          = _configService.Config.Quality,
                    Framerate        = _configService.Config.Framerate,
                    IsFixedFramerate = false,
                    EncoderProfile   = H264Profile.Main
                },
                MouseOptions = new MouseOptions
                {
                    IsMousePointerEnabled         = _configService.Config.IsMousePointerEnabled,
                    IsMouseClicksDetected         = _configService.Config.IsMouseClicksDetected,
                    MouseClickDetectionColor      = "#FFFF00",
                    MouseRightClickDetectionColor = "#FFFF00",
                    MouseClickDetectionMode       = MouseDetectionMode.Hook
                }
            };

            _recorder = Recorder.CreateRecorder(options);
            _recorder.OnRecordingComplete += (sender, args) => Completed?.Invoke(args.FilePath);
            _recorder.OnRecordingFailed   += (sender, args) => Failed?.Invoke(args.Error);
            _recorder.OnStatusChanged     += (sender, args) => StatusChanged?.Invoke(args.Status);
            _recorder.OnSnapshotSaved     += (sender, args) => SnapshotSaved?.Invoke();
            return(this);
        }
        public void DoSync(Action callback, Failed failed)
        {
            // set...
            this.Callback = callback;
            this.Failed = failed;

            // push up the changes...
            this.PushChanges();
        }
        public void DoSync(Action callback, Failed failed)
        {
            // set...
            this.Callback = callback;
            this.Failed = failed;

            // get latest...
            this.PushChanges();
        }
        public static void DownloadXml(string url, DownloadSettings settings, Action<XDocument> success, Failed failure)
        {
            // download a regular document...
            Download(url, settings, new Action<string>(delegate(string xml) {

                // turn into into a proper document and return...
                XDocument doc = XDocument.Parse(xml);
                success(doc);
                    
            }), failure);
        }
 protected override void Run()
 {
     Description = string.Format(Messages.PLUGIN_CALLING, Plugin);
     Result = XenAPI.Host.call_plugin(Session, Host.opaque_ref, Plugin, Function, Args);
     if (Result == "True")
         Description = string.Format(Messages.PLUGIN_SUCCEED, Plugin);
     else
     {
         log.WarnFormat("Plugin call {0}.{1}({2}) on {3} failed with {4}", Plugin, Function, ArgString(), Host.uuid, Result);
         Exception = new Failed(Result);
     }
 }
        public void ConnectedResultFilter_HandleReturnObject_FailedMessage()
        {
            var connectedResultFilter = new ConnectedResultFilter();

            var failed = new Failed() {Version = "1"};

            var returnedObject = new ReturnedObject("failed", JObject.FromObject(failed),
                JsonConvert.SerializeObject(failed));

            connectedResultFilter.HandleReturnObject(returnedObject);

            Assert.IsTrue(connectedResultFilter.IsCompleted());
            Assert.AreEqual(returnedObject, connectedResultFilter.GetReturnedObject());
        }
        internal void GetAll(Action<List<Bookmark>> callback, Failed failed)
        {
            // ask the server for a collection...
            AMX.BookmarkCollection serverItems = this.GetServerTarget();

            // create some state...
            QueryState state = new QueryState();
            state.Query = serverItems.CreateQuery<AMX.Bookmark>("Bookmark");
            state.Success = callback;
            state.Failed = failed;

            // run it, passing in the state object to be unwrapped in the callback handler...
            state.Query.BeginExecute(new AsyncCallback(ServerQueryFinished), state);
        }
        public static void Download(string url, DownloadSettings settings, Action<string> success, Failed failure)
        {
            // create the request stub...
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            // add...
            if (settings != null)
            {
                foreach (string name in settings.ExtraHeaders.Keys)
                    request.Headers[name] = settings.ExtraHeaders[name];
            }

            // call the server... we'll get notified at some point...
            request.BeginGetResponse(new AsyncCallback(HandleDownloadResult), new object[] { request, success, failure });
        }
        internal ExecuteServerItemsState ExecuteServerItems(AsyncCallback callback, Failed failed)
        {
            // state...
            ExecuteServerItemsState state = new ExecuteServerItemsState();
            state.ServerTarget = this.GetServerTarget();
            if (state.ServerTarget == null)
                throw new InvalidOperationException("'state.Bookmarks' is null.");

            // run...
            state.Query = state.ServerTarget.CreateQuery<AMX.Bookmark>("Bookmark");
            state.Query.BeginExecute(callback, failed);

            // erturn...
            return state;
        }
        public static void Download(string url, DownloadSettings settings, Action<string> success, Failed failure)
        {
            // create the request stub...
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.7) Gecko/20100713 Firefox/3.6.7";

            // add...
            if (settings != null)
            {
                foreach (string name in settings.ExtraHeaders.Keys)
                    request.Headers[name] = settings.ExtraHeaders[name];
            }

            // call the server... we'll get notified at some point...
            request.BeginGetResponse(new AsyncCallback(HandleDownloadResult), new object[] { request, success, failure });
        }
        public void ReplyMessageHandler_HandleMessage_HandlesFailed()
        {
            var connectionMock = new Mock<IDdpConnectionSender>();
            var collectionMock = new Mock<ICollectionManager>();
            var resultHandlerMock = new Mock<IResultHandler>();

            var failed = new Failed() {Version = "2"};

            var handler = new ReplyMessageHandler();

            handler.HandleMessage(connectionMock.Object, collectionMock.Object, resultHandlerMock.Object,
                JsonConvert.SerializeObject(failed));

            Assert.IsTrue(handler.CanHandle(failed.MessageType));

            resultHandlerMock.Verify(resultHandler => resultHandler.AddResult(It.IsAny<ReturnedObject>()));
        }
Beispiel #43
0
        public void DdpClient_ConnectAsync_ThrowsExceptionOnFailedConnect()
        {
            try
            {
                var task = this.client.ConnectAsync();

                var failed = new Failed { Version = "pre1" };
                this.testConnection.Reply(JsonConvert.SerializeObject(failed));

                task.Wait();
            }
            catch (AggregateException e)
            {
                Assert.IsTrue(e.InnerException is InvalidOperationException, "Expected InvalidOperationException");
                return;
            }
            
            Assert.Fail("Expected AggregateException");
        }
        public void Logon(string password, Action<LogonResponse> result, Failed failed)
        {
            // create the request...
            RestRequestArgs args = new RestRequestArgs("logon");
            args["password"] = password;

            // send the request...
            this.SendRequest(args, (Action<XElement>)delegate(XElement element)
            {
                // walk...
                LogonResponse response = LogonResponse.FromXmlElement(element);
                if (response == null)
                    throw new InvalidOperationException("'response' is null.");

                // call...
                result(response);

            }, failed);
        }
        internal static void Authenticate(Action callback, Failed failed)
        {
            ApiService service = new ApiService();
            service.Logon(ApiPassword, (Action<LogonResponse>)delegate(LogonResponse result)
            {
                // we have a result from *our* call to ApiService, if that works, call back to the next
                // item in the chain...
                if (result.Result == LogonResult.LogonOk)
                {
                    // store the token in static memory...
                    Token = result.Token;

                    // call the caller...
                    callback();
                }
                else
                    throw new InvalidOperationException(string.Format("A response of '{0}' was returned when authenticating the API.  Check that the the values of ApiUsername and ApiPassword correspond to your unique API account.", result.Result));

            }, failed);
        }
        public void Logon(String username, String password, Action<LogonResponse> callback, Failed failed)
        {
            // create the request...
            RestRequestArgs args = new RestRequestArgs("logon");

            // add the username and password...
            args["username"] = username;
            args["password"] = password;

            // send the request...
            SendRequest(args, delegate(XElement element)
            {
                // create a result from that...
                LogonResponse response = LogonResponse.FromXmlElement(element);
                if (response == null)
                    throw new InvalidOperationException("'response' is null.");

                // callback...
                callback(response);

            }, failed);
        }
        internal void Fail(int connection, Exception reason)
        {
            var currentState = PortStates[connection];
            if (IsDebug) Console.WriteLine($"{Name}   Fail({connection}, {reason}) [{currentState}]");
            PortStates[connection] = currentState | OutClosed;
            if ((currentState & (InClosed | OutClosed)) == 0)
            {
                PortStates[connection] = currentState | (OutClosed | InFailed);
                ConnectionSlots[connection] = new Failed(reason, ConnectionSlots[connection]);
                if ((currentState & (Pulling | Pushing)) == 0)
                    Enqueue(connection);
            }

            if ((currentState & OutClosed) == 0)
                CompleteConnection(Assembly.OutletOwners[connection]);
        }
Beispiel #48
0
 private bool Equals(Failed other)
 {
     return Equals(_ref, other._ref) && _exception.GetType() == other._exception.GetType();
 }
        internal static void DownloadXml(string url, DownloadSettings settings, Action<XDocument> callback, Failed failed)
        {
            // state...
            DownloadXmlState state = new DownloadXmlState();
            state.Callback = callback;
            state.Failed = failed;

            // call...
            Download(url, settings, new Action<string>(state.ReceiveHtml), failed);
        }