protected async Task WebClient(PhotonServerDefinition server, Func <WebClient, Task> clientTask) { var client = WebClientFactory.Create(server, Username, Password); try { await clientTask(client); } catch (WebException error) { if (error.Response is HttpWebResponse httpResponse) { if (httpResponse.StatusCode == HttpStatusCode.NotFound) { throw new ApplicationException($"Photon-Server instance '{server.Name}' not found!"); } if (httpResponse.StatusCode == HttpStatusCode.Unauthorized) { throw new HttpUnauthorizedException(); } } throw; } finally { client.Dispose(); } }
public override Task <WebClientResponseMessage> GetAsync(WebClientRequestMessage request, ClientSetting clientSetting, CancellationToken cancellationToken) { var client = WebClientFactory.Create(new Settings() { TimeOut = (int)clientSetting.TimeOut.TotalMilliseconds }); return(client.GetAsync(request, cancellationToken)); }
private Result <IEnumerable <S> > GetResponse <TResponse, S>(string url) where TResponse : IWebResponse <S> { WebClient client; string rawResponse; try { client = WebClientFactory.Create(); rawResponse = client.DownloadString(url); } catch (WebException) { return(Result <IEnumerable <S> > .Fail("Network Failure")); } TResponse response = JsonConvert.DeserializeObject <TResponse>(rawResponse); return(Result <IEnumerable <S> > .Ok(response.Data.ToList())); }
protected async Task <T> WebClient <T>(PhotonServerDefinition server, Func <WebClient, Task <T> > clientTask) { var client = WebClientFactory.Create(server, Username, Password); try { return(await clientTask(client)); } catch (WebException error) { if (error.Response is HttpWebResponse httpResponse) { if (httpResponse.StatusCode == HttpStatusCode.NotFound) { throw new ApplicationException($"Photon-Server instance '{server.Name}' not found!"); } if (httpResponse.StatusCode == HttpStatusCode.Unauthorized) { throw new HttpUnauthorizedException(); } if (httpResponse.StatusCode == HttpStatusCode.BadRequest) { string text = null; try { using (var stream = httpResponse.GetResponseStream()) using (var reader = new StreamReader(stream)) { text = await reader.ReadToEndAsync(); } } catch {} throw new ApplicationException($"Bad Request! {text}"); } } throw; } finally { client.Dispose(); } }
/// <summary> /// Проверить наличие обновлений на сервере. /// </summary> /// <returns></returns> public Task <bool> CheckUpdateAsync() { return(Task.Factory.StartNew(() => { //Уведомляем подписчиков, что проверка наличия новой версии запущена. OnUpdateStateChanged(UpdateState.Checking); string localPidFile = _localPidFile; string localPidHash = null; if (File.Exists(localPidFile)) //если локальный файл с хэшем версии обновления найден { localPidHash = Pid.FromTextFile(localPidFile).Hash; } WebClient web = _webClientFactory.Create(); string pidText = web.DownloadString(_serverPidFile); Pid downloadedPid = Pid.FromString(pidText); if (localPidHash == null) { Pid newLocalPid = Pid.FromVersionNumber(-1); localPidHash = newLocalPid.Hash; using (StreamWriter writer = File.CreateText(localPidFile)) { writer.Write(newLocalPid.ToString()); } } OnUpdateStateChanged(UpdateState.None); if (downloadedPid.Hash != localPidHash) { _pidFromServer = downloadedPid; return true; } //Уведомляем подписчиков, что обновление не требуется. OnUpdateStateChanged(UpdateState.NotNeeded); OnUpdateStateChanged(UpdateState.None); return false; })); }
/// <summary> /// Инициализирует экземпляр класса. /// </summary> /// <param name="rootDirectory">Корневая папка, в которой происходят обновления</param> /// <param name="serverPidFile">Адрес pid файла на сервере</param> /// <param name="localPidFile">Путь к локальному Pid файлу</param> /// <param name="serverPatchListFile">Адрес файла c описанием файлов для обновления на сервере</param> /// <param name="serverFilesRoot">Корневая папка на сервере, в которой лежат файлы для обновления</param> public WowUpdater(string rootDirectory, string serverPidFile, string localPidFile, string serverPatchListFile, string serverFilesRoot) { if (!Directory.Exists(rootDirectory)) { throw new DirectoryNotFoundException("rootDirectory"); } _rootDirectory = rootDirectory; _serverPidFile = serverPidFile; _localPidFile = localPidFile; _serverPatchListFile = serverPatchListFile; _serverFilesRoot = serverFilesRoot; _syncContext = SynchronizationContext.Current ?? new SynchronizationContext(); _webClientFactory = new WebClientFactory(); _webClient = _webClientFactory.Create(); _currentState = UpdateState.None; TempFolder = Path.Combine(Path.GetTempPath(), Wow.FolderName.TEMP_FOLDER_NAME); }
private async Task Reconnect(PhotonServerDefinition server, string latestVersion, TimeSpan timeout) { using (var tokenSource = new CancellationTokenSource(timeout)) using (var webClient = WebClientFactory.Create(server, Username, Password)) { var token = tokenSource.Token; while (true) { token.ThrowIfCancellationRequested(); try { var version = await webClient.DownloadStringTaskAsync("api/version"); if (!VersionTools.HasUpdates(version, latestVersion)) { break; } } catch (Exception error) when(error is SocketException || error is WebException) { await Task.Delay(1000, tokenSource.Token); } } } }
public void Initialize() { Task.Factory.StartNew(() => { bool availiable = CheckConnectionToServerInternal(_mySqlConfig.Ip, _mySqlConfig.Port); if (!availiable) { OnDataLoadingStateChanged(LauncherState.ConnectionFailed); return; } //Уведомляем подписчиков, что инициализация запущена OnDataLoadingStateChanged(LauncherState.InitializationStarted); Task[] tasks = { //Загрузка экспресс новостей new Task(() => { OnNewsLoadBanner(LoadingState.Started); WebClient web = _webClientFactory.Create(); QueryResult <string> queryResult; try { string bannerNews = web.DownloadString(_addressSet.LoadBannerNews); queryResult = new QueryResult <string>(bannerNews != "note", bannerNews); } catch (Exception) { queryResult = new QueryResult <string>(false, null); } OnNewsLoadBanner(LoadingState.Completed, queryResult); }), //Загрузка статистики игроков new Task(() => { OnStatOnline(LoadingState.Started); WebClient web = _webClientFactory.Create(); QueryResult <string> queryResult; try { string updateStatsOnline = web.DownloadString(_addressSet.LoadStatOnline); queryResult = new QueryResult <string>(updateStatsOnline != "note", updateStatsOnline); } catch (Exception) { queryResult = new QueryResult <string>(false, null); } OnStatOnline(LoadingState.Completed, queryResult); }), //Загрузка статистики игроков //Загрузка информации о персонаже new Task(() => { OnShowPlayerInfo(LoadingState.Started); WebClient web = _webClientFactory.Create(); QueryResult <string> queryResult; try { string showPlayerInfo = web.DownloadString(_addressSet.ShowPlayerInfo); queryResult = new QueryResult <string>(showPlayerInfo != "note", showPlayerInfo); } catch (Exception) { queryResult = new QueryResult <string>(false, null); } OnShowPlayerInfo(LoadingState.Completed, queryResult); }), //Загрузка информации о персонаже //Загрузка информации о вещах чара new Task(() => { OnPlayerImage(LoadingState.Started); WebClient web = _webClientFactory.Create(); QueryResult <string> queryResult; try { string playerImage = web.DownloadString(_addressSet.PlayerImage); queryResult = new QueryResult <string>(playerImage != "note", playerImage); } catch (Exception) { queryResult = new QueryResult <string>(false, null); } OnPlayerImage(LoadingState.Completed, queryResult); }), //Загрузка информации о вещах чара //Загрузка горячих новостей new Task(() => { OnNewsLoadStateChanged(LoadingState.Started); WebClient web = _webClientFactory.Create(); QueryResult <string> queryResult; try { string hotNews = web.DownloadString(_addressSet.HotNews); queryResult = new QueryResult <string>(hotNews != "note", hotNews); } catch (Exception) { queryResult = new QueryResult <string>(false, null); } OnNewsLoadStateChanged(LoadingState.Completed, queryResult); }), }; //Запускаем выполнение всех задач Array.ForEach(tasks, (task) => { task.Start(); }); //Ожидаем останавливая выполнение текущего потока, пока не выполнятся все задачи Task.WaitAll(tasks); //Уведомляем подписчиков, что все операции выполнены OnDataLoadingStateChanged(LauncherState.InitializationCompleted); }); }