private void OnAddGeocacheClick(object sender, RoutedEventArgs args)
        {
            if (activePerson == null)
            {
                MessageBox.Show("Please select a person before adding a geocache.");
            }
            else
            {
                var dialog = new GeocacheDialog();
                dialog.Owner = this;
                dialog.ShowDialog();
                if (dialog.DialogResult == false)
                {
                    return;
                }

                string contents = dialog.GeocacheContents;
                string message  = dialog.GeocacheMessage;

                // Add geocache to map and database here.
                Geocache geocache = AddGeocacheToDatabase(dialog, latestClickLocation);
                var      pin      = AddPin(latestClickLocation, HooverOnGeocachePinShowToolTip(geocache), Colors.Black, geocache);

                pin.MouseDown += (s, a) =>
                {
                    // Handle click on geocache pin here.
                    var clickedGeocache = db.Geocache.First(p => p.ID == geocache.ID);
                    ClickedGeochachePin(clickedGeocache);

                    // Prevent click from being triggered on map.
                    a.Handled = true;
                };
            }
        }
        private void ClickedGeochachePin(Geocache geocache)
        {
            if (activePerson != null && activePerson.Geocaches == null || activePerson != null && !activePerson.Geocaches.Contains(geocache))
            {
                var listOfIds = db.FoundGeocache.Where(fg => fg.PersonID == activePerson.ID).Select(fg => fg.GeocacheID).ToList();

                if (listOfIds.Contains(geocache.ID))
                {
                    var foundGeocacheToDelete = db.FoundGeocache.First(fg => (fg.PersonID == activePerson.ID) && (fg.GeocacheID == geocache.ID));
                    db.Remove(foundGeocacheToDelete);
                    db.SaveChanges();
                }
                else
                {
                    FoundGeocache foundgeocache = new FoundGeocache()
                    {
                        PersonID   = activePerson.ID,
                        GeocacheID = geocache.ID
                    };
                    db.Add(foundgeocache);
                    db.SaveChanges();
                }
            }
            UpdateMap();
        }
 private string HooverOnGeocachePinShowToolTip(Geocache geocache)
 {
     return($"Latitude: {geocache.GeoCoordinate.Latitude}\n" +
            $"Longitude: {geocache.GeoCoordinate.Longitude}\n" +
            $"Message: {geocache.Message}\n" +
            $"Content: {geocache.Contents}\n" +
            $"Person placed geocache: {geocache.Person.FirstName} {geocache.Person.LastName}");
 }
        private void AddFoundGeochacheToDB(Geocache geocache)
        {
            var foundGeocache = new FoundGeocache();

            foundGeocache.GeocacheID = geocache.ID;
            foundGeocache.PersonID   = activePerson.ID;
            db.FoundGeocaches.Add(foundGeocache);
            db.SaveChanges();
        }
        private void Start()
        {
            System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;

            if (applicationId == null)
            {
                MessageBox.Show("Please set the applicationId variable before running this program.");
                Environment.Exit(0);
            }
            CreateMap();


            #region load data from database
            foreach (var personobj in db.Person.Include(x => x.FoundGeocaches))
            {
                Person person = new Person
                {
                    ID           = personobj.ID,
                    FirstName    = personobj.FirstName,
                    LastName     = personobj.LastName,
                    Country      = personobj.Country,
                    City         = personobj.City,
                    StreetName   = personobj.StreetName,
                    StreetNumber = personobj.StreetNumber,
                    Longitude    = personobj.Longitude,
                    Latitude     = personobj.Latitude
                };
                Location locationPer = new Location(longitude: person.Longitude, latitude: person.Latitude);

                string messageTooltipPer = TooltipMessagePer(person);
                var    addPin            = AddPersonPin(locationPer, tooltip: messageTooltipPer, Colors.Blue, 1, person);


                foreach (var geo in db.Geocache.Include(g => g.Person).Include(fg => fg.FoundGeocaches))
                {
                    Geocache geocache = new Geocache
                    {
                        ID        = geo.ID,
                        Latitude  = geo.Latitude,
                        Longitude = geo.Longitude,
                        Contents  = geo.Contents,
                        Message   = geo.Message,
                        Person    = geo.Person
                    };

                    Location location          = new Location(longitude: geocache.Longitude, latitude: geocache.Latitude);
                    string   messageTooltipGeo = TooltipMessageGeo(geocache);
                    addPin = AddGeoPin(location, tooltip: messageTooltipGeo, Colors.Gray, 1, geocache);
                }
            }
            #endregion
        }
        private string GetGeocacheTooltip(Geocache geocache)
        {
            string tooltip;

            if (geocache.Person == null)
            {
                tooltip = $"Latitude: {geocache.Latitude} \nLongitude: {geocache.Longitude}\n\n{geocache.Message}\n{geocache.Contents}";
            }
            else
            {
                tooltip = $"Latitude: {geocache.Latitude} \nLongitude: {geocache.Longitude}\n\n{geocache.Message}\n{geocache.Contents}\n{geocache.Person.FirstName} {geocache.Person.LastName}";
            }
            return(tooltip);
        }
Esempio n. 7
0
        private async void OnAddGeocacheClickAsync(object sender, RoutedEventArgs args)
        {
            if (activePinPerson == null)
            {
                MessageBox.Show("Select Person First", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var dialog = new GeocacheDialog
            {
                Owner = this
            };

            dialog.ShowDialog();
            if (dialog.DialogResult == false)
            {
                return;
            }

            string contents = dialog.GeocacheContents;
            string message  = dialog.GeocacheMessage;

            string tooltip = $"Latitude:\t\t{latestClickLocation.Latitude}\r\nLongitude:\t{latestClickLocation.Longitude}\r\n" +
                             $"Made by:\t{activePinPerson.FirstName + " " + activePinPerson.LastName}\r\n" +
                             $"Contents:\t{contents}\r\nMessage:\t{message}";


            // Add geocache to map and database here.
            Pushpin pin = AddPin(latestClickLocation, tooltip, Colors.Black);

            pin.MouseLeftButtonDown += OnCachePinClick;

            var geocache = new Geocache()
            {
                Contents    = contents,
                Coordinates = latestClickLocation,
                Message     = message
            };

            await _db.AddGeocacheAsync(geocache, activePinPerson.ID);

            pin.Tag = new Dictionary <string, ITag> {
                ["Person"] = activePinPerson, ["Geocache"] = geocache
            };
            cachePins.Add(pin);
        }
        private Geocache AddGeocacheToDatabase(GeocacheDialog dialog, Location latestClickLocation)
        {
            Geocache geocache = new Geocache()
            {
                PersonID      = activePerson.ID,
                GeoCoordinate = new Coordinate()
                {
                    Latitude  = latestClickLocation.Latitude,
                    Longitude = latestClickLocation.Longitude
                },
                Contents = dialog.GeocacheContents,
                Message  = dialog.GeocacheMessage
            };

            db.Add(geocache);
            db.SaveChanges();

            return(geocache);
        }
        private void OnAddGeocacheClick(object sender, RoutedEventArgs args)
        {
            if (CurrentPerID != 0)
            {
                var dialog = new GeocacheDialog();
                dialog.Owner = this;
                dialog.ShowDialog();
                if (dialog.DialogResult == false)
                {
                    return;
                }

                double latitude  = latestClickLocation.Latitude;
                double longitude = latestClickLocation.Longitude;
                string contents  = dialog.GeocacheContents;
                string message   = dialog.GeocacheMessage;


                Geocache geocache = new Geocache
                {
                    Latitude  = latitude,
                    Longitude = longitude,
                    Contents  = contents,
                    Message   = message,
                    Person    = currentPerson
                };

                db.Add(geocache);
                db.SaveChanges();

                // Add geocache to map and database here.
                string messageGeo = TooltipMessageGeo(geocache);
                var    pinPerson  = AddGeoPin(latestClickLocation, messageGeo, Colors.Gray, 1, geocache);

                UpdateMap();
            }
            else
            {
                MessageBox.Show("You need to select a person");
            }
        }
Esempio n. 10
0
        private async void OnCachePinClick(object sender, MouseButtonEventArgs args)
        {
            if (activePinPerson == null)
            {
                return;
            }
            var      pin           = sender as Pushpin;
            Geocache cachePinCache = (Geocache)(pin.Tag as Dictionary <string, ITag>)["Geocache"];

            // To prevent the calling of OnMapLeftClick.
            args.Handled = true;

            if (pin.Background == colors["Red"])
            {
                try
                {
                    await _db.AddFoundGeocacheAsync(new FoundGeocache { PersonID = activePinPerson.ID, GeocacheID = cachePinCache.ID });

                    pin.Background = colors["Green"];
                }
                catch (Exception e)
                {
                    MessageBox.Show("Something went wrong when updating the database.\r\n\r\n" +
                                    e.Message, "Error");
                }
            }
            else if (pin.Background == colors["Green"])
            {
                try
                {
                    await _db.RemoveFoundGeocacheAsync(activePinPerson, cachePinCache);

                    pin.Background = colors["Red"];
                }
                catch (Exception e)
                {
                    MessageBox.Show("Something went wrong when updating the database.\r\n\r\n" +
                                    e.Message, "Error");
                }
            }
        }
        private void OnAddGeocacheClick(object sender, RoutedEventArgs args)
        {
            var dialog = new GeocacheDialog();

            dialog.Owner = this;
            dialog.ShowDialog();
            if (dialog.DialogResult == false)
            {
                return;
            }

            if (activePerson.FirstName != null)
            {
                string contents = dialog.GeocacheContents;
                string message  = dialog.GeocacheMessage;
                // Add geocache to map and database here.
                int cacheID = 1;
                foreach (var cache in geocaches)
                {
                    cacheID = cacheID + 1;
                }
                var geocache = new Geocache();
                geocache.ID        = cacheID;
                geocache.Latitude  = latestClickLocation.Latitude;
                geocache.Longitude = latestClickLocation.Longitude;
                geocache.Contents  = contents;
                geocache.Message   = message;
                geocache.Person    = db.Person.First(p => p.ID == activePerson.ID);


                db.Add(geocache);
                db.SaveChanges();
                OnMapLeftClick();
            }
            else
            {
                MessageBox.Show("Please select a person before adding a geocache.");
            }
        }
        private void ColorGeoPin()
        {
            IEnumerable <Geocache> GeocacheList = new List <Geocache>();

            GeocacheList = db.Geocache.Include(geo => geo.Person).Include(geo => geo.FoundGeocaches);

            foreach (var g in GeocacheList)
            {
                Location location   = new Location(g.Latitude, g.Longitude);
                string   geoToolTip = TooltipMessageGeo(g);
                if (CurrentPerID == 0)
                {
                    color = Colors.Gray;
                }
                else if (g.Person.ID == CurrentPerID)
                {
                    color = Colors.Black;
                }
                else
                {
                    color = Colors.Red;
                }

                var pinGeo = AddGeoPin(location, geoToolTip, color, 1, g);

                foreach (var fg in g.FoundGeocaches)
                {
                    if (fg.PersonID == CurrentPerID)
                    {
                        pinGeo = AddGeoPin(location, geoToolTip, Colors.Green, 1, g);
                    }
                }

                pinGeo.MouseDown += (s, a) =>
                {
                    a.Handled = true;
                    Geocache   currentGeo     = new Geocache();
                    List <int> currentFGeoIDs = new List <int>();

                    currentGeo = db.Geocache.Include(geo => geo.Person)
                                 .First(geo => geo.Latitude == location.Latitude && geo.Longitude == location.Longitude);
                    // To find out each geocache ID that the currently selected person has found and add all of them to a list.
                    currentFGeoIDs = db.FoundGeocache.Where(fg => fg.PersonID == CurrentPerID).Select(fg => fg.GeocacheID).ToList();



                    if (CurrentPerID != currentGeo.Person.ID && CurrentPerID != 0)
                    {
                        if (currentFGeoIDs.Contains(currentGeo.ID))
                        {   // if currently clicked person have found the geocache, remove from db and change color to red
                            pinGeo = AddGeoPin(location, geoToolTip, Colors.Red, 1, currentGeo);
                            var fgToDelete = db.FoundGeocache.First(fg => (fg.PersonID == CurrentPerID) && (fg.GeocacheID == currentGeo.ID));
                            db.Remove(db.FoundGeocache.Single(fg => fg.GeocacheID == fgToDelete.GeocacheID && fg.PersonID == CurrentPerID));
                        }
                        else
                        {
                            // if currently clicked person haven't found geocache add to db and change color to green.
                            pinGeo = AddGeoPin(location, geoToolTip, Colors.Green, 1, currentGeo);
                            var foundFG = new FoundGeocache
                            {
                                GeocacheID = currentGeo.ID,
                                PersonID   = CurrentPerID
                            };
                            db.Add(foundFG);
                        }
                        db.SaveChanges();
                        UpdateMap();
                    }
                };
            }
        }
        private string TooltipMessageGeo(Geocache geo)
        {
            string message = geo.Latitude + ", " + geo.Longitude + "\n" + geo.Message + "\n" + geo.Contents + "\n" + geo.Person.FirstName + " " + geo.Person.LastName;

            return(message);
        }
Esempio n. 14
0
 public Log(Geocache parent)
 {
     ParentGeocache = parent;
     GeocacheID     = parent.GeocacheID;
 }
Esempio n. 15
0
        // Loops through Geocache and gives the right color to the pins, asynchronously.
        private async void BeginColorGeocachePins()
        {
            var database = new AppDbContext();

            IEnumerable <Geocache> GeocacheAsync = new List <Geocache>();
            var task = Task.Run(() =>
            {
                GeocacheAsync = database.Geocache.Include(g => g.Person).Include(g => g.FoundGeocaches);
            });

            await(task);

            foreach (var g in GeocacheAsync)
            {
                Location locationGeocache = new Location(g.Coordinates.Latitude, g.Coordinates.Longitude);
                string   geocacheToolTip  = "long:" + g.Coordinates.Longitude + "\nlat:    " + g.Coordinates.Latitude + "\nContent: "
                                            + g.Content + "\nMessage: " + g.Message + "\nPlaced by: " + g.Person.FirstName + " " + g.Person.LastName;
                if (ActivePersonID == 0)
                {
                    color = Colors.Gray;
                }
                else if (g.Person.ID == ActivePersonID)
                {
                    color = Colors.Black;
                }
                else
                {
                    color = Colors.Red;
                }
                var pinGeocache = AddPin(locationGeocache, geocacheToolTip, color);

                foreach (var f in g.FoundGeocaches)
                {
                    if (f.PersonID == ActivePersonID)
                    {
                        pinGeocache = AddPin(locationGeocache, geocacheToolTip, Colors.Green);
                    }
                }
                // Put delay here to check asynchronisity on geocache-pins.
                await Task.Delay(0);

                // Change color on Geocache-pins on click.
                pinGeocache.MouseDown += async(s, a) =>
                {
                    a.Handled = true;
                    Geocache   activeGeocache = new Geocache();
                    List <int> ActivePersonFoundGeocachIDs = new List <int>();

                    var task1 = Task.Run(() =>
                    {
                        activeGeocache = database.Geocache.Include(e => e.Person).First(gc => gc.Coordinates.Latitude == locationGeocache.Latitude && g.Coordinates.Longitude == locationGeocache.Longitude);
                        ActivePersonFoundGeocachIDs = database.FoundGeocache.Where(f => f.PersonID == ActivePersonID).Select(f => f.GeocacheID).ToList();
                    });
                    await(task1);

                    // If ActivePerson is selected and is not the one who placed the geocache...
                    if (ActivePersonID != activeGeocache.Person.ID && ActivePersonID != 0)
                    {
                        //... and ActivePerson already found this geocachen, then change the pin-color to red and remove from FoundGeocache.
                        if (ActivePersonFoundGeocachIDs.Contains(activeGeocache.ID))
                        {
                            pinGeocache = AddPin(locationGeocache, geocacheToolTip, Colors.Red);
                            var task2 = Task.Run(() =>
                            {
                                var foundGeocacheToDelete = database.FoundGeocache.First(fg => (fg.PersonID == ActivePersonID) && (fg.GeocacheID == activeGeocache.ID));
                                database.Remove(database.FoundGeocache.Single(fg => fg.GeocacheID == foundGeocacheToDelete.GeocacheID && fg.PersonID == ActivePersonID));
                            });
                            await(task2);
                        }
                        // Else change pin-color to green and add to FoundGeocache.
                        else
                        {
                            pinGeocache = AddPin(locationGeocache, geocacheToolTip, Colors.Green);
                            var foundGeocache = new FoundGeocache
                            {
                                GeocacheID = activeGeocache.ID,
                                PersonID   = ActivePersonID
                            };
                            database.Add(foundGeocache);
                        }
                        var task3 = Task.Run(() =>
                        {
                            database.SaveChanges();
                        });
                        await(task3);

                        UpdateMap();
                    }
                };
            }
        }
        private void OnLoadFromFileClick(object sender, RoutedEventArgs args)
        {
            activePerson = new Person();
            ClearDatabase();
            var dialog = new Microsoft.Win32.OpenFileDialog();

            dialog.DefaultExt = ".txt";
            dialog.Filter     = "Text documents (.txt)|*.txt";
            bool?result = dialog.ShowDialog();

            if (result != true)
            {
                return;
            }

            string path = dialog.FileName;

            // Read the selected file here.
            string[] lines = File.ReadAllLines(path).ToArray();

            var foundList = new Dictionary <Person, List <int> >();

            try
            {
                foreach (string line in lines)
                {
                    string[] values = line.Split('|').Select(v => v.Trim()).ToArray();
                    if (!line.StartsWith("Found:") && values.Length == 8)
                    {
                        var person = new Person();
                        person.FirstName    = values[0];
                        person.LastName     = values[1];
                        person.Country      = values[2];
                        person.City         = values[3];
                        person.StreetName   = values[4];
                        person.StreetNumber = byte.Parse(values[5]);
                        person.Latitude     = double.Parse(values[6]);
                        person.Longitude    = double.Parse(values[7]);
                        db.Add(person);
                        db.SaveChanges();
                    }
                    else if (!line.StartsWith("Found:") && values.Length == 5)
                    {
                        var person   = db.Person.OrderByDescending(p => p.ID).First();
                        var geocache = new Geocache();
                        geocache.Person    = person;
                        geocache.ID        = int.Parse(values[0]);
                        geocache.Latitude  = double.Parse(values[1]);
                        geocache.Longitude = double.Parse(values[2]);
                        geocache.Contents  = values[3];
                        geocache.Message   = values[4];
                        db.Add(geocache);
                        db.SaveChanges();
                    }
                    else if (line.StartsWith("Found:"))
                    {
                        var      person  = db.Person.OrderByDescending(p => p.ID).First();
                        string[] found   = line.Split(',', ':').Skip(1).Select(v => v.Trim()).ToArray();
                        var      intList = new List <int>();
                        foreach (var foundNum in found)
                        {
                            int intAdd;
                            var num = int.TryParse(foundNum, out intAdd);
                            if (num)
                            {
                                intList.Add(intAdd);
                            }
                        }
                        foundList.Add(person, intList);
                    }
                }

                foreach (var pair in foundList)
                {
                    var personValue = pair.Value;
                    foreach (var value in personValue)
                    {
                        var geocache      = db.Geocache.First(g => g.ID == value);
                        var foundGeocache = new FoundGeocache();
                        foundGeocache.Person   = pair.Key;
                        foundGeocache.Geocache = geocache;
                        db.Add(foundGeocache);
                        db.SaveChanges();
                    }
                }
            }
            catch
            {
                MessageBox.Show("The textfile is not properly formatted");
            }


            UpdateMap();
        }
        private void UpdateMap()
        {
            List <Pushpin> notFoundPins = new List <Pushpin>();

            notFoundPins = pushpins.ToList();
            // It is recommended (but optional) to use this method for setting the color and opacity of each pin after every user interaction that might change something.
            // This method should then be called once after every significant action, such as clicking on a pin, clicking on the map, or clicking a context menu option.

            // This code runs if a person-pin is clicked. This code fades all other person-pins.
            if (activePerson != null)
            {
                foreach (var pin in pushpins)
                {
                    if (pin.Tag.GetType() == typeof(Person))
                    {
                        Person person = (Person)pin.Tag;
                        if (person.ID != activePerson.ID)
                        {
                            pin.Opacity = 0.5;
                        }
                        else
                        {
                            pin.Opacity = 1;
                        }
                    }
                }

                // Finds the clicked person's placed geocaches.
                if (activePerson.Geocaches != null)
                {
                    foreach (var placedCache in activePerson.Geocaches)
                    {
                        foreach (var pin in pushpins)
                        {
                            if (pin.Tag.GetType() == typeof(Geocache))
                            {
                                Geocache geocache = (Geocache)pin.Tag;
                                if (placedCache.PersonID == geocache.PersonID)
                                {
                                    pin.Background = new SolidColorBrush(Colors.Black);
                                    notFoundPins.Remove(pin);
                                }
                                else
                                {
                                    pin.Background = new SolidColorBrush(Colors.Gray);
                                }
                            }
                        }
                    }
                }

                // Colors the clicked person's found geocaches.
                if (activePerson.FoundGeocache != null)
                {
                    foreach (var foundCache in activePerson.FoundGeocache)
                    {
                        foreach (var pin in pushpins)
                        {
                            if (pin.Tag.GetType() == typeof(Geocache))
                            {
                                Geocache geocache = (Geocache)pin.Tag;
                                if (foundCache.GeocacheID == geocache.ID)
                                {
                                    pin.Background = new SolidColorBrush(Colors.Green);
                                    notFoundPins.Remove(pin);
                                }
                            }
                        }
                    }
                }

                // Colors the clicked person's NOT found geocaches.
                foreach (var pin in notFoundPins)
                {
                    if (pin.Tag.GetType() == typeof(Geocache))
                    {
                        Geocache geocache = (Geocache)pin.Tag;
                        pin.Background = new SolidColorBrush(Colors.Red);
                    }
                }
            }

            // If no person is selected, this code runs. Resets colors and opacity of all pins.
            else
            {
                foreach (var pin in pushpins)
                {
                    pin.Opacity = 1;

                    pin.Background = pin.Tag.GetType() == typeof(Person) ?
                                     pin.Background = new SolidColorBrush(Colors.Blue) :
                                                      pin.Background = new SolidColorBrush(Colors.Gray);
                }
            }
        }
Esempio n. 18
0
        // Load from file.
        private async void OnLoadFromFileClick(object sender, RoutedEventArgs args)
        {
            var dialog = new Microsoft.Win32.OpenFileDialog();

            dialog.DefaultExt = ".txt";
            dialog.Filter     = "Text documents (.txt)|*.txt";
            bool?result = dialog.ShowDialog();

            if (result != true)
            {
                return;
            }
            string path = dialog.FileName;

            // Clear database and reset map.
            using (var database = new AppDbContext())
            {
                var task = Task.Run(() =>
                {
                    database.Person.RemoveRange(database.Person);
                    database.Geocache.RemoveRange(database.Geocache);
                    database.SaveChanges();
                });
                await(task);

                ActivePersonID = 0;
                layer.Children.Clear();
            }

            // Read and split selected file here.
            List <Person> personsTotalList = new List <Person> {
            };
            string textFromFile            = File.ReadAllText(path, Encoding.Default);

            string[] textParts = textFromFile.Split(new string[] { Environment.NewLine + Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            // Loop to get person objects and there placed geocaches to lists.
            foreach (string part in textParts)
            {
                List <Geocache> geocaches = new List <Geocache> {
                };
                string[] lines            = part.Split('\n');

                foreach (string line in lines)
                {
                    if (char.IsDigit(line[0]))
                    {
                        string[] values = line.Split('|');
                        Geocache g      = new Geocache
                        {
                            Content     = values[3].Trim(),
                            Message     = values[4].Trim(),
                            Coordinates = new GeoCoordinate
                            {
                                Latitude  = Convert.ToDouble(values[1]),
                                Longitude = Convert.ToDouble(values[2])
                            }
                        };
                        geocaches.Add(g);
                    }
                    else if (line.StartsWith("Found:") == false && char.IsDigit(line[0]) == false)
                    {
                        string[] values = line.Split('|');
                        Person   p      = new Person
                        {
                            FirstName    = values[0].Trim(),
                            LastName     = values[1].Trim(),
                            Country      = values[2].Trim(),
                            City         = values[3].Trim(),
                            StreetName   = values[4].Trim(),
                            StreetNumber = Convert.ToByte(values[5]),
                            Geocaches    = geocaches,
                            Coordinates  = new GeoCoordinate
                            {
                                Latitude  = Convert.ToDouble(values[6]),
                                Longitude = Convert.ToDouble(values[7])
                            }
                        };
                        personsTotalList.Add(p);
                    }
                }
            }

            // Loop to put all geocaches in geocachesTotalList.
            List <Geocache> geocachesTotalList = new List <Geocache> {
            };

            foreach (Person p in personsTotalList)
            {
                foreach (Geocache g in p.Geocaches)
                {
                    geocachesTotalList.Add(g);
                }
            }

            // Loop to get FoundGeocaches and connections to join-tabel to a dictionary.
            Dictionary <Person, List <int> > foundGeocachesDictionary = new Dictionary <Person, List <int> >();

            foreach (string part in textParts)
            {
                List <int> indexes = new List <int>();
                string[]   lines   = part.Split('\n');

                foreach (string line in lines)
                {
                    string ln1 = line.Substring(6);
                    if (line.StartsWith("Found:") && ln1 != " " && ln1 != "")
                    {
                        string[] numbers = ln1.Split(',');
                        foreach (string n in numbers)
                        {
                            int n1 = Convert.ToInt32(n);
                            indexes.Add(n1);
                        }
                    }
                    else if (line.StartsWith("Found:") == false && char.IsDigit(line[0]) == false)
                    {
                        string[] values = line.Split('|');
                        foreach (Person p in personsTotalList)
                        {
                            if (p.FirstName == values[0].Trim() && p.LastName == values[1].Trim())
                            {
                                foundGeocachesDictionary[p] = indexes;
                            }
                        }
                        ;
                    }
                }
            }

            // Loop through dictionary and make a lista of FoundGeocaches.
            List <FoundGeocache> foundGeocaches = new List <FoundGeocache>();

            foreach (KeyValuePair <Person, List <int> > pair in foundGeocachesDictionary)
            {
                foreach (int i in pair.Value)
                {
                    FoundGeocache fg = new FoundGeocache
                    {
                        Person   = pair.Key,
                        Geocache = geocachesTotalList[i - 1]
                    };
                    foundGeocaches.Add(fg);
                }
            }

            // Loop through all persons and add to foundGeocaches list.
            foreach (Person p in personsTotalList)
            {
                p.FoundGeocaches = new List <FoundGeocache>();
                foreach (FoundGeocache fg in foundGeocaches)
                {
                    if (fg.Person.FirstName == p.FirstName && fg.Person.LastName == p.LastName)
                    {
                        p.FoundGeocaches.Add(fg);
                    }
                }
            }

            // Loop through all geocaches and add to foundGeocaches list.
            foreach (Geocache g in geocachesTotalList)
            {
                g.FoundGeocaches = new List <FoundGeocache>();
                foreach (FoundGeocache fg in foundGeocaches)
                {
                    if (fg.Geocache.Message == g.Message && fg.Geocache.Content == g.Content)
                    {
                        g.FoundGeocaches.Add(fg);
                    }
                }
            }

            // Save all persons and geocaches to database, asynchronously.
            using (var database = new AppDbContext())
            {
                foreach (Person p in personsTotalList)
                {
                    database.Add(p);
                }

                foreach (Geocache g in geocachesTotalList)
                {
                    database.Add(g);
                }

                var task = Task.Run(() =>
                {
                    database.SaveChanges();
                });
                await(task);
            }
            UpdateMap();
        }
        private Pin AddGeoPin(Location location, string tooltip, Color color, double opacity, Geocache geocache)
        {
            var pin = new Pin();

            pin.Cursor     = Cursors.Hand;
            pin.Background = new SolidColorBrush(color);
            pin.Geocache   = geocache;
            pin.Opacity    = opacity;
            pin.Tag        = geocache;
            ToolTipService.SetToolTip(pin, tooltip);
            ToolTipService.SetInitialShowDelay(pin, 0);
            layer.AddChild(pin, new Location(location.Latitude, location.Longitude));
            return(pin);
        }
        private void OnLoadFromFileClick(object sender, RoutedEventArgs args)
        {
            var dialog = new Microsoft.Win32.OpenFileDialog();

            dialog.DefaultExt = ".txt";
            dialog.Filter     = "Text documents (.txt)|*.txt";
            bool?result = dialog.ShowDialog();

            if (result != true)
            {
                return;
            }

            string path = dialog.FileName;

            // Read the selected file here.
            Dictionary <Person, List <int> > personFoundGeocaches = new Dictionary <Person, List <int> >();
            Dictionary <int, Geocache>       specificGeocache     = new Dictionary <int, Geocache>();

            string[] lines = File.ReadAllLines(path, Encoding.GetEncoding("ISO-8859-1")).ToArray();
            int      counterPersonObject = 0;
            int      emptyLineCounter    = 0;

            Person   person   = new Person();
            Geocache geocache = new Geocache();

            db.Person.RemoveRange(db.Person);
            db.Geocache.RemoveRange(db.Geocache);
            db.SaveChanges();

            foreach (string line in lines)
            {
                if (!line.Contains("Found"))
                {
                    string[] values = line.Split('|').Select(v => v.Trim()).ToArray();

                    if (values[0] != "" && counterPersonObject == 0)
                    {
                        person           = new Person();
                        person.FirstName = values[0];
                        person.LastName  = values[1];

                        person.Address = new Address
                        {
                            Country      = values[2],
                            City         = values[3],
                            StreetName   = values[4],
                            StreetNumber = byte.Parse(values[5])
                        };
                        person.GeoCoordinate = new Coordinate
                        {
                            Latitude  = double.Parse(values[6]),
                            Longitude = double.Parse(values[7])
                        };
                        db.Person.Add(person);
                        db.SaveChanges();

                        emptyLineCounter = 0;
                        counterPersonObject++;
                    }

                    else if (values[0] == "")
                    {
                        counterPersonObject = 0;
                        emptyLineCounter++;

                        if (emptyLineCounter == 2)
                        {
                            return;
                        }
                    }

                    else
                    {
                        geocache = new Geocache();

                        int geocacheNumber = int.Parse(values[0]);
                        geocache.GeoCoordinate = new Coordinate
                        {
                            Latitude  = double.Parse(values[1]),
                            Longitude = double.Parse(values[2])
                        };
                        geocache.Contents = values[3];
                        geocache.Message  = values[4];
                        geocache.Person   = person;

                        db.Geocache.Add(geocache);
                        db.SaveChanges();

                        specificGeocache.Add(geocacheNumber, geocache);
                    }
                }

                else
                {
                    string[]   geocachesFound = line.Split(':', ',').Skip(1).Select(v => v.Trim()).ToArray();
                    List <int> geocachesId    = new List <int>();
                    foreach (var item in geocachesFound)
                    {
                        int geocacheId = int.Parse(item);
                        geocachesId.Add(geocacheId);
                    }
                    personFoundGeocaches.Add(person, geocachesId);
                }
            }

            foreach (var personObject in personFoundGeocaches.Keys)
            {
                foreach (int geocacheId in personFoundGeocaches[personObject])
                {
                    var           geocacheObject = specificGeocache[geocacheId];
                    FoundGeocache foundGeocache  = new FoundGeocache
                    {
                        PersonID   = personObject.ID,
                        GeocacheID = geocacheObject.ID
                    };
                    db.Add(foundGeocache);
                    db.SaveChanges();
                }
                ;
            }
            pushpins.Clear();
            layer.Children.Clear();
            activePerson = null;
            ReadPersonAndGeocacheFromDatabase();
        }
Esempio n. 21
0
        private static IEnumerable <Geocache> ImportGPX(XDocument doc)
        {
            List <Geocache> geocaches = new List <Geocache>();

            DateTime datePocketQueryGenerated = GetGenerationDate(doc);

            foreach (XElement wpt in doc.Descendants(ns + "wpt"))
            {
                Geocache geocache = new Geocache()
                {
                    Latitude  = Convert.ToSingle(wpt.Attribute("lat").Value),
                    Longitude = Convert.ToSingle(wpt.Attribute("lon").Value)
                };

                geocache.LastChanged = datePocketQueryGenerated;

                geocache.Time        = wpt.Element(ns + "time").Value;
                geocache.GeocacheID  = wpt.Element(ns + "name").Value;
                geocache.Description = wpt.Element(ns + "desc").Value;
                geocache.URL         = wpt.Element(ns + "url").Value;
                geocache.URLName     = wpt.Element(ns + "urlname").Value;
                geocache.Symbol      = wpt.Element(ns + "sym").Value;
                geocache.SymbolType  = wpt.Element(ns + "type").Value;

                XElement groundspeak = wpt.Element(gs + "cache");

                geocache.CacheID         = groundspeak.Attribute("id").Value;
                geocache.StatusAvailable = Convert.ToBoolean(groundspeak.Attribute("available").Value);
                geocache.StatusArchived  = Convert.ToBoolean(groundspeak.Attribute("archived").Value);
                geocache.Name            = groundspeak.Element(gs + "name").Value;
                geocache.Owner           = groundspeak.Element(gs + "owner").Value;
                geocache.Type            = groundspeak.Element(gs + "type").Value;
                geocache.Size            = groundspeak.Element(gs + "container").Value;

                //TODO:attributes go here

                geocache.Difficulty       = Convert.ToSingle(groundspeak.Element(gs + "difficulty").Value);
                geocache.Terrain          = Convert.ToSingle(groundspeak.Element(gs + "terrain").Value);
                geocache.Country          = groundspeak.Element(gs + "country").Value;
                geocache.State            = groundspeak.Element(gs + "state").Value;
                geocache.ShortDescription = groundspeak.Element(gs + "short_description").Value;
                geocache.LongDescription  = groundspeak.Element(gs + "long_description").Value;

                // save logs here
                foreach (XElement l in groundspeak.Descendants(gs + "log"))
                {
                    Log log = new Log(geocache);
                    log.ID = Int64.Parse(l.FirstAttribute.Value);
                    /* date */
                    log.Date = DateTime.Parse(l.Element(gs + "date").Value);
                    /* type */
                    log.Type = l.Element(gs + "type").Value;
                    /* author */
                    log.Author = l.Element(gs + "finder").Value; //TODO get finder ID from attribute
                    /* text */
                    log.Text = l.Element(gs + "text").Value;
                    /* text encoded */
                    log.TextEncoded = Boolean.Parse(l.Element(gs + "text").FirstAttribute.Value);
                    log.LastChanged = geocache.LastChanged;



                    geocache.Logs.Add(log);
                }

                geocaches.Add(geocache);
            }

            return(geocaches);
        }
        public void ReadFromFile(string path, AppDbContext db)
        {
            var person   = new List <Person>();
            var found    = new Dictionary <Person, int[]>();
            var geocache = new Dictionary <int, Geocache>();

            found.Clear();

            string[] lines = File.ReadAllLines(path);
            foreach (string line in lines)
            {
                string[] split = line.Split('|').Select(v => v.Trim()).ToArray();

                if (split[0] != "")
                {
                    if (split.Length == 8)
                    {
                        string firstName    = split[0];
                        string lastName     = split[1];
                        string country      = split[2];
                        string city         = split[3];
                        string streetName   = split[4];
                        Int16  streetNumber = Int16.Parse(split[5]);
                        double latitude     = double.Parse(split[6]);
                        double longitude    = double.Parse(split[7]);

                        var newPerson = new Person
                        {
                            FirstName    = firstName,
                            LastName     = lastName,
                            Country      = country,
                            City         = city,
                            StreetName   = streetName,
                            StreetNumber = streetNumber,
                            Latitude     = latitude,
                            Longitude    = longitude
                        };



                        if (person.Count == 0)
                        {
                            person.Add(newPerson);
                        }
                        else
                        {
                            person.Clear();
                            person.Add(newPerson);
                        }
                    }

                    else if (split.Length == 5)
                    {
                        int    id        = int.Parse(split[0]);
                        double latitude  = double.Parse(split[1]);
                        double longitude = double.Parse(split[2]);
                        string contents  = split[3];
                        string message   = split[4];

                        var newGeo = new Geocache
                        {
                            Latitude  = latitude,
                            Longitude = longitude,
                            Contents  = contents,
                            Message   = message,
                            Person    = person[0]
                        };

                        geocache.Add(id, newGeo);
                    }
                    else
                    {
                        string foundString = split[0].Substring(6);

                        int[] intSplit = foundString.Split(',').Select(s => int.Parse(s.Trim())).ToArray();

                        if (foundString != "")
                        {
                            found.Add(person[0], intSplit);
                        }
                        else
                        {
                            db.Add(person[0]);
                        }
                    }
                }
            }

            foreach (var item in found)
            {
                foreach (var foundGeo in item.Value)
                {
                    var newfg = new FoundGeocache()
                    {
                        Person   = item.Key,
                        Geocache = geocache.Where(s => s.Key == foundGeo).Select(fg => fg.Value).First()
                    };
                    db.Add(newfg);
                    try
                    {
                        db.SaveChanges();
                    }
                    catch
                    {
                    }
                }
            }
        }