private void OnLoadData()
        {
            PeopleCollection.Clear();

            // Create OpenFileDialog
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            // Set filter for file extension and default file extension
            dlg.DefaultExt = ".png";
            dlg.Filter     = "Text Files (*.txt)|*.txt";

            // Display OpenFileDialog by calling ShowDialog method
            Nullable <bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;

                if (filename != "")
                {
                    ProcessText(filename);
                }
            }
        }
Ejemplo n.º 2
0
        public static void PeopleCollectionEnumerationExample()
        {
            PeopleCollection people = new PeopleCollection();
            people.AddPerson(new Person()
            {
                Name = "Mike",
                Age = 22
            });

            people.AddPerson(new Person()
            {
                Name = "Kate",
                Age = 17
            });

            people.AddPerson(new Person()
            {
                Name = "John",
                Age = 20
            });

            Console.WriteLine("All people");
            foreach (Person person in people)
                Console.WriteLine(person);

            Console.WriteLine("\r\nUnder age people");
            foreach (Person person in people.GetUnderAgePeople())
                Console.WriteLine(person);

            Console.WriteLine("\r\nTake people until under aged");
            foreach(Person person in people.GetPeopleUntilUnderAged())
                Console.WriteLine(person);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Populate the people collection with information from the GEDCOM file.
        /// </summary>
        public void Import(PeopleCollection peopleCollection, string gedcomFilePath)
        {
            // Clear current content.
            peopleCollection.Clear();

            // First convert the GEDCOM file to an XML file so it's easier to parse,
            // the temp XML file is deleted when importing is complete.
            string xmlFilePath = Path.GetTempFileName();

            try
            {
                this.people = peopleCollection;

                // Convert the GEDCOM file to a temp XML file.
                GedcomConverter.ConvertToXml(gedcomFilePath, xmlFilePath, true);
                doc = new XmlDocument();
                doc.Load(xmlFilePath);

                // Import data from the temp XML file to the people collection.
                ImportPeople();
                ImportFamilies();

                // The collection requires a primary-person, use the first
                // person added to the collection as the primary-person.
                if (peopleCollection.Count > 0)
                    peopleCollection.Current = peopleCollection[0];
            }
            finally
            {
                // Delete the temp XML file.
                File.Delete(xmlFilePath);
            }
        }
Ejemplo n.º 4
0
        public static void RunMain()
        {
            PeopleCollection pc = new PeopleCollection()
            {
                new Person()
                {
                    Age = 22, FirstName = "Janne", LastName = "Doe"
                }
            };

            pc.Add(new Person()
            {
                Age = 21, LastName = "Doe", FirstName = "John"
            });
            pc.Add(new Person()
            {
                Age = 21, LastName = "Do1e", FirstName = "John"
            });
            pc.Add(new Person()
            {
                Age = 21, LastName = "Do11e", FirstName = "John"
            });

            Console.WriteLine("Count: {0}, Contents: {1}", pc.Count, pc.ToString());
            Console.WriteLine("Removing persons with 21 age...");
            pc.RemoveByAge(21);
            Console.WriteLine("Count: {0}, Contents: {1}", pc.Count, pc.ToString());

            Console.Write("Press a key to exit ... ");
            Console.ReadKey();
        }
Ejemplo n.º 5
0
        public DiagramLogic()
        {
            // The list of people, this is a global list shared by the application.
            family = App.Family;

            Clear();
        }
        public void Add_Person_WithIncorrectAge_ThrownExceptionShouldHaveMessage()
        {
            try
            {
                // Arrange
                PeopleCollection people = new PeopleCollection();

                // Act
                people.AddPerson(new Person() { Name = "Jack", Age = -1 });

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.InnerException);

                Assert.AreNotEqual<string>(string.Empty, ex.Message);
                Assert.IsNull(ex.InnerException);

                Assert.IsTrue(true);
                return;
            }

            Assert.IsTrue(false);
        }
Ejemplo n.º 7
0
        public DiagramLogic()
        {
            // The list of people, this is a global list shared by the application.
            family = App.Family;

            Clear();
        }
        public void Add_Person_WithAgeBelowZero_ThrowsInvalidAgeException()
        {
            // Arrange
            PeopleCollection people = new PeopleCollection();

            // Act
            people.AddPerson(new Person() { Name = "Jack", Age = -1 });
        }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            SetUpClient();
            var response = client.GetAsync("people/1").Result;
            //var luke = response.Content.ReadAsStringAsync().Result;
            People luke = response.Content.ReadAsAsync <People>().Result;

            var allPeopleResponse      = client.GetAsync("people").Result;
            PeopleCollection allPeople = allPeopleResponse.Content.ReadAsAsync <PeopleCollection> .Result;
            var nextPage = allPeople.GetNext(client);
        }
        private void ProcessText(string fileName)
        {
            string[] linesFromFile = System.IO.File.ReadAllLines(fileName);

            if (linesFromFile.Length > 0)
            {
                foreach (string line in linesFromFile)
                {
                    PeopleCollection.Add(line);
                }
            }
        }
Ejemplo n.º 11
0
        public void LoadPhotos(PeopleCollection people)
        {
            PhotosListBox.Items.Clear();

            PhotoCollection allPhotos = new PhotoCollection();

            foreach (Person p in people)
            {
                foreach (Photo photo in p.Photos)
                {
                    bool add = true;

                    foreach (Photo existingPhoto in allPhotos)
                    {
                        if (string.IsNullOrEmpty(photo.RelativePath))
                        {
                            add = false;
                        }

                        if (existingPhoto.RelativePath == photo.RelativePath)
                        {
                            add = false;
                            break;
                        }
                    }
                    if (add == true)
                    {
                        allPhotos.Add(photo);
                    }
                }

                if (allPhotos.Count == 0)
                {
                    View.Visibility = Visibility.Collapsed;
                }
                else
                {
                    View.Visibility = Visibility.Visible;
                }
            }


            foreach (Photo photo in allPhotos)
            {
                PhotosListBox.Items.Add(photo);
            }

            if (PhotosListBox.Items.Count > 0)
            {
                PhotosListBox.SelectedIndex = 0;
            }
        }
Ejemplo n.º 12
0
 public void OnNavigatedTo(NavigationParameters parameters)
 {
     PeopleCollection.Clear();
     for (int i = 0; i < 100; i++)
     {
         PeopleCollection.Add(new Person
         {
             Name       = $"Name{i}",
             Age        = i,
             IsSelected = false
         });
     }
 }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to Star Wars");
            SetUpClient();
            // var luke = response.Content.ReadAsStringAsync().Result;
            var    luke        = GetPeople("3");
            Planet lukesPlanet = luke.HomeworldDetail(client);

            var allPeopleResponse      = client.GetAsync("people").Result;
            PeopleCollection allPeople = allPeopleResponse.Content.ReadAsAsync <PeopleCollection>().Result;

            allPeople.GetPrevious(client); // instance
            allPeople.GetNext(client);     // instance
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Performs the business logic for adding the Parent relationship between the person and the parents.
 /// </summary>
 public static void AddParent(PeopleCollection family, Person person, ParentSet parentSet)
 {
     // First add child to parents.
     family.AddChild(parentSet.FirstParent, person, ParentChildModifier.Natural);
     family.AddChild(parentSet.SecondParent, person, ParentChildModifier.Natural);
     
     // Next update the siblings. Get the list of full siblings for the person. 
     // A full sibling is a sibling that has both parents in common. 
     List<Person> siblings = GetChildren(parentSet);
     foreach (Person sibling in siblings)
     {
         if (sibling != person)
             family.AddSibling(person, sibling);
     }
 }
Ejemplo n.º 15
0
        internal static void CustomCollection()
        {
            Entities.Custom_Collection.Person p1 = new Entities.Custom_Collection.Person {
                FirstName = "John", LastName = "Doe", Age = 42
            };
            Entities.Custom_Collection.Person p2 = new Entities.Custom_Collection.Person {
                FirstName = "Jane", LastName = "Doe", Age = 21
            };

            PeopleCollection people = new PeopleCollection {
                p1, p2
            };

            people.RemoveByAge(42);

            Console.WriteLine($"{people.Count}");
        }
Ejemplo n.º 16
0
        public void LoadAttachments(PeopleCollection people)
        {
            AttachmentsListBox.Items.Clear();

            AttachmentCollection allAttachments = new AttachmentCollection();

            foreach (Person p in people)
            {
                foreach (Attachment Attachment in p.Attachments)
                {
                    bool add = true;

                    foreach (Attachment existingAttachment in allAttachments)
                    {
                        if (string.IsNullOrEmpty(Attachment.RelativePath))
                        {
                            add = false;
                        }

                        if (existingAttachment.RelativePath == Attachment.RelativePath)
                        {
                            add = false;
                            break;
                        }
                    }
                    if (add == true)
                    {
                        allAttachments.Add(Attachment);
                    }
                }
            }


            foreach (Attachment Attachment in allAttachments)
            {
                AttachmentsListBox.Items.Add(Attachment);
            }

            if (AttachmentsListBox.Items.Count > 0)
            {
                AttachmentsListBox.SelectedIndex = 0;
            }
        }
Ejemplo n.º 17
0
        public static void Test_Custom_Collection()
        {
            Person p1 = new Person {
                FirstName = "John", LastName = "Doe", Age = 42
            };
            Person p2 = new Person {
                FirstName = "Jane", LastName = "Doe", Age = 21
            };

            PeopleCollection people = new PeopleCollection {
                p1, p2
            };

            Console.WriteLine(people.ToString()); // the overridden ToString function
            people.RemoveByAge(42);               // RemoveByAge is a custom function of PeopleCollection
            Console.WriteLine(people.Count);
            Console.WriteLine(people.ToString()); // the overridden ToString function
            Console.ReadLine();
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Downloads people list from Azure Storage and stores it locally.
        /// </summary>
        public static async Task <PeopleCollection> DownloadPeopleListAsync()
        {
            PeopleCollection res = null;

            using (var hc = new HttpClient())
            {
                try
                {
                    res = PeopleCollection.FromCsv(await hc.GetStringAsync(_peopleListUrl));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Unable to download people list from URL {_peopleListUrl}.");
                }
            }

            File.WriteAllText(PEOPLE_LIST_PATH, JsonConvert.SerializeObject(res));

            return(res);
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            var people = new PeopleCollection();

            new GedcomImport().Import(people, @"C:\Users\davit\source\repos\RelationshipSearch\hayden.ged");
            Person from     = people[0];
            Person to       = people[163];
            var    solution = new GraphSearch(new BreadthFirstFrontier()).FindSolution(new PersonChildState(from), new GoalTest(to));

            if (solution == null)
            {
                solution = new GraphSearch(new BreadthFirstFrontier()).FindSolution(new PersonParentState(from), new GoalTest(to));
            }
            if (solution == null)
            {
                solution = new GraphSearch(new BreadthFirstFrontier()).FindSolution(new PersonCousinState(from, true), new GoalTest(to));
            }
            var html = HtmlHelper.ConvertToHtml(solution);

            File.WriteAllText("D:/temp/test.html", html);
        }
        private void OnGenerate()
        {
            int numberOfWinners;

            if (Int32.TryParse(NumberOfWinners, out numberOfWinners))
            {
                string winnersAre = "";

                for (int i = 0; i < numberOfWinners; i++)
                {
                    Random randomGenerator     = new Random();
                    var    luckyWinnerPosition = randomGenerator.Next(0, PeopleCollection.Count);
                    var    luckyWinner         = PeopleCollection[luckyWinnerPosition];
                    PeopleCollection.Remove(luckyWinner);
                    winnersAre += i + 1 + ": " + luckyWinner + System.Environment.NewLine;
                }
                MessageBox.Show(winnersAre, "Lucky Winners");
            }
            NumberOfWinners = "";

            GenerateCommand.RaiseCanExecuteChanged();
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Performs the business logic for adding the Child relationship between the person and the child.
        /// </summary>
        public static void AddChild(PeopleCollection family, Person person, Person child)
        {
            // Add the new child as a sibling to any existing children
            foreach (Person existingSibling in person.Children)
            {
                family.AddSibling(existingSibling, child);
            }

            switch (person.Spouses.Count)
            {
                // Single parent, add the child to the person
                case 0:
                    family.AddChild(person, child, ParentChildModifier.Natural);
                    break;

                // Has existing spouse, add the child to the person's spouse as well.
                case 1:
                    family.AddChild(person, child, ParentChildModifier.Natural);
                    family.AddChild(person.Spouses[0], child, ParentChildModifier.Natural);
                    break;
            }
        }
Ejemplo n.º 22
0
        /*****************************
         * Main()
         ****************************/
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to Star Wars API!");
            SetUpClient();

            //Make request to the api
            var response = client.GetAsync("people/1").Result;

            //Bring data back as string
            /*var luke = response.Content.ReadAsStringAsync().Result;*/

            //Bring data in as Model Type
            People luke = response.Content.ReadAsAsync<People>().Result;

            var allPeopleResponse = client.GetAsync("people").Result;
            PeopleCollection allPeeps = allPeopleResponse.Content.ReadAsAsync<PeopleCollection>().Result;
            var lukeHomeWorld = luke.HomeworldDetail(client);

            Console.WriteLine(luke.Name + " : " + lukeHomeWorld.Name);


            //allPeeps.GetNext(client);
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            Person p1 = new Person
            {
                FirstName = "John",
                LastName  = "Doe",
                Age       = 42
            };

            Person p2 = new Person
            {
                FirstName = "Jane",
                LastName  = "Doe",
                Age       = 21
            };

            PeopleCollection people = new PeopleCollection {
                p1, p2
            };

            people.RemoveByAge(42);
            Console.WriteLine(people.Count); // Displays: 1
        }
Ejemplo n.º 24
0
        public static void Start()
        {
            Person p1 = new Person
            {
                FirstName = "John",
                LastName  = "Doe",
                Age       = 42
            };
            Person p2 = new Person
            {
                FirstName = "Jane",
                LastName  = "Doe",
                Age       = 21
            };
            PeopleCollection people = new PeopleCollection {
                p1, p2
            };

            Console.WriteLine(people.ToString());
            people.RemoveByAge(42);
            Console.WriteLine(people.Count);
            Console.WriteLine(people.ToString());
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Performs the business logic for adding the Parent relationship between the person and the parent.
        /// </summary>
        public static void AddParent(PeopleCollection family, Person person, Person parent)
        {
            // A person can only have 2 parents, do nothing
            if (person.Parents.Count == 2)
                return;
            
            // Add the parent to the main collection of people.
            family.Add(parent);

            switch (person.Parents.Count)
            {
                // No exisitng parents
                case 0: 
                    family.AddChild(parent, person, ParentChildModifier.Natural);
                    break;

                // An existing parent
                case 1: 
                    family.AddChild(parent, person, ParentChildModifier.Natural);
                    family.AddSpouse(parent, person.Parents[0], SpouseModifier.Current);
                    break;
            }

            // Handle siblings
            if (person.Siblings.Count > 0)
            {
                // Make siblings the child of the new parent
                foreach (Person sibling in person.Siblings)
                {
                    family.AddChild(parent, sibling, ParentChildModifier.Natural);
                }
            }

            // Setter for property change notification
            person.HasParents = true;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Performs the business logic for adding the Sibling relationship between the person and the sibling.
        /// </summary>
        public static void AddSibling(PeopleCollection family, Person person, Person sibling)
        {
            // Handle siblings
            if (person.Siblings.Count > 0)
            {
                // Make the siblings siblings to each other.
                foreach (Person existingSibling in person.Siblings)
                {
                    family.AddSibling(existingSibling, sibling);
                }
            }

            if (person.Parents != null)
            {
                switch (person.Parents.Count)
                {
                    // No parents
                    case 0:
                        family.AddSibling(person, sibling);
                        break;

                    // Single parent
                    case 1:
                        family.AddSibling(person, sibling);
                        family.AddChild(person.Parents[0], sibling, ParentChildModifier.Natural);
                        break;

                    // 2 parents
                    case 2:
                        // Add the sibling as a child of the same parents
                        foreach (Person parent in person.Parents)
                        {
                            family.AddChild(parent, sibling, ParentChildModifier.Natural);
                        }

                        family.AddSibling(person, sibling);
                        break;

                    default:
                        family.AddSibling(person, sibling);
                        break;
                }
            }
        }
Ejemplo n.º 27
0
 public static void Start()
 {
     var people = new PeopleCollection();
 }
Ejemplo n.º 28
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            if (_people == null)
            {
                _people = await PeopleService.GetPeopleLisAtAsync();
            }

            var mess = await result as IMessageActivity;

            if (context.ConversationData.ContainsKey(Constants.LAST_PERSON_KEY))
            {
                var lastPerson = context.ConversationData.GetValue <Person>(Constants.LAST_PERSON_KEY);

                var guessResult = _people.FindByName(mess.Text);
                if (guessResult.Count > 3 && guessResult.Contains(lastPerson, new PersonComparer()))
                {
                    await context.PostAsync("That is too generic. Try again.");

                    context.Wait(MessageReceivedAsync);
                }
                else if (guessResult.Contains(lastPerson, new PersonComparer()))
                {
                    // správná odpověď
                    TelemetryService.SendTelemetry(new TelemetryModel("correct", lastPerson.Name));

                    await context.PostAsync("✔️ Correct!");

                    // zvednout skóre
                    if (context.ConversationData.ContainsKey(Constants.SECOND_CHANCE))
                    {
                        await context.PostAsync("That's **0.5** points for you.");

                        await Utils.ChangeScoreAsync(context, 0.5);

                        context.ConversationData.RemoveValue(Constants.SECOND_CHANCE);
                    }
                    else
                    {
                        await context.PostAsync("That's **2** points for you.");

                        await Utils.ChangeScoreAsync(context, 2);
                    }

                    // DEBUG
                    //context.Done(1.0);
                    //return;

                    // zobrazit další
                    await GoNext(context);
                }
                else
                {
                    // špatná odpověď - dáme nápovědu, pokud už nejsme v nápovědě :)
                    TelemetryService.SendTelemetry(new TelemetryModel("incorrect", lastPerson.Name));

                    if (context.ConversationData.ContainsKey(Constants.SECOND_CHANCE))
                    {
                        await context.PostAsync($"❌ That is not correct. Let's try another speaker.");

                        context.ConversationData.RemoveValue(Constants.SECOND_CHANCE);

                        await GoNext(context);
                    }
                    else
                    {
                        await context.PostAsync("Not correct. I'll give you a hint. But it will be for less points. This person's name is one of those:");

                        var msg = context.MakeMessage();
                        msg.Attachments.Add(PrepareButtonsCard(_people.GetRandomPeople(lastPerson, 5).Select(p => p.Name).ToArray()).ToAttachment());
                        await context.PostAsync(msg);

                        context.ConversationData.SetValue(Constants.SECOND_CHANCE, "true");

                        context.Wait(MessageReceivedAsync);
                    }
                }
            }
            else
            {
                await GoNext(context);
            }
        }
 private void OnClearData()
 {
     PeopleCollection.Clear();
 }
        public void OneBigTest()
        {
            {
                #region LogicBrokerTests
                //  GetPerson(PersonID)
                {
                    var expectedPerson = new Person()
                    {
                        FirstName = "John",
                        LastName  = "Smith",
                        Email     = "*****@*****.**",
                        Phone     = "1112223333"
                    };

                    int    personID     = 1;
                    Person actualPerson = LogicBroker.GetPerson(personID);

                    bool areEqual = expectedPerson.Equals(actualPerson);
                    Assert.IsTrue(areEqual);
                }

                //  GetPerson(firstname, lastname)
                {
                    string firstName = "John";
                    string lastName  = "Smith";

                    var expectedPerson = new Person()
                    {
                        FirstName = firstName,
                        LastName  = lastName,
                        Email     = "*****@*****.**",
                        Phone     = "1112223333"
                    };

                    Person actualPerson = LogicBroker.GetPerson(firstName, lastName);

                    bool areEqual = expectedPerson.Equals(actualPerson);
                    Assert.IsTrue(areEqual);
                }

                //  GetHome(homeID)
                {
                    var address = "23 Oak St.";
                    var zip     = "955551111";

                    var expectedHome = new Home()
                    {
                        Address = address,
                        City    = "Johnsonville",
                        State   = "CA",
                        Zip     = zip
                    };

                    int  homeID     = 1;
                    Home actualHome = LogicBroker.GetHome(homeID);

                    bool areEqual = expectedHome.Equals(actualHome);
                    Assert.IsTrue(areEqual);
                }

                //  GetHome(address, zip)
                {
                    var address = "23 Oak St.";
                    var zip     = "955551111";

                    var expectedHome = new Home()
                    {
                        Address = address,
                        City    = "Johnsonville",
                        State   = "CA",
                        Zip     = zip
                    };

                    Home actualHome = LogicBroker.GetHome(address, zip);

                    bool areEqual = expectedHome.Equals(actualHome);
                    Assert.IsTrue(areEqual);
                }

                //  GetHomeSale(saleID)
                //  SOLD
                {
                    int homesaleID = 6;

                    var expectedHomeSale = new HomeSale()
                    {
                        SaleID     = homesaleID,
                        HomeID     = 3,
                        SoldDate   = new DateTime(2014, 06, 13),
                        AgentID    = 1,
                        SaleAmount = 550_000m,
                        BuyerID    = 5,
                        MarketDate = new DateTime(2014, 06, 01),
                        CompanyID  = 4
                    };

                    var actualHomeSale = LogicBroker.GetHomeSale(homesaleID);

                    bool areEqual = expectedHomeSale.Equals(actualHomeSale);
                    if (!areEqual)
                    {
                        var items = new List <HomeSale>()
                        {
                            expectedHomeSale, actualHomeSale
                        };

                        PrintObjects(items);
                    }

                    Assert.IsTrue(areEqual);
                }

                //  GetHomeSale(marketDate, saleAmount)
                //  SOLD
                {
                    int homesaleID = 6;
                    var marketDate = new DateTime(2015, 03, 01);
                    var saleAmount = 335_000m;

                    var expectedHomeSale = new HomeSale()
                    {
                        SaleID     = homesaleID,
                        HomeID     = 1,
                        SoldDate   = new DateTime(2010, 03, 15),
                        AgentID    = 1,
                        SaleAmount = saleAmount,
                        BuyerID    = 1,
                        MarketDate = marketDate,
                        CompanyID  = 2
                    };

                    var actualHomeSale = LogicBroker.GetHomeSale(marketDate, saleAmount);

                    bool areEqual = expectedHomeSale.Equals(actualHomeSale);
                    if (!areEqual)
                    {
                        var items = new List <HomeSale>()
                        {
                            expectedHomeSale, actualHomeSale
                        };

                        PrintObjects(items);
                    }

                    Assert.IsTrue(areEqual);
                }

                //  GetHomeSale(saleID)
                //  FOR SALE
                {
                    var saleID = 1;

                    var expectedHomeForSale = new HomeSale()
                    {
                        SaleID     = saleID,
                        HomeID     = 3,
                        SoldDate   = null,
                        AgentID    = 4,
                        SaleAmount = 700_000m,
                        MarketDate = new DateTime(2016, 08, 15),
                        CompanyID  = 1
                    };

                    var actualHomeForSale = LogicBroker.GetHomeSale(saleID);

                    bool areEqual = expectedHomeForSale.Equals(actualHomeForSale);
                    if (!areEqual)
                    {
                        var items = new List <HomeSale>()
                        {
                            expectedHomeForSale, actualHomeForSale
                        };

                        PrintObjects(items);
                    }

                    Assert.IsTrue(areEqual);
                }

                //  GetReCompany(companyID)
                {
                    int companyID = 3;

                    var expectedRECo = new RealEstateCompany()
                    {
                        CompanyID   = companyID,
                        CompanyName = "Rapid Real Estate",
                        Phone       = "6662221111"
                    };

                    var actualRECo = LogicBroker.GetReCompany(companyID);

                    bool areEqual = expectedRECo.Equals(actualRECo);
                    if (!areEqual)
                    {
                        var items = new List <RealEstateCompany>()
                        {
                            expectedRECo, actualRECo
                        };

                        PrintObjects(items);
                    }

                    Assert.IsTrue(areEqual);
                }

                //  GetReCompany(companyName)
                {
                    int companyID   = 3;
                    var companyName = "Rapid Real Estate";

                    var expectedRECo = new RealEstateCompany()
                    {
                        CompanyID   = companyID,
                        CompanyName = companyName,
                        Phone       = "6662221111"
                    };

                    var actualRECo = LogicBroker.GetReCompany(companyName);

                    bool areEqual = expectedRECo.Equals(actualRECo);
                    if (!areEqual)
                    {
                        var items = new List <RealEstateCompany>()
                        {
                            expectedRECo, actualRECo
                        };

                        PrintObjects(items);
                    }

                    Assert.IsTrue(areEqual);
                }

                //  GetAgent(AgentID)
                {
                    var agentID = 4;

                    var expectedAgent = new Agent()
                    {
                        AgentID           = agentID,
                        CompanyID         = 1,
                        CommissionPercent = 0.03m
                    };

                    var actualAgent = LogicBroker.GetAgent(agentID);

                    bool areEqual = expectedAgent.Equals(actualAgent);
                    if (!areEqual)
                    {
                        var items = new List <Agent>()
                        {
                            expectedAgent, actualAgent
                        };

                        PrintObjects(items);
                    }

                    Assert.IsTrue(areEqual);
                }

                //  GetBuyer(BuyerID)
                {
                    var buyerID = 7;

                    var expectedBuyer = new Buyer()
                    {
                        BuyerID      = buyerID,
                        CreditRating = 780
                    };

                    var actualBuyer = LogicBroker.GetBuyer(buyerID);

                    bool areEqual = expectedBuyer.Equals(actualBuyer);
                    if (!areEqual)
                    {
                        var items = new List <Buyer>()
                        {
                            expectedBuyer, actualBuyer
                        };

                        PrintObjects(items);
                    }

                    Assert.IsTrue(areEqual);
                }

                //  GetOwner(OwnerID)
                {
                    var ownerID = 7;

                    var expectedOwner = new Owner()
                    {
                        OwnerID         = ownerID,
                        PreferredLender = "Unique Mortgaging"
                    };

                    var actualOwner = LogicBroker.GetOwner(ownerID);

                    bool areEqual = expectedOwner.Equals(actualOwner);
                    if (!areEqual)
                    {
                        var items = new List <Owner>()
                        {
                            expectedOwner, actualOwner
                        };

                        PrintObjects(items);
                    }

                    Assert.IsTrue(areEqual);
                }

                //  UpdateExistingItem<Person>(person)
                {
                    var updatePersonFirstName = "p1FirstName";
                    var updatePersonLastName  = "p2LastName";
                    var addUpdateRemovePerson = new Person
                    {
                        FirstName = updatePersonFirstName,
                        LastName  = updatePersonLastName,
                        Phone     = "123456789",
                        Email     = "*****@*****.**"
                    };

                    var expectedStoreResult = true;
                    var actualStoreResult   = LogicBroker.StoreItem <Person>(addUpdateRemovePerson);

                    PrintObject <Person>(addUpdateRemovePerson, "Update Existing Item addUpdateRemovePerson.");
                    PrintObject <bool>(actualStoreResult, "Return value from StoreItem().");

                    if (!actualStoreResult)
                    {
                        Console.WriteLine(addUpdateRemovePerson.ToString());
                    }

                    Assert.AreEqual(expectedStoreResult, actualStoreResult);

                    var personToUpdate = LogicBroker.GetPerson(updatePersonFirstName, updatePersonLastName);
                    PrintObject <Person>(personToUpdate, "Returned Person from GetPerson(firstname, lastname).");

                    var expectedUpdateResult = true;
                    var updatePerson         = new Person()
                    {
                        PersonID  = personToUpdate.PersonID,
                        FirstName = personToUpdate.FirstName,
                        LastName  = personToUpdate.LastName,
                        Phone     = "0000000000",
                        Email     = "*****@*****.**"
                    };

                    var actualUpdateResult = LogicBroker.UpdateExistingItem <Person>(updatePerson);

                    PrintObject <bool>(actualUpdateResult, "Return value from UpdateExistingItem().");

                    if (actualUpdateResult)
                    {
                        Person resultPerson = LogicBroker.GetPerson(addUpdateRemovePerson.FirstName, addUpdateRemovePerson.LastName);
                        Console.WriteLine(resultPerson.ToString());
                    }

                    Assert.AreEqual(expectedUpdateResult, actualUpdateResult);

                    var expectedRemoveResult = true;
                    var actualRemoveResult   = LogicBroker.RemoveEntity <Person>(updatePerson);

                    PrintObject <bool>(actualRemoveResult, "Return value from RemoveEntity<Person>().");

                    if (!actualRemoveResult)
                    {
                        Console.WriteLine("RemoveEntity<Person>(addUpdateRemovePerson) failed.");
                        Console.WriteLine(addUpdateRemovePerson.ToString());
                    }

                    Assert.AreEqual(expectedRemoveResult, actualRemoveResult);
                }
            }
            #endregion LogicBrokerTests

            #region InitializeCollections

            DbPeopleCollection = new PeopleCollection <Person>(EntityLists.GetListOfPeople());
            Assert.IsTrue(DbPeopleCollection.Count == 10);

            DbHomesCollection = new HomesCollection(EntityLists.GetTreeListOfHomes());
            Assert.IsTrue(DbHomesCollection.Count == 5);

            DbHomesalesCollection = new HomeSalesCollection(EntityLists.GetListOfHomeSales());
            Assert.IsTrue(DbHomesalesCollection.Count == 8);

            DbRECosCollection = new RealEstateCosCollection(EntityLists.GetTreeListOfRECompanies());
            Assert.IsTrue(DbRECosCollection.Count == 4);
            #endregion InitializeCollections

            #region PeopleCollectionTests
            {
                //  COUNT
                var expectedCount = 10;
                var actualCount   = DbPeopleCollection.Count;
                Assert.AreEqual(expectedCount, actualCount);

                //  ADD
                var personPerson = new Person()
                {
                    FirstName = "Owen",
                    LastName  = "Owner",
                    Phone     = "123456789",
                    Email     = "*****@*****.**"
                };
                var personAddedCount = DbPeopleCollection.Add(personPerson);
                PrintObject <Person>(personPerson, $"Attempted to add Person to PersonCollection. Result: { personAddedCount }.");
                Assert.IsTrue(personAddedCount == 1);   //  Add plain Person

                //  GET (PersonID by F+L Names)
                int addedPersonID = 0;
                addedPersonID = DbPeopleCollection.GetPersonIDbyName(personPerson.FirstName, personPerson.LastName);
                PrintObject <int>(addedPersonID, "Returned PersonID from GetPersonIDbyName(Owen, Owner).");
                Assert.IsTrue(addedPersonID > 10);

                //  GET (Person by Person)
                Person addedPerson = null;
                addedPerson = DbPeopleCollection.Get(addedPersonID);
                PrintObject <Person>(addedPerson, "Returned Person from Get(addedPersonID).");
                Assert.IsTrue(addedPerson != null);

                //  UPDATE (Person's Phone)
                addedPerson.Phone = "3254678451";
                var addedPersonUpdated = DbPeopleCollection.UpdatePerson(addedPerson);
                PrintObject <Person>(addedPerson, $"UpdatePerson(addedPerson) result: { addedPersonUpdated }.");
                Assert.IsTrue(addedPersonUpdated == 1);

                //  UPDATE (Person as an Owner)
                var existingUpdatePerson = DbPeopleCollection.Get(addedPersonID);
                var owner = new Owner()
                {
                    OwnerID         = addedPerson.PersonID,
                    PreferredLender = "Lender Test"
                };
                existingUpdatePerson.Owner = owner;
                var ownerPersonUpdated = DbPeopleCollection.UpdatePerson(existingUpdatePerson);
                PrintObject <Person>(existingUpdatePerson, $"UpdatePerson(addedPerson) with Owner result: { ownerPersonUpdated }.");
                Assert.IsTrue(ownerPersonUpdated > 0);

                //  REMOVE
                var updatePersonWithOwner = DbPeopleCollection.Get(addedPersonID);
                var personRemoved         = DbPeopleCollection.Remove(updatePersonWithOwner);
                PrintObject <Person>(updatePersonWithOwner, $"Removing person from collection result: { personRemoved }.");
                Assert.IsTrue(personRemoved);           //  Remove Person with Owner FK

                //  CLEAR
                DbPeopleCollection.Clear();
                expectedCount = 0;
                actualCount   = DbPeopleCollection.Count;

                //  REINIT
                DbPeopleCollection = new PeopleCollection <Person>(EntityLists.GetListOfPeople());
                Assert.IsTrue(DbPeopleCollection.Count == 10);
            }
            #endregion

            #region HomesCollectionTests
            {
                var newHome = new Home()
                {
                    Address = "4412 153rd Ave SE",
                    City    = "Bellevue",
                    State   = "WA",
                    Zip     = "980060000"
                };

                //  GET HOME BY ADDRESS AND ZIP
                //  var homeByAddress = DbHomesCollection.GetHome(anAddress, aZipCode);


                //  GET HOME BY ID
                var homeID   = 1;
                var homeByID = DbHomesCollection.Retreive(homeID);

                var expectedHome = new Home()
                {
                    HomeID  = 1,
                    Address = "23 Oak St.",
                    City    = "Johnsonville",
                    State   = "CA",
                    Zip     = "955551111",
                    OwnerID = 1
                };
                var expectedResult = true;
                var actualResult   = expectedHome.Equals(homeByID);
                PrintObject <Home>(homeByID, "Get Home by ID Result.");
                PrintObject <bool>(actualResult, "Get Home by id actual result:");
                Assert.AreEqual(expectedResult, actualResult);

                //  UPDATE HOME
                newHome.OwnerID = 3;
                var actualUpdateResult   = DbHomesCollection.Update(newHome);
                var expectedUpdateResult = 1;
                PrintObject <int>(actualUpdateResult, "Update Home actual update result:");
                Assert.AreEqual(expectedUpdateResult, actualUpdateResult);

                //  REMOVE HOME
                var expectedRemoveResult = true;
                var actualRemoveResult   = DbHomesCollection.Remove(newHome.HomeID);
                PrintObject <bool>(actualRemoveResult, "Remove Home actual result:");
                Assert.AreEqual(expectedRemoveResult, actualRemoveResult);

                //  CLEAR
                //DbHomesCollection.Clear();
                //expectedCount = 0;
                //actualCount = DbHomesCollection.Count;
                //Assert.AreEqual(expectedCount, actualCount);

                //  REINIT
                DbHomesCollection = new HomesCollection(EntityLists.GetTreeListOfHomes());

                var expectedCount = 5;
                var actualCount   = DbHomesCollection.Count;
                PrintObject <int>(actualCount, "Actual Count of reinitialized Homes collection.");
                Assert.AreEqual(expectedCount, actualCount);
            }
            #endregion

            #region HomeSalesCollectionTests
            {
                //  GET BY ID
                var existingSaleID = 1;
                var getHomesale    = DbHomesalesCollection.Retreive(existingSaleID);
                PrintObject <HomeSale>(getHomesale, "Retreived Homesale with SaleID=1: ");
                var marketDate       = new DateTime(2016, 08, 15);
                var expectedHomesale = new HomeSale()
                {
                    SaleID     = 6,
                    HomeID     = 3,
                    AgentID    = 4,
                    SaleAmount = 700000m,
                    MarketDate = new DateTime(2016, 08, 15),
                    CompanyID  = 1
                };

                var expectedResult = true;
                var actualResult   = expectedHomesale.Equals(getHomesale);
                Assert.AreEqual(expectedResult, actualResult);

                //  GET BY ITEM?
                //  TODO: Implement if necessary

                //  UPDATE E.G. SELLHOME
                var preNewHomesale = DbHomesalesCollection.Retreive(1); //  so it can be put back into DB at end of tests
                PrintObject <HomeSale>(preNewHomesale, "PreNewHomesale instance, SaleID=1: ");

                var newHomeSale = new HomeSale()
                {
                    SaleID     = 1,
                    HomeID     = 3,
                    AgentID    = 4,
                    SaleAmount = 766666m,
                    MarketDate = new DateTime(2016, 08, 15),
                    CompanyID  = 1,
                    SoldDate   = new DateTime(2020, 08, 15),
                    BuyerID    = 1
                };

                var actualUpdateResult = DbHomesalesCollection.Update(newHomeSale);
                PrintObject <HomeSale>(newHomeSale, "NewHomeSale instance sent to Update method: ");
                PrintObject <int>(actualUpdateResult, "UPDATE Home as sold result: ");
                var expectedUpdateResult = 1;
                Assert.AreEqual(expectedUpdateResult, actualUpdateResult);

                //  REMOVE
                var actualRemoveResult = DbHomesalesCollection.Remove(newHomeSale);
                PrintObject <HomeSale>(newHomeSale, "Item sent to Remove() method: ");

                var expectedRemoveResult = true;
                Assert.AreEqual(expectedRemoveResult, actualRemoveResult);

                //  GET UPDATE REMOVEFROMMARKET (put homesale back, then remove from market)
                var expectedPostRemoveFromMarketCount = DbHomesalesCollection.Count;
                var resetHomesale = new HomeSale()
                {
                    SaleID     = 6,
                    HomeID     = 3,
                    AgentID    = 4,
                    SaleAmount = 700000m,
                    MarketDate = new DateTime(2016, 08, 15),
                    CompanyID  = 1
                };
                var reAddHomeForSaleToCollectionResult = DbHomesalesCollection.Add(resetHomesale);
                PrintObject <HomeSale>(resetHomesale, "ResetHomesale, SaleID=6, sent to Add method: ");

                var expectedReAddHomeForSaleToCollectionResult = 1;
                Assert.AreEqual(expectedReAddHomeForSaleToCollectionResult, reAddHomeForSaleToCollectionResult);

                var expectedPostRemoveFromMarketResult = true;
                var actualPostRemoveFromMarketResult   = DbHomesalesCollection.Remove(resetHomesale);
                PrintObject <HomeSale>(resetHomesale, "ResetHomesale, SaleID=6, sent to Remove method: ");

                var actualPostRemoveFromMarketCount = DbHomesalesCollection.Count;

                Assert.AreEqual(expectedPostRemoveFromMarketResult, actualPostRemoveFromMarketResult);
                Assert.AreEqual(expectedPostRemoveFromMarketCount, actualPostRemoveFromMarketCount);

                //  CLEAR
                //  TODO: Implement Clear method if necessary.
            }
            #endregion

            #region RealEstateCompaniesTests
            {
                //  RETREIVE
                var recoToRetreiveID = 3;
                var retreivedRECo    = DbRECosCollection.Retrieve(recoToRetreiveID);
                var expectedRECo     = new RealEstateCompany()
                {
                    CompanyID   = 3,
                    CompanyName = "Rapid Real Estate",
                    Phone       = "6662221111",
                };
                var expectedAgentsCount    = 1;
                var expectedHomesalesCount = 2;
                PrintObject <RealEstateCompany>(retreivedRECo, "Expecting Rapid Real Estate. RECo retreived from Collection: ");
                var actualRetreivedRECoAgentsCount    = retreivedRECo.Agents.Count;
                var actualRetreivedRECoHomesalesCount = retreivedRECo.HomeSales.Count;
                PrintObject <int>(actualRetreivedRECoAgentsCount, "Expected: 1; Actual AGENTS in retreived RECo instance: ");
                PrintObject <int>(actualRetreivedRECoHomesalesCount, "Expected: 2; Actual HOMESALES in retreived RECo instance: ");
                Assert.AreEqual(expectedAgentsCount, retreivedRECo.Agents.Count);
                Assert.AreEqual(expectedHomesalesCount, retreivedRECo.HomeSales.Count);
                var expectedRECoRetreiveResult = true;
                var actualRECoRetreiveResult   = expectedRECo.Equals(retreivedRECo);
                PrintObject <bool>(actualRECoRetreiveResult, "Expected .Equals(): True; Actual comparison result: ");
                Assert.AreEqual(expectedRECoRetreiveResult, actualRECoRetreiveResult);

                //  ADD
                var expectedPreCount = DbRECosCollection.Count;
                var recoToAdd        = new RealEstateCompany()
                {
                    CompanyName = "TestCompany",
                    Phone       = "2061234567"
                };
                var expectedAddResult = 1;
                var actualAddResult   = DbRECosCollection.Add(recoToAdd);
                Assert.AreEqual(expectedAddResult, actualAddResult);

                //  SEARCH and store
                var recoToRemove = DbRECosCollection.Where(re => re.CompanyName == recoToAdd.CompanyName).FirstOrDefault();
                if (recoToRemove == null)
                {
                    Assert.Fail($"Unable to recover added RECo: { recoToAdd }");
                }

                //  Remove
                var expectedRemoveResult = true;
                var recoRemovalPreCount  = DbRECosCollection.Count;
                var expectedPostCount    = recoRemovalPreCount - 1;
                var actualRemoveResult   = DbRECosCollection.Remove(recoToRemove.CompanyID); //  this exercizes BOTH remove methods
                var actualPostCount      = DbRECosCollection.Count;
                Assert.AreEqual(expectedPostCount, actualPostCount);
                Assert.AreEqual(expectedRemoveResult, actualRemoveResult);
            }
            #endregion
        }
    }
}
Ejemplo n.º 31
0
 private async static Task LoadPeople()
 {
     People = new PeopleCollection(ApplicationData.Current.LocalFolder);
     //await People.LoadState();
     await People.LoadStateMock();
 }
        public static void Run()
        {
            PrintTitle("OBSERVABLE COLLECTION");

            PeopleCollection <Person> people = new PeopleCollection <Person>();
            string divider = new string('-', 30);

            Action <string> printTitle = (title) =>
            {
                Console.WriteLine(divider);
                Console.WriteLine(title);
                Console.WriteLine(divider);
            };

            Action printList = () =>
            {
                printTitle("LIST");
                foreach (Person p in people)
                {
                    Console.WriteLine(p.Name);
                }
                Console.WriteLine();
            };

            printTitle("ADDING PEOPLE");
            people.Add(new Person {
                Name = "Mary"
            });
            people.Add(new Person {
                Name = "John"
            });
            people.Add(new Person {
                Name = "Phillip"
            });
            people.Add(new Person {
                Name = "Joan"
            });
            people.Add(new Person {
                Name = "Barry"
            });

            printList();

            // ---
            printTitle("Changing Mary to Bernard");
            Person mary = people[0];

            mary.Name = "Bernard";
            people[0] = mary;

            printList();

            // ---
            printTitle("Removing Bernard");
            people.Remove(mary);

            printList();


            // ----
            printTitle("Clearing List");
            people.Clear();
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Performs the business logic for changing the deleting the person
        /// </summary>
        public static void DeletePerson(PeopleCollection family, Person personToDelete)
        {
            if (!personToDelete.IsDeletable)
                return;

            // Remove the personToDelete from the relationships that contains the personToDelete.
            foreach (Relationship relationship in personToDelete.Relationships)
            {
                foreach (Relationship rel in relationship.RelationTo.Relationships)
                {
                    if (rel.RelationTo.Equals(personToDelete))
                    {
                        relationship.RelationTo.Relationships.Remove(rel);
                        break;
                    }                    
                } 
            }

            // Delete the person's photos and story
            personToDelete.DeletePhotos();
            personToDelete.DeleteStory();

            family.Remove(personToDelete);
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Performs the business logic for changing the person parents
        /// </summary>
        public static void ChangeParents(PeopleCollection family, Person person, ParentSet newParentSet)
        {
            // Don't do anything if there is nothing to change or if the parents are the same
            if (person.ParentSet == null || newParentSet == null || person.ParentSet.Equals(newParentSet))
                return;

            // store the current parent set which will be removed
            ParentSet formerParentSet = person.ParentSet;

            // Remove the first parent
            RemoveParentChildRelationship(person, formerParentSet.FirstParent);

            // Remove the person as a child of the second parent
            RemoveParentChildRelationship(person, formerParentSet.SecondParent);

            // Remove the sibling relationships
            RemoveSiblingRelationships(person);

            // Add the new parents
            AddParent(family, person, newParentSet);
        }
Ejemplo n.º 35
0
		private async static Task LoadPeople()
		{
			People = new PeopleCollection(ApplicationData.Current.LocalFolder);
			//await People.LoadState();
			await People.LoadStateMock();
		}
Ejemplo n.º 36
0
 private void AddPerson(Person person)
 {
     PeopleCollection.Add(person);
 }
Ejemplo n.º 37
0
        /// <summary>
        /// Performs the business logic for adding the Spousal relationship between the person and the spouse.
        /// </summary>
        public static void AddSpouse(PeopleCollection family, Person person, Person spouse, SpouseModifier modifier)
        {
            // Assume the spouse's gender based on the counterpart of the person's gender
            if (person.Gender == Gender.Male)
                spouse.Gender = Gender.Female;
            else
                spouse.Gender = Gender.Male;

            if (person.Spouses != null)
            {
                switch (person.Spouses.Count)
                {
                    // No existing spouse	
                    case 0:
                        family.AddSpouse(person, spouse, modifier);

                        // Add any of the children as the child of the spouse.
                        if (person.Children != null || person.Children.Count > 0)
                        {
                            foreach (Person child in person.Children)
                            {
                                family.AddChild(spouse, child, ParentChildModifier.Natural);
                            }
                        }
                        break;

                    // Existing spouse(s)
                    default:
                        // If specifying a new married spouse, make existing spouses former.
                        if (modifier == SpouseModifier.Current)
                        {
                            foreach (Relationship relationship in person.Relationships)
                            {
                                if (relationship.RelationshipType == RelationshipType.Spouse)
                                    ((SpouseRelationship)relationship).SpouseModifier = SpouseModifier.Former;
                            }
                        }
                        
                        family.AddSpouse(person, spouse, modifier);
                        break;
                }

                // Setter for property change notification
                person.HasSpouse = true;
            }
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Display the current file stats
        /// </summary>
        public void DisplayStats(PeopleCollection people, SourceCollection sources, RepositoryCollection repositories)
        {
            #region fields

            // Media
            double photos                = 0;
            double notes                 = 0;
            double attachments           = 0;
            double sourcesCount          = 0;
            double repositoriesCount     = 0;
            double citations             = 0;
            double relationshipCitations = 0;

            PhotoCollection      allPhotos      = new PhotoCollection();
            AttachmentCollection allAttachments = new AttachmentCollection();

            // Events
            double relationships = 0;
            double marriages     = 0;
            double divorces      = 0;
            double births        = 0;
            double deaths        = 0;
            double occupations   = 0;
            double cremations    = 0;
            double burials       = 0;
            double educations    = 0;
            double religions     = 0;

            double livingFacts   = 7;
            double deceasedFacts = 4 + livingFacts; // Normally a person either has cremation or burial date and place so this counts a 2 events plus death place and death date events plus the normal 7 events.
            double marriageFacts = 2;
            double divorceFacts  = 1;

            double totalEvents = 0;

            double living   = 0;
            double deceased = 0;

            decimal minimumYear = DateTime.Now.Year;
            decimal maximumYear = DateTime.MinValue.Year;

            DateTime?marriageDate  = DateTime.MaxValue;
            DateTime?divorceDate   = DateTime.MaxValue;
            DateTime?birthDate     = DateTime.MaxValue;
            DateTime?deathDate     = DateTime.MaxValue;
            DateTime?cremationDate = DateTime.MaxValue;
            DateTime?burialDate    = DateTime.MaxValue;

            // Top names
            string[] maleNames   = new string[people.Count];
            string[] femaleNames = new string[people.Count];
            string[] surnames    = new string[people.Count];

            // Data quality
            double progress = 0;

            int i = 0;  // Counter

            #endregion

            foreach (Person p in people)
            {
                #region top names

                if (p.Gender == Gender.Male)
                {
                    maleNames[i] = p.FirstName.Split()[0];
                }
                else
                {
                    femaleNames[i] = p.FirstName.Split()[0];
                }

                surnames[i] = p.LastName;

                #endregion

                #region photos

                foreach (Photo photo in p.Photos)
                {
                    bool add = true;

                    foreach (Photo existingPhoto in allPhotos)
                    {
                        if (string.IsNullOrEmpty(photo.RelativePath))
                        {
                            add = false;
                        }

                        if (existingPhoto.RelativePath == photo.RelativePath)
                        {
                            add = false;
                            break;
                        }
                    }
                    if (add == true)
                    {
                        allPhotos.Add(photo);
                    }
                }

                #endregion

                #region attachments

                foreach (Attachment attachment in p.Attachments)
                {
                    bool add = true;

                    foreach (Attachment existingAttachment in allAttachments)
                    {
                        if (string.IsNullOrEmpty(attachment.RelativePath))
                        {
                            add = false;
                        }

                        if (existingAttachment.RelativePath == attachment.RelativePath)
                        {
                            add = false;
                            break;
                        }
                    }
                    if (add == true)
                    {
                        allAttachments.Add(attachment);
                    }
                }

                #endregion

                if (p.HasNote)
                {
                    notes++;
                }

                #region events and citations

                if ((!string.IsNullOrEmpty(p.ReligionSource)) && (!string.IsNullOrEmpty(p.ReligionCitation)) && (!string.IsNullOrEmpty(p.Religion)))
                {
                    citations++;
                }
                if ((!string.IsNullOrEmpty(p.CremationSource)) && (!string.IsNullOrEmpty(p.CremationCitation)) && (!string.IsNullOrEmpty(p.CremationPlace) || p.CremationDate > DateTime.MinValue))
                {
                    citations++;
                }
                if ((!string.IsNullOrEmpty(p.OccupationSource)) && (!string.IsNullOrEmpty(p.OccupationCitation)) && (!string.IsNullOrEmpty(p.Occupation)))
                {
                    citations++;
                }
                if ((!string.IsNullOrEmpty(p.EducationSource)) && (!string.IsNullOrEmpty(p.EducationCitation)) && (!string.IsNullOrEmpty(p.Education)))
                {
                    citations++;
                }
                if ((!string.IsNullOrEmpty(p.BirthSource)) && (!string.IsNullOrEmpty(p.BirthCitation)) && ((!string.IsNullOrEmpty(p.BirthPlace)) || p.BirthDate > DateTime.MinValue))
                {
                    citations++;
                }
                if ((!string.IsNullOrEmpty(p.DeathSource)) && (!string.IsNullOrEmpty(p.DeathCitation)) && ((!string.IsNullOrEmpty(p.DeathPlace)) || p.DeathDate > DateTime.MinValue))
                {
                    citations++;
                }
                if ((!string.IsNullOrEmpty(p.BurialSource)) && (!string.IsNullOrEmpty(p.BurialCitation)) && ((!string.IsNullOrEmpty(p.BurialPlace)) || p.BurialDate > DateTime.MinValue))
                {
                    citations++;
                }

                foreach (Relationship rel in p.Relationships)
                {
                    if (rel.RelationshipType == RelationshipType.Spouse)
                    {
                        SpouseRelationship spouseRel = ((SpouseRelationship)rel);

                        marriages++;

                        if (!string.IsNullOrEmpty(spouseRel.MarriageCitation) && !string.IsNullOrEmpty(spouseRel.MarriageSource) && (!string.IsNullOrEmpty(spouseRel.MarriagePlace) || spouseRel.MarriageDate > DateTime.MinValue))
                        {
                            relationshipCitations++;
                        }

                        if (!string.IsNullOrEmpty(spouseRel.MarriagePlace))
                        {
                            progress++;
                        }

                        if (spouseRel.MarriageDate != null)
                        {
                            if (spouseRel.MarriageDate > DateTime.MinValue)
                            {
                                marriageDate = spouseRel.MarriageDate;
                                progress++;
                            }
                        }

                        if (spouseRel.SpouseModifier == SpouseModifier.Former)
                        {
                            divorces++;

                            if (spouseRel.DivorceDate != null)
                            {
                                if (spouseRel.DivorceDate > DateTime.MinValue)
                                {
                                    divorceDate = spouseRel.DivorceDate;
                                    progress++;
                                }
                            }

                            if (!string.IsNullOrEmpty(spouseRel.DivorceCitation) && !string.IsNullOrEmpty(spouseRel.DivorceSource) && spouseRel.DivorceDate > DateTime.MinValue)
                            {
                                relationshipCitations++;
                            }
                        }
                    }
                }

                if (!string.IsNullOrEmpty(p.Religion))
                {
                    religions++;
                }
                if (!string.IsNullOrEmpty(p.Education))
                {
                    educations++;
                }
                if (!string.IsNullOrEmpty(p.Occupation))
                {
                    occupations++;
                }
                if (p.BurialDate > DateTime.MinValue || !string.IsNullOrEmpty(p.BurialPlace))
                {
                    burials++;
                }
                if (p.CremationDate > DateTime.MinValue || !string.IsNullOrEmpty(p.CremationPlace))
                {
                    cremations++;
                }
                if (p.DeathDate > DateTime.MinValue || !string.IsNullOrEmpty(p.DeathPlace))
                {
                    deaths++;
                }
                if (p.BirthDate > DateTime.MinValue || !string.IsNullOrEmpty(p.BirthPlace))
                {
                    births++;
                }

                #endregion

                #region min/max dates

                if (p.BirthDate != null)
                {
                    birthDate = p.BirthDate;
                }
                if (p.DeathDate != null)
                {
                    deathDate = p.DeathDate;
                }
                if (p.CremationDate != null)
                {
                    cremationDate = p.CremationDate;
                }
                if (p.BurialDate != null)
                {
                    burialDate = p.BurialDate;
                }

                DateTime?yearmin = year(marriageDate, divorceDate, birthDate, deathDate, cremationDate, burialDate, "min");
                DateTime?yearmax = year(marriageDate, divorceDate, birthDate, deathDate, cremationDate, burialDate, "max");

                if (minimumYear > yearmin.Value.Year)
                {
                    minimumYear = yearmin.Value.Year;
                }
                if (maximumYear < yearmax.Value.Year && yearmax.Value.Year <= DateTime.Now.Year)
                {
                    maximumYear = yearmax.Value.Year;
                }

                #endregion

                relationships += p.Relationships.Count;

                #region progress

                if (!string.IsNullOrEmpty(p.FirstName))
                {
                    progress++;
                }
                if (!string.IsNullOrEmpty(p.LastName))
                {
                    progress++;
                }
                if (!string.IsNullOrEmpty(p.BirthPlace))
                {
                    progress++;
                }
                if (p.BirthDate > DateTime.MinValue)
                {
                    progress++;
                }
                if (!string.IsNullOrEmpty(p.Occupation))
                {
                    progress++;
                }
                if (!string.IsNullOrEmpty(p.Education))
                {
                    progress++;
                }
                if (!string.IsNullOrEmpty(p.Religion))
                {
                    progress++;
                }

                if (!p.IsLiving)
                {
                    deceased++;

                    // Only add progress for one cremation or burial not both
                    if (p.CremationDate > DateTime.MinValue || !string.IsNullOrEmpty(p.CremationPlace))
                    {
                        if (p.CremationDate > DateTime.MinValue)
                        {
                            progress++;
                        }
                        if (!string.IsNullOrEmpty(p.CremationPlace))
                        {
                            progress++;
                        }
                    }
                    else
                    {
                        if (p.BurialDate > DateTime.MinValue)
                        {
                            progress++;
                        }
                        if (!string.IsNullOrEmpty(p.BurialPlace))
                        {
                            progress++;
                        }
                    }

                    if (p.DeathDate > DateTime.MinValue)
                    {
                        progress++;
                    }
                    if (!string.IsNullOrEmpty(p.DeathPlace))
                    {
                        progress++;
                    }
                }
                else
                {
                    living++;
                }

                #endregion

                i++;
            }

            // Will have double counted as marriage/divorce/relationships is always between 2 people
            marriages             = marriages / 2;
            divorces              = divorces / 2;
            relationships         = relationships / 2;
            relationshipCitations = relationshipCitations / 2;
            citations            += relationshipCitations;

            // Media data
            photos            = allPhotos.Count;
            attachments       = allAttachments.Count;
            sourcesCount      = sources.Count;
            repositoriesCount = repositories.Count;

            Photos.Text       = Properties.Resources.Photos + ": " + photos;
            Notes.Text        = Properties.Resources.Notes + ": " + notes;
            Attachments.Text  = Properties.Resources.Attachments + ": " + attachments;
            Citations.Text    = Properties.Resources.Citations + ": " + citations;
            Sources.Text      = Properties.Resources.Sources + ": " + sourcesCount;
            Repositories.Text = Properties.Resources.Repositories + ": " + repositoriesCount;

            // Relationship and event data
            totalEvents = births + deaths + marriages + divorces + cremations + burials + educations + occupations + religions;

            Marriages.Text = Properties.Resources.Marriages + ": " + marriages;
            Divorces.Text  = Properties.Resources.Divorces + ": " + divorces;

            MinYear.Text = Properties.Resources.EarliestKnownEvent + ": " + minimumYear;

            if (maximumYear == DateTime.MinValue.Year)
            {
                MaxYear.Text = Properties.Resources.LatestKnownEvent + ": " + DateTime.Now.Year;
            }
            else
            {
                MaxYear.Text = Properties.Resources.LatestKnownEvent + ": " + maximumYear;
            }

            if (totalEvents == 0)
            {
                MinYear.Text = Properties.Resources.EarliestKnownEvent + ": ";
                MaxYear.Text = Properties.Resources.LatestKnownEvent + ": ";
            }

            TotalFactsEvents.Text = Properties.Resources.FactsEvents + ": " + totalEvents;
            Relationships.Text    = Properties.Resources.Relationships + ": " + relationships;

            // Top 3 names
            string[,] mostCommonNameMale3   = Top3(maleNames);
            string[,] mostCommonNameFemale3 = Top3(femaleNames);
            string[,] mostCommonSurname3    = Top3(surnames);

            FemaleNames.Text = Properties.Resources.TopGirlsNames + ": \n" + "1. " + mostCommonNameFemale3[0, 0] + " " + mostCommonNameFemale3[0, 1] + " 2. " + mostCommonNameFemale3[1, 0] + " " + mostCommonNameFemale3[1, 1] + " 3. " + mostCommonNameFemale3[2, 0] + " " + mostCommonNameFemale3[2, 1];
            MaleNames.Text   = Properties.Resources.TopBoysNames + ": \n" + "1. " + mostCommonNameMale3[0, 0] + " " + mostCommonNameMale3[0, 1] + " 2. " + mostCommonNameMale3[1, 0] + " " + mostCommonNameMale3[1, 1] + " 3. " + mostCommonNameMale3[2, 0] + " " + mostCommonNameMale3[2, 1];
            Surnames.Text    = Properties.Resources.TopSurnames + ": \n" + "1. " + mostCommonSurname3[0, 0] + " " + mostCommonSurname3[0, 1] + " 2. " + mostCommonSurname3[1, 0] + " " + mostCommonSurname3[1, 1] + " 3. " + mostCommonSurname3[2, 0] + " " + mostCommonSurname3[2, 1];

            #region data quality

            // Data quality is a % measuring the number of sourced events converted to a 5 * rating

            star1.Visibility = Visibility.Collapsed;
            star2.Visibility = Visibility.Collapsed;
            star3.Visibility = Visibility.Collapsed;
            star4.Visibility = Visibility.Collapsed;
            star5.Visibility = Visibility.Collapsed;

            if (totalEvents > 0)
            {
                double dataQuality = citations / totalEvents;
                string tooltip     = Math.Round(dataQuality * 100, 2) + "%";

                star1.ToolTip = tooltip;
                star2.ToolTip = tooltip;
                star3.ToolTip = tooltip;
                star4.ToolTip = tooltip;
                star5.ToolTip = tooltip;

                if (dataQuality >= 0)
                {
                    star1.Visibility = Visibility.Visible;
                }
                if (dataQuality >= 0.2)
                {
                    star2.Visibility = Visibility.Visible;
                }
                if (dataQuality >= 0.4)
                {
                    star3.Visibility = Visibility.Visible;
                }
                if (dataQuality >= 0.6)
                {
                    star4.Visibility = Visibility.Visible;
                }
                if (dataQuality >= 0.8)
                {
                    star5.Visibility = Visibility.Visible;
                }
            }

            #endregion

            #region progress

            // Progress is a measure of the completness of a family tree
            // When a person's fields are completed the completeness score increases (ignores suffix as most people won't have one)

            double totalProgress = progress / ((living * livingFacts) + (deceased * deceasedFacts) + (marriages * marriageFacts) + (divorces * divorceFacts));

            if (totalProgress > 100)
            {
                FileProgressBar.Value = 100;
                FileProgressText.Text = "100%";
            }
            else
            {
                FileProgressBar.Value = totalProgress * 100;
                FileProgressText.Text = Math.Round(totalProgress * 100, 2) + "%";
            }

            #endregion

            #region size

            //Data size breakdown of file sizes
            string appLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                                              App.ApplicationFolderName);

            appLocation = Path.Combine(appLocation, App.AppDataFolderName);

            // Absolute path to the photos folder
            string photoLocation      = Path.Combine(appLocation, Photo.PhotosFolderName);
            string noteLocation       = Path.Combine(appLocation, Story.StoriesFolderName);
            string attachmentLocation = Path.Combine(appLocation, Attachment.AttachmentsFolderName);
            string xmlLocation        = Path.Combine(appLocation, "content.xml");
            string currentLocation    = App.FamilyCollection.FullyQualifiedFilename;

            long photoSize      = 0;
            long attachmentSize = 0;
            long noteSize       = 0;
            long xmlSize        = 0;
            long currentSize    = 0;

            if (Directory.Exists(photoLocation))
            {
                photoSize = FileSize(Directory.GetFiles(photoLocation, "*.*"));
            }
            if (Directory.Exists(noteLocation))
            {
                noteSize = FileSize(Directory.GetFiles(noteLocation, "*.*"));
            }
            if (Directory.Exists(attachmentLocation))
            {
                attachmentSize = FileSize(Directory.GetFiles(attachmentLocation, "*.*"));
            }
            if (File.Exists(xmlLocation))
            {
                xmlSize = (new FileInfo(xmlLocation).Length) / 1024;      //convert to Kb
            }
            if (File.Exists(currentLocation))
            {
                currentSize = (new FileInfo(currentLocation).Length) / 1024;      //convert to Kb
            }
            if (currentSize > 0)
            {
                DataSize.Text = Properties.Resources.DataSize + ": " + currentSize + " KB - (" + Properties.Resources.Photos + " " + photoSize + " KB, " + Properties.Resources.Notes + " " + noteSize + " KB, " + Properties.Resources.Attachments + " " + attachmentSize + " KB, " + Properties.Resources.Xml + " " + xmlSize + " KB)";
            }
            else
            {
                DataSize.Text = Properties.Resources.DataSize + ": ";
            }

            #endregion

            #region charts

            //Gender bar chart

            ListCollectionView histogramView = CreateView("Gender", "Gender");
            GenderDistributionControl.View = histogramView;
            GenderDistributionControl.CategoryLabels.Clear();
            GenderDistributionControl.CategoryLabels.Add(Gender.Male, Properties.Resources.Male);
            GenderDistributionControl.CategoryLabels.Add(Gender.Female, Properties.Resources.Female);

            //Living bar chart

            ListCollectionView histogramView2 = CreateView("IsLiving", "IsLiving");
            LivingDistributionControl.View = histogramView2;

            LivingDistributionControl.CategoryLabels.Clear();

            LivingDistributionControl.CategoryLabels.Add(false, Properties.Resources.Deceased);
            LivingDistributionControl.CategoryLabels.Add(true, Properties.Resources.Living);

            //Age group bar chart

            ListCollectionView histogramView4 = CreateView("AgeGroup", "AgeGroup");
            AgeDistributionControl.View = histogramView4;

            AgeDistributionControl.CategoryLabels.Clear();

            AgeDistributionControl.CategoryLabels.Add(AgeGroup.Youth, Properties.Resources.AgeGroupYouth);
            AgeDistributionControl.CategoryLabels.Add(AgeGroup.Unknown, Properties.Resources.AgeGroupUnknown);
            AgeDistributionControl.CategoryLabels.Add(AgeGroup.Senior, Properties.Resources.AgeGroupSenior);
            AgeDistributionControl.CategoryLabels.Add(AgeGroup.MiddleAge, Properties.Resources.AgeGroupMiddleAge);
            AgeDistributionControl.CategoryLabels.Add(AgeGroup.Adult, Properties.Resources.AgeGroupAdult);

            #endregion

            // Ensure the controls are refreshed
            AgeDistributionControl.Refresh();
            SharedBirthdays.Refresh();
            LivingDistributionControl.Refresh();
            GenderDistributionControl.Refresh();
        }
 private void OnDeleteSelected()
 {
     PeopleCollection.Remove(SelectedItem);
 }