private static void EnsureValidForCreation(Appointment appt) { var errors = new RulesException <Appointment>(); if (string.IsNullOrEmpty(appt.ClientName)) { errors.ErrorFor(x => x.ClientName, "Please specify a name"); } if (appt.AppointmentDate < DateTime.Now.Date) { errors.ErrorFor(x => x.AppointmentDate, "Can't book in the past"); } else if ((appt.AppointmentDate - DateTime.Now.Date).TotalDays > 7) { errors.ErrorFor(x => x.AppointmentDate, "Can't book more than a week in advance"); } if (appt.ClientName == "Steve" && appt.AppointmentDate.DayOfWeek == DayOfWeek.Saturday) { errors.ErrorForModel("Steve can't book on weekends"); } if (errors.Errors.Any()) { throw errors; } }
public void RulesExceptionUseCaseModelFoo() { var modelFoo = new ModelFoo { ModelFooId = 1, Name = "Test", ModelBar = new ModelBar { ModelBarId = 1, Name = "Test" } }; var rulesException = new RulesException <ModelFoo>(); // This will apply to the model as whole and should be used for // scenarios where there are multiple issues against another object. rulesException.ErrorForModel("There is already a ModelFoo with this Id and Name"); Assert.Single(rulesException.Errors); // Should be used for property issues. rulesException.ErrorFor(x => x.Name, "The Name is not Unique"); rulesException.ErrorFor(x => x.ModelBar.Name, "The Name is not Unique"); rulesException.ErrorFor("Name", "Another Error"); var errorMessage = rulesException.ToString(); Assert.Equal(4, rulesException.Errors.Count()); }
/// <summary> /// ตรวจสอบว่าข้อมูลที่กรอกเข้ามาถูกต้องหรือไม่ /// โดยเป็นส่วนของ logic ที่ไม่สามารถระบุใน metadata ไม่ได้ และไม่ได้ระบุเอาไว้ใน constraint ของ database /// </summary> /// <param name="reentry"></param> /// <param name="isCreate"></param> private void _validate(ReEntry reentry, bool isCreate) { var errors = new RulesException <ReEntry>(); if (reentry.Code != "") { int reentryId = 0; if (!isCreate) { reentryId = reentry.Id; } var oldCode = (from p in entities.ReEntrys where (p.Id != reentryId) && (p.Code == reentry.Code) && (p.RequestDate.Year == reentry.RequestDate.Year) && (!p.IsCancel) select p.Id).Count(); if (oldCode > 0) { errors.ErrorFor(x => x.Code, "Code ที่กรอก ซ้ำกับรายการอื่นในปีเดียวกัน"); } } if (errors.Errors.Any()) { throw errors; } }
internal static void ValidateExternalCss(ExternalCss externalCss, RulesException errors, int index, string[] duplicateUrls) { if (string.IsNullOrWhiteSpace(externalCss.Url)) { errors.ErrorForModel(string.Format(VisualEditorStrings.ExternalCssUrlRequired, index)); externalCss.Invalid = true; } else { if (duplicateUrls.Contains(externalCss.Url)) { errors.ErrorForModel(string.Format(VisualEditorStrings.ExternalCssUrlDuplicate, index)); externalCss.Invalid = true; } if (!UrlHelpers.IsValidWebFolderUrl(externalCss.Url)) { errors.ErrorForModel(string.Format(VisualEditorStrings.ExternalCssUrlNotValid, index)); externalCss.Invalid = true; } if (externalCss.Url.Length > 255) { errors.ErrorForModel(string.Format(VisualEditorStrings.ExternalCssUrlMaxLengthExceeded, index)); externalCss.Invalid = true; } } }
/// <summary> /// เรียกการบันทึกข้อมูล โดยตรวจสอบว่า Code ซ้ำหรือไม่ /// </summary> /// <param name="convInOut"></param> /// <param name="numRecursive">จำนวนที่ให้วน loop ปรกติไม่ต้องใส่มา</param> private void _saveCheckCode(ConveyanceInOut convInOut, int numRecursive = 5) { try { _checkCode(convInOut, convInOut.Id == 0); _save(); } catch (Exception ex) { //ถ้าซ้ำ ก็หา code ใหม่... if (ex.ExMessage() == "dupcode") { if (numRecursive > 0) { convInOut.Code = GetNewCode(); _saveCheckCode(convInOut, --numRecursive); //recursive } else { var clash = new RulesException <ConveyanceInOut>(); clash.ErrorFor(x => x.Code, "Sorry, error when generating the code."); throw clash; } } else { throw; } } }
public void ValidateModel(TModel model) { RulesException.ErrorsForValidationResults(ValidateModelProperties(model)); ValidateModelRules(model); RulesException.ThrowException(); }
public void Constructor_Should_Set_Property() { var errorInfo = new[] { new ErrorInfo("Dummy", "Error!") }; var exception = new RulesException(errorInfo); Assert.Equal(exception.Errors, errorInfo); }
public void Validate(RulesException <Db> errors, int index, string[] dupNames) { var messages = new List <string>(); if (string.IsNullOrWhiteSpace(Key)) { messages.Add(string.Format(DBStrings.KeyRequired, index)); } if (dupNames.Contains(Key)) { messages.Add(string.Format(DBStrings.KeyNotUnique, index)); } if (string.IsNullOrWhiteSpace(Value)) { messages.Add(string.Format(DBStrings.ValueRequired, index)); } if (Key.Length > 255) { messages.Add(string.Format(DBStrings.KeyMaxLengthExceeded, index)); } if (Value.Length > 255) { messages.Add(string.Format(DBStrings.ValueMaxLengthExceeded, index)); } Invalid = messages.Any(); foreach (var message in messages) { errors.ErrorForModel(message); } }
public void ValidateModel(TModel model) { ValidateModelPropertiesAndBuildRulesException(model); ValidateModelRules(model); RulesException.ThrowException(); }
/// <summary> /// ตรวจสอบว่าข้อมูลที่กรอกเข้ามาถูกต้องหรือไม่ /// โดยเป็นส่วนของ logic ที่ไม่สามารถระบุใน metadata ไม่ได้ และไม่ได้ระบุเอาไว้ใน constraint ของ database /// </summary> /// <param name="crew"></param> /// <param name="isCreate"></param> private void _validate(Crew crew, bool isCreate) { var errors = new RulesException <Crew>(); if (crew.Code != "") { int crewId = 0; if (!isCreate) { crewId = crew.Id; } var oldCode = (from p in entities.Crews where (p.Id != crewId) && (p.Code == crew.Code) && (p.IsCrew == crew.IsCrew) && !p.IsCancel && (p.ConveyanceInOutId == crew.ConveyanceInOutId) select p.Id).Count(); if (oldCode > 0) { errors.ErrorFor(x => x.Code, "Code ที่กรอก ซ้ำกับรายการอื่นในหน้านี้"); } } if (errors.Errors.Any()) { throw errors; } }
/// <summary> /// ตรวจสอบว่าข้อมูลที่กรอกเข้ามาถูกต้องหรือไม่ /// โดยเป็นส่วนของ logic ที่ไม่สามารถระบุใน metadata ไม่ได้ และไม่ได้ระบุเอาไว้ใน constraint ของ database /// </summary> /// <param name="visa"></param> /// <param name="isCreate"></param> private void _validate(VisaDetail visa, bool isCreate) { var errors = new RulesException <VisaDetail>(); if (string.IsNullOrWhiteSpace(visa.StayReasonDetail)) { errors.ErrorFor(x => x.Code, "เลือกข้อมูลระยะเวลาให้ถูกต้องด้วยค่ะ"); } if (visa.Code != "") { int visaId = 0; if (!isCreate) { visaId = visa.Id; } var oldCode = (from p in entities.VisaDetails where (p.Id != visaId) && (p.Code == visa.Code) && (p.RequestDate.Year == visa.RequestDate.Year) && (!p.IsCancel) select p.Id).Count(); if (oldCode > 0) { errors.ErrorFor(x => x.Code, "Code ที่กรอก ซ้ำกับรายการอื่นในปีเดียวกัน"); } } if (errors.Errors.Any()) { throw errors; } }
public override void Validate() { var errors = new RulesException <VisualEditorPlugin>(); base.Validate(errors); if (!string.IsNullOrEmpty(Url) && !UrlHelpers.IsValidWebFolderUrl(Url)) { errors.ErrorFor(n => Url, VisualEditorStrings.UrlPrefixInvalidFormat); } var duplicateCurrentNames = VeCommands.GroupBy(c => c.Name).Where(g => g.Count() > 1).Select(x => x.Key).ToArray(); var duplicateCurrentAliases = VeCommands.GroupBy(c => c.Alias).Where(g => g.Count() > 1).Select(x => x.Key).ToArray(); if (VeCommands.Count == 0) { errors.ErrorForModel(VisualEditorStrings.CommandsRequired); } else { var veCommandsArray = VeCommands.ToArray(); for (var i = 0; i < veCommandsArray.Length; i++) { ValidateVeCommand(veCommandsArray[i], errors, i + 1, duplicateCurrentNames, duplicateCurrentAliases); } } if (!errors.IsEmpty) { throw errors; } }
public async Task ValidateModelAsync(TModel model) { ValidateModelPropertiesAndBuildRulesException(model); await ValidateModelRulesAsync(model); RulesException.ThrowException(); }
/// <summary> /// ตรวจสอบว่าข้อมูลที่กรอกเข้ามาถูกต้องหรือไม่ /// โดยเป็นส่วนของ logic ที่ไม่สามารถระบุใน metadata ไม่ได้ และไม่ได้ระบุเอาไว้ใน constraint ของ database /// </summary> /// <param name="endorseStamp"></param> /// <param name="isCreate"></param> private void _validate(EndorseStamp endorseStamp, bool isCreate) { var errors = new RulesException <EndorseStamp>(); if (endorseStamp.Code != "") { int endorseStampId = 0; if (!isCreate) { endorseStampId = endorseStamp.Id; } var oldCode = (from p in entities.EndorseStamps where (p.Id != endorseStampId) && (p.Code == endorseStamp.Code) && (p.StampDate.Year == endorseStamp.StampDate.Year) select p.Id).Count(); if (oldCode > 0) { errors.ErrorFor(x => x.Code, "Code ที่กรอก ซ้ำกับรายการอื่นในปีเดียวกัน"); } } if (errors.Errors.Any()) { throw errors; } }
/// <summary> /// สร้าง code /// </summary> /// <returns>ถ้าแปลงเป็น Int ได้จะ return ตัวเลขให้ แต่ถ้าไม่ได้ ก็ส่ง error ไปแจ้ง</returns> private string _getNewCode(int refTypeId, string defaultCode) { if (defaultCode != null && defaultCode != "") { return(defaultCode); } string result = (from p in FindAll(refTypeId) select p.Code).DefaultIfEmpty("000").Max(); int iResult; try { iResult = Convert.ToInt32(result); } catch { iResult = -1; } if (iResult >= 0) { return((iResult + 1).ToString("D3")); } //ถ้าไม่สามารถแปลงได้ ให้ throw error แสดงให้ user เห็น var clash = new RulesException <zz_Reference>(); clash.ErrorFor(x => x.Code, "สร้างรหัสอัตโนมัติไม่ได้เนื่องจาก code เดิมไม่ใช่ตัวเลข"); throw clash; }
// // Persistance /// <summary> /// บันทึกข้อมูลลง database (ef) จริง ๆ /// </summary> private void _save() { try { entities.SaveChanges(); } catch (Exception ex) { //ตรวจสอบ error จาก sql server string exMessage = ex.ExMessage(); //เช็คค่า unique index ไม่ต้อง loop เช็คซ้ำอีกแล้ว if (exMessage.Contains("IX_zz_References_RefTypeId_Code")) { var clash = new RulesException <zz_Reference>(); clash.ErrorFor(x => x.Code, "รหัสซ้ำไม่ได้ค่ะ"); throw clash; } if (exMessage.Contains("IX_zz_References_RefTypeId_RefName")) { var clash = new RulesException <zz_Reference>(); clash.ErrorFor(x => x.RefName, "ความหมายซ้ำไม่ได้ค่ะ"); throw clash; } throw; // Rethrow any other exceptions to avoid interfering with them } }
// // Persistance /// <summary> /// บันทึกข้อมูลลง database (ef) จริง ๆ /// </summary> private void _save() { try { entities.SaveChanges(); } catch (Exception ex) { //ตรวจสอบ error จาก sql server string exMessage = ex.ExMessage(); //เช็คค่า unique index ไม่ต้อง loop เช็คซ้ำอีกแล้ว if (exMessage.Contains("IX_mst_Product_ProdCode")) { throw new ApplicationException("dupcode"); } if (exMessage.Contains("IX_mst_Product_ProdName")) { var clash = new RulesException <Alien>(); clash.ErrorFor(x => x.Name.FirstName, "Sorry, duplicate name not allowed"); throw clash; } throw; // Rethrow any other exceptions to avoid interfering with them } }
/// <summary> /// เรียกการบันทึกข้อมูล โดยตรวจสอบว่า Code ซ้ำหรือไม่ /// </summary> /// <param name="stay"></param> /// <param name="numRecursive">จำนวนที่ให้วน loop ปรกติไม่ต้องใส่มา</param> private void _saveCheckCode(Staying90Day stay, int numRecursive = 5) { try { _checkCode(stay, stay.Id == 0); _save(); } catch (Exception ex) { //ถ้าซ้ำ ก็หา code ใหม่... if (ex.ExMessage() == "dupcode") { if (numRecursive > 0) { stay.Code = GetNewCode(); _saveCheckCode(stay, --numRecursive); //recursive } else { var clash = new RulesException <Staying90Day>(); clash.ErrorFor(x => x.Code, "Sorry, error when generating the code."); throw clash; } } else { throw; } } }
public async Task ValidateModelAsync(TModel model) { RulesException.ErrorsForValidationResults(ValidateModelProperties(model)); await ValidateModelRulesAsync(model); RulesException.ThrowException(); }
public static void CopyTo <TModel>( this RulesException <TModel> ex, Controller controller, FlashEnum type = FlashEnum.Error) where TModel : class { if (ex.Errors.Count > 0) { controller.Flash(ex.Errors, type); } }
public static void CopyTo(this RulesException ex, ModelStateDictionary modelState, string prefix) { prefix = string.IsNullOrEmpty(prefix) ? "" : prefix + "."; foreach (var propertyError in ex.Errors) { string key = ExpressionHelper.GetExpressionText(propertyError.Property); modelState.AddModelError(prefix + key, propertyError.Message); } }
/// <summary> /// ตรวจสอบว่าข้อมูลที่กรอกเข้ามาถูกต้องหรือไม่ /// โดยเป็นส่วนของ logic ที่ไม่สามารถระบุใน metadata ไม่ได้ และไม่ได้ระบุเอาไว้ใน constraint ของ database /// </summary> /// <param name="conv"></param> /// <param name="isCreate"></param> private void _validate(Conveyance conv, bool isCreate) { var errors = new RulesException <Conveyance>(); if (errors.Errors.Any()) { throw errors; } }
public void Constructor_Should_Create_ErrorInfo_List_Without_Object() { var exception = new RulesException("Dummy", "Error!"); Assert.Equal(1, exception.Errors.Count()); Assert.Equal("Dummy", exception.Errors.First().PropertyName); Assert.Equal("Error!", exception.Errors.First().ErrorMessage); Assert.Equal(null, exception.Errors.First().Object); }
public void rules_base() { var foo = new RulesException <Foo>(); foo.ErrorForModel("Test1"); foo.ErrorForModel("Test2"); Assert.Equal(2, foo.ErrorMessages.Count); }
public RulesException ValidateXamlById(int articleId, string customerCode) { using (new QPConnectionScope(ConnectionString)) { var errors = new RulesException(); Article.ValidateXamlById(articleId, errors, customerCode); return(errors); } }
private void ValidateVeCommand(VisualEditorCommand command, RulesException errors, int index, IEnumerable <string> dupNames, IEnumerable <string> dupAliases) { if (!string.IsNullOrWhiteSpace(command.Name) && dupNames.Contains(command.Name)) { errors.ErrorForModel(string.Format(VisualEditorStrings.CommandNameDuplicate, index)); command.IsInvalid = true; } if (!string.IsNullOrWhiteSpace(command.Alias) && dupAliases.Contains(command.Alias)) { errors.ErrorForModel(string.Format(VisualEditorStrings.CommandAliasDuplicate, index)); command.IsInvalid = true; } if (string.IsNullOrWhiteSpace(command.Name)) { errors.ErrorForModel(string.Format(VisualEditorStrings.CommandNameRequired, index)); command.IsInvalid = true; } if (!string.IsNullOrWhiteSpace(command.Name) && Regex.IsMatch(command.Name, RegularExpressions.InvalidEntityName)) { errors.ErrorForModel(string.Format(VisualEditorStrings.CommandNameInvalidFormat, index)); command.IsInvalid = true; } if (string.IsNullOrWhiteSpace(command.Alias)) { errors.ErrorForModel(string.Format(VisualEditorStrings.CommandAliasRequired, index)); command.IsInvalid = true; } if (command.Name.Length > 255) { errors.ErrorForModel(string.Format(VisualEditorStrings.CommandNameMaxLengthExceeded, index)); command.IsInvalid = true; } if (command.Alias.Length > 255) { errors.ErrorForModel(string.Format(VisualEditorStrings.CommandAliasMaxLengthExceeded, index)); command.IsInvalid = true; } if (!VisualEditorRepository.IsCommandNameFree(command.Name, Id)) { errors.ErrorForModel(string.Format(VisualEditorStrings.CommandNameNonUnique, index)); command.IsInvalid = true; } if (!VisualEditorRepository.IsCommandAliasFree(command.Alias, Id)) { errors.ErrorForModel(string.Format(VisualEditorStrings.CommandAliasNonUnique, index)); command.IsInvalid = true; } }
public RulesException ValidateXamlById(int articleId, string customerCode, bool persistChanges = false) { var errors = new RulesException(); using (new QPConnectionScope(ConnectionInfo)) { QPContext.CurrentUserId = TestedUserId; Article.ValidateXamlById(articleId, errors, customerCode, persistChanges); QPContext.CurrentUserId = 0; } return(errors); }
/// <summary> /// เรียกการบันทึกข้อมูล โดยตรวจสอบว่า Code ซ้ำหรือไม่ /// </summary> /// <param name="reentry"></param> /// <param name="numRecursive">จำนวนที่ให้วน loop ปรกติไม่ต้องใส่มา</param> private void _saveCheckCode(ReEntry reentry, int numRecursive = 5) { try { _save(); } catch (Exception ex) { var clash = new RulesException <ReEntry>(); clash.ErrorFor(x => x.Code, "Error :" + ex.ExMessage()); throw clash; } }
/// <summary> /// เรียกการบันทึกข้อมูล โดยตรวจสอบว่า Code ซ้ำหรือไม่ /// </summary> /// <param name="endorseStamp"></param> /// <param name="numRecursive">จำนวนที่ให้วน loop ปรกติไม่ต้องใส่มา</param> private void _saveCheckCode(EndorseStamp endorseStamp, int numRecursive = 5) { try { _save(); } catch (Exception ex) { var clash = new RulesException <EndorseStamp>(); clash.ErrorFor(x => x, "Error :" + ex.ExMessage()); throw clash; } }
/// <summary> /// เรียกการบันทึกข้อมูล โดยตรวจสอบว่า Code ซ้ำหรือไม่ /// </summary> /// <param name="addRemoveCrew"></param> /// <param name="numRecursive">จำนวนที่ให้วน loop ปรกติไม่ต้องใส่มา</param> private void _saveCheckCode(AddRemoveCrew addRemoveCrew, int numRecursive = 5) { try { _save(); } catch (Exception ex) { var clash = new RulesException <AddRemoveCrew>(); clash.ErrorFor(x => x, "Error :" + ex.ExMessage()); throw clash; } }