Beispiel #1
0
        public HttpResponseMessage AddGeolocation([Url] string ipOrUrl)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, "Input parameter ipOrUrl is not valid"));
            }
            var result = GeolocationService.AddGeolocation(ipOrUrl);

            switch (result)
            {
            case ResultCode.OK:
                return(Request.CreateResponse(HttpStatusCode.OK, "Geolocation added successfully"));

            case ResultCode.ServiceUnavailable:
                return(Request.CreateResponse(HttpStatusCode.ServiceUnavailable, "IPStack service which is used for getting geolocation data is unavailable"));

            case ResultCode.RecordAlreadyExists:
                return(Request.CreateResponse(HttpStatusCode.Conflict, "Geolocation with this ip or url is already added"));

            case ResultCode.UrlNotFound:
                return(Request.CreateResponse((HttpStatusCode)422, "Geolocation with this ip or url cannot be found"));

            case ResultCode.UnexpectedError:
            case ResultCode.DatabaseError:
            default:
                return(Request.CreateResponse(HttpStatusCode.InternalServerError));
            }
        }
Beispiel #2
0
        public ActionResult Flair([DefaultValue("html")] string format)
        {
            string SourceIP = string.IsNullOrEmpty(Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) ?
                              Request.ServerVariables["REMOTE_ADDR"] :
                              Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            var location = GeolocationService.HostIpToPlaceName(SourceIP);
            var dinners  = dinnerRepository.
                           FindByLocation(location.Position.Lat, location.Position.Long).
                           OrderByDescending(p => p.EventDate).Take(3);

            // Select the view we'll return. Using a switch because we'll add in JSON and other formats later.
            // Will probably extract or refactor this.
            string view;

            switch (format.ToLower())
            {
            case "javascript":
                view = "JavascriptFlair";
                break;

            default:
                view = "Flair";
                break;
            }

            return(View(
                       view,
                       new FlairViewModel
            {
                Dinners = dinners.ToList(),
                LocationName = string.IsNullOrEmpty(location.City) ? "you" :  String.Format("{0}, {1}", location.City, location.RegionName)
            }
                       ));
        }
        public async Task GetAsync_GeolocationExists_ShouldBeReturned()
        {
            var ipAddress = "192.168.0.1";
            var geolocationRepositoryMock = new Mock <IGeolocationRepository>();

            geolocationRepositoryMock.Setup(x => x.GetAsync(It.IsAny <string>()))
            .ReturnsAsync(new Domain.Geolocation()
            {
                City      = "San Francisco",
                Latitude  = 37.773972d,
                Longitude = -122.431297d
            });
            var ipDetailsServiceMock = new Mock <IIpDetailsService>();
            var networkAddressMock   = new Mock <INetworkAddress>();

            var geolocationService = new GeolocationService(geolocationRepositoryMock.Object, ipDetailsServiceMock.Object,
                                                            networkAddressMock.Object);

            var result = await geolocationService.GetAsync(ipAddress);

            result.Should().NotBeNull().And.BeOfType(typeof(GeolocationDto));
            result.City.Should().Be("San Francisco");
            result.Latitude.Should().Be(37.773972d);
            result.Longitude.Should().Be(-122.431297d);
        }
        public IntervalsPageViewModel(Tts TextToSpeech, GeolocationService geolocationService)
        {
            TimerPickersViewModel.Add(new WheelTimerPickerViewModel
            {
                Name      = "Walking Duration",
                IsVisible = true,
                InEdit    = true,
                Time      = new TimeSpan(0, 1, 0) //tobind with default val
            });

            TimerPickersViewModel.Add(new WheelTimerPickerViewModel
            {
                Name      = "Running Duration",
                IsVisible = false,
                InEdit    = false,
                Time      = new TimeSpan(0, 1, 0) //to bind with default val
            });

            _locationService = geolocationService;
            _locationService.SpeedErrorrAreaOFMonoticity = 3; // acceptble error area of 2 km/h
            _locationService.PartialSpeedGraphSize       = 15;
            Task.Run(async() => { await _locationService.GetPermissions(); });
            _oldViewModel             = TimerPickersViewModel[0];
            _textToSpeach             = TextToSpeech;
            RightButtonClickedCommand = new Command(() => OnRightButtonClicked());
            EditButtonClickedCommand  = new Command(() => OnEditButtonClicked());
            LeftButtonClickedCommand  = new Command(() => OnLeftButtonClicked());
            StartTimerCommand         = new Command(() => StartTimer());
            PauseTimerCommand         = new Command(() => PauseTimer());
            CancelTimerCommand        = new Command(() => CancelTimer());
        }
        public string FindGeolocationCustomer()
        {
            var apiService = new GeolocationService();

            var location = apiService.FindLocationCustomer("");

            return(location.Lat + location.Lng);
        }
Beispiel #6
0
        public INormalizedWeatherData GetWeatherData()
        {
            var GeoService = new GeolocationService();
            var Ip         = IpFunctions.GetUserIP();

            if (Ip == null)
            {
                Logger.Critical("Unable to obtain IP targetable IP address. If running locally, set FallbackGeolocationIP in AppSettings to a geo-targetable IP address.");
                return(null);
            }

            var geodata = GeoService.GetGeolocation(Ip);

            if (geodata == null)
            {
                Logger.Critical("Unable to retrieve geolocation data for the provided IP address. Have you correctly installed and configured a Geolocation provider?");
                return(null);
            }

            var url = $"{_urlBase}?lat={geodata.Location.Latitude}&lon={geodata.Location.Longitude}&appid={AssemblySettings.OpenWeatherMapApiKey}";

            WeatherResponse response;

            try
            {
                response = Task.Run(async() => await weatherMapClient.GetWeatherDataAsync(url)).Result;
            }
            catch (Exception ex)
            {
                Logger.Critical(ex.Message, ex);
                return(null);
            }

            var weather = new NormalizedWeatherData
            {
                CurrentConditions = new CurrentConditions
                {
                    CloudinessPercent        = response.CloudinessPct.HasValue ? response.CloudinessPct.Value : -1,
                    ConditionCategory        = response.WeatherData.First().Main,
                    Description              = response.WeatherData.First().Description,
                    Humidity                 = response.MainData.Humidity,
                    Pressure                 = response.MainData.Pressure,
                    RainPastHourMetric       = response.RainData?.OneHourMetric,
                    RainPastThreeHoursMetric = response.RainData?.ThreeHourMetric,
                    SnowPastHourMetric       = response.SnowData?.OneHourMetric,
                    SnowPastThreeHoursMetric = response.SnowData?.ThreeHourMetric,
                    SunriseUnixUTC           = response.SystemData.Sunrise,
                    SunsetUnixUTC            = response.SystemData.Sunset,
                    TemperatureK             = response.MainData.TemperatureKelvin,
                    TemperatureMaxK          = response.MainData.TemperatureKelvinMax,
                    TemperatureMinK          = response.MainData.TemperatureKelvinMin,
                    WindDegrees              = response.WindData.Degrees,
                    WindSpeedMetric          = response.WindData.Speed
                }
            };

            return(weather);
        }
Beispiel #7
0
        public static IGeolocationService GetGeolocationService()
        {
            var mapper =
                new MapperConfiguration(options => { options.AddProfile(new MappingsProfile()); }).CreateMapper();

            var geolocationService = new GeolocationService(BuildDbContext(), mapper);

            return(geolocationService);
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (_geolocation == null)
            {
                _geolocation = new GeolocationService();
                _geolocation.PositionUpdated += GeolocationPositionUpdated;
                _geolocation.Initialize();
            }
        }
        public ActionResult ExtraQuestionsStep(ExtraQuestionsViewModel vm, HttpPostedFileBase file)
        {
            if (file != null)
            {
                IGeolocationService geo = new GeolocationService();
                var location            = geo.GetLocation(file.InputStream);
                vm.Latitude  = location.Latitude;
                vm.Longitude = location.Longitude;
            }

            return(View("Summary", vm));
        }
Beispiel #10
0
        public HttpResponseMessage DeleteGeolocation(string ipOrUrl)
        {
            var result = GeolocationService.DeleteGeolocation(ipOrUrl);

            if (result == ResultCode.OK)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, "Geolocation removed successfully"));
            }
            if (result == ResultCode.RecordDoesNotExist)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound, "Geolocation is not found for this ip or url"));
            }
            return(Request.CreateResponse(HttpStatusCode.InternalServerError));
        }
        public async void Should_CheckIfGeolocationIsSupportedAsync()
        {
            var isGeolocationSupported = true;

            _mapJsRuntimeMock.Setup(runtime => runtime.InvokeAsync <bool>(It.IsAny <string>(), It.IsAny <object[]>())).ReturnsAsync(isGeolocationSupported);
            var service = new GeolocationService(_mapJsRuntimeMock.Object, _loggerMock.Object);

            var result = await service.IsGeolocationSupportedAsync();

            Assert.Equal(isGeolocationSupported, result);

            _mapJsRuntimeMock.Verify(runtime => runtime.InvokeAsync <bool>(Constants.JsConstants.Methods.GeolocationControl.IsGeolocationSupported.ToGeolocationControlNamespace(), It.Is <object[]>(parameters => parameters.Length == 0)), Times.Once);
            _mapJsRuntimeMock.VerifyNoOtherCalls();
        }
        public ActionResult SearchByPlaceNameOrZip(string placeOrZip)
        {
            if (String.IsNullOrEmpty(placeOrZip))
            {
                return(null);
            }
            var location = GeolocationService.PlaceOrZipToLatLong(placeOrZip);

            var dinners = dinnerReadModel
                          .FindDinnerByLocation(location.Lat, location.Long)
                          .OrderByDescending(p => p.EventDate);

            return(View("Results", new PaginatedList <Dinner>(dinners, 0, 20)));
        }
Beispiel #13
0
        public ActionResult SearchByPlaceNameOrZip(string placeOrZip)
        {
            if (String.IsNullOrEmpty(placeOrZip))
            {
                return(null);
            }
            ;
            LatLong location = GeolocationService.PlaceOrZipToLatLong(placeOrZip);

            var dinners = dinnerRepository.
                          FindByLocation(location.Lat, location.Long).
                          OrderByDescending(p => p.EventDate);

            return(View("Results", dinners.ToPagedList(1, 20)));
        }
Beispiel #14
0
        public async Task <ActionResult> Index(RatingViewModel model)
        {
            try
            {
                // TODO: Add insert logic here
                GeolocationService service = new GeolocationService();
                GeocodeResult      result  = await service.Geocode(model.Address);

                return(View("GeocodingResult", result.Geometry.Location));
            }
            catch
            {
                return(View());
            }
        }
Beispiel #15
0
        public IEnumerable <JsonDinner> SearchByPlaceNameOrZip(string location)
        {
            if (String.IsNullOrEmpty(location))
            {
                return(null);
            }
            LatLong foundlocation = GeolocationService.PlaceOrZipToLatLong(location);

            if (foundlocation != null)
            {
                return(FindByLocation(foundlocation.Lat, foundlocation.Long).
                       OrderByDescending(p => p.EventDate));
            }
            return(null);
        }
        public IQueryable <Dinner> DinnersNearMe(string placeOrZip)
        {
            if (String.IsNullOrEmpty(placeOrZip))
            {
                return(null);
            }
            ;

            LatLong location = GeolocationService.PlaceOrZipToLatLong(placeOrZip);

            var dinners = dinnerRepository.
                          FindByLocation(location.Lat, location.Long).
                          OrderByDescending(p => p.EventDate);

            return(dinners);
        }
Beispiel #17
0
        public MainViewModel(IParkenDdClient client,
                             VoiceCommandService voiceCommandService,
                             JumpListService jumpList,
                             ParkingLotListFilterService filterService,
                             SettingsService settings,
                             StorageService storage,
                             GeolocationService geo,
                             TrackingService tracking,
                             ExceptionService exceptionService)
        {
            _client           = client;
            _voiceCommands    = voiceCommandService;
            _jumpList         = jumpList;
            _filterService    = filterService;
            _settings         = settings;
            _storage          = storage;
            _geo              = geo;
            _tracking         = tracking;
            _exceptionService = exceptionService;

            Messenger.Default.Register(this, (SettingChangedMessage msg) =>
            {
                if (msg.IsSetting(nameof(_settings.ShowExperimentalCities)))
                {
                    var temp      = SelectedCity;
                    _selectedCity = null;
                    RaisePropertyChanged(() => SelectedCity);
                    RaisePropertyChanged(() => MetaDataCities);
                    _selectedCity = temp;
                    RaisePropertyChanged(() => SelectedCity);
                }
            });

            PropertyChanged += (sender, args) =>
            {
                if (args.PropertyName == nameof(MetaDataCities))
                {
                    UpdateServiceData();
                }
            };

            NetworkInformation.NetworkStatusChanged += sender =>
            {
                UpdateInternetAvailability();
            };
            UpdateInternetAvailability();
        }
        async Task ExecuteRefreshCommand(bool forceRefresh)
        {
            if (IsBusy)
            {
                return;
            }

            if (!await CheckConnectivityAsync())
            {
                return;
            }

            IsBusy = true;

            try
            {
                Analytics.TrackEvent("SerchedForNearby");
                var position = await GeolocationService.GetCurrentPositionAsync();

                if (position == null)
                {
                    throw new Exception("Unable to get location.");
                }

                ContactsGrouped.Clear();
                var contacts = await DataService.GetNearbyAsync(position.Longitude, position.Latitude);

                if (contacts.Count() > 0)
                {
                    ContactsGrouped.AddRange(contacts);
                }
                else
                {
                    await Dialogs.AlertAsync(null, AppResources.NoCDAsNearby, AppResources.OK);
                }
            }
            catch (Exception ex)
            {
                Crashes.TrackError(ex);
                System.Diagnostics.Debug.WriteLine($"*** ERROR: {ex.Message}");
            }
            finally
            {
                IsBusy = false;
            }
        }
        private async Task <GeocodingResult> Getgeocoding()
        {
            if (!String.IsNullOrEmpty(FullAddressOfOpportunity))
            {
                try
                {
                    var geocodeOfAddress = await GeolocationService.GetGeolocationFromAddress(FullAddressOfOpportunity);

                    return(geocodeOfAddress);
                }
                catch
                {
                    ModelState.AddModelError("FullAddressOfOpportunity", "We could not find that address. Please check it and try again.");
                }
            }
            return(null);
        }
Beispiel #20
0
        public async void ShowCurrentPosition()
        {
            if (CurrentPositionMarker != null)
            {
                await CurrentPositionMarker.Remove();
            }
            CurrentPositionResult = await GeolocationService.GetCurrentPosition();

            if (CurrentPositionResult.IsSuccess)
            {
                CurrentPositionMarker = new Marker(
                    CurrentPositionResult.Position.ToLeafletLatLng(), null
                    );
                await CurrentPositionMarker.AddTo(PositionMap);
            }
            StateHasChanged();
        }
        public async Task GetAsync_GeolocationDoesNotExists_ThrowsException()
        {
            var ipAddress = "192.168.0.1";
            var geolocationRepositoryMock = new Mock <IGeolocationRepository>();

            geolocationRepositoryMock.Setup(x => x.GetAsync(It.IsAny <string>()))
            .ReturnsAsync(value: null);
            var ipDetailsServiceMock = new Mock <IIpDetailsService>();
            var networkAddressMock   = new Mock <INetworkAddress>();

            var geolocationService = new GeolocationService(geolocationRepositoryMock.Object, ipDetailsServiceMock.Object,
                                                            networkAddressMock.Object);

            var exception = await Assert.ThrowsAsync <ServiceException>(() =>
                                                                        geolocationService.GetAsync(ipAddress));

            exception.Code.Should().Be(HttpStatusCode.NotFound);
        }
        public async Task AddAsync_GeolocationAlreadyExists_ThrowsException()
        {
            var ipAddress = "192.168.0.1";
            var geolocationRepositoryMock = new Mock <IGeolocationRepository>();

            geolocationRepositoryMock.Setup(x => x.GetAsync(It.IsAny <string>()))
            .ReturnsAsync(new Domain.Geolocation());
            var ipDetailsServiceMock = new Mock <IIpDetailsService>();
            var networkAddressMock   = new Mock <INetworkAddress>();

            var geolocationService = new GeolocationService(geolocationRepositoryMock.Object, ipDetailsServiceMock.Object,
                                                            networkAddressMock.Object);

            var exception = await Assert.ThrowsAsync <ServiceException>(() =>
                                                                        geolocationService.AddAsync(ipAddress));

            exception.Code.Should().Be(HttpStatusCode.Conflict);
            geolocationRepositoryMock.Verify(x => x.AddAsync(It.IsAny <Domain.Geolocation>()), Times.Never);
            ipDetailsServiceMock.Verify(x => x.GetDetailsAboutAddress(It.IsAny <string>()), Times.Never);
        }
Beispiel #23
0
        public List <AccessLogDto> CreateBulk(List <AccessLogDto> list)
        {
            foreach (var item in list)
            {
                string geo = null;
                geo = _geoCache[item.Host];
                if (geo == null)
                {
                    _geoCache[item.Host] = GeolocationService.GetGeolocation(item.Host);
                }

                if (JsonValidator.IsValid(_geoCache[item.Host]))
                {
                    var country = JObject.Parse(_geoCache[item.Host])["country_name"].Value <string>();
                    item.Geolocation = string.IsNullOrEmpty(country) ? null : country;
                }
                else
                {
                    item.Geolocation = null;
                }
            }
            return(Mapper.Map <List <AccessLogDto> >(_accessLogRepository.CreateBulk(Mapper.Map <List <AccessLog> >(list))));
        }
Beispiel #24
0
        public void Test()
        {
            var result = GeolocationService.GetGeolocation("");

            Assert.AreEqual(ResultCode.RecordDoesNotExist, result.ResultCode);
            Assert.IsNull(result.Geolocation);

            result = GeolocationService.GetGeolocation("178.235.146.51");
            Assert.AreEqual(ResultCode.RecordDoesNotExist, result.ResultCode);
            Assert.IsNull(result.Geolocation);

            var resultCode = GeolocationService.AddGeolocation("178.235.146.51");

            Assert.AreEqual(ResultCode.OK, resultCode);

            result = GeolocationService.GetGeolocation("178.235.146.51");
            Assert.AreEqual(ResultCode.OK, result.ResultCode);
            Assert.IsNotNull(result.Geolocation);
            Assert.AreEqual("178.235.146.51", result.Geolocation.Ip);

            resultCode = GeolocationService.DeleteGeolocation("178.235.146.51");
            Assert.AreEqual(ResultCode.OK, resultCode);
        }
Beispiel #25
0
        public async void TogglePositionWatch()
        {
            if (isWatching)
            {
                await StopWatching();

                WatchHandlerId = null;
                foreach (var marker in WatchMarkers)
                {
                    await marker.Remove();
                }
                WatchMarkers.Clear();
                await WatchPath.Remove();

                WatchPath = null;
            }
            else
            {
                GeolocationService.WatchPositionReceived += HandleWatchPositionReceived;
                WatchHandlerId = await GeolocationService.WatchPosition();
            }
            StateHasChanged();
        }
        public async Task AddAsync_GeolocationDoesNotExists_ShouldBeCreated()
        {
            var ipAddress = "192.168.0.1";
            var geolocationRepositoryMock = new Mock <IGeolocationRepository>();

            geolocationRepositoryMock.Setup(x => x.GetAsync(It.IsAny <string>()))
            .ReturnsAsync(value: null);
            var ipDetailsServiceMock = new Mock <IIpDetailsService>();

            ipDetailsServiceMock.Setup(x => x.GetDetailsAboutAddress(It.IsAny <string>()))
            .ReturnsAsync(new Domain.Geolocation()
            {
                Ip = ipAddress
            });
            var networkAddressMock = new Mock <INetworkAddress>();

            var geolocationService = new GeolocationService(geolocationRepositoryMock.Object, ipDetailsServiceMock.Object,
                                                            networkAddressMock.Object);

            await geolocationService.AddAsync(ipAddress);

            geolocationRepositoryMock.Verify(x => x.AddAsync(It.IsAny <Domain.Geolocation>()), Times.Once);
            ipDetailsServiceMock.Verify(x => x.GetDetailsAboutAddress(It.IsAny <string>()), Times.Once);
        }
Beispiel #27
0
 public GeolocationController(GeolocationService geolocationService)
 {
     _geolocationService = geolocationService;
 }
 public FacadeService()
 {
     this.EnglishMetricConverter = new EnglishMetricConverter();
     this.WeatherService         = new WeatherService();
     this.GeolocationService     = new GeolocationService();
 }
Beispiel #29
0
 private async Task StopWatching()
 {
     GeolocationService.WatchPositionReceived -= HandleWatchPositionReceived;
     await GeolocationService.ClearWatch(WatchHandlerId.Value);
 }
Beispiel #30
0
        public async Task <IActionResult> WeatherForecasts([FromQuery] string address)
        {
            var location = await GeolocationService.GetCoordinates(address);

            return(new OkObjectResult(location));
        }