This question mayt sound duplicate but I am not satisfied with any of the answers as some are suggesting MVC Foolproof validaiton for conditional validaiton and some tells it dont work well with entity framework
I am using MVC Foolproof RequiredIf validation in my project.It works well on clientside and is validation is working on server side as well.
[RequiredIf("STCompulsory",Operator.EqualTo,true,ErrorMessage="Please enter Registration No")]
public string STRegNo { get; set; }
But when i call db.Savechanges() to insert data an exception is coming
An unexpected exception was thrown during validation of 'STRegNo' when invoking
Foolproof.RequiredIfAttribute.IsValid. See the inner exception for details.
InnerException
The method or operation is not implemented.
You do not need the Operator.EqualTo parameter and it can be simply
[RequiredIf("STCompulsory", true, ErrorMessage="Please enter Registration No")
public string STRegNo { get; set; }
You are correct in that the foolproof [RequiredIf] attribute does have some problems with EF and it is discussed in detail in this work issue (along with some suggested changes).
The easiest solution is to use a view model rather than your data model in the view, and apply the attribute to the view model property.
Related
I got a problem with my WCF service. Here is the
[OperationContract]
[WebGet(UriTemplate = "/needs", ResponseFormat = WebMessageFormat.Json)]
List<CustomerNeed> getAllCustomerNeeds();
When I go on the page which call this service, I got this error
GET http://localhost:666/rest/Service1.svc/needs net::ERR_CONNECTION_RESET
When I'm trying to return a string instead of a List, it works.
CustomerNeed is a class generate from my database via EntityFramework.
In my service, I'm only calling an other method which is in an other class;
public List<CustomerNeed> getAllCustomerNeeds()
{
var needs = from cn in db.CustomerNeeds
select cn;
List<CustomerNeed> list = new List<CustomerNeed>();
foreach (CustomerNeed cusN in needs)
{
list.Add(cusN);
}
return list;
}
Maybe is it because I have a foreign key in my table CustomerNeed ?
When I do "LINQ to entities" to import my database, do I have to import tables that were created because of many to many relation ?
I will recommend you to create a simple custom class which will represent your CustomerNeeds database entity, initiate this object on the server side and pass to the client application. It can help you to avoid this problem and also it is recommended way to transfer data accross the WCF services.
In this case you need to do the next steps:
1) Create a public class CustomerNeeds and mark it with the DataContract attribute. For example:
[DataContract]
public class CustomerNeeds
{
[DataMember]
public SomeDataType PropertyName {get; set;}
}
2) Initiate this object on the service, change return datatype in getAllCustomerNeeds() method from the entity class to the newly created class CustomerNeed and pass this data to the clien
And that`s all.
You haven't shown where/what db is, but I'm assuming if you're using entity framework as your tag implies it's a entities context. You might be having some issues with the context already being disposed or not newed up correctly (though I would have expected you to receive a slightly different error if that's the case.)
It looks like you're going through some unnecessary steps in your function, I would think something like this would work:
public List<CustomerNeed> getAllCustomerNeeds()
{
using (var db = new YourContext()) // plug in your context object
{
return db.CustomerNeeds.ToList();
}
}
Additionally when you say it "works as a string" are you returning something small like "hello world"? you might need to take a look at your WCF configuration to make sure it can handle the amount of data you're trying to pass back and forth.
Hope this helps!
We are running into a very odd problem: We are using entity framework 4 and ria services for a silverlight 5 appliation hosted in IIS 6.1. For long periods of time, everything is running smoothly, but occasionally the application fails with the following error message in the event log:
WebHost failed to process a request. Sender Information:
System.ServiceModel.Activation.HostedHttpRequestAsyncResult/56703158
Exception: System.ServiceModel.ServiceActivationException: The service
'/Services/EcoFleet-DomainServices-Repository-EcofleetRepository.svc'
cannot be activated due to an exception during compilation. The
exception message is: The Entity 'DeviceData' in DomainService
'EcofleetRepository' does not have a key defined. Entity types exposed
by DomainService operations must have at least one public property
marked with the KeyAttribute.. ---> System.InvalidOperationException:
The Entity 'DeviceData' in DomainService 'EcofleetRepository' does not
have a key defined. Entity types exposed by DomainService operations
must have at least one public property marked with the
KeyAttribute. at
System.ServiceModel.DomainServices.Server.DomainServiceDescription.ValidateEntityTypes()
at
System.ServiceModel.DomainServices.Server.DomainServiceDescription.Initialize()
at
System.ServiceModel.DomainServices.Server.DomainServiceDescription.CreateDescription(Type
domainServiceType) at
System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey
key, Func2 valueFactory) at
System.ServiceModel.DomainServices.Server.DomainServiceDescription.GetDescription(Type
domainServiceType) at
System.ServiceModel.DomainServices.Hosting.DomainServiceHost..ctor(Type
domainServiceType, Uri[] baseAddresses) at
System.ServiceModel.DomainServices.Hosting.DomainServiceHostFactory.CreateServiceHost(Type
serviceType, Uri[] baseAddresses) at
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String
constructorString, Uri[] baseAddresses) at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.CreateService(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity) at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(ServiceActivationInfo
serviceActivationInfo, EventTraceActivity eventTraceActivity)
at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity)
--- End of inner exception stack trace --- at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult
result) Process Name: w3wp Process ID: 2300
The application still responds, but no entities can be loaded from the server. After stopping and starting the site, everything works again.
The entity in this case (DeviceData) is a database table, and it does have a key, and regardless it seems to be random which entity fails. Furthermore I would only expect to see the "key not defined" error at compile time. Does anyone have a clue what the problem is, and how to fix it?
Your DeviceData entity do not have key defined, which is required. You should create property with name Id or DeviceDataId which will be treated as key by convention (Entity Framework currently looks for these properties). Also you can use mappings to set other property as key. This can be achieved with data annotations attributes:
[Key]
public int Foo { get; set; }
Or with fluent mappings:
modelBuilder.Entity<DeviceData>().HasKey(d => d.Foo);
First you won't have an error at compile time because it is not a mandatory thing, but not having one might give you quite the headache, because EF use it in many ways. so you have to redefine your key by naming it Id or DeviceDataId(Using the convention) or define a one from the model.
It seems from your question that there is a key defined for DeviceData, in that case I advice you to relook the properties of the key column in your model.
remember also that not having a key column might reduce the performance of your app.
I'm a C# developer but I read nearly every tutorial about cqrs out there, doesn't matter if the language was Java, because I want to learn the structure and base of cqrs.
But now I think, the fact that I read so much tutorials is the problem because there are differences in the tutorials and now I'm confused and don't know which technique I have to use.
Two main questions are running wild in my head and maybe some of you can bring some clarity in there.
On the command side, where should I place the logic to call my ORM for example?
Some tutorials do that in the command handler (what is more logic to me) and some do it in the event handlers which will be fired by the command handler which in that case do only validation logic.
For the event store and to undo thinks, which data do I have to save into the db, some tutorials save the aggregate and some save the event model.
I hope that someone can explain me what pattern to use and why, maybe both in different scenarios, I don't know.
An practical example would be great. (Only pseudo code)
Maybe a User registration, RegisterTheUser command:
Things to do:
Check if the username is already in use
Add user to db
Send confirmation mail (In command or in the UserIsRegistered event?)
Fire event ConfirmationMailSended or only UserIsRegistered event?
Kind regards
EDIT:
Here is my current implementation (Simple)
public class RegisterTheUser : ICommand
{
public String Login { get; set; }
public String Password { get; set; }
}
public class RegisterTheUserHandler : IHandleCommand<RegisterTheUser, AccountAggregate>
{
public void Handle(AccountAggregate agg, RegisterTheUser command)
{
if (agg.IsLoginAlreadyInUse(command.Login))
throw new LoginIsAlreadyInUse();
agg.AddUserAccount(command);
CommandBus.Execute<SendMail>(x => { });
EventBus.Raise<UserIsRegistred>(x => { x.Id = agg.UserAccount.Id; });
}
}
public class UserIsRegistred : IEvent
{
public Guid Id { get; set; }
}
public class AccountAggregate : AggregateBase
{
public AccountAggregate(IUnitOfWork uow)
{
UnitOfWork = uow;
}
private IUnitOfWork UnitOfWork { get; set; }
public UserAccount UserAccount { get; set; }
public void AddUserAccount(RegisterTheUser command)
{
UserAccount = new UserAccount
{
Id = Guid.NewGuid(),
IsAdmin = false,
Login = command.Login,
Password = Crypto.Sha512Encrypt(command.Password)
};
UnitOfWork.UserAccountRepository.Add(UserAccount);
UnitOfWork.Commit();
}
public Boolean IsLoginAlreadyInUse(String login)
{
var result = UnitOfWork.UserAccountRepository.SingleOrDefault(x => x.Login == login);
return (result != null);
}
}
So a number of questions, but I'll take a stab at answering.
On the command side, where should I place the logic to call my ORM for
example?
Having this logic either in the command handler or in your event handler, to me, really depends on the type of system you're building. If you have a fairly simple system, you can probably have your persistence logic in your event handlers, which receive events raised by your domain. The thinking here is that your commands handled by the command handler will already have the information needed and your command handler ends up being not much more than a router. If you need more complexity in your command handler, such as dealing with sagas, long running transactions, or some additional layer of validation, then your command handler will use your persistence layer here to pull out data (and perhaps write data) and then route the command to the proper domain or issue more commands or raise events. So I believe it really depends on the level of complexity you're dealing with.
I tend to favor simplicity over complexity when starting out, and would probably look at having that logic in the event handler to begin with. Move to the command handler if your system is more complex.
For the event store and to undo thinks, which data do I have to save
into the db, some tutorials save the aggregate and some save the event
model
I'm not exactly sure what you're asking here, but if you're asking what should be stored in your event store, then I think a simple solution is the aggregate id, the aggregate type, the event with data (serialized) and the event type. Off the top of my head, that's probably the bare bones of what you'd need: based on the aggregate id you're working with, get all the events for that aggregate (in order raised) and then replay them to rebuild the aggregate. I don't think you need to save the aggregate unless there's some compelling reason to (which is always possible).
As for your request for a practical example and the steps you laid out, that's probably a question in and of itself, but my thoughts on that are:
Check if the user name is already in use
Depending on your application, you may want to do this from the read side in your controller (or whichever layer is raising commands) before you issue a command. Validate at that point, but you'd probably want to validate again before persisting it. You could do that in your event handler where it would probably catch an exception because you're violating a unique index in your database.
Add user to DB
Again, my thought is keep it simple and handle it in your event handler, since your domain is raising a UserIsRegistered event.
Send confirmation email
Your domain could raise the UserIsRegistered event and a second event handler (EmailHandler) would also subscribe to that event and send out the email.
ConfirmationMailSent event could be raised by the event handler, added to the event queue and handled accordingly. I guess I'm not sure what you want to happen here.
But, hopefully this helps a bit.
I have a weird problem in that I am trying to edit an existing Company object through a Spring MVC Controller that has a few Validation rules on it. The validation is getting triggered using #Valid.
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#Valid Company company, BindingResult result, SessionStatus status) {
if(result.hasErrors()) {
return view("edit");
} else {
companyService.saveCompany(company);
status.setComplete();
return redirect("?isSaved=true");
}
}
The individual validations on the Company object pass in unit tests. When used in other parts of the application, they work fine. However, for one of the forms, Spring always throws errors like "Field should not be empty" or "the phone number format is wrong", but the data is actually correct.
The worst thing about this situation is that this code has been in play for over a year - it is just a simple "Edit your company info" screen. It has suddenly just stopped working. Regardless of what I submit on the form, Spring will throw these errors.
I have checked and double-checked everything that could be going wrong. It is loading the correct Company object. It is also posting the correct values too. As a sanity check, I even display the exact error objects after I submit the form:
Field error in object 'company' on field 'phoneNumber': rejected value [451-324-3232]; codes [Pattern.company.phoneNumber,Pattern.phoneNumber,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [company.phoneNumber,phoneNumber]; arguments []; default message [phoneNumber],[Ljavax.validation.constraints.Pattern$Flag;#2c99f9,(\()?(\d){3}(\))?(\s|-)(\d){3}(\s|-)(\d){4}]; default message [Must be of the form: ###-###-####]
Field error in object 'company' on field 'name': rejected value [somewhere]; codes [NotEmpty.company.name,NotEmpty.name,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [company.name,name]; arguments []; default message [name]]; default message [Name may not be empty]
Field error in object 'company' on field 'address.address': rejected value [135431]; codes [NotEmpty.company.address.address,NotEmpty.address.address,NotEmpty.address,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [company.address.address,address.address]; arguments []; default message [address.address]]; default message [Address may not be empty]
As you can see, the values are correct, but it's throwing the errors anyway.
Also, the company object has an ID - it's not getting lost or anything like that.
If I remove #Valid, everything works. All the values get changed, so I know it's something directly related to #Valid. But what?
I know you might be thinking that the validation rules must be wrong or something... but they aren't. How can someone mess up #NotEmpty constraints?
public class Company extends DomainObject {
#NotEmpty(message = "{company.name.notEmpty}")
private String name;
#Valid
private Address address = new Address();
#Pattern(message = "{company.phoneNumber.valid}",
regexp = "(\\()?(\\d){3}(\\))?(\\s|-)(\\d){3}(\\s|-)(\\d){4}")
private String phoneNumber = "";
private boolean isEnabled = true;
private boolean homepageViewable = true;
private int coursesCreated = 0;
#Valid
private Theme theme = new Theme();
It doesn't matter what I put into these fields - I still get the errors. Also, when testing these validations in isolation, THEY WORK. In fact, when #Valid is used for the Company object in other parts of the system (like a Registration sign-up form), it works too.
So the only part where it does not work is the Company Profile screens.
Is there any reason why Spring-MVC would do this? I am totally at a loss. I don't even know what the heck I did to cause this problem. It's not like any unit/integration tests have failed as I was making changes. I was never alerted that this was a problem until I manually tried these screens - a common annoyance when using Spring/Java because there are many cases where unit/integration tests are slightly different than using a real production container, so problems slip by anyway.
Please help.
One thought. When company validation works, is it always on a form where the company is part of something bigger? E.g., with registration, the company is part of a registration. But when you try to save the company on a company form, it fails...
Can you try attaching #ModelAttribute to the Company arg? I.e.
#ModelAttribute #Valid Company company
Does it help?
I am using the following in my model for a date control
[DataType(DataType.DateTime)]
public DateTime txtDateAppCompletion { get; set; }
I also tried DataType.Date as I only want a date input.
[DataType(DataType.Date)]
public DateTime txtDateAppCompletion { get; set; }
For some reason when I run the form and I type anything that is not a date it does not validate it, not on server or on client(client validation is enabled).
Any Idea why I am having this problems? How to solve it?
Ok, after some research I found this in a Microsoft book.
■ Caution Even though [DataType] looks
like a validation attribute along with
the others in Data Annotations,
ASP.NET MVC does not treat it as one,
so don’t expect
[DataType(DataType.EmailAddress)] to
validate for legal e-mail addresses!
[DataType] is an anomaly; even though
it inherits from
System.ComponentModel.DataAnnotations.ValidationAttribute,
its IsValid() method is hard-coded to
return true regardless of the
property’s value. Microsoft has
explained that [DataType] is only
meant to serve as a hint for
formatting data in a scaffolded UI...