private static FormCollection Compatibility(FormCollection collection) { switch (collection.Count) { case 9: if (!IsDocument(collection)) { collection.Add("Document", ""); } return(collection); case 8: if (!IsDocument(collection)) { collection.Add("Document", ""); } return(collection); case 6: var totalcost = collection[4]; var plantname = collection[5]; collection.Remove("TotalCost"); collection.Remove("PlantName"); if (!IsDocument(collection)) { collection.Add("Document", ""); } collection.Add("TotalCost", totalcost); collection.Add("PlantName", plantname); return(collection); default: return(collection); } }
public void MissingPlayerName() { testForm.Remove("player-1-name"); ViewResult result = testController.PokerEvaluation(testForm) as ViewResult; PokerEvaluationViewModel viewModel = shucker.Shuck <PokerEvaluationViewModel>(result); Assert.IsTrue( viewModel != null && viewModel.ThrownException != null, "View model was generated incorrectly or exception was not recorded."); }
public void create_post_invalid_throws_exception() { //Arrange var workOrder = new WorkOrder(); serv.Setup(p => p.Create(workOrder, "UnitTest")).Returns(workOrder); fakeform.Remove("contactName"); _ctrlr.ValueProvider = fakeform.ToValueProvider(); //Act _ctrlr.Create(workOrder, "UnitTest", workerRequest); //Assert }
public void create_post_invalid_throws_exception() { //Arrange var person = new Person(); _serv.Setup(p => p.Create(person, "UnitTest")).Returns(person); fakeform.Remove("firstname1"); _ctrlr.ValueProvider = fakeform.ToValueProvider(); //Act _ctrlr.Create(person, "UnitTest"); //Assert }
public ActionResult SubmitForm(String formId, FormCollection formData) { // Remove CSRF token // formData.Remove("__RequestVerificationToken"); // Get form entity // Form form = FormRepository.GetForm(formId); Log.Debug("Form data for form '" + form.Id + "' : "); foreach (var param in formData.Keys) { Log.Debug(" " + param + " = " + formData.Get(param.ToString())); } var formHandler = FormHandlerRegistry.Get(form.FormAction.FormHandler); string resultLink; if (formHandler != null) { resultLink = formHandler.ProcessForm(form, formData); } else { resultLink = WebRequestContext.Localization.Path + "/error-404"; } return(Redirect(resultLink)); }
public ActionResult RoleOperation(FormCollection from) { List <RoleNav> list = new List <RoleNav>(); var l = from; string roleid = from["RoleId"]; try { from.Remove("RoleId"); _roleNavService.Delete(a => a.RoleId == roleid, false); if (from.Keys.Count > 0) { foreach (string k in from.Keys) { var arr = from[k].Split(','); for (int i = 0; i < arr.Length; i++) { RoleNav entity = new RoleNav(); entity.NavId = k; entity.RoleId = roleid; entity.OperationId = Convert.ToInt32(arr[i]); list.Add(entity); } } } _roleNavService.AddRange(list, false); _context.SaveChanges(); } catch (Exception ex) { _logger.Debug(ex, "添加角色权限出现异常!"); } return(RedirectToAction("Details", new{ id = roleid })); }
public void create_post_invalid_throws_exception() { //Arrange var employer = new Domain.Employer(); form.Remove("name"); serv = new Mock <IEmployerService>(); serv.Setup(p => p.Create(employer, "UnitTest")).Returns(employer); woServ = new Mock <IWorkOrderService>(); ctrlr = new EmployerController(serv.Object, def.Object, map); ctrlr.SetFakeControllerContext(); ctrlr.ValueProvider = form.ToValueProvider(); JsonResult result = ctrlr.Create(employer, "UnitTest"); Assert.IsNotNull(result); }
public SocketLabsEvent(FormCollection formCollection) : this() { ServerId = Convert.ToInt64(formCollection["ServerId"]); Address = formCollection["Address"]; EventType type; if (Enum.TryParse(formCollection["Type"], true, out type)) { formCollection.Remove("Type"); } else { type = EventType.Unknown; } Type = type; DateTime = Convert.ToDateTime(formCollection["DateTime"]); MailingId = formCollection["MailingId"]; MessageId = formCollection["MessageId"]; SecretKey = formCollection["SecretKey"]; formCollection.Remove("ServerId"); formCollection.Remove("Address"); formCollection.Remove("DateTime"); formCollection.Remove("MailingId"); formCollection.Remove("MessageId"); formCollection.Remove("SecretKey"); ExtraData = formCollection.AllKeys.ToDictionary(k => k, v => formCollection[v]); }
public ActionResult EnableArchive(FormCollection collection) { var initiativeId = collection.GetValue("InitiativeId").AttemptedValue; var applicationId = collection.GetValue("ApplicationId").AttemptedValue; var applicationName = _initiativeBusiness.GetInitiatives().SelectMany(x => x.ApplicationGroups).SelectMany(x => x.Applications).Single(x => x.Id == Guid.Parse(applicationId)).Name; collection.Remove("InitiativeId"); collection.Remove("ApplicationId"); var versionIds = (from object key in collection.Keys select collection.GetValue(key.ToString()).AttemptedValue).ToList(); foreach (var versionId in versionIds) { _initiativeBusiness.ArchiveApplicationVersion(versionId); } return(RedirectToAction("Details", "Application", new { id = initiativeId, application = applicationName })); }
public new string Edit(FormCollection fc) { if (ModelState.IsValid) { try { var entity = context.Set <Admin>().Find(fc["ID"]); if (string.IsNullOrEmpty(fc["ID"]) && entity == null) { fc.Remove("ID"); entity = new Admin(); TryUpdateModel(entity, fc); entity.RoleName = context.Roles.Find(entity.RoleID).RoleName; entity.Salt = PersonalFramework.Service.DeCrypt.SetSalt(); entity.Password = PersonalFramework.Service.DeCrypt.SetPassWord(entity.Password, entity.Salt); context.Set <Admin>().Add(entity); context.SaveChanges(); ReturnData result = new ReturnData(200, "编辑成功"); return(result.ToJson()); } else { TryUpdateModel(entity, fc); entity.RoleName = context.Roles.Find(entity.RoleID).RoleName; context.Entry(entity).Property(m => m.Salt).IsModified = false; if (entity.Password == "") { context.Entry(entity).Property(m => m.Password).IsModified = false; } else { entity.Password = PersonalFramework.Service.DeCrypt.SetPassWord(entity.Password, entity.Salt); } context.SaveChanges(); ReturnData result = new ReturnData(200, "编辑成功"); return(result.ToJson()); } } catch (DbEntityValidationException ex) { ReturnData result = new ReturnData(500, ex.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage); return(result.ToJson()); } catch (Exception ex) { ReturnData result = new ReturnData(500, ex.Message); return(result.ToJson()); } } else { ReturnData result = new ReturnData(500, "false"); return(result.ToJson()); } }
protected override void OnEntityEditing(Category entity, FormCollection collection) { var lang = DependencyResolver.Current.GetService <ILocalizationContext>(); entity.Lang = lang.Current.Lang; var groupsValue = collection["Groups"]; collection.Remove("Groups"); PopulateGroups(groupsValue, entity); base.OnEntityEditing(entity, collection); }
public ActionResult GetRecomendation(FormCollection collection) { var searchRecomendation = new SearchRecomendation(); searchRecomendation.Year = collection["year"]; collection.Remove("year"); searchRecomendation.Genres = collection.AllKeys; var artistModel = _spotifySearchProvider.GetRecomendation(searchRecomendation); return(PartialView("ListArtist", artistModel)); }
private void UpdateCurrencies(TEntity entity, FormCollection collection) { foreach (var field in Settings.FormSettings.Fields.Where(settings => settings is CurrencySettings).Cast <CurrencySettings>()) { var value = collection[field.Name]; if (!string.IsNullOrEmpty(value)) { var d = decimal.Parse(value, NumberStyles.Currency); TypeHelpers.SetPropertyValue(entity, field.Name, d); collection.Remove(field.Name); } } }
public ActionResult Delete(int id, FormCollection collection) { try { Movie movie = Movies.FirstOrDefault(m => m.ID == id); collection.Remove(movie.Title); return(RedirectToAction("Index")); } catch { return(View()); } }
protected override void OnEntityEditing(Partner entity, FormCollection collection) { var name = collection["Name"]; var url = collection["Url"]; var alias = collection["Alias"]; collection.Remove("Name"); collection.Remove("Url"); if (string.IsNullOrEmpty(alias)) { if (string.IsNullOrEmpty(name)) { ModelState.AddModelError("Name", "Введите название партнёра"); return; } alias = name.Transliterate(); } entity.Alias = alias; if (string.IsNullOrEmpty(entity.Name)) { entity.Name = NameKey + alias; } var nameText = GetByKey(entity.Name, true); nameText.Value = name; if (entity.Url.IsNullOrEmpty()) { entity.Url = UrlKey + alias; } var urlText = GetByKey(entity.Url, true); urlText.Value = url; DataModelContext.SaveChanges(); }
public ActionResult AddData(string tabName, FormCollection form) { var tabInfo = TableInfoHelper.GetTableInfo(_tableInfoService, tabName); var keys = form.AllKeys; StringBuilder sb = new StringBuilder(); foreach (string colName in keys) { var name = colName; var colConfig = tabInfo.ColumnInfos.SingleOrDefault(c => c.Name == name); if (colConfig != null) { sb.AppendLine(string.Format("declare @{0} {1};", colConfig.Name, colConfig.Type)); if (colConfig.FormItemType == FormItemType.Double || colConfig.FormItemType == FormItemType.Money || colConfig.FormItemType == FormItemType.Number) { sb.AppendLine(string.Format("set @{0} = {1};", colConfig.Name, form[colName])); } else { sb.AppendLine(string.Format("set @{0} = '{1}';", colConfig.Name, form[colName])); } } else { form.Remove(colName); } } string fields = ""; string values = ""; form.AllKeys.ForEach(key => { fields += string.Format("[{0}],", key); values += string.Format("@{0},", key); }); fields = fields.Substring(0, fields.Length - 1); values = values.Substring(0, values.Length - 1); sb.AppendLine(string.Format("insert into [{0}] ({1}) values({2})", tabName, fields, values)); string sql = sb.ToString(); SqlHelper.ExecuteNonQuery(sql); return(RedirectToAction("AddData", new { tabName = tabName })); }
protected virtual void SaveBlocks(T entity, FormCollection collection) { var vm = (dynamic)entity; var listToRemove = Enumerable.Cast <IBlockEntity>((IEnumerable)vm.Blocks).ToList(); //var engine = DependencyResolver.Current.GetService<MixberryTemplateEngine>(); foreach (var key in collection.AllKeys.Where(x => x.StartsWith("BlockId")).ToList()) { var idValue = collection[key]; var sortValue = collection["BlockSort" + idValue]; var imageIdValue = collection["BlockImagesId" + idValue]; var id = int.Parse(idValue); var sort = int.Parse(sortValue); var name = collection["BlockName" + idValue]; var alias = collection["BlockAlias" + idValue]; var content = collection["BlockContent" + idValue]; var item = listToRemove.FirstOrDefault(x => x.Id == id); if (item != null) { item.Sort = sort; item.Name = name; item.Alias = alias; if (item.Alias.IsNullOrEmpty()) { item.Alias = item.Name.Transliterate(); } item.Content = content; if (!imageIdValue.IsNullOrEmpty()) { var imageId = int.Parse(imageIdValue); if (imageId != 0) { item.Images.Clear(); item.Images.Add(Repository.DataContext.Set <WebFile>().Find(imageId)); } } listToRemove.Remove(item); } collection.Remove(key); collection.Remove("BlockSort" + idValue); collection.Remove("BlockImageId" + idValue); collection.Remove("BlockName" + idValue); collection.Remove("BlockAlias" + idValue); collection.Remove("BlockContent" + idValue); } listToRemove.ForEach(x => { RemoveBlock(entity, x); }); }
public new string Edit(FormCollection fc) { if (ModelState.IsValid) { try { var entity = context.Set <Article>().Find(fc["ID"]); if (string.IsNullOrEmpty(fc["ID"]) && entity == null) { fc.Remove("ID"); entity = new Article(); entity.Author = AdminLoginHelper.CurrentUser().ID; TryUpdateModel(entity, fc); context.Set <Article>().Add(entity); context.SaveChanges(); ReturnData result = new ReturnData(200, "编辑成功"); return(result.ToJson()); } else { TryUpdateModel(entity, fc); context.SaveChanges(); ReturnData result = new ReturnData(200, "编辑成功"); return(result.ToJson()); } } catch (DbEntityValidationException ex) { ReturnData result = new ReturnData(500, ex.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage); return(result.ToJson()); } catch (Exception ex) { ReturnData result = new ReturnData(500, ex.Message); return(result.ToJson()); } } else { ReturnData result = new ReturnData(500, "false"); return(result.ToJson()); } }
private JsonResult SaveModules( FormCollection _vars, SaveModulesOperation _op) { if (String.IsNullOrEmpty(_vars["userid"])) { return(Json(new { result = -1, msg = "Erro: Identificação do usuário inválida." })); } Guid userID; try { userID = new Guid(_vars["userid"]); } catch (Exception e) { return(Json(new { result = -1, msg = "Identificação do usuário em formato inválido.\n" + e.Message })); } _vars.Remove("userid"); Action <Guid, int> del; if (_op == SaveModulesOperation.Add) { del = ModRepository.AddUserModule; } else { del = ModRepository.RemoveUserModule; } foreach (string s in _vars) { try { del(userID, Int32.Parse(_vars[s])); } catch (Exception e) { return(Json(new { result = -1, msg = "Falha ao adicionar o módulo selecionado.\n" + e.Message })); } } return(Json(new { result = 0, msg = "Sucesso." })); }
public ActionResult ConferirRespotaRecebida(Atividade atividade, FormCollection form, string metodo, string controle) { Aluno aluno = (Aluno)Session["dadosAlunoLogado"]; var respostaDoAluno = ""; form.Remove("IdAtividade"); if (form != null) { for (int i = 0; i < form.Count; i++) { respostaDoAluno += form[i]; } } if (respostaDoAluno.Equals(atividadeREP.RespostaExata(atividade.IdAtividade))) { //consulta atividade pra ver se ja existe if (atividadeAlunoREP.ExisteAtividadeFeita(aluno.IdAluno, atividade.IdAtividade)) { TempData.Add("Mensagem", "Resposta Correta. Atividade feita anteriormente."); return(RedirectToAction(metodo, controle)); } else { atividadeAlunoREP.AdicionaAtividadeAluno(aluno.IdAluno, atividade.IdAtividade); TempData.Add("Mensagem", "Resposta correta!"); } } else { TempData.Add("Mensagem", "Resposta Errada!"); } return(RedirectToAction(metodo, controle)); }
protected override void OnEntityEditing(Country entity, FormCollection collection) { var name = collection["Name"]; collection.Remove("Name"); if (name.IsNullOrEmpty()) { ModelState.AddModelError("Name", "Обязательное поле"); return; } if (string.IsNullOrEmpty(entity.Name)) { var alias = name.Transliterate().Replace(" ", ""); entity.Name = alias; } var text = GetByKey(entity.Name, true); text.Value = name; DataModelContext.SaveChanges(); }
private void UpdatePartialLocalization(TEntity entity, FormCollection collection) { var l = DependencyResolver.Current.GetService <ILocalizationDbHelper>(); var lang = DependencyResolver.Current.GetService <ILocalizationProvider>(); var fields = Settings.FormSettings.Fields; foreach (var f in fields.Where(settings => settings.Localizable)) { try { var value = collection[f.Name]; var key = (Guid?)TypeHelpers.GetPropertyValue(entity, f.Name); if (key == null || key.Value == Guid.Empty) { if (string.IsNullOrEmpty(f.Name)) { continue; } key = Guid.NewGuid(); TypeHelpers.SetPropertyValue(entity, f.Name, key); } l.Set(lang.GetLanguageName(), key.Value, value); lang.Reset(); collection.Remove(f.Name); } catch { } } //aganzha //var unitOfWork = DependencyResolver.Current.GetService<IUnitOfWork>(); //unitOfWork.Commit(); using (var db = ApplicationDbContext.Create()) { db.SaveChanges(); } }
public new ActionResult Edit(FormCollection fc) { if (ModelState.IsValid) { try { var entity = context.Set <User>().Find(fc["ID"]); if (string.IsNullOrEmpty(fc["ID"]) && entity == null) { fc.Remove("ID"); entity = new User(); TryUpdateModel(entity, fc); entity.Salt = PersonalFramework.Service.DeCrypt.SetSalt(); entity.Password = PersonalFramework.Service.DeCrypt.SetPassWord(entity.Password, entity.Salt); context.Set <User>().Add(entity); context.SaveChanges(); return(Json(new { data = "", Status = 200 }, JsonRequestBehavior.DenyGet)); } else { TryUpdateModel(entity, fc); entity.Password = PersonalFramework.Service.DeCrypt.SetPassWord(entity.Password, entity.Salt); context.SaveChanges(); return(Json(new { data = "", Status = 200 }, JsonRequestBehavior.DenyGet)); } } catch (Exception ex) { return(Json(new { data = "", Status = 500, Message = ex.Message }, JsonRequestBehavior.DenyGet)); } } else { return(Json(new { data = "", Status = 500, Message = "false" }, JsonRequestBehavior.DenyGet)); } }
/// <summary> /// Sanitizes the form collection. /// </summary> /// <param name="collection">The collection.</param> protected virtual void SanitizeFormCollection(FormCollection collection) { const char ReplacementSymbol = '_'; var forbidenSymbols = new char[] { '-' }; if (collection != null) { var forbidenKeys = collection.AllKeys.Where(k => k.IndexOfAny(forbidenSymbols) >= 0); foreach (var key in forbidenKeys) { var newKey = key.ToCharArray(); for (int i = 0; i < newKey.Length; i++) { if (forbidenSymbols.Contains(newKey[i])) { newKey[i] = ReplacementSymbol; } } collection.Add(new string(newKey), collection[key]); collection.Remove(key); } } }
/// <summary> /// Check if the querystring directive of TreeQueryStringParameters.RenderParent is true, if so then /// set the _dynamicRootNodeId value to the one being requested and only return the root node, otherwise /// proceed as normal. /// </summary> /// <param name="parentId"></param> /// <param name="queryStrings"></param> /// <param name="actualRootNodeId"> </param> /// <param name="nodeCollection"> </param> /// <param name="createRootNode"> </param> /// <param name="returnResult"> </param> /// <param name="returnDefaultResult"> </param> /// <returns></returns> internal RebelTreeResult GetTreeData( HiveId parentId, FormCollection queryStrings, HiveId actualRootNodeId, TreeNodeCollection nodeCollection, Func <FormCollection, TreeNode> createRootNode, Func <RebelTreeResult> returnResult, Func <HiveId, FormCollection, RebelTreeResult> returnDefaultResult) { if (queryStrings.GetValue <bool>(TreeQueryStringParameters.RenderParent)) { //if the requested node does not equal the root node set, then set the _dynamicRootNodeId if (!parentId.Value.Equals(actualRootNodeId.Value)) { _dynamicRootNodeId = parentId; } //need to remove the query strings we don't want passed down to the children. queryStrings.Remove(TreeQueryStringParameters.RenderParent); nodeCollection.Add(createRootNode(queryStrings)); return(returnResult()); } return(returnDefaultResult(parentId, queryStrings)); }
public ActionResult Profile(FormCollection _vars) { var user = Membership.GetUser(Guid.Parse(_vars["UserGuid"])); var prfMgr = new UserProfileManager(user); UserProfileViewModel viewModel = new UserProfileViewModel() { AccountProperties = new UserProfileManager(user).UserProfile.Properties, UserId = (Guid)user.ProviderUserKey, Email = user.Email, }; user.Email = _vars["Email"]; string currPwd = _vars["CurrentPassword"]; string newPwd = _vars["NewPassword"]; string newPwdConfirmation = _vars["NewPasswordConfirmation"]; if (!string.IsNullOrWhiteSpace(currPwd)) { // attempt to change the user's password if (string.IsNullOrWhiteSpace(newPwd)) { ModelState.AddModelError("NewPassword", "Você deve digitar a nova senha."); return(View(viewModel)); } if (string.IsNullOrWhiteSpace(newPwdConfirmation)) { ModelState.AddModelError("NewPassword", "Você deve digitar a confirmação da nova senha."); return(View(viewModel)); } if (newPwdConfirmation != newPwd) { ModelState.AddModelError("NewPassword", "A nova senha e a confirmação devem ser iguais."); ModelState.AddModelError("NewPasswordConfirmation", "A nova senha e a confirmação devem ser iguais."); return(View(viewModel)); } if (!user.ChangePassword(currPwd, newPwd)) { ModelState.AddModelError("CurrentPassword", "Não foi possível trocar sua senha. Verifique sua senha atual e tente novamente."); return(View(viewModel)); } } if (_vars["Administrator"] != null) { if (!Roles.IsUserInRole(user.UserName, "administrators")) { Roles.AddUserToRole(user.UserName, "administrators"); } } else if (Roles.IsUserInRole(user.UserName, "administrators")) { Roles.RemoveUserFromRole(user.UserName, "administrators"); } _vars.Remove("UserGuid"); _vars.Remove("Email"); _vars.Remove("CurrentPassword"); _vars.Remove("NewPassword"); _vars.Remove("NewPasswordConfirmation"); _vars.Remove("Administrator"); foreach (string key in _vars.Keys) { prfMgr.SetUserProfileProperty(key, _vars[key]); } try { Membership.UpdateUser(user); } catch (ProviderException e) { ModelState.AddModelError("Email", "Ocorreu um erro atualizar seus dados. " + e.Message); return(View(viewModel)); } TempData["Message"] = "Dados salvos com sucesso."; return(RedirectToAction("Index", "Home")); }
public void EditRecords(TempLedgerBranch postData, FormCollection collection, DataTable DtTbl) { // if (ModelState.IsValid) //{ try { List <TempLedgerBranch> test = new List <TempLedgerBranch>(); if (collection["oper"] == "edit") { collection.Remove("oper"); string id = collection["id"]; var EditRecord = test.Where(x => x.Sno == id).SingleOrDefault(); test.Remove(EditRecord); test.Add(postData); Session["postData"] = test; GetRecords("", "asc", 1, 100, true); } else if (collection["oper"] == "add" && postData.Code != null) { try { //collection.Remove("oper"); // collection.Remove("id"); postData.RecordKey = 0; postData.UserId = "1"; postData.AccPeriod = ""; postData.Audited = true; postData.AuthIds = ""; postData.Authorise = ""; postData.BankCode = postData.BankCode; postData.BillDate = System.DateTime.Now; postData.BillNo = "333"; postData.Branch = postData.Branch; postData.Cheque = postData.Cheque; postData.ChequeReturn = true; postData.ChqCategory = 12; postData.ClearDate = System.DateTime.Now; postData.Code = postData.Code; postData.CostCentre = postData.CostCentre; postData.Credit = postData.Credit; postData.CurrAmount = 124; postData.CurrName = "Dipti"; postData.CurrRate = 154; postData.Debit = postData.Debit; postData.DocDate = System.DateTime.Now; postData.HWSerial = ""; postData.MainType = ""; postData.Narr = postData.Narr; postData.OSAdj = ""; postData.Party = ""; postData.PCCode = ""; postData.PeriodCode = ""; postData.Prefix = ""; postData.ProjectCode = ""; postData.ProjectStage = ""; postData.ProjectUnit = ""; postData.RecoFlag = ""; postData.RefDoc = ""; postData.SLCode = ""; postData.Sno = postData.Sno; postData.Srl = ""; postData.SubType = ""; postData.TDSCode = ""; postData.TDSFlag = false; postData.TouchValue = 1; postData.Type = ""; postData.ValueDate = System.DateTime.Now; postData.xBranch = ""; postData.EnteredBy = ""; postData.LastUpdateDate = System.DateTime.Now; postData.HWSERIAL2 = ""; DataRow Drow = DtTbl.NewRow(); if (Session.Count != 0) { test = Session["postData"] as List <TempLedgerBranch>; } else { test = new List <TempLedgerBranch>(); } test.Add(postData); Session["postData"] = test; GetRecords("", "asc", 1, 100, true); } catch (Exception ex) { Debug.WriteLine(ex.StackTrace); } } else if (postData.Branch == null) { string[] rowid = { collection["id"] }; string csvString = string.Join(",", rowid); foreach (var id in csvString) { var DeleteRecord = test.Where(x => x.Sno == Convert.ToString(id)).SingleOrDefault(); test.Remove(DeleteRecord); } Session["postData"] = test; GetRecords("", "asc", 1, 100, true); //ctx.SaveChanges(); } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } }
public String saveObject(FormCollection data, HttpPostedFileBase file, IEnumerable <HttpPostedFileBase> files, String parentCategory = "null", String id = null) { if (id == "null" || id == "") //differents ways to receive null from javascript { id = null; } bool access = getpermissions("objects", "u"); if (access == true) { data = CustomForm.unserialize(data); JObject objectArray = new JObject(); try //name must be gived { if (data["txtserie"] == null || data["txtserie"] == "") { return("ingrese un numero de serie"); //name is wrong } objectArray.Add("serie", data["txtserie"].ToString()); data.Remove("txtserie"); } catch (Exception e) { //what to do if name is wrong return("Ha ocurrido un error"); } try //name must be gived { if (data["name"] == null || data["name"] == "") { return("ingrese un nombre"); //name is wrong } objectArray.Add("name", data["name"].ToString()); data.Remove("name"); } catch (Exception e) { //what to do if name is wrong return("Ha ocurrido un error"); } objectArray.Add("hardware_reference", parentCategory); JObject profileFields = new JObject(); //foreach element in the formData, let's append it to the jsonData in the profileFields foreach (String key in data.Keys) { profileFields.Add(key, data[key]); } objectArray.Add("profileFields", profileFields); String jsonData = JsonConvert.SerializeObject(objectArray); String auxid = id; id = _hardwareTable.SaveRow(jsonData, id); return("Guardado Correctamente"); } else { return(null); } }
/// <summary> /// Validate Instant Transaction Notification Callback /// </summary> /// <param name="form">List of parameters</param> /// <param name="order">Order</param> /// <returns>true if there are no errors; otherwise false</returns> protected bool ValidateITN(FormCollection form, out Order order) { order = null; //validate order Guid orderGuid; if (!Guid.TryParse(form["m_payment_id"], out orderGuid)) { return(false); } order = _orderService.GetOrderByGuid(orderGuid); if (order == null) { _logger.Error(string.Format("PayFast ITN error: Order with guid {0} is not found", orderGuid)); return(false); } //validate merchant ID if (!form["merchant_id"].Equals(_payFastPaymentSettings.MerchantId, StringComparison.InvariantCulture)) { _logger.Error("PayFast ITN error: Merchant ID mismatch"); return(false); } //validate IP address IPAddress ipAddress; if (!IPAddress.TryParse(Request.ServerVariables["REMOTE_ADDR"], out ipAddress)) { _logger.Error("PayFast ITN error: IP address is empty"); return(false); } var validIPs = new[] { "www.payfast.co.za", "sandbox.payfast.co.za", "w1w.payfast.co.za", "w2w.payfast.co.za" }.SelectMany(dns => Dns.GetHostAddresses(dns)); if (!validIPs.Contains(ipAddress)) { _logger.Error(string.Format("PayFast ITN error: IP address {0} is not valid", ipAddress)); return(false); } //validate data form.Remove("signature"); var parameters = HttpUtility.ParseQueryString(string.Empty); parameters.Add(form); var postData = Encoding.Default.GetBytes(parameters.ToString()); var request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/eng/query/validate", _payFastPaymentSettings.UseSandbox ? "https://sandbox.payfast.co.za" : "https://www.payfast.co.za")); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postData.Length; try { using (var stream = request.GetRequestStream()) { stream.Write(postData, 0, postData.Length); } var httpResponse = (HttpWebResponse)request.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var responseParams = HttpUtility.ParseQueryString(streamReader.ReadToEnd()); if (!responseParams.ToString().StartsWith("VALID", StringComparison.InvariantCulture)) { _logger.Error("PayFast ITN error: passed data is not valid"); return(false); } } } catch (WebException) { _logger.Error("PayFast ITN error: passed data is not valid"); return(false); } //validate payment status if (!form["payment_status"].Equals("COMPLETE", StringComparison.InvariantCulture)) { _logger.Error(string.Format("PayFast ITN error: order #{0} is {1}", order.Id, form["payment_status"])); return(false); } return(true); }
public FileResult getCSV(string from = "") { FormCollection form = new FormCollection(); foreach (string key in Request.QueryString.AllKeys) { if (key != "limit" && key != "offset") { form.Add(key, Request.QueryString[key]); } } var wb = new XLWorkbook(); JsonCsTableHelper table = new JsonCsTableHelper(db, form, Request.QueryString); form.Remove("limit"); form.Remove("offset"); table.TableName = "[BaseViewRelation]"; table.PrimaryKey = "id"; string[] hides = table.hideColumns; List <string> tohide = hides.ToList(); //tohide.Add("column"); //tohide.Remove("creationDate"); if (!string.IsNullOrEmpty(from)) { string[] relation = from.Split(':'); table.AdditionalWhere = $"{relation[0]}='{relation[1]}'"; tohide.Add(relation[0]); } table.hideColumns = tohide.ToArray(); table.ReplacedText.Add("id", ("Id")); table.ReplacedText.Add("tableFrom", ("Table From")); table.ReplacedText.Add("fkColumn", ("Fk Column")); table.ReplacedText.Add("pkColumn", ("Pk Column")); table.ReplacedText.Add("pkColumnName", ("Pk Column Name")); table.ReplacedText.Add("tableTo", ("Table To")); table.SearchCondition = " id like '%{0}%' OR tableFrom like '%{0}%' OR fkColumn like '%{0}%' OR pkColumn like '%{0}%' OR pkColumnName like '%{0}%' OR tableTo like '%{0}%' "; table.VarName = "csBaseViewRelation"; table.ReferenceText = "seViewRelation"; table.Links.Add(new CsTableLink() { ButtonType = CsTableLinkType.button, Href = URLHelper.getActionUrl("BaseViewRelation", "Form"), Title = "Edit", Css = "btn btn-warning btn-circle refreshTable", Icon = BaseUIIconText.fa.fa_fa_pencil }); table.Links.Add(new CsTableLink() { ButtonType = CsTableLinkType.deleteButton, Href = URLHelper.getActionUrl("BaseViewRelation", "Delete"), Title = "Delete", Css = "btn btn-danger btn-circle refreshTable", Icon = BaseUIIconText.fa.fa_fa_trash_o }); if (Request.QueryString.AllKeys.Contains("filter")) { table.buildDataTable(Request.QueryString["filter"]); } else { table.buildDataTable(""); } foreach (DataRow item in table.Data.Rows) { } wb.Worksheets.Add(table.Data, "View Relation"); using (var memoryStream = new MemoryStream()) { wb.SaveAs(memoryStream); byte[] byteInfo = memoryStream.ToArray(); return(File(byteInfo, System.Net.Mime.MediaTypeNames.Application.Octet, String.Format("View Relation Viya Spark {0}.xlsx", DateTime.Now.ToShortDateString()))); } }