/*------------------------------------------------------------------------- * 共有情報の取得と設定 * スレッド対応 * ---------------------------------------------------------------------------*/ public void Share(int x, int y, State _state) { if (m_lib.setting.share_group == "") { return; } if (m_lib.setting.share_group_myname == "") { return; } string url = "/getposition.php?server=" + GvoWorldInfo.GetServerStringForShare(m_lib.setting.server); url += "&group=" + Useful.UrlEncodeShiftJis(m_lib.setting.share_group); url += "&name=" + Useful.UrlEncodeShiftJis(m_lib.setting.share_group_myname); url += "&x=" + x.ToString(); url += "&y=" + y.ToString(); url += "&out=" + ((int)_state).ToString(); string data = HttpDownload.Download(def.URL_HP_ORIGINAL + url, Encoding.GetEncoding("shift_jis")); if (data == null) { return; } update_list(data); }
public static void Init(MonoBehaviour mono, GeneralGameSetting gameSetting) { instance = new DownloadManager(); //这里还可以用多线程模式,速度其实差不多 instance.httpDownload = HttpDownload.GetHttpDownload(HttpDownload.DownloadMechanic.Coroutine, 3, mono); instance.m_gameSetting = gameSetting; }
private void HttpDownloadFile(string sourceuri, string targetfilename) { if (IsWebResourceAvailable(sourceuri) == false) { MessageBox.Show("指定的资源无效"); return; } listBox1.Items.Add("同时接受线程数:" + threadNumber); HttpWebRequest request; long fileSize = 0; try { request = (HttpWebRequest)HttpWebRequest.Create(sourceuri); request.Method = WebRequestMethods.Http.Head; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); fileSize = response.ContentLength; listBox1.Items.Add("文件大小:" + Math.Ceiling(fileSize / 1024.0f) + "KB"); response.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } int downloadFileSize = (int)(fileSize / threadNumber); d = new HttpDownload[threadNumber]; for (int i = 0; i < threadNumber; i++) { d[i] = new HttpDownload(listBox1, i); d[i].StartPosition = downloadFileSize * i; if (i < threadNumber - 1) { d[i].FileSize = downloadFileSize; } else { d[i].FileSize = (int)(fileSize - downloadFileSize * (i - 1)); } d[i].IsFinish = false; d[i].TargetFileName = "D:/Study P2P/target/tmp/" + Path.GetFileNameWithoutExtension(targetfilename) + i + "._tmp"; //d[i].filename = Path.GetFileNameWithoutExtension(targetfilename) + ".$$" + i; d[i].SourceUri = textBox1.Text; } Thread [] threads = new Thread[threadNumber]; for (int i = 0; i < threadNumber; i++) { threads[i] = new Thread(d[i].Receive); threads[i].IsBackground = true; threads[i].Start(); } CombineFiles c = new CombineFiles(listBox1, d, "D:\\Study P2P\\target\\tmp\\" + textBox2.Text); Thread t = new Thread(c.Combine); t.IsBackground = true; t.Start(); }
private void onCmp(WWW www) { var text = HttpDownload.GetString(www); ServerList.Singleton.Init(text); Debug.Log("serverlist下载成功:" + text); //检测是否需要更新app AppUpdate.Singleton.Enter(); }
public void Download() { //下载serverlist var serverlistUrl = BaseConfig.Singleton.BaseIndexServerUrl + "/serverlist/ServerList.json" + BaseConfig.Singleton.ChannelId; Debug.Log("ServerList地址:" + serverlistUrl); HttpDownload.Request(serverlistUrl, 15, onCmp, onTimeout, onFail, onUpdate); }
private void download(string url, string saveFileName) { this.progress.Value = 0; this.progress.Maximum = 100; HttpDownload conn = new HttpDownload(url, saveFileName); conn.OnDownloadProgress += conn_OnDownloadProgress; conn.Download(); }
private List <FileVersionInfo> GetRemoteFileVersionInfo() { var data = HttpDownload.HttpGetString(RemoteFileList); if (!string.IsNullOrEmpty(data)) { return(JsonConvert.DeserializeObject <List <FileVersionInfo> >(data)); } return(null); }
/*------------------------------------------------------------------------- * 共有情報の取得と設定 * スレッド対応 * ---------------------------------------------------------------------------*/ public void Share() { string data = HttpDownload.Download(def.URL_HP_ORIGINAL + @"/getallpos.php", Encoding.GetEncoding("shift_jis")); if (data == null) { return; } update_list(data); }
private void updateCommand_action(object obj) { downloader = new HttpDownload(githubRelease.Info.DownloadUrl, savePath); downloader.ProcessUpdateEvent += Downloader_ProcessUpdateEvent; downloader.CompleteEvent += Downloader_CompleteEvent; downloader.ErrorEvent += Downloader_ErrorEvent;; downloader.Start(); Tip = $"{Application.Current.Resources["Lang_Requestingdownloadsources"]}..."; PlayProcess = true; UpVisibility = Visibility.Collapsed; }
private void updateCommand_action(object obj) { downloader = new HttpDownload(githubRelease.Info.DownloadUrl, savePath); downloader.ProcessUpdateEvent += Downloader_ProcessUpdateEvent; downloader.CompleteEvent += Downloader_CompleteEvent; downloader.ErrorEvent += Downloader_ErrorEvent;; downloader.Start(); Tip = "正在请求下载资源..."; PlayProcess = true; UpVisibility = Visibility.Collapsed; }
public async Task GetPageAsString_WithErrorException_ReturnsEmptyString() { //Arrange var httpClientFactoryMock = FakeHttpClientFactory.GetHttpClientFactoryWithExceptionMock(); var httpDownload = new HttpDownload(httpClientFactoryMock.Object); //Act var pageContent = httpDownload.DownloadPage(_url); await pageContent; //Assert Assert.True(string.IsNullOrWhiteSpace(pageContent.Result)); }
private void InitialDownloadEvents(HttpDownload downloadInfo) { var taskInfo = DownloadTaskList.FirstOrDefault(item => item.FilePath.FullPath == downloadInfo.DownloadPath); if (taskInfo != null) { downloadInfo.DownloadProgressChangedEvent += taskInfo.OnDownloadProgressChanged; downloadInfo.DownloadStateChangedEvent += taskInfo.OnDownloadStateChanged; } downloadInfo.DownloadProgressChangedEvent += OnDownloadProgressChanged; downloadInfo.DownloadStateChangedEvent += OnDownloadStateChanged; }
/*------------------------------------------------------------------------- * 최신버전チェック * ---------------------------------------------------------------------------*/ private void button4_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; // 버전を확인する bool result = HttpDownload.Download(def.VERSION_URL, def.VERSION_FNAME); Cursor = Cursors.Default; if (!result) { // 업데이트しない MessageBox.Show(this, "업데이트정보が取得できませんでした. \nインターネットの연결を확인してください. ", "업데이트확인오류", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // 업데이트された데이터があるかどうか확인する string line = ""; List <string> data = new List <string>(); int version = 0; try { using (StreamReader sr = new StreamReader( def.VERSION_FNAME, Encoding.GetEncoding("UTF-8"))) { // 버전 line = sr.ReadLine(); version = Convert.ToInt32(line); // 残り while ((line = sr.ReadLine()) != null) { data.Add(line); } } } catch { MessageBox.Show(this, "버전정보が확인できません. \n업데이트확인に실패하였습니다. ", "업데이트확인오류", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (version > def.VERSION) { // 업데이트されている check_update_result dlg = new check_update_result(data.ToArray()); dlg.ShowDialog(this); dlg.Dispose(); } else { // 업데이트されていない MessageBox.Show(this, "업데이트されたソフトウェアは見つかりませんでした. \nお使いの버전が최신です. ", "업데이트확인결과", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
/*------------------------------------------------------------------------- * 最新バージョンチェック * ---------------------------------------------------------------------------*/ private void button4_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; // バージョンを確認する bool result = HttpDownload.Download(def.VERSION_URL, def.VERSION_FNAME); Cursor = Cursors.Default; if (!result) { // 更新しない MessageBox.Show(this, "更新情報が取得できませんでした。\nインターネットの接続を確認してください。", "更新確認エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // 更新されたデータがあるかどうか確認する string line = ""; List <string> data = new List <string>(); int version = 0; try{ using (StreamReader sr = new StreamReader( def.VERSION_FNAME, Encoding.GetEncoding("Shift_JIS"))){ // バージョン line = sr.ReadLine(); version = Convert.ToInt32(line); // 残り while ((line = sr.ReadLine()) != null) { data.Add(line); } } }catch { MessageBox.Show(this, "バージョン情報が確認できません。\n更新確認に失敗しました。", "更新確認エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (version > def.VERSION) { // 更新されている check_update_result dlg = new check_update_result(data.ToArray()); dlg.ShowDialog(this); dlg.Dispose(); } else { // 更新されていない MessageBox.Show(this, "更新されたソフトウェアは見つかりませんでした。\nお使いのバージョンが最新です。", "更新確認結果", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
private void service_GetLatestVersionCompleted(object sender, ConnectUO.Framework.Web.GetLatestVersionCompletedEventArgs e) { if (e.Cancelled) { return; } Invoke((MethodInvoker) delegate { if (e.Error != null) { Program.Status = UpdateStatus.Failure; txtChangeLog.Text = string.Format("The following error occured while trying to get the lastest ConnectUO version information: \n {0}", e.Error.Message); Complete(); return; } string url = e.Result.Tables[0].Rows[0].Field <string>("UpdateUrl"); string changeLog = e.Result.Tables[0].Rows[0].Field <string>("ChangeLog"); txtChangeLog.Text = changeLog; txtChangeLog.Focus(); txtChangeLog.Select(0, 0); FileSystemHelper.EnsureDirectoryExists(_destinationDirectory); DirectoryInfo dir = new DirectoryInfo(_destinationDirectory); FileInfo[] files = dir.GetFiles(); for (int i = 0; i < files.Length; i++) { Tracer.Verbose("Removing old file {0}", files[i].Name); try { files[i].Delete(); } catch { } } _update = HttpDownload.CreateDownload(url, _destinationFile); _update.ProgressStarted += new EventHandler <ProgressStartedEventArgs>(update_ProgressStarted); _update.ProgressUpdate += new EventHandler <ProgressUpdateEventArgs>(update_ProgressUpdate); _update.ProgressCompleted += new EventHandler <ProgressCompletedEventArgs>(update_ProgressCompleted); _update.Begin(); }); }
private void UpdateDownLoadList_Timer_Tick(object sender, EventArgs e) { DownloadListView.BeginUpdate(); //DownloadListView.Items.Clear(); for (int i = 0; i < DownloadList.Count; i++) { HttpDownload download = (HttpDownload)DownloadList[i]; DownloadListView.Items[i].SubItems[2].Text = (getSizeMB((long)download.getSpeed()) < 1 ? (download.getSpeed() / 1024) + "K/s" : getSizeMB((long)download.getSpeed()) + "M/s"); DownloadListView.Items[i].SubItems[3].Text = download.getDownloadPercentage() + "%"; DownloadListView.Items[i].SubItems[4].Text = download.Stop?"已终止":download.Paste?"暂停中":(download.DownloadComplete() ? "下载完成" : "下载中"); } DownloadListView.EndUpdate(); return; }
/// <summary> /// 创建下载任务 /// </summary> /// <param name="DownLoadUrl">下载链接</param> /// <param name="DownLoadPath">下载路径</param> /// <param name="FileName">保存文件名</param> /// <param name="ThreadNum">下载线程数</param> /// <returns></returns> public HttpDownload CreateDownloadTask(string DownLoadUrl, string DownLoadPath, string FileName, int ThreadNum) { int id = Tasks.Count; HttpTask task = new HttpDownload { ID = id, DownLoadUrl = DownLoadUrl, FilePath = DownLoadPath, FileName = FileName, ThreadNum = ThreadNum, }; Tasks.Add(id, task); return((HttpDownload)task); }
private IEnumerator DownloadUpdate(string filePath) { DownloadPopup.Instance.message.text = "Fazendo o download da nova versão. Por favor, aguarde..."; DownloadPopup.Instance.ShowPopup(true); DownloadPopup.Instance.buttom.onClick.AddListener(CancelDownload); //Get changelog from server string fileName = Path.GetFileName(filePath); fileName = IndexedFilename(Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName)); client = null; //Check the type of the selected client if (clientType == ClientType.FtpClient) { client = FtpDownload.CreateNewInstance(); } else if (clientType == ClientType.HttpClient) { client = HttpDownload.CreateNewInstance(); } //Starts the Download process client.SetCredentials(username, password); client.Download(serverPath + "/" + filePath, FilesPath + fileName); while (!client.Done && !client.Failed) { DownloadPopup.Instance.SetProgress(client.Progress); yield return(null); } if (client.Failed) { DownloadPopup.Instance.message.text = "O download falhou. Tente novamente mais tarde ou contate o suporte. Erro:" + client.ErrorMessage; DownloadPopup.Instance.buttonText.text = "Fechar"; } else { DownloadPopup.Instance.ShowPopup(false); ChangelogPopup.Instance.Message = "O arquivo " + fileName + " foi salvo em 'Downlaods'. Pressione 'Ok' para executar a intalação ou 'Fechar' para instalar posteriormente"; ChangelogPopup.Instance.FirstButtonText = "Ok"; ChangelogPopup.Instance.SecondButtonText = "Fechar"; AddToAndroidDownloads(fileName); ChangelogPopup.Instance.ShowPopup(true); ChangelogPopup.Instance.FirstButtom.onClick.AddListener(() => { RunFile(fileName); CancelDownload(); ChangelogPopup.Instance.ShowPopup(false); }); ChangelogPopup.Instance.SecondButtom.onClick.AddListener(() => { CancelDownload(); ChangelogPopup.Instance.ShowPopup(false); }); } }
static void Main(string[] args) { System.Net.ServicePointManager.DefaultConnectionLimit = 99999; Console.WriteLine("测试下载程序"); Console.WriteLine("下载文件为: " + Url); Console.WriteLine("下载目录为: " + Path); var t = new HttpDownload { Url = Url, DownloadPath = Path, ThreadNum = 120 }; t.Start(); Thread.Sleep(9999999); }
public void DoUpdate(UpdateMgr UpdateManager) { CloseLauncher(); var res = UpdateManager.GetUpdateResult(); var fn = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), UpdatePath); cancleSource = new CancellationTokenSource(); UpdateCount = res.Count; UpdateNow = 0; if (!Directory.Exists(fn)) { Directory.CreateDirectory(fn); } UpdateTask = Task.Factory.StartNew(() => { SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Application.Current.Dispatcher)); foreach (var file in res) { if (cancleSource.IsCancellationRequested) { break; } var url = UpdateManager.GetDownloadUrl(file.Name); HttpDownload.HttpDownloadFile(url, fn + file.Name + ".cozy_update"); SynchronizationContext.Current.Send(x => { FileInfoList.Add(file.Name); UpdateNow++; }, null); } MoveFile(); OkEnable = true; CancleEnable = false; }, cancleSource.Token); CancleEnable = true; OkEnable = false; }
/// <summary> /// 创建一个下载任务 /// </summary> /// <param name="DownloadUrl"></param> /// <param name="DownloadPath"></param> /// <param name="ThreadNum"></param> public void CreateDownloadTask(string DownloadUrl, string DownloadPath) { if (File.Exists(DownloadPath)) { return; } var Task = new HttpDownload { ID = TaskList.Count, Url = DownloadUrl, DownloadPath = DownloadPath, ThreadNum = Program.config.NetSpeed }; Task.CreateDataFile(); Program.config.SetDownloadInfo(DownloadPath + ".dcj", false); TaskList.Add(TaskList.Count, Task); }
private void btnSync_Click(object sender, EventArgs e) { this.btnSync.Enabled = false; if (MsgBox.Confirm("确定要同步图片到本地文件夹?")) { try { string path = Dialog.GetFolder(); if (!string.IsNullOrEmpty(path)) { IList <FateUserInfo> users = FateUserInfoManager.GetUserList(); if (users != null && users.Count > 0) { int total = users.Count; this.progressSync.Maximum = total; this.progressSync.Value = 0; for (int i = 0; i < users.Count; i++) { FateUserInfo user = users[i]; string fileUrl = user.HeadFileName; string ext = Path.GetExtension(fileUrl); string newFileName = user.UserCode + ext; string saveFileName = Path.Combine(path, newFileName); if (!File.Exists(saveFileName)) { HttpDownload download = new HttpDownload(fileUrl, saveFileName); download.Download(); this.progressSync.Value++; Application.DoEvents(); } } MsgBox.Alert("同步完成"); } } } catch (Exception ex) { MsgBox.Alert("同步失败,错误信息:" + ex.Message); } } this.btnSync.Enabled = true; }
/// <summary> /// 创建一个下载任务 /// </summary> /// <param name="DownloadUrl"></param> /// <param name="DownloadPath"></param> /// <param name="ThreadNum"></param> public void CreateDownloadTask(string DownloadUrl, string DownloadPath, CookiesData Cookies = null, int ThreadNum = 0) { if (File.Exists(DownloadPath)) { return; } Flag = true; var Task = new HttpDownload { ID = TaskList.Count, Url = DownloadUrl, DownloadPath = DownloadPath, ThreadNum = ThreadNum == 0?Program.config.NetSpeed:ThreadNum, Cookies = Cookies }; Task.CreateDataFile(); Program.config.SetDownloadInfo(DownloadPath + ".dcj", false); TaskList.Add(TaskList.Count, Task); Flag = false; }
public void AddDownloadFile(FileInfo info, string DownloadPath, string FileName) { HttpDownload download = new HttpDownload { DownLoadUrl = string.Format("https://www.baidupcs.com/rest/2.0/pcs/stream?method=download&access_token={0}&path={1}", Program.config.Access_Token, info.path), DownLoadPath = DownloadPath, FileName = FileName, ThreadNum = 8 }; DownloadList.Add(download); download.Start(); ListViewItem item = new ListViewItem(); item.Text = download.FileName; item.SubItems.Add(download.DownLoadPath); item.SubItems.Add((getSizeMB((long)download.getSpeed()) < 1 ? (download.getSpeed() / 1024) + "K/s" : getSizeMB((long)download.getSpeed()) + "M/s")); item.SubItems.Add(download.getDownloadPercentage() + "%"); item.SubItems.Add((download.DownloadComplete() ? "下载完成" : "下载中")); DownloadListView.Items.Add(item); DownloadTaskInfo.Add(download.FileName, download); }
private void _Start() { Process[] localByName = Process.GetProcessesByName(_killExeName); if (localByName.Length > 0) { _startExePath = localByName[0].MainModule.FileName; Console.WriteLine("杀掉进程的路径:" + _startExePath); Mydebug.MyDEBUG("杀掉进程的路径:" + _startExePath); } else { Console.WriteLine("未找到杀掉进程的路径:"); Mydebug.MyDEBUG("杀掉进程的路径:" + _startExePath); } KillExe.KillExeByCMD(_killExeName + ".exe"); //int pr = ScreenTool.GetCurrentWindowHandle(); //ScreenTool.MaxScreen(); //Console.WriteLine(pr); if (!_startSucess) { return; } if (!_isdownloading) { _isdownloading = true; } else { return; } _UIInit(); if (Directory.Exists(_rootPath)) { try { Console.WriteLine("开始删除"); Mydebug.MyDEBUG("开始删除上次缓存"); FileSystemInfo[] fileinfo = new DirectoryInfo(_rootPath).GetFileSystemInfos(); foreach (FileSystemInfo i in fileinfo) { if (i is DirectoryInfo) { DirectoryInfo info = new DirectoryInfo(i.FullName); info.Delete(true); } else { FileInfo info = new FileInfo(i.FullName); if (info.IsReadOnly) { info.IsReadOnly = false; } File.Delete(i.FullName); } } Mydebug.MyDEBUG("删除上次缓存完毕"); } catch (Exception ex) { KillExe.KillExeByCMD("explorer.exe"); Directory.Delete(_rootPath, true); Directory.CreateDirectory(_rootPath); KillExe.StartExeByCMD("explorer.exe"); } } else { Directory.CreateDirectory(_rootPath); } if (_isOSS) { //if (_downLoadOSS == null) //{ // _downLoadOSS = new DownLoadOSS(); // _downLoadOSS.rootPath = _downloadPath; // _downLoadOSS.ProgrecessEvent += _UpdateUIAsy; //} //_downLoadOSS.EventCompelete += _SaveComPelete; //_downLoadOSS.DownloadZip(_ossPath); } else { if (_httpDownload == null) { _httpDownload = new HttpDownload(); _httpDownload.rootPath = _downloadPath; _httpDownload.ProgrecessEvent += _UpdateUIAsy; } _httpDownload.EventCompelete += _SaveComPelete; _httpDownload.DownloadFile(_ossPath); } }
private IEnumerator CheckUpdates() { DownloadPopup.Instance.message.text = "Checando atualizações, Por favor, aguarde..."; DownloadPopup.Instance.ShowPopup(true); DownloadPopup.Instance.buttom.onClick.AddListener(CancelDownload); //Check the type of the selected client client = null; if (clientType == ClientType.FtpClient) { client = FtpDownload.CreateNewInstance(); } else if (clientType == ClientType.HttpClient) { client = HttpDownload.CreateNewInstance(); } //Starts the download process client.SetCredentials(username, password); client.Download(serverPath + "/" + changelogFileName, ""); while (!client.Done && !client.Failed) { DownloadPopup.Instance.SetProgress(client.Progress); yield return(null); } //Verify if the file download succeed if (client.Failed) { DownloadPopup.Instance.message.text = "Falha ao verificar atualizações. Tente novamente mais tarde ou contate o suporte. Erro: " + client.ErrorMessage; DownloadPopup.Instance.buttonText.text = "Fechar"; } else { DownloadPopup.Instance.ShowPopup(false); } //Each line on the file represent a new version and contains the information of the updates string str = System.Text.Encoding.UTF8.GetString(FtpDownload.Instance.Bytes); //Parse the first line which must contains the headers and the last line, which is the last version logsHistory = new List <string>(System.Text.RegularExpressions.Regex.Split(str, "\r\n|\r|\n")); string[] headers = null; string[] infos = null; if (logsHistory.Count > 0) { headers = logsHistory[0].Split(':'); infos = logsHistory[logsHistory.Count - 1].Split(':'); for (int i = 0; i < headers.Length && i < infos.Length; i++) { changes.Add(headers[i], infos[i]); } } string version; //Compare if the last version from the file is higher than the current running if (changes.TryGetValue("versao", out version) && version.CompareTo(currentVersion) == 1) { string fileName; changes.TryGetValue(headers[0], out fileName); string message = FileExists(FilesPath + fileName)? "Um arquivo referente à atualização detectada já existe. Gostaria de fazer o download novamente?\n": "Uma nova versão foi detectada. Gostaria de iniciar o download?\n"; ChangelogPopup.Instance.Message = message + "\nVersão disponível: " + changes["versao"] + "\n" + "\nData: " + changes["data"] + "\n" + "\nMudanças detectadas:\n"; string[] updates = changes["updates"].Split(','); foreach (string s in updates) { ChangelogPopup.Instance.Message += "- " + s + "\n"; } int response = 0; ChangelogPopup.Instance.FirstButtonText = "Sim"; ChangelogPopup.Instance.SecondButtonText = "Não"; ChangelogPopup.Instance.FirstButtom.onClick.AddListener(() => { response = 1; }); ChangelogPopup.Instance.SecondButtom.onClick.AddListener(() => { response = 2; }); ChangelogPopup.Instance.ShowPopup(true); //Wait until the user choose an option yield return(new WaitUntil(() => response != 0)); ChangelogPopup.Instance.ShowPopup(false); if (response == 1) { StartCoroutine(DownloadUpdate(fileName)); } //Ask if the user wnats to execute the file, if it already exists and he choose to not download again else if (FileExists(FilesPath + fileName)) { ChangelogPopup.Instance.Message = "Gostaria de executar o arquivo encontrado?"; ChangelogPopup.Instance.FirstButtonText = "Sim"; ChangelogPopup.Instance.SecondButtonText = "Não"; ChangelogPopup.Instance.FirstButtom.onClick.AddListener(() => { RunFile(fileName); ChangelogPopup.Instance.ShowPopup(false); onFinished.Invoke(); }); ChangelogPopup.Instance.SecondButtom.onClick.AddListener(() => { ChangelogPopup.Instance.ShowPopup(false); onFinished.Invoke(); }); ChangelogPopup.Instance.ShowPopup(true); } else { onFinished.Invoke(); } } else { onFinished.Invoke(); } }
private async Task NextSync(TimeSpan timeout, CancellationToken cancellationToken) { Trace.TraceInformation("NextSync started."); try { Trace.TraceInformation($"Before provider."); using (var provider = new TemperatureProvider()) { var lastDateTime = await provider.GetLastTemperatureDate(); DateTime requestDateTime; if (lastDateTime.HasValue) { requestDateTime = lastDateTime.Value; Trace.TraceInformation($"Last date in database is {lastDateTime}. "); } else { requestDateTime = _defaultDateTime; Trace.TraceInformation($"Last date in database is absent. Use default datetime {_defaultDateTime}"); } requestDateTime = requestDateTime.AddMinutes(1); var httpDownload = new HttpDownload(_httpUrl); Trace.TraceInformation($"Send request with date {requestDateTime}. "); httpDownload.SendRequest(requestDateTime); httpDownload.GetResponse(); if (httpDownload.IsPagePresent()) { var device = httpDownload.DownloadTemperature(); Trace.TraceInformation($"Device name {device.Name}. Found {device.Temperatures.Count()} temperatures information. "); if (device.Temperatures.Any()) { Trace.TraceInformation($"Start add {device.Temperatures.Count()} items temperatures information to database. "); var deviceId = await provider.AddDeviceIfNotExist(device); Task task = provider.AddTemperatures(deviceId, device.Temperatures); } } else { Trace.TraceWarning($"Response without StatusCode - OK"); } await Task.Delay(timeout, cancellationToken); } } catch (OperationCanceledException) { return; } catch (HttpRequestException ex) { if ((timeout += timeout) > _maxTimeout) { Trace.TraceError($"Communication error, but maximum timeout was reached. Sync will be terminated. {ex}"); Environment.Exit(1); } else { Trace.TraceWarning($"Communication error. Timeout increased to {timeout}. {ex}"); Trace.TraceInformation("Timeout " + timeout); await Task.Delay(timeout, cancellationToken); } } finally { Trace.TraceWarning("Before NextSync"); await NextSync(timeout, cancellationToken); } }
public void _OnStartDownload() { Button dlButton = GetNode <Button>("Button"); HttpDownload.Download(dlButton); }