/// <summary> /// 初始化. /// </summary> /// <param name="iTarget">下载目标.</param> /// <param name="iOnStart">开始事件委托.</param> /// <param name="iOnSuccessed">成功事件委托.</param> /// <param name="iOnFailed">失败事件委托.</param> /// <param name="iLocalSave">本地保存标志位.</param> /// <param name="iType">下载对象类型.</param> public void Init( DownloadTargetInfo iTarget, OnStart iOnStart, OnSuccessed iOnSuccessed, OnFailed iOnFailed) { this._target = iTarget; this.DownloadBaseUrl = ServersConf.GetBundleDownloadBaseURL(iTarget); this.FileName = UploadList.GetLocalBundleFileName(iTarget.ID, iTarget.FileType); this.FullFileName = string.Format("{0}/{1}", this.DownloadDir, this.FileName); this.onStart = iOnStart; this.onSuccessed = iOnSuccessed; this.onFailed = iOnFailed; this.Retries = ServersConf.GetInstance().NetRetries; this.TimeOut = ServersConf.GetInstance().NetTimeOut * 1000; if (TBundleType.Scene != iTarget.BundleType) { this.TargetType = TargetType.BundleOfNormal; } else { this.TargetType = TargetType.BundleOfScenes; } // 检查目录 if (Directory.Exists(this.DownloadDir) == false) { Directory.CreateDirectory(this.DownloadDir); } }
private void Process() { if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var localVersion = Directory.GetDirectories(dir) .Select(x => { long datetime; string name = Path.GetFileName(x); string time = name.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries)[0]; bool success = long.TryParse(time, out datetime); return(new { success, dir = x, datetime }); }) .Where(x => x.success) .Prepend(new { success = false, dir = "", datetime = 0L }) .OrderBy(x => x.datetime) .Last(); // リポジトリ上の最新版を調べる前に、ローカルのバージョンを通知 if (localVersion.success) { OnComplete?.Invoke(false, localVersion.dir); } Task.Run(() => { var req = (HttpWebRequest)HttpWebRequest.Create(latestReleaseURL); req.ContentType = "application/json;charset=UTF-8"; req.UserAgent = "Mozilla/5.0"; WebResponse res; try { res = req.GetResponse(); } catch (Exception e) { OnFailed?.Invoke(e.Message); return; } var serializer = new DataContractJsonSerializer(typeof(GithubRelease)); // releases/latest に変える GithubRelease release = (GithubRelease)serializer.ReadObject(res.GetResponseStream()); long latestTicks = release.PublishedAt.Ticks; if (localVersion.datetime < latestTicks) { var dst = dir + "\\" + latestTicks + "_" + release.TagName; var cli = new WebClient(); var tempFile = Path.GetTempFileName(); cli.DownloadFile(release.Assets[0].DownloadUrl, tempFile); ZipFile.ExtractToDirectory(tempFile, dst); new DirectoryInfo(dst).CreationTime = release.PublishedAt; OnComplete?.Invoke(true, dst); } }); }
public async Task Failed(string fileName) { if (OnFailed != null) { await OnFailed.Invoke(fileName); } }
public async Task Build() { BuildContext buildContext = null; try { var dataSource = _pluginManager.Resolve <IDataSource>(_project.DataSource.Name); if (OnStartup != null) { await OnStartup.Invoke(this, new OnProjectBuildStartupEventArgs { Project = _project }); } await dataSource.InitData(); foreach (var buildKV in _project.BuildTasks) { _logger.LogInformation($"-------- BuildTask:{buildKV.Key} Start! ---------"); var output = buildKV.Value.Output; buildContext = new BuildContext { PluginManager = _pluginManager, Project = _project, DataSource = dataSource, BuildKey = buildKV.Key, Build = buildKV.Value, Output = output == null ? null : new Output { Type = output.Type, Path = output.Path, Name = output.Name, Mode = output.Mode, Extension = output.Extension } }; await _pluginManager.Resolve <IBuildTask>(buildKV.Value.Type).Build(buildContext); _logger.LogInformation($"-------- BuildTask:{buildKV.Key} End! ---------"); } if (OnSucceed != null) { await OnSucceed.Invoke(this, new OnProjectBuildSucceedEventArgs { Project = _project }); } } catch (Exception ex) { if (OnFailed != null) { await OnFailed.Invoke(this, new OnProjectBuildFailedEventArgs { Project = _project, Context = buildContext, ErrorException = ex }); } throw; } }
public void BeginRun() { if (State == JobsManagerState.Bussy) { return; } State = JobsManagerState.Bussy; OnStart?.Invoke(this, new EventArgs()); try { jobs = jobsProvider.GetJobs(GetJobsContext()); AttachEvents(jobs); tasks = jobs.Select(x => x.GetTask()).Union(jobs.Select(x => x.GetBackTask())).ToArray(); Task.Factory.ContinueWhenAll(tasks, x => { OnFinished?.Invoke(this, new EventArgs()); State = JobsManagerState.Ready; }); } catch (AggregateException) { OnFailed?.Invoke(this, new EventArgs()); State = JobsManagerState.Ready; } }
/// <summary> /// load data in the background /// </summary> /// <param name="path"></param> private async void loadData(string path) { if (cached) { // hack otherwise eventhandlers are not atached await Task.Delay(10); OnLoaded?.Invoke(Data, EventArgs.Empty); return; } try { using (var client = new HttpClient()) { var download = await client.GetStringAsync($"http://145.24.222.220/v2/{path}"); cache = JsonConvert.DeserializeObject <TData>(download); OnLoaded?.Invoke(Data, EventArgs.Empty); cached = true; } } catch { OnFailed?.Invoke(this, EventArgs.Empty); } }
private async void DownloadFile(MyFile file) { try { using (var client = new HttpClient()) { var response = client.GetAsync(file.Url); using (var fs = new FileStream(file.PathToSave + $"{file.FileID}.jpg", FileMode.CreateNew)) { await response.Result.Content.CopyToAsync(fs); } OnDownloaded?.Invoke($"Файл {file.FileID} загружен"); } } catch (Exception e) { OnFailed?.Invoke($"Файл {file.FileID} не загружен", e); } if (downloadingQueue.TryDequeue(out file)) { DownloadFile(file); } else { CurrentThreadCount--; } }
private void CheckProbe(bool IsFinal) { var Index = new QuickIndex(ElementsCount_); if (Elements_.ContainsKey(Index.GetHashCode())) { var Node = Elements_[Index.GetHashCode()]; if (IsFinal) { OnSucceed?.Invoke(Node); } else { OnProbe?.Invoke(Node); } } else { if (IsFinal) { OnFailed?.Invoke(); } else { OnProbe?.Invoke(null); } } }
public bool NextStage() { if (IsEnded) { return(false); } if (GoodPrecent < BadPrecent) { IsFailed = true; OnFailed?.Invoke(this); return(false); } if (_stagesQueue.Count > 1) { _stagesQueue.Dequeue(); OnStageChange?.Invoke(this); } else { IsFinite = true; OnStageChange?.Invoke(this); OnFinite?.Invoke(this); } return(true); }
/// <summary> /// Fail the objective /// </summary> /// <param name="reason">Reason of fail</param> public virtual void fail(string reason) { Tools.log("Fail " + getName()); this.stop(); OnFailed?.Invoke(this, reason); }
private void TimeoutElapsed(object sender, ElapsedEventArgs e) { if (!SharkDto.IsSolved) { OnFailed?.Invoke(this, _game); } }
async Task HandleUploadAsync(UploadOperation upload, bool start) { cts = new CancellationTokenSource(); try { LogStatus("Running: " + upload.Guid); Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(UploadProgress); if (start) { await upload.StartAsync().AsTask(cts.Token, progressCallback); } else { await upload.AttachAsync().AsTask(cts.Token, progressCallback); } ResponseInformation response = upload.GetResponseInformation(); LogStatus(string.Format("Completed: {0}, Status Code: {1}", upload.Guid, response.StatusCode)); } catch (TaskCanceledException) { OnFailed?.Invoke(this); MainPage.Current?.HideMediaUploadingUc(); LogStatus("Canceled: " + upload.Guid); } catch (Exception ex) { OnFailed?.Invoke(this); ex.PrintException("HandleUploadAsync"); MainPage.Current?.HideMediaUploadingUc(); } }
public static void Generate(OnSucceeded OnSucceeded, OnFailed OnFailed) { #if (UNITY_IOS) GenerateIdentityVerificationSignature(OnSucceeded, OnFailed); #else OnFailed.Invoke("GameCenter authentification is only available for iOS"); #endif }
private void SetFailed(Exception?unhandledException) { Dispose(); _unhandledException = unhandledException; _isFailed = true; OnFailed?.Invoke(this, _unhandledException); }
public void Interact(GameObject obj) { if (MeetsRequirements(obj)) { ChangeSignal(!Signaled); } else { OnFailed?.Invoke(obj); } }
void OnCollisionEnter2D(Collision2D collision) { if (collision.collider.GetComponent <Tile>()) { OnCollision?.Invoke(this, EventArgs.Empty); } if (collision.collider.transform.tag == "Bottom") { OnFailed?.Invoke(this, EventArgs.Empty); } }
/// <summary> /// 创建上传者. /// </summary> /// <param name="iTarget">上传目标.</param> /// <param name="iOnStart">开始上传委托.</param> /// <param name="iOnFailed">上传失败委托.</param> /// <param name="iOnSuccessed">上传成功委托.</param> /// <param name="iUploadWay">上传方式.</param> public static Uploader Create( UploadItem iTarget, OnStart iOnStart, OnFailed iOnFailed, OnSuccessed iOnSuccessed, TUploadWay iUploadWay = TUploadWay.Ftp) { Uploader objRet = new Uploader(); objRet.Init(iTarget, iOnStart, iOnFailed, iOnSuccessed, iUploadWay); return(objRet); }
public PanoDownloader() { m_UserDownloader = new UserPanoDownloader(); m_GoogleDownloader = new GooglePanoDownloader(); m_UserDownloader.OnStarted += () => OnStarted.TryInvoke(); m_UserDownloader.OnLoaded += tex => OnLoaded.TryInvoke(tex); m_UserDownloader.OnFailed += exception => OnFailed.TryInvoke(exception); m_GoogleDownloader.OnStarted += () => OnStarted.TryInvoke(); m_GoogleDownloader.OnLoaded += tex => OnLoaded.TryInvoke(tex); m_GoogleDownloader.OnFailed += exception => OnFailed.TryInvoke(exception); }
/// <summary> /// 资源释放 /// </summary> public void Dispose() { if (!_isBeginCalledBefore || IsDisposed) { return; } IsDisposed = true; if (!_succeed) { OnFailed?.Invoke(this, new UnitOfWorkFailedEventArgs(_exception)); } DisposeUow(); OnDisposed?.Invoke(this, EventArgs.Empty); }
private void Update() { if (moveType == MoveType.None) { return; } if (moveType == MoveType.Goal) //목표지점까지 이동 { transform.position = Vector3.MoveTowards(transform.position, destination, speed * Time.deltaTime); if (Vector3.Distance(transform.position, destination) < stopDistance) { if (nextGoals.Count == 0) { transform.position = destination; OnCompleted?.Invoke(); ResetState(); return; } else { destination = nextGoals[0]; nextGoals.RemoveAt(0); return; } } } else if (moveType == MoveType.Follow) //목표 타겟한테 이동 { if (target == null) { OnFailed?.Invoke(); ResetState(); return; } transform.position = Vector3.MoveTowards(transform.position, target.transform.position, speed * Time.deltaTime); if (Vector3.Distance(transform.position, target.transform.position) < stopDistance) { transform.position = target.transform.position; OnCompleted?.Invoke(); ResetState(); } } }
/// <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 WWWDownloader Create( DownloadTargetInfo iTargetInfo, OnStart iOnStart, OnSuccessed iOnSuccessed, OnFailed iOnFailed) { WWWDownloader downloader = new WWWDownloader(); if (downloader != null) { // 初始化 downloader.Init(iTargetInfo, iOnStart, iOnSuccessed, iOnFailed); return(downloader); } else { UtilsLog.Error("Create", "Downloader Create failed!!"); return(null); } }
private async Task CreateDownload(string url, string pathToSave, string id) { try { int fileSize = await GetFileSize(url); var finalPathToSave = pathToSave + "\\" + Path.GetFileName(url); using (var httpClient = new HttpClient()) { using (var request = new HttpRequestMessage(HttpMethod.Get, url)) { using ( Stream contentStream = await(await httpClient.SendAsync(request)).Content.ReadAsStreamAsync(), stream = new FileStream(finalPathToSave, FileMode.Create)) { var buffer = new byte[4096]; var downloaded = 0; while (true) { var length = contentStream.Read(buffer, 0, buffer.Length); if (length <= 0) { break; } await stream.WriteAsync(buffer, 0, length); downloaded += length; if (downloaded % 102400 == 0) { Task.Factory.StartNew(() => OnFileProgress?.Invoke(id, fileSize, downloaded)).Wait(); } } } } } OnDownloaded?.Invoke(id); } catch (Exception ex) { OnFailed?.Invoke(id, ex); } ManageDownloads(); }
private void ConnectCallback(IAsyncResult ar) { if (_closed) { return; } try { AsyncSession <ServerTimer> session = (AsyncSession <ServerTimer>)ar.AsyncState; ServerTimer timer = session.State; _server = timer.Server; timer.Elapsed -= DestConnectTimer_Elapsed; timer.Enabled = false; timer.Dispose(); IProxy remote = session.Remote; // Complete the connection. remote.EndConnectDest(ar); _destConnected = true; Logger.Debug($"Socket connected to ss server: {_server.ToString()}"); TimeSpan latency = DateTime.Now - _startConnectTime; OnConnected?.Invoke(this, new SSTCPConnectedEventArgs(_server, latency)); StartPipe(session); } catch (ArgumentException) { } catch (Exception e) { if (_server != null) { OnFailed?.Invoke(this, new SSRelayEventArgs(_server)); } ErrorClose(e); } }
/// <summary> /// Downloads the panorama image using the known PanoID /// </summary> /// <param name="panoID">The PanoID to be downloaded</param> /// <param name="size">The <see cref="PanoSize"/> of the image to be downloaded.</param> /// <param name="onResult">Callback containing the Texture2D of the pano image</param> /// <param name="onException">Callback containing the exception when the download fails</param> public void Download(string panoID, PanoSize size, TextureFormat format, Action <Texture32> onResult = null, Action <Exception> onException = null) { var width = PanoUtility.GetUserPanoWidth(size); string url = "https://lh5.googleusercontent.com/p/" + panoID + "=w" + width; m_Running = true; OnStarted.TryInvoke(); new RestClient().ExecuteAsync(new RestRequest(url, Method.GET), out m_Handle) .Then(response => { if (!m_Running) { return; } Dispatcher.Enqueue(() => { if (response.IsSuccess()) { var texture = new Texture2D(1, 1, format, true); texture.LoadImage(response.RawBytes); var result = Texture32.FromTexture2D(texture); MonoBehaviour.Destroy(texture); texture = null; onResult.TryInvoke(result); OnLoaded.TryInvoke(result); } else { OnFailed.TryInvoke(response.GetException()); onException.TryInvoke(response.GetException()); } }); }) .Catch(exception => { if (!m_Running) { return; } onException.TryInvoke(exception); }); }
/// <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); }
private void DestConnectTimer_Elapsed(object sender, ElapsedEventArgs e) { ServerTimer timer = (ServerTimer)sender; timer.Elapsed -= DestConnectTimer_Elapsed; timer.Enabled = false; timer.Dispose(); if (_destConnected || _closed) { return; } AsyncSession session = timer.Session; Server server = timer.Server; OnFailed?.Invoke(this, new SSRelayEventArgs(_server)); Logger.Info($"{server.ToString()} timed out"); session.Remote.Close(); Close(); }
private async Task DownloadFileAsync(FileModel file) { await Task.Run(async() => { try { using (var response = client.GetAsync(file.Url)) { using (var stream = new FileStream(file.PathToSave, FileMode.Create)) { await response.Result.Content.CopyToAsync(stream); } } OnDownloaded?.Invoke($"File {file.FileId} downloaded"); } catch (Exception e) { OnFailed?.Invoke($"Downloading of file {file.FileId} canceled", e); } }); countOfDownloadTasks--; }
public void Dispense(IEnumerable <OrderItem> items) { IEnumerable <DispenseCommand> dispensingChain = _strategy.BuildDispensingChain(items); foreach (DispenseCommand command in dispensingChain) { IDispenser _dispenser = _dispensers.SingleOrDefault(x => x.Id == command.Address.VendingMachineID); if (_dispenser == null) { OnFailed?.Invoke(this, new DispenseFailEventArgs { address = command.Address.Address, message = "Unable to detect the machine" }); } if (_dispenser.Dispense(command.Address, command.Quantity)) { OnDispensing?.Invoke(this, new DispenseEventArgs { address = command.Address.Address }); } } }
/// <summary> /// Fail event /// </summary> /// <param name="obj">object</param> private static void OnFailedHandle(ConnectionFailedEventArgs obj) { //Invoke event OnFailed?.Invoke(obj); }
/// <summary>Events</summary> public void Event() { RaiseEvent raiseEvent; while (Events.TryDequeue(out raiseEvent)) { // Raise start event if (raiseEvent.EventType == EventType.Started) { OnStarted?.Invoke(); } // Raise stop event if (raiseEvent.EventType == EventType.Stopped) { OnStopped?.Invoke(); } // Raise link event if (raiseEvent.EventType == EventType.Linked) { OnLinked?.Invoke(raiseEvent.Link); } // Raise redirection event if (raiseEvent.EventType == EventType.Redirect) { OnRedirect?.Invoke(raiseEvent.Link); } // Raise post redirection event if (raiseEvent.EventType == EventType.Redirected) { OnRedirected?.Invoke(raiseEvent.Link); } // Raise approval event if (raiseEvent.EventType == EventType.Approval) { OnApproval?.Invoke(raiseEvent.Link, raiseEvent.Content); } // Raise content event if (raiseEvent.EventType == EventType.Content) { OnContent?.Invoke(raiseEvent.Link, raiseEvent.Content); } // Raise unlink event if (raiseEvent.EventType == EventType.Unlinked) { OnUnlinked?.Invoke(raiseEvent.Link, raiseEvent.Reason); } // Raise failure event if (raiseEvent.EventType == EventType.Failed) { OnFailed?.Invoke(raiseEvent.Link, raiseEvent.Failure); } } }