mvc 4 validations using DataAnnotatoins - c#-4.0

Am practising MVC4 validations and got some basic idea. But am not sure where the Error message comes from in my below code and how to override the message
My model:
[Required(ErrorMessage = "Contact number field is required.")]
public int ContactNumber { get; set; }
when i leave the field empty am getting
Contact number field is required
but when i type any string and submit am getting
The value 'string i typed' is not valid for ContactNumber
how to override my error message ?

Add this validation to your propery which matches for valid number. This way you can override it.
[Required(ErrorMessage = "Contact number field is required.")]
[RegularExpression(#"[0-9]*\.?[0-9]+", ErrorMessage = "Contact number must be a Number.")]
public int ContactNumber { get; set; }

The error message you added was in the "Required" attribute, so it only gets used when something fails the "Required" check, ie. when it is left blank. If you want a particular message for when it's not a number then you'll need to add an attribute to check for that too, and give it a custom error message. A regex should do it. As a nice side effect of this, you can also take the opportunity to do some more detailed checking here, like making sure it's actually in phone number format with the right number of digits and stuff, rather than just checking that the value is numeric.

Related

Why I'm getting Muti-part identifier error in view query(after added the newly created extension field into the query?)

Multi-part identifier error
I newly created one extension field in Contacts screen (UsrLocationCD int field). After creatimg that field I added that field into the view query and I got the above error.
The concept is the "Customer and Location ID" (Customer Location screen) should match in Contacts screen "Business Account and Location ID" (Location ID, newly added). After this condition is satisfied that related Contact ID should display in Customer Location screen under the Contacts Tab.
Full concept
This the query what I wrote:
[PXViewName(Messages.Contacts)]
[PXFilterable]
[PXViewSavedDetailsButton(typeof(Location))]
public PXSelectJoin<Contact,
LeftJoin<Address, On<Address.addressID, Equal<Contact.defAddressID>>>,
Where<Contact.bAccountID, Equal<Current<Location.bAccountID>>,
And<Where<ContactExt.usrLocationCD, Equal<Location.locationID>,
And<Where<Contact.contactType, Equal<ContactTypesAttribute.person>,
Or<Contact.contactType, Equal<ContactTypesAttribute.lead>>>>>>>> Contacts;
here is the newly created extension field:
public class ContactExt : PXCacheExtension<PX.Objects.CR.Contact> /*, IBqlTable*/
{
#region UsrLocationCD
[PXDBInt()]
[PXUIField(DisplayName = "Location ID")]
[PXSelector(
typeof(Search<Location.locationID, Where<Location.bAccountID,
Equal<Current<Contact.bAccountID>>>>),
SubstituteKey = typeof(Location.locationCD), ValidateValue = false)]
public virtual int? UsrLocationCD { get; set; }
public abstract class usrLocationCD : PX.Data.BQL.BqlInt.Field<usrLocationCD> { }
#endregion
}
I'm sharing one point here that newly created extension field is not creating any problem in the Contacts screen, successfully I'm able to saving the record you can see the below imgs.
Before saving the record
After saving the record
In the contacts screen location id field is "Int".
Where is the mistake and how to overcome this issue?
Your PXSelect is missing a Current<> on where you added in your usrLocationCD.
Original line with missing Current<>:
And<Where<ContactExt.usrLocationCD, Equal<Location.locationID>,
After adding the missing Current<> back in:
[PXViewName(Messages.Contacts)]
[PXFilterable]
[PXViewSavedDetailsButton(typeof(Location))]
public PXSelectJoin<Contact,
LeftJoin<Address, On<Address.addressID, Equal<Contact.defAddressID>>>,
Where<Contact.bAccountID, Equal<Current<Location.bAccountID>>,
And<Where<ContactExt.usrLocationCD, Equal<Current<Location.locationID>>,
And<Where<Contact.contactType, Equal<ContactTypesAttribute.person>,
Or<Contact.contactType, Equal<ContactTypesAttribute.lead>>>>>>>> Contacts;
When selecting data, you always must connect the referenced DAC's in some way... either by joining directly to another table selected in the join, by joining the field to a Current value (such as a field in a parent view), or by supplying a parameter that you pass in.
Also, for consistency, I'd recommend changing the name of your new field from usrLocationCD to usrLocationID. ID means "identifier" and CD means "code". LocationID (the identifier) is the integer field used to identify the Location record, in this case. LocationCD is the field of the Location record that contains the Location Code that we normally see in the display. When another Acumatica developer looks at the code above, the first impression is that you are trying to relate a string field to an integer field. Technically, as long as your field type matches on both sides of the equals then it will work, but consistency is important in coding standards.
In the above code, join is missed for location DAC. I hope this may help you.
[PXViewName(PX.Objects.CR.Messages.Contacts)]
[PXFilterable]
[PXViewSavedDetailsButton(typeof(Location))]
public PXSelectJoin<Contact,
LeftJoin<Address, On<Address.addressID, Equal<Contact.defAddressID>>,
LeftJoin<Location, On <Location.bAccountID,Equal<Contact.bAccountID>>>>,
Where<Contact.bAccountID, Equal<Current<Location.bAccountID>>,
And<Where<ContactExt.usrLocationCD, Equal<Location.locationID>,
And<Where<Contact.contactType, Equal<ContactTypesAttribute.person>,
Or<Contact.contactType, Equal<ContactTypesAttribute.lead>>>>>>>> Contacts;

JHipster: jhi-alert-error element and server side form validation?

I am using JHipster 3.3. In the generated "entity"-dialog.html, I noticed the tag jhi-alert-error element will display server validation error so for example if a field is mandatory as specified in entity JPA class like
#NotNull
private String name;
Then error message for that field will be returned after clicking the Submit button if value of the field is empty.
So questions:
How is jhi-alert-error implemented? I can't seem to see its implementation
I tried tweaking JPA annotation to make a field unique BUT this time no error message will be displayed in jhi-alert-error if I break the unique constraint by adding 2 records having the same value for the field,
E.g.
// note 'unique=true' below
#NotNull
#Column(name = "name", unique=true)
private String name;
or
#Table(name="Module", uniqueConstraints = #UniqueConstraint(columnNames = "Name"))
public Class Module implements Serializable { ...
So how would I go about implementing my own server side form validation so error messages will be displayed in jhi-alert-error when the unique constraint of a field is broken after clicking the Submit button?
Thanks in advance,
I'm using a slightly older version of jhipster (2.26), so there could be some differences in the code. To answer your first question the jhi-alert-error is a custom Angular directive, have a look at the alert.directive.js file and the jhAlertError directive (should appear after the jhAlert directive). The directive expects the httpResponse.data object to be the ErrorDTO server side object.
To add custom error messages, you need to return an ErrorDTO object and the directive will display the message. To do this you need to throw an exception and ensure that the spring AOP - ExceptionTranslator is configured to catch it. If you don't want to create new custom Exceptions, you can use the CustomParameterizedException:
#RequestMapping(value = "/pizzas",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public ResponseEntity<Pizza> create(#RequestBody Pizza pizza) throws URISyntaxException {
if(pizza.isDisgusting()){
throw new CustomParameterizedException("Sorry, your pizza recipe is horrible");
}
log.debug("REST request to save Pizza : {}", pizza);
if (pizza.getId() != null) {
return ResponseEntity.badRequest().header("Failure", "A new pizza cannot already have an ID").body(null);
}
Pizza result = pizzaRepository.save(pizza);
return ResponseEntity.created(new URI("/api/pizzas/" + pizza.getId())).body(result);
}

Setting up Error message DataAnnotation in Unique constraint in code first approach in Entity Framework

I made this model class.Here I set Email property as a Unique key. When I try to insert existing Email it shows unique key error. Thats fine, but I want to set error message DataAnnotations in the model class.
Here is the code:
[String Length(450)]
[Index("IX_FirstAndSecond",1,IsUnique=true)]
public string Email { get; set; }
How can i do this?

RavenDB: Raven Query not returning correct count with document authorization

public class EngineInfo
{
public int Id{get;set;}
public int? AircraftId { get; set; }
public string SerialNumber { get; set; }
public int Position { get; set; }
public string RegNumber { get; set; }
}
// Here is the code which uses the above model. I have 17,000 documents with this model
ravenSession.Store(new AuthorizationUser
{
Id = "Authorization/Users/1",
Name = "user-1",
Permissions =
{
new OperationPermission
{
Allow = true,
Operation = "EngineInfos/View",
Tags = "Company/100"
}
}
});
1. var query = ravenSession.Query<EngineInfo>();
// When I log query.Count(), I see all the documents count ie., 17000, This is ignoring the authorization I set in the before statement. If I add where clause to the above statement it is working and I could see the correct count. But I want to get all the documents for which the user has authorization to.
2. var query = ravenSession.Query<EngineInfo>().ToList();
Now, I get the correct count considering authorization. But the problem is unless I mention Take(x), it will not return all the results.
I tried with
RavenQueryStatistics queryStats;
query.Statistics(out queryStats);
queryStats.TotalResults
I still could not get the authorizes results. I get all the count.
Could you please help me figuring out in finding TotalCount of the query results without loading all records?
My requirement is to display all engines in an searchable ExtJS paging grid. I need to know the total count of the records to display calculate and display the number of pages(page count is fixed).
This is by design, see http://ravendb.net/docs/intro/safe-by-default.
session.Query<Post>().Count() will give you the count of all the posts on the server, while session.Query<Post>().ToList().Count() will give the count of the posts that was fetched to the client.
By default, RavenDB apply .Take(128) to the query, in order to encourage you to do paging and be safe by default. If you want to get more then that you need to specify how much to take, like .Take(1024), but by default the server will not return more then 1024 items at once. You can configure the server to do so, but this is not recommended. You much better use paging as the user cannot handle that much on info at once anyway.
What you're seeing is that Raven's QueryStatistics ignore the Authorization bundle. This has been reported in the Raven Google Group.
As far as I can tell, there isn't, at the time of this writing, a reliable way to get the total count of authorized documents for a query. It seems to me that the Authorization bundle should include some support for this.
I'll look into it and update this answer as I find out more.

service stack wildcard path with swagger

I'm using ServiceStack and have the route like this:
[Route("/hello/{Name*}")]
So anything like /hello/some/parameters should be handled.
Swagger use the following url: /hello/{Name*} and no matter what value I provide for Name parameter I get the following message when I hit "Try it out button":
A potentially dangerous client value Request.Path retrieved from the client(*).
Note, I'm using the following ApiMember attribute:
[ApiMember(Name = "Params", DataType = "string", ParameterType = "path" , IsRequired = true)]
and still any text I input is overriden with * and I have the error as above.
Is there any workaround for this?
First, the error is occurring because the Swagger call is using the default value of {Name*} in the path/request. (*) is not allowed in the path of the URL.
By using the correct attributes in your ServiceStack class, you should be able to get a text box to enter your own value within the Swagger UI.
Something like below should get the text box to appear. See https://github.com/ServiceStack/ServiceStack.UseCases/tree/master/SwaggerHelloWorld for examples.
public class Hello {
[ApiMember(Name=”Name*”, Description = “Name Description”, ParameterType = “path”, DataType = “string”, IsRequired = true)]
public string Name {get; set; }
}

Resources