/// <summary> /// 提交当前操作的结果 /// </summary> public int Commit() { try { int returnValue = Dbcontext.SaveChanges(); if (DbTransaction != null) { DbTransaction.Commit(); this.Close(); } return(returnValue); } catch (Exception ex) { if (ex.InnerException != null && ex.InnerException.InnerException is SqlException) { SqlException sqlEx = ex.InnerException.InnerException as SqlException; string msg = ExceptionMessageHelper.GetSqlExceptionMessage(sqlEx.Number); throw DataAccessException.ThrowDataAccessException(sqlEx, msg); } throw; } finally { if (DbTransaction == null) { this.Close(); } } }
private async Task <string> ConstructDetailsExceptionMessageAsync(Exception exception) { var retVal = await ExceptionMessageHelper.GetInnerMostExceptionMessageAsync(exception); retVal += $". {Constant.ErrorMessages.REFER_TO_ERRORS_TAB_FOR_MORE_DETAILS}"; return(retVal); }
/// <summary> /// 提交当前操作的结果 /// </summary> public int Commit() { try { if (SqlTransaction != null) { SqlTransaction.Commit(); this.Close(); } return(1); } catch (Exception ex) { if (ex.InnerException != null && ex.InnerException.InnerException is SqlException) { SqlException sqlEx = ex.InnerException.InnerException as SqlException; string msg = ExceptionMessageHelper.GetSqlExceptionMessage(sqlEx.Number); throw DataAccessException.ThrowDataAccessException(sqlEx, msg); } return(0); } finally { if (SqlTransaction == null) { this.Close(); } } }
private void CheckAuthentication(int RUserId, string TKey) { if (!Authentication.CheckTokenAuthentication(RUserId, TKey)) { Logger.AddLog(LogTypeEnum.Warn, "CustomerManager.CheckAuthentication", RUserId, ExceptionMessageHelper.UnauthorizedAccess(RUserId), null); throw new KnownException(ErrorTypeEnum.AuthorizeException, ExceptionMessageHelper.UnauthorizedAccess(RUserId), string.Empty); } }
public Course(string name, decimal price, DateTime startTime, DateTime endTime) { Name = name; Price = price; var isStartTimeBeforeEndTime = startTime <= endTime; var isWeekDayCorrect = DateHelper.AllowedDaysOfWeek.Contains(startTime.DayOfWeek) && DateHelper.AllowedDaysOfWeek.Contains(endTime.DayOfWeek); var isTimeCorrect = DateHelper.IsWorkTime(startTime) && DateHelper.IsWorkTime(endTime); if (isStartTimeBeforeEndTime && isWeekDayCorrect && isTimeCorrect) { StartTime = startTime; EndTime = endTime; return; } throw ExceptionMessageHelper.GetExceptionAndPopulateMessage(isWeekDayCorrect, isTimeCorrect); }
// POST api/<controller> public HttpResponseMessage Post([FromBody] Planting planting) { try { var parcelArea = planting.Parcel.ParcelAreas.FirstOrDefault(); if (parcelArea != null && parcelArea.MetricUnit == null) { parcelArea.MetricUnit = Context.MetricUnits.FirstOrDefault(mu => mu.Id == Context.Parcels.FirstOrDefault(p => p.Id == planting.Parcel.Id).ParcelAreas.FirstOrDefault().MetricUnit.Id); planting.Parcel.ParcelAreas = new List <ParcelArea>() { parcelArea }; } if (planting.PlantingCrops != null && planting.PlantingCrops.Count > 0) { foreach (var plantingCrop in planting.PlantingCrops) { plantingCrop.Crop = Context.Crops.FirstOrDefault(c => c.Id == plantingCrop.Crop.Id); plantingCrop.MetricUnit = Context.MetricUnits.FirstOrDefault(mu => mu.Id == plantingCrop.MetricUnit.Id); } } if (planting.PlantingFertilizers != null && planting.PlantingFertilizers.Count > 0) { foreach (var plantingFertilizer in planting.PlantingFertilizers) { plantingFertilizer.Fertilizer = Context.Fertilizers.FirstOrDefault(f => f.Id == plantingFertilizer.Fertilizer.Id); plantingFertilizer.MetricUnit = Context.MetricUnits.FirstOrDefault(mu => mu.Id == plantingFertilizer.MetricUnit.Id); } } if (planting.Yields != null && planting.Yields.Count > 0) { foreach (var yield in planting.Yields) { yield.MetricUnit = Context.MetricUnits.FirstOrDefault(mu => mu.Id == yield.MetricUnit.Id); } } var tempParcel = Context.Parcels.Include(p => p.ParcelAreas).FirstOrDefault(p => p.Id == planting.Parcel.Id); if (tempParcel != null) { tempParcel.GruntId = planting.Parcel.GruntId; tempParcel.Name = planting.Parcel.Name; tempParcel.OwnerName = planting.Parcel.OwnerName; var tempParcelAreas = tempParcel.ParcelAreas.ToList(); var tempPlantingParcelAreas = planting.Parcel.ParcelAreas.ToList(); for (int i = 0; i < tempParcelAreas.Count; i++) { var muId = tempPlantingParcelAreas[i].MetricUnit.Id; tempParcelAreas[i].MetricUnit = Context.MetricUnits.FirstOrDefault(mu => mu.Id == muId); tempParcelAreas[i].Quantity = tempPlantingParcelAreas[i].Quantity; } tempParcel.ParcelAreas = tempParcelAreas; planting.Parcel = tempParcel; } Context.Plantings.AddOrUpdate(planting); Context.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.Created, true)); } catch (Exception ex) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ExceptionMessageHelper.GetErrorMessage(ex))); } }
public CustomerAddressDto CreateOrUpdateCustomerAddress(CustomerAddressDto dto, int RequestUserId, string TokenKey) { try { CheckAuthentication(RequestUserId, TokenKey); #region Empty Control if (dto.CustomerId.IsNullOrEmpty()) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.CannotEmptyField, ExceptionMessageHelper.CannotEmptyField("Customer Id")); } if (dto.AddressTitle.IsNullOrEmpty()) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.CannotEmptyField, ExceptionMessageHelper.CannotEmptyField("Address Title")); } #endregion var data = GetAllCachedData <CustomerAddressDto>().ToList(); var entity = dto.ConvertTo <CustomerAdressEntitiy>(); var conn = Db.CreateConnection(true); if (dto.Id > 0) { entity.UpdateUser = RequestUserId; entity.UpdateDate = DateTimeHelper.Now; conn.Update(entity, Db._DbTransaction); data.RemoveAt(data.FindIndex(q => q.Id == entity.Id)); } else { int Id = conn.Insert(entity, Db._DbTransaction).ToInt(); entity = conn.Get <CustomerAdressEntitiy>(Id); } var result = entity.ConvertTo <CustomerAddressDto>(); data.Add(result); FillCacheData(data); return(result); } catch (KnownException ex) { throw ex; } catch (Exception ex) { Logger.AddLog(LogTypeEnum.Error, "CustomerManager.CreateOrUpdateCustomerAddress", RequestUserId, ex.Message, dto.ToJson(), ex); throw new KnownException(ErrorTypeEnum.UnexpectedExeption, ex.Message, ex); } }
// PUT api/<controller>/5 public HttpResponseMessage Put(int id, [FromBody] Crop crop) { try { var existingRecord = Context.Crops.FirstOrDefault(c => c.Id == id); if (existingRecord != null) { existingRecord.Name = crop.Name; existingRecord.Color = crop.Color; existingRecord.Description = crop.Description; existingRecord.ImageUrl = crop.ImageUrl; existingRecord.ImageName = crop.ImageName; Context.Crops.AddOrUpdate(existingRecord); Context.SaveChanges(); } return(Request.CreateResponse(HttpStatusCode.OK, true)); } catch (Exception ex) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Conflict, ExceptionMessageHelper.GetErrorMessage(ex))); } }
/// <summary> /// Throws <see cref="ArgumentException"/> if argument is <c>null</c> or argument is contains only whitespaces /// </summary> /// <exception cref="ArgumentException">Throws if argument is <c>null</c> or argument is contains only whitespaces</exception> public static Argument <string> NotNullOrWhitespace(this Argument <string> arg) { if (arg.ValidationIsDisabled()) { return(arg); } if (string.IsNullOrWhiteSpace(arg.Value)) { ValidationErrorExceptionThrower.ArgumentException(arg, $"Argument '{arg.Name}' cannot be empty or whitespace. Current value: {ExceptionMessageHelper.GetStringValueForMessage(arg.Value)}"); } return(arg); }
// PUT api/<controller>/5 public HttpResponseMessage Put(int id, [FromBody] Yield yield) { try { var existingRecord = Context.Amounts.OfType <Yield>().FirstOrDefault(y => y.AmountId == id); if (existingRecord != null) { existingRecord.Name = yield.Name; existingRecord.Quantity = yield.Quantity; existingRecord.MetricUnit = yield.MetricUnit; Context.Amounts.AddOrUpdate(existingRecord); Context.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, true)); } throw new Exception("Yield with id " + id + " not found."); } catch (Exception ex) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Conflict, ExceptionMessageHelper.GetErrorMessage(ex))); } }
// POST api/<controller> public HttpResponseMessage Post([FromBody] Fertilizer fertilizer) { try { Context.Fertilizers.Add(new Fertilizer() { Name = fertilizer.Name, Description = fertilizer.Description }); Context.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.Created, true)); } catch (Exception ex) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ExceptionMessageHelper.GetErrorMessage(ex))); } }
// PUT api/<controller>/5 public HttpResponseMessage Put(int id, [FromBody] MetricUnit metricUnit) { try { var existingRecord = Context.MetricUnits.FirstOrDefault(mu => mu.Id == id); if (existingRecord != null) { existingRecord.Name = metricUnit.Name; Context.MetricUnits.AddOrUpdate(existingRecord); Context.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, true)); } throw new Exception("Metric unit with id " + id + " not found."); } catch (Exception ex) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Conflict, ExceptionMessageHelper.GetErrorMessage(ex))); } }
private async Task <string> ConstructExceptionMessageAsync(Exception exception) { var retVal = await ExceptionMessageHelper.GetInnerMostExceptionMessageAsync(exception); return(retVal); }
// PUT api/<controller>/5 public HttpResponseMessage Put(int id, [FromBody] Planting planting) { try { var dbQuery = from p in Context.Plantings .Include(p => p.PlantingCrops.Select(pc => pc.MetricUnit)) .Include(p => p.PlantingCrops.Select(pc => pc.Crop)) .Include(p => p.PlantingFertilizers.Select(pa => pa.MetricUnit)) .Include(p => p.PlantingFertilizers.Select(pa => pa.Fertilizer)) .Include(p => p.Yields) .Include(p => p.Yields.Select(py => py.MetricUnit)) .Where(p => p.Id == id) select p; var existingRecord = dbQuery.FirstOrDefault(); Context.Entry(existingRecord).CurrentValues.SetValues(planting); if (existingRecord != null) { existingRecord.Season = planting.Season; #region Update PlantingCrops var plantingCropsToRemove = existingRecord.PlantingCrops.Where(existingPlantingCrop => planting.PlantingCrops.All(pc => !ObjectComparisonHelper.AreEqual(pc, existingPlantingCrop))).ToList(); if (plantingCropsToRemove.Count > 0) { foreach (var plantingCropToRemove in plantingCropsToRemove) { existingRecord.PlantingCrops.Remove(plantingCropToRemove); } } foreach (var plantingCrop in planting.PlantingCrops) { if (existingRecord.PlantingCrops.All(pc => !ObjectComparisonHelper.AreEqual(pc, plantingCrop))) { plantingCrop.Crop = Context.Crops.FirstOrDefault(c => c.Id == plantingCrop.Crop.Id); plantingCrop.MetricUnit = Context.MetricUnits.FirstOrDefault(mu => mu.Id == plantingCrop.MetricUnit.Id); existingRecord.PlantingCrops.Add(plantingCrop); } } #endregion #region Update PlantingFertilizers var plantingFertilizersToRemove = existingRecord.PlantingFertilizers.Where(existingPlantingFertilizer => planting.PlantingFertilizers.All(pf => !ObjectComparisonHelper.AreEqual(pf, existingPlantingFertilizer))).ToList(); if (plantingFertilizersToRemove.Count > 0) { foreach (var plantingFertilizerToRemove in plantingFertilizersToRemove) { existingRecord.PlantingFertilizers.Remove(plantingFertilizerToRemove); } } foreach (var plantingFertilizer in planting.PlantingFertilizers) { if (existingRecord.PlantingFertilizers.All(pf => !ObjectComparisonHelper.AreEqual(pf, plantingFertilizer))) { plantingFertilizer.Fertilizer = Context.Fertilizers.FirstOrDefault(c => c.Id == plantingFertilizer.Fertilizer.Id); plantingFertilizer.MetricUnit = Context.MetricUnits.FirstOrDefault(mu => mu.Id == plantingFertilizer.MetricUnit.Id); existingRecord.PlantingFertilizers.Add(plantingFertilizer); } } #endregion #region Update Yields var yieldsToRemove = existingRecord.Yields.Where(existingYield => planting.Yields.All(y => !ObjectComparisonHelper.AreEqual(y, existingYield))).ToList(); if (yieldsToRemove.Count > 0) { foreach (var yieldToRemove in yieldsToRemove) { existingRecord.Yields.Remove(yieldToRemove); } } foreach (var yield in planting.Yields) { if (existingRecord.Yields.All(y => !ObjectComparisonHelper.AreEqual(y, yield))) { yield.MetricUnit = Context.MetricUnits.FirstOrDefault(mu => mu.Id == yield.MetricUnit.Id); existingRecord.Yields.Add(yield); } } #endregion var tempParcel = Context.Parcels.Include(p => p.ParcelAreas).FirstOrDefault(p => p.Id == planting.Parcel.Id); if (tempParcel != null) { tempParcel.GruntId = planting.Parcel.GruntId; tempParcel.Name = planting.Parcel.Name; tempParcel.OwnerName = planting.Parcel.OwnerName; var tempParcelAreas = tempParcel.ParcelAreas.ToList(); var tempPlantingParcelAreas = planting.Parcel.ParcelAreas.ToList(); for (int i = 0; i < tempParcelAreas.Count; i++) { var muId = tempPlantingParcelAreas[i].MetricUnit.Id; tempParcelAreas[i].MetricUnit = Context.MetricUnits.FirstOrDefault(mu => mu.Id == muId); tempParcelAreas[i].Quantity = tempPlantingParcelAreas[i].Quantity; } tempParcel.ParcelAreas = tempParcelAreas; existingRecord.Parcel = tempParcel; } Context.Plantings.AddOrUpdate(existingRecord); Context.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, true)); } throw new Exception("Planting with id " + id + " not found."); } catch (Exception ex) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Conflict, ExceptionMessageHelper.GetErrorMessage(ex))); } }
public CustomerDto CreateOrUpdateCustomer(CustomerDto dto, int RequestUserId, string TokenKey) { try { CheckAuthentication(RequestUserId, TokenKey); #region Empty Control if (dto.UserName.IsNullOrEmpty()) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.CannotEmptyField, ExceptionMessageHelper.CannotEmptyField("User Name")); } if (dto.Password.IsNullOrEmpty()) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.CannotEmptyField, ExceptionMessageHelper.CannotEmptyField("Password")); } if (dto.FullName.IsNullOrEmpty()) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.CannotEmptyField, ExceptionMessageHelper.CannotEmptyField("Full Name")); } #endregion var data = GetAllCachedData <CustomerDto>().ToList(); #region Field Control if (data != null) { if (data.Any(q => q.UserName == dto.UserName)) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.IsInUse, ExceptionMessageHelper.IsInUse("UserName")); } } #endregion var entity = dto.ConvertTo <CustomerEntity>(); var Pass = PasswordHelper.GeneratePassword(6); entity.Password = (dto.Id > 0) ? PasswordHelper.EncryptData(dto.Password) : PasswordHelper.EncryptData(Pass); var conn = Db.CreateConnection(true); if (dto.Id > 0) { entity.UpdateUser = RequestUserId; entity.UpdateDate = DateTimeHelper.Now; conn.Update(entity, Db._DbTransaction); data.RemoveAt(data.FindIndex(q => q.Id == entity.Id)); } else { int Id = conn.Insert(entity, Db._DbTransaction).ToInt(); entity = conn.Get <CustomerEntity>(Id); } var result = entity.ConvertTo <CustomerDto>(); data.Add(result); FillCacheData(data); return(result); } catch (KnownException ex) { throw ex; } catch (Exception ex) { Logger.AddLog(LogTypeEnum.Error, "CustomerManager.CreateOrUpdateCustomer", RequestUserId, ex.Message, dto.ToJson(), ex); throw new KnownException(ErrorTypeEnum.UnexpectedExeption, ex.Message, ex); } }
// PUT api/<controller>/5 public HttpResponseMessage Put(int id, [FromBody] Parcel parcel) { try { var existingRecord = Context.Parcels.FirstOrDefault(p => p.Id == id); if (existingRecord != null) { if (parcel.ParcelAreas != null && parcel.ParcelAreas.Count > 0) { existingRecord.ParcelAreas = new List <ParcelArea>(); foreach (var parcelArea in parcel.ParcelAreas) { parcelArea.MetricUnit = Context.MetricUnits.FirstOrDefault(mu => mu.Id == parcelArea.MetricUnit.Id); existingRecord.ParcelAreas.Add(parcelArea); } } existingRecord.GruntId = parcel.GruntId; existingRecord.Name = parcel.Name; existingRecord.OwnerName = parcel.OwnerName; existingRecord.Points = parcel.Points; Context.Parcels.AddOrUpdate(existingRecord); Context.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, true)); } throw new Exception("Parcel with id " + id + " not found."); } catch (Exception ex) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Conflict, ExceptionMessageHelper.GetErrorMessage(ex))); } }
// POST api/<controller> public HttpResponseMessage Post([FromBody] Parcel parcel) { try { foreach (var parcelArea in parcel.ParcelAreas) { parcelArea.MetricUnit = Context.MetricUnits.FirstOrDefault(mu => mu.Id == parcelArea.MetricUnit.Id); } Context.Parcels.Add(parcel); Context.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.Created, true)); } catch (Exception ex) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ExceptionMessageHelper.GetErrorMessage(ex))); } }
// PUT api/<controller>/5 public HttpResponseMessage Put(int id, [FromBody] Fertilizer fertilizer) { try { var existingRecord = Context.Fertilizers.FirstOrDefault(f => f.Id == id); if (existingRecord != null) { existingRecord.Name = fertilizer.Name; existingRecord.Description = fertilizer.Description; Context.Fertilizers.AddOrUpdate(existingRecord); Context.SaveChanges(); } return(Request.CreateResponse(HttpStatusCode.OK, true)); } catch (Exception ex) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Conflict, ExceptionMessageHelper.GetErrorMessage(ex))); } }
public ProductTypeDto CreateOrUpdateProductType(ProductTypeDto dto, int RequestUserId, string TokenKey) { try { CheckAuthentication(RequestUserId, TokenKey); #region Empty Control if (dto.Name.IsNullOrEmpty()) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.CannotEmptyField, ExceptionMessageHelper.CannotEmptyField("Name")); } #endregion var data = GetAllCachedData <ProductTypeEntity>().ToList(); #region Field Control if (data != null) { if (data.Any(q => q.Name == dto.Name)) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.IsInUse, ExceptionMessageHelper.IsInUse("Name")); } } #endregion var entity = dto.ConvertTo <ProductTypeEntity>(); var conn = Db.CreateConnection(true); if (dto.Id > 0) { entity.UpdateUser = RequestUserId; entity.UpdateDate = DateTimeHelper.Now; conn.Update(entity, Db._DbTransaction); data.RemoveAt(data.FindIndex(q => q.Id == entity.Id)); } else { int Id = conn.Insert(entity, Db._DbTransaction).ToInt(); entity = conn.Get <ProductTypeEntity>(Id); } data.Add(entity); FillCacheData(data); return(entity.ConvertTo <ProductTypeDto>()); } catch (KnownException ex) { throw ex; } catch (Exception ex) { Logger.AddLog(LogTypeEnum.Error, "ProductManager.CreateOrUpdateProductType", RequestUserId, ex.Message, dto.ToJson(), ex); throw new KnownException(ErrorTypeEnum.UnexpectedExeption, ex.Message, ex); } }
// DELETE api/<controller>/5 public HttpResponseMessage Delete(int id) { try { Context.Fertilizers.Remove(Context.Fertilizers.FirstOrDefault(f => f.Id == id)); Context.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.NoContent, true)); } catch (Exception ex) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Conflict, ExceptionMessageHelper.GetErrorMessage(ex))); } }
// POST api/<controller> public HttpResponseMessage Post([FromBody] MetricUnit metricUnit) { try { Context.MetricUnits.Add(new MetricUnit() { Name = metricUnit.Name }); Context.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.Created, true)); } catch (Exception ex) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ExceptionMessageHelper.GetErrorMessage(ex))); } }
/// <summary> /// 捕获异常 /// </summary> /// <param name="ex"></param> protected virtual void CatchException(Exception ex) { MyMessageBox.Show(this, "处理数据时出现错误。", ExceptionMessageHelper.Trans(ex)); }
/// <summary> /// Throws <see cref="ArgumentException"/> if argument is contains <paramref name="elem"/> /// </summary> /// <exception cref="ArgumentException">Throws if argument is contains <paramref name="elem"/></exception> /// <exception cref="ArgValidationException">Throws if argument is <c>null</c></exception> public static Argument <TEnumerable> NotContains <TEnumerable, T>(this Argument <TEnumerable> arg, T elem) where TEnumerable : IEnumerable <T> { if (arg.ValidationIsDisabled()) { return(arg); } InvalidMethodArgumentThrower.IfArgumentValueIsNull(arg, methodName: nameof(NotContains)); if (arg.Value.Contains(elem)) { ValidationErrorExceptionThrower.ArgumentException(arg, $"Argument '{arg.Name}' contains {ExceptionMessageHelper.GetStringValueForMessage(elem)} value. {GetCurrentValuesString(arg.Value)}"); } return(arg); }
/// <summary> /// Throws <see cref="ArgumentException"/> if argument is not <c>null</c> or length is more than 0 /// </summary> /// <exception cref="ArgumentException">Throws if argument is not <c>null</c> or length is more than 0</exception> public static Argument <string> NullOrEmpty(this Argument <string> arg) { if (arg.ValidationIsDisabled()) { return(arg); } if (!string.IsNullOrEmpty(arg.Value)) { ValidationErrorExceptionThrower.ArgumentException(arg, $"Argument '{arg.Name}' must be empty or null. Current value: {ExceptionMessageHelper.GetStringValueForMessage(arg.Value)}"); } return(arg); }
// POST api/<controller> public HttpResponseMessage Post([FromBody] Yield yield) { try { Context.Amounts.Add(new Yield() { Name = yield.Name, Quantity = yield.Quantity, MetricUnit = yield.MetricUnit }); Context.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.Created, true)); } catch (Exception ex) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ExceptionMessageHelper.GetErrorMessage(ex))); } }
/// <summary> /// Throws <see cref="ArgumentException"/> if argument is ends with <paramref name="value"/> /// </summary> /// <exception cref="ArgumentException">Throws if argument is ends with <paramref name="value"/></exception> /// <exception cref="ArgValidationException">Throws if argument is <c>null</c></exception> public static Argument <string> NotEndsWith(this Argument <string> arg, string value, StringComparison comparisonType) { if (arg.ValidationIsDisabled()) { return(arg); } if (EndsWithPrivate(arg, value, comparisonType, methodName: nameof(NotEndsWith))) { ValidationErrorExceptionThrower.ArgumentException(arg, $"Argument '{arg.Name}' must not ends with {ExceptionMessageHelper.GetStringValueForMessage(value)}. Current value: {ExceptionMessageHelper.GetStringValueForMessage(arg.Value)}"); } return(arg); }
// DELETE api/<controller>/5 public HttpResponseMessage Delete(int id) { try { Context.Amounts.Remove(Context.Amounts.OfType <Yield>().FirstOrDefault(y => y.AmountId == id)); Context.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.NoContent, true)); } catch (Exception ex) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ExceptionMessageHelper.GetErrorMessage(ex))); } }
/// <summary> /// Throws <see cref="ArgumentException"/> if argument is match <paramref name="pattern"/> /// </summary> /// <exception cref="ArgumentException">Throws if argument is match <paramref name="pattern"/></exception> /// <exception cref="ArgValidationException">Throws if argument is <c>null</c> or <paramref name="pattern"/> is <c>null</c></exception> public static Argument <string> NotMatch(this Argument <string> arg, string pattern) { if (arg.ValidationIsDisabled()) { return(arg); } InvalidMethodArgumentThrower.IfArgumentValueIsNull(arg, methodName: nameof(NotMatch)); InvalidMethodArgumentThrower.IfArgumentOfMethodIsNull(arg: pattern, argName: nameof(pattern), methodName: nameof(NotMatch)); if (StringConditionChecker.Match(arg, pattern)) { ValidationErrorExceptionThrower.ArgumentException(arg, $"Argument '{arg.Name}' not must be match with pattern '{pattern}'. Current value: {ExceptionMessageHelper.GetStringValueForMessage(arg.Value)}"); } return(arg); }
private async Task HandleCommandAsync(SocketMessage messageParam) { // Don't process the command if it was a system message if (!(messageParam is SocketUserMessage message)) { return; } // Create a number to track where the prefix ends and the command begins int argPos = 0; // Determine if the message is a command based on the prefix and make sure no bots trigger commands if (!(message.HasCharPrefix('+', ref argPos) || message.HasMentionPrefix(client.CurrentUser, ref argPos)) || message.Author.IsBot) { return; } // Create a WebSocket-based command context based on the message var context = new BotCommandContext(client, message, bot); // Execute the command with the command context we just // created, along with the service provider for precondition checks. // Keep in mind that result does not indicate a return value // rather an object stating if the command executed successfully. var result = await commands.ExecuteAsync( context : context, argPos : argPos, services : null); // Optionally, we may inform the user if the command fails // to be executed; however, this may not always be desired, // as it may clog up the request queue should a user spam a // command. if (!result.IsSuccess) { EmbedBuilder embed = new EmbedBuilder(); embed.WithColor(Color.Red); switch (result.Error) { case CommandError.Exception when result is ExecuteResult eResult: await ExceptionMessageHelper.HandleException(eResult.Exception, message.Channel); return; case CommandError.ParseFailed: case CommandError.BadArgCount: var c = commands.Search(context, argPos).Commands.FirstOrDefault().Command; string name = c.Name; var module = c.Module; while (module != null) { if (!string.IsNullOrEmpty(module.Group)) { name = module.Group + " " + name; } module = module.Parent; } embed.WithTitle("Incorrect Command Usage"); embed.WithDescription($"Error parsing command. Run `+help {name}` for more information."); break; case CommandError.UnmetPrecondition: embed.WithTitle("Error Executing Command"); embed.WithDescription(result.ErrorReason == "" ? "You do not have permission to use this command here." : result.ErrorReason); break; case CommandError.UnknownCommand: // Do nothing return; default: embed.WithTitle("Error Executing Command"); embed.WithColor(Color.Red); embed.WithDescription(result.ErrorReason); break; } await context.Channel.SendMessageAsync(embed : embed.Build()); } }
// POST api/<controller> public HttpResponseMessage Post([FromBody] Crop crop) { try { Context.Crops.Add(new Crop() { Name = crop.Name, Color = crop.Color, Description = crop.Description, ImageUrl = crop.ImageUrl, ImageName = crop.ImageName }); Context.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.Created, true)); } catch (Exception ex) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ExceptionMessageHelper.GetErrorMessage(ex))); } }