Click here to Skip to main content
15,885,985 members
Articles / Desktop Programming / WPF

Building WPF Applications with Self-Tracking Entity Generator - Project Setup

Rate me:
Please Sign up or sign in to vote.
4.80/5 (11 votes)
20 Feb 2012CPOL10 min read 75.3K   4.8K   54  
This article describes the project setup of building a WPF sample application with Self-Tracking Entity Generator for WPF/Silverlight.
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;

#if WPF
namespace SchoolSample.EntityModel
{
    public partial class Course : IClientChangeTracking, IChangeTracking, IRevertibleChangeTracking, IDataErrorInfo, IEditableObject
    {
        #region IClientChangeTracking Interface
    
        /// <summary>
        /// Accepts changes made to the entity object
        /// </summary>
        void IClientChangeTracking.AcceptChanges()
        {
            this.AcceptChanges();
        }
    
        /// <summary>
        /// Rejects changes made to the entity object
        /// </summary>
        void IClientChangeTracking.RejectChanges()
        {
            this.RejectChanges();
        }
    
        /// <summary>
        /// Returns whether the entity object has any changes
        /// </summary>
        public Boolean HasChanges
        {
            get { return _hasChanges; }
            private set
            {
                if (_hasChanges != value)
                {
                    _hasChanges = value;
                    if (_propertyChanged != null)
                    {
                        _propertyChanged(this, new PropertyChangedEventArgs("HasChanges"));
                    }
                }
            }
        }
        private Boolean _hasChanges = true;
    
        /// <summary>
        /// Accepts changes made to the entity object and all objects of its object graph
        /// </summary>
        public virtual void AcceptObjectGraphChanges()
        {
            this.AcceptChanges();
            // call AccetChanges() on all Navigation properties
            foreach (var item in Enrollments)
                item.AcceptChanges();
            if (Instructor != null)
                Instructor.AcceptChanges();
        }
    
        /// <summary>
        /// Rejects changes made to the entity object and all objects of its object graph
        /// </summary>
        public virtual void RejectObjectGraphChanges()
        {
            this.RejectChanges();
            // call RejectChanges() on all Navigation properties
            foreach (var item in Enrollments)
                item.RejectChanges();
            if (Instructor != null)
                Instructor.RejectChanges();
        }
    
        /// <summary>
        /// Returns whether the entity object along with its object graph has any changes
        /// </summary>
        public bool ObjectGraphHasChanges()
        {
            return ObjectGraphHasChanges(new List<object>());
        }
    
        internal virtual bool ObjectGraphHasChanges(List<object> objectList)
        {
            // if already visited this object, just return false
            if (objectList.Any(n => ReferenceEquals(n, this))) return false;
    
            var hasChanges = HasChanges;
            if (hasChanges) return true;
    
            // if not, add itself to the visited graph
            var visitedGraph = objectList.ToList();
            visitedGraph.Add(this);
    
            // call ObjectGraphHasChanges() on all Navigation properties
            foreach (var item in Enrollments)
            {
                hasChanges = item.ObjectGraphHasChanges(visitedGraph);
                if (hasChanges) return true;
            }
            if (Instructor != null)
            {
                hasChanges = Instructor.ObjectGraphHasChanges(visitedGraph);
                if (hasChanges) return true;
            }
            return false;
        }
    
        /// <summary>
        /// Returns the estimate size of the entity object along with its object graph
        /// </summary>
        public long EstimateObjectGraphSize()
        {
            long size = 0;
            var visitedGraph = new List<object>();
            EstimateObjectGraphSize(ref size, ref visitedGraph);
            return size;
        }
    
        internal virtual void EstimateObjectGraphSize(ref long size, ref List<object> visitedGraph)
        {
            // if already visited this object, just return
            if (visitedGraph.Any(n => ReferenceEquals(n, this))) return;
    
            size += EstimateSize;
            if (visitedGraph.All(i => !ReferenceEquals(i, this))) visitedGraph.Add(this);
    
            // call EstimateObjectGraphSize() on all Navigation properties
            foreach (var item in Enrollments)
            {
                item.EstimateObjectGraphSize(ref size, ref visitedGraph);
            }
            if (Instructor != null)
            {
                Instructor.EstimateObjectGraphSize(ref size, ref visitedGraph);
            }
        }
    
        /// <summary>
        /// Returns the estimate size of the optimized entity object graph
        /// with only objects that have changes
        /// </summary>
        public long EstimateObjectGraphChangeSize()
        {
            long size = 0;
            if (!ObjectGraphHasChanges()) return size;
            var visitedGraph = new List<object> {this};
            EstimateObjectGraphChangeSize(ref size, visitedGraph);
            return size;
        }
    
        internal virtual void EstimateObjectGraphChangeSize(ref long size, List<object> objectList)
        {
    
            size += EstimateSize;
    
            // call EstimateObjectGraphChangeSize() on all Navigation properties that has change
            foreach (var n in Enrollments)
            {
                // if n has already been visited, we need to skip it
                if (objectList.All(i => !ReferenceEquals(i, n)))
                {
                    if (ChangeTracker.ObjectsAddedToCollectionProperties.ContainsKey("Enrollments")
                        && ChangeTracker.ObjectsAddedToCollectionProperties["Enrollments"].Contains(n))
                    {
                        // if n exists in ObjectsAddedToCollectionProperties, we need to add its size
                        var visitedGraph = objectList.ToList();
                        visitedGraph.Add(n);
                        n.EstimateObjectGraphChangeSize(ref size, visitedGraph);
                    }
                    else if (n.ObjectGraphHasChanges(objectList))
                    {
                        // if n has changes, we also need to add its size
                        var visitedGraph = objectList.ToList();
                        visitedGraph.Add(n);
                        n.EstimateObjectGraphChangeSize(ref size, visitedGraph);
                    }
                }
            }
            // if Instructor has already been visited, we need to skip it
            if (Instructor != null && objectList.All(i => !ReferenceEquals(i, Instructor)))
            {
                if (Instructor.ObjectGraphHasChanges(objectList))
                {
                    var visitedGraph = objectList.ToList();
                    visitedGraph.Add(Instructor);
                    Instructor.EstimateObjectGraphChangeSize(ref size, visitedGraph);
                }
            }
        }
    
        /// <summary>
        /// Returns an optimized entity object graph with only objects that have changes
        /// </summary>
        public IObjectWithChangeTracker GetObjectGraphChanges()
        {
            if (!ObjectGraphHasChanges()) return null;
    
            var item = this.Clone();
            var visitedGraph = new List<object> { item };
    
            // loop through all navigation properties and trim any unchanged items
            item.TrimUnchangedEntities(visitedGraph);
    
            return item;
        }
    
        internal virtual void TrimUnchangedEntities(List<object> objectList)
        {
            bool changeTrackingEnabled = ChangeTracker.ChangeTrackingEnabled;
            this.StopTracking();
    
            // trim all navigation property items that do not have any change
            foreach (var n in Enrollments.ToList())
            {
                // if n has already been visited, we need to skip it
                if (objectList.All(i => !ReferenceEquals(i, n)))
                {
                    if (ChangeTracker.ObjectsAddedToCollectionProperties.ContainsKey("Enrollments")
                        && ChangeTracker.ObjectsAddedToCollectionProperties["Enrollments"].Contains(n))
                    {
                        // if n exists in ObjectsAddedToCollectionProperties, we need to keep it
                        var visitedGraph = objectList.ToList();
                        visitedGraph.Add(n);
                        n.TrimUnchangedEntities(visitedGraph);
                    }
                    else if (n.ObjectGraphHasChanges(objectList))
                    {
                        // if n has changes, we also need to keep it
                        var visitedGraph = objectList.ToList();
                        visitedGraph.Add(n);
                        n.TrimUnchangedEntities(visitedGraph);
                    }
                    else
                    {
                        Enrollments.Remove(n);
                    }
                }
            }
            // if Instructor has already been visited, we need to skip it
            if (Instructor != null && objectList.All(i => !ReferenceEquals(i, Instructor)))
            {
                if (Instructor.ObjectGraphHasChanges(objectList))
                {
                    var visitedGraph = objectList.ToList();
                    visitedGraph.Add(Instructor);
                    Instructor.TrimUnchangedEntities(visitedGraph);
                }
                else
                {
                    Instructor = null;
                }
            }
    
            ChangeTracker.ChangeTrackingEnabled = changeTrackingEnabled;
        }

        #endregion
        #region IClientChangeTracking Helper Property
    
        internal virtual long EstimateSize
        {
            get
            {
                long _size = 0;
                // estimate size of all Primitive Properties
                _size += sizeof(Int32);    // CourseId
                _size += sizeof(Int32);    // InstructorId
                if (Title != null)
                    _size += Title.Length * sizeof(char);    // Title
                if (Version != null)
                    _size += Version.Length * sizeof (Byte);    // Version
                return _size;
            }
        }

        #endregion
        #region IChangeTracking and IRevertibleChangeTracking interfaces
    
        void IChangeTracking.AcceptChanges()
        {
            this.AcceptChanges();
        }
    
        bool IChangeTracking.IsChanged
        {
            get { return HasChanges; }
        }
    
        void IRevertibleChangeTracking.RejectChanges()
        {
            this.RejectChanges();
        }

        #endregion
        #region IDataErrorInfo interface
    
        private Dictionary<string, ValidationResult> _validationErrors;
    
        protected Dictionary<string, ValidationResult> ValidationErrors
        {
            get
            {
                if (_validationErrors == null)
                {
                    _validationErrors = new Dictionary<string, ValidationResult>();
                }
                return _validationErrors;
            }
        }
    
        string IDataErrorInfo.Error
        {
            get
            {
                if (ValidationErrors.ContainsKey(string.Empty))
                {
                    return ValidationErrors[string.Empty].ErrorMessage;
                }
                return null;
            }
        }
    
        string IDataErrorInfo.this[string propertyName]
        {
            get
            {
                if (propertyName == null)
                {
                    propertyName = string.Empty;
                }
    
                if (ValidationErrors.ContainsKey(propertyName))
                {
                    return ValidationErrors[propertyName].ErrorMessage;
                }
                return null;
            }
        }

        #endregion
        #region IDataErrorInfo Protected & Private Helper Methods
    
        /// <summary>
        /// Declares a new error for the property name provided, or the entity if
        /// propertyName is String.Empty/null.
        /// </summary>
        protected void AddError(string propertyName, ValidationResult validationResult)
        {
            if (validationResult == null)
            {
                throw new ArgumentNullException("validationResult");
            }
    
            if (propertyName == null)
            {
                propertyName = string.Empty;
            }
    
            if (!ValidationErrors.ContainsKey(propertyName))
            {
                ValidationErrors.Add(propertyName, validationResult);
                OnPropertyChanged(propertyName);
            }
        }
    
        /// <summary>
        /// Removes one specific error for the provided property name.
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="validationResult"></param>
        protected void RemoveError(string propertyName, ValidationResult validationResult)
        {
            if (validationResult == null)
            {
                throw new ArgumentNullException("validationResult");
            }
    
            if (propertyName == null)
            {
                propertyName = string.Empty;
            }
    
            if (ValidationErrors.ContainsKey(propertyName))
            {
                if (string.Equals(ValidationErrors[propertyName].ErrorMessage, validationResult.ErrorMessage, StringComparison.CurrentCulture))
                {
                    // This entity no longer exposes error for this property name.
                    ValidationErrors.Remove(propertyName);
                    OnPropertyChanged(propertyName);
                }
            }
        }
    
        /// <summary>
        /// Removes the known errors for the provided property name.
        /// </summary>
        /// <param name="propertyName">Propery name or String.Empty/null for top-level errors</param>
        protected void ClearErrors(string propertyName)
        {
            if (propertyName == null)
            {
                propertyName = string.Empty;
            }
    
            if (ValidationErrors.ContainsKey(propertyName))
            {
                // This entity no longer exposes error for this property name.
                ValidationErrors.Remove(propertyName);
                OnPropertyChanged(propertyName);
            }
        }
    
        /// <summary>
        /// Removes the known errors for all property names.
        /// </summary>
        protected void ClearErrors()
        {
            foreach (string propertyName in ValidationErrors.Keys.ToList())
            {
                // This entity no longer exposes error for this property name.
                ValidationErrors.Remove(propertyName);
                OnPropertyChanged(propertyName);
            }
        }
    
        /// <summary>
        /// Gets or sets a value indicating whether to suspend validation
        /// whenever any entity property changes.
        /// </summary>
        public Boolean SuspendValidation;
    
        /// <summary>
        /// Gets a value indicating whether or not top-level validation rules
        /// must be applied whenever any entity property changes.
        /// </summary>
        protected static Boolean ValidateEntityOnPropertyChanged;
    
        /// <summary>
        /// Removes any known errors for the provided property name
        /// by calling ClearErrors()
        /// </summary>
        /// <param name="propertyName">Propery name or String.Empty/null for top-level errors</param>
        partial void PropertySetterEntry(string propertyName)
        {
            if (IsDeserializing || SuspendValidation)
            {
                return;
            }
    
            if (ValidateEntityOnPropertyChanged)
            {
                ClearErrors();
            }
            else
            {
                ClearErrors(propertyName);
            }
        }
    
        /// <summary>
        /// Validates for any known errors for the provided property name
        /// </summary>
        /// <param name="propertyName">Propery name or String.Empty/null for top-level errors</param>
        /// <param name="propertyValue">Property value</param>
        partial void PropertySetterExit(string propertyName, object propertyValue)
        {
            if (IsDeserializing || SuspendValidation)
            {
                return;
            }
    
            if (ValidateEntityOnPropertyChanged)
            {
                Validate(string.Empty, this);
            }
            else
            {
                Validate(propertyName, propertyValue);
            }
        }

        #endregion
        #region IEditableObject interface
    
        private Dictionary<string , object> _cache;
    
        public virtual void BeginEdit()
        {
            if (_cache == null) _cache = new Dictionary<string, object>();
            // copy all Primitive Properties except the primary key fields
            _cache["InstructorId"] = InstructorId;
            _cache["Title"] = Title;
            _cache["Version"] = Version;
            // copy all Navigation Properties
            _cache["Enrollments"] = Enrollments;
            _cache["Instructor"] = Instructor;
            // copy ChangeTracker
            _cache["ChangeTracker"] = ChangeTracker.Clone();
        }
    
        public virtual void CancelEdit()
        {
            if (_cache == null) _cache = new Dictionary<string, object>();
            if (_cache.Count == 0) return;
            bool changeTrackingEnabled = ChangeTracker.ChangeTrackingEnabled;
            this.StopTracking();
            // copy all Primitive Properties except the primary key fields
            if (InstructorId != (int)_cache["InstructorId"])
                InstructorId = (int)_cache["InstructorId"];
            else
                OnPropertyChanged("InstructorId");
            if (Title != (string)_cache["Title"])
                Title = (string)_cache["Title"];
            else
                OnPropertyChanged("Title");
            if (Version != (byte[])_cache["Version"])
                Version = (byte[])_cache["Version"];
            else
                OnPropertyChanged("Version");
            // copy all Navigation Properties
            Enrollments = (TrackableCollection<Enrollment>)_cache["Enrollments"];
            Instructor = (Instructor)_cache["Instructor"];
            // copy ChangeTracker
            ChangeTracker = (ObjectChangeTracker)_cache["ChangeTracker"];
            ChangeTracker.ChangeTrackingEnabled = changeTrackingEnabled;
            _cache.Clear();
        }
    
        public virtual void EndEdit()
        {
            if (_cache == null) _cache = new Dictionary<string, object>();
            _cache.Clear();
        }

        #endregion
    }
}
#endif

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
Weidong has been an information system professional since 1990. He has a Master's degree in Computer Science, and is currently a MCSD .NET

Comments and Discussions