Can Validator.TryValidateObject force [CustomValidation] attributes to validate a property? - silverlight

I have decorated a property of a class with a CustomValidationAttribute to validate if a GUID value was set but when I try to force it to be executed by using the helper method Validator.TryValidateObject() it seems that it doesn't invoke my validation logic.
The validation logic is being triggered when the value of the decorated property has changed, but I need to handle the scenario wherein the user clicks the save button without filling up required fields, hence the need to force validation attributes to run before a call to DomainContext.SubmitChanges() is called.
Interestingly, even classes that inherit from ValidationAtrribute isn't being run by Validator.TryValidateObject().
What is the correct way to force validation attributes to be executed?

Custom validators applied at the property level will have to be validated separately by using TryValidateProperty.
e.g.
Validator.TryValidateProperty(ViewModel.MyProperty,
new ValidationContext(ViewModel.MyProperty, null, null)
{ MemberName = "MyProperty" }, results);

A more simplistic way of doing this is to set the last parameter (validateAllProperties) on TryValidateObject() to true. See the msdn article for more information.
List<ValidationResult> vr = new List<ValidationResult>();
ValidationContext vc = new ValidationContext(viewModel, null, null);
Validator.TryValidateObject(viewModel, vc, vr, true);

Related

How do you use an Event, given only a name string supplied in xaml?

I've seen in triggers, attached properties, and behaviors the ability to specify SourceObject="myButton" EventName="Click" -- what I want to know is how do you access the event, given its name and owner object, in code? Does this require reflection to implement?
Yes, you use reflection:
var instance = new SomeClassType();
var method = "MyEvent";
var handler = instance.GetType().GetMethod(method);
handler.Invoke(instance, null);

adding required property option not working

I'm trying to add property options to my model. I have a StringProperty and I added required=True but I'm still able to create an object with the required field being empty.
I tried it in the admin and also in my update form for the specific model so not sure what I'm doing wrong?
You can create it, but can you put it?
class x(ndb.Model):
author = ndb.StringProperty(required=True)
a = x()
a.put()
Fails with: BadValueError: Entity has uninitialized properties: **author**
Setting a value on the required property author allows you to save it:
a.author = "some_value"
The put can now succeed.
key = a.put()
and key is now:
Key('x', 5707702298738688)
or even key.urlsafe()
ahNzfnNoYXJlZC1wbGF5Z3JvdW5kcg4LEgF4GICAgICArpkKDKIBEDYwNTM4Njc2MzY2NTQwODA
Read more about storing data here.

ADF ActionListener for operation

I have a button made from a data controls 'CreateInsert' operation.
I have set a boolean in my code (initialized to false) and when the createInsert button is clicked, I want to check this boolean before executing it's operation.
However, in this button's ActionListener, is nothing related to the CreateInsert operation I need to stop if my boolean check returns true..
Now my question is, where is the real Action handling for the CreateInsert button/how can I control it (stop it from executing) in my code?
Thanks in advance!
create a managed bean to the create insert button(I hope u can do that).
now open the managed bean java class , it automatically contains create insert method somewhat like this :::
BindingContainer bindings = getBindings();
OperationBinding operationBinding = bindings.getOperationBinding("CreateInsert1");
Object result = operationBinding.execute();
if (!operationBinding.getErrors().isEmpty()) {
return null;
}
return null;

How to register to receive all property changes in Mvvm-Light

I want a class (called PremiseServer) in my Mvvm-Light solution (WP7) to subscribe to all property changes for classes that are derived from a base type (SysObject is the base class and it derives from ViewModel).
I have a set of classes derived from SysObject. These classes have various properties on them of differing types (Strings, booleans, ints etc...).
When any property on any of these classes changes I want my PremiseServer instance to see these changes and then make web-service calls to push the data to a server.
I have tried this and it never gets called (which makes sense to me now; because the property that is getting changed is not SysObject, but some property OF the SysObject):
Messenger.Default.Register<PropertyChangedMessage<SysObject>>(this, (action) => {
String location = ((SysObject)action.Sender).Location; // URL to POST to
Debug.WriteLine("PremiseServer PropertyChange - " + action.NewValue.ToString());
});
I also tried the below (registering String messages) and it works, but I don't want to create one of these for each property type:
Messenger.Default.Register<PropertyChangedMessage<String>>(this, (action) => {
String location = ((SysObject)action.Sender).Location; // URL to POST to
Debug.WriteLine("PremiseServer PropertyChange - " + action.NewValue.ToString());
});
I also tried Register<PropertyChangeMessage<Object> thinking I'd see messages for all derived types (I didn't).
What I really want is "Register for all property change messags from any property of objects of class SysObject". How can I do that?
Thanks!
You can register for PropertyChangedMessageBase using the Register method overload that has a boolean flag as the last parameter, and setting this flag to true. Like its name shows, this flag allows you to register for a message type, or all messages deriving from this type.
Note that in the handler, you will need to cast the message to the exact type that you want to handle.
Does it make sense?
Cheers,
Laurent
Be careful about this because everywhere in your app where you invoke RaisePropertyChanged(...) this registered listener will see the PropertyChangedMessageBase.
You may have to do something like:
// this registration ensures that if a broadcast is issued for RaisePropertyChanged the vm will acknowledge it and enable IsDirty.
// NOTE: Do not broadcast from IsDirty or we will get into an endless loop here.
Messenger.Default.Register<PropertyChangedMessageBase>(this, true,
(m) =>
{
if (m.Sender != this) return; // we only listen for property changes on ourself
if (IsStartingUp || IsShuttingDown) return;
if (m.PropertyName != IsDirtyPropertyName && m.PropertyName != IsBusyPropertyName && m.PropertyName != IsStartingUpPropertyName && m.PropertyName != IsShuttingDownPropertyName)
IsDirty = true;
});

Silverlight And DataAnnotations

When I am not using data controls like the DataForm and DataGrid is there any use for the attributes like [Required], [StringLength] on my entities? Can these be used for validation outside of the above mentioned data controls?
If so, could you point me to some examples or documentation. I would like to prevent users from pressing the OK button if there are any validation errors and would like to avoid the throwing of exceptions from the setters(possible?).
Yes, those can be used for validation without using UI controls. Brad Abrams has a blog post with details on using those attributes for data forms, but seems like you should be able to separate the UI portion of his post from the core validation logic.
From the post, here's a sample property with validation logic added manually.
[DataMember()]
[Key()]
[ReadOnly(true)]
public int EmployeeID
{
get
{
return this._employeeID;
}
set
{
if ((this._employeeID != value))
{
ValidationContext context = new ValidationContext(
this, null, null);
context.MemberName = "EmployeeID";
Validator.ValidateProperty(value, context);
this._employeeID = value;
this.OnPropertyChanged("EmployeeID");
}
}
}

Resources