Ejemplo n.º 1
0
        /// <summary>
        /// 创建Downloader.
        /// </summary>
        /// <param name="iTargetInfo">下载目标.</param>
        /// <param name="iOnStart">开始委托回调.</param>
        /// <param name="iOnSuccessed">成功委托回调.</param>
        /// <param name="iOnFailed">失败委托回调.</param>
        /// <param name="iRetries">重下载次数.</param>
        /// <param name="iTimeOut">超时时间(单位:秒).</param>
        public static HttpDownloader Create(
            DownloadTargetInfo iTargetInfo, OnStart iOnStart,
            OnSuccessed iOnSuccessed, OnFailed iOnFailed)
        {
            HttpDownloader downloader = new HttpDownloader();

            if (downloader != null)
            {
                // 初始化
                downloader.Init(iTargetInfo, iOnStart, iOnSuccessed, iOnFailed);
                return(downloader);
            }
            else
            {
                UtilsLog.Error("Create", "Downloader Create failed!!");
                return(null);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 创建Downloader(Http).
        /// </summary>
        /// <param name="iDownloadUrl">下载Url.</param>
        /// <param name="iOnStart">开始事件委托.</param>
        /// <param name="iOnSuccessed">成功事件委托.</param>
        /// <param name="iOnFailed">失败事件委托.</param>
        /// <param name="iType">下载对象类型.</param>
        public static HttpDownloader Create(
            string iDownloadUrl, OnStart iOnStart,
            OnSuccessedByUrl iOnSuccessed, OnFailedByUrl iOnFailed,
            TargetType iType = TargetType.Bundle)
        {
            HttpDownloader downloader = new HttpDownloader();

            if (downloader != null)
            {
                downloader.Init(iDownloadUrl, iOnStart, iOnSuccessed, iOnFailed, iType);
                return(downloader);
            }
            else
            {
                UtilsLog.Error("Create", "Downloader Create failed!!");
                return(null);
            }
        }
Ejemplo n.º 3
0
        public void Start(TimeSpan time)
        {
            if (active)
            {
                return;
            }

            active = true;
            OnStart?.Invoke();

            stopTimer = new Timer(time.TotalMilliseconds)
            {
                AutoReset = false,
            };

            stopTimer.Elapsed += Stop;
            stopTimer.Start();
        }
Ejemplo n.º 4
0
        /// <inheritdoc />
        public async Task StartAsync()
        {
            if (!IsInitialized)
            {
                await InitializeAsync();
            }

            if (InitializationException != null)
            {
                _log.LogCritical(InitializationException, "EliteAPI could not be started");
                OnError?.Invoke(this, InitializationException);
                await StopAsync();

                return;
            }

            IsRunning = true;

            var delay = TimeSpan.FromMilliseconds(500);

            if (_codeConfig.TickFrequency != TimeSpan.Zero)
            {
                delay = _codeConfig.TickFrequency;
            }

            var task = Task.Run(async() =>
            {
                _log.LogInformation("EliteAPI has started");
                OnStart?.Invoke(this, EventArgs.Empty);

                if (_codeConfig.ProcessHistoricalJournals)
                {
                    await ProcessHistoricalJournalFiles(_codeConfig.HistoricalJournalSpan);
                }

                while (IsRunning)
                {
                    await DoTick();
                    await Task.Delay(delay);
                }

                OnStop?.Invoke(this, EventArgs.Empty);
            });
        }
Ejemplo n.º 5
0
 /// <summary>
 /// 下载磁链接文件
 /// </summary>
 /// <param name="metalink">磁链接文件</param>
 /// <param name="dir">下载目录</param>
 /// <returns>成功返回任务标识符,失败返回空</returns>
 public string AddMetalink(string metalink, string fileName = "", string dir = "")
 {
     try
     {
         string gid = Aria2cWarpper.AddMetalink(metalink, fileName, dir);
         if (!string.IsNullOrWhiteSpace(gid))
         {
             Aria2cTask task = Aria2cWarpper.TellStatus(gid);
             OnStart?.Invoke(this, new Aria2cTaskEvent(task));
             AddDownTask(task);
         }
         return(gid);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
         return(string.Empty);
     }
 }
    void Update()
    {
        if (devContainer == null)
        {
            return;
        }
        if (!streaming && devContainer.newFrameAvailable && devContainer.pipe.ActiveProfile != null)
        {
            OnStart?.Invoke(devContainer.pipe.ActiveProfile);
            streaming = true;
        }
        if (streaming && devContainer.newFrameAvailable)
        {
            OnNewSample?.Invoke(devContainer.latestFrameSet);
        }

        meshRenderer.material.SetFloat("_PointSize", bodyghost.GetPointSize);
        meshRenderer.material.SetFloat("_UseDistance", bodyghost.GetScaleByDistance ? 1 : 0);
    }
Ejemplo n.º 7
0
        public void Start(IPEndPoint localIPEP, ushort bufferSize = 512)
        {
            _Cleanup();

            LocalIPEP  = localIPEP ?? throw new ArgumentNullException(nameof(localIPEP));
            BufferSize = bufferSize < 64 ? throw new ArgumentOutOfRangeException(nameof(bufferSize)) : bufferSize;

            _isOpen = new ValueWrapper <bool>(true);

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _socket.Bind(localIPEP);

            _thread = new Thread(_ReceiveThread);
            _thread.Start();

            LocalIPEP = (IPEndPoint)_socket.LocalEndPoint;

            OnStart?.Invoke();
        }
Ejemplo n.º 8
0
        public static async Task CSV(DataTable dt, string filename)
        {
            await Task.Yield();

            OnStart?.Invoke();
            using (StringWriter sw = new StringWriter())
            {
                StringBuilder sb = new StringBuilder();
                char          c  = ',';
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    sb.Append(dt.Columns[i].Caption + c);
                }
                sb.Append("\r\n");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        try
                        {
                            sb.Append(ConvertToSaveCell(dt.Rows[i][j]));

                            OnRunning.Invoke(i * dt.Columns.Count + (j + 1), dt.Rows.Count * dt.Columns.Count);
                        }
                        catch
                        {
                            sb.Append(c);
                        }
                    }
                    sb.Append("\r\n");
                }
                sw.Write(Encoding.UTF8.GetString(new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF }));
                sw.Write(sb);
                using (var fs = File.Open(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    using (StreamWriter ssw = new StreamWriter(fs))
                    {
                        await ssw.WriteAsync(sb.ToString());
                    }
                }
            }
            OnStop?.Invoke();
        }
Ejemplo n.º 9
0
        public void RunAction(Action <ActionContext> action, [CallerMemberName] string name = null)
        {
            using (var context = new ActionContext(name, Sanitizers))
            {
                try
                {
                    if (context.IsRoot)
                    {
                        OnStart?.Invoke(context);
                    }

                    action?.Invoke(context);
                }
                catch (Exception ex)
                {
                    throw HandleError(ex, context);
                }
            };
        }
Ejemplo n.º 10
0
        public async Task <T> RunAction <T>(Func <ActionContext, Task <T> > action, [CallerMemberName] string name = null)
        {
            using (var context = new ActionContext(name, Sanitizers))
            {
                try
                {
                    if (context.IsRoot)
                    {
                        OnStart?.Invoke(context);
                    }

                    return(await action?.Invoke(context));
                }
                catch (Exception ex)
                {
                    throw HandleError(ex, context);
                }
            };
        }
Ejemplo n.º 11
0
        public void AdjustedStart(int offsetMs)
        {
            if (CurrentState.CurrentPhase == TimerPhase.NotRunning)
            {
                TimeSpan AdjustedTimeSpan = new TimeSpan(0, 0, 0, 0, offsetMs);

                CurrentState.CurrentPhase          = TimerPhase.Running;
                CurrentState.CurrentSplitIndex     = 0;
                CurrentState.AttemptStarted        = TimeStamp.CurrentDateTime;
                CurrentState.AdjustedStartTime     = CurrentState.StartTimeWithOffset = TimeStamp.Now - CurrentState.Run.Offset - AdjustedTimeSpan;
                CurrentState.StartTime             = TimeStamp.Now;
                CurrentState.TimePausedAt          = CurrentState.Run.Offset;
                CurrentState.IsGameTimeInitialized = false;
                CurrentState.Run.AttemptCount++;
                CurrentState.Run.HasChanged = true;

                OnStart?.Invoke(this, null);
            }
        }
        public List <PoreAnalyzeData> FindShapes(Bitmap bitmap)
        {
            Bitmap      reversedbmp = ReverseBitmapColors(bitmap);
            BlobCounter blobCounter = new BlobCounter(reversedbmp);

            Blob[] blobs = blobCounter.GetObjects(reversedbmp, false);

            PoreAnalyzeData[] poreData = new PoreAnalyzeData[blobs.Length];
            OnStart?.Invoke(this, blobs.Length);

            Parallel.For(0, blobs.Length, index =>
            {
                var edgePoints  = blobCounter.GetBlobsEdgePoints(blobs[index]);
                poreData[index] = new PoreAnalyzeData(blobs[index], ReverseBitmapColors(blobs[index].Image.ToManagedImage()), edgePoints);
                OnProgress?.Invoke(this, new EventArgs());
            });

            return(poreData.ToList());
        }
Ejemplo n.º 13
0
        public IActionContext Create([CallerMemberName] string name = null,
                                     string contextGroupName        = "default")
        {
            var context = new ActionContext(contextGroupName, name, Settings, Sanitizers);

            context.State.SetParam("RunnerType", this.GetType().Name);

            if (context.Info.IsRoot)
            {
                OnStart?.Invoke(context);
            }

            context.OnDispose = c =>
            {
                OnEnd?.Invoke(c);
            };

            return(context);
        }
Ejemplo n.º 14
0
        public async Task RunAction(Func <ActionContext, Task> action, [CallerMemberName] string name = null, string contextGroupName = "default")
        {
            using (var context = new ActionContext(contextGroupName, name, Settings, Sanitizers))
            {
                try
                {
                    if (context.IsRoot)
                    {
                        OnStart?.Invoke(context);
                    }

                    await action?.Invoke(context);
                }
                catch (Exception ex)
                {
                    throw HandleError(ex, context);
                }
            };
        }
Ejemplo n.º 15
0
 /// <summary>
 /// 添加下载任务
 /// </summary>
 /// <param name="uri">下载地址</param>
 /// <param name="fileName">输出文件名</param>
 /// <param name="dir">下载文件夹</param>
 /// <param name="taskOptions">下载任务选项</param>
 /// <returns>成功返回任务标识符,失败返回空</returns>
 public string AddUri(string uri, string fileName = "", string dir = "", List <Dictionary <string, string> > taskOptions = null)
 {
     try
     {
         string gid = Aria2cWarpper.AddUri(uri, fileName, dir, taskOptions);
         if (!string.IsNullOrWhiteSpace(gid))
         {
             Aria2cTask task = Aria2cWarpper.TellStatus(gid);
             OnStart?.Invoke(this, new Aria2cTaskEvent(task));
             AddDownTask(task);
         }
         return(gid);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
         return(string.Empty);
     }
 }
Ejemplo n.º 16
0
        public void Start()
        {
            if (started || starting)
            {
                return;
            }


            LogEngineInfo("Starting...");
            starting = true;

            changedInputsStack.Clear();
            UpdateStatesFromLinks();

            started = true;

            //     updateNodesTimer.Start();
            OnStart?.Invoke();
            LogEngineInfo("Started");
        }
Ejemplo n.º 17
0
    public void Execute()
    {
        OnStart.Invoke();
        Caster.EventHandler.CastAbility.Invoke(this);
        foreach (Character target in Targets)
        {
            target.EventHandler.TargetedByAbility.Invoke(this);
        }
        Ability.Cooldown.StartCD();

        List <AbilityActionInstance> actionInsts = GenerateActionInstances();

        ActionSeriesExecuter seriesExecuter = new ActionSeriesExecuter();

        seriesExecuter.DoSeriesOfDelayedActions(actionInsts, () =>
        {
            OnComplete.Invoke();
            isActive = false;
        });
    }
Ejemplo n.º 18
0
 public void OnStartGame()
 {
     Gameisrun            = true;
     Score                = 0;
     button5050.Enabled   = true;
     buttonZvonok.Enabled = true;
     buttonZal.Enabled    = true;
     buttonA.Enabled      = true;
     buttonB.Enabled      = true;
     buttonC.Enabled      = true;
     buttonD.Enabled      = true;
     AnswerButtonsEnabled = true;
     StartGameToolStripMenuItem.Enabled = false;
     StopGameToolStripMenuItem.Enabled  = true;
     AdminToolStripMenuItem.Enabled     = false;
     labelScore.BackColor = System.Drawing.Color.FromArgb(50, 0, 255, 0);
     labelScore.Location  = new System.Drawing.Point(787, ScorePositionY + Yshift);
     Yshift -= 20;
     OnStart?.Invoke(this, EventArgs.Empty);
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Метод получает html-код страницы и запускает работу парсера.
        /// </summary>
        public async void StartParse()
        {
            OnStart?.Invoke(this);

            // Получаем код страницы.
            string source = await _loader.GetSource();

            if (string.IsNullOrEmpty(source))
            {
                return;
            }

            // Парсим код страницы с помощью AngleSharp.
            var           domParser = new AngleSharp.Html.Parser.HtmlParser();
            IHtmlDocument document  = await domParser.ParseDocumentAsync(source);

            T result = Parser.Parse(document);

            OnComplited?.Invoke(this, result);
        }
Ejemplo n.º 20
0
        private void Button_Start_Click(object sender, RoutedEventArgs e)
        {
            if (_Watch.IsRunning)
            {
                return;
            }


            if (Models.SettingsModel.Singleton.IsServer)
            {
                Models.SettingsModel.Singleton.Server.BroadcastLine((int)Scripts.JsonCommandIDs.Broadcast_TimerStarted);
            }



            EventTimer.Start();
            _Watch.Start();

            OnStart?.Invoke();
        }
Ejemplo n.º 21
0
        public void StartGame(String word = null)
        {
            if (IsGameStarted)
            {
                throw new HangmanGameAlreadyStartedException();
            }
            if (_difficultyPending != null)
            {
                _difficulty        = _difficultyPending;
                _difficultyPending = null;
            }
            var client = new WebClient();

            if (word != null)
            {
                GivenWord = word.ToUpper();
            }
            else
            {
                var wordLength = _random.Next(_difficulty.MinimumLetters, 20);
                try
                {
                    var data    = client.DownloadString(WordProvider).ToUpper();
                    var strings = JsonConvert.DeserializeObject <String[]>(data);
                    GivenWord = strings[0];
                }
                catch (WebException)
                {
                    throw new HangmanGameUnableToStartException("Couldn't fetch a random word from Online API");
                }
            }
            _lastState = HangmanState.Started;
            CorrectLetters.Clear();
            IncorrectLetters.Clear();
            _timer.Start();
            _stopwatch.Reset();
            _stopwatch.Start();
            IsGameStarted = true;
            FetchGameState();
            OnStart?.Invoke(_lastGameState);
        }
Ejemplo n.º 22
0
 public ValueTo(GameObject target) : base(target, iTween.ValueTo)
 {
     name             = new Name(this);
     from             = new From(this);
     to               = new To(this);
     time             = new Time(this);
     delay            = new Delay(this);
     speed            = new Speed(this);
     onstarttarget    = new OnStartTarget(this);
     onstartparams    = new OnStartParams(this);
     onstart          = new OnStart(this);
     onupdatetarget   = new OnUpdateTarget(this);
     onupdateparams   = new OnUpdateParams(this);
     onupdate         = new OnUpdate(this);
     oncompletetarget = new OnCompleteTarget(this);
     oncompleteparams = new OnCompleteParams(this);
     oncomplete       = new OnComplete(this);
     easetype         = new EaseType(this);
     looptype         = new LoopType(this);
     ignoretimescale  = new IgnoreTimeScale(this);
 }
Ejemplo n.º 23
0
 private void DoStart(bool isHard = true)
 {
     //允许硬启动,否则只有在关闭暂不提醒和番茄时钟模式时才允许启动工作计时
     if (isHard || !config.options.General.Noreset && !config.options.General.IsTomatoMode)
     {
         //休息提醒
         work_timer.Start();
         workTimerStopwatch.Restart();
     }
     //离开监听
     leave_timer.Start();
     //数据统计
     if (config.options.General.Data)
     {
         //重置用眼计时
         statistic.ResetStatisticTime();
         //用眼统计
         useeye_timer.Start();
     }
     OnStart?.Invoke(this, 0);
 }
Ejemplo n.º 24
0
        /// <summary>
        /// 初始化.
        /// </summary>
        /// <param name="iTarget">上传目标.</param>
        /// <param name="iOnStart">开始上传委托.</param>
        /// <param name="iOnFailed">上传失败委托.</param>
        /// <param name="iOnSuccessed">上传成功委托.</param>
        /// <param name="iUploadWay">上传方式.</param>
        private void Init(
            UploadItem iTarget,
            OnStart iOnStart,
            OnFailed iOnFailed,
            OnSuccessed iOnSuccessed,
            TUploadWay iUploadWay = TUploadWay.Ftp)
        {
            this._target      = iTarget;
            this._onStart     = iOnStart;
            this._onFailed    = iOnFailed;
            this._onSuccessed = iOnSuccessed;
            this._uploadWay   = iUploadWay;
            this.Retries      = ServersConf.GetInstance().NetRetries;

            if (this._server == null)
            {
                this._server = ServersConf.GetInstance().UploadServer;
            }
            this.UploadBaseUrl = ServersConf.GetBundleUploadBaseURL(this._server, this._target);
            this.FileName      = UploadList.GetLocalBundleFileName(this._target.ID, this._target.FileType);
        }
Ejemplo n.º 25
0
        public async Task DownloadLatestVersion()
        {
            try
            {
                OnStart?.Invoke(this, EventArgs.Empty);

                _webClient = new WebClient();

                _webClient.DownloadProgressChanged += (sender, e) => OnProgress?.Invoke(this, e);

                var release = await LatestVersion();

                var userprofile  = UserProfile.Get();
                var downloadPath = Path.Combine(Path.Combine(SaveFolderPath, "EliteVA"), release.TagName);

                Directory.CreateDirectory(downloadPath);
                Directory.CreateDirectory(userprofile.EliteVA.InstallationDirectory);

                userprofile.EliteVA.IsInstalled      = true;
                userprofile.EliteVA.InstalledVersion = release.TagName;
                userprofile.Save();

                foreach (var releaseAsset in release.Assets)
                {
                    var path = Path.Combine(downloadPath, releaseAsset.Name);
                    OnNewTask?.Invoke(this, "Downloading files");
                    await _webClient.DownloadFileTaskAsync(releaseAsset.BrowserDownloadUrl, path);

                    OnNewTask?.Invoke(this, "Extracting files");
                    ZipFile.ExtractToDirectory(path, userprofile.EliteVA.InstallationDirectory, true);
                }

                OnFinished?.Invoke(this, EventArgs.Empty);
                _webClient.Dispose();
            }
            catch (Exception ex)
            {
                OnError?.Invoke(this, ex.Message);
            }
        }
    public void Update()
    {
        m_Driver.ScheduleUpdate().Complete();

        if (!m_Connection.IsCreated)
        {
            Debug.Log("Something went wrong during connect");
            return;
        }

        DataStreamReader stream;

        NetworkEvent.Type cmd;

        while ((cmd = m_Connection.PopEvent(m_Driver, out stream)) != NetworkEvent.Type.Empty)
        {
            if (cmd == NetworkEvent.Type.Connect)
            {
                Debug.Log("We are now connected to the server");
                m_isConnected = true;
                m_mainThreadContext.Post(d => OnStart?.Invoke(this), null);
            }
            else if (cmd == NetworkEvent.Type.Data)
            {
                var str = "";
                while (stream.Length > stream.GetBytesRead())
                {
                    str += stream.ReadString();
                }

                ProcessMessage(str);
            }
            else if (cmd == NetworkEvent.Type.Disconnect)
            {
                Debug.Log("Client got disconnected from server");
                m_Connection  = default(NetworkConnection);
                m_isConnected = false;
            }
        }
    }
Ejemplo n.º 27
0
        private void TryDelayStart()
        {
            // 无需延时启动
            if (DelayStartTime < 0)
            {
                RequireInvokeDelayStart = false;
                Tick();
                return;
            }

            // 更新当前延时启动已运行时间
            DelayStartRunTime += Time.deltaTime;

            // 延时启动时间未到
            if (DelayStartRunTime <= DelayStartTime)
            {
                return;
            }

            OnStart?.Invoke(this);
            RequireInvokeDelayStart = false;
        }
Ejemplo n.º 28
0
        public void _capDevice_OnStart(object sender, DeviceEventBaseArgs e)
        {
            if (this.statusStrip1.InvokeRequired)
            {
                OnStart onStart = new OnStart(_capDevice_OnStart);
                this.statusStrip1.BeginInvoke(onStart, new object[] { sender, e });
            }
            else
            {
                label1.ForeColor = Color.Green;
                label1.Text      = string.Format("Device {0} started", this._capDevice.DeviceID);

                try
                {
                    this.toolStripContaminationBar.Value = Convert.ToInt32(_capDevice.Contamination);
                }
                catch (Exception)
                {
                    System.Diagnostics.Trace.WriteLine("Not all Live Scanners support Contamination function", "Warning");
                }
            }
        }
Ejemplo n.º 29
0
        public void ExecuteStep()
        {
            try
            {
                SetStart();
                OnStart?.Invoke(Reference);

                Execute();
                OnSuccess?.Invoke(Reference, this);

                SetEnd();
            }
            catch (Exception e)
            {
                HasExecutionError = true;
                OnFail?.Invoke(Reference, e);
            }
            finally
            {
                OnFinish?.Invoke(Reference);
            }
        }
    private void FaceIn(RectTransform rectTransform, float timeAnimation, float timeDelay, float end = 1f, TweenCallback actionOnStart = null, TweenCallback actionOnComplete = null, Ease ease = Ease.OutCubic)
    {
        if (canvasGroup == null)
        {
            canvasGroup = rectTransform.GetComponent <CanvasGroup>();
        }
        if (canvasGroup == null)
        {
            canvasGroup = rectTransform.gameObject.AddComponent <CanvasGroup>();
        }
        canvasGroup.alpha = 0f;

        gameObject.SetActive(true);
        canvasGroup.DOKill(true);
        rectTransform.DOKill(true);
        rectTransform
        .DOAnchorPos(UIManager.startAnchoredPosition2D, 0).OnComplete(() =>
        {
            canvasGroup
            .DOFade(end, timeAnimation)
            .SetDelay(timeDelay)
            .SetEase(ease)
            .SetUpdate(UpdateType.Normal, true)
            .OnStart(() =>
            {
                actionOnStart?.Invoke();
                OnStart?.Invoke();
            })
            .OnComplete(() =>
            {
                ShowElements(() =>
                {
                    Status = UIAnimStatus.IsShow;
                    actionOnComplete?.Invoke();
                    OnShowCompleted?.Invoke();
                });
            });
        }).SetUpdate(UpdateType.Normal, true);
    }