public override void OnStop() { base.OnStop(); GeolocationHelper.Current.LocationServiceConnected -= OnLocationServiceConnected; if (viewModel != null) { viewModel.PropertyChanged -= OnPropertyChanged; } if (trailPointList != null) { trailPointList.CollectionChanged -= OnTrailUpdated; } if (fab != null) { fab.Click -= OnRecordButtonClick; } //If we are recording then don't stop the background service if ((viewModel?.IsRecording).GetValueOrDefault()) { return; } GeolocationHelper.Current.LocationService.StopLocationUpdates(); GeolocationHelper.StopLocationService(); }
async Task StartLocationService() { try { var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location); if (status != PermissionStatus.Granted) { var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location); status = results[Permission.Location]; } if (status == PermissionStatus.Granted) { if ((viewModel == null || !viewModel.IsRecording) && !GeolocationHelper.Current.IsRunning) { await GeolocationHelper.StartLocationService(); } else { OnLocationServiceConnected(null, null); } } else if (status != PermissionStatus.Unknown) { Toast.MakeText(Activity, "Location permission is not granted, can't track location", ToastLength.Long); } } catch (Exception ex) { //23Logger.Instance.Report(ex); } }
protected void SetLanguage(bool checkIp = true) { if (Request.QueryString.Count == 0) { var ipGeolocationInfo = new GeolocationHelper("teamlabsite").GetIPGeolocationFromHttpContext(); if (checkIp && ipGeolocationInfo != null && !string.IsNullOrEmpty(ipGeolocationInfo.Key)) { var cultureInfo = SetupInfo.EnabledCultures.Find(c => String.Equals(c.TwoLetterISOLanguageName, ipGeolocationInfo.Key, StringComparison.InvariantCultureIgnoreCase)); if (cultureInfo != null) { Response.Redirect(Request.Path + "?lang=" + cultureInfo.TwoLetterISOLanguageName, true); } } } else { var lang = Request["lang"]; if (!string.IsNullOrEmpty(lang)) { var cultureInfo = SetupInfo.EnabledCultures.Find(c => String.Equals(c.TwoLetterISOLanguageName, lang, StringComparison.InvariantCultureIgnoreCase)); if (cultureInfo != null) { Thread.CurrentThread.CurrentUICulture = cultureInfo; } } } }
public static void ToLatLongTest(string latLong, double expectedLat, double expectedLong) { var obj = GeolocationHelper.ToLatLong(latLong); Assert.Equal(expectedLat, obj.Latitude); Assert.Equal(expectedLong, obj.Longitude); }
private void Watcher_OnStatusChanged(object sender, GeoPositionStatusChangedEventArgs args) { if (args.Status != GeoPositionStatus.Ready) { return; } this.SetProgressIndicator(false); GeolocationHelper.HandleDisabledLocationSettings(); }
protected void Page_Load(object sender, EventArgs e) { if (SecurityContext.IsAuthenticated && User.ID != SecurityContext.CurrentAccount.ID) { Response.Redirect(GetRefererURL()); return; } if (!CoreContext.Configuration.YourDocs) { _communitations.Controls.Add(LoadControl(AuthCommunications.Location)); } AjaxPro.Utility.RegisterTypeForAjax(GetType()); Page.RegisterBodyScripts(ResolveUrl("~/usercontrols/Management/SmsControls/js/confirmmobile.js")); Page.RegisterStyleControl(VirtualPathUtility.ToAbsolute("~/usercontrols/management/SmsControls/css/confirmmobile.less")); Context.Session["SmsAuthData"] = User.ID; if (string.IsNullOrEmpty(User.MobilePhone)) { Activation = true; } if (!Activation) { try { SmsManager.PutAuthCode(User, false); } catch (Exception) { Activation = true; } } if (Activation) { var ipGeolocationInfo = new GeolocationHelper("db").GetIPGeolocationFromHttpContext(); if (ipGeolocationInfo != null) { Country = ipGeolocationInfo.Key; } var clientScriptReference = new ClientScriptReference(); clientScriptReference.Includes.Add(typeof(CountriesResources)); Page.RegisterBodyScripts(clientScriptReference); Page.RegisterBodyScripts(ResolveUrl("~/js/asc/plugins/countries.js")); Page.RegisterBodyScripts(ResolveUrl("~/js/asc/plugins/phonecontroller.js")); Page.RegisterStyleControl(VirtualPathUtility.ToAbsolute("~/skins/default/phonecontroller.css")); } }
public ShelterCardModel(Data.Entities.Models.Shelter shelter, Geolocation userGeolocation) { Id = shelter.Id; Name = shelter.Name; WebsiteUrl = shelter.WebsiteUrl; City = shelter.City; Address = shelter.Address; ContactPhone = shelter.ContactPhone; ContactEmail = shelter.ContactEmail; DistanceFromUser = GeolocationHelper.GetDistance(shelter.Geolocation, userGeolocation); }
protected void Page_Load(object sender, EventArgs e) { if (SecurityContext.IsAuthenticated && User.ID != SecurityContext.CurrentAccount.ID) { Response.Redirect(GetRefererURL()); return; } var authCommunications = (AuthCommunications)LoadControl(AuthCommunications.Location); authCommunications.DisableJoin = true; _communitations.Controls.Add(authCommunications); AjaxPro.Utility.RegisterTypeForAjax(GetType()); Page.RegisterBodyScripts("~/usercontrols/Management/SmsControls/js/confirmmobile.js") .RegisterStyle("~/usercontrols/management/SmsControls/css/confirmmobile.less"); Context.Session["SmsAuthData"] = User.ID; if (string.IsNullOrEmpty(User.MobilePhone)) { Activation = true; } if (!Activation) { try { SmsManager.PutAuthCode(User, false); } catch (Exception) { Activation = true; } } if (Activation) { var ipGeolocationInfo = new GeolocationHelper("teamlabsite").GetIPGeolocationFromHttpContext(); if (ipGeolocationInfo != null) { Country = ipGeolocationInfo.Key; } Page .RegisterClientScript(new CountriesResources()) .RegisterBodyScripts( "~/js/asc/plugins/countries.js", "~/js/asc/plugins/phonecontroller.js") .RegisterStyle("~/skins/default/phonecontroller.css"); } }
protected void SetLanguage(bool checkIp = true) { if (Request.QueryString.Count == 0) { var ipGeolocationInfo = new GeolocationHelper("teamlabsite").GetIPGeolocationFromHttpContext(); if (checkIp && ipGeolocationInfo != null && !string.IsNullOrEmpty(ipGeolocationInfo.Key)) { var culture = SetupInfo.GetPersonalCulture(ipGeolocationInfo.Key); if (culture.Value != null) { var redirectUrl = String.Format("/{0}/{1}", culture.Key, Request.Path); if (redirectUrl.EndsWith("Auth.aspx", StringComparison.InvariantCultureIgnoreCase)) { redirectUrl = redirectUrl.Remove(redirectUrl.IndexOf("Auth.aspx", StringComparison.OrdinalIgnoreCase)); } Response.Redirect(redirectUrl, true); } } } else if (!String.IsNullOrEmpty(Request["lang"])) { var lang = Request["lang"].Split(',')[0]; var cultureInfo = SetupInfo.GetPersonalCulture(lang).Value; if (cultureInfo != null) { Thread.CurrentThread.CurrentUICulture = cultureInfo; Thread.CurrentThread.CurrentCulture = cultureInfo; } else { Log.WarnFormat("Lang {0} not supported", lang); } } else if (!String.IsNullOrEmpty(Request["email"])) { var user = CoreContext.UserManager.GetUserByEmail(Request["email"]); if (user.ID.Equals(Constants.LostUser.ID)) { return; } if (user.CultureName != null) { Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(user.CultureName); Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(user.CultureName); } } }
public void distanceBetweenNewyorkAndNewyorkShouldBe0() { var newyorkCoord = new Coordinate() { Latitude = _newYork.Lat, Longitude = _newYork.Long }; var result = GeolocationHelper.GetDistance(newyorkCoord, newyorkCoord); var expected = 0; Assert.Equal(expected, result); }
/// <summary> /// 签到 /// </summary> /// <param name="rows"></param> /// <param name="page"></param> /// <param name="longitude"></param> /// <param name="latitude"></param> /// <param name="websiteOwner"></param> /// <param name="total"></param> /// <returns></returns> public bool AddSignInLog(int autoId, string userId, double longitude, double latitude, string websiteOwner, out string errmsg) { errmsg = ""; StringBuilder sbSql = new StringBuilder(); sbSql.AppendFormat(" AutoID={0} and IsDelete=0 ", autoId); if (!string.IsNullOrWhiteSpace(websiteOwner)) { sbSql.AppendFormat(" and WebsiteOwner='{0}' ", websiteOwner); } SignInAddress signInAddress = Get <SignInAddress>(sbSql.ToString()); if (signInAddress == null) { errmsg = "签到地点未找到"; return(false); } signInAddress.Distance = GeolocationHelper.ComputeDistance(longitude, latitude , Convert.ToDouble(signInAddress.Longitude), Convert.ToDouble(signInAddress.Latitude)); SignInLog signInLog = new SignInLog(); signInLog.UserID = userId; signInLog.WebsiteOwner = websiteOwner; signInLog.IP = ZentCloud.Common.MySpider.GetClientIP(); signInLog.CreateDate = DateTime.Now; signInLog.Longitude = longitude.ToString(); signInLog.Latitude = latitude.ToString(); signInLog.AddressId = signInAddress.AutoID; signInLog.Address = signInAddress.Address; signInLog.Distance = signInAddress.Distance; string DistanceString = string.Empty; if (signInAddress.Distance > signInAddress.Range) { signInLog.Status = 0; signInLog.Remark = "签到失败,超出有效距离"; } else { signInLog.Status = 1; signInLog.Remark = "签到成功"; } if (!Add(signInLog)) { errmsg = "签到出错"; return(false); } errmsg = signInLog.Remark; return(signInLog.Status == 1); }
protected override async void OnAppearing() { base.OnAppearing(); //if (String.IsNullOrEmpty(Preferences.Get("Latitude", "")) && String.IsNullOrEmpty(Preferences.Get("Longitude", ""))) //{ // //} await GeolocationHelper.GetGeolocationInfo(viewModel.geoModel); await viewModel.LoadActualAndDailyWeatherInfoForSevenDays(); timer = new PollingTimerHelper(TimeSpan.FromMinutes(1), async() => { await GeolocationHelper.GetGeolocationInfo(viewModel.geoModel); await viewModel.LoadActualAndDailyWeatherInfoForSevenDays(); }); timer.Start(); }
private void Map_OnLoaded(object sender, RoutedEventArgs e) { MapsSettings.ApplicationContext.ApplicationId = ("55677f7c-3dab-4a57-95b2-4efd44a0e692"); MapsSettings.ApplicationContext.AuthenticationToken = ("1jh4FPILRSo9J1ADKx2CgA"); MapLayer mapLayer = new MapLayer(); MapOverlay mapOverlayPushpin = this._mapOverlayPushpin; ((Collection <MapOverlay>)mapLayer).Add(mapOverlayPushpin); this.Map.Layers.Add(mapLayer); if (this.ViewModel.GeoCoordinate != null) { this.SetPushpin(this.ViewModel.GeoCoordinate, true); } else { if (!this._canGetPlacement) { return; } try { GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(); watcher.PositionChanged += ((EventHandler <GeoPositionChangedEventArgs <GeoCoordinate> >)((o, args) => { if (!(this.ViewModel.GeoCoordinate == null)) { return; } PageBase.SetInProgress(false); this.SetPushpin(args.Position.Location, true); watcher.Stop(); })); watcher.StatusChanged += ((EventHandler <GeoPositionStatusChangedEventArgs>)((o, args) => { if (args.Status != GeoPositionStatus.Ready) { return; } GeolocationHelper.HandleDisabledLocationSettings(); })); watcher.Start(); PageBase.SetInProgress(true); } catch { } } }
private RegionInfo FindRegionInfo() { RegionInfo regionInfo = null; var owner = CoreContext.UserManager.GetUsers(CurrentOwnerId); if (!string.IsNullOrEmpty(owner.MobilePhone)) { try { var phoneUtil = PhoneNumberUtil.GetInstance(); var number = phoneUtil.Parse("+" + owner.MobilePhone.TrimStart('+'), "en-US"); var regionCode = phoneUtil.GetRegionCodeForNumber(number); if (!string.IsNullOrEmpty(regionCode)) { try { regionInfo = new RegionInfo(regionCode); } catch { } } } catch (Exception err) { LogManager.GetLogger("ASC.Web.Tariff").WarnFormat("Can not find country by phone {0}: {1}", owner.MobilePhone, err); } } if (regionInfo == null) { var geoinfo = new GeolocationHelper("teamlabsite").GetIPGeolocationFromHttpContext(); if (!string.IsNullOrEmpty(geoinfo.Key)) { try { regionInfo = new RegionInfo(geoinfo.Key); } catch (Exception) { } } } return(regionInfo); }
public void distanceBetweenMontrealAndNewyorkShouldBe535km() { var montrealCoord = new Coordinate() { Latitude = _montreal.Lat, Longitude = _montreal.Long }; var newyorkCoord = new Coordinate() { Latitude = _newYork.Lat, Longitude = _newYork.Long }; var result = GeolocationHelper.GetDistance(montrealCoord, newyorkCoord); var expected = 534209.131234364; Assert.Equal(expected, result); }
public void GetIPGeolocationTest() { var helper = new GeolocationHelper("db"); var info = helper.GetIPGeolocation("62.213.10.13"); Assert.AreEqual("Nizhny Novgorod", info.City); Assert.AreEqual("062.213.011.127", info.IPEnd); Assert.AreEqual("062.213.008.240", info.IPStart); Assert.AreEqual("RU", info.Key); Assert.AreEqual("Europe/Moscow", info.TimezoneName); Assert.AreEqual(4d, info.TimezoneOffset); info = helper.GetIPGeolocation(""); Assert.AreEqual(IPGeolocationInfo.Default.City, info.City); Assert.AreEqual(IPGeolocationInfo.Default.IPEnd, info.IPEnd); Assert.AreEqual(IPGeolocationInfo.Default.IPStart, info.IPStart); Assert.AreEqual(IPGeolocationInfo.Default.Key, info.Key); Assert.AreEqual(IPGeolocationInfo.Default.TimezoneName, info.TimezoneName); Assert.AreEqual(IPGeolocationInfo.Default.TimezoneOffset, info.TimezoneOffset); }
/// <summary> /// Calculate the score of a city based on the searched coordinates. /// </summary> /// <param name="city">City</param> /// <param name="latitude">Latitude</param> /// <param name="longitude">Longitude</param> /// <returns>City score based on the searched coordinates</returns> private double GetCoordinateScore(City city, double latitude, double longitude) { var firstLocation = new Coordinate() { Latitude = city.Lat, Longitude = city.Long }; var secondLocation = new Coordinate() { Latitude = latitude, Longitude = longitude }; var distance = GeolocationHelper.GetDistance(firstLocation, secondLocation); var farthestDistance = 1500000; return(distance < farthestDistance ? (farthestDistance - distance) / farthestDistance : 0); }
public void RecalculateDistanceToPlayer() { DistanceToPlayer = GeolocationHelper.DistanceBetweenPlaces(latitude, longitude, ViewPointManager.Instance.Geolocation.latitude, ViewPointManager.Instance.Geolocation.longitude); DistanceRecalculated(this, EventArgs.Empty); }
public DawnDuskController(GeolocationHelper geoLocationHelper) { _geolocationHelper = geoLocationHelper; }
protected void Page_Load(object sender, EventArgs e) { if (SecurityContext.IsAuthenticated && User.ID != SecurityContext.CurrentAccount.ID) { Response.Redirect(Context.GetRefererURL(), true); return; } if (!Activation && (!StudioSmsNotificationSettings.IsVisibleAndAvailableSettings || !StudioSmsNotificationSettings.Enable)) { Response.Redirect(Context.GetRefererURL(), true); return; } if (IsPostBack && !Activation) { try { SmsManager.ValidateSmsCode(User, Request["phoneAuthcode"]); Response.Redirect(Context.GetRefererURL(), true); } catch { MessageService.Send(HttpContext.Current.Request, User.DisplayUserName(false), MessageAction.LoginFailViaSms, MessageTarget.Create(User.ID)); } } var authCommunications = (AuthCommunications)LoadControl(AuthCommunications.Location); authCommunications.DisableJoin = true; _communitations.Controls.Add(authCommunications); AjaxPro.Utility.RegisterTypeForAjax(GetType()); Page.RegisterBodyScripts("~/UserControls/Management/SmsControls/js/confirmmobile.js") .RegisterStyle("~/UserControls/Management/SmsControls/css/confirmmobile.less"); if (string.IsNullOrEmpty(User.MobilePhone)) { Activation = true; } if (!Activation) { try { SmsManager.PutAuthCode(User, false); } catch (Exception) { Activation = true; } } if (Activation) { Country = new RegionInfo(Thread.CurrentThread.CurrentCulture.LCID).TwoLetterISORegionName; if (!CoreContext.Configuration.Standalone) { var ipGeolocationInfo = new GeolocationHelper("teamlabsite").GetIPGeolocationFromHttpContext(); if (ipGeolocationInfo != null && !string.IsNullOrEmpty(ipGeolocationInfo.Key)) { Country = ipGeolocationInfo.Key; } } Page .RegisterClientScript(new CountriesResources()) .RegisterBodyScripts( "~/js/asc/plugins/countries.js", "~/js/asc/plugins/phonecontroller.js") .RegisterStyle("~/skins/default/phonecontroller.css"); } }
protected override void HandleOnNavigatedTo(NavigationEventArgs e) { base.HandleOnNavigatedTo(e); if (this._isInitialized) { return; } PlacementSelectionViewModel viewModel = new PlacementSelectionViewModel(long.Parse(((Page)this).NavigationContext.QueryString["CommunityId"]), (Place)ParametersRepository.GetParameterForIdAndReset("PlacementSelectionPlace")); base.DataContext = viewModel; ApplicationBarIconButton applicationBarIconButton1 = new ApplicationBarIconButton(); Uri uri1 = new Uri("/Resources/check.png", UriKind.Relative); applicationBarIconButton1.IconUri = uri1; string appBarMenuSave = CommonResources.AppBarMenu_Save; applicationBarIconButton1.Text = appBarMenuSave; int num = this.ViewModel.GeoCoordinate != null ? 1 : 0; applicationBarIconButton1.IsEnabled = (num != 0); ApplicationBarIconButton appBarButtonSave = applicationBarIconButton1; ApplicationBarIconButton applicationBarIconButton2 = new ApplicationBarIconButton(); Uri uri2 = new Uri("/Resources/appbar.cancel.rest.png", UriKind.Relative); applicationBarIconButton2.IconUri = uri2; string appBarCancel = CommonResources.AppBar_Cancel; applicationBarIconButton2.Text = appBarCancel; ApplicationBarIconButton applicationBarIconButton3 = applicationBarIconButton2; appBarButtonSave.Click += ((EventHandler)((p, f) => { ((Control)this).Focus(); viewModel.SaveChanges(); })); applicationBarIconButton3.Click += ((EventHandler)((p, f) => Navigator.Current.GoBack())); this.ApplicationBar = ((IApplicationBar)ApplicationBarBuilder.Build(new Color?(), new Color?(), 0.9)); viewModel.PropertyChanged += (PropertyChangedEventHandler)((p, f) => appBarButtonSave.IsEnabled = (viewModel.IsFormEnabled && viewModel.GeoCoordinate != null)); this.ApplicationBar.Buttons.Add(appBarButtonSave); this.ApplicationBar.Buttons.Add(applicationBarIconButton3); try { if (!AppGlobalStateManager.Current.GlobalState.AllowUseLocationQuestionAsked || !AppGlobalStateManager.Current.GlobalState.AllowUseLocation) { bool flag = MessageBox.Show(CommonResources.MapAttachment_AllowUseLocation, CommonResources.AccessToLocation, (MessageBoxButton)1) == MessageBoxResult.OK; AppGlobalStateManager.Current.GlobalState.AllowUseLocationQuestionAsked = true; AppGlobalStateManager.Current.GlobalState.AllowUseLocation = flag; } if (!AppGlobalStateManager.Current.GlobalState.AllowUseLocation) { this._canGetPlacement = false; } } catch (Exception ex) { if (ex.HResult == -2147467260) { GeolocationHelper.HandleDisabledLocationSettings(); this._canGetPlacement = false; } } this._isInitialized = true; }
public static void IsValidTest(string latLong, bool expected) { Assert.Equal(expected, GeolocationHelper.IsValid(latLong)); }
public GeolocationController(GeolocationHelper geoLocationHelper) { _geolocationHelper = geoLocationHelper; }
public async Task Load48HoursWeatherInfo() { if (IsBusy) { return; } IsBusy = true; try { await GeolocationHelper.GetGeolocationInfo(geoModel); var result = await HttpConnection.Get48HoursWeatherInfoAsync(geoModel.Lat, geoModel.Lon, "apiKey"); if (result.Hourly != null) { foreach (var item in result.Hourly) { Hourly48ForecastList.Add(new Forecast48HoursModel { Dt = DateAndTimeHelper.ConvertToDateAndTime(item.Dt, DateAndTimeHelper.TypeForDateAndTimeFormat.TIME), DateAndTime = DateAndTimeHelper.ConvertToDateAndTime(item.Dt, DateAndTimeHelper.TypeForDateAndTimeFormat.DATE_AND_TIME_FOR_48FORECAST), Temp = Math.Round(item.Temp.Value, 1).ToString(), Icon = HttpConnection.GetIconForWeather(item.Weather.First().Icon), WindDeg = WindHelper.DegreesToGeogrpahicalDirections(item.WindDeg.Value), GroupName = DateAndTimeHelper.ConvertToDateAndTime(item.Dt, DateAndTimeHelper.TypeForDateAndTimeFormat.COMMON_DATETIME), ColorOfTemperatureLabel = item.Weather.First().Icon.Contains("n")?"#000000": "#008000", Humidity = item.Humidity, WindSpeed = WindHelper.MpsToKmph(item.WindSpeed.Value), Rain = string.IsNullOrEmpty(item.Rain) ? "0" : item.Rain, Clouds = item.Clouds, Pressure = item.Pressure, Description = item.Weather.First().Description, FeelsTemp = Math.Round(item.FeelsLike.Value, 1).ToString() }); } List <string> groupNamesList = new List <string>(); foreach (var item in Hourly48ForecastList) { groupNamesList.Add(item.GroupName); } var distinctGroupNamesList = groupNamesList.Distinct().ToList(); foreach (var item in distinctGroupNamesList) { GroupedHourly48ForecastList.Add(new GroupingForListClass <string, Forecast48HoursModel>(item, Hourly48ForecastList.Where(x => x.GroupName == item))); } } else { await App.Current.MainPage.DisplayAlert("Błąd", "Coś poszło nie tak.", "OK"); } } catch (Exception ex) { await App.Current.MainPage.DisplayAlert("Błąd", "Coś poszło nie tak.", "OK"); } finally { IsBusy = false; } }
protected override void HandleOnNavigatedTo(NavigationEventArgs e) { try { base.HandleOnNavigatedTo(e); if (!this._isInitialized) { base.DataContext = (new ViewModelBase()); this._shouldPick = ((Page)this).NavigationContext.QueryString.ContainsKey("Pick") && ((Page)this).NavigationContext.QueryString["Pick"] == true.ToString(); if (!this._shouldPick) { this.MoveMapToPosition(new GeoCoordinate(double.Parse(((Page)this).NavigationContext.QueryString["latitude"], (IFormatProvider)CultureInfo.InvariantCulture), double.Parse(((Page)this).NavigationContext.QueryString["longitude"], (IFormatProvider)CultureInfo.InvariantCulture))); return; } if (!AppGlobalStateManager.Current.GlobalState.AllowUseLocationQuestionAsked || !AppGlobalStateManager.Current.GlobalState.AllowUseLocation) { bool flag = MessageBox.Show(CommonResources.MapAttachment_AllowUseLocation, CommonResources.AccessToLocation, (MessageBoxButton)1) == MessageBoxResult.OK; AppGlobalStateManager.Current.GlobalState.AllowUseLocationQuestionAsked = true; AppGlobalStateManager.Current.GlobalState.AllowUseLocation = flag; } this.InitializeAppBar(); this._isInitialized = true; } if (!(this._lastPosition == null)) { return; } if (!AppGlobalStateManager.Current.GlobalState.AllowUseLocation) { return; } try { if (this._watcher != null) { this._watcher.PositionChanged -= new EventHandler <GeoPositionChangedEventArgs <GeoCoordinate> >(this.Watcher_OnPositionChanged); this._watcher.StatusChanged -= new EventHandler <GeoPositionStatusChangedEventArgs>(this.Watcher_OnStatusChanged); } this._watcher = new GeoCoordinateWatcher(); this._watcher.PositionChanged += new EventHandler <GeoPositionChangedEventArgs <GeoCoordinate> >(this.Watcher_OnPositionChanged); this._watcher.StatusChanged += new EventHandler <GeoPositionStatusChangedEventArgs>(this.Watcher_OnStatusChanged); GeoCoordinateWatcher watcher = this._watcher; if (watcher != null) { // ISSUE: explicit non-virtual call watcher.Start(); } this.SetProgressIndicator(true); } catch (Exception ex) { this.SetProgressIndicator(false); if (ex.HResult != -2147467260) { return; } GeolocationHelper.HandleDisabledLocationSettings(); } } catch (Exception ex) { Logger.Instance.ErrorAndSaveToIso("Failed to OnNavigatedTo MapAttachmentPage", ex); } }
/// <summary> /// The main entry point for the application. /// </summary> /// <param name="args">The Command Line Arguments.</param> public static void Main(string[] args) { // not keen on the format of --help so let's do our own here if (args == null || args.Length == 0) { ConsoleHelper.WriteHeader(); ConsoleHelper.WriteHelp(); ConsoleHelper.WriteDebugExit(); return; } var parser = new Parser(); // get the command line parser results var results = parser.ParseArguments <Options>(args); // execute program functionality and return an exit code var exitCode = 1; results.WithParsed( options => { try { if (!string.IsNullOrWhiteSpace(options.LatLong)) { // we have been given a set option if (!GeolocationHelper.IsValid(options.LatLong)) { ErrorHelper.InvalidArguments("Invalid LatLong"); } // set the value to the registry var latLong = GeolocationHelper.ToLatLong(options.LatLong); RegistryHelper.SetLatLong(latLong); Console.WriteLine("The following location has been set in the driver's registry settings:"); ConsoleHelper.WriteLatLong(latLong); } if (options.Get) { // get the value from the location API var latLong = GeolocationHelper.Get(); Console.WriteLine("The following location has been returned from the Windows location API:"); ConsoleHelper.WriteLatLong(latLong); } } catch (Exception ex) { ConsoleHelper.WriteError(ex.Message); // if the debugger is attached, break. if (Debugger.IsAttached) { Debugger.Break(); } exitCode = 1; } exitCode = 0; }); Environment.Exit(exitCode); ConsoleHelper.WriteDebugExit(); }
protected void SetLanguage(bool checkIp = true, bool abTesting = false) { var abTestingQuery = string.Empty; if (abTesting) { abTesting = AbTestingQuery(out abTestingQuery); } if (Request.QueryString.Count == 0) { var ipGeolocationInfo = new GeolocationHelper("teamlabsite").GetIPGeolocationFromHttpContext(); if (checkIp && ipGeolocationInfo != null && !string.IsNullOrEmpty(ipGeolocationInfo.Key)) { var cultureInfo = SetupInfo.EnabledCulturesPersonal.Find(c => String.Equals(c.TwoLetterISOLanguageName, ipGeolocationInfo.Key, StringComparison.InvariantCultureIgnoreCase)); if (cultureInfo != null) { var redirectUrl = String.Format("/{0}/{1}", cultureInfo.TwoLetterISOLanguageName, Request.Path); if (redirectUrl.EndsWith("auth.aspx", StringComparison.InvariantCulture)) { redirectUrl = redirectUrl.Remove(redirectUrl.IndexOf("auth.aspx", StringComparison.Ordinal)); } if (abTesting) { redirectUrl += (redirectUrl.Contains("?") ? "&" : "?") + abTestingQuery; } Response.Redirect(redirectUrl, true); } } } else { var lang = Request["lang"]; if (!string.IsNullOrEmpty(lang)) { lang = lang.Split(',')[0]; var cultureInfo = SetupInfo.EnabledCulturesPersonal.Find(c => String.Equals(c.TwoLetterISOLanguageName, lang, StringComparison.InvariantCultureIgnoreCase)); if (cultureInfo != null) { Thread.CurrentThread.CurrentUICulture = cultureInfo; } else { Log.WarnFormat("Lang {0} not supported", lang); } } } if (abTesting) { var redirectUrl = Request.Path; redirectUrl += (redirectUrl.Contains("?") ? "&" : "?") + abTestingQuery; Response.Redirect(redirectUrl, true); } }
public object GetIPInformation(string ipAddress) { GeolocationHelper helper = new GeolocationHelper("teamlabsite"); return(helper.GetIPGeolocation(ipAddress)); }
/// <summary> /// 智能签到 /// </summary> /// <param name="rows"></param> /// <param name="page"></param> /// <param name="longitude"></param> /// <param name="latitude"></param> /// <param name="websiteOwner"></param> /// <param name="total"></param> /// <returns></returns> public bool AddSignInLogAuto(string userId, double longitude, double latitude, string websiteOwner, out string errmsg) { errmsg = ""; StringBuilder sbSql = new StringBuilder(); sbSql.AppendFormat(" 1=1 "); if (!string.IsNullOrWhiteSpace(websiteOwner)) { sbSql.AppendFormat(" and WebsiteOwner='{0}' ", websiteOwner); } List <SignInAddress> list = GetList <SignInAddress>(sbSql.ToString()); if (list.Count == 0) { errmsg = "请设置签到地点"; return(false); } for (int i = 0; i < list.Count; i++) { list[i].Distance = GeolocationHelper.ComputeDistance(longitude, latitude , Convert.ToDouble(list[i].Longitude), Convert.ToDouble(list[i].Latitude)); } List <SignInAddress> tempList = list.Where(p => p.Distance <= p.Range).ToList(); SignInLog signInLog = new SignInLog(); SignInAddress nearestAddress = new SignInAddress(); signInLog.UserID = userId; signInLog.WebsiteOwner = websiteOwner; signInLog.IP = ZentCloud.Common.MySpider.GetClientIP(); signInLog.CreateDate = DateTime.Now; signInLog.Longitude = longitude.ToString(); signInLog.Latitude = latitude.ToString(); string distanceString = string.Empty; if (tempList.Count > 0) { nearestAddress = tempList.OrderBy(p => p.Distance).FirstOrDefault(); signInLog.AddressId = nearestAddress.AutoID; signInLog.Address = nearestAddress.Address; signInLog.Distance = nearestAddress.Distance; signInLog.Status = 1; distanceString = nearestAddress.Distance > 1000 ? (nearestAddress.Distance / 1000).ToString("f2") + "千米" : nearestAddress.Distance.ToString("f2") + "米"; signInLog.Remark = "签到成功,距离[" + nearestAddress.Address + "]" + distanceString; } else { nearestAddress = list.OrderBy(p => p.Distance).FirstOrDefault(); signInLog.AddressId = nearestAddress.AutoID; signInLog.Address = nearestAddress.Address; signInLog.Distance = nearestAddress.Distance; signInLog.Status = 0; distanceString = nearestAddress.Distance > 1000 ? (nearestAddress.Distance / 1000).ToString("f2") + "千米" : nearestAddress.Distance.ToString("f2") + "米"; double moreDistance = signInLog.Distance - nearestAddress.Range; string moreDistanceString = string.Empty; moreDistanceString = moreDistance > 1000 ? (moreDistance / 1000).ToString("f2") + "千米" : moreDistance.ToString("f2") + "米"; signInLog.Remark = "签到失败,距离最近签到地址[" + nearestAddress.Address + "]" + distanceString + ",超出有效距离" + moreDistanceString; } if (!Add(signInLog)) { errmsg = "签到出错"; return(false); } errmsg = signInLog.Remark; return(signInLog.Status == 1); }