private static string VerifySignedHash( string str_DataToVerify, string str_SignedData, string str_publicKeyFilePath) { byte[] signedData = Convert.FromBase64String(str_SignedData); var byteConverter = new UTF8Encoding(); byte[] dataToVerify = byteConverter.GetBytes(str_DataToVerify); try { string publicKeyPEM = File.ReadAllText(str_publicKeyFilePath); var rsa = new RSACryptoServiceProvider(); rsa.PersistKeyInCsp = false; rsa.LoadPublicKeyPEM(publicKeyPEM); if (rsa.VerifyData(dataToVerify, "SHA256", signedData)) { return("verify success"); } return("verify fail"); } catch (CryptographicException e) { CustomTrace.TraceError(e); return("verify error"); } }
public async Task <IHttpActionResult> ResetPassword([FromBody] AccountResetPasswordInfo info, CancellationToken token) { CustomTrace.TraceInformation($"Account.ResetPassword AccountName={info.AccountName}"); var account = await this.Database.Accounts.GetSingleAsync(a => a.AccountName == info.AccountName, token); if (account == null) { throw new UCenterException(UCenterErrorCode.AccountNotExist); } if (!EncryptHashManager.VerifyHash(info.SuperPassword, account.SuperPassword)) { await this.RecordLogin( account, UCenterErrorCode.AccountLoginFailedPasswordNotMatch, "The super password provided is incorrect", token); throw new UCenterException(UCenterErrorCode.AccountLoginFailedPasswordNotMatch); } account.Password = EncryptHashManager.ComputeHash(info.Password); await this.Database.Accounts.UpsertAsync(account, token); await this.RecordLogin(account, UCenterErrorCode.Success, "Reset password successfully.", token); return(this.CreateSuccessResult(this.ToResponse <AccountResetPasswordResponse>(account))); }
public async Task <IHttpActionResult> GuestLogin([FromBody] AccountLoginInfo info, CancellationToken token) { CustomTrace.TraceInformation("Account.GuestLogin"); var r = new Random(); string accountNamePostfix = r.Next(0, 1000000).ToString("D6"); string accountName = $"uc_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{accountNamePostfix}"; string accountToken = EncryptHashManager.GenerateToken(); string password = Guid.NewGuid().ToString(); var account = new AccountEntity { Id = Guid.NewGuid().ToString(), AccountName = accountName, IsGuest = true, Password = EncryptHashManager.ComputeHash(password), Token = EncryptHashManager.GenerateToken() }; await this.Database.Accounts.InsertAsync(account, token); var response = new AccountGuestLoginResponse { AccountId = account.Id, AccountName = accountName, Token = accountToken, Password = password }; return(this.CreateSuccessResult(response)); }
public void CustomTracePropertyTest(CustomTrace customTrace) { UnityEngine.Debug.Log("CustomTracePropertyTest start"); customTrace.putProperty("ProcessingResult", "Success"); customTrace.putProperty("Status", "Normal"); string prop = customTrace.getProperty("ProcessingResult"); Debug.Log("get prop name: ProcessingResult, value: " + prop); customTrace.putProperty("Time", "2020-02-02"); customTrace.removeProperty("Time"); Map propertiesMap = customTrace.getTraceProperties(); if (propertiesMap != null) { UnityEngine.Debug.Log("getTraceProperties, map size: " + propertiesMap.keySet().toArray().Length); } else { UnityEngine.Debug.Log("getTraceProperties fail"); } UnityEngine.Debug.Log("CustomTracePropertyTest success"); }
public async Task <IHttpActionResult> Convert([FromBody] AccountConvertInfo info, CancellationToken token) { CustomTrace.TraceInformation($"Account.Convert AccountName={info.AccountName}"); var account = await this.GetAndVerifyAccount(info.AccountId, token); if (!EncryptHashManager.VerifyHash(info.OldPassword, account.Password)) { await this.RecordLogin( account, UCenterErrorCode.AccountLoginFailedPasswordNotMatch, "The account name and password do not match", token); throw new UCenterException(UCenterErrorCode.AccountLoginFailedPasswordNotMatch); } account.AccountName = info.AccountName; account.IsGuest = false; account.Name = info.Name; account.IdentityNum = info.IdentityNum; account.Password = EncryptHashManager.ComputeHash(info.Password); account.SuperPassword = EncryptHashManager.ComputeHash(info.SuperPassword); account.PhoneNum = info.PhoneNum; account.Email = info.Email; account.Sex = info.Sex; await this.Database.Accounts.UpsertAsync(account, token); await this.RecordLogin(account, UCenterErrorCode.Success, "Account converted successfully.", token); return(this.CreateSuccessResult(this.ToResponse <AccountRegisterResponse>(account))); }
public async Task <IHttpActionResult> UploadProfileImage([FromUri] string accountId, CancellationToken token) { CustomTrace.TraceInformation($"Account.UploadProfileImage AccountId={accountId}"); var account = await this.GetAndVerifyAccount(accountId, token); using (var stream = await this.Request.Content.ReadAsStreamAsync()) { var image = Image.FromStream(stream); using (var thumbnailStream = this.GetThumbprintStream(image)) { var smallProfileName = this.settings.ProfileThumbnailForBlobNameTemplate.FormatInvariant(accountId); account.ProfileThumbnail = await this.storageContext.UploadBlobAsync(smallProfileName, thumbnailStream, token); } string profileName = this.settings.ProfileImageForBlobNameTemplate.FormatInvariant(accountId); stream.Seek(0, SeekOrigin.Begin); account.ProfileImage = await this.storageContext.UploadBlobAsync(profileName, stream, token); await this.Database.Accounts.UpsertAsync(account, token); await this.RecordLogin(account, UCenterErrorCode.Success, "Profile image uploaded successfully.", token); return(this.CreateSuccessResult( this.ToResponse <AccountUploadProfileImageResponse>(account))); } }
public async Task <IHttpActionResult> Login([FromBody] AccountLoginInfo info, CancellationToken token) { CustomTrace.TraceInformation($"Account.Login AccountName={info.AccountName}"); var account = await this.Database.Accounts.GetSingleAsync(a => a.AccountName == info.AccountName, token); if (account == null) { throw new UCenterException(UCenterErrorCode.AccountNotExist); } if (!EncryptHashManager.VerifyHash(info.Password, account.Password)) { await this.RecordLogin( account, UCenterErrorCode.AccountLoginFailedPasswordNotMatch, "The account name and password do not match", token); throw new UCenterException(UCenterErrorCode.AccountLoginFailedPasswordNotMatch); } account.LastLoginDateTime = DateTime.UtcNow; account.Token = EncryptHashManager.GenerateToken(); await this.Database.Accounts.UpsertAsync(account, token); await this.RecordLogin(account, UCenterErrorCode.Success, token : token); return(this.CreateSuccessResult(this.ToResponse <AccountLoginResponse>(account))); }
public async Task <IHttpActionResult> CreateAppConfiguration([FromBody] AppConfigurationInfo info, CancellationToken token) { CustomTrace.TraceInformation("[CreateAppConfiguration] AppId={0}", info.AppId); var appConfiguration = await this.Database.AppConfigurations.GetSingleAsync(info.AppId, token); if (appConfiguration == null) { appConfiguration = new AppConfigurationEntity { Id = info.AppId, Configuration = info.Configuration, }; await this.Database.AppConfigurations.InsertAsync(appConfiguration, token); } else { await this.Database.AppConfigurations.UpsertAsync(appConfiguration, token); } var response = new AppConfigurationResponse { AppId = info.AppId, Configuration = info.Configuration }; return(this.CreateSuccessResult(response)); }
public async Task <IHttpActionResult> CreateApp([FromBody] AppInfo info, CancellationToken token) { CustomTrace.TraceInformation("[CreateApp] AppId={0}", info.AppId); var app = await this.Database.Apps.GetSingleAsync(info.AppId, token); if (app == null) { // todo: currently, app name equals app id. app = new AppEntity { Id = info.AppId, Name = info.AppId, AppSecret = info.AppSecret, }; await this.Database.Apps.InsertAsync(app, token); } var response = new AppResponse { AppId = info.AppId, AppSecret = info.AppSecret }; return(this.CreateSuccessResult(response)); }
public async Task <IHttpActionResult> PingPlusPlusWebHook(CancellationToken token) { CustomTrace.TraceInformation("AppServer.PingPlusPlusWebHook"); // 获取 post 的 event对象 var inputData = Request.Content.ReadAsStringAsync().Result; CustomTrace.TraceInformation("Received event\n" + inputData); // 获取 header 中的签名 IEnumerable <string> headerValues; string sig = string.Empty; if (Request.Headers.TryGetValues("x-pingplusplus-signature", out headerValues)) { sig = headerValues.FirstOrDefault(); } // 公钥路径(请检查你的公钥 .pem 文件存放路径) string certPath = this.GetCertFilePath("rsa_public_key.pem"); // 验证签名 VerifySignedHash(inputData, sig, certPath); await this.ProcessOrderAsync(inputData, token); return(this.Ok()); }
/// <summary> /// Occurs after the action method is invoked. /// </summary> /// <param name="context">Indicating the executed context.</param> public override void OnActionExecuted(HttpActionExecutedContext context) { if (context.Exception != null) { CustomTrace.TraceError( context.Exception, "Execute request exception: url:{0}, arguments: {1}", context.Request.RequestUri, context.ActionContext.ActionArguments); var errorCode = UCenterErrorCode.InternalHttpServerError; if (context.Exception is UCenterException) { errorCode = (context.Exception as UCenterException).ErrorCode; } else if (context.Exception is MongoException) { errorCode = UCenterErrorCode.InternalDatabaseError; } string errorMessage = context.Exception.Message; context.Response = this.CreateErrorResponseMessage(errorCode, errorMessage); } base.OnActionExecuted(context); }
public void BusinessLogicStart(CustomTrace customTrace) { customTrace.PutMeasure("PutMeasure", 0); for (int i = 0; i < 5; i++) { customTrace.IncrementMeasure("IncrementMeasure", 1); } }
static void Main(string[] args) { CustomTrace.Write(Console.Out, "Starting Main"); Console.WriteLine("Doing work in Main"); CustomTrace.Write(Console.Out, "Leaving Main"); Console.ReadLine(); }
public async Task <IHttpActionResult> GetClientIpArea(CancellationToken token) { CustomTrace.TraceInformation("AppClient.GetClientIpArea"); string ipAddress = IPHelper.GetClientIpAddress(Request); var response = await IPHelper.GetIPInfoAsync(ipAddress, token); return(this.CreateSuccessResult(response)); }
public void TestEncryptAndCompare() { string password = Guid.NewGuid().ToString(); var hash = EncryptHashManager.ComputeHash(password); CustomTrace.TraceInformation("Hash code is: {0}", hash); Assert.IsFalse(EncryptHashManager.VerifyHash(Guid.NewGuid().ToString(), hash)); Assert.IsTrue(EncryptHashManager.VerifyHash(password, hash)); }
// Use this for initialization void Start() { TestPackBuilder.main(); //初始化 UnityThreadHelper.EnsureHelper(); //线程初始化,这个必须要在开始定义. CustomTrace.close(true); //关闭输出。关闭框架输出,如果影响调试。 TinyPlayerCS pp = new TinyPlayerCS(); pp.id = 2009; client = new Client(); client.testUint((uint)3312); //client.testPlayer.addEventListener("onOpen", onCSOpen); Debug.Log("是否解决了?"); client.onSocketCloseCS = onSocketClose; client.onSocketOpenCS = onSocketOpen; client.onSocketErrorCS = onSocketError; // client.connectWithIP("27.102.127.81", 9003); //这里改成你自己的ip client.connectWithIP("127.0.0.1", 9003); //这里改成你自己的ip // client.connectWithIP("144.48.4.186", 9003); //这里改成你自己的ip client.onGlobalError = onGlobalError; // client.testPlayer.dispatchEvent(new CEvent("onOpen"),this ); self = new PlayerCS(null); self.addEvent(); //这里添加倾听器,如果要移除用off self.addEventListener(HallEvent.LOGIN, onLogin); self.addEventListener(HallEvent.OnReg, onReg); self.addEventListener(PlayerEvent.GET_USER_INFO, onGetuserInfo); self.addEventListener(PlayerEvent.GET_TEARM_INCOME, onGetIncome); self.addEventListener(ShoppingEvent.GET_BUY_LIST, onGetBuyList); self.addEventListener(ShoppingEvent.GET_CHARGE_LIST, onGetChargeList); self.addEventListener(ShoppingEvent.GET_DRAW_OUT_LIST, onGetDrawOutList); self.addEventListener(ShoppingEvent.GET_LAST_CHARGE_TIME, onGetLastChargeTime); self.addEventListener(PlayerEvent.STATIC_CHANGE, onStatusChange); self.addEventListener(PlayerEvent.ADD_BET, onPlayerAddBet); self.addEventListener(RoomEvent.JOIN_ROOM, onJoinRoom); self.addEventListener(ShoppingEvent.GET_REATE, onGetRate); TestEventDispathFromHaxe(); //---------------新增------------------- hall = new HallCS(); //创建大厅 hall.addEvent(); //这个一定不能删除。//todo:不能其他人登陆会影响到这里。 hall.addEventListener(RoomEvent.CREATE_ROOM, onCreateRoom); hall.addEventListener(RoomEvent.JOIN_ROOM, onJoinRoom); hall.addEventListener(CMDEvent.RESULT, onCMDResult); }
private void BtnCustomNormalEvent_Click(object sender, System.EventArgs e) { CustomTrace customTrace = APMS.Instance.CreateCustomTrace("testCustomTrace"); customTrace.Start(); // code you want trace BusinessLogicStart(customTrace); BusinessLogicEnd(customTrace); customTrace.Stop(); }
public void sendCustomEvent() { CustomTrace customTrace = APMS.getInstance().createCustomTrace("CustomEvent1"); if (customTrace != null) { UnityEngine.Debug.Log("customTrace is not null"); } customTrace.start(); // code you want trace CustomTracePropertyTest(customTrace); CustomTraceMeasureTest(customTrace); customTrace.stop(); }
public void CustomTraceMeasureTest(CustomTrace customTrace) { UnityEngine.Debug.Log("CustomTraceMeasureTest start"); customTrace.putMeasure("ProcessingTimes", 0); for (int i = 0; i < 100; i++) { customTrace.incrementMeasure("ProcessingTimes", 1); } long value = customTrace.getMeasure("ProcessingTimes"); Debug.Log("Measurename: ProcessingTimes, value: " + value); UnityEngine.Debug.Log("CustomTraceMeasureTest success"); }
private void LogInboundRequest(HttpActionContext context) { try { string clientIpAddress = IPHelper.GetClientIpAddress(context.Request); string request = context.Request.ToString(); string arguments = context .ActionArguments.Select(a => $"{a.Value.DumpToString(a.Key)}") .JoinToString(","); string message = $"Inbound Request IP: {clientIpAddress}\n\tRequest: {request}\n\n\t Arguments: {arguments}"; CustomTrace.TraceInformation(message); } catch (Exception ex) { CustomTrace.TraceError(ex, $"Log Inbound Request Error: \n\t{context.Request}"); } }
public async Task <IHttpActionResult> VerifyAccount(AppVerifyAccountInfo info, CancellationToken token) { CustomTrace.TraceInformation($"App.VerifyAccount AppId={info.AppId} AccountId={info.AccountId}"); await this.VerifyApp(info.AppId, info.AppSecret, token); var account = await this.GetAndVerifyAccount(info.AccountId, info.AccountToken, token); var result = new AppVerifyAccountResponse(); result.AccountId = account.Id; result.AccountName = account.AccountName; result.AccountToken = account.Token; result.LastLoginDateTime = account.LastLoginDateTime; result.LastVerifyDateTime = DateTime.UtcNow; return(this.CreateSuccessResult(result)); }
public async Task <IHttpActionResult> ReadAppAccountData(AppAccountDataInfo info, CancellationToken token) { CustomTrace.TraceInformation($"App.ReadAppAccountData AppId={info.AppId} AccountId={info.AccountId}"); await this.VerifyApp(info.AppId, info.AppSecret, token); var account = await this.GetAndVerifyAccount(info.AccountId, token); var dataId = this.CreateAppAccountDataId(info.AppId, info.AccountId); var accountData = await this.Database.AppAccountDatas.GetSingleAsync(dataId, token); var response = new AppAccountDataResponse { AppId = info.AppId, AccountId = info.AccountId, Data = accountData?.Data }; return(this.CreateSuccessResult(response)); }
public async Task <IHttpActionResult> GetAppConfiguration([FromUri] string appId, CancellationToken token) { CustomTrace.TraceInformation($"AppClient.GetAppConfiguration AppId={appId}"); var app = await this.Database.Apps.GetSingleAsync(appId, token); if (app == null) { throw new UCenterException(UCenterErrorCode.AppNotExit); } var appConfiguration = await this.Database.AppConfigurations.GetSingleAsync(appId, token); var response = new AppConfigurationResponse { AppId = app.Id, Configuration = appConfiguration == null ? string.Empty : appConfiguration.Configuration }; return(this.CreateSuccessResult(response)); }
public async Task <IHttpActionResult> WriteAppAccountData(AppAccountDataInfo info, CancellationToken token) { CustomTrace.TraceInformation($"App.WriteAppAccountData AppId={info.AppId} AccountId={info.AccountId}"); await this.VerifyApp(info.AppId, info.AppSecret, token); var account = await this.GetAndVerifyAccount(info.AccountId, token); var dataId = this.CreateAppAccountDataId(info.AppId, info.AccountId); var accountData = await this.Database.AppAccountDatas.GetSingleAsync(dataId, token); if (accountData != null) { accountData.Data = info.Data; } else { accountData = new AppAccountDataEntity { Id = dataId, AppId = info.AppId, AccountId = info.AccountId, Data = info.Data }; } await this.Database.AppAccountDatas.UpsertAsync(accountData, token); var response = new AppAccountDataResponse { AppId = info.AppId, AccountId = info.AccountId, Data = accountData.Data }; return(this.CreateSuccessResult(response)); }
public async Task <string> UploadBlobAsync(string blobName, Stream stream, CancellationToken token) { try { string key = $"{this.settings.ImageContainerName}/{blobName}"; this.CreateBucketIfNotExists(); var result = await Task <PutObjectResult> .Factory.FromAsync( this.client.BeginPutObject, this.client.EndPutObject, this.bucketName, key, stream, null); var uri = this.client.GeneratePresignedUri(this.bucketName, key); return(uri.GetLeftPart(UriPartial.Path)); } catch (Exception ex) { CustomTrace.TraceError(ex, "Error while upload file to ali oss"); throw; } }
public WebContext(ExportProvider exportProvider, Settings settings) { this.settings = settings; this.BaseAddress = $"http://{this.settings.ServerHost}:{this.settings.ServerPort}"; if (UseSelfHost()) { try { this.configuration = new HttpSelfHostConfiguration(this.BaseAddress); this.configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; this.configuration.MapHttpAttributeRoutes(); WebApplicationManager.InitializeApplication(configuration, exportProvider); this.server = new HttpSelfHostServer(configuration); this.server.OpenAsync().Wait(); } catch (Exception ex) { CustomTrace.TraceError(ex); throw; } } }
public UCenterTestBase() { this.Tenant = ExportProvider.GetExportedValue <TenantEnvironment>(); CustomTrace.Initialize(ExportProvider, "Trace.Console"); }
public async Task <IActionResult> Register([FromBody] AccountRegisterRequestInfo info, CancellationToken token) { // 检测注册信息合法性 ValidateAccount(info); try { // 检测帐号名是否可以被注册 var oldAccountEntity = await this.Database.Accounts.GetSingleAsync( a => a.AccountName == info.AccountName, //|| a.Email == info.Email //|| a.Phone == info.Phone, token); if (oldAccountEntity != null) { throw new UCenterException(UCenterErrorCode.AccountNameAlreadyExist); } // 检查Device是否绑定了游客号 AccountEntity accountEntity = null; if (info != null && !string.IsNullOrEmpty(info.AppId) && info.Device != null && !string.IsNullOrEmpty(info.Device.Id)) { string guestDeviceId = $"{info.AppId}_{info.Device.Id}"; var guestDeviceEntity = await this.Database.GuestDevices.GetSingleAsync(guestDeviceId, token); if (guestDeviceEntity != null) { accountEntity = await this.Database.Accounts.GetSingleAsync(guestDeviceEntity.AccountId, token); } } bool guestConvert = true; if (accountEntity == null) { guestConvert = false; // 没有绑定游客号,正常注册 accountEntity = new AccountEntity { Id = Guid.NewGuid().ToString(), }; } accountEntity.AccountName = info.AccountName; accountEntity.AccountType = AccountType.NormalAccount; accountEntity.AccountStatus = AccountStatus.Active; accountEntity.Name = info.Name; accountEntity.Identity = info.Identity; accountEntity.Password = EncryptHelper.ComputeHash(info.Password); accountEntity.SuperPassword = EncryptHelper.ComputeHash(info.SuperPassword); accountEntity.Phone = info.Phone; accountEntity.Email = info.Email; accountEntity.Gender = info.Gender; //var placeholders = new[] // { // this.GenerateKeyPlaceholder(accountEntity.AccountName, KeyType.Name, accountEntity.Id, accountEntity.AccountName), // this.GenerateKeyPlaceholder(accountEntity.Phone, KeyType.Phone, accountEntity.Id, accountEntity.AccountName), // this.GenerateKeyPlaceholder(accountEntity.Email, KeyType.Email, accountEntity.Id, accountEntity.AccountName) // }; //foreach (var placeholder in placeholders) //{ // if (!string.IsNullOrEmpty(placeholder.Name)) // { // await this.Database.KeyPlaceholders.InsertAsync(placeholder, token); // removeTempsIfError.Add(placeholder); // } //} if (guestConvert) { // 绑定了游客号,游客号转正 await this.Database.Accounts.UpsertAsync(accountEntity, token); try { await this.Database.GuestDevices.DeleteAsync( d => d.AppId == info.AppId && d.AccountId == accountEntity.Id, token); } catch (Exception ex) { CustomTrace.TraceError(ex, "Error to remove guest device"); } await this.TraceAccountEvent(accountEntity, "GuestConvert", token : token); } else { // 没有绑定游客号,正常注册 // Remove this from UCenter for performance concern // If user does not have default profile icon, app client should use local default one // accountEntity.ProfileImage = await this.storageContext.CopyBlobAsync( // accountEntity.Gender == Gender.Female ? this.settings.DefaultProfileImageForFemaleBlobName : this.settings.DefaultProfileImageForMaleBlobName, // this.settings.ProfileImageForBlobNameTemplate.FormatInvariant(accountEntity.Id), // token); // accountEntity.ProfileThumbnail = await this.storageContext.CopyBlobAsync( // accountEntity.Gender == Gender.Female // ? this.settings.DefaultProfileThumbnailForFemaleBlobName // : this.settings.DefaultProfileThumbnailForMaleBlobName, // this.settings.ProfileThumbnailForBlobNameTemplate.FormatInvariant(accountEntity.Id), // token); await this.Database.Accounts.InsertAsync(accountEntity, token); await TraceAccountEvent(accountEntity, "Register", info.Device, token : token); } if (info.Device != null) { await LogDeviceInfo(info.Device, token); } return(this.CreateSuccessResult(this.ToResponse <AccountRegisterResponse>(accountEntity))); } catch (Exception ex) { CustomTrace.TraceError(ex, "Account.Register Exception:AccoundName={info.AccountName}"); throw; } }
public void BusinessLogicEnd(CustomTrace customTrace) { customTrace.PutProperty("PutProperty", "propertyValue"); customTrace.PutProperty("key", "value"); }
public async Task <IHttpActionResult> Register([FromBody] AccountRegisterRequestInfo info, CancellationToken token) { CustomTrace.TraceInformation($"Account.Register AccountName={info.AccountName}"); if (!ValidateAccountName(info.AccountName)) { // TODO: Change to AccountRegisterFailedInvalidName in next client refresh throw new UCenterException(UCenterErrorCode.AccountRegisterFailedAlreadyExist); } var removeTempsIfError = new List <KeyPlaceholderEntity>(); var error = false; try { var account = await this.Database.Accounts.GetSingleAsync(a => a.AccountName == info.AccountName, token); if (account != null) { throw new UCenterException(UCenterErrorCode.AccountRegisterFailedAlreadyExist); } account = new AccountEntity { Id = Guid.NewGuid().ToString(), AccountName = info.AccountName, IsGuest = false, Name = info.Name, Email = info.Email, IdentityNum = info.IdentityNum, Password = EncryptHashManager.ComputeHash(info.Password), SuperPassword = EncryptHashManager.ComputeHash(info.SuperPassword), PhoneNum = info.PhoneNum, Sex = info.Sex }; var placeholders = new[] { this.GenerateKeyPlaceholder(account.AccountName, KeyType.Name, account.Id, account.AccountName), this.GenerateKeyPlaceholder(account.PhoneNum, KeyType.Phone, account.Id, account.AccountName), this.GenerateKeyPlaceholder(account.Email, KeyType.Email, account.Id, account.AccountName) }; foreach (var placeholder in placeholders) { if (!string.IsNullOrEmpty(placeholder.Name)) { await this.Database.KeyPlaceholders.InsertAsync(placeholder, token); removeTempsIfError.Add(placeholder); } } // set the default profiles account.ProfileImage = await this.storageContext.CopyBlobAsync( account.Sex == Sex.Female?this.settings.DefaultProfileImageForFemaleBlobName : this.settings.DefaultProfileImageForMaleBlobName, this.settings.ProfileImageForBlobNameTemplate.FormatInvariant(account.Id), token); account.ProfileThumbnail = await this.storageContext.CopyBlobAsync( account.Sex == Sex.Female ?this.settings.DefaultProfileThumbnailForFemaleBlobName : this.settings.DefaultProfileThumbnailForMaleBlobName, this.settings.ProfileThumbnailForBlobNameTemplate.FormatInvariant(account.Id), token); await this.Database.Accounts.InsertAsync(account, token); return(this.CreateSuccessResult(this.ToResponse <AccountRegisterResponse>(account))); } catch (Exception ex) { CustomTrace.TraceError(ex, "Account.Register Exception:AccoundName={info.AccountName}"); error = true; if (ex is MongoWriteException) { var mex = ex as MongoWriteException; if (mex.WriteError.Category == ServerErrorCategory.DuplicateKey) { throw new UCenterException(UCenterErrorCode.AccountRegisterFailedAlreadyExist, ex); } } throw; } finally { if (error) { try { foreach (var item in removeTempsIfError) { this.Database.KeyPlaceholders.DeleteAsync(item, token).Wait(token); } } catch (Exception ex) { CustomTrace.TraceError(ex, "Error to remove placeholder"); } } } }