private void Build(int retryCount)
        {
            _queryProcessor = ServiceProviderLocator.Current.GetService<IProcessQueries>();
            _updateEstablishment = ServiceProviderLocator.Current.GetService<IHandleCommands<UpdateEstablishment>>();
            _unitOfWork = ServiceProviderLocator.Current.GetService<IUnitOfWork>();
            _placeFinder = ServiceProviderLocator.Current.GetService<IConsumePlaceFinder>();
            try
            {
                var establishment = _queryProcessor.Execute(new GetEstablishmentByIdQuery(_establishmentId));
                if (!establishment.Location.Center.HasValue) return;

                var latitude = establishment.Location.Center.Latitude;
                var longitude = establishment.Location.Center.Longitude;
                if (!latitude.HasValue || !longitude.HasValue) return;

                var result = _placeFinder.Find(new PlaceByCoordinates(latitude.Value, longitude.Value)).SingleOrDefault();
                if (result == null) return;
                if (!result.WoeId.HasValue)
                {
                    throw new NotSupportedException(string.Format(
                        "Could not find WOE ID for coordinates {0},{1}", latitude, longitude));
                }
                //var place = _placeFactory.FromWoeId(result.WoeId.Value);
                var place = _queryProcessor.Execute(
                    new GetPlaceByWoeIdQuery
                    {
                        WoeId = result.WoeId.Value,
                    });
                var places = place.Ancestors.OrderByDescending(n => n.Separation).Select(a => a.Ancestor).ToList();
                places.Add(place);
                var command = new UpdateEstablishment
                {
                    Id = establishment.RevisionId,
                    PlaceIds = places.Select(p => p.RevisionId).ToArray(),
                };
                _updateEstablishment.Handle(command);
                //_establishment.Location.Places.Clear();
                //_establishment.Location.Places = places;
                //_objectCommander.Update(_establishment, true);
                //_entities.Update(_establishment);
                _unitOfWork.SaveChanges();
            }
            catch (Exception ex)
            {
                var exceptionLogger = ServiceProviderLocator.Current.GetService<ILogExceptions>();
                exceptionLogger.LogException(ex);

                if (ex is NotSupportedException)
                {
                    retryCount = 3;
                }

                if (retryCount < 2)
                {
                    Build(++retryCount);
                }
            }
        }
 public virtual ActionResult Locate(EstablishmentForm model)
 {
     if (model != null)
     {
         var establishment = _queryProcessor.Execute(new EstablishmentByGuid(model.EntityId)
         {
             EagerLoad = new Expression<Func<Establishment, object>>[]
             {
                 e => e.Location,
             }
         });
         if (establishment != null)
         {
             var command = new UpdateEstablishment
             {
                 Id = establishment.RevisionId,
                 GoogleMapZoomLevel = model.Location.GoogleMapZoomLevel,
                 CenterLatitude = model.Location.CenterLatitude,
                 CenterLongitude = model.Location.CenterLongitude,
                 NorthLatitude = model.Location.BoundingBoxNortheastLatitude,
                 EastLongitude = model.Location.BoundingBoxNortheastLongitude,
                 SouthLatitude = model.Location.BoundingBoxSouthwestLatitude,
                 WestLongitude = model.Location.BoundingBoxSouthwestLongitude,
             };
             var oldCenter = establishment.Location.Center;
             //establishment.Location.GoogleMapZoomLevel = model.Location.GoogleMapZoomLevel;
             //establishment.Location.Center = new Coordinates
             //{
             //    Latitude = model.Location.CenterLatitude,
             //    Longitude = model.Location.CenterLongitude
             //};
             //establishment.Location.BoundingBox = new BoundingBox
             //{
             //    Northeast = new Coordinates
             //    {
             //        Latitude = model.Location.BoundingBoxNortheastLatitude,
             //        Longitude = model.Location.BoundingBoxNortheastLongitude,
             //    },
             //    Southwest = new Coordinates
             //    {
             //        Latitude = model.Location.BoundingBoxSouthwestLatitude,
             //        Longitude = model.Location.BoundingBoxSouthwestLongitude,
             //    },
             //};
             //_establishments.UnitOfWork.SaveChanges();
             //_objectCommander.Update(establishment, true);
             //_entities.Update(establishment);
             _updateEstablishment.Handle(command);
             _unitOfWork.SaveChanges();
             if (!oldCenter.HasValue)
             {
                 var builder = new SupplementalLocationPlacesBuilder(establishment.RevisionId);
                 var thread = new Thread(builder.Build);
                 thread.Start();
             }
             SetFeedbackMessage(string.Format("Successfully located {0}", establishment.TranslatedName));
             return Redirect(string.Format("/{0}", model.ReturnUrl));
         }
     }
     return HttpNotFound();
 }
Exemple #3
0
 public virtual ActionResult Locate(EstablishmentForm model)
 {
     if (model != null)
     {
         var establishment = _queryProcessor.Execute(new EstablishmentByGuid(model.EntityId)
         {
             EagerLoad = new Expression <Func <Establishment, object> >[]
             {
                 e => e.Location,
             }
         });
         if (establishment != null)
         {
             var command = new UpdateEstablishment
             {
                 Id = establishment.RevisionId,
                 GoogleMapZoomLevel = model.Location.GoogleMapZoomLevel,
                 CenterLatitude     = model.Location.CenterLatitude,
                 CenterLongitude    = model.Location.CenterLongitude,
                 NorthLatitude      = model.Location.BoundingBoxNortheastLatitude,
                 EastLongitude      = model.Location.BoundingBoxNortheastLongitude,
                 SouthLatitude      = model.Location.BoundingBoxSouthwestLatitude,
                 WestLongitude      = model.Location.BoundingBoxSouthwestLongitude,
             };
             var oldCenter = establishment.Location.Center;
             //establishment.Location.GoogleMapZoomLevel = model.Location.GoogleMapZoomLevel;
             //establishment.Location.Center = new Coordinates
             //{
             //    Latitude = model.Location.CenterLatitude,
             //    Longitude = model.Location.CenterLongitude
             //};
             //establishment.Location.BoundingBox = new BoundingBox
             //{
             //    Northeast = new Coordinates
             //    {
             //        Latitude = model.Location.BoundingBoxNortheastLatitude,
             //        Longitude = model.Location.BoundingBoxNortheastLongitude,
             //    },
             //    Southwest = new Coordinates
             //    {
             //        Latitude = model.Location.BoundingBoxSouthwestLatitude,
             //        Longitude = model.Location.BoundingBoxSouthwestLongitude,
             //    },
             //};
             //_establishments.UnitOfWork.SaveChanges();
             //_objectCommander.Update(establishment, true);
             //_entities.Update(establishment);
             _updateEstablishment.Handle(command);
             _unitOfWork.SaveChanges();
             if (!oldCenter.HasValue)
             {
                 var builder = new SupplementalLocationPlacesBuilder(establishment.RevisionId);
                 var thread  = new Thread(builder.Build);
                 thread.Start();
             }
             SetFeedbackMessage(string.Format("Successfully located {0}", establishment.TranslatedName));
             return(Redirect(string.Format("/{0}", model.ReturnUrl)));
         }
     }
     return(HttpNotFound());
 }
Exemple #4
0
        private void Build(int retryCount)
        {
            _queryProcessor      = ServiceProviderLocator.Current.GetService <IProcessQueries>();
            _updateEstablishment = ServiceProviderLocator.Current.GetService <IHandleCommands <UpdateEstablishment> >();
            _unitOfWork          = ServiceProviderLocator.Current.GetService <IUnitOfWork>();
            _placeFinder         = ServiceProviderLocator.Current.GetService <IConsumePlaceFinder>();
            try
            {
                var establishment = _queryProcessor.Execute(new GetEstablishmentByIdQuery(_establishmentId));
                if (!establishment.Location.Center.HasValue)
                {
                    return;
                }

                var latitude  = establishment.Location.Center.Latitude;
                var longitude = establishment.Location.Center.Longitude;
                if (!latitude.HasValue || !longitude.HasValue)
                {
                    return;
                }

                var result = _placeFinder.Find(new PlaceByCoordinates(latitude.Value, longitude.Value)).SingleOrDefault();
                if (result == null)
                {
                    return;
                }
                if (!result.WoeId.HasValue)
                {
                    throw new NotSupportedException(string.Format(
                                                        "Could not find WOE ID for coordinates {0},{1}", latitude, longitude));
                }
                //var place = _placeFactory.FromWoeId(result.WoeId.Value);
                var place = _queryProcessor.Execute(
                    new GetPlaceByWoeIdQuery
                {
                    WoeId = result.WoeId.Value,
                });
                var places = place.Ancestors.OrderByDescending(n => n.Separation).Select(a => a.Ancestor).ToList();
                places.Add(place);
                var command = new UpdateEstablishment
                {
                    Id       = establishment.RevisionId,
                    PlaceIds = places.Select(p => p.RevisionId).ToArray(),
                };
                _updateEstablishment.Handle(command);
                //_establishment.Location.Places.Clear();
                //_establishment.Location.Places = places;
                //_objectCommander.Update(_establishment, true);
                //_entities.Update(_establishment);
                _unitOfWork.SaveChanges();
            }
            catch (Exception ex)
            {
                var exceptionLogger = ServiceProviderLocator.Current.GetService <ILogExceptions>();
                exceptionLogger.LogException(ex);

                if (ex is NotSupportedException)
                {
                    retryCount = 3;
                }

                if (retryCount < 2)
                {
                    Build(++retryCount);
                }
            }
        }
        public virtual ActionResult RunEstablishmentImport()
        {
            var placeMarks = new KmlPlaceMarks(Server.MapPath(string.Format("~{0}",
                                                                            Links.content.kml.establishment_import_kml)));
            var establishmentRows = new EstablishmentRows(Server.MapPath(string.Format("~{0}",
                                                                                       Links.content.kml.establishment_import_tsv)));
            var en = _entities.Get <Language>().SingleOrDefault(x => x.TwoLetterIsoCode.Equals("en", StringComparison.OrdinalIgnoreCase));

            if (en == null)
            {
                throw new InvalidOperationException("Could not find entity for 'English' language");
            }
            var university = _entities.Get <EstablishmentType>().SingleOrDefault(x =>
                                                                                 x.EnglishName.Equals("University", StringComparison.OrdinalIgnoreCase));

            if (university == null)
            {
                throw new InvalidOperationException("Could not find entity for 'University' establishment type");
            }

            foreach (var placeMark in placeMarks)
            {
                ConsoleLog(); // write a new line

                // skip placemarks with no name / title
                if (string.IsNullOrWhiteSpace(placeMark.Name))
                {
                    ConsoleLog("Skipping Placemark with no name", false, true);
                    continue;
                }

                // begin processing the placemark
                ConsoleLog(string.Format("Processing Placemark '{0}'", placeMark.Name));

                // look in spreadsheet for row where official name or english name matches placemark name / title
                var placeMarkClosure     = placeMark;
                var establishmentMatches = establishmentRows.Where(e => placeMarkClosure.Name.Equals(e.OfficialName) ||
                                                                   placeMarkClosure.Name.Equals(e.EnglishName)).ToList();
                if (establishmentMatches.Count > 1)
                {
                    // skip when there are multiple matching rows in the spreadsheet
                    ConsoleLog(string.Format("Skipping, found multiple establishments with name '{0}'.", placeMark.Name), false, true);
                    continue;
                }
                if (establishmentMatches.Count < 1)
                {
                    // skip when there are no matching rows in the spreadsheet
                    ConsoleLog(string.Format("Skipping, found no establishments with name '{0}'.", placeMark.Name), false, true);
                    continue;
                }

                // settle on the row found in the spreadsheet
                ConsoleLog(string.Format("Found 1 establishment with name '{0}'.", placeMark.Name), true);
                var establishmentRow = establishmentMatches.Single();

                // skip if the spreadsheet row has no website URL
                if (string.IsNullOrWhiteSpace(establishmentRow.WebsiteUrl))
                {
                    ConsoleLog(string.Format("Skipping, establishment with name '{0}' has no website URL.", placeMark.Name), false, true);
                    continue;
                }

                // make sure the spreadsheet does not contain any duplicates for this row
                var duplicateEstablishmentRows = establishmentRows.Where(r =>
                                                                         establishmentRow.WebsiteUrl.Equals(r.WebsiteUrl) ||
                                                                         r.OtherUrls.Contains(establishmentRow.WebsiteUrl) ||
                                                                         establishmentRow.OfficialName.Equals(r.OfficialName, StringComparison.OrdinalIgnoreCase) ||
                                                                         establishmentRow.OfficialName.Equals(r.EnglishName, StringComparison.OrdinalIgnoreCase) ||
                                                                         establishmentRow.OfficialName.Equals(r.UCosmic1Name, StringComparison.OrdinalIgnoreCase) ||
                                                                         establishmentRow.EnglishName.Equals(r.OfficialName, StringComparison.OrdinalIgnoreCase) ||
                                                                         establishmentRow.EnglishName.Equals(r.EnglishName, StringComparison.OrdinalIgnoreCase) ||
                                                                         establishmentRow.EnglishName.Equals(r.UCosmic1Name, StringComparison.OrdinalIgnoreCase)
                                                                         ).ToList();
                if (duplicateEstablishmentRows.Count > 1)
                {
                    ConsoleLog(string.Format("Skipping, spreadsheet has duplicate rows for '{0}' / '{1}'.", establishmentRow.OfficialName, establishmentRow.WebsiteUrl), false, true);
                    continue;
                }

                // lookup the establishment in the database by URL
                var establishment = _queryProcessor.Execute(new GetEstablishmentByUrlQuery(establishmentRow.WebsiteUrl));

                // when exactly 1 establishment exists in the db, check its geography
                if (establishment != null)
                {
                    ConsoleLog(string.Format("Establishment with website URL '{0}' is already seeded", establishmentRow.WebsiteUrl));
                    //establishment = establishments.Single();

                    // check geography
                    if (!establishment.Location.Center.HasValue)
                    {
                        var result = _placeFinder.Find(new PlaceByCoordinates(placeMark.Latitude, placeMark.Longitude)).Single();
                        var places = new List <Place>();
                        if (!result.WoeId.HasValue)
                        {
                            ConsoleLog(string.Format("Unable to determine WOE ID for establishment with website URL '{0}'.", establishmentRow.WebsiteUrl), null, true);
                        }
                        else
                        {
                            //var place = placeFactory.FromWoeId(result.WoeId.Value);
                            var place = _queryProcessor.Execute(
                                new GetPlaceByWoeIdQuery
                            {
                                WoeId = result.WoeId.Value,
                            });
                            places = place.Ancestors.OrderByDescending(n => n.Separation).Select(a => a.Ancestor).ToList();
                            places.Add(place);
                        }

                        var placesCount = places.Count();
                        var lastPlace   = places.Last();
                        var command     = new UpdateEstablishment
                        {
                            Id              = establishment.RevisionId,
                            CenterLatitude  = placeMark.Latitude,
                            CenterLongitude = placeMark.Longitude,
                            NorthLatitude   = placesCount > 0 ? lastPlace.BoundingBox.Northeast.Latitude : null,
                            EastLongitude   = placesCount > 0 ? lastPlace.BoundingBox.Northeast.Longitude : null,
                            SouthLatitude   = placesCount > 0 ? lastPlace.BoundingBox.Southwest.Latitude : null,
                            WestLongitude   = placesCount > 0 ? lastPlace.BoundingBox.Southwest.Longitude : null,
                            PlaceIds        = places.Select(p => p.RevisionId),
                        };
                        _updateEstablishment.Handle(command);
                        _unitOfWork.SaveChanges();
                        //establishment.Location.Center = new Coordinates { Latitude = placeMark.Latitude, Longitude = placeMark.Longitude };
                        //establishment.Location.Places = places;
                        //establishment.Location.BoundingBox = (places.Count > 0) ? places.Last().BoundingBox : new BoundingBox();
                        //_unitOfWork.SaveChanges();
                        ConsoleLog(string.Format("Updated location of seeded establishment with website URL '{0}'.", establishmentRow.WebsiteUrl), true, true);
                        continue;
                    }
                    ConsoleLog(string.Format("Bypassing seeded establishment with website URL '{0}' as it already has location information", establishmentRow.WebsiteUrl), true, true);
                }
                else
                {
                    ConsoleLog(string.Format("Seeding establishment with website URL '{0}'...", establishmentRow.WebsiteUrl));
                    //var result = _placeFinder.Find(new PlaceByCoordinates(placeMark.Latitude, placeMark.Longitude)).Single();
                    //var places = new List<Place>();
                    //if (!result.WoeId.HasValue)
                    //{
                    //    ConsoleLog(string.Format("Unable to determine WOE ID for establishment with website URL '{0}'.", establishmentRow.WebsiteUrl), null, true);
                    //}
                    //else
                    //{
                    //    var place = _queryProcessor.Execute(
                    //        new GetPlaceByWoeIdQuery
                    //        {
                    //            WoeId = result.WoeId.Value,
                    //        });
                    //    places = place.Ancestors.OrderByDescending(n => n.Separation).Select(a => a.Ancestor).ToList();
                    //    places.Add(place);
                    //}

                    var command = new CreateEstablishment
                    {
                        TypeId                  = university.RevisionId,
                        OfficialName            = establishmentRow.OfficialName,
                        OfficialWebsiteUrl      = establishmentRow.WebsiteUrl,
                        FindPlacesByCoordinates = true,
                        CenterLatitude          = placeMark.Latitude,
                        CenterLongitude         = placeMark.Longitude,
                        UCosmicCode             = establishmentRow.CeebCode,
                    };

                    var nonOfficialNames = new List <CreateEstablishment.NonOfficialName>();
                    if (!establishmentRow.OfficialName.Equals(establishmentRow.EnglishName, StringComparison.OrdinalIgnoreCase))
                    {
                        nonOfficialNames.Add(new CreateEstablishment.NonOfficialName
                        {
                            Text = establishmentRow.EnglishName,
                            TranslationToLanguageId = en.Id,
                        });
                    }
                    command.NonOfficialNames = nonOfficialNames.ToArray();

                    var nonOfficialUrls = new List <CreateEstablishment.NonOfficialUrl>();
                    if (establishmentRow.OtherUrls != null && establishmentRow.OtherUrls.Length > 0)
                    {
                        nonOfficialUrls.AddRange(establishmentRow.OtherUrls.Select(u =>
                                                                                   new CreateEstablishment.NonOfficialUrl
                        {
                            Value = u,
                        })
                                                 );
                    }
                    command.NonOfficialUrls = nonOfficialUrls.ToArray();
                    _createEstablishment.Handle(command);
                    establishment = command.CreatedEstablishment;

                    _entities.Create(establishment);
                    _unitOfWork.SaveChanges();
                    ConsoleLog(string.Format("Establishment with website URL '{0}' has been seeded.", establishmentRow.WebsiteUrl), true, true);
                }
            }

            //// set up new member(s)
            //var hpu = _entities.Get<Establishment>().SingleOrDefault(
            //    e => e.Urls.Any(u => u.Value.Equals("www.hpu.edu", StringComparison.OrdinalIgnoreCase)));
            //if (hpu != null)
            //{
            //    if (!hpu.IsMember)
            //    {
            //        hpu.IsMember = true;
            //        hpu.EmailDomains.Add(new EstablishmentEmailDomain
            //        {
            //            Value = "@hpu.edu",
            //        });

            //        var lindseyCreator = new CreatePersonHandler(_entities);
            //        var createLindsey = new CreatePersonCommand
            //        {
            //            DisplayName = "Lindsey Garbenis",
            //            UserName = "******",
            //            UserIsRegistered = false,
            //            FirstName = "Lindsey",
            //            LastName = "Garbenis",
            //        };
            //        lindseyCreator.Handle(createLindsey);
            //        createLindsey.CreatedPerson.Emails
            //            .Add(new EmailAddress { IsDefault = true, Value = createLindsey.UserName });

            //        _entities.Update(hpu);
            //        _unitOfWork.SaveChanges();
            //    }
            //}
            //var uwm = _entities.Get<Establishment>().SingleOrDefault(
            //    e => e.Urls.Any(u => u.Value.Equals("www.uwm.edu", StringComparison.OrdinalIgnoreCase)));
            //if (uwm != null)
            //{
            //    if (!uwm.IsMember)
            //    {
            //        uwm.IsMember = true;
            //        uwm.EmailDomains.Add(new EstablishmentEmailDomain
            //                                 {
            //                                     Value = "@uwm.edu",
            //                                 });
            //        _entities.Update(uwm);
            //        _unitOfWork.SaveChanges();
            //    }
            //}

            //// add former name(s)
            //const string upvName = "Universidad Privada del Valle";
            //var univalle = _entities.Get<Establishment>().SingleOrDefault(e => e.WebsiteUrl == "www.univalle.edu");
            //var upv = univalle.Names.SingleOrDefault(n => n.Text == upvName);
            //if (upv == null)
            //{
            //    univalle.Names.Add(new EstablishmentName { Text = upvName, IsFormerName = true });
            //    _entities.Update(univalle);
            //}

            //// fix name
            //var uniatlantico = _entities.Get<Establishment>().Single(e => e.WebsiteUrl == "www.uniatlantico.edu.co");
            //var engName = uniatlantico.Names.SingleOrDefault(n => n.Text == "Atlantic University, Atlantico");
            //if (engName != null)
            //{
            //    engName.Text = "Atlantic University";
            //    _unitOfWork.SaveChanges();
            //}

            ViewBag.Console = _consoleLog.ToString();
            return(View());
        }
        public HttpResponseMessage ValidateParentId(int establishmentId, EstablishmentApiScalarModel model)
        {
            //System.Threading.Thread.Sleep(2000); // test api latency

            model.Id = establishmentId;

            var command = new UpdateEstablishment(model.Id, User);
            Mapper.Map(model, command);
            var validationResult = _updateValidator.Validate(command);
            var propertyName = command.PropertyName(y => y.ParentId);

            Func<ValidationFailure, bool> forText = x => x.PropertyName == propertyName;
            if (validationResult.Errors.Any(forText))
                return Request.CreateResponse(HttpStatusCode.BadRequest,
                    validationResult.Errors.First(forText).ErrorMessage, "text/plain");

            return Request.CreateResponse(HttpStatusCode.OK);
        }
        public HttpResponseMessage Put(int id, EstablishmentApiScalarModel model)
        {
            //System.Threading.Thread.Sleep(2000); // test api latency

            var entity = _queryProcessor.Execute(new EstablishmentById(id));
            if (entity == null) throw new HttpResponseException(HttpStatusCode.NotFound);

            model.Id = id;
            var command = new UpdateEstablishment(id, User);
            Mapper.Map(model, command);

            try
            {
                _updateHandler.Handle(command);
            }
            catch (ValidationException ex)
            {
                var badRequest = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message, "text/plain");
                return badRequest;
            }

            var response = Request.CreateResponse(HttpStatusCode.OK, "Establishment was successfully updated.");
            return response;
        }