KGy SOFT

ValidatingObjectBase Class

KGy SOFT Core Libraries Help
Represents an object with validating capabilities by adding IValidatingObject implementation to the PersistableObjectBase class.
See the Remarks section for details and examples.
Inheritance Hierarchy

SystemObject
  KGySoft.ComponentModelObservableObjectBase
    KGySoft.ComponentModelPersistableObjectBase
      KGySoft.ComponentModelValidatingObjectBase
        KGySoft.ComponentModelModelBase

Namespace:  KGySoft.ComponentModel
Assembly:  KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 5.0.0-rc.1
Syntax

public abstract class ValidatingObjectBase : PersistableObjectBase, 
	IValidatingObject, IDataErrorInfo

The ValidatingObjectBase type exposes the following members.

Constructors

  NameDescription
Protected methodValidatingObjectBase
Initializes a new instance of the ValidatingObjectBase class
Top
Properties

  NameDescription
Public propertyIsModified
Gets whether this instance has been modified. Modified state can be set by the SetModified method.
(Inherited from ObservableObjectBase.)
Public propertyIsValid
Gets whether this instance is valid. That is, if ValidationResults property does not return any entries where the value of Severity is Error.
Public propertyValidationResults
Gets the validation results for this instance.
Top
Methods

  NameDescription
Protected methodAffectsModifiedState
Gets whether the change of the specified propertyName affects the IsModified property.
The EditableObjectBase implementation excludes the IsModified, IsValid and ValidationResults properties.
(Overrides ObservableObjectBaseAffectsModifiedState(String).)
Protected methodCanGetProperty
Gets whether the specified property can be get.
The base implementation allows to get the actual instance properties in this instance.
(Inherited from ObservableObjectBase.)
Protected methodCanSetProperty
Gets whether the specified property can be set.
The base implementation allows to set the actual instance properties in this instance if the specified value is compatible with the property type.
(Inherited from ObservableObjectBase.)
Public methodClone
Creates a new object that is a copy of the current instance.
The base implementation clones the internal property storage, the IsModified property and if clonePropertyChanged is , then also the subscribers of the PropertyChanged event.
(Inherited from ObservableObjectBase.)
Public methodDispose
Releases the resources held by this instance.
(Inherited from ObservableObjectBase.)
Protected methodDispose(Boolean)
Releases the resources held by this instance.
The base implementation removes the subscribers of the PropertyChanged event.
(Inherited from ObservableObjectBase.)
Protected methodDoValidation
Performs the validation on this instance and returns the validation results. Must not return .
Public methodEquals
Determines whether the specified object is equal to the current object.
(Inherited from Object.)
Protected methodFinalize
Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
(Inherited from Object.)
Protected methodGetT(FuncT, String)
Gets the value of a property, or - if it was not set before -, then creates its initial value. The created initial value will be stored in the internal property storage without triggering the PropertyChanged event. For constant or simple expressions, or to return a default value for a non-existing property without storing it internally use the other Get overload.
For an example, see the Remarks section of the ObservableObjectBase class.
(Inherited from ObservableObjectBase.)
Protected methodGetT(T, String)
Gets the value of a property or defaultValue if no value is stored for it. No new value will be stored if the property does not exist. If the default initial value is too complex and should not be evaluated every time when the property is get, or to throw an exception for an uninitialized property use the other Get overload.
For an example, see the Remarks section of the ObservableObjectBase class.
(Inherited from ObservableObjectBase.)
Public methodGetHashCode
Serves as the default hash function.
(Inherited from Object.)
Public methodGetType
Gets the Type of the current instance.
(Inherited from Object.)
Protected methodMemberwiseClone
Creates a shallow copy of the current Object.
(Inherited from Object.)
Protected methodOnPropertyChanged
Raises the PropertyChanged event.
(Overrides ObservableObjectBaseOnPropertyChanged(PropertyChangedExtendedEventArgs).)
Protected methodResetProperty
Resets the property of the specified name, meaning, it will be removed from the underlying storage so the getter methods will return the default value again.
(Inherited from ObservableObjectBase.)
Protected methodResumeChangedEvent
Resumes the raising of the PropertyChanged event suspended by the SuspendChangeEvents method.
(Inherited from ObservableObjectBase.)
Protected methodSet
Sets the value of a property.
For an example, see the Remarks section of the ObservableObjectBase class.
(Inherited from ObservableObjectBase.)
Public methodSetModified
Sets the modified state of this ObservableObjectBase instance represented by the IsModified property.
(Inherited from ObservableObjectBase.)
Protected methodSuspendChangedEvent
Suspends the raising of the PropertyChanged event until ResumeChangeEvents method is called. Supports nested calls.
(Inherited from ObservableObjectBase.)
Public methodToString
Returns a string that represents the current object.
(Inherited from Object.)
Top
Events

  NameDescription
Public eventPropertyChanged
Occurs when a property value changed. The actual type of the event argument is PropertyChangedExtendedEventArgs.
(Inherited from ObservableObjectBase.)
Top
Extension Methods

  NameDescription
Public Extension MethodConvert(Type, CultureInfo)Overloaded.
Converts an Object specified in the obj parameter to the desired targetType.
See the Examples section of the generic ConvertTTarget(Object, CultureInfo) overload for an example.
(Defined by ObjectExtensions.)
Public Extension MethodCode exampleConvertTTarget(CultureInfo)Overloaded.
Converts an Object specified in the obj parameter to the desired TTarget.
(Defined by ObjectExtensions.)
Public Extension MethodIn (Defined by ObjectExtensions.)
Public Extension MethodTryConvert(Type, Object)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired targetType.
(Defined by ObjectExtensions.)
Public Extension MethodTryConvert(Type, CultureInfo, Object)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired targetType.
(Defined by ObjectExtensions.)
Public Extension MethodTryConvertTTarget(TTarget)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired TTarget.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions.)
Public Extension MethodTryConvertTTarget(CultureInfo, TTarget)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired TTarget.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions.)
Top
Remarks

In a derived class the DoValidation method must be overridden.

Validation is automatically performed when the IsValid or ValidationResults property is accessed or when the object is accessed by the standard IDataErrorInfo interface.

IsValid returns  if ValidationResults does not contain any entries with Error severity.

Differences between CanGetProperty/CanSetProperty methods and IsValid/ValidationResults properties:

  • When CanGetProperty and CanSetProperty methods return , then an exception will be thrown when the property is get or set via the ObservableObjectBase and IPersistableObject members. Do not use these methods for business validation. Instead, they can be used to prevent accessing an unknown property or when a property is tried to be set by a value of invalid type.
  • On the other hand, IsValid and ValidationResults properties can be used to indicate whether an object contains problematic values. For every issue a severity level (see ValidationSeverity) and a corresponding message can be assigned. These can be displayed by a UI, for example.

IDataErrorInfo support:
ValidatingObjectBase implements also the System.ComponentModel.IDataErrorInfo interface, which is the oldest standard way in .NET to support validation, therefore it is supported by most frameworks. IDataErrorInfo is able to report errors only, so if warnings and validation infos should also be displayed by a UI, then the object should be accessed via the IValidatingObject interface.

Examples

The following example shows how to implement property validation:
C#
public class MyModel : ValidatingObjectBase
{
    public int Id { get => Get<int>(); set => Set(value); }

    public string Name { get => Get<string>(); set => Set(value); }

    protected override ValidationResultsCollection DoValidation()
    {
        var result = new ValidationResultsCollection();

        // info
        if (Id == 0)
            result.AddInfo(nameof(Id), "This will be considered as a new object when saved");
            // or: result.Add(new ValidationResult(nameof(Id), "This will be considered as a new object when saved", ValidationSeverity.Information));

        // warning
        if (Id < 0)
            result.AddWarning(nameof(Id), $"{nameof(Id)} is recommended to be greater or equal to 0.");

        // error
        if (String.IsNullOrEmpty(Name))
            result.AddError(nameof(Name), $"{nameof(Name)} must not be null or empty.");

        return result;
    }
}
Note Notes to Implementers
For another example see the Remarks section of the ObservableObjectBase class. The same applies also for the ValidatingObjectBase class regarding the ways of defining properties in a derived class.
See Also

Reference