Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

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

, 20 Feb 2012
This article describes the project setup of building a WPF sample application with Self-Tracking Entity Generator for WPF/Silverlight.
SchoolSample_20111201.zip
SchoolSample
Local.testsettings
SchoolSample.vsmdi
TraceAndTestImpact.testsettings
Assemblies
GalaSoft.MvvmLight.Extras.WPF4.dll
GalaSoft.MvvmLight.WPF4.dll
Moq.dll
System.Windows.Interactivity.dll
WPFToolkit.Extended.dll
ComponentModel.Composition.Initialization.Desktop
Microsoft
ComponentModel
Composition
Hosting
Internal
Properties
System
ComponentModel
Composition
Hosting
System.Windows.Controls.Data.Input
Common
Properties
Settings.settings
themes
Validation
Database
SchoolSample
SchoolSample.csproj.user
Asset
Control
Properties
Settings.settings
View
SchoolSample.Common
Model
Properties
Resource
SchoolSample.Data
EntityModel
Properties
Validation
SchoolSample.Data.Wcf
EntityModel
SchoolModel.edmx
Properties
Validation
SchoolSample.Model
Properties
SchoolSample.ViewModel
Properties
SchoolSample.Wcf
SchoolSample.Wcf.csproj.user
Properties
Service
SchoolService.svc
SchoolSample.WCFService
SchoolSample.WCFService.csproj.user
Properties
Service References
SchoolService
configuration.svcinfo
configuration91.svcinfo
Reference.svcmap
SchoolService.disco
SchoolService.wsdl
Test.SchoolSample.Model
Properties
Test References
SchoolSample.Model.accessor
Test.SchoolSample.ViewModel
Properties
Test References
SchoolSample.ViewModel.accessor
SchoolSample_20120117.zip
Local.testsettings
SchoolSample.vsmdi
TraceAndTestImpact.testsettings
GalaSoft.MvvmLight.Extras.WPF4.dll
GalaSoft.MvvmLight.WPF4.dll
Moq.dll
System.Windows.Interactivity.dll
WPFToolkit.Extended.dll
Settings.settings
SchoolSample.csproj.user
Settings.settings
SchoolModel.edmx
SchoolSample.Wcf.csproj.user
SchoolService.svc
SchoolSample.WCFService.csproj.user
configuration.svcinfo
configuration91.svcinfo
Reference.svcmap
SchoolService.disco
SchoolService.wsdl
SchoolSample.Model.accessor
SchoolSample.ViewModel.accessor
SchoolSample_20120216.zip
Local.testsettings
SchoolSample.vsmdi
TraceAndTestImpact.testsettings
GalaSoft.MvvmLight.Extras.WPF4.dll
GalaSoft.MvvmLight.WPF4.dll
Moq.dll
System.Windows.Interactivity.dll
WPFToolkit.Extended.dll
Settings.settings
SchoolSample.csproj.user
Settings.settings
SchoolModel.edmx
SchoolSample.Wcf.csproj.user
SchoolService.svc
SchoolSample.WCFService.csproj.user
configuration.svcinfo
configuration91.svcinfo
Reference.svcmap
SchoolService.disco
SchoolService.wsdl
SchoolSample.Model.accessor
SchoolSample.ViewModel.accessor
//------------------------------------------------------------------------------
// <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.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.ServiceModel;

namespace SchoolSample.EntityModel
{
    [DataContract(IsReference = true)]
    [KnownType(typeof(Course))]
    public partial class Instructor : Person, IObjectWithChangeTracker, INotifyPropertyChanged
    {
        #region Primitive Properties
    
        [DataMember]
        [Display(Name="Hire Date", Description="hire date")]
        public Nullable<System.DateTime> HireDate
        {
            get { return _hireDate; }
            set
            {
                if (_hireDate != value)
                {
                    ChangeTracker.RecordOriginalValue("HireDate", _hireDate);
                    PropertySetterEntry("HireDate");
                    _hireDate = value;
                    PropertySetterExit("HireDate", value);
                    OnPropertyChanged("HireDate");
                }
            }
        }
        private Nullable<System.DateTime> _hireDate;
    
        [DataMember]
        [Display(Name="Salary", Description="salary")]
        public Nullable<decimal> Salary
        {
            get { return _salary; }
            set
            {
                if (_salary != value)
                {
                    ChangeTracker.RecordOriginalValue("Salary", _salary);
                    PropertySetterEntry("Salary");
                    _salary = value;
                    PropertySetterExit("Salary", value);
                    OnPropertyChanged("Salary");
                }
            }
        }
        private Nullable<decimal> _salary;

        #endregion
        #region Navigation Properties
    
        [DataMember]
        public TrackableCollection<Course> Courses
        {
            get
            {
                if (_courses == null)
                {
                    _courses = new TrackableCollection<Course>();
                    _courses.CollectionChanged += FixupCourses;
                }
                return _courses;
            }
            set
            {
                if (!ReferenceEquals(_courses, value))
                {
                    if (ChangeTracker.ChangeTrackingEnabled)
                    {
                        throw new InvalidOperationException("Cannot set the FixupChangeTrackingCollection when ChangeTracking is enabled");
                    }
                    if (_courses != null)
                    {
                        _courses.CollectionChanged -= FixupCourses;
                    }
                    _courses = value;
                    if (_courses != null)
                    {
                        _courses.CollectionChanged += FixupCourses;
                    }
                    OnNavigationPropertyChanged("Courses");
                }
            }
        }
        private TrackableCollection<Course> _courses;

        #endregion
        #region ChangeTracking
    
        protected override void ClearNavigationProperties()
        {
            base.ClearNavigationProperties();
            Courses.Clear();
        }

        #endregion
        #region Validation and Helper Method
    
        /// <summary>
        /// Loops through all related data annotation attributes as well as all related
        /// custom validation actions for the specified property name. If  propertyName
        /// is String.Empty/null, the validation is on the entity level.
        /// </summary>
        /// <param name="propertyName">Propery name or String.Empty/null for top-level errors</param>
        /// <param name="value">New value that needs to be validated for the specified property</param>
        public override void Validate(string propertyName, object value)
        {
            // call base Validate() first
            base.Validate(propertyName, value);
            // next, process custom validation actions
            if (ValidationActions.Count == 0) InitializeValidationSettings();
            if (string.IsNullOrEmpty(propertyName))
            {
                // loop through all properties and call its list of validation actions
                foreach (string memberName in ValidationActions.Keys.ToList())
                {
                    List<Action<object>> actions = ValidationActions[memberName];
                    if (string.IsNullOrEmpty(memberName))
                    {
                        // this is top-level validation
                        actions.ForEach(action => action(this));
                    }
                    else
                    {
                        // this is validation for each property
                        object memberValue = GetType().GetProperty(memberName).GetValue(this, null);
                        actions.ForEach(action => action(memberValue));
                    }
                }
            }
            else
            {
                if (ValidationActions.ContainsKey(propertyName))
                {
                    List<Action<object>> actions = ValidationActions[propertyName];
                    actions.ForEach(action => action(value));
                }
            }
        }
    
    #if SILVERLIGHT
        /// <summary>
        /// Client-side validation function to loop through all data annotation
        /// attributes and all custom validation actions.  If any validation fails,
        /// this function will return false. Otherwise, true.
        /// </summary>
        /// <returns></returns>
        public override bool TryValidate()
        {
            // call base TryValidate() first
            base.TryValidate();
            // next, process custom validation actions
            if (ValidationActions.Count == 0) InitializeValidationSettings();
            // loop through all properties and call its list of validation actions
            foreach (string propertyName in ValidationActions.Keys.ToList())
            {
                List<Action<object>> actions = ValidationActions[propertyName];
                if (string.IsNullOrEmpty(propertyName))
                {
                    // this is top-level validation
                    actions.ForEach(action => action(this));
                }
                else
                {
                    // this is validation for each property
                    object value = GetType().GetProperty(propertyName).GetValue(this, null);
                    actions.ForEach(action => action(value));
                }
            }
            return !(((INotifyDataErrorInfo)this).HasErrors);
        }
    
        internal override void TryValidateObjectGraph(ref bool validated, ref List<object> visitedGraph)
        {
            // if already visited this object, just return
            if (visitedGraph.Any(n => ReferenceEquals(n, this))) return;
    
            if (!TryValidate()) validated = false;
            visitedGraph.Add(this);
    
            // call TryValidateObjectGraph() on all Navigation properties
            TryValidateOnNavigationProperties(ref validated, ref visitedGraph);
        }
    
        internal override void TryValidateOnNavigationProperties(ref bool validated, ref List<object> visitedGraph)
        {
            // call base TryValidateOnNavigationProperties() first
            base.TryValidateOnNavigationProperties(ref validated, ref visitedGraph);
            foreach (var item in Courses)
            {
                item.TryValidateObjectGraph(ref validated, ref visitedGraph);
            }
        }
    #elif WPF
        /// <summary>
        /// Client-side validation function to loop through all data annotation
        /// attributes and all custom validation actions.  If any validation fails,
        /// this function will return false. Otherwise, true.
        /// </summary>
        /// <returns></returns>
        public override bool TryValidate()
        {
            // call base TryValidate() first
            base.TryValidate();
            // Next, process custom validation actions
            if (ValidationActions.Count == 0) InitializeValidationSettings();
            // loop through all properties and call its list of validation actions
            foreach (string propertyName in ValidationActions.Keys.ToList())
            {
                List<Action<object>> actions = ValidationActions[propertyName];
                if (string.IsNullOrEmpty(propertyName))
                {
                    // this is top-level validation
                    actions.ForEach(action => action(this));
                }
                else
                {
                    // this is validation for each property
                    object value = GetType().GetProperty(propertyName).GetValue(this, null);
                    actions.ForEach(action => action(value));
                }
            }
            return (ValidationErrors.Count == 0);
        }
    
        internal override void TryValidateObjectGraph(ref bool validated, ref List<object> visitedGraph)
        {
            // if already visited this object, just return
            if (visitedGraph.Any(n => ReferenceEquals(n, this))) return;
    
            if (!TryValidate()) validated = false;
            visitedGraph.Add(this);
    
            // call TryValidateObjectGraph() on all Navigation properties
            TryValidateOnNavigationProperties(ref validated, ref visitedGraph);
        }
    
        internal override void TryValidateOnNavigationProperties(ref bool validated, ref List<object> visitedGraph)
        {
            // call base TryValidateOnNavigationProperties() first
            base.TryValidateOnNavigationProperties(ref validated, ref visitedGraph);
            foreach (var item in Courses)
            {
                item.TryValidateObjectGraph(ref validated, ref visitedGraph);
            }
        }
    #else
        /// <summary>
        /// Server-side validation function to loop through all data annotation
        /// attributes and all custom validation actions.  If any validation fails,
        /// it will throw an exception.
        /// </summary>
        public override void Validate()
        {
            // call base Validate() first
            base.Validate();
            // Next, process custom validation actions
            if (ValidationActions.Count == 0) InitializeValidationSettings();
            // loop through all properties and call its list of validation actions
            foreach (string propertyName in ValidationActions.Keys.ToList())
            {
                List<Action<object>> actions = ValidationActions[propertyName];
                if (string.IsNullOrEmpty(propertyName))
                {
                    // this is top-level validation
                    actions.ForEach(action => action(this));
                }
                else
                {
                    // this is validation for each property
                    object value = GetType().GetProperty(propertyName).GetValue(this, null);
                    actions.ForEach(action => action(value));
                }
            }
        }
    
        internal override void ValidateObjectGraph(ref List<object> visitedGraph)
        {
            // if already visited this object, just return
            if (visitedGraph.Any(n => ReferenceEquals(n, this))) return;
    
            Validate();
            visitedGraph.Add(this);
    
            // call ValidateObjectGraph() on all Navigation properties
            ValidateOnNavigationProperties(ref visitedGraph);
        }
    
        internal override void ValidateOnNavigationProperties(ref List<object> visitedGraph)
        {
            // call base ValidateOnNavigationProperties() first
            base.ValidateOnNavigationProperties(ref visitedGraph);
            foreach (var item in Courses)
            {
                item.ValidateObjectGraph(ref visitedGraph);
            }
        }
    #endif
    	partial void PropertySetterEntry(string propertyName);
        partial void PropertySetterExit(string propertyName, object propertyValue);
        partial void InitializeValidationSettings();
    
        private Dictionary<string, List<Action<object>>> ValidationActions
        {
            get
            {
                if (_validationActions == null)
                {
                    _validationActions = new Dictionary<string, List<Action<object>>>();
                }
                return _validationActions;
            }
        }
        private Dictionary<string, List<Action<object>>> _validationActions;
    
        /// <summary>
        /// Add one validation action for the specified property name.
        /// </summary>
        /// <param name="propertyName">Propery name or String.Empty/null for top-level errors</param>
        /// <param name="validationAction">Function to carry out a specific validation action</param>
        private void AddPropertyValidationAction(string propertyName, Action<object> validationAction)
        {
            List<Action<object>> validationActionList;
            if (!ValidationActions.ContainsKey(propertyName))
            {
                validationActionList = new List<Action<object>>();
                ValidationActions.Add(propertyName, validationActionList);
            }
            else
                validationActionList = ValidationActions[propertyName];
    
            validationActionList.Add(validationAction);
        }

        #endregion
        #region Association Fixup
    
        private void FixupCourses(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (IsDeserializing)
            {
                return;
            }
    
            if (e.NewItems != null)
            {
                foreach (Course item in e.NewItems)
                {
                    item.Instructor = this;
                    if (ChangeTracker.ChangeTrackingEnabled)
                    {
                        if (!item.ChangeTracker.ChangeTrackingEnabled)
                        {
                            item.StartTracking();
                        }
                        ChangeTracker.RecordAdditionToCollectionProperties("Courses", item);
                    }
                }
            }
    
            if (e.OldItems != null)
            {
                foreach (Course item in e.OldItems)
                {
                    if (ReferenceEquals(item.Instructor, this))
                    {
                        item.Instructor = null;
                    }
                    if (ChangeTracker.ChangeTrackingEnabled)
                    {
                        ChangeTracker.RecordRemovalFromCollectionProperties("Courses", item);
                    }
                }
            }
        }

        #endregion
    }
}

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)

Share

About the Author

Weidong Shen
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

| Advertise | Privacy | Mobile
Web03 | 2.8.140814.1 | Last Updated 20 Feb 2012
Article Copyright 2011 by Weidong Shen
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid