public void ResolveTest() { var deferred = new Deferred<string, int>(); bool alwaysHit = false; dynamic alwaysArg = null; bool doneHit = false; string doneArg = null; bool failHit = false; var promise = deferred.Promise(); promise.Always((arg) => { alwaysHit = true; alwaysArg = arg; }); promise.Done((arg) => { doneHit = true; doneArg = arg; }); promise.Fail(() => failHit = true); deferred.Resolve("test"); Assert.IsTrue(alwaysHit, "Always is hit"); Assert.AreEqual("test", alwaysArg); Assert.IsTrue(doneHit, "Done is hit"); Assert.AreEqual("test", doneArg); Assert.IsFalse(failHit, "Fail is not hit"); }
public void RejectTest() { var deferred = new Deferred<string, int>(); bool alwaysHit = false; dynamic alwaysArg = null; bool doneHit = false; bool failHit = false; int? failArg = null; var promise = deferred.Promise(); promise.Always((arg) => { alwaysHit = true; alwaysArg = arg; }); promise.Done(() => doneHit = true); promise.Fail((arg) => { failHit = true; failArg = arg; }); deferred.Reject(1337); Assert.IsTrue(alwaysHit, "Always is hit"); Assert.AreEqual(alwaysArg, 1337); Assert.IsFalse(doneHit, "Done is not hit"); Assert.IsTrue(failHit, "Fail is hit"); Assert.AreEqual(failArg, 1337); }
private static Promise InternalUpdateAchievementToServer(bool showDialog) { Deferred deferred = new Deferred(); //BacktoryCloudUrl.Url = "http://localhost:8086"; UpdateAchievementsRequest request = new UpdateAchievementsRequest(); List <ServerAchievement> serverAchievements = new List <ServerAchievement>(); foreach ( AchievementInfo achievementInfo in InfoResolver.Resolve <FortInfo>().Achievement.AchievementInfos.Where(info => info != null)) { NoneLevelBaseAchievementInfo noneLevelBaseAchievementInfo = achievementInfo as NoneLevelBaseAchievementInfo; if (noneLevelBaseAchievementInfo != null) { serverAchievements.Add(new ServerAchievement { Name = noneLevelBaseAchievementInfo.Name, AchievementId = noneLevelBaseAchievementInfo.Id, Score = noneLevelBaseAchievementInfo.Score, Values = noneLevelBaseAchievementInfo.Balance.Values }); } else { LevelBaseAchievementInfo levelBaseAchievementInfo = (LevelBaseAchievementInfo)achievementInfo; AchievementLevelInfo[] achievementLevelInfos = levelBaseAchievementInfo.GetAchievementLevelInfos(); for (int i = 0; i < achievementLevelInfos.Length; i++) { serverAchievements.Add(new ServerAchievement { Name = achievementLevelInfos[i].Name, AchievementId = achievementLevelInfos[i].Id, Score = achievementLevelInfos[i].Score, Values = achievementLevelInfos[i].Balance.Values }); } } } request.Items = serverAchievements.ToArray(); EditorUtility.DisplayProgressBar("Syncronizing Achievements", "Syncronizing Achievements", 0); InfoResolver.Resolve <FortInfo>() .ServerConnectionProvider.EditorConnection.Call <object>("UpdateAchievements", request) .Then( o => { EditorUtility.ClearProgressBar(); if (showDialog) { EditorUtility.DisplayDialog("Syncronizing Achievements", "Achievemet syncronization succeeded", "Ok"); } deferred.Resolve(); }, error => { EditorUtility.ClearProgressBar(); deferred.Reject(); throw new Exception("Achievemet syncronization failed"); }); return(deferred.Promise()); }
public Promise <string, MarketPurchaseError> PurchasePackage(string sku, string payload) { _deferred = new Deferred <string, MarketPurchaseError>(); if (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.WindowsEditor) { _deferred.Resolve("FiB5nxjC8mxzwxLG"); return(_deferred.Promise()); } var androidJc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); var jo = androidJc.GetStatic <AndroidJavaObject>("currentActivity"); // Accessing the class to call a static method on it var jc = new AndroidJavaClass("com.redcap.thugs.PurchaseActivity"); // Calling a Call method to which the current activity is passed jc.CallStatic("RunActivity", jo, sku, payload, ((BazaarMarketInfo)FortInfo.Instance.MarketInfos.First(info => info.MarketName == "Bazaar")).Key); return(_deferred.Promise()); }
public Promise Relogin() { IDispatcher dispatcher = GameDispatcher.Dispatcher; Deferred deferred = new Deferred(); if (!IsReloginCapable()) { throw new Exception("Relogin is not capable.No saved refresh token found"); } string authenticationId = InfoResolver.Resolve <BacktoryInfo>().AuthenticationId; string authenticationClientKey = InfoResolver.Resolve <BacktoryInfo>().AuthenticationClientKey; string url = "https://api.backtory.com/auth/login"; ThreadPool.QueueUserWorkItem(state => { try { BacktoryAccessData backtoryAccessData = ServiceLocator.Resolve <IStorageService>().ResolveData <BacktoryAccessData>(); string result = MultiPartCall(url, new Dictionary <string, string> { { "refresh_token", backtoryAccessData.RefreshToken }, }, new Dictionary <string, string> { { "X-Backtory-Authentication-Id", authenticationId }, { "X-Backtory-Authentication-Key", authenticationClientKey }, { "X-Backtory-Authentication-Refresh", "1" } }); LoginResponse loginResponse = JsonConvert.DeserializeObject <LoginResponse>(result); dispatcher.Dispach(() => { if (string.IsNullOrEmpty(loginResponse.AccessToken)) { deferred.Reject(); } else { backtoryAccessData = ServiceLocator.Resolve <IStorageService>().ResolveData <BacktoryAccessData>(); backtoryAccessData.AccessToken = loginResponse.AccessToken; backtoryAccessData.RefreshToken = loginResponse.RefreshToken; backtoryAccessData.TokenType = loginResponse.TokenType; ServiceLocator.Resolve <IStorageService>().UpdateData(backtoryAccessData); deferred.Resolve(); } }); } catch (Exception) { dispatcher.Dispach(() => { deferred.Reject(); }); } }); return(deferred.Promise()); }
private Promise <string> QueryForTranslation(string data, string from, string to) { Deferred <string> deferred = new Deferred <string>(); // register callback support (required for WebClient) if (ServicePointManager.ServerCertificateValidationCallback == null) { AddCertificateChainValidation(); } // get an access token using (WebClient client = new WebClient()) { //client.Headers.Add("Authorization", "Bearer " + accessToken); client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => { try { if (e.Cancelled) { _status = StatusOptions.failed; deferred.Reject("web call was cancelled."); } else if (e.Error != null) { _status = StatusOptions.failed; deferred.Reject(e.Error.Message); } else { string response_string = System.Text.Encoding.Default.GetString(e.Result); string encapsulated = "<xml>" + response_string + "</xml>"; XmlSerializer serializer = new XmlSerializer(typeof(TranslationResponse)); using (TextReader reader = new StringReader(encapsulated)) { TranslationResponse result = (TranslationResponse)serializer.Deserialize(reader); deferred.Resolve(result.text); } } } catch (Exception ex) { _status = StatusOptions.failed; deferred.Reject(ex.Message); } Reset(); }; string parameters = "appid=Bearer " + Uri.EscapeUriString(accessToken) + "&text=" + Uri.EscapeUriString(data) + "&from=" + Uri.EscapeUriString(from) + "&to=" + Uri.EscapeUriString(to); client.DownloadDataAsync(new System.Uri("https://api.microsofttranslator.com/v2/http.svc/Translate?" + parameters)); } return(deferred.Promise()); }
public Promise Login(string username, string password) { IDispatcher dispatcher = GameDispatcher.Dispatcher; Deferred deferred = new Deferred(); string authenticationId = InfoResolver.Resolve <BacktoryInfo>().AuthenticationId; string authenticationClientKey = InfoResolver.Resolve <BacktoryInfo>().AuthenticationClientKey; string url = "https://api.backtory.com/auth/login"; ThreadPool.QueueUserWorkItem(state => { try { string result = MultiPartCall(url, new Dictionary <string, string> { { "username", username }, { "password", password } }, new Dictionary <string, string> { { "X-Backtory-Authentication-Id", authenticationId }, { "X-Backtory-Authentication-Key", authenticationClientKey } }); LoginResponse loginResponse = JsonConvert.DeserializeObject <LoginResponse>(result); dispatcher.Dispach(() => { if (string.IsNullOrEmpty(loginResponse.AccessToken)) { deferred.Reject(); } else { BacktoryAccessData backtoryAccessData = ServiceLocator.Resolve <IStorageService>().ResolveData <BacktoryAccessData>() ?? new BacktoryAccessData(); backtoryAccessData.AccessToken = loginResponse.AccessToken; backtoryAccessData.RefreshToken = loginResponse.RefreshToken; backtoryAccessData.TokenType = loginResponse.TokenType; ServiceLocator.Resolve <IStorageService>().UpdateData(backtoryAccessData); deferred.Resolve(); } }); } catch (Exception) { dispatcher.Dispach(() => { deferred.Reject(); }); } }); return(deferred.Promise()); }
private Promise <string> QueryForAccessToken() { Deferred <string> deferred = new Deferred <string>(); // register callback support (required for WebClient) if (ServicePointManager.ServerCertificateValidationCallback == null) { AddCertificateChainValidation(); } // get an access token using (WebClient client = new WebClient()) { client.Headers.Add("Ocp-Apim-Subscription-Key", TranslationKey); client.UploadDataCompleted += (object sender, UploadDataCompletedEventArgs e) => { try { if (e.Cancelled) { _status = StatusOptions.failed; deferred.Reject("web call was cancelled."); } else if (e.Error != null) { _status = StatusOptions.failed; deferred.Reject(e.Error.Message); } else { accessToken = System.Text.Encoding.Default.GetString(e.Result); lastToken = DateTime.Now; deferred.Resolve(); } } catch (Exception ex) { _status = StatusOptions.failed; deferred.Reject(ex.Message); } Reset(); }; byte[] buffer = { 0 }; client.UploadDataAsync(new System.Uri("https://api.cognitive.microsoft.com/sts/v1.0/issueToken"), buffer); } return(deferred.Promise()); }
public void ResolveFinishedTest() { var deferred = new Deferred(); deferred.Resolve(); var promise = deferred.Promise(); bool alwaysHit = false; bool doneHit = false; bool failHit = false; promise.Always(() => alwaysHit = true); promise.Done(() => doneHit = true); promise.Fail(() => failHit = true); Assert.IsTrue(alwaysHit, "Always is hit"); Assert.IsTrue(doneHit, "Done is hit"); Assert.IsFalse(failHit, "Fail is not hit"); }
public void RejectTest() { var deferred = new Deferred <string, int>(); bool alwaysHit = false; dynamic alwaysArg = null; bool doneHit = false; bool failHit = false; int? failArg = null; var promise = deferred.Promise(); promise.Always((arg) => { alwaysHit = true; alwaysArg = arg; }); promise.Done(() => doneHit = true); promise.Fail((arg) => { failHit = true; failArg = arg; }); deferred.Reject(1337); Assert.IsTrue(alwaysHit, "Always is hit"); Assert.AreEqual(alwaysArg, 1337); Assert.IsFalse(doneHit, "Done is not hit"); Assert.IsTrue(failHit, "Fail is hit"); Assert.AreEqual(failArg, 1337); }
public void ResolveTest() { var deferred = new Deferred <string, int>(); bool alwaysHit = false; dynamic alwaysArg = null; bool doneHit = false; string doneArg = null; bool failHit = false; var promise = deferred.Promise(); promise.Always((arg) => { alwaysHit = true; alwaysArg = arg; }); promise.Done((arg) => { doneHit = true; doneArg = arg; }); promise.Fail(() => failHit = true); deferred.Resolve("test"); Assert.IsTrue(alwaysHit, "Always is hit"); Assert.AreEqual("test", alwaysArg); Assert.IsTrue(doneHit, "Done is hit"); Assert.AreEqual("test", doneArg); Assert.IsFalse(failHit, "Fail is not hit"); }
public Promise <T, ICallError> Call <T>(string methodName, object requestBody) { IDispatcher dispatcher = GameDispatcher.Dispatcher; Deferred <T, ICallError> deferred = new Deferred <T, ICallError>(); string url = string.Format("https://api.backtory.com/cloud-code/{0}/{1}", InfoResolver.Resolve <BacktoryInfo>().CloudId, methodName); if (!string.IsNullOrEmpty(BacktoryCloudUrl.Url)) { url = new Uri(new Uri(BacktoryCloudUrl.Url), new Uri(string.Format("/{0}", methodName))).ToString(); } string authorization = string.Empty; if (ServiceLocator.Resolve <IStorageService>().ContainsData <BacktoryAccessData>()) { BacktoryAccessData backtoryAccessData = ServiceLocator.Resolve <IStorageService>().ResolveData <BacktoryAccessData>(); authorization = string.Format("{0} {1}", backtoryAccessData.TokenType, backtoryAccessData.AccessToken); } string body = JsonConvert.SerializeObject(requestBody); if (body == "null") { body = "{}"; } ThreadPool.QueueUserWorkItem(state => { try { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url)); webRequest.KeepAlive = true; webRequest.Method = "POST"; webRequest.ContentType = "application/json; charset=utf-8"; if (!string.IsNullOrEmpty(authorization)) { webRequest.Headers.Add("Authorization", authorization); } byte[] resoponse = Encoding.UTF8.GetBytes(body); webRequest.ContentLength = resoponse.Length; using (System.IO.Stream requestStream = webRequest.GetRequestStream()) { requestStream.Write(resoponse, 0, resoponse.Length); } using (WebResponse webResponse = webRequest.GetResponse()) { using (System.IO.Stream responseStream = webResponse.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { string readToEnd = reader.ReadToEnd(); dispatcher.Dispach(() => { try { T result = JsonConvert.DeserializeObject <T>(readToEnd); deferred.Resolve(result); } catch (Exception) { deferred.Reject(new BactkoryCallError(HttpStatusCode.Continue, CallErrorType.MethodConversionFailed)); } }); } } } dispatcher.Dispach(() => { deferred.Resolve(default(T)); }); } catch (WebException we) { dispatcher.Dispach(() => { HttpWebResponse httpWebResponse = we.Response as HttpWebResponse; if (httpWebResponse != null) { deferred.Reject(new BactkoryCallError(httpWebResponse.StatusCode, CallErrorType.Other)); } deferred.Reject(new BactkoryCallError(HttpStatusCode.Continue, CallErrorType.Other)); }); } catch (Exception) { deferred.Reject(new BactkoryCallError(HttpStatusCode.Continue, CallErrorType.Other)); } }); return(deferred.Promise()); }
public static Promise SyncAssetBundles() { //BacktoryCloudUrl.Url = "http://localhost:8086"; Deferred deferred = new Deferred(); string outputPath = Path.Combine(EditorAssetBundleUtility.AssetBundlesOutputPath, EditorAssetBundleUtility.GetPlatformName()); AssetBundleManifest assetBundleManifest = Build(); EditorUtility.DisplayProgressBar("Get server asset bundles", "Get server asset bundles", 0); InfoResolver.Resolve <FortInfo>() .ServerConnectionProvider.EditorConnection.Call <ServerAssetBundle[]>("GetAssetBundles", new { Platform = EditorAssetBundleUtility.GetPlatformName() }).Then( serverBundles => { List <AssetNameVersion> addedAssets = new List <AssetNameVersion>(); List <ServerAssetBundle> finalAssetBundles = new List <ServerAssetBundle>(serverBundles); Dictionary <string, ServerAssetBundleVersion> finalMap = new Dictionary <string, ServerAssetBundleVersion>(); EditorUtility.ClearProgressBar(); foreach ( var source in assetBundleManifest.GetAllAssetBundles() .Select(s => new { Name = s, Hash = assetBundleManifest.GetAssetBundleHash(s) }) .Where( arg1 => !serverBundles.Any( bundle => bundle.Name == arg1.Name && bundle.Versions.Any(version => version.Hash == arg1.Hash.ToString()))) ) { AssetNameVersion assetNameVersion = new AssetNameVersion { Name = source.Name, Version = new ServerAssetBundleVersion { Hash = source.Hash.ToString(), Path = ResolveAssetBundlePath(source.Name, source.Hash.ToString()), Size = GetBundleFileSize(source.Name) } }; ServerAssetBundle serverAssetBundle = finalAssetBundles.FirstOrDefault(bundle => bundle.Name == source.Name); if (serverAssetBundle == null) { serverAssetBundle = new ServerAssetBundle { Name = source.Name, Versions = new[] { assetNameVersion.Version } }; finalAssetBundles.Add(serverAssetBundle); } else { serverAssetBundle.Versions = serverAssetBundle.Versions.Concat(new[] { assetNameVersion.Version }).ToArray(); } addedAssets.Add(assetNameVersion); } foreach (string bundleName in assetBundleManifest.GetAllAssetBundles()) { string hash = assetBundleManifest.GetAssetBundleHash(bundleName).ToString(); ServerAssetBundleVersion serverAssetBundleVersion = finalAssetBundles.Where(bundle => bundle.Name == bundleName).SelectMany(bundle => bundle.Versions).First(version => version.Hash == hash); finalMap.Add(bundleName, serverAssetBundleVersion); } EditorUtility.DisplayProgressBar("Uploading Asset Bundles", "Uploading Asset Bundles", 0); InfoResolver.Resolve <FortInfo>() .ServerConnectionProvider.EditorConnection.SendFilesToStorage( addedAssets.Select(version => new StorageFile { FileName = Path.GetFileName(version.Version.Path), Path = Path.GetDirectoryName(version.Version.Path) + "/", Stream = File.OpenRead(Path.Combine(outputPath, version.Name)) }).ToArray(), f => { EditorUtility.DisplayProgressBar("Uploading Asset Bundles", "Uploading Asset Bundles", f); }).Then(files => { for (int i = 0; i < addedAssets.Count; i++) { addedAssets[i].Version.Path = files[i]; } EditorUtility.DisplayProgressBar("Updating server Asset bundle list", "Updating server Asset bundle list", 0); InfoResolver.Resolve <FortInfo>() .ServerConnectionProvider.EditorConnection .Call <UpdateServerAchievementResoponse>("UpdateAssetBundles", new { AssetBundles = finalAssetBundles.ToArray(), Platform = EditorAssetBundleUtility.GetPlatformName() }) .Then(resoponse => { EditorUtility.ClearProgressBar(); string fullDirectory = string.Format("/Assets/Fort/Resources/BundleConfig/{0}", EditorAssetBundleUtility.GetPlatformName()); string inAssetPath = string.Format("/Fort/Resources/BundleConfig/{0}", EditorAssetBundleUtility.GetPlatformName()); if (!Directory.Exists(fullDirectory)) { AssetDatabaseHelper.CreateFolderRecursive(fullDirectory); } string jsonFile = Application.dataPath + inAssetPath + "/AssetBundleBundleInfo.json"; using (StreamWriter writer = new StreamWriter(jsonFile)) { writer.Write(JsonConvert.SerializeObject(finalMap)); } //AssetDatabase.ImportAsset(fullDirectory+"/AssetBundleBundleInfo.json"); AssetDatabase.Refresh(); deferred.Resolve(); }, error => { EditorUtility.ClearProgressBar(); deferred.Reject(); throw new Exception("Cannot update server asset bundle list"); }); }, () => { EditorUtility.ClearProgressBar(); deferred.Reject(); throw new Exception("Cannot Upload asset bundles to storage"); }); }, error => { EditorUtility.ClearProgressBar(); deferred.Reject(); throw new Exception("Cannot resolve asset bundles from server"); }); return(deferred.Promise()); }
private static Promise InternalUpdatePurchasableItemsToServer(bool showDialog) { Deferred deferred = new Deferred(); //BacktoryCloudUrl.Url = "http://localhost:8086"; UpdateItemsRequest request = new UpdateItemsRequest(); List <ServerPurchasableItem> serverPurchasableItems = new List <ServerPurchasableItem>(); foreach ( PurchasableItemInfo purchasableItemInfo in InfoResolver.Resolve <FortInfo>().Purchase.GetAllPurchasableItemInfos().Where(info => info != null)) { NoneLevelBasePurchasableItemInfo noneLevelBasePurchasableItemInfo = purchasableItemInfo as NoneLevelBasePurchasableItemInfo; if (noneLevelBasePurchasableItemInfo != null) { serverPurchasableItems.Add(new ServerPurchasableItem { ItemId = noneLevelBasePurchasableItemInfo.Id, Name = noneLevelBasePurchasableItemInfo.Name, PurchaseCost = noneLevelBasePurchasableItemInfo.Costs.Purchase.Values, RentCost = noneLevelBasePurchasableItemInfo.Costs.Rent.Values }); } else { LevelBasePurchasableItemInfo levelBasePurchasableItemInfo = (LevelBasePurchasableItemInfo)purchasableItemInfo; PurchasableLevelInfo[] purchasableLevelInfos = levelBasePurchasableItemInfo.GetPurchasableLevelInfos(); for (int i = 0; i < purchasableLevelInfos.Length; i++) { serverPurchasableItems.Add(new ServerPurchasableItem { ItemId = purchasableLevelInfos[i].Id, Name = purchasableLevelInfos[i].Name, PurchaseCost = purchasableLevelInfos[i].Costs.Purchase.Values, RentCost = purchasableLevelInfos[i].Costs.Rent.Values }); } } } request.Items = serverPurchasableItems.ToArray(); EditorUtility.DisplayProgressBar("Syncronizing Purchasable items", "Syncronizing Purchasable items", 0); InfoResolver.Resolve <FortInfo>() .ServerConnectionProvider.EditorConnection.Call <object>("UpdateItems", request) .Then( o => { EditorUtility.ClearProgressBar(); if (showDialog) { EditorUtility.DisplayDialog("Syncronizing Purchasable items", "Purchasable items syncronization succeeded", "Ok"); } deferred.Resolve(); }, error => { EditorUtility.ClearProgressBar(); deferred.Reject(); throw new Exception("purchasable items syncronization failed"); }); return(deferred.Promise()); }
public void ResolveFinishedTest() { var deferred = new Deferred(); deferred.Resolve(); var promise = deferred.Promise(); bool alwaysHit = false; bool doneHit = false; bool failHit = false; promise.Always(() => alwaysHit = true); promise.Done(() => doneHit = true); promise.Fail(() => failHit = true); Assert.IsTrue(alwaysHit, "Always is hit"); Assert.IsTrue(doneHit, "Done is hit"); Assert.IsFalse(failHit, "Fail is not hit"); }
private static Promise InternalUpdateServerSettings(bool showDialog) { Deferred deferred = new Deferred(); ServerSettings serverSettings = new ServerSettings(); serverSettings.ValuesDefenition = InfoResolver.Resolve <FortInfo>().ValueDefenitions; serverSettings.InvitationPrize = InfoResolver.Resolve <FortInfo>().InvitationInfo.InvitationPrize; serverSettings.StartupBalance = InfoResolver.Resolve <FortInfo>().StartupBalance; AdvertisementSettings advertisementSettings = new AdvertisementSettings(); advertisementSettings.VideoPriority = InfoResolver.Resolve <FortInfo>().Advertisement.AdvertisementProviders.Where( priority => priority.AdvertisementProvider != null && priority.AdvertisementProvider.IsVideoSupported) .Select((priority, i) => new { Priority = priority, Index = i }) .OrderBy(arg => arg.Priority.VideoPriority < 0 ? arg.Index * 10000 : arg.Priority.VideoPriority) .Select(arg => arg.Priority.AdvertisementProvider.Name) .ToArray(); AdvertisementPriority advertisementPriority = InfoResolver.Resolve <FortInfo>().Advertisement.AdvertisementProviders.Where( priority => priority.AdvertisementProvider != null && priority.AdvertisementProvider.IsStandardBannerSupported) .Select((priority, i) => new { Priority = priority, Index = i }) .OrderBy( arg => arg.Priority.VideoPriority < 0 ? arg.Index * 10000 : arg.Priority.VideoPriority) .Select(arg => arg.Priority) .FirstOrDefault(); if (advertisementPriority != null) { advertisementSettings.StandardBannerPriority = advertisementPriority.AdvertisementProvider.Name; } else { advertisementSettings.StandardBannerPriority = string.Empty; } advertisementPriority = InfoResolver.Resolve <FortInfo>().Advertisement.AdvertisementProviders.Where( priority => priority.AdvertisementProvider != null && priority.AdvertisementProvider.IsInterstitialBannerSupported) .Select((priority, i) => new { Priority = priority, Index = i }) .OrderBy( arg => arg.Priority.VideoPriority < 0 ? arg.Index * 10000 : arg.Priority.VideoPriority) .Select(arg => arg.Priority) .FirstOrDefault(); if (advertisementPriority != null) { advertisementSettings.InterstiatialBannerPriority = advertisementPriority.AdvertisementProvider.Name; } else { advertisementSettings.InterstiatialBannerPriority = string.Empty; } serverSettings.AdvertisementSettings = advertisementSettings; EditorUtility.DisplayProgressBar("Syncronizing Server settings", "Syncronizing Server settings", 0); InfoResolver.Resolve <FortInfo>() .ServerConnectionProvider.EditorConnection.Call <object>("UpdateSettings", new UpdateServerSettingRequest { ServerSettings = serverSettings }) .Then( o => { EditorUtility.ClearProgressBar(); if (showDialog) { EditorUtility.DisplayDialog("Syncronizing Server settings", "Server settings syncronization succeeded", "Ok"); } deferred.Resolve(); }, error => { EditorUtility.ClearProgressBar(); deferred.Reject(); throw new Exception("Server settings syncronization failed"); }); return(deferred.Promise()); }
public Promise <T, ICallError> Call <T>(string methodName, object requestBody) { Deferred <T, ICallError> deferred = new Deferred <T, ICallError>(); IDispatcher dispatcher = EditorDispatcher.Dispatcher; string url = string.Format("https://api.backtory.com/cloud-code/{0}/{1}", InfoResolver.Resolve <BacktoryInfo>().CloudId, methodName); if (!string.IsNullOrEmpty(BacktoryCloudUrl.Url)) { url = new Uri(new Uri(BacktoryCloudUrl.Url), new Uri(string.Format("/{0}", methodName), UriKind.Relative)).ToString(); } string authenticationId = InfoResolver.Resolve <BacktoryInfo>().AuthenticationId; string authenticationMasterKey = EditorInfoResolver.Resolve <BacktoryEditorInfo>().AuthenticationMasterKey; string body = JsonConvert.SerializeObject(requestBody); if (body == "null") { body = "{}"; } ThreadPool.QueueUserWorkItem(state => { MasterLogin(authenticationId, authenticationMasterKey).Then(response => { string authorization = string.Format("{0} {1}", response.TokenType, response.AccessToken); try { string iUrl = url; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(iUrl)); webRequest.KeepAlive = true; webRequest.Method = "POST"; webRequest.ContentType = "application/json; charset=utf-8"; if (!string.IsNullOrEmpty(authorization)) { webRequest.Headers.Add("Authorization", authorization); } byte[] resoponse = Encoding.UTF8.GetBytes(body); webRequest.ContentLength = resoponse.Length; using (System.IO.Stream requestStream = webRequest.GetRequestStream()) { requestStream.Write(resoponse, 0, resoponse.Length); } using (WebResponse webResponse = webRequest.GetResponse()) { using (System.IO.Stream responseStream = webResponse.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { string readToEnd = reader.ReadToEnd(); dispatcher.Dispach(() => { try { T result = JsonConvert.DeserializeObject <T>(readToEnd); deferred.Resolve(result); } catch (Exception) { deferred.Reject(new BactkoryCallError(HttpStatusCode.Continue, CallErrorType.MethodConversionFailed)); } }); } } } } catch (WebException we) { Debug.LogException(we); dispatcher.Dispach(() => { HttpWebResponse httpWebResponse = we.Response as HttpWebResponse; if (httpWebResponse != null) { deferred.Reject(new BacktoryEditorCallError(CallErrorType.Other, false, httpWebResponse.StatusCode)); } deferred.Reject(new BacktoryEditorCallError(CallErrorType.Other, false, HttpStatusCode.Continue)); }); } catch (Exception) { deferred.Reject(new BacktoryEditorCallError(CallErrorType.Other, false, HttpStatusCode.Continue)); } }, () => { dispatcher.Dispach(() => { deferred.Reject(new BacktoryEditorCallError(CallErrorType.Other, true, HttpStatusCode.Continue)); }); }); }); return(deferred.Promise()); }