//NEED to REMOVE Cons PRAM public ReportHelper(UtilityHelper uh, string MSSQLServerName, string Catalog, string UserID, string Password) { Utility = uh; strConStr = "Data Source = " + MSSQLServerName + "; Initial Catalog = " + Catalog + "; Persist Security Info = True; UID = " + UserID + "; Pwd = " + Password + "; Connection Timeout = 30;"; }
/// <summary> /// Register customer /// </summary> /// <param name="request">Request</param> /// <returns>Result</returns> public virtual CustomerRegistrationResult RegisterCustomer(Customer request) { var result = new CustomerRegistrationResult(); #region 验证 if (request == null) { throw new ArgumentNullException("request"); } if (string.IsNullOrWhiteSpace(request.Username)) { throw new ArgumentNullException("Customer's name cant't Empty!"); } if (string.IsNullOrWhiteSpace(request.Password)) { throw new ArgumentNullException("Customer's password cant't Empty!"); } if (!Validator.IsUserName(request.Username)) { result.AddError("Messages_Account.RegisterCustomer.Errors.UsernameError"); return(result); } if (_customerService.GetCustomerByUsername(request.Username) != null) { result.AddError("Messages_Account.RegisterCustomer.Errors.UsernameAlreadyExists"); return(result); } if (!Validator.IsPassword(request.Password)) { result.AddError("Messages_Account.RegisterCustomer.Errors.PasswordError"); return(result); } if (!string.IsNullOrEmpty(request.Email)) { if (!Validator.IsValidEmail(request.Email)) { result.AddError("Messages_CheckEmailAvailability.EmailError"); return(result); } if (_customerService.GetCustomerByEmail(request.Email) != null) { result.AddError("Messages_Account.RegisterCustomer.Errors.EmailAlreadyExists"); return(result); } } #endregion #region 密码 switch (request.PasswordFormat) { case PasswordFormat.Encrypted: { request.Password = _encryptionService.EncryptText(request.Password); request.Password = UtilityHelper.MD5(request.Password); } break; case PasswordFormat.Hashed: { string saltKey = _encryptionService.CreateSaltKey(5); request.PasswordSalt = saltKey; request.Password = _encryptionService.CreatePasswordHash(request.Password, saltKey, _customerSettings.HashedPasswordFormat); request.Password = UtilityHelper.MD5(request.Password); } break; //明码 case PasswordFormat.Clear: default: request.Password = UtilityHelper.TxtEnDes(request.Password); break; } #endregion request.RegisterIp = UtilityHelper.GetRealIP(); bool res = _customerService.InsertCustomer(request); //if (res) //{ // if (request.CustomerAttribute != null) _customerService.InsertCustomerAttribute(request.CustomerAttribute); // if (request.CustomerExtentions != null) _customerService.InsertCustomerExtentions(request.CustomerExtentions); //} if (!res) { result.AddError("Messages_Account.RegisterCustomer.Errors.RegisterFail"); } return(result); }
public void Init(params object[] args) { UtilityHelper.Log("BattleMapCreator初始化"); }
public async Task <BackupPolicy> GetBackupSchedulingPolicyAsync(BackupPartitionInfo backupPartitionInfo, TimeSpan timeout, CancellationToken cancellationToken) { BackupPolicy backupPolicy; BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "{0} GetBackupPolicy invoked", backupPartitionInfo.PartitionId); var backupMappingStore = await BackupMappingStore.CreateOrGetBackupMappingStore(this.statefulService); var backupPolicyStore = await BackupPolicyStore.CreateOrGetBackupPolicyStore(this.statefulService); var suspendStore = await SuspendStore.CreateOrGetSuspendStatusStore(this.statefulService); var serviceNameUri = await UtilityHelper.GetCustomServiceUri(backupPartitionInfo.ServiceName, timeout, cancellationToken); var backupMappingKey = UtilityHelper.GetBackupMappingKey(serviceNameUri, backupPartitionInfo.PartitionId.ToString()); var backupMappingModel = (await backupMappingStore.GetValueAsync(backupMappingKey) ?? await backupMappingStore.GetValueAsync(serviceNameUri)) ?? await backupMappingStore.GetValueAsync(UtilityHelper.GetApplicationNameFromService(serviceNameUri)); bool isPartitionSuspended = await suspendStore.GetValueAsync(backupMappingKey) != null; if (backupMappingModel == null || isPartitionSuspended) { BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "{0} Backup protection not enabled", backupPartitionInfo.PartitionId); throw new FabricPeriodicBackupNotEnabledException(); } var backupPolicyName = backupMappingModel.BackupPolicyName; var backupPolicyModel = await backupPolicyStore.GetValueAsync(backupPolicyName); switch (backupPolicyModel.BackupSchedule.BackupScheduleType) { case BackupScheduleType.FrequencyBased: backupPolicy = new FrequencyBasedBackupPolicy(); var frequencyBasedSchedulePolicy = (System.Fabric.BackupRestore.Common.Model.FrequencyBasedBackupSchedule)backupPolicyModel.BackupSchedule; backupPolicy.PolicyType = BackupPolicyType.FrequencyBased; var freqBackupPolicy = (FrequencyBasedBackupPolicy)backupPolicy; freqBackupPolicy.RunFrequency = (ushort)frequencyBasedSchedulePolicy.Interval; if (frequencyBasedSchedulePolicy.IntervalType == BackupScheduleInterval.Hours) { freqBackupPolicy.RunFrequencyType = BackupPolicyRunFrequency.Hours; } if (frequencyBasedSchedulePolicy.IntervalType == BackupScheduleInterval.Minutes) { freqBackupPolicy.RunFrequencyType = BackupPolicyRunFrequency.Minutes; } break; case BackupScheduleType.TimeBased: backupPolicy = new ScheduleBasedBackupPolicy(); var scheduleBasedSchedulePolicy = (System.Fabric.BackupRestore.Common.Model.TimeBasedBackupSchedule)backupPolicyModel.BackupSchedule; backupPolicy.PolicyType = BackupPolicyType.ScheduleBased; var schdBackupPolicy = (ScheduleBasedBackupPolicy)backupPolicy; if (scheduleBasedSchedulePolicy.ScheduleFrequencyType == BackupScheduleFrequency.Daily) { schdBackupPolicy.RunSchedule = BackupPolicyRunSchedule.Daily; } if (scheduleBasedSchedulePolicy.ScheduleFrequencyType == BackupScheduleFrequency.Weekly) { schdBackupPolicy.RunSchedule = BackupPolicyRunSchedule.Weekly; } schdBackupPolicy.RunDays = new List <DayOfWeek>(scheduleBasedSchedulePolicy.RunDays); schdBackupPolicy.RunTimes = new List <TimeSpan>(scheduleBasedSchedulePolicy.RunTimes); break; default: throw new FabricPeriodicBackupNotEnabledException(); } backupPolicy.MaxIncrementalBackups = Convert.ToByte(backupPolicyModel.MaxIncrementalBackup); backupPolicy.Name = backupPolicyModel.Name; backupPolicy.PolicyId = backupPolicyModel.UniqueId; switch (backupPolicyModel.Storage.BackupStorageType) { case BackupStorageType.FileShare: var fileShareStorage = (System.Fabric.BackupRestore.Common.Model.FileShareBackupStorageInfo)backupPolicyModel.Storage; backupPolicy.StoreInformation = new FileShareBackupStore { AccessType = String.IsNullOrEmpty(fileShareStorage.PrimaryUserName) ? FileShareAccessType.None : FileShareAccessType.DomainUser, FileSharePath = Path.Combine(fileShareStorage.Path, UtilityHelper.GetBaseDirectoryPathForPartition(serviceNameUri, backupPartitionInfo.PartitionId.ToString())), PrimaryUserName = fileShareStorage.PrimaryUserName, PrimaryPassword = fileShareStorage.PrimaryPassword, SecondaryUserName = fileShareStorage.SecondaryUserName, SecondaryPassword = fileShareStorage.SecondaryPassword, IsPasswordEncrypted = fileShareStorage.IsPasswordEncrypted, }; break; case BackupStorageType.AzureBlobStore: var azureStorage = (System.Fabric.BackupRestore.Common.Model.AzureBlobBackupStorageInfo)backupPolicyModel.Storage; backupPolicy.StoreInformation = new AzureBlobBackupStore { ConnectionString = azureStorage.ConnectionString, ContainerName = azureStorage.ContainerName, FolderPath = UtilityHelper.GetBaseDirectoryPathForPartition(serviceNameUri, backupPartitionInfo.PartitionId.ToString()), IsAccountKeyEncrypted = azureStorage.IsConnectionStringEncrypted, }; break; case BackupStorageType.DsmsAzureBlobStore: var dsmsAzureStorage = (System.Fabric.BackupRestore.Common.Model.DsmsAzureBlobBackupStorageInfo)backupPolicyModel.Storage; backupPolicy.StoreInformation = new DsmsAzureBlobBackupStore { StorageCredentialsSourceLocation = dsmsAzureStorage.StorageCredentialsSourceLocation, ContainerName = dsmsAzureStorage.ContainerName, FolderPath = UtilityHelper.GetBaseDirectoryPathForPartition(serviceNameUri, backupPartitionInfo.PartitionId.ToString()), }; break; } return(backupPolicy); }
private void InitGlobalSearchConfig() { try { var authComponent = ComponentFactory.GetComponent <IAuth>(); var configComponent = ComponentFactory.GetComponent <IConfiguration>(); var configValue = configComponent.GetConfigValue("Framework", "GlobalSearchConfig"); if (!configValue.IsNullOrEmpty()) { var list = UtilityHelper.XmlDeserialize <List <GlobalSearchModel> >(configValue); if (list != null && list.Count > 0) { foreach (var item in list) { if (authComponent.HasFunctionForPage(item.BaseUrl)) { item.Name = GetKeyDescription(item.QuickKey).IsNullOrEmpty() ? item.Name : string.Format("{0}[{1}]", item.Name, GetKeyDescription(item.QuickKey)); m_globalSearchModel.Add(item); } } if (m_globalSearchModel.Count > 0) { CbGlobalSearchType.DataContext = new GlobalSearchModel(); CbGlobalSearchType.ItemsSource = m_globalSearchModel; var value = ComponentFactory.GetComponent <IUserProfile>().Get <GlobalSearchModel>(UserProfileKey.Key_GlobalSearch); if (value != null) { var selectedValue = m_globalSearchModel.FirstOrDefault(p => p.UrlTemplate == value.UrlTemplate); if (selectedValue != null) { CbGlobalSearchType.SelectedItem = selectedValue; } else { CbGlobalSearchType.SelectedIndex = 0; } } else { CbGlobalSearchType.SelectedIndex = 0; } } else { this.Visibility = Visibility.Collapsed; } } else { this.Visibility = Visibility.Collapsed; } } else { this.Visibility = Visibility.Collapsed; } } catch (Exception ex) { this.Visibility = Visibility.Collapsed; ComponentFactory.Logger.LogError(ex); } }
internal override async Task <HttpResponseMessage> RunAsync(TimeSpan timeout, CancellationToken cancellationToken) { string applicationNameUri; string serviceNameUri; string partitionId; var fabricUri = await UtilityHelper.GetFabricUriFromRequstHeader(this.fabricRequestHeader, timeout, cancellationToken); WorkItem workItem = null; FabricBackupResourceType fabricBackupResourceType = UtilityHelper.GetApplicationAndServicePartitionUri(fabricUri, out applicationNameUri, out serviceNameUri, out partitionId); bool isApplicationOrServiceExisting; switch (fabricBackupResourceType) { case FabricBackupResourceType.ApplicationUri: isApplicationOrServiceExisting = await this.IsApplicationOrServiceExisting(fabricBackupResourceType, applicationNameUri, null, timeout, cancellationToken); if (isApplicationOrServiceExisting) { workItem = new ResolveToPartitionWorkItem(FabricBackupResourceType.ApplicationUri, applicationNameUri, new WorkItemInfo { WorkItemType = WorkItemPropogationType.Disable, }); } break; case FabricBackupResourceType.ServiceUri: isApplicationOrServiceExisting = await this.IsApplicationOrServiceExisting(fabricBackupResourceType, serviceNameUri, null, timeout, cancellationToken); if (isApplicationOrServiceExisting) { workItem = new ResolveToPartitionWorkItem(FabricBackupResourceType.ServiceUri, serviceNameUri, new WorkItemInfo { WorkItemType = WorkItemPropogationType.Disable, }); } break; case FabricBackupResourceType.PartitionUri: isApplicationOrServiceExisting = await this.IsApplicationOrServiceExisting(fabricBackupResourceType, serviceNameUri, partitionId, timeout, cancellationToken); if (isApplicationOrServiceExisting) { serviceNameUri = await FabricClientHelper.GetFabricServiceUriFromPartitionId(partitionId, timeout, cancellationToken); workItem = new SendToServiceNodeWorkItem(serviceNameUri, partitionId, new WorkItemInfo { WorkItemType = WorkItemPropogationType.Disable, }); } break; case FabricBackupResourceType.Error: throw new ArgumentException(StringResources.InvalidArguments); } if (workItem == null) { using (var transaction = this.StatefulService.StateManager.CreateTransaction()) { var backupMapping = await this.BackupMappingStore.GetValueWithUpdateLockModeAsync(fabricUri, timeout, cancellationToken, transaction); if (backupMapping == null) { throw new FabricPeriodicBackupNotEnabledException(); } var assignedBackupPolicy = await this.BackupPolicyStore.GetValueWithUpdateLockModeAsync(backupMapping.BackupPolicyName, timeout, cancellationToken, transaction); await this.BackupMappingStore.DeleteValueAsync(fabricUri, timeout, cancellationToken, transaction); await this.BackupPolicyStore.RemoveProtectionEntity(assignedBackupPolicy, fabricUri, timeout, cancellationToken, transaction); await transaction.CommitAsync(); } } else { RetentionManager retentionManager = await RetentionManager.CreateOrGetRetentionManager(this.StatefulService); using (var transaction = this.StatefulService.StateManager.CreateTransaction()) { var backupMapping = await this.BackupMappingStore.GetValueWithUpdateLockModeAsync(fabricUri, timeout, cancellationToken, transaction); if (backupMapping == null) { throw new FabricPeriodicBackupNotEnabledException(); } var assignedBackupPolicy = await this.BackupPolicyStore.GetValueWithUpdateLockModeAsync(backupMapping.BackupPolicyName, timeout, cancellationToken, transaction); await this.BackupMappingStore.DeleteValueAsync(fabricUri, timeout, cancellationToken, transaction); await this.BackupPolicyStore.RemoveProtectionEntity(assignedBackupPolicy, fabricUri, timeout, cancellationToken, transaction); await this.WorkItemQueue.AddWorkItem(workItem, timeout, cancellationToken, transaction); if (cleanBackups) { await retentionManager.DisablePolicyAsync(fabricUri, backupMapping, timeout, cancellationToken, transaction); } await transaction.CommitAsync(); } } return(new HttpResponseMessage(HttpStatusCode.Accepted)); }
public void PlaceProductAtAnchorFacingCamera(Transform anchor) { PlaceProductAtAnchor(anchor); UtilityHelper.RotateTowardCamera(this.chair); }
internal static String CreateLocationRequest(String bRequest, String gpsLocation = null, String ipAddress = null, String country_code = null, String city = null) { Debug.Assert(bRequest != null); if (bRequest == null) { return(null); } if (gpsLocation != null || ipAddress != null || country_code != null || city != null) { String res = null; String rGps = gpsLocation == null ? null : String.Format("&location={0}", UtilityHelper.EncodeDataForURL(gpsLocation)); String rIp = ipAddress == null ? null : String.Format("&ip={0}", UtilityHelper.EncodeDataForURL(ipAddress)); String rCountry = country_code == null ? null : String.Format("&country_code={0}", UtilityHelper.EncodeDataForURL(country_code)); String rCity = city == null ? null : String.Format("&city={0}", UtilityHelper.EncodeDataForURL(city)); res = String.Format("{0}{1}{2}{3}{4}", bRequest, rGps, rIp, rCountry, rCity); return(res); } return(null); }
protected string GetTemporaryBucket() { return(UtilityHelper.GetTemporaryBucket()); }
protected void btnSearch_Click(object sender, EventArgs e) { string strWhere = string.Empty, strTableName = string.Empty; List <string> listWhere = new List <string>(); bool isJoinMembership = false, isJoinUsers = false; try { //查询条件:是否在线 if (this.ddlIsOnline.SelectedIndex == 0) { this.ddlIsOnline.Style.Clear(); } else { if (this.ddlIsOnline.SelectedValue == "1") { UtilityHelper.AntiSQLInjection(this.ddlIsOnline.SelectedValue); listWhere.Add(string.Format("DATEADD(mi,-{0},GETDATE())<=aspnet_Users.LastActivityDate", Membership.UserIsOnlineTimeWindow + 480)); this.ddlIsOnline.Style.Add("background-color", CRITERIA_BG_COLOR.Name); isJoinUsers = true; } else { UtilityHelper.AntiSQLInjection(this.ddlIsOnline.SelectedValue); listWhere.Add(string.Format("DATEADD(mi,-{0},GETDATE())>aspnet_Users.LastActivityDate", Membership.UserIsOnlineTimeWindow + 480)); this.ddlIsOnline.Style.Add("background-color", CRITERIA_BG_COLOR.Name); isJoinUsers = true; } } //查询条件:是否订阅微信公众号 if (this.ddlIsSubscribe.SelectedIndex != 0) { UtilityHelper.AntiSQLInjection(this.ddlIsSubscribe.SelectedValue); listWhere.Add(string.Format("WeChatUsers.IsSubscribe = {0}", this.ddlIsSubscribe.SelectedValue)); this.ddlIsSubscribe.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.ddlIsSubscribe.Style.Clear(); } //查询条件:性别 if (this.ddlSex.SelectedIndex != 0) { UtilityHelper.AntiSQLInjection(this.ddlSex.SelectedValue); listWhere.Add(string.Format("WeChatUsers.Sex = {0}", this.ddlSex.SelectedValue)); this.ddlSex.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.ddlSex.Style.Clear(); } //查询条件:是否允许登录 if (this.ddlIsApproved.SelectedIndex != 0) { UtilityHelper.AntiSQLInjection(this.ddlIsApproved.SelectedValue); listWhere.Add(string.Format("aspnet_Membership.IsApproved = {0}", this.ddlIsApproved.SelectedValue)); this.ddlIsApproved.Style.Add("background-color", CRITERIA_BG_COLOR.Name); isJoinMembership = true; } else { this.ddlIsApproved.Style.Clear(); } //查询条件:微信昵称 if (!string.IsNullOrEmpty(this.txtNickName.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtNickName.Text); listWhere.Add(string.Format("WeChatUsers.NickName like '%{0}%'", this.txtNickName.Text.Trim())); this.txtNickName.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.txtNickName.Style.Clear(); } //查询条件:国家 if (!string.IsNullOrEmpty(this.txtCountry.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtCountry.Text); listWhere.Add(string.Format("WeChatUsers.Country like '%{0}%'", this.txtCountry.Text.Trim())); this.txtCountry.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.txtCountry.Style.Clear(); } //查询条件:省份 if (!string.IsNullOrEmpty(this.txtProvince.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtProvince.Text); listWhere.Add(string.Format("WeChatUsers.Province like '%{0}%'", this.txtProvince.Text.Trim())); this.txtProvince.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.txtProvince.Style.Clear(); } //查询条件:城市 if (!string.IsNullOrEmpty(this.txtCity.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtCountry.Text); listWhere.Add(string.Format("WeChatUsers.City like '%{0}%'", this.txtCity.Text.Trim())); this.txtCity.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.txtCity.Style.Clear(); } //查询条件:开始注册日期 if (!string.IsNullOrEmpty(this.txtStartCreationDate.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtStartCreationDate.Text); listWhere.Add(string.Format("CONVERT(varchar(8), aspnet_Membership.CreateDate, 112) >= '{0}'", this.txtStartCreationDate.Text.Trim().Replace("-", ""))); this.txtStartCreationDate.Style.Add("background-color", CRITERIA_BG_COLOR.Name); isJoinMembership = true; } else { this.txtStartCreationDate.Style.Clear(); } //查询条件:结束注册日期 if (!string.IsNullOrEmpty(this.txtEndCreationDate.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtEndCreationDate.Text); listWhere.Add(string.Format("CONVERT(varchar(8), aspnet_Membership.CreateDate, 112) <= '{0}'", this.txtEndCreationDate.Text.Trim().Replace("-", ""))); this.txtEndCreationDate.Style.Add("background-color", CRITERIA_BG_COLOR.Name); isJoinMembership = true; } else { this.txtEndCreationDate.Style.Clear(); } //查询条件:开始活跃时间 if (!string.IsNullOrEmpty(this.txtStartLastActivityDate.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtStartLastActivityDate.Text); listWhere.Add(string.Format("CONVERT(varchar(8), DATEADD(hh,8,aspnet_Users.LastActivityDate), 112) >= '{0}'", this.txtStartLastActivityDate.Text.Trim().Replace("-", ""))); this.txtStartLastActivityDate.Style.Add("background-color", CRITERIA_BG_COLOR.Name); isJoinUsers = true; } else { this.txtStartLastActivityDate.Style.Clear(); } //查询条件:结束活跃时间 if (!string.IsNullOrEmpty(this.txtEndLastActivityDate.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtEndLastActivityDate.Text); listWhere.Add(string.Format("CONVERT(varchar(8), DATEADD(hh,8,aspnet_Users.LastActivityDate), 112) <= '{0}'", this.txtEndLastActivityDate.Text.Trim().Replace("-", ""))); this.txtEndLastActivityDate.Style.Add("background-color", CRITERIA_BG_COLOR.Name); isJoinUsers = true; } else { this.txtEndLastActivityDate.Style.Clear(); } strWhere = string.Join <string>(" and ", listWhere); this.odsUserList.SelectParameters["strWhere"].DefaultValue = strWhere; //根据查询涉及表做关联 strTableName = "WeChatUsers"; if (isJoinMembership) { strTableName += " left join aspnet_Membership on WeChatUsers.UserId = aspnet_Membership.UserId"; } if (isJoinUsers) { strTableName += " left join aspnet_Users on WeChatUsers.UserId = aspnet_Users.UserId"; } this.odsUserList.SelectParameters["tableName"].DefaultValue = strTableName; this.gvUserList.PageIndex = 0; this.gvUserList.DataBind(); } catch (Exception ex) { ScriptManager.RegisterStartupScript(Page, this.GetType(), "jsWarn", string.Format("alert('{0}');", ex.Message), true); } }
public HttpResponseMessage DownloadCSV(string dataType, string lang) { DBConnection dbConnection = new DBConnection(lang); var jsonResult = string.Empty; var fileNameDate = string.Format("{0}{1}{2}", DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString().PadLeft(2, '0'), DateTime.Now.Day.ToString().PadLeft(2, '0')); var fileName = string.Format(dataType + "_{0}.csv", fileNameDate); byte[] outputBuffer = null; string resultString = string.Empty; HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); var json = string.Empty; switch (dataType) { case "medicinalIngredient": var medicinalIngredient = dbConnection.GetAllMedicinalIngredient(lang).ToList(); if (medicinalIngredient.Count > 0) { json = JsonConvert.SerializeObject(medicinalIngredient); } break; case "nonMedicinalIngredient": var nonMedicinalIngredient = dbConnection.GetAllNonMedicinalIngredient(lang).ToList(); if (nonMedicinalIngredient.Count > 0) { json = JsonConvert.SerializeObject(nonMedicinalIngredient); } break; //case "ingQuantity": // var ingQuantity = dbConnection.GetAllIngredientQuantity(lang).ToList(); // if (ingQuantity.Count > 0) // { // json = JsonConvert.SerializeObject(ingQuantity); // } // break; //case "ingSource": // var ingSource = dbConnection.GetAllIngredientSource(lang).ToList(); // if (ingSource.Count > 0) // { // json = JsonConvert.SerializeObject(ingSource); // } // break; //case "ingSubmission": // var ingSubmission = dbConnection.GetAllIngredientSubmission(lang).ToList(); // if (ingSubmission.Count > 0) // { // json = JsonConvert.SerializeObject(ingSubmission); // } // break; case "productDose": var productDose = dbConnection.GetAllProductDose(lang).ToList(); if (productDose.Count > 0) { json = JsonConvert.SerializeObject(productDose); } break; case "productLicence": var productLicence = dbConnection.GetAllProductLicence(lang).ToList(); if (productLicence.Count > 0) { json = JsonConvert.SerializeObject(productLicence); } break; case "productPurpose": var productPurpose = dbConnection.GetAllProductPurpose(lang).ToList(); if (productPurpose.Count > 0) { json = JsonConvert.SerializeObject(productPurpose); } break; case "productRisk": var productRisk = dbConnection.GetAllProductRisk(lang).ToList(); if (productRisk.Count > 0) { json = JsonConvert.SerializeObject(productRisk); } break; case "productRoute": var productRoute = dbConnection.GetAllProductRoute(lang).ToList(); if (productRoute.Count > 0) { json = JsonConvert.SerializeObject(productRoute); } break; } if (!string.IsNullOrWhiteSpace(json)) { DataTable dt = JsonConvert.DeserializeObject<DataTable>(json); if (dt.Rows.Count > 0) { using (MemoryStream stream = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(stream)) { UtilityHelper.WriteDataTable(dt, writer, true); outputBuffer = stream.ToArray(); resultString = Encoding.UTF8.GetString(outputBuffer, 0, outputBuffer.Length); } } result.Content = new StringContent(resultString); result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; } } return result; }
protected void btnSearch_Click(object sender, EventArgs e) { string strWhere = string.Empty, tableName = string.Empty; List <string> listWhere = new List <string>(); try { //查询条件:支付方式 if (this.ddlPaymentTerm.SelectedIndex != 0) { UtilityHelper.AntiSQLInjection(this.ddlPaymentTerm.SelectedValue); listWhere.Add(string.Format("PaymentTerm = {0}", this.ddlPaymentTerm.SelectedValue)); this.ddlPaymentTerm.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.ddlPaymentTerm.Style.Clear(); } //查询条件:支付状态 if (this.ddlTradeState.SelectedIndex != 0) { UtilityHelper.AntiSQLInjection(this.ddlTradeState.SelectedValue); listWhere.Add(string.Format("TradeState = {0}", this.ddlTradeState.SelectedValue)); this.ddlTradeState.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.ddlTradeState.Style.Clear(); } //查询条件:发货状态 if (this.ddlIsDelivery.SelectedIndex != 0) { UtilityHelper.AntiSQLInjection(this.ddlIsDelivery.SelectedValue); listWhere.Add(string.Format("IsDelivered = {0}", this.ddlIsDelivery.SelectedValue)); this.ddlIsDelivery.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.ddlIsDelivery.Style.Clear(); } //查询条件:签收状态 if (this.ddlIsAccept.SelectedIndex != 0) { UtilityHelper.AntiSQLInjection(this.ddlIsAccept.SelectedValue); listWhere.Add(string.Format("IsAccept = {0}", this.ddlIsAccept.SelectedValue)); this.ddlIsAccept.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.ddlIsAccept.Style.Clear(); } //查询条件:撤单状态 if (this.ddlIsCancel.SelectedIndex != 0) { UtilityHelper.AntiSQLInjection(this.ddlIsCancel.SelectedValue); listWhere.Add(string.Format("IsCancel = {0}", this.ddlIsCancel.SelectedValue)); this.ddlIsCancel.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.ddlIsCancel.Style.Clear(); } //查询条件:收货人姓名 if (!string.IsNullOrEmpty(this.txtReceiverName.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtReceiverName.Text); listWhere.Add(string.Format("DeliverName like '%{0}%'", this.txtReceiverName.Text.Trim())); this.txtReceiverName.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.txtReceiverName.Style.Clear(); } //查询条件:收货人电话 if (!string.IsNullOrEmpty(this.txtReceiverPhone.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtReceiverPhone.Text); listWhere.Add(string.Format("DeliverPhone like '%{0}%'", this.txtReceiverPhone.Text.Trim())); this.txtReceiverPhone.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.txtReceiverPhone.Style.Clear(); } //查询条件:订单ID if (!string.IsNullOrEmpty(this.txtOrderID.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtOrderID.Text); listWhere.Add(string.Format("OrderID like '%{0}%'", this.txtOrderID.Text.Trim())); this.txtOrderID.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.txtOrderID.Style.Clear(); } //查询条件:团购活动ID if (!string.IsNullOrEmpty(this.txtGroupEventID.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtGroupEventID.Text); listWhere.Add(string.Format("Id in (select PoID from OrderDetail where GroupEventID = {0})", this.txtGroupEventID.Text.Trim())); this.txtGroupEventID.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.txtGroupEventID.Style.Clear(); } //查询条件:订单商品详情 if (!string.IsNullOrEmpty(this.txtOrderDetail.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtOrderDetail.Text); listWhere.Add(string.Format("Id in (select PoID from OrderDetail where OrderProductName like '%{0}%')", this.txtOrderDetail.Text.Trim())); this.txtOrderDetail.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.txtOrderDetail.Style.Clear(); } //查询条件:微信支付交易号 if (!string.IsNullOrEmpty(this.txtTransactionID.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtTransactionID.Text); listWhere.Add(string.Format("TransactionID like '%{0}%'", this.txtTransactionID.Text.Trim())); this.txtTransactionID.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.txtTransactionID.Style.Clear(); } //查询条件:支付宝交易号 if (!string.IsNullOrEmpty(this.txtTradeNo.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtTradeNo.Text); listWhere.Add(string.Format("AP_TradeNo like '%{0}%'", this.txtTradeNo.Text.Trim())); this.txtTransactionID.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.txtTradeNo.Style.Clear(); } //查询条件:订单开始日期 if (!string.IsNullOrEmpty(this.txtStartOrderDate.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtStartOrderDate.Text); listWhere.Add(string.Format("CONVERT(varchar(8), OrderDate, 112) >= '{0}'", this.txtStartOrderDate.Text.Trim().Replace("-", ""))); this.txtStartOrderDate.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.txtStartOrderDate.Style.Clear(); } //查询条件:订单结束日期 if (!string.IsNullOrEmpty(this.txtEndOrderDate.Text.Trim())) { UtilityHelper.AntiSQLInjection(this.txtEndOrderDate.Text); listWhere.Add(string.Format("CONVERT(varchar(8), OrderDate, 112) <= '{0}'", this.txtEndOrderDate.Text.Trim().Replace("-", ""))); this.txtEndOrderDate.Style.Add("background-color", CRITERIA_BG_COLOR.Name); } else { this.txtEndOrderDate.Style.Clear(); } strWhere = string.Join <string>(" and ", listWhere); this.gvOrderList.PageIndex = 0; this.odsOrderList.SelectParameters["strWhere"].DefaultValue = strWhere; this.gvOrderList.DataBind(); } catch (Exception ex) { ScriptManager.RegisterStartupScript(Page, this.GetType(), "jsWarn", string.Format("alert('{0}');", ex.Message), true); } }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { try { string openID, agentOpenID, groupEventID, strWhere = string.Empty; if (Request.QueryString["OpenID"] != null) { UtilityHelper.AntiSQLInjection(Request.QueryString["OpenID"]); openID = Request.QueryString["OpenID"]; strWhere = string.Format("OpenID='{0}'", openID); } if (Request.QueryString["AgentOpenID"] != null) { UtilityHelper.AntiSQLInjection(Request.QueryString["AgentOpenID"]); agentOpenID = Request.QueryString["AgentOpenID"]; strWhere = string.Format("AgentOpenID='{0}'", agentOpenID); } if (Request.QueryString["GroupEventID"] != null) { UtilityHelper.AntiSQLInjection(Request.QueryString["GroupEventID"]); groupEventID = Request.QueryString["GroupEventID"]; this.txtGroupEventID.Text = groupEventID; this.txtGroupEventID.Style.Add("background-color", CRITERIA_BG_COLOR.Name); strWhere = string.Format("Id in (select PoID from OrderDetail where GroupEventID = {0})", groupEventID); } this.odsOrderList.TypeName = "ProductOrder"; this.odsOrderList.EnablePaging = true; this.odsOrderList.SelectParameters.Add("strWhere", DbType.String, strWhere); this.odsOrderList.SelectParameters.Add("strOrder", DbType.String, string.Empty); this.odsOrderList.SelectParameters[this.odsOrderList.SelectParameters.Add("totalRows", DbType.Int32, "0")].Direction = ParameterDirection.Output; this.odsOrderList.SelectParameters[this.odsOrderList.SelectParameters.Add("payingOrderCount", DbType.Int32, "0")].Direction = ParameterDirection.Output; this.odsOrderList.SelectParameters[this.odsOrderList.SelectParameters.Add("deliveringOrderCount", DbType.Int32, "0")].Direction = ParameterDirection.Output; this.odsOrderList.SelectParameters[this.odsOrderList.SelectParameters.Add("acceptingOrderCount", DbType.Int32, "0")].Direction = ParameterDirection.Output; this.odsOrderList.SelectParameters[this.odsOrderList.SelectParameters.Add("cancelledOrderCount", DbType.Int32, "0")].Direction = ParameterDirection.Output; this.odsOrderList.SelectParameters[this.odsOrderList.SelectParameters.Add("totalOrderPrice", DbType.Decimal, "0")].Direction = ParameterDirection.Output; this.gvOrderList.AllowPaging = true; this.gvOrderList.AllowCustomPaging = true; this.gvOrderList.PageIndex = 0; this.gvOrderList.PageSize = Config.OrderListPageSize; this.ddlPaymentTerm.Items.Add(new ListItem("微信支付", ((int)PaymentTerm.WECHAT).ToString())); this.ddlPaymentTerm.Items.Add(new ListItem("支付宝", ((int)PaymentTerm.ALIPAY).ToString())); this.ddlPaymentTerm.Items.Add(new ListItem("货到付款", ((int)PaymentTerm.CASH).ToString())); this.ddlTradeState.Items.Add(new ListItem("===微信支付状态===", "-1")); this.ddlTradeState.Items.Add(new ListItem("支付成功", ((int)TradeState.SUCCESS).ToString())); this.ddlTradeState.Items.Add(new ListItem("转入退款", ((int)TradeState.REFUND).ToString())); this.ddlTradeState.Items.Add(new ListItem("未支付", ((int)TradeState.NOTPAY).ToString())); this.ddlTradeState.Items.Add(new ListItem("已关闭", ((int)TradeState.CLOSED).ToString())); this.ddlTradeState.Items.Add(new ListItem("已撤销(刷卡支付)", ((int)TradeState.REVOKED).ToString())); this.ddlTradeState.Items.Add(new ListItem("用户支付中", ((int)TradeState.USERPAYING).ToString())); this.ddlTradeState.Items.Add(new ListItem("支付失败", ((int)TradeState.PAYERROR).ToString())); this.ddlTradeState.Items.Add(new ListItem("===支付宝状态===", "-1")); this.ddlTradeState.Items.Add(new ListItem("等待买家付款", ((int)TradeState.AP_WAIT_BUYER_PAY).ToString())); this.ddlTradeState.Items.Add(new ListItem("等待卖家收款", ((int)TradeState.AP_TRADE_PENDING).ToString())); this.ddlTradeState.Items.Add(new ListItem("交易成功", ((int)TradeState.AP_TRADE_SUCCESS).ToString())); this.ddlTradeState.Items.Add(new ListItem("交易成功且结束", ((int)TradeState.AP_TRADE_FINISHED).ToString())); this.ddlTradeState.Items.Add(new ListItem("未支付已关闭", ((int)TradeState.AP_TRADE_CLOSED).ToString())); this.ddlTradeState.Items.Add(new ListItem("===货到付款状态===", "-1")); this.ddlTradeState.Items.Add(new ListItem("已付现金", ((int)TradeState.CASHPAID).ToString())); this.ddlTradeState.Items.Add(new ListItem("未付现金", ((int)TradeState.CASHNOTPAID).ToString())); this.txtDeliveryName.Text = Config.DeliveryName; this.txtDeliveryPhone.Text = Config.DeliveryPhone; } catch (Exception ex) { Response.Write(string.Format("<script>alert('{0}');history.back();</script>", ex.Message)); Response.End(); } } }
public static async Task <ResultResponse> SendException(string serverUrl, string appKey, string deviceId, ExceptionEvent exception) { string exceptionJson = JsonConvert.SerializeObject(exception, Formatting.None, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); return(await Call <ResultResponse>(String.Format("{0}/i?app_key={1}&device_id={2}&crash={3}", serverUrl, appKey, deviceId, UtilityHelper.EncodeDataForURL(exceptionJson)))); }
public static async Task <ResultResponse> SendEvents(string serverUrl, string appKey, string deviceId, List <CountlyEvent> events, CountlyUserDetails userDetails = null) { string eventsJson = JsonConvert.SerializeObject(events, Formatting.None, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); string userDetailsJson = String.Empty; if (userDetails != null) { userDetailsJson = "&user_details=" + UtilityHelper.EncodeDataForURL(JsonConvert.SerializeObject(userDetails, Formatting.None, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore })); } return(await Call <ResultResponse>(String.Format("{0}/i?app_key={1}&device_id={2}&events={3}{4}", serverUrl, appKey, deviceId, UtilityHelper.EncodeDataForURL(eventsJson), userDetailsJson))); }
public async Task <IHttpActionResult> Register([FromBody] TD_Register model) { if (!UtilityHelper.VerifyMobileCode(model.Mobile, model.Code, true)) { return(Json(new { Code = 1, Message = "验证码错误或已经失效" })); } DataBaseEntities db = new DataBaseEntities(); //判断该手机号是否可以注册 // string Id = Guid.NewGuid().ToString(); string UserName = Guid.NewGuid().ToString(); var user = new ApplicationUser() { Id = Id, UserName = UserName, MyMobilePhone = model.Mobile, RegisterTime = UtilityHelper.getNow(), EmailConfirmed = false, PhoneNumberConfirmed = false, AccessFailedCount = 0, LockoutEnabled = true, Sex = 2, //表示没有性别认定 Portrait = UtilityHelper.ConstVar.DefaultPortrait }; IdentityResult result = await Request.GetOwinContext().GetUserManager <ApplicationUserManager>().CreateAsync(user, model.Password); if (!result.Succeeded) { //注册不成功 return(Json(new { Code = 1, Message = "注册不成功" })); } else { //注册成功 #region 完成一些初始化工作 #endregion } string grant_type = "password"; ASCIIEncoding encoding = new ASCIIEncoding(); string postData = "grant_type=" + grant_type; postData += ("&password="******"&username="******"POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; myRequest.ContentLength = data.Length; Stream newStream = myRequest.GetRequestStream(); // Send the data. newStream.Write(data, 0, data.Length); newStream.Close(); // Get response HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default); string content = reader.ReadToEnd(); JavaScriptSerializer serializer = new JavaScriptSerializer(); Dictionary <string, object> json = (Dictionary <string, object>)serializer.DeserializeObject(content); string username = json["userName"].ToString(); var myuser = db.AspNetUsers.Single(u => u.UserName == username); return(Json(new { Code = 10000, Detail = new { token = json["access_token"].ToString(), IsValid = true, expired = json[".expires"].ToString(), //NickName = myuser.AspNetUsers.NickName, //UserName = myuser.AspNetUsers.UserName, Portrait = myuser.Portrait } })); }
public Expression GetDatabaseReadExpressionFromSecurity(Expression sourceExpression, Type type) { Expression loadExpression = null; if (permissionsProvider.GetPermissions().Count() > 0) { ParameterExpression parameterExpression = Expression.Parameter(type, "p"); bool allowReadLevelType = permissionProcessor.IsGranted(type, SecurityOperation.Read); if (allowReadLevelType) { IEnumerable <IObjectPermission> objectsDenyExpression = GetObjectPermissions(type).Where(p => p.OperationState == OperationState.Deny && p.Operations.HasFlag(SecurityOperation.Read)); if (objectsDenyExpression.Count() > 0) { IEnumerable <Expression> originalExpressions = GetBodiesOfLambdaExpressions(objectsDenyExpression.Select(p => p.Criteria)); IEnumerable <Expression> invertedExpressions = GetInvertedExpressions(originalExpressions); loadExpression = GetAndMergedExpression(invertedExpressions); } } else { IEnumerable <IObjectPermission> objectsAllowExpression = GetObjectPermissions(type).Where(p => p.OperationState == OperationState.Allow && p.Operations.HasFlag(SecurityOperation.Read)); if (objectsAllowExpression.Count() > 0) { IEnumerable <Expression> nativeExpression = GetBodiesOfLambdaExpressions(objectsAllowExpression.Select(p => p.Criteria)); loadExpression = GetOrMergedExpression(nativeExpression); IEnumerable <IObjectPermission> objectsDenyExpression = GetObjectPermissions(type).Where(p => p.OperationState == OperationState.Deny && p.Operations.HasFlag(SecurityOperation.Read)); nativeExpression = GetBodiesOfLambdaExpressions(objectsDenyExpression.Select(p => p.Criteria)); IEnumerable <Expression> invertedExpressions = GetInvertedExpressions(nativeExpression); Expression denyObjectExpression = GetAndMergedExpression(invertedExpressions); if (denyObjectExpression != null) { loadExpression = Expression.AndAlso(loadExpression, denyObjectExpression); } } IEnumerable <IMemberPermission> memberAllowExpression = GetMemberPermissions(type).Where(p => p.OperationState == OperationState.Allow && p.Operations.HasFlag(SecurityOperation.Read)); if (memberAllowExpression.Count() > 0) { Expression membersExpression = null; IEnumerable <IMemberPermission> memberDenyExpression = GetMemberPermissions(type).Where(p => p.OperationState == OperationState.Deny && p.Operations.HasFlag(SecurityOperation.Read)); IEnumerable <string> memberNames = memberAllowExpression.GroupBy(x => x.MemberName).Select(g => g.First().MemberName); foreach (string memberName in memberNames) { Expression memberExpression; IEnumerable <IMemberPermission> currentMemberAllowExpressions = memberAllowExpression.Where(p => p.MemberName == memberName); IEnumerable <Expression> nativeExpression = GetBodiesOfLambdaExpressions(currentMemberAllowExpressions.Select(p => p.Criteria)); memberExpression = GetOrMergedExpression(nativeExpression); IEnumerable <IMemberPermission> currentMemberDenyExpressions = memberDenyExpression.Where(p => p.MemberName == memberName); if (currentMemberDenyExpressions.Count() > 0) { nativeExpression = GetBodiesOfLambdaExpressions(currentMemberDenyExpressions.Select(p => p.Criteria)); IEnumerable <Expression> inversionExpression = GetInvertedExpressions(nativeExpression); Expression denyLoadObjectExpression = GetAndMergedExpression(inversionExpression); if (denyLoadObjectExpression != null) { memberExpression = Expression.AndAlso(memberExpression, denyLoadObjectExpression); } } if (membersExpression == null) { membersExpression = memberExpression; } else { membersExpression = Expression.OrElse(membersExpression, memberExpression); } } if (membersExpression != null) { if (loadExpression == null) { loadExpression = membersExpression; } else { loadExpression = Expression.OrElse(loadExpression, membersExpression); } } } if (loadExpression == null) { loadExpression = Expression.Constant(false); } } if (loadExpression != null) { UpdateParameterVisitor updateParameterVisitor = new UpdateParameterVisitor(realDbContext, parameterExpression); loadExpression = updateParameterVisitor.Visit(loadExpression); //loadExpression = Expression.Condition( // loadExpression, // Expression.Constant(true, typeof(bool)), // Expression.Constant(false, typeof(bool))); MethodInfo whereMethodInfo = UtilityHelper.GetMethods("Where", type, 1).First().MakeGenericMethod(type); Expression whereLambda = Expression.Lambda(loadExpression, parameterExpression); loadExpression = Expression.Call(whereMethodInfo, new[] { sourceExpression, whereLambda }); } else { loadExpression = sourceExpression; } } else { loadExpression = sourceExpression; } return(loadExpression); }
public void GenerateTradeNo_Test_NoLine() { var result = UtilityHelper.GenerateTradeNo(); Assert.IsFalse(result.Contains("-")); }
/// <summary> /// 设置查询条件 /// </summary> /// <typeparam name="TPropertyType"></typeparam> /// <param name="propertyName"></param> /// <param name="target"></param> /// <param name="value"></param> /// <param name="resourceType"></param> /// <param name="resourceName"></param> /// <param name="queryFilter"></param> /// <returns></returns> protected bool SetValue <TPropertyType>(string propertyName, ref TPropertyType target, TPropertyType value, Type resourceType, string resourceName, ref string queryFilter) { var result = base.SetValue(propertyName, ref target, value); string queryDesc = GetHeardValue(resourceType, resourceName); if (queryFilter == null) { queryFilter = ""; } if (!String.IsNullOrEmpty(queryDesc)) { queryFilter = RemoveValue(queryDesc, queryFilter); if (value == null) { queryFilter = RemoveValue(queryDesc, queryFilter); return(result); } if (value is string) { var tempValue = Convert.ToString(value).Trim(); if (string.IsNullOrEmpty(tempValue)) { return(result); } } if (typeof(TPropertyType).IsGenericType && typeof(TPropertyType).GetGenericTypeDefinition() == typeof(Nullable <>) && typeof(TPropertyType).GetGenericArguments().Length == 1) { var currentType = UtilityHelper.GetGenericType(value, typeof(TPropertyType)); if (currentType.IsEnum) { if (OnEnumChange != null) { var valueDesc = OnEnumChange(value); queryDesc = String.Format("【{0}={1}】", queryDesc, valueDesc); } } else { if (value != null) { queryDesc = String.Format("【{0}={1}】", queryDesc, value); } //if ((bool)Invoker.PropertyGet(typeof(TPropertyType), value, "HasValue", false, true)) //{ // var source = Invoker.PropertyGet(typeof(TPropertyType), value, "Value", false, true); // queryDesc = String.Format("【{0}={1}】", queryDesc, source); //} } } else if (typeof(TPropertyType).IsEnum) { var valueDesc = OnEnumChange(value); queryDesc = String.Format("【{0}={1}】", queryDesc, valueDesc); } else { queryDesc = String.Format("【{0}={1}】", queryDesc, value); } } queryFilter += queryDesc; return(result); }
public void GenerateTradeNo_Test_LengthIs32() { var result = UtilityHelper.GenerateTradeNo(); Assert.IsTrue(result.Length == 32); }
public async Task <RestorePointDetails> GetRestorePointDetailsAsync(BackupPartitionInfo backupPartitionInfo, TimeSpan timeout, CancellationToken cancellationToken) { BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "GetRestorePointDetailsAsync invoked for partition {0}", backupPartitionInfo.PartitionId); var restoreStore = await RestoreStore.CreateOrGetRestoreStatusStore(this.statefulService); var backupMappingStore = await BackupMappingStore.CreateOrGetBackupMappingStore(this.statefulService); var backupPolicyStore = await BackupPolicyStore.CreateOrGetBackupPolicyStore(this.statefulService); bool userInitiatedOperation; BackupStorage backupStorage; BackupStoreInformation backupStoreInformation = null; List <string> backupLocations; string brsServiceUri = await UtilityHelper.GetCustomServiceUri(backupPartitionInfo.ServiceName, timeout, cancellationToken); var fabricUri = UtilityHelper.GetBackupMappingKey(brsServiceUri, backupPartitionInfo.PartitionId.ToString()); var restoreStatus = await restoreStore.GetValueAsync(fabricUri); if (restoreStatus != null && ( restoreStatus.RestoreStatusState != RestoreState.Failure || restoreStatus.RestoreStatusState != RestoreState.Invalid || restoreStatus.RestoreStatusState != RestoreState.Success || restoreStatus.RestoreStatusState != RestoreState.Timeout)) { backupStorage = restoreStatus.BackupStorage; userInitiatedOperation = true; backupLocations = restoreStatus.BackupLocations.ToList(); } else { var backupMappingKey = UtilityHelper.GetBackupMappingKey(brsServiceUri, backupPartitionInfo.PartitionId.ToString()); var backupMappingModel = (await backupMappingStore.GetValueAsync(backupMappingKey) ?? await backupMappingStore.GetValueAsync(brsServiceUri)) ?? await backupMappingStore.GetValueAsync(UtilityHelper.GetApplicationNameFromService(brsServiceUri)); if (backupMappingModel == null) { throw new FabricPeriodicBackupNotEnabledException(); } var backupPolicy = await backupPolicyStore.GetValueAsync(backupMappingModel.BackupPolicyName); if (backupPolicy != null && backupPolicy.AutoRestore) { backupStorage = backupPolicy.Storage; userInitiatedOperation = false; string applicationName, serviceName; UtilityHelper.GetApplicationAndServiceNameFromServiceUri(brsServiceUri, out applicationName, out serviceName); // Get the latest backup now var backups = await backupStorage.GetBackupEnumerationsTask( applicationName, serviceName, backupPartitionInfo.PartitionId.ToString(), DateTime.MinValue, DateTime.MaxValue, true, cancellationToken); if (backups == null || backups.Count == 0) { throw new ArgumentException(); // TODO: Change this with appropriate exception } var backupDetail = backups.First(); var recoveryPointManager = RecoveryPointManagerFactory.GetRecoveryPointManager(backupStorage); backupLocations = await recoveryPointManager.GetBackupLocationsInBackupChainAsync(backupDetail.BackupLocation, cancellationToken); } else { throw new ArgumentException(); // TODO: Change with the OTher exception } } switch (backupStorage.BackupStorageType) { case BackupStorageType.FileShare: var fileShareStorage = (FileShareStorage)backupStorage; backupStoreInformation = new FileShareBackupStore { AccessType = String.IsNullOrEmpty(fileShareStorage.PrimaryUserName) ? FileShareAccessType.None : FileShareAccessType.DomainUser, FileSharePath = fileShareStorage.Path, PrimaryUserName = fileShareStorage.PrimaryUserName, PrimaryPassword = fileShareStorage.PrimaryPassword, SecondaryUserName = fileShareStorage.SecondaryUserName, SecondaryPassword = fileShareStorage.SecondaryPassword, IsPasswordEncrypted = fileShareStorage.IsPasswordEncrypted, }; break; case BackupStorageType.AzureBlobStore: var azureStorage = (AzureStorage)backupStorage; backupStoreInformation = new AzureBlobBackupStore { ConnectionString = azureStorage.ConnectionString, ContainerName = azureStorage.ContainerName, FolderPath = String.Empty, // TODO: This should be constructed IsAccountKeyEncrypted = azureStorage.IsConnectionStringEncrypted, }; break; case BackupStorageType.DsmsAzureBlobStore: var dsmsAzureStorage = (DsmsAzureStorage)backupStorage; backupStoreInformation = new DsmsAzureBlobBackupStore { StorageCredentialsSourceLocation = dsmsAzureStorage.StorageCredentialsSourceLocation, ContainerName = dsmsAzureStorage.ContainerName, FolderPath = String.Empty, // TODO: This should be constructed }; break; } Guid restoreOperationId = Guid.NewGuid(); if (userInitiatedOperation) { await UtilityHelper.InvokeWithRetry(async() => { using (ITransaction transaction = this.statefulService.StateManager.CreateTransaction()) { var currentRestoreStatus = await restoreStore.GetValueWithUpdateLockModeAsync(fabricUri, timeout, cancellationToken, transaction); restoreOperationId = currentRestoreStatus.RestoreRequestGuid; if (currentRestoreStatus.RestoreStatusState == RestoreState.Accepted) //TODO Check for Guid { var toUpdateRestoreStatus = currentRestoreStatus.ToBuilder().WithState(RestoreState.RestoreInProgress).Build(); await restoreStore.UpdateValueAsync(fabricUri, toUpdateRestoreStatus, timeout, cancellationToken, transaction); await transaction.CommitAsync(); } else { transaction.Abort(); } } }); } var restorePartitionDetails = new RestorePointDetails() { BackupLocations = backupLocations, UserInitiatedOperation = userInitiatedOperation, StoreInformation = backupStoreInformation, OperationId = restoreOperationId }; BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "GetRestorePointDetailsAsync invoked for partition {0} with Return Values {1}", backupPartitionInfo.PartitionId, restorePartitionDetails); return(restorePartitionDetails); }
public HttpResponseMessage DownloadCSV(string dataType, string lang) { DBConnection dbConnection = new DBConnection(lang); var jsonResult = string.Empty; var fileNameDate = string.Format("{0}{1}{2}", DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString().PadLeft(2, '0'), DateTime.Now.Day.ToString().PadLeft(2, '0')); var fileName = string.Format(dataType + "_{0}.csv", fileNameDate); byte[] outputBuffer = null; string resultString = string.Empty; HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); var json = string.Empty; switch (dataType) { case "drugProduct": var brand = dbConnection.GetAllDrugProduct().ToList(); if (brand.Count > 0) { json = JsonConvert.SerializeObject(brand); } break; case "nocci": //notice of compliance complete information var nocci = dbConnection.GetAllNoticeOfComplianceMain().ToList(); if (nocci.Count > 0) { json = JsonConvert.SerializeObject(nocci); } break; //case "product": // var product = dbConnection.GetAllProduct().ToList(); // if (product.Count > 0) // { // json = JsonConvert.SerializeObject(product); // } // break; case "dosageForm": var dosageForm = dbConnection.GetAllDosageForm().ToList(); if (dosageForm.Count > 0) { json = JsonConvert.SerializeObject(dosageForm); } break; case "medicinalIngredient": var productIngredient = dbConnection.GetAllMedicinalIngredient().ToList(); if (productIngredient.Count > 0) { json = JsonConvert.SerializeObject(productIngredient); } break; case "route": var route = dbConnection.GetAllRoute().ToList(); if (route.Count > 0) { json = JsonConvert.SerializeObject(route); } break; case "vetSpecies": var vetSpecies = dbConnection.GetAllVetSpecies().ToList(); if (vetSpecies.Count > 0) { json = JsonConvert.SerializeObject(vetSpecies); } break; } if (!string.IsNullOrWhiteSpace(json)) { DataTable dt = JsonConvert.DeserializeObject <DataTable>(json); if (dt.Rows.Count > 0) { using (MemoryStream stream = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(stream)) { UtilityHelper.WriteDataTable(dt, writer, true); outputBuffer = stream.ToArray(); resultString = Encoding.UTF8.GetString(outputBuffer, 0, outputBuffer.Length); } } result.Content = new StringContent(resultString); result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; } } return(result); }
void BuildAllMenu(List <ItemData> data) { //Build Normal Menu UI List <ItemData> menuItems = data; if (menuItems == null) { return; } foreach (var item1 in menuItems) { var menuItem1 = new MenuItem { Text = item1.Name, DataContext = item1, Menu = this }; StackPanel stackPanelItem1 = new StackPanel(); menuItem1.MouseLeftButtonUp += new MouseButtonEventHandler(menuItem1_MouseLeftButtonUp); if (item1.SubItems != null) { foreach (var item2 in item1.SubItems) { StackPanel stackPanelItem2 = new StackPanel(); var menuItem2 = new MenuItem { Text = item2.Name, IsLevel2 = true, DataContext = item2, ParentNode = menuItem1, Menu = this }; menuItem2.MouseLeftButtonUp += new MouseButtonEventHandler(menuItem2_MouseLeftButtonUp); stackPanelItem1.Children.Add(menuItem2); if (item2.SubItems != null) { foreach (var item3 in item2.SubItems) { var menuItem3 = new SubMenuItemPanel { Menu = this, DataContext = item3, Tag = UtilityHelper.DeepClone(item1), ParentNode = menuItem2 }; menuItem3.ItemBinding = item3; stackPanelItem2.Children.Add(menuItem3); } } menuItem2.Tag = stackPanelItem2; } menuItem1.Tag = stackPanelItem1; StackPanelMenuContainer1.Children.Add(menuItem1); } } ItemData lastMenuItemData = ComponentFactory.GetComponent <IUserProfile>().Get <ItemData>(UserProfileKey.Key_AllStatus); if (lastMenuItemData == null) { //Initial Normal Menu UI if (StackPanelMenuContainer1.Children.Count > 0) { var menuItem1 = StackPanelMenuContainer1.Children[0] as MenuItem; BuildSubLevel2(menuItem1); if (menuItem1 != null && (StackPanel)((MenuItem)menuItem1).Tag != null && ((StackPanel)((MenuItem)menuItem1).Tag).Children.Count > 0) { var menuItem2 = ((StackPanel)((MenuItem)menuItem1).Tag).Children[0] as MenuItem; BuildSubLevel3(menuItem2); } } } else if (this.LastSubMenuItemInAll != null) { if (this.LastSubMenuItemInAll.ParentNode is SubMenuItem) { InitMenuSelected((MenuItem)((MenuItem)((SubMenuItem)this.LastSubMenuItemInAll.ParentNode).ParentNode).ParentNode, (MenuItem)((SubMenuItem)this.LastSubMenuItemInAll.ParentNode).ParentNode); } else { InitMenuSelected((MenuItem)((MenuItem)this.LastSubMenuItemInAll.ParentNode).ParentNode, (MenuItem)(this.LastSubMenuItemInAll).ParentNode); } } }
public override bool CheckCustomerWantCondiment() { return(UtilityHelper.GetUserConfirm("Do you want to add condiment?")); }
public void HandleInteractiveHitTest(HitTestResult result) { if (result == null) { Debug.LogError("Invalid hit test result!"); return; } if (!groundPlaneUI.IsCanvasButtonPressed()) { Debug.Log("HandleInteractiveHitTest() called."); // If the PlaneFinderBehaviour's Mode is Automatic, then the Interactive HitTestResult will be centered. // PlaneMode.Ground and PlaneMode.Placement both use PlaneFinder's ContentPositioningBehaviour this.contentPositioningBehaviour = this.planeFinder.GetComponent <ContentPositioningBehaviour>(); this.contentPositioningBehaviour.DuplicateStage = false; // Place object based on Ground Plane mode switch (CurrentPlaneMode) { case PlaneMode.GROUND: // With each tap, the Astronaut is moved to the position of the // newly created anchor. Before we set any anchor, we first want // to verify that the Status=TRACKED/EXTENDED_TRACKED and StatusInfo=NORMAL. if (TrackingStatusIsTrackedOrLimited) { this.contentPositioningBehaviour.AnchorStage = this.planeAnchor; this.contentPositioningBehaviour.PositionContentAtPlaneAnchor(result); UtilityHelper.EnableRendererColliderCanvas(this.planeAugmentation, true); // Astronaut should rotate toward camera with each placement this.planeAugmentation.transform.localPosition = Vector3.zero; UtilityHelper.RotateTowardCamera(this.planeAugmentation); } break; case PlaneMode.PLACEMENT: // With initial tap or a double-tap, a new anchor is created, // so we first check that Status=TRACKED/EXTENDED_TRACKED and StatusInfo=NORMAL // before proceeding. if (TrackingStatusIsTrackedOrLimited) { // If the product is yet to be placed when a tap occurs, // we assign our stage content, set an anchor and enable the // content. If a double-tap occurs, for instance when the content // has already been placed and positioned, then a new anchor // is placed and the stage is centered to it, but the content // retains its offset in relation to the stage. if (!this.productPlacement.IsPlaced || TouchHandler.DoubleTap) { this.contentPositioningBehaviour.AnchorStage = this.placementAnchor; this.contentPositioningBehaviour.PositionContentAtPlaneAnchor(result); UtilityHelper.EnableRendererColliderCanvas(placementAugmentation, true); } // Immediately following the steps above, we again confirm that the // IsPlaced flag has not been set and call SetProductAnchor to // reset the transform and rotation of the content in relation to the // stage collision plane. This only happens when setting the first // anchor or when reseting the scene. When double-tapping to simply // create a new anchor, the content retains its positional offset in // relation to the stage collision plane as well as its rotation. // The SetProductAnchor() will set the IsPlaced flag to true if the // transform argument is valid and to false if it is null. if (!this.productPlacement.IsPlaced) { this.productPlacement.SetProductAnchor(this.placementAnchor.transform); this.touchHandler.enableRotation = true; } } break; } } }
/// <summary> /// Shift elements by one /// </summary> /// <param name="n"></param> public static void ShiftMatrix(int[,] matrix) { int top = 0, bottom = matrix.GetLength(0) - 1; int left = 0, right = matrix.GetLength(1) - 1; int prev = matrix[0, 0]; UtilityHelper.PrintMatrix(matrix, matrix.GetLength(0), matrix.GetLength(1)); while (true) { if (left > right) { break; } // change top row for (int i = left; i <= right; i++) { // swap(matrix[top, i], prev); prev = matrix[top, i]; matrix[top, i] = prev; prev = matrix[top, i]; } top++; if (top > bottom) { break; } // change right column for (int i = top; i <= bottom; i++) { // swap(matrix[i, right], prev); prev = matrix[i, right]; matrix[i, right] = prev; prev = matrix[i, right]; } right--; if (left > right) { break; } // change bottom row for (int i = right; i >= left; i--) { // swap(matrix[bottom, i], prev); prev = matrix[bottom, i]; matrix[bottom, i] = prev; prev = matrix[bottom, i]; } bottom--; if (top > bottom) { break; } // change left column for (int i = bottom; i >= top; i--) { // swap(matrix[i, left], prev); // swap(matrix[bottom, i], prev); prev = matrix[i, left]; matrix[i, left] = prev; prev = matrix[i, left]; } left++; } // first element of the matrix will be the last element replaced matrix[0, 0] = prev; UtilityHelper.PrintMatrix(matrix, matrix.GetLength(0), matrix.GetLength(1)); Console.Read(); }
/// <summary> /// Change password /// </summary> /// <param name="request">Request</param> /// <returns>Result</returns> public virtual CustomerResult ChangePassword(ChangePasswordRequest request) { if (request == null) { throw new ArgumentNullException("request"); } var result = new CustomerResult(); if (string.IsNullOrWhiteSpace(request.Email)) { result.AddError("Account.ChangePassword.Errors.EmailIsNotProvided"); return(result); } if (string.IsNullOrWhiteSpace(request.NewPassword)) { result.AddError("Account.ChangePassword.Errors.PasswordIsNotProvided"); return(result); } var customer = _customerService.GetCustomerByEmail(request.Email); if (customer == null) { result.AddError("Account.ChangePassword.Errors.EmailNotFound"); return(result); } var requestIsValid = false; if (request.ValidateRequest) { //password string oldPwd = ""; switch (customer.PasswordFormat) { case PasswordFormat.Encrypted: oldPwd = _encryptionService.EncryptText(request.OldPassword); oldPwd = UtilityHelper.MD5(oldPwd); break; case PasswordFormat.Hashed: oldPwd = _encryptionService.CreatePasswordHash(request.OldPassword, customer.PasswordSalt, _customerSettings.HashedPasswordFormat); oldPwd = UtilityHelper.MD5(oldPwd); break; case PasswordFormat.Clear: default: oldPwd = UtilityHelper.TxtEnDes(request.OldPassword); break; } bool oldPasswordIsValid = oldPwd == customer.Password; if (!oldPasswordIsValid) { result.AddError("Account.ChangePassword.Errors.OldPasswordDoesntMatch"); } if (oldPasswordIsValid) { requestIsValid = true; } } else { requestIsValid = true; } //at this point request is valid if (requestIsValid) { switch (request.NewPasswordFormat) { case PasswordFormat.Encrypted: { customer.Password = _encryptionService.EncryptText(request.NewPassword); customer.Password = UtilityHelper.MD5(customer.Password); } break; case PasswordFormat.Hashed: { string saltKey = _encryptionService.CreateSaltKey(5); customer.PasswordSalt = saltKey; customer.Password = _encryptionService.CreatePasswordHash(request.NewPassword, saltKey, _customerSettings.HashedPasswordFormat); customer.Password = UtilityHelper.MD5(customer.Password); } break; case PasswordFormat.Clear: default: customer.Password = UtilityHelper.TxtEnDes(request.NewPassword); break; } customer.PasswordFormat = request.NewPasswordFormat; _customerService.UpdateCustomer(customer); } return(result); }
public void WarmUpShaders() { UtilityHelper.Log("Warm up all shaders."); }
public void Init(params object[] args) { UtilityHelper.Log("Battle team manager inited."); }
private void SetupBundleRelationships() { var bundle = AssetBundle.LoadFromFile(ManifestPath); if (bundle) { AssetBundleManifest abManifest = bundle.LoadAsset <AssetBundleManifest>("AssetBundleManifest"); if (abManifest == null) { Debug.LogError("Setup bundle info nodes failed, none manifest file... => " + ManifestPath); return; } //setup relationship assetBundleInfoNodes.Clear(); string[] assets = abManifest.GetAllAssetBundles(); foreach (var item in assets) { if (item.Contains("lua/")) { continue; } //Create bundle info node if (!assetBundleInfoNodes.ContainsKey(item.ToLower())) { AssetBundleInfoNode node = new AssetBundleInfoNode(item); assetBundleInfoNodes.Add(item.ToLower(), node); } } foreach (var item in assetBundleInfoNodes) { //Get dependencies string[] dependencies = abManifest.GetDirectDependencies(item.Key); foreach (var dependence in dependencies) { //Ignore shader bundle if (dependence.Contains("shaders.unity3d")) { continue; } if (assetBundleInfoNodes.ContainsKey(dependence.ToLower())) { AssetBundleInfoNode son = assetBundleInfoNodes[dependence]; AssetBundleInfoNode parent = item.Value; if (parent.dependentNode.Contains(son) || son.beDependentNode.Contains(parent)) { continue; } else { //Link son.beDependentNode.Add(parent); parent.dependentNode.Add(son); } } else { Debug.LogError(string.Format("Bundle node error: can not find out dependence node, file name : {0}", dependence)); } } } bundle.Unload(true); WarmUpShaders(); UtilityHelper.Log("======>> Bundle relationship compelted!! <<=========="); } else { Debug.LogError("Get manifest failed!! => " + ManifestPath); } }
public AppManager() { DataAccess = new AccessDB(dbINFO._SRV, dbINFO._CAT, dbINFO._UID, dbINFO._PWD); AppLogin = new AppLoginHelper(); Utility = new UtilityHelper(); SendMail = new MailHelper(); Report = new ReportHelper(Utility, dbINFO._SRV, dbINFO._CAT, dbINFO._UID, dbINFO._PWD); }
public static async Task <ResultResponse> BeginSession(string serverUrl, string appKey, string deviceId, string sdkVersion, string metricsJson) { return(await Call <ResultResponse>(String.Format("{0}/i?app_key={1}&device_id={2}&sdk_version={3}&begin_session=1&metrics={4}", serverUrl, appKey, deviceId, sdkVersion, UtilityHelper.EncodeDataForURL(metricsJson)))); }