Set ModelState Based on Server Side Query Result in MVC5 - model-view-controller

I have a query that tests for a valid postcode entry:
using (_ctx)
{
try
{
var pc = _ctx.tblPostcodes.Where(z => z.Postcode == postcodeOutward)
.Select(x => new { postcodeId = x.PostcodeID }).Single();
pcId = pc.postcodeId;
}
catch (Exception)
{
pcId = 0;
Response.Redirect("./");
}
}
I don't like how I've done it. It's clumsy and it doesn't show an error (this is my first MVC project).
I'd rather it return a validation error against the Postcode textbox. I have model annotations for various input mistakes, but have to check the postcode against the database.
Any suggestions on how to set ModelState to get a proper response?

You could try:
if(this.ModelState.ContainsKey("postcodeOutward"))
this.ModelState.Add("postcodeOutward", new ModelState());
ModelState state = this.ModelState["postcodeOutward"];
state.Errors.Add("<error_message>");
state.Value = new ValueProviderResult(postcodeOutward, postcodeOutward == null ? "" : postcodeOutward.ToString(), CultureInfo.CurrentCulture);
You could also try having a custom validation attribute that will perform a check against the database and that should automatically populated the this.ModelState property, but I'm not too sure if accessing the database inside of a validation attribute would be a good/recommened approach to take.

Related

How to update only one property of model?

I'm working on user consents. In my request I have these properties:
$newsLetters (bool|nullable),
$sms (bool|nullable),
$billEmail (bool|nullable),
I need update only one. So I need to find one which is not null and update it, if in my request is more than one properties with bool values i need to throw exception.
How can I achieve this?
My request extends spatie/laravel-data.
I don't understand why would you handle something like this on the backend (you can use radio button for this and always send only one value), you can use validation for requests or something like this:
$newsLetters = null;
$sms = true;
$billEmail = null;
$values = [$newsLetters, $sms, $billEmail];
$filter = sizeof(array_filter($values, function($el) { return $el === null;})) < 2;
if($filter) {
//return exception or whatever
} else {
//update values
}

How to search exact record by asp.net web api with help of lamda expresion

I am facing a problem in searching a exact record by LINQ query method in ASP.NET Web API my controller. This is my code:
[HttpGet]
[Route("api/tblProducts/AllProductbySearch/{SearchText}")]
[ResponseType(typeof(IEnumerable<tblProduct>))]
public IHttpActionResult AllProductbySearch(string SearchText)
{
IEnumerable<tblProduct> tblProduct = db.tblProducts.Where(x=>x.PrdKeyword.Contains(SearchText)).AsEnumerable();
if (tblProduct == null)
{
return NotFound();
}
return Ok(tblProduct);
}
In this I am searching the record with value have keyword column and getting the result but problem is that it is not giving exact result for example if in database two record have keyword column value like shirt and another have Tshirt
Then if I pass shirt in SearchText or pass tshirt in SearchText it is giving both record while I want one record which exact match with SearchText. Please help me
My updated action method code is:
[HttpGet]
[Route("api/tblProducts/AllProductbySearch/{SearchText}")]
[ResponseType(typeof(IEnumerable<tblProduct>))]
public IHttpActionResult AllProductbySearch(string SearchText)
{
IEnumerable<tblProduct> tblProduct = db.tblProducts.Where(x => CheckWord(x.PrdKeyword, SearchText)).AsEnumerable();
if (tblProduct == null)
{
return NotFound();
}
return Ok(tblProduct);
}
private bool CheckWord(string source, string searchWord)
{
var punctuation = source.Where(Char.IsPunctuation).Distinct().ToArray();
var words = source.Split().Select(x => x.Trim(punctuation));
return words.Contains(searchWord, StringComparer.OrdinalIgnoreCase);
}
But is throwing the same error - http 500
EDITED 2
Added ToList() - db.tblProducts.ToList().... In this case we retrieve all data from Data Base and filter them in memory. If we don't retrieve all data before filtering .Net tries to create request to SQL with filtration and can't because there are .Net methods as CheckWord().
I think we can get required data without retrieving all table into memory, but don't know how. As variant we should write specific Stored Procedure and use it. Get all into memory is a simplest way (but not faster)
Please, look at this post Get only Whole Words from a .Contains() statement
Actually, for your case solution can be:
IEnumerable<tblProduct> tblProduct = db.tblProducts.ToList()
.Where(x => Regex.Match(x.PrdKeyword, $#"\b{SearchText}\b", RegexOptions.IgnoreCase).Success)
.AsEnumerable();
Option 2. Without regexp:
public static bool CheckWord(string source, string searchWord)
{
if (source == null)
return false;
var punctuation = source.Where(Char.IsPunctuation).Distinct().ToArray();
var words = source.Split().Select(x => x.Trim(punctuation));
return words.Contains(searchWord, StringComparer.OrdinalIgnoreCase);
}
[HttpGet]
[Route("api/tblProducts/AllProductbySearch/{SearchText}")]
[ResponseType(typeof(IEnumerable<tblProduct>))]
public IHttpActionResult AllProductbySearch(string SearchText)
{
IEnumerable<tblProduct> tblProduct = db.tblProducts.ToList()
.Where(x => CheckWord(x.PrdKeyword, SearchText)).AsEnumerable();
if (tblProduct == null)
{
return NotFound();
}
return Ok(tblProduct);
}
Sorry, I'm from phone now, there can be mistakes here. Will try it in 3-4 hour
You are making a simple mistake. You just need to use .Equals instead of .Contains.
When you use Contains .Net will check if the input string is part of the main string. Whereas Equals will check for exact match.
var mainStr = “long string with Hello World”;
var inputStr = “Hello”;
var status = mainStr.Contains(inputStr);
// Value of status is `true`
status = mainStr.Equals(inputStr);
// Value of status is `false`
So your code should look like this:
IEnumerable<tblProduct> tblProduct = db.tblProducts.Where(x=>x.PrdKeyword.Equals(SearchText)).AsEnumerable();
.Equals can also help you find exact match with or without having case-sensitive check in force. The single-parameterised method does a Case-Sensitive check whereas the other overridden methods of .Equals gives you an opportunity to ignore it.
Hope this helps!

Passing in LUIS entities to bind to dialog state

Can somebody help me interpret what the heck this means from the bot framework documention:
You can also pass in LUIS entities to bind to the state. If the EntityRecommendation.Type is a path to a field in your C# class then the EntityRecommendation.Entity will be passed through the recognizer to bind to your field. Just like initial state, any step for filling in that field will be skipped.
When I call my dialog I pass in my LuisResult result Entities collection like so:
context.Call(new FormDialog<ItemSearch>( new ItemSearch(), ItemSearch.BuildForm, options: FormOptions.PromptInStart,entities:result.Entities), null);
Within those entities is at least one which maps in both name and type to a public property on my dialog however the state never gets filled. What am I missing?
TIA.
You can find an example of this in the PizzaOrderDialog. if you look at FormDialog implementation, it is using the entity.type to map the passed in entity recommendation to a step in the form. Then the detected entities will be provided as an input to that step of the form.
Here is an example of how form can skip the kind step based on the detected entities by Luis model in pizza form:
var entities = new List<EntityRecommendation>(result.Entities);
if (!entities.Any((entity) => entity.Type == "Kind"))
{
// Infer kind
foreach (var entity in result.Entities)
{
string kind = null;
switch (entity.Type)
{
case "Signature": kind = "Signature"; break;
case "GourmetDelite": kind = "Gourmet delite"; break;
case "Stuffed": kind = "stuffed"; break;
default:
if (entity.Type.StartsWith("BYO")) kind = "byo";
break;
}
if (kind != null)
{
entities.Add(new EntityRecommendation(type: "Kind") { Entity = kind });
break;
}
}
}
var pizzaForm = new FormDialog<PizzaOrder>(new PizzaOrder(), this.MakePizzaForm, FormOptions.PromptInStart, entities);
It also appears that there is an issue with passing Entities in. It seems to work if the property you are mapping to is a Enum (as per the PizzaBot sample). However if the public property is a string, it doesn't map. I'm not sure about other types.
See here https://github.com/Microsoft/BotBuilder/issues/151

mvc3 assign anonymous types or workaround

I have a model that is used to modify a user's password and captures the date that the password has been changed. I am getting an error saying property or indexer anonymous type cannot be assigned to it is read only I get that error for both fields the password and CreateDate . I only know of 1 way to select multiple fields from entity and this is it..
var old= db.registration.Where(b => b.email == getid.email).Select
(s => new { s.password, s.CreateDate }).FirstOrDefault();
old.CreateDate = DateTime.Now();
old.password = new.password;
db.Entry(old).State = EntityState.Modified;
db.SaveChanges();
Is there a way that I can assign these new values without getting the error message or a workaround ?
Just select the default object and run with it
var old= db.registration.Where(b => b.email == getid.email).FirstOrDefault();
old.CreateDate = DateTime.Now();
old.password = new.password;
db.Entry(old).State = EntityState.Modified;
db.SaveChanges();
The error message you're getting is likely because you're assigning to the index of an anonymous type, ie.
s => new { s.password, s.CreateDate }
is anonymous and its indexed properties cant be assigned to

Query DB loads one of my object's properties and it shouldn't

In my Edit Controller Action, I post the object to update.
[HttpPost]
public virtual ActionResult Edit(Case myCase){
var currentDocuments = db.CaseDocuments.Where(p => p.idCase == myCase.idCase);
foreach (CaseDocument docInDB in currentDocuments )
{
var deleteDoc = true;
foreach (CaseDocument docNew in myCase.CaseDocuments )
{
if (docNew.idDocument == docInDB.idDocument)
deleteDoc = false;
}
if (deleteDoc )
db.CaseDocuments.Remove(docInDB);
}
foreach (CaseDocument pc in myCase.CaseDocuments)
{
if (pc.idDocument == 0)
db.CaseDocuments.Add(pc);
else
db.Entry(pc).State = EntityState.Modified;
}
*** **db.Entry(myCase).State = EntityState.Modified;** //THIS LINE
db.SaveChanges();
}
The Case model has a collection of Documents, and they are posted along with the Case Model.
As soon I enter the action, I can count the number of documents in the collection, and lets say there are 3.
Then, in order to see if I need to delete documents from database (as the user deleted one from UI), I need to get the Documents for that case from database in this way:
var currentDocuments = db.CaseDocuments.Where(p => p.idCase == myCase.idCase);
And here starts the weird thing: as soon I executa that statement, the myCase.Documents is loaded with what it is in database (lets say there are 4)!! So, I'm not able to compare the 2 collections (to detect if a document was deleted and remove it from db).
What I need is during the Edit Action of my Case model, I need to create/update/modify its documents. Do I need to see this from other angle? What I'm doing is wrong?
EDIT:
After the comments, I realized that the line where I marked myCase as Modified, was at the begining, and I suppose that this was the reason for that behaviour.
Now, moving that line to just before the db.SaveChanges(), fixed that problem, but at the db.Entry(myCase).State = EntityState.Modified; says "There is already an object with the same key in ObjectStateManager. "
What am I doing wrong here? This code looks bad!
Try it this way:
[HttpPost]
public virtual ActionResult Edit(Case myCase){
var currentDocumentIds = db.CaseDocuments
.Where(p => p.idCase == myCase.idCase)
.Select(p => p.idDocument);
foreach (int idInDb in currentDocumentsIds.Where(i => !myCase.CaseDocuments
.Any(ci => ci.idDocumnet == i))
{
var docToDelete = new CaseDocument { idDocument = idInDb };
db.CaseDocuments.Remove(docToDelete);
}
foreach (CaseDocument pc in myCase.CaseDocuments)
{
if (pc.idDocument == 0)
db.CaseDocuments.Add(pc);
else
db.Entry(pc).State = EntityState.Modified;
}
db.Entry(myCase).State = EntityState.Modified;
db.SaveChanges();
}
Edit: The difference between this code and your code is the way how it works with existing documents. It doesn't load them - it loads just their ids. This way you will save some data transfer from database but it should also help you avoiding that exception. When you load the document from the database you have it already attached in the context but if you try to call this:
db.Entry(pc).State = EntityState.Modified;
you will try to attach another instance of the document with the same key to the context. That is not allowed - context can have attached only single instance with unique key.

Resources