public static void DownloadFile(string webFile, string localFile, PlatformTask action) { try { var task2 = new PlatformTask(() => { }); task2.OnStartFinish += new AsyncCallback((result0) => { byte[] bytes = task2.ParamArrayResultBytes; if (bytes != null && bytes.Length > 0) { var task = new PlatformTask(() => { if (action != null) { action.Start(); } }); Platform.Current.SaveUserFile(localFile, bytes, task); } else { WebTools.TakeWarnMsg("用户文件下载失败:" + localFile, "DownloadFile:" + webFile, new Exception("文件空或长度为0")); } }); Platform.Current.DownloadWebData(WebSite + (webFile.StartsWith("/") ? "" : "/") + webFile, task2); } catch (Exception ex) { WebTools.TakeWarnMsg("用户文件下载失败:" + localFile, "DownloadFile:" + webFile, ex); } }
/// <summary> /// Gets operation result for PUT and PATCH operations. /// </summary> /// <typeparam name="T">Type of the resource</typeparam> /// <param name="client">IAzureClient</param> /// <param name="response">Response from the begin operation</param> /// <param name="customHeaders">Headers that will be added to request</param> /// <param name="cancellationToken">Cancellation token</param> /// <returns>Response with created resource</returns> public static async Task <AzureOperationResponse <T> > GetPutOrPatchOperationResultAsync <T>( this IAzureClient client, AzureOperationResponse <T> response, Dictionary <string, List <string> > customHeaders, CancellationToken cancellationToken) where T : class { if (response == null) { throw new ValidationException(ValidationRules.CannotBeNull, "response"); } if (response.Response.StatusCode != HttpStatusCode.OK && response.Response.StatusCode != HttpStatusCode.Accepted && response.Response.StatusCode != HttpStatusCode.Created) { throw new CloudException(string.Format(Resources.UnexpectedPollingStatus, response.Response.StatusCode)); } var pollingState = new PollingState <T>(response, client.LongRunningOperationRetryTimeout); Uri getOperationUrl = response.Request.RequestUri; // Check provisioning state while (!AzureAsyncOperation.TerminalStatuses.Any(s => s.Equals(pollingState.Status, StringComparison.OrdinalIgnoreCase))) { await PlatformTask.Delay(pollingState.DelayInMilliseconds, cancellationToken).ConfigureAwait(false); if (!string.IsNullOrEmpty(pollingState.AzureAsyncOperationHeaderLink)) { await UpdateStateFromAzureAsyncOperationHeader(client, pollingState, customHeaders, cancellationToken); } else if (!string.IsNullOrEmpty(pollingState.LocationHeaderLink)) { await UpdateStateFromLocationHeaderOnPut(client, pollingState, customHeaders, cancellationToken); } else { await UpdateStateFromGetResourceOperation(client, pollingState, getOperationUrl, customHeaders, cancellationToken); } } if (AzureAsyncOperation.SuccessStatus.Equals(pollingState.Status, StringComparison.OrdinalIgnoreCase) && pollingState.Resource == null) { await UpdateStateFromGetResourceOperation(client, pollingState, getOperationUrl, customHeaders, cancellationToken); } // Check if operation failed if (AzureAsyncOperation.FailedStatuses.Any( s => s.Equals(pollingState.Status, StringComparison.OrdinalIgnoreCase))) { throw pollingState.CloudException; } return(pollingState.AzureOperationResponse); }
public virtual TResult ExecuteAction <TResult>(Func <TResult> func) { Guard.ArgumentNotNull(func, "func"); int retryCount = 0; TimeSpan delay = TimeSpan.Zero; Exception lastError; var shouldRetry = this.RetryStrategy.GetShouldRetryHandler(); for (;;) { lastError = null; try { return(func()); } catch (Exception ex) { lastError = ex; if (!(this.ErrorDetectionStrategy.IsTransient(lastError))) { throw; } RetryCondition condition = shouldRetry(retryCount++, lastError); if (!condition.RetryAllowed) { throw; } delay = condition.DelayBeforeRetry; } // Perform an extra check in the delay interval. Should prevent from accidentally ending up with the // value of -1 that will block a thread indefinitely. In addition, any other negative numbers will // cause an ArgumentOutOfRangeException fault that will be thrown by Thread.Sleep. if (delay.TotalMilliseconds < 0) { delay = TimeSpan.Zero; } this.OnRetrying(retryCount, lastError, delay); if (retryCount > 1 || !this.RetryStrategy.FastFirstRetry) { PlatformTask.Delay(delay).Wait(); } } }
private Task <TResult> ExecuteAsyncContinueWith(Task <TResult> runningTask) { if (!runningTask.IsFaulted || this._cancellationToken.IsCancellationRequested) { return(runningTask); } TimeSpan delay = TimeSpan.Zero; Exception lastError = runningTask.Exception.InnerException; if (!(this._isTransient(lastError))) { // if not transient, return the faulted running task. return(runningTask); } RetryCondition condition = this._shouldRetryHandler(this._retryCount++, lastError); if (!condition.RetryAllowed) { return(runningTask); } delay = condition.DelayBeforeRetry; // Perform an extra check in the delay interval. if (delay < TimeSpan.Zero) { delay = TimeSpan.Zero; } this._onRetrying(this._retryCount, lastError, delay); this._previousTask = runningTask; if (delay > TimeSpan.Zero && (this._retryCount > 1 || !this._fastFirstRetry)) { return(PlatformTask.Delay(delay) .ContinueWith <Task <TResult> >(this.ExecuteAsyncImpl, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .Unwrap()); } return(this.ExecuteAsyncImpl(null)); }
protected override void Draw(GameTime gameTime) { //第五步 if (Platform.PlatFormType == PlatFormType.Win || Platform.PlatFormType == PlatFormType.UWP || Platform.PlatFormType == PlatFormType.Android || Platform.PlatFormType == PlatFormType.Desktop) { if (takePicture == true) { try { if (screenshot == null || screenshot.GraphicsDevice == null) { screenshot = new RenderTarget2D(Platform.GraphicsDevice, Platform.GraphicsDevice.Viewport.Width, Platform.GraphicsDevice.Viewport.Height, false, SurfaceFormat.Color, DepthFormat.None); } Platform.GraphicsDevice.SetRenderTarget(screenshot); } #pragma warning disable CS0168 // The variable 'ex' is declared but never used catch (Exception ex) #pragma warning restore CS0168 // The variable 'ex' is declared but never used { //Log... } //takePicture = false; } } var spriteMode = mainGameScreen == null ? SpriteSortMode.Deferred : SpriteSortMode.BackToFront; if (disScale) //Platform.PlatFormType == PlatForm.iOS && isRetina) { if (mainGameScreen == null || loadingScreen != null) { SpriteBatch.Begin(spriteMode, BlendState.AlphaBlend, null, null, null, null, SpriteScale1); } else { SpriteBatch.Begin(spriteMode, BlendState.AlphaBlend, null, null, null, null, SpriteScale2); } } else { SpriteBatch.Begin(spriteMode, BlendState.AlphaBlend); } Platform.GraphicsDevice.Clear(Color.TransparentBlack); //this.graphics.GraphicsDevice.Clear(Color.TransparentBlack); if (loadingScreen == null) { if (mainGameScreen == null) { if (mainMenuScreen == null) { } else { mainMenuScreen.Draw(gameTime); } } else { if (isDebug) { mainGameScreen.Draw(gameTime); } else { if (String.IsNullOrEmpty(err)) { try { mainGameScreen.Draw(gameTime); } catch (Exception ex) { err = "不好意思,游戏运行出错,点击将返回主菜单,请考虑读取自动存档。\r\n" + ex.Message; WebTools.TakeWarnMsg("mainGameScreen.Draw", "", ex); } } else { if (!String.IsNullOrEmpty(err)) { CacheManager.DrawString(Session.Current.Font, err.SplitLineString(100), errPos, Color.Red, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f); } if (InputManager.IsPressed) { err = ""; //保存當前進度 mainGameScreen.SaveGameAutoPosition(); loadingScreen = new LoadingScreen(); loadingScreen.LoadScreenEvent += (sender0, e0) => { Platform.Sleep(1000); }; } } } } } else { loadingScreen.Draw(gameTime); } //view = Platform.Current.MemoryUsage; //if (!String.IsNullOrEmpty(view)) //{ // CacheManager.DrawString(Session.Current.Font, "view:" + view.SplitLineString(100), errPos, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f); //} //if (!String.IsNullOrEmpty(warn) && lastWarnTime != null && (DateTime.Now - (DateTime)lastWarnTime).TotalSeconds < 20) //{ // CacheManager.DrawString(Session.Current.Font, "Warn:" + warn, errPos, Color.Red, 0f, Vector2.Zero, 0.8f, SpriteEffects.None, 1f); //} ////if (!String.IsNullOrEmpty(err)) ////{ ////CacheManager.DrawString(LightAncient, "Err:" + err.SplitLineString(100).ProcessStar(), errPos, Color.Red, 0f, Vector2.Zero, 0.5f, SpriteEffects.None, 1f); ////} if (renderLast != null) { SpriteBatch.Draw(renderLast, Vector2.Zero, Color.White); } SpriteBatch.End(); if (takePicture == true && String.IsNullOrEmpty(err)) { takePicture = false; try { if (Platform.PlatFormType == PlatFormType.Win || Platform.PlatFormType == PlatFormType.UWP || Platform.PlatFormType == PlatFormType.Android || Platform.PlatFormType == PlatFormType.Desktop) // || Platform.PlatFormType == PlatForm.iOS) { if (screenshot != null) { byte[] shot = Platform.Current.ScreenShot(Platform.GraphicsDevice, screenshot); //Season.GraphicsDevice.SetRenderTarget(null); if (shot != null && shot.Length > 0) { var task = new PlatformTask(() => { }); task.OnStartFinish += (result) => { if (task.ParamArrayResultBytes != null && task.ParamArrayResultBytes.Length > 0) { Platform.Current.SaveUserFile(picture, task.ParamArrayResultBytes, null); } }; Platform.Current.ResizeImageFile(shot, 800, 480, false, task); } } //Task.Run(async () => await Season.Current.SaveUserFile(picture, shot)); //var task = new SeasonTask(() => //{ // screenshot = new RenderTarget2D(Season.GraphicsDevice, 800, 480, false, SurfaceFormat.Color, DepthFormat.None); //}); } } catch (Exception ex) { WebTools.TakeWarnMsg("游戏界面截屏失败:", "takePicture:", ex); } } base.Draw(gameTime); }
public static RecordBase SeasonMessage(RecordBase info, string binary, ref string status, ref string errorMsg, PlatformTask onUpload) { status = ""; errorMsg = ""; string json = ""; try { string url = String.Format("{0}/Webservice.asmx/SeasonMessageFile2?", WebTools.WebSite); string jso = SimpleSerializer.SerializeJson <RecordBase>(info, false, false, false); string jsonEncryptZip = EncryptionHelper.Encrypt(jso, des3Key).GZipCompressString().UrlEncodePath2(); string binaryEncryptZip = ""; if (!String.IsNullOrEmpty(binary)) { binaryEncryptZip = binary.UrlEncodePath2(); } string data = String.Format("info={0}&binary={1}&product={2}&guid={3}&platform={4}", jsonEncryptZip, binaryEncryptZip, "WorldOfTheThreeKingdoms", Setting.Current.UserGuid, Platform.PlatFormType.ToString()); json = new Platform().GetWebServicePost(url.UrlEncodePath2(), data, onUpload); json = json.GZipDecompressString(); json = EncryptionHelper.Decrypt(json, des3Key); } catch (Exception ex) { errorMsg = ex.ToString(); } if (!String.IsNullOrEmpty(json)) { if (json.Length <= 20) { status = json; } else { try { RecordBase message = null; if (info is Record) { message = SimpleSerializer.DeserializeJson <Record>(json, false, false); } else if (info is ClientStatus) { message = SimpleSerializer.DeserializeJson <ClientStatus>(json, false, false); } else if (info is ErrorLog) { message = SimpleSerializer.DeserializeJson <ErrorLog>(json, false, false); } else if (info is UnknownTexts) { message = SimpleSerializer.DeserializeJson <UnknownTexts>(json, false, false); } else if (info is WebRecord) { message = SimpleSerializer.DeserializeJson <WebRecord>(json, false, false); } return(message); } catch (Exception ex) { //解析出錯 status = json; if (String.IsNullOrEmpty(errorMsg)) { errorMsg = ex.ToString(); } } } } return(null); }