Click here to Skip to main content
15,867,835 members
Articles / Desktop Programming / WPF

Building WPF Applications with Self-Tracking Entity Generator and Visual Studio 2012 - Project Setup

Rate me:
Please Sign up or sign in to vote.
5.00/5 (14 votes)
17 Mar 2013CPOL8 min read 68K   3.5K   44  
This article describes the project setup of building a WPF sample application with Self-Tracking Entity Generator and Visual Studio 2012.
using System;
using System.Collections.Generic;
using System.Linq;
using SchoolSample.EntityModel;
using System.Data;

namespace SchoolSample.Wcf.Service
{
    public class SchoolService : ISchoolService
    {
        public List<Student> GetStudents(ClientQuery clientQuery)
        {
            using (var context = new SchoolEntities())
            {
                if (clientQuery.IncludeList.Count == 0)
                {
                    return context.People.OfType<Student>().ApplyClientQuery(clientQuery).ToList();
                }
                var studentList = new List<Student>();
                foreach (var student in context.People.OfType<Student>().ApplyClientQuery(clientQuery).ToList())
                {
                    var currentStudent = student;
                    using (var innerContext = new SchoolEntities())
                    {
                        studentList.Add(
                            innerContext.People.OfType<Student>()
                                .ApplyIncludePath(clientQuery)
                                .Single(n => n.PersonId == currentStudent.PersonId));
                    }
                }
                return studentList;
            }
        }

        public Student GetStudentById(int studentId)
        {
            using (var context = new SchoolEntities())
            {
                return context.People.OfType<Student>()
                    .Include("Enrollments.Course")
                    .FirstOrDefault(n => n.PersonId == studentId);
            }
        }

        public List<Instructor> GetInstructors(ClientQuery clientQuery)
        {
            using (var context = new SchoolEntities())
            {
                if (clientQuery.IncludeList.Count == 0)
                {
                    return context.People.OfType<Instructor>().ApplyClientQuery(clientQuery).ToList();
                }
                var instructorList = new List<Instructor>();
                foreach (var instructor in context.People.OfType<Instructor>().ApplyClientQuery(clientQuery).ToList())
                {
                    var currentInstructor = instructor;
                    using (var innerContext = new SchoolEntities())
                    {
                        instructorList.Add(
                            innerContext.People.OfType<Instructor>()
                                .ApplyIncludePath(clientQuery)
                                .Single(n => n.PersonId == currentInstructor.PersonId));
                    }
                }
                return instructorList;
            }
        }

        public Instructor GetInstructorById(int instructorId)
        {
            using (var context = new SchoolEntities())
            {
                return context.People.OfType<Instructor>()
                    .Include("Courses")
                    .FirstOrDefault(n => n.PersonId == instructorId);
            }
        }


        public List<Course> GetCourses(ClientQuery clientQuery)
        {
            using (var context = new SchoolEntities())
            {
                if (clientQuery.IncludeList.Count == 0)
                {
                    return context.Courses.ApplyClientQuery(clientQuery).ToList();
                }
                var courseList = new List<Course>();
                foreach (var course in context.Courses.ApplyClientQuery(clientQuery).ToList())
                {
                    var currentCourse = course;
                    using (var innerContext = new SchoolEntities())
                    {
                        courseList.Add(
                            innerContext.Courses
                                .ApplyIncludePath(clientQuery)
                                .Single(n => n.CourseId == currentCourse.CourseId));
                    }
                }
                return courseList;
            }
        }

        public Course GetCourseById(int courseId)
        {
            using (var context = new SchoolEntities())
            {
                return context.Courses
                    .Include("Enrollments.Student")
                    .FirstOrDefault(n => n.CourseId == courseId);
            }
        }

        public List<object> UpdateInstructor(Instructor item)
        {
            var returnList = new List<object>();
            if (item == null)
            {
                returnList.Add("Instructor cannot be null.");
                returnList.Add(0);
                return returnList;
            }
            try
            {
                using (var context = new SchoolEntities())
                {
                    switch (item.ChangeTracker.State)
                    {
                        case ObjectState.Added:
                            // server side validation
                            item.ValidateObjectGraph();
                            // save changes
                            context.People.ApplyChanges(item);
                            context.SaveChanges();
                            break;
                        case ObjectState.Deleted:
                            // verify whether there is any course assigned to this instructor
                            var courseExists = context.Courses.Any(n => n.InstructorId == item.PersonId);
                            if (courseExists)
                            {
                                returnList.Add("Cannot delete, there still exists course assigned to this instructor.");
                                returnList.Add(item.PersonId);
                                return returnList;
                            }
                            // save changes
                            context.People.ApplyChanges(item);
                            context.SaveChanges();
                            break;
                        default:
                            // server side validation
                            item.ValidateObjectGraph();
                            // save changes
                            context.People.ApplyChanges(item);
                            context.SaveChanges();
                            break;
                    }
                }
                returnList.Add(string.Empty);
                returnList.Add(item.PersonId);
            }
            catch (OptimisticConcurrencyException)
            {
                var errorMessage = "Instructor " + item.PersonId + " was modified by another user. " +
                                   "Refresh that item before reapply your changes.";
                returnList.Add(errorMessage);
                returnList.Add(item.PersonId);
            }
            catch (Exception ex)
            {
                Exception exception = ex;
                while (exception.InnerException != null)
                {
                    exception = exception.InnerException;
                }
                var errorMessage = "Instructor " + item.PersonId + " has error: " + exception.Message;
                returnList.Add(errorMessage);
                returnList.Add(item.PersonId);
            }
            return returnList;
        }

        public List<object> UpdateStudent(Student item)
        {
            var returnList = new List<object>();
            if (item == null)
            {
                returnList.Add("Student cannot be null.");
                returnList.Add(0);
                return returnList;
            }
            try
            {
                using (var context = new SchoolEntities())
                {
                    switch (item.ChangeTracker.State)
                    {
                        case ObjectState.Added:
                            // server side validation
                            item.ValidateObjectGraph();
                            // save changes
                            context.People.ApplyChanges(item);
                            context.SaveChanges();
                            break;
                        case ObjectState.Deleted:
                            // verify whether there is any course enrollment for this student
                            var courseExists = context.Enrollments.Any(n => n.StudentId == item.PersonId);
                            if (courseExists)
                            {
                                returnList.Add("Cannot delete, there still exists course enrollment for this student.");
                                returnList.Add(item.PersonId);
                                return returnList;
                            }
                            // save changes
                            context.People.ApplyChanges(item);
                            context.SaveChanges();
                            break;
                        default:
                            // server side validation
                            item.ValidateObjectGraph();
                            // save changes
                            context.People.ApplyChanges(item);
                            context.SaveChanges();
                            break;
                    }
                }
                returnList.Add(string.Empty);
                returnList.Add(item.PersonId);
            }
            catch (OptimisticConcurrencyException)
            {
                var errorMessage = "Student " + item.PersonId + " was modified by another user. " +
                                   "Refresh that item before reapply your changes.";
                returnList.Add(errorMessage);
                returnList.Add(item.PersonId);
            }
            catch (Exception ex)
            {
                Exception exception = ex;
                while (exception.InnerException != null)
                {
                    exception = exception.InnerException;
                }
                var errorMessage = "Student " + item.PersonId + " has error: " + exception.Message;
                returnList.Add(errorMessage);
                returnList.Add(item.PersonId);
            }
            return returnList;
        }

        public List<object> UpdateCourse(Course item)
        {
            var returnList = new List<object>();
            if (item == null)
            {
                returnList.Add("Course cannot be null.");
                returnList.Add(0);
                return returnList;
            }
            try
            {
                using (var context = new SchoolEntities())
                {
                    switch (item.ChangeTracker.State)
                    {
                        case ObjectState.Added:
                            // server side validation
                            item.ValidateObjectGraph();
                            // verify whether the instructor for this course exists
                            bool instructorExists = context.People.OfType<Instructor>()
                                .Any(n => n.PersonId == item.InstructorId);
                            if (!instructorExists)
                            {
                                returnList.Add("Cannot add, there does not exist this instructor for the course.");
                                returnList.Add(item.CourseId);
                                return returnList;
                            }
                            // verify all enrollments for this course have valid students
                            bool enrollmentsValid = item.Enrollments
                                .Aggregate(true, (current, enrollment) =>
                                                 current && context.People.OfType<Student>()
                                                                .Any(n => n.PersonId == enrollment.StudentId));
                            if (!enrollmentsValid)
                            {
                                returnList.Add("Cannot add, some enrollment does not have valid student.");
                                returnList.Add(item.CourseId);
                                return returnList;
                            }
                            // save changes
                            context.Courses.ApplyChanges(item);
                            context.SaveChanges();
                            break;
                        case ObjectState.Deleted:
                            // save changes
                            context.Courses.ApplyChanges(item);
                            context.SaveChanges();
                            break;
                        default:
                            // server side validation
                            item.ValidateObjectGraph();
                            // verify whether the instructor for this course exists
                            instructorExists =
                                context.People.OfType<Instructor>()
                                    .Any(n => n.PersonId == item.InstructorId);
                            if (!instructorExists)
                            {
                                returnList.Add("Cannot update, there does not exist this instructor for the course.");
                                returnList.Add(item.CourseId);
                                return returnList;
                            }
                            // verify all enrollments for this course have valid students
                            enrollmentsValid = item.Enrollments
                                .Aggregate(true, (current, enrollment) =>
                                                 current && context.People.OfType<Student>()
                                                                .Any(n => n.PersonId == enrollment.StudentId));
                            if (!enrollmentsValid)
                            {
                                returnList.Add("Cannot update, some enrollment does not have valid student.");
                                returnList.Add(item.CourseId);
                                return returnList;
                            }
                            // save changes
                            context.Courses.ApplyChanges(item);
                            context.SaveChanges();
                            break;
                    }
                }
                returnList.Add(string.Empty);
                returnList.Add(item.CourseId);
            }
            catch (OptimisticConcurrencyException)
            {
                var errorMessage = "Course " + item.CourseId + " was modified by another user. " +
                                   "Refresh that item before reapply your changes.";
                returnList.Add(errorMessage);
                returnList.Add(item.CourseId);
            }
            catch (Exception ex)
            {
                Exception exception = ex;
                while (exception.InnerException != null)
                {
                    exception = exception.InnerException;
                }
                var errorMessage = "Course " + item.CourseId + " has error: " + exception.Message;
                returnList.Add(errorMessage);
                returnList.Add(item.CourseId);
            }
            return returnList;
        }
    }
}

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