private CustomResult <Organisation> SecurityCodeGenericMethod(Organisation organisation, DateTime securityCodeExpiryDateTime, SecurityCodeNotExpiredValidator securityCodeNotExpiredValidator, SecurityCodeDateTimeValidator securityCodeDateTimeValidator, GetOrganisationAndWorkWithSecurityCode getOrganisationAndWorkWithSecurityCode) { CustomResult <Organisation> result; try { var securityCodeNotExpiredValidationResult = securityCodeNotExpiredValidator?.Invoke(organisation); if (securityCodeNotExpiredValidationResult != null) { return(securityCodeNotExpiredValidationResult); } var securityValidationResult = securityCodeDateTimeValidator?.Invoke(organisation, securityCodeExpiryDateTime); if (securityValidationResult != null) { return(securityValidationResult); } var org = getOrganisationAndWorkWithSecurityCode(organisation, securityCodeExpiryDateTime); result = new CustomResult <Organisation>(org); } catch (Exception ex) { result = new CustomResult <Organisation>(new CustomError(0, ex.Message), organisation); } return(result); }
public IActionResult Post([FromBody] ReqTinDang value) { CustomResult cusRes = new CustomResult(); try { if (string.IsNullOrEmpty(value.Data.Ma) || string.IsNullOrEmpty(value.Data.DiaChi) || string.IsNullOrEmpty(value.Data.TenLoai)) { cusRes.SetException("Dữ liệu không hợp lệ. Vui lòng kiểm tra lại thông tin dự án"); } else { string path = CommonMethods.getPathImages(value.Data.Ma); if (path == string.Empty) { cusRes.SetException("Dự án không tồn tại thư mục ảnh. Vui lòng tải ảnh lên để thực hiện tiếp."); } else { cusRes.StrResult = new ProcessDangTin().dangTin(value); cusRes.Message = Messages.SCS_001; cusRes.IntResult = 1; } } } catch (Exception ex) { cusRes.SetException(ex.Message); } return(Ok(cusRes)); }
[Obsolete("Please use method 'Employer' instead.")] //, true)] public IActionResult EmployerDetails(string e = null, int y = 0, string id = null) { if (!string.IsNullOrWhiteSpace(id)) { Organisation organisation; try { CustomResult <Organisation> organisationLoadingOutcome = OrganisationBusinessLogic.GetOrganisationByEncryptedReturnId(id); if (organisationLoadingOutcome.Failed) { return(organisationLoadingOutcome.ErrorMessage.ToHttpStatusViewResult()); } organisation = organisationLoadingOutcome.Result; } catch (Exception ex) { CustomLogger.Error("Cannot decrypt return id from query string", ex); return(View("CustomError", new ErrorViewModel(400))); } string organisationIdEncrypted = organisation.GetEncryptedId(); return(RedirectToActionPermanent(nameof(Employer), new { employerIdentifier = organisationIdEncrypted })); } if (string.IsNullOrWhiteSpace(e)) { return(new HttpBadRequestResult("EmployerDetails: \'e\' query parameter was null or white space")); } return(RedirectToActionPermanent(nameof(Employer), new { employerIdentifier = e })); }
public async Task <RuntimeResult> OBanAsync(ulong name, [Remainder] string reason = null) { var modlog = Context.Guild.GetTextChannel(Global.Channels["modlog"]); await Context.Guild.AddBanAsync(name, 0, reason); return(CustomResult.FromSuccess()); }
private void btnAddProductType_Click(object sender, EventArgs e) { try { if (!GetConfirmation("Are you sure to add this Product Type ?", "Confirm Add")) { return; } CustomResult customResult = bus.AddProductType(new ProductType() { Name = txtProductTypeName.Text.Trim(), IsActive = checkBoxIsActive.Checked }); if (customResult.Result == CustomResultType.Succeed) { MessageBox.Show("Product Type added!", "Add Complete", MessageBoxButtons.OK, MessageBoxIcon.Information); productTypeDataGridView.Refresh(); } else if (customResult.Result == CustomResultType.InvalidModelState) { GetInvalidModelStateErrors(); } else { throw new Exception(customResult.ErrorMessage); } } catch (Exception ex) { ShowErrorMessagerBox(ex.Message); } txtProductTypeName.Focus(); }
private void btnLockProductType_Click(object sender, EventArgs e) { try { if (!GetConfirmation("Are you sure to Lock/Unlock this Product Type", "Lock/Unlock Confirm")) { return; } ProductType productType = productTypeBindingSource.Current as ProductType; productType.IsActive = !productType.IsActive; bool currentLockStatus = productType.IsActive; CustomResult customResult = bus.EditProductType(productType); if (customResult.Result == CustomResultType.Succeed) { MessageBox.Show(currentLockStatus ? "Product Type unLocked!" : "Product Type locked!" , "Edit Complete", MessageBoxButtons.OK, MessageBoxIcon.Information); productTypeDataGridView.Refresh(); } else if (customResult.Result == CustomResultType.InvalidModelState) { GetInvalidModelStateErrors(); } else { throw new Exception(customResult.ErrorMessage); } } catch (Exception ex) { ShowErrorMessagerBox(ex.Message); } }
public async Task <RuntimeResult> ShowProfanities(IGuildUser user) { using (var db = new Database()){ var allProfanities = db.Profanities.Where(pro => pro.UserId == user.Id); var actualProfanities = allProfanities.Where(pro => pro.Valid == true).Count(); var falseProfanities = allProfanities.Where(pro => pro.Valid == false).Count(); var builder = new EmbedBuilder(); builder.AddField(f => { f.Name = "Actual"; f.Value = actualProfanities; f.IsInline = true; }); builder.AddField(f => { f.Name = "False positives"; f.Value = falseProfanities; f.IsInline = true; }); builder.WithAuthor(new EmbedAuthorBuilder().WithIconUrl(user.GetAvatarUrl()).WithName(Extensions.FormatUserName(user))); await Context.Channel.SendMessageAsync(embed : builder.Build()); return(CustomResult.FromSuccess()); } }
public async Task <RuntimeResult> RemoveChannelGroup(string name) { new ChannelManager().RemoveChannelGroup(name); await Task.CompletedTask; return(CustomResult.FromSuccess()); }
public async Task <RuntimeResult> EnableModmailForUser(IGuildUser user) { new ModMailManager().EnableModmailForUser(user); await Task.CompletedTask; return(CustomResult.FromSuccess()); }
public async Task <RuntimeResult> ReloadDB() { await Task.Delay(500); Global.LoadGlobal(); return(CustomResult.FromSuccess()); }
private static void CheckResultFailInternal <TError>(CustomResult <TError> result, [NotNull] string expectedError, [NotNull] TError expectedErrorObject) { Assert.IsFalse(result.IsSuccess); Assert.IsFalse(result.IsWarning); Assert.IsTrue(result.IsFailure); Assert.AreEqual(expectedError, result.Message); }
private void btnDELETE_Click(object sender, EventArgs e) { if (!GetConfirmation("Do you want to delete this product ?", "Delete confirm")) { return; } if (MessageBox.Show("ARE YOU SURE TO DELETE THIS PRODUCT, THIS ACTION CAN CAUSE DATA LOSS", "DELETE CONFIRM", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) { return; } if (MessageBox.Show("THIS FEATURE IS STILL UNDER DEVELOP SO YOU CAN'T GET YOUR DATA BACK, ARE YOU SURE TO PROCEED?", "DELETE CONFIRM", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.No) { return; } try { CustomResult cr = bus.DeleteProduct((productBindingSource.Current as Product).Id); if (cr.Result == CustomResultType.Succeed) { MessageBox.Show(cr.ErrorMessage); } } catch (Exception ex) { ShowErrorMessagerBox(ex.Message); } }
public async Task <RuntimeResult> Purge(int messageCount) { if (messageCount > 100) { return(CustomResult.FromError("You cannot purge more than 100 messages at a time")); } // Check if the amount provided by the user is positive. if (messageCount <= 0) { return(CustomResult.FromError("You cannot purge a negative number")); } var messages = await Context.Channel.GetMessagesAsync(messageCount).FlattenAsync(); var filteredMessages = messages.Where(x => (DateTimeOffset.UtcNow - x.Timestamp).TotalDays <= 14); // Get the total amount of messages. var count = filteredMessages.Count(); // Check if there are any messages to delete. if (count == 0) { return(CustomResult.FromError("Nothing to delete.")); } else { await(Context.Channel as ITextChannel).DeleteMessagesAsync(filteredMessages); await ReplyAndDeleteAsync($"Done. Removed {count} {(count > 1 ? "messages" : "message")}."); return(CustomResult.FromSuccess()); } }
/// <summary> /// 会员注册表单校验 /// </summary> /// <param name="memberInfo"></param> /// <returns></returns> public JsonResult MemberRegisterCheck(RegisterDto memberInfo) { if (!ModelState.IsValid) { var error = ModelState.Where(m => m.Value.Errors.Any()).FirstOrDefault(); return(CustomResult.ErrorMessage(error.Value.Errors[0].ErrorMessage)); } if (!memberInfo.Level.In(LevelInt.Golden, LevelInt.Diamon, LevelInt.SpecialVip)) { return(CustomResult.ErrorMessage("注册级别不正确")); } if (!memberInfo.InsuranceType.In(InsuranceType.None, InsuranceType.BType)) { return(CustomResult.ErrorMessage("百万身价俱乐部不正确")); } if (!registerService.RegisterCheck(memberInfo, out string errMsg)) { return(CustomResult.ErrorMessage(errMsg)); } return(CustomResult.SuccessMessage("该去购物车啦")); }
public async Task <RuntimeResult> SetExpGainEnabled(IGuildUser user, bool newValue) { new ExpManager().SetXPDisabledTo(user, newValue); await Task.CompletedTask; return(CustomResult.FromSuccess()); }
public async Task <RuntimeResult> ToggleGroupDisabled(string groupName, bool newValue) { new ChannelManager().setGroupDisabledTo(groupName, newValue); await Task.CompletedTask; return(CustomResult.FromSuccess()); }
public async Task <RuntimeResult> Announce(String message) { // THIS IS BAD PRACTICE DON'T DO THIS // TODO: Move this to a service or somewhere not here, so if the bot crashes we can continue automatically. _ = Task.Run(() => { Thread.Sleep(5000); foreach (SocketGuild g in this.Client.Guilds) { var embed = new EmbedBuilder { Title = "Bot Announcement", Color = Color.Orange, Description = message, Footer = new EmbedFooterBuilder { Text = DateTime.Now.ToShortDateString() } }.Build(); g.DefaultChannel.SendMessageAsync(embed: embed); Thread.Sleep(5000); } }); return(CustomResult.FromSuccess("Announcement will begin in 10 seconds.")); }
public async Task <RuntimeResult> CreateChannelGroup(string groupName) { var configurationStep = new ConfigurationStep("What type of group is this? (🏁 checks, ❓ FAQ, 🤖 command)", Interactive, Context, ConfigurationStep.StepType.Reaction, null); var addAction = new ReactionAction(new Emoji("🏁")); addAction.Action = async(ConfigurationStep a) => { new ChannelManager().createChannelGroup(groupName, ChannelGroupType.CHECKS); await Task.CompletedTask; }; var deleteCommandChannelAction = new ReactionAction(new Emoji("❓")); deleteCommandChannelAction.Action = async(ConfigurationStep a) => { new ChannelManager().createChannelGroup(groupName, ChannelGroupType.FAQ); await Task.CompletedTask; }; var deleteCommandAction = new ReactionAction(new Emoji("🤖")); deleteCommandAction.Action = async(ConfigurationStep a) => { new ChannelManager().createChannelGroup(groupName, ChannelGroupType.COMMANDS); await Task.CompletedTask; }; configurationStep.Actions.Add(addAction); configurationStep.Actions.Add(deleteCommandChannelAction); configurationStep.Actions.Add(deleteCommandAction); await configurationStep.SetupMessage(); return(CustomResult.FromSuccess()); }
private EmployerSearchModel GetEmployer(string employerIdentifier, bool activeOnly = true) { EmployerSearchModel employer = SearchViewService.LastSearchResults?.GetEmployer(employerIdentifier); if (employer == null) { //Get the employer from the database CustomResult <Organisation> organisationResult = activeOnly ? OrganisationBusinessLogic.LoadInfoFromActiveEmployerIdentifier(employerIdentifier) : OrganisationBusinessLogic.LoadInfoFromEmployerIdentifier(employerIdentifier); if (organisationResult.Failed) { throw organisationResult.ErrorMessage.ToHttpException(); } if (organisationResult.Result.OrganisationId == 0) { throw new HttpException(HttpStatusCode.NotFound, "Employer not found"); } employer = organisationResult.Result.ToEmployerSearchResult(); } return(employer); }
private void btnEditProductType_Click(object sender, EventArgs e) { try { if (!GetConfirmation("Are you sure to edit this Product Type", "Edit Confirm")) { return; } ProductType productType = productTypeBindingSource.Current as ProductType; productType.Name = txtProductTypeName.Text.Trim(); productType.IsActive = checkBoxIsActive.Checked; CustomResult customResult = bus.EditProductType(productType); if (customResult.Result == CustomResultType.Succeed) { MessageBox.Show("Product Type edited!", "Edit Complete", MessageBoxButtons.OK, MessageBoxIcon.Information); productTypeDataGridView.Refresh(); } else if (customResult.Result == CustomResultType.InvalidModelState) { GetInvalidModelStateErrors(); } else { throw new Exception(customResult.ErrorMessage); } } catch (Exception ex) { ShowErrorMessagerBox(ex.Message); } txtProductTypeName.Focus(); }
public async Task <RuntimeResult> SubscribeToThread() { if (CommandHandler.FeatureFlagDisabled(FeatureFlag.MODMAIL)) { return(CustomResult.FromIgnored()); } var bot = Global.Bot; using (var db = new Database()) { var existing = db.ThreadSubscribers.AsQueryable().Where(sub => sub.ModMailThreadId == Context.Channel.Id && sub.UserId == Context.User.Id); if (existing.Count() > 0) { return(CustomResult.FromError("You are already subscribed!")); } } var subscription = new ThreadSubscriber(); subscription.ModMailThreadId = Context.Channel.Id; subscription.UserId = Context.User.Id; using (var db = new Database()) { db.ThreadSubscribers.Add(subscription); db.SaveChanges(); } await Task.CompletedTask; return(CustomResult.FromSuccess()); }
public async Task <RuntimeResult> NewsAsync([Remainder] string news) { var guild = Context.Guild; var user = (SocketGuildUser)Context.Message.Author; var newsChannel = guild.GetTextChannel(Global.Channels["news"]); var newsRole = guild.GetRole(Global.Roles["news"]); var journalistRole = guild.GetRole(Global.Roles["journalist"]); if (news.Contains("@everyone") || news.Contains("@here") || news.Contains("@news")) { return(CustomResult.FromError("Your news article contained one or more illegal pings!")); } if (!user.Roles.Contains(journalistRole)) { return(CustomResult.FromError("Only Journalists can post news.")); } await newsRole.ModifyAsync(x => x.Mentionable = true); await newsChannel.SendMessageAsync(news + Environment.NewLine + Environment.NewLine + newsRole.Mention + Environment.NewLine + "- " + Context.Message.Author); await newsRole.ModifyAsync(x => x.Mentionable = false); return(CustomResult.FromSuccess()); }
public async Task <RuntimeResult> UnsubscribeFromThread() { if (CommandHandler.FeatureFlagDisabled(FeatureFlag.MODMAIL)) { return(CustomResult.FromIgnored()); } var bot = Global.Bot; using (var db = new Database()) { var existing = db.ThreadSubscribers.AsQueryable().Where(sub => sub.ModMailThreadId == Context.Channel.Id && sub.UserId == Context.User.Id); if (existing.Count() == 0) { return(CustomResult.FromError("You are not subscribed!")); } } using (var db = new Database()) { var existing = db.ThreadSubscribers.AsQueryable().Where(sub => sub.ModMailThreadId == Context.Channel.Id && sub.UserId == Context.User.Id).First(); db.ThreadSubscribers.Remove(existing); db.SaveChanges(); } await Task.CompletedTask; return(CustomResult.FromSuccess()); }
/// <summary> /// 修改所有不能设置假期名称的假期名称配置项 /// </summary> /// <param name="holidayId"></param> /// <returns></returns> public CustomResult Update(int holidayId) { using (DataSubmittedEntities db = new DataSubmittedEntities()) { using (TransactionScope transaction = new TransactionScope()) { CustomResult pReturnValue = new CustomResult(); var list = db.OT_HDayConfig.ToList(); if (list != null && list.Count > 0) { foreach (var item in list) { if (item.ConfigItem == null || !item.ConfigItem.Contains("HDayId")) { item.HDayId = holidayId; } } pReturnValue = Result.SaveUpdateResult(db, transaction); } else { pReturnValue.ResultKey = (byte)EResult.IsNull1; pReturnValue.ResultValue = Wttech.DataSubmitted.Common.Resources.TipInfo.InexistHoliday; } return(pReturnValue); } } }
public IActionResult GetStatusLink([FromBody] JObject value) { CustomResult cusRes = new CustomResult(); try { Account ac = new Account(); ac.TenDangNhap = value.GetValue("TenDangNhap").ToString(); ac.MatKhau = value.GetValue("MatKhau").ToString(); String id = value.GetValue("Id").ToString(); if (String.IsNullOrEmpty(ac.TenDangNhap) || String.IsNullOrEmpty(ac.MatKhau)) { cusRes.SetException(new Exception("Tên đăng nhập hoặc mật khẩu không hợp lệ")); } else { if (String.IsNullOrEmpty(id)) { cusRes.SetException(new Exception("Id tin đăng không hợp lệ")); } else { cusRes.DataResult = new List <Object> { new ProcessDangTin().getStatusLink(ac, id) }; cusRes.IntResult = 1; } } } catch (Exception ex) { cusRes.SetException(ex); } return(Ok(cusRes)); }
public async Task <RuntimeResult> BanAsync(IGuildUser user, [Remainder] string reason = null) { if (user.IsBot) { return(CustomResult.FromError("You can't ban bots.")); } if (user.GuildPermissions.PrioritySpeaker) { return(CustomResult.FromError("You can't ban staff.")); } try { const string banMessage = "You were banned on r/OnePlus for the following reason: {0}\n" + "If you believe this to be a mistake, please send an appeal e-mail with all the details to [email protected]"; await user.SendMessageAsync(string.Format(banMessage, reason)); await Context.Guild.AddBanAsync(user, 0, reason); return(CustomResult.FromSuccess()); } catch (Exception ex) { // may not be needed // await Context.Guild.AddBanAsync(user, 0, reason); return(CustomResult.FromError(ex.Message)); } }
public async Task <RuntimeResult> ToggleChannelGroupAttributes(string groupName, bool xpGain, [Optional] bool?profanityCheck, [Optional] Boolean?inviteCheck) { new ChannelManager().SetChannelGroupAttributes(groupName, xpGain, inviteCheck, profanityCheck); await Task.CompletedTask; return(CustomResult.FromSuccess()); }
public async Task <RuntimeResult> SteampAsync([Remainder] string user) { await Context.Message.AddReactionAsync(Global.Emotes[Global.OnePlusEmote.SUCCESS].GetAsEmote()); var request = (HttpWebRequest)WebRequest.Create(string.Format(BadgeUrl, user)); using (var response = await request.GetResponseAsync()) using (var stream = response.GetResponseStream()) { if (stream == null) { return(CustomResult.FromError("Could not establish a connection to the Steam API")); } using (var fs = File.Open("output.png", FileMode.Create, FileAccess.Write, FileShare.Read)) { await stream.CopyToAsync(fs); } await Context.Channel.SendFileAsync("output.png"); } File.Delete("output.png"); return(CustomResult.FromSuccess()); }
public JsonResult UpdateHoliday(NodeViewModel model) { CustomResult result = new CustomResult(); if (string.IsNullOrEmpty(model.Name)) { result.ResultKey = (byte)ENodeAddResult.Exist; result.ResultValue = Wttech.DataSubmitted.Common.Resources.TipInfo.InputHolidayName; return(Json(result, JsonRequestBehavior.DenyGet)); } result = ReportFactory.Instance.DicUpdate(model); //精确假期名称存在提示信息 if (result.ResultKey == (byte)ENodeAddResult.Exist) { result.ResultValue = Wttech.DataSubmitted.Common.Resources.TipInfo.HolidayExist; } else if (result.ResultKey == (byte)EResult.Succeed) { ReportFactory.Instance.log.WriteLog(Common.OperationType.Update, string.Format("编辑了假期名称{0}", model.Name)); } return(Json(result, JsonRequestBehavior.DenyGet)); }
public void CustomResultToOption() { // Explicit conversions CustomResult <CustomErrorTest> resultOk = Result.CustomOk <CustomErrorTest>(); Option <bool> optionBool = resultOk.ToOption(); CheckOptionValue(optionBool, true); CustomResult <CustomErrorTest> resultWarn = Result.CustomWarn <CustomErrorTest>("Warning"); optionBool = resultWarn.ToOption(); CheckOptionValue(optionBool, true); CustomResult <CustomErrorTest> resultFail = Result.CustomFail("Failure", new CustomErrorTest()); optionBool = resultFail.ToOption(); CheckOptionValue(optionBool, false); // Implicit conversions optionBool = resultOk; CheckOptionValue(optionBool, true); optionBool = resultWarn; CheckOptionValue(optionBool, true); optionBool = resultFail; CheckOptionValue(optionBool, false); }
public object Any(CustomResult request) { return new CustomXmlResult(); }