C# MVC CMS - Customising Remote Validation - c#

At the link below I asked a question about how to ensure a field does not already contain the same value (for example when there is a unique constraint on a field which correctly causes C# to throw an exception when voilated). With the answer I received, it solved that problem but presented another.
Ensuring another record does not already contain the same value for a field
The main issue I now have is that when I create a new View. The validation works as expected. In brief - The system needs to check that the ViewName and ViewPath (route) are both unique so a search of the DB is required.
However, when I edit the view, the validation kicks in again (and it actually should not because obviously the view exists already because you are editing it).
My issue now is how do I customise the remote validation to work differently for edit vs create. While we should not be able to edit the name of a view to match an existing view, we should also not be stopped from saving the current view simply because it is the same as the current view.
Below is my Model (the part that is not (hopefully) generated by a tool :-):
[MetadataType(typeof(IViewMetaData))]
public partial class View : IViewMetaData { }
public interface IViewMetaData
{
[Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(DALResources), ErrorMessageResourceName = "ErrorRequiredField")]
[StringLength(50, ErrorMessageResourceType = typeof(DALResources), ErrorMessageResourceName = "ErrorLessThanCharacters")]
[Display(ResourceType = typeof(DALResources), Name = "ViewName")]
[Remote("IsViewNameAvailable", "Validation")]
string ViewName { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(DALResources), ErrorMessageResourceName = "ErrorRequiredField")]
[StringLength(400, ErrorMessageResourceType = typeof(DALResources), ErrorMessageResourceName = "ErrorLessThanCharacters")]
[Display(ResourceType = typeof(DALResources), Name = "ViewPath")]
[Remote("IsViewPathAvailable", "Validation")]
string ViewPath { get; set; }
[Display(ResourceType = typeof(DALResources), Name = "ViewContent")]
string ViewContent { get; set; }
}
The part I am having a problem with is the [Remote] validation attribute which is defined below:
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public class ValidationController : Controller
{
private FRCMSV1Entities db = new FRCMSV1Entities();
public JsonResult IsViewNameAvailable(View view)
{
bool isViewNameInvalid = db.View.Any(v => v.ViewName == view.ViewName && v.Id != view.Id);
if (!isViewNameInvalid)
return Json(true, JsonRequestBehavior.AllowGet);
string suggestedViewName = string.Format(UI_Prototype_MVC_Resources.ErrorViewAlreadyExists, view.ViewName);
for (int i = 1; i < 100; i++)
{
string altViewName = view.ViewName + i.ToString();
bool doesAltViewNameExist = db.View.Any(v => v.ViewName == altViewName);
if (!doesAltViewNameExist)
{
suggestedViewName = string.Format(UI_Prototype_MVC_Resources.ErrorViewNotAvailableTry, view.ViewName, altViewName);
break;
}
}
return Json(suggestedViewName, JsonRequestBehavior.AllowGet);
}
public JsonResult IsViewPathAvailable(View view)
{
bool doesViewPathExist = db.View.Any(v => v.ViewPath == view.ViewPath && v.Id != view.Id);
if (!doesViewPathExist)
return Json(true, JsonRequestBehavior.AllowGet);
string suggestedViewPath = string.Format(UI_Prototype_MVC_Resources.ErrorViewAlreadyExists, view.ViewPath);
for (int i = 1; i < 100; i++)
{
string altViewPath = view.ViewPath + i.ToString();
bool doesAltViewPathExist = db.View.Any(v => v.ViewPath == altViewPath);
if (!doesAltViewPathExist)
{
suggestedViewPath = string.Format(UI_Prototype_MVC_Resources.ErrorViewNotAvailableTry, view.ViewPath, altViewPath);
break;
}
}
return Json(suggestedViewPath, JsonRequestBehavior.AllowGet);
}
}
The problem is, the validation needs to work the same on both create and edit. It just needs to do an additional check on edit to ensure we are still referring to the same record and if so, then there is no need to show the validation message because there is nothing wrong.
My question is:
1. How do I get this to work as expected.
2. I can see that both methods are pretty much identical, which violates the DRY principle. How can I make this more generic and simplify it. However the first question is really the one I would like answered because there is no point in refactoring something that doesn't work.
For more information, the above code is also an edit of the code at the following link:
https://msdn.microsoft.com/en-us/library/gg508808(VS.98).aspx
Thanks for any help.

You need to add a parameter to pass the ID property of the model as AdditionalFields. Assuming its int Id, then
[Remote("IsViewPathAvailable", "Validation", AdditionalFields = "Id")]
public string ViewName { get; set; }
and the the method should be
public JsonResult IsViewNameAvailable(string viewName, int? id)
Note that in the Edit view, you include a hidden input for the Id property, so its value will be posted back by the jquery.validate remote function.
You can then check if the id parameter is null (i.e. it's new) or has a value (it's existing) and adjust the queries to suit.
bool isViewNameInvalid;
if (id.HasValue)
{
isViewNameInvalid = db.View.Any(v => v.ViewName == viewName && v.Id != id);
}
else
{
isViewNameInvalid = db.View.Any(v => v.ViewName == ViewName);
}
What is currently happening is that the Remote is only posting the value of the ViewName property, and because your parameter is the model, it is initialized with the default id value (0) and your query is translated to Any(v => v.ViewName == viewName && v.Id != 0);
I also recommend using a view model rather that your partial class
Side note: from the code that generates suggestedViewName, your expecting a lot of ViewName with the same value, meaning your possibly making numerous database calls inside you for loop. You could consider using linq .StartsWith() query to get all the records that start with your ViewName value, and then check the in-memory set in your loop.

Related

DevForce Validation returning Ok for navigation properties that have not been set

I have been working on validatin for our entities in DevForce and I have managed to get everything I need working aside from validating Navigation Properties.
I have tried placing a RequiredValueVerifier attribute on the property and that does show the validation error on the UI but as soon as I use Manager.VerifierEngine.Execute({entitytovalidate}) the result comes back as Ok.
I know DevForce creates nullos and we can modify what the properties have in said nullos but I would like a way that the VeirifierEngine would return not Ok when we have not updated the value from the nullo.
My current work-around is to have a secondary Int32RangeVerifier on the Id that is used for the FKey but I am not to happy with that as a work-around.
Trying to do this without having to create Verifier Providers just for these properties.
If anyone has a solution to this I would be greatly appreciative if you could share.
Here is a sample of the current work-around:
namespace BearPaw.Models.Main
{
[MetadataType(typeof(TechnicianNoteMetadata))]
public partial class TechnicianNote {
public static TechnicianNote Create(int byUserId, DateTimeZone clientZone, DateTime userUtc)
{
var newItem = new TechnicianNote()
{
CreatedById = byUserId,
CreatedDate = userUtc,
CreatedDateTz = clientZone.Id,
ModifiedById = byUserId,
ModifiedDate = userUtc,
ModifiedDateTz = clientZone.Id
};
return newItem;
}
}
public class TechnicianNoteMetadata
{
[Int32RangeVerifier(ErrorMessage = "Note Category is required", MinValue = 1)]
public static int NoteCategoryId;
[RequiredValueVerifier(DisplayName = "Note Category")]
public static NoteCategory NoteCategory;
[RequiredValueVerifier(DisplayName = "Note Detail")]
public static string NoteDetail;
}
}
Many thanks in advance
You can create a custom verifier to handle navigation property validation, and add it directly to the VerifierEngine with the AddVerifier method if you don't want to use an IVerifierProvider.
For example:
public class NullEntityVerifier : PropertyValueVerifier
{
public NullEntityVerifier(
Type entityType,
string propertyName,
string displayName = null)
: base(new PropertyValueVerifierArgs(entityType, propertyName, true, displayName)) { }
public NullEntityVerifier(PropertyValueVerifierArgs verifierArgs)
: base(verifierArgs) { }
protected override VerifierResult VerifyValue(object itemToVerify, object valueToVerify, TriggerContext triggerContext, VerifierContext verifierContext)
{
var entity = valueToVerify as Entity;
var msg = $"{this.ApplicableType.Name}.{this.DisplayName} is required.";
return new VerifierResult(entity != null && !entity.EntityAspect.IsNullEntity, msg);
}
}
To add to the engine:
var verifier = new NullEntityVerifier(typeof(TechnicianNote), "NoteCategory");
_em1.VerifierEngine.AddVerifier(verifier);
If you want to stick with attributed verifiers you can create a custom attribute for your verifier. See the DevForce Resource Center for more information.

MVC model properties returning default value

Something weird is happening and I am not able to understand why.. here's the scenario -
I have a model with few properties when I populate the model the properties in model does have values set (checked by putting breakpoints). It comes on the view also but it is not being shown on textbox. It is showing the default value (guessing by seeing the item textbox on the page as it has 0).
Below is my model -
public class PriceEnquiryModel
{
[DisplayName("Item")]
public int item { get; set; }
[DisplayName("Description")]
public string description { get; set; }
[DisplayName("UOP")]
public string uop { get; set; }
[DisplayName("UOS")]
public string uos { get; set; }
[DisplayName("Pack Description")]
public string pack_description { get; set; }
[DisplayName("Pack Size")]
public string PackSize { get; set; }
}
This is the controller;s code -
public ActionResult Search(PriceEnquiryModel price)
{
var priceEnquiryModel = new PriceEnquiryModel();
// Read parameter values from form.
int item = Convert.ToInt32(Request.Form["txtSearch"].ToString());
int maxrow = Convert.ToInt32(Request.Form["txtmaxrow"].ToString());
string priceType = !string.IsNullOrWhiteSpace(price.priceType) && price.priceType.ToUpper().Equals("STA") ? "N" : "Y";
// Get the price information
var operationResult = priceBal.SearchPriceEnquiry(0, item, price.price_scheme, priceType, maxrow);
var priceEnquiryDomList = (List<PriceEnquiryDom>)operationResult[0].Result;
// Check if we have something
if (priceEnquiryDomList != null && priceEnquiryDomList.Count > 0)
{
// Parse the model.
priceEnquiryModel = helper.ConvertDomToModel(priceEnquiryDomList[0]);
// Prepare the list.
priceEnquiryModel.PriceEnquiryModelList = new List<PriceEnquiryModel>();
foreach (var priceEnquiryDom in priceEnquiryDomList)
{
var priceEnquiryModelListItem = helper.ConvertDomToModel(priceEnquiryDom);
priceEnquiryModel.PriceEnquiryModelList.Add(priceEnquiryModelListItem);
}
Session["mainModel"] = priceEnquiryModel;
}
// Prepare product drop down list items if searched by product desc
if (TempData.Count > 0 && TempData["Products"] != null)
{
var products = TempData["Products"] as List<ProductSearchByDescModel>;
ViewBag.Products = products;
}
return View("Index", priceEnquiryModel);
}
This is the model on the View (while debugging) -
This is how I am rendering the model on the view -
This is the page after running -
Does anyone has any idea what is going on ? I have done the same thing on multiple pages and all run as expected.
Thanks in Advance.
Rohit
The issue is that your method has parameter PriceEnquiryModel price but then you return a new instance of PriceEnquiryModel (named priceEnquiryModel). The process of model binding includes binding your model and adding its values to ModelState (along with any validation errors).
When you return the view, the html helper methods use the values from ModelState (not the models values) so attempting to change the values (which I assume is what priceEnquiryModel = helper.ConvertDomToModel(priceEnquiryDomList[0]); is doing) is ignored by the helpers.
For an explanation of why this is the default behavior, refer the second part of this answer
One option to call ModelState.Clear() before setting new values for the properties of PriceEnquiryModel

Entity Framework 6.1 Updating a Subset of a Record

I have a view model that encapsulates only some of the database model properties. These properties contained by the view model are the only properties I want to update. I want the other properties to preserve their value.
During my research I found this answer which appears to be perfect for my needs however, despite my best efforts, I cannot get the code to work as expected.
Here is an isolated example of what I came up with:
static void Main() {
// Person with ID 1 already exists in database.
// 1. Update the Age and Name.
Person person = new Person();
person.Id = 1;
person.Age = 18;
person.Name = "Alex";
// 2. Do not update the NI. I want to preserve that value.
// person.NINumber = "123456";
Update(person);
}
static void Update(Person updatedPerson) {
var context = new PersonContext();
context.Persons.Attach(updatedPerson);
var entry = context.Entry(updatedPerson);
entry.Property(e => e.Name).IsModified = true;
entry.Property(e => e.Age).IsModified = true;
// Boom! Throws a validation exception saying that the
// NI field is required.
context.SaveChanges();
}
public class PersonContext : DbContext {
public DbSet<Person> Persons { get; set; }
}
public class Person {
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Age { get; set; } // this is contrived so, yeah.
[Required]
public string NINumber { get; set; }
}
What am I doing wrong?
You based your work on the post https://stackoverflow.com/a/15339512/2015959, but in the other thread the fields that weren't changed (and as such weren't in the attached model) weren't mandatory, and that's why it worked. Since your fields are required, you'll get this validation error.
Your problem can be solved by the solution provided in question Entity Framework validation with partial updates
It is the validation that is causing it not to be saved. You can disable validation with context.Configuration.ValidateOnSaveEnabled = false; and it will work. To validate specific fields you can call var error = entry.Property(e => e.Name).GetValidationErrors();. So you certainly can make an 'UpdateNameAndAge' method that only only enforces business rules and flags those properties as modified. No double query required.
private static bool UpdateNameAndAge(int id, string name, int age)
{
bool success = false;
var context = new PersonContext();
context.Configuration.ValidateOnSaveEnabled = false;
var person = new Person() {Id = id, Name = name, Age = age};
context.Persons.Attach(person);
var entry = context.Entry(person);
// validate the two fields
var errorsName = entry.Property(e => e.Name).GetValidationErrors();
var errorsAge = entry.Property(e => e.Age).GetValidationErrors();
// save if validation was good
if (!errorsName.Any() && !errorsAge.Any())
{
entry.Property(e => e.Name).IsModified = true;
entry.Property(e => e.Age).IsModified = true;
if (context.SaveChanges() > 0)
{
success = true;
}
}
return success;
}
(Edited for clarity)
The context must have a complete copy of the object to enforce business rules. This can only happen if the attached object has all the necessary properties populated or the partial view is merged with a complete copy before updating.
I believe that what you want to do is conceptually impossible: doing updates like this will require either a preserved pre-change copy, or two queries to the database because the business layer needs a full copy of the object for validation.

Performing an effcient upsert in mongodb

I have the following C# model class:
public class Thingy
{
public ObjectId Id { get; set; }
public string Title { get; set; }
public DateTime TimeCreated { get; set; }
public string Content { get; set; }
public string UUID { get; set; }
}
and the following ASP.MVC controller action:
public ActionResult Create(Thingy thing)
{
var query = Query.EQ("UUID", thing.UUID);
var update = Update.Set("Title", thing.Title)
.Set("Content", thing.Content);
var t = _collection.Update(query, update, SafeMode.True);
if (t.UpdatedExisting == false)
{
thing.TimeCreated = DateTime.Now;
thing.UUID = System.Guid.NewGuid().ToString();
_collection.Insert(thing);
}
/*
var t = _collection.FindOne(query);
if (t == null)
{
thing.TimeCreated = DateTime.Now;
thing.UUID = System.Guid.NewGuid().ToString();
_collection.Insert(thing);
}
else
{
_collection.Update(query, update);
}
*/
return RedirectToAction("Index", "Home");
}
This method either does an update or insert. If it needs to do an insert, it must set the UUID and TimeCreated members. If it needs to do an update, it must leave UUID and TimeCreated alone, but must update the members Title and Content.
The code that's commented out works, but does not seem to be most efficient. When it calls FindOne, that is one trip to mongodb. Then if it goes to the else clause, it does another query and an update operation, so that's 2 more trips to mongodb.
What is a more efficient way to do what I'm trying to accomplish?
As mentioned in the linked SO answer, for upserts to work, you need to update the entire document, not just a few properties.
Personally I would separate the Create and Edit into separate MVC actions. SRP. Creating a Thingy has different considerations from updating it.
If you still want to do an upsert instead of separate insert/update calls, you will need to use the following code:
_collection.Update(
Query.EQ("UUID", thing.UUID),
Update.Replace(thing),
UpsertFlags.Upsert
);
The question now becomes, how do we ensure the thing has the appropriate values for both cases, ie insert as well as update.
My assumption is (based on your code model binding to a Thingy instance), your view is sending back all fields (including UUID and TimeCreated). Which implies, in case of an update, the view already has the values pre-populated for UUID and TimeCreated. So in the case of a Thingy being updated, the thing object has the latest values.
Now in case of an create, when the view is rendered, you could store DateTime.MinValue for the TimeCreated field. In your Create MVC action, you could check if TimeCreated is DateTime.MinValue, then set it to current time and also store a new value for UUID.
This way, in the case of a insert as well, the thing has the latest values. We can thus safely do an Upsert.
I take this approach when doing upserts for Mongo from the controller
public ActionResult Create(Thingy model)
{
var thing = _collection.FindOneAs<Thingy>(Query.EQ("UUID", model.UUID));
if(thing == null)
{
thing = new Thingy{
TimeCreated = DateTime.Now,
UUID = System.Guid.NewGuid().ToString(),
Id = ObjectId.GenerateNewId()
}
}
else
{
thing.Content = model.Content;
//other updates here
}
_collection.Save<Thingy>(thing);
return View();
}

Data Annotations Custom Validator not working (as I'd expect) in MVC2

Before I start ... I can't easily migrate the project to MVC3. So.
The problem I'm having is that I've defined a custom validator attribute to check the max AND min length of a string property, StringLengthInRangeAttribute.
When the Controller calls ModelState.IsValid, on a list of Passengers only the validation of a Date property is throwing invalid, when nothing has been supplied. I guess that means my problem is not with the custom validator but all validation?
Update (additional info for clarity):
I have two symptoms of this problem :
1.The Required validator on the strings doesn't fire when they are empty
and
2.My custom validator never gets called (a breakpoint I set never gets hit).
Model:
public class Passenger
{
[Required(ErrorMessageResourceType = typeof(Resources.Messages.Passenger),
ErrorMessageResourceName = "RequireNumber")]
public int Number { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Messages.Passenger),
ErrorMessageResourceName = "RequireSurname")]
[StringLengthInRange(MinLength = 2, MaxLength = 30, ErrorMessageResourceType = typeof(Resources.Messages.Passenger),
ErrorMessageResourceName = "MaxLengthSurname")]
public string Surname { get; set; }
}
Custom Validator:
public class StringLengthInRangeAttribute:ValidationAttribute
{
public int MinLength { get; set; }
public int MaxLength { get; set; }
public override bool IsValid(object value)
{
if (((string)value).Length < MinLength)
{
return false;
}
if (((string)value).Length > MaxLength)
{
return false;
}
return true;
}
}
Controller Action:
public ViewResult TailorHoliday(List<SearchAndBook.Models.ViewModels.Passenger> passengers,
int leadPassengerIndex)
{
if(!ModelState.IsValid)
{
return View("PassengerDetails", GetBookingState(_currentSession));
}
//...
return View();
}
Any advice appreciated. This is the first time I've used Data Annotations, so I'm quite prepared to feel stupid for missing something!
If you check the content of the ModelState property (in the debugger) you should be able to see every property that gets validated in ModelState.Keys and for each value you see the actual state in the ModelState.Values. If I look at your controller you seem to post a whole list of passengers. You should check as well, whether your values are really posted (use Firebug or Fiddler). Maybe your fields are outside the form.
Maybe you should show part of your view as well to spot the bug.

Categories