Esempio n. 1
0
        public string GetLatLongFromAddress(GoogleAddress address)
        {
            if (address.FormattedAddress == null)
            {
                return "<coordinate>\n" +
                          "<lat>unknown</lat>\n" +
                          "<lon>unknown</lon>\n" +
                       "</coordinate>";
            }

            XDocument doc = XDocument.Load(String.Format(ApiGeoCode, address.FormattedAddress.Replace(" ", "+")));

            var result = doc.Descendants("result").Descendants("geometry").Descendants("location").FirstOrDefault();
            if (result == null)
            {
                return "<coordinate>\n" +
                          "<lat>unknown</lat>\n" +
                          "<lon>unknown</lon>\n" +
                       "</coordinate>";
            }
            XElement lat = result.Descendants("lat").FirstOrDefault();
            XElement lon = result.Descendants("lng").FirstOrDefault();
            return "<coordinate>\n" +
                      "<lat>" + (lat != null ? lat.Value : "unknown") + "</lat>\n" +
                      "<lon>" + (lon != null ? lon.Value : "unknown") + "</lon>\n" +
                   "</coordinate>";
        }
Esempio n. 2
0
        public static string GetAddress(double Lat, double Lon)
        {
            string sURL;

            sURL  = "http://maps.googleapis.com/maps/api/geocode/json?latlng=";
            sURL += Lat.ToString().Replace(',', '.') + "," + Lon.ToString().Replace(',', '.');
            sURL += "&sensor=false";

            WebRequest wrGETURL;

            wrGETURL = WebRequest.Create(sURL);

            Stream objStream;

            objStream = wrGETURL.GetResponse().GetResponseStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(GoogleAddress));

            StreamReader  objReader = new StreamReader(objStream);
            GoogleAddress data      = (GoogleAddress)ser.ReadObject(objStream);

            if (data.results == null || data.results.Count == 0)
            {
                return(null);
            }

            return(data.results[0].formatted_address);
        }
Esempio n. 3
0
        /// <summary>
        /// Determines whether the specified value is valid.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>
        ///     <c>true</c> if the specified value is valid; otherwise, <c>false</c>.
        /// </returns>
        public override bool IsValid(object value)
        {
            var address = GetPropertyValue(value, AddressPropertyName);

            if (address.IsNullOrEmpty())
            {
                return(AllowNull);
            }

            var geocoder = new GoogleGeoCoder(); // key not needed
            var result   = geocoder.GeoCode(address.Trim()).FirstOrDefault();

            if (result == null)
            {
                // No results
                return(false);
            }
            _result = result;                                                             // store so that other classes that inherit from this attribute can access the result without re-geocoding
            SetPropertyValue(value, result.Coordinates.Latitude, LatitudePropertyName);   // set latitude
            SetPropertyValue(value, result.Coordinates.Longitude, LongitudePropertyName); // set longitude

            var fullAddress = result.FormattedAddress;                                    // (result.Street.HasValue() && result.Street.Trim().HasValue() ? result.Street + ", " : "") + result.City + " " + result.State + ", " + result.Country + " " + result.PostalCode;

            SetPropertyValue(value, fullAddress, AddressPropertyName);                    // set exact address

            return(true);
        }
Esempio n. 4
0
        // Geocodes an address using the Bing Maps engine
        public static Location SearchGoogle(string add)
        {
            try
            {
                // Calls the webservice
                GoogleGeocoder geocoder = new GoogleGeocoder()
                {
                    ApiKey = ConfigurationManager.AppSettings["GoogleApiKey"]
                };
                IEnumerable <Address> addresses = geocoder.Geocode(add);

                // Selects the firt result
                GoogleAddress g = (GoogleAddress)addresses.FirstOrDefault();

                Location r = new Location();

                r.Lat     = addresses.FirstOrDefault().Coordinates.Latitude;
                r.Lon     = addresses.FirstOrDefault().Coordinates.Longitude;
                r.Quality = g.LocationType.ToString();
                r.Address = addresses.FirstOrDefault().FormattedAddress;

                return(r);
            }
            catch (Exception Ex)
            {
                throw new Exception(Ex.Message);
            }
        }
Esempio n. 5
0
        private static async Task AddOrUpdateLocation(int id, GoogleAddress address)
        {
            using (var telegramContext = new TelegramContext())
            {
                await telegramContext.Database.EnsureCreatedAsync();

                var locationProfile = await telegramContext.UserLocations.FindAsync(id);

                if (locationProfile != null)
                {
                    locationProfile.Latitude         = address.Coordinates.Latitude;
                    locationProfile.Longitude        = address.Coordinates.Longitude;
                    locationProfile.FormattedAddress = address.FormattedAddress;
                    locationProfile.IsAmerica        = address.IsAmerica();
                }
                else
                {
                    await telegramContext.UserLocations.AddAsync(
                        new UserLocation
                    {
                        Id               = id,
                        Latitude         = address.Coordinates.Latitude,
                        Longitude        = address.Coordinates.Longitude,
                        FormattedAddress = address.FormattedAddress,
                        IsAmerica        = address.IsAmerica()
                    }
                        );
                }

                await telegramContext.SaveChangesAsync();
            }
        }
Esempio n. 6
0
        public Task <(string Address, string Flag)> GetShortLocationAsync(GoogleAddress geocode)
        {
            var country = geocode.Components.FirstOrDefault(
                x => x.Types.Any(y => y == GoogleAddressType.Country || y == GoogleAddressType.Establishment));
            var addressTypes = geocode.Components.ToDictionary(x => x.Types.FirstOrDefault(), y => y)
                               .OrderBy(x => x.Key);
            var state = addressTypes.FirstOrDefault(x => (x.Key >= GoogleAddressType.AdministrativeAreaLevel1) &
                                                    (x.Key <= GoogleAddressType.AdministrativeAreaLevel3)).Value;
            var city = addressTypes.FirstOrDefault(x => (x.Key == GoogleAddressType.Locality) |
                                                   (x.Key == GoogleAddressType.ColloquialArea)).Value;
            var    sb          = new StringBuilder();
            string countryFlag = null;

            try
            {
                countryFlag = EmojiExtensions.FromText($":flag_{country.ShortName.ToLower()}:").Name;
            }
            catch
            {
                // ignored
            }
            if (city != null)
            {
                sb.Append($"{city.LongName}, ");
            }
            if (state != null)
            {
                sb.Append($"{state.LongName}, ");
            }
            sb.Append(country.ShortName);
            return(Task.FromResult((sb.ToString(), countryFlag)));
        }
Esempio n. 7
0
        private RealEstate CreateRealEstate(CreateRealEstateViewModel realEstate, GoogleAddress addressFull)
        {
            var userId = this.User.Identity.GetUserId();
            var currentlyLoggedUser = this.usersService.GetUserDetailsById(userId);

            realEstate.Country = addressFull.Components[3].LongName;
            realEstate.City    = addressFull.Components[1].LongName;

            var dbRealEstate = this.Mapper.Map <RealEstate>(realEstate);

            dbRealEstate.PublisherId = userId;
            if (currentlyLoggedUser.MyOwnAgencyId != null)
            {
                dbRealEstate.AgencyId = currentlyLoggedUser.MyOwnAgencyId;
            }

            dbRealEstate.Latitude  = addressFull.Coordinates.Latitude;
            dbRealEstate.Longitude = addressFull.Coordinates.Longitude;

            var visitors = new VisitorsDetails();

            visitors.AllUsers.Add(currentlyLoggedUser);

            var visitorsDetailsId = this.visitorsService.Add(visitors);

            dbRealEstate.VisitorsDetailsId = visitorsDetailsId;
            dbRealEstate.VisitorsDetails   = visitors;
            return(dbRealEstate);
        }
Esempio n. 8
0
        public async Task ReverseGeocode()
        {
            GoogleGeocoder geocoder  = new GoogleGeocoder();
            var            addresses = await geocoder.ReverseGeocodeAsync(Latitude, Longitude);

            GoogleAddress addr = addresses.Where(a => !a.IsPartialMatch).FirstOrDefault();

            if (addr != null)
            {
                if (addr[GoogleAddressType.Country] != null)
                {
                    Country = addr[GoogleAddressType.Country].LongName;
                }
                if (addr[GoogleAddressType.Locality] != null)
                {
                    Locality = addr[GoogleAddressType.Locality].LongName;
                }
                if (addr[GoogleAddressType.AdministrativeAreaLevel1] != null)
                {
                    AdminLevel1 = addr[GoogleAddressType.AdministrativeAreaLevel1].LongName;
                }
                if (addr[GoogleAddressType.AdministrativeAreaLevel2] != null)
                {
                    AdminLevel2 = addr[GoogleAddressType.AdministrativeAreaLevel2].LongName;
                }
                if (addr[GoogleAddressType.AdministrativeAreaLevel3] != null)
                {
                    AdminLevel3 = addr[GoogleAddressType.AdministrativeAreaLevel3].LongName;
                }
            }
        }
Esempio n. 9
0
        public async Task <List <GoogleAddress> > GetAddressPosition(string address)
        {
            var url    = EndPoints.GoogleAddressUrl(address);
            var client = new HttpClient();
            var json   = client.GetStringAsync(url).Result;
            var adds   = new List <GoogleAddress>();

            GooglePlaceSearchResponse resp = JsonConvert.DeserializeObject <GooglePlaceSearchResponse>(json);

            try
            {
                foreach (var add in resp.Results)
                {
                    var pos = new GoogleAddress
                    {
                        RequestedAddress = address,
                        FormattedAddress = add.Vicinity,
                        Lat      = add.Geometry.Location.Lat,
                        Lon      = add.Geometry.Location.Lng,
                        Name     = add.Name,
                        Distance = TrackingHelper.Instance.CalculateDistance(add.Geometry.Location.Lat, add.Geometry.Location.Lng),
                    };
                    adds.Add(pos);
                }
            }
            catch (Exception e)
            {
            }
            return(adds.OrderBy(x => x.Distance).ToList());;
        }
Esempio n. 10
0
        private void OlvAddresses_FormatRow(object sender, BrightIdeasSoftware.FormatRowEventArgs e)
        {
            GoogleAddress address = e.Model as GoogleAddress;

            if (address.PlaceId == txtPlaceID.Text)
            {
                e.Item.BackColor = Color.LightGreen;
            }
        }
Esempio n. 11
0
        public async Task <List <Stop> > SearchStops(GoogleAddress googleAddress)
        {
            var stops = Db.SearchStopsNearAddress(googleAddress.Lat, googleAddress.Lon, 0.5, googleAddress.Name);

            foreach (var stop in stops)
            {
                stop.IsDestinationStart = true;
            }
            return(stops);
        }
Esempio n. 12
0
        //public static List<GeocodeAddress> Geocoder(string address)
        //{
        //	List<GeocodeAddress> geocodeAddresses = new List<GeocodeAddress>();
        //	GoogleGeocoder geocoder = new GoogleGeocoder(ConfigurationManager.AppSettings["GoogleMapsApiKey"].ToString());
        //	IEnumerable<GoogleAddress> addresses = geocoder.Geocode(address).ToArray();

        //	if (addresses.Count() == 0)
        //	{
        //		geocodeAddresses.Add(new GeocodeAddress()
        //		{
        //			Status = GeocodeStatus.NotFound.ToString(),
        //			Source = "Google"
        //		});
        //		return geocodeAddresses;
        //	}

        //	foreach (GoogleAddress gaddress in addresses)
        //	{
        //		geocodeAddresses.Add(new GeocodeAddress()
        //		{
        //			Status = GoogleToGeocode[GoogleStatus.Ok].ToString(),
        //			Latitude = gaddress.Coordinates.Latitude,
        //			Longitude = gaddress.Coordinates.Longitude,
        //			Source = gaddress.Provider,
        //			SourceId = gaddress.PlaceId,
        //			FormattedAddress = gaddress.FormattedAddress,
        //			StreetNumber = GetComponentType(gaddress, GoogleAddressType.StreetNumber).LongName,
        //			StreetName = GetComponentType(gaddress, GoogleAddressType.Route).LongName,
        //			City = GetComponentType(gaddress, GoogleAddressType.Locality).LongName,
        //			County = GetComponentType(gaddress, GoogleAddressType.AdministrativeAreaLevel2).LongName,
        //			State = GetComponentType(gaddress, GoogleAddressType.AdministrativeAreaLevel1).LongName,
        //			Country = GetComponentType(gaddress, GoogleAddressType.Country).LongName,
        //			PostalCode = GetComponentType(gaddress, GoogleAddressType.PostalCode).LongName
        //		});
        //	}
        //          //Sleep the thread so we dont go over the limit per seconds with google maps.
        //          Thread.Sleep(100);
        //          return geocodeAddresses;
        //}

        public static GoogleAddressComponent GetComponentType(GoogleAddress address, GoogleAddressType type)
        {
            GoogleAddressComponent component;

            if ((component = address.Components.Where(w => w.Types.Contains(type)).SingleOrDefault()) != null)
            {
                return(component);
            }
            return(new GoogleAddressComponent(null, null, null));
        }
Esempio n. 13
0
        public static bool IsAmerica(this GoogleAddress address)
        {
            var americaCheck = from component in address.Components
                               where component.ShortName.Equals("US") &&
                               component.Types.Contains(GoogleAddressType.Country) &&
                               component.Types.Contains(GoogleAddressType.Political)
                               select component;

            return(americaCheck.Any());
        }
Esempio n. 14
0
        public async Task StorageService_GetAddresses()
        {
            var model = new GoogleAddress {
                UserName = "******"
            };

            SetDocumentQuery("mentorbot", "addresses", "SELECT TOP 1000 * FROM addresses", model);

            var result = await _service.GetAddressesAsync();

            Assert.AreEqual("A", result[0].UserName);
        }
        private string ReverseGeoCodeCapturedCellIdToLocation(ulong capturedCellId)
        {
            var    cellId = new S2CellId(capturedCellId);
            var    latlng = cellId.ToLatLng();
            string location;

            // Check cache for location.
            bool success = PokemonListModel.LocationsCache.TryGetValue(this.PokemonData.CapturedCellId, out location);

            if (success)
            {
                return(location);
            }

            GoogleGeocoder geocoder  = new GoogleGeocoder();
            var            addresses = geocoder.ReverseGeocode(new Geocoding.Location(latlng.LatDegrees, latlng.LngDegrees));
            GoogleAddress  addr      = addresses.Where(a => !a.IsPartialMatch).FirstOrDefault();

            if (addr != null && addr[GoogleAddressType.Country] != null)
            {
                if (addr[GoogleAddressType.Locality] != null)
                {
                    location = $"{addr[GoogleAddressType.Locality].LongName}, {addr[GoogleAddressType.Country].LongName}";
                }
                else if (addr[GoogleAddressType.AdministrativeAreaLevel1] != null)
                {
                    location = $"{addr[GoogleAddressType.AdministrativeAreaLevel1].LongName}, {addr[GoogleAddressType.Country].LongName}";
                }
                else if (addr[GoogleAddressType.AdministrativeAreaLevel2] != null)
                {
                    location = $"{addr[GoogleAddressType.AdministrativeAreaLevel2].LongName}, {addr[GoogleAddressType.Country].LongName}";
                }
                else if (addr[GoogleAddressType.AdministrativeAreaLevel3] != null)
                {
                    location = $"{addr[GoogleAddressType.AdministrativeAreaLevel3].LongName}, {addr[GoogleAddressType.Country].LongName}";
                }
                else
                {
                    location = $"{addr[GoogleAddressType.Country].LongName}";
                }

                // Add to cache
                PokemonListModel.LocationsCache.Add(this.PokemonData.CapturedCellId, location);
            }
            else
            {
                location = $"{latlng.LatDegrees}, {latlng.LngDegrees}";
            }

            return(location);
        }
Esempio n. 16
0
        public string ReverseGeocode(string ApiKey, double Latitude, double Longitude)
        {
            GoogleGeocoder coder = new GoogleGeocoder(ApiKey);

            GoogleAddress address = coder.ReverseGeocode(Latitude, Longitude).FirstOrDefault();

            if (address != null)
            {
                return(address.FormattedAddress);
            }
            else
            {
                return(null);
            }
        }
        public LocationInfo Geocode(string input)
        {
            IGeocoder             geocoder  = new GoogleGeocoder();
            IEnumerable <Address> addresses = geocoder.Geocode(input);

            GoogleAddress address = (GoogleAddress)addresses.First();

            return(new LocationInfo
            {
                Latitude = address.Coordinates.Latitude.ToString(),
                Longitude = address.Coordinates.Longitude.ToString(),
                City = address[GoogleAddressType.Locality].LongName,
                State = address[GoogleAddressType.AdministrativeAreaLevel1].ShortName
            });
        }
Esempio n. 18
0
        // Geocodes an address using the Bing Maps engine
        public static Location Geocode_Google(string ADDRESS)
        {
            try
            {
                // Calls the webservice
                GoogleGeocoder GEOCODER = new GoogleGeocoder()
                {
                    ApiKey = ConfigurationManager.AppSettings["GoogleApiKey"]
                };
                IEnumerable <Address> addresses = GEOCODER.Geocode(ADDRESS);

                Location R = new Location();

                // Checks if the process returned a valid result
                if (addresses.Count() > 0)
                {
                    // Selects the firt result
                    GoogleAddress G = (GoogleAddress)addresses.FirstOrDefault();

                    R.Lat     = G.Coordinates.Latitude;
                    R.Lon     = G.Coordinates.Longitude;
                    R.Address = Find_Value(G, "ROUTE") + " " +
                                Find_Value(G, "STREETNUMBER");
                    R.City       = Find_Value(G, "ADMINISTRATIVEAREALEVEL2");
                    R.State      = Find_Value(G, "ADMINISTRATIVEAREALEVEL1");
                    R.PostalCode = Find_Value(G, "POSTALCODE");
                    R.Quality    = G.LocationType.ToString();
                    R.Complete   = G.FormattedAddress;
                }
                else
                {
                    R.Lat     = 0;
                    R.Lon     = 0;
                    R.Quality = "Bad";
                }

                return(R);
            }
            catch (Exception ERROR)
            {
                throw new Exception(ERROR.Message);
            }
        }
Esempio n. 19
0
        public Coordinates Geocode(string ApiKey, string Address)
        {
            GoogleGeocoder coder = new GoogleGeocoder(ApiKey);

            GoogleAddress address = coder.Geocode(Address).FirstOrDefault();

            if (address != null)
            {
                return new Coordinates()
                       {
                           Latitude = address.Coordinates.Latitude, Longitude = address.Coordinates.Longitude
                       }
            }
            ;
            else
            {
                return(null);
            }
        }
Esempio n. 20
0
        // Find a value into GoogleAddress IEnumerable
        public static string Find_Value(GoogleAddress Obj, string Tag)
        {
            string V = "";

            if (Obj.Components.Count() > 0)
            {
                for (int I = 0; I < Obj.Components.Count(); I++)
                {
                    string[] Results = Obj.Components[I].ToString().Split(':');
                    if (Results[0].Trim().ToUpper() == Tag)
                    {
                        V = Obj.Components[I].ShortName;
                        break;
                    }
                }
            }

            return(V);
        }
Esempio n. 21
0
        private void MnuSetBasicAddress_Click(object sender, System.EventArgs e)
        {
            if (olvAddresses.SelectedObject == null)
            {
                return;
            }

            GoogleAddress basicAddress = olvAddresses.SelectedObject as GoogleAddress;
            var           allAddresses = olvAddresses.CollectCheckedObjects <Address>(ObjectListViewHelper.ObjectListViewCollector.All);
            Bind          sourceBind   = this.BindAlternative ?? this.Bind;

            BindAddress newBindAddress = BindAddress.Create(allAddresses, basicAddress);

            Bind newBind = new Bind {
                Address = newBindAddress, Addresses = allAddresses, Description = sourceBind.Description, OriginalAddress = sourceBind.OriginalAddress
            };

            this.BindAlternative = newBind;

            UpdateBindInfo(newBind);
        }
Esempio n. 22
0
        protected string GetGeoCode(sp_Vol_Address_DM VolAddr)
        {
            GoogleAddress googleAddress = new GoogleAddress();
            googleAddress.FormattedAddress = VolAddr.AddrLine1 + ", " +
               VolAddr.City + ", " + VolAddr.St + " " + VolAddr.Zip;
            //Assume we want to send the request to Google using SSL
            IGeocoder geoCoder = new GoogleGeocoder(true);
            String geoCoderXML = geoCoder.GetLatLongFromAddress(googleAddress);
            String latitude;
            String longitude;

            using (XmlReader reader = XmlReader.Create(new StringReader(geoCoderXML)))
            {
                reader.ReadToFollowing("lat");
                reader.MoveToFirstAttribute();
                latitude = reader.Value;

                reader.ReadToFollowing("lon");
                longitude = reader.Value;
            }

            String gcReturn;
            if (latitude.Contains("unknown") || longitude.Contains("unknown"))
            {
                gcReturn = null;
            }
            else
            {
                gcReturn = "'POINT(" + longitude + " " + latitude + ")'";
            }

            return gcReturn;
        }
Esempio n. 23
0
        /// <summary>Processes the specified timesheets.</summary>
        private async Task ProcessNotify(
            IReadOnlyList <Timesheet> timesheets,
            string department,
            bool notify,
            GoogleChatAddress address,
            IHangoutsChatConnector connector)
        {
            string text;
            var    filteredTimesheet =
                department == null ?
                timesheets :
                timesheets
                .Where(it => it.DepartmentName.Equals(department, StringComparison.InvariantCultureIgnoreCase))
                .ToArray();

            var notifiedUserList = new List <string>();

            if (filteredTimesheet.Count == 0)
            {
                text = "<b>All user have submitted timesheets.</b>";
            }
            else if (notify && filteredTimesheet.Count > 0)
            {
                var emails             = filteredTimesheet.Select(it => it.UserEmail).ToArray();
                var storeAddresses     = _storageService.GetAddresses();
                var filteredAddresses  = storeAddresses.Where(it => emails.Contains(it.UserEmail)).ToArray();
                var addressesForUpdate = new List <GoogleAddress>();

                IReadOnlyList <GoogleAddress> privateAddresses = new GoogleAddress[0];
                if (filteredAddresses.Length < timesheets.Count)
                {
                    var storeAddressesNames = storeAddresses.Select(it => it.SpaceName).ToArray();
                    privateAddresses = connector
                                       .GetPrivateAddress(storeAddressesNames)
                                       .Select(it => new GoogleAddress
                    {
                        SpaceName       = it.Space.Name,
                        UserName        = it.Sender.Name,
                        UserDisplayName = it.Sender.DisplayName
                    })
                                       .ToArray();

                    // Store inactive spaces, so not to be requested the next time
                    addressesForUpdate.AddRange(privateAddresses.Where(it => it.UserName == null));
                }

                foreach (var timesheet in filteredTimesheet)
                {
                    var message = $"{timesheet.UserName}, Please submit your timesheet. Your current hours are {timesheet.Total}.";
                    var addr    = filteredAddresses.FirstOrDefault(it => it.UserEmail == timesheet.UserEmail);
                    if (addr == null)
                    {
                        addr = privateAddresses.FirstOrDefault(it => it.UserDisplayName == timesheet.UserName);
                        if (addr == null)
                        {
                            continue;
                        }

                        addr.UserEmail = timesheet.UserEmail;

                        addressesForUpdate.Add(addr);
                    }

                    notifiedUserList.Add(timesheet.UserName);
                    await connector.SendMessageAsync(
                        message,
                        new GoogleChatAddress(addr.SpaceName, string.Empty, "DM", addr.UserName, addr.UserDisplayName));
                }

                if (addressesForUpdate.Count > 0)
                {
                    await _storageService.AddAddressesAsync(addressesForUpdate);
                }

                text = notifiedUserList.Count == filteredTimesheet.Count ?
                       "All users width unsubmitted timesheets are notified! Total of " + notifiedUserList.Count :
                       "The following people where not notified: <br>" + GetCardText(filteredTimesheet, notifiedUserList);
            }
            else
            {
                text = "The following people have to submit timesheet: <br>" + GetCardText(filteredTimesheet, notifiedUserList);
            }

            var paragraph = new TextParagraph {
                Text = text
            };
            var card = ChatEventFactory.CreateCard(paragraph);

            await connector.SendMessageAsync(null, address, card);
        }
Esempio n. 24
0
        public async Task <(List <EmbedBuilder> WeatherResults, List <EmbedBuilder> Alerts)> GetWeatherEmbedsAsync(
            DarkSkyResponse forecast, GoogleAddress geocode)
        {
            if (forecast.IsSuccessStatus)
            {
                var alertEmbeds   = new List <EmbedBuilder>();
                var weatherEmbeds = new List <EmbedBuilder>();
                var response      = forecast.Response;
                (string address, string flag) = await GetShortLocationAsync(geocode).ConfigureAwait(false);

                var hourlyDataPoint = response.Hourly.Data.FirstOrDefault();
                if (hourlyDataPoint != null)
                {
                    var weatherIcons = GetWeatherEmoji(hourlyDataPoint.Icon);
                    var color        = CreateWeatherColor(hourlyDataPoint.Temperature);
                    var embed        = new EmbedBuilder
                    {
                        Color       = color,
                        Title       = $"{flag ?? ""}{address}",
                        Description = $"Weather from {hourlyDataPoint.DateTime.Humanize()}",
                        Footer      = new EmbedFooterBuilder
                        {
                            Text    = "Powered by Dark Sky",
                            IconUrl = "https://darksky.net/images/darkskylogo.png"
                        },
                        ThumbnailUrl = weatherIcons.Url
                    }.WithCurrentTimestamp();
                    embed.AddField($"{weatherIcons.Emoji.Name} Summary", response.Hourly.Summary, true);
                    embed.AddField("🌡 Temperature",
                                   $"{hourlyDataPoint.Temperature} °C / {hourlyDataPoint.Temperature * 1.8 + 32} °F", true);
                    embed.AddField("☂ Precipitation", string.Format("{0:P1}", hourlyDataPoint.PrecipProbability), true);
                    if (hourlyDataPoint.PrecipIntensity.HasValue && hourlyDataPoint.PrecipIntensity.Value > 0)
                    {
                        embed.AddField("💧 Precipitation Intensity", $"{hourlyDataPoint.PrecipIntensity} (mm/h)", true);
                    }
                    embed.AddField("💧 Humidity", string.Format("{0:P1}", hourlyDataPoint.Humidity), true);
                    embed.AddField("🌬 Wind Speed", $"{hourlyDataPoint.WindSpeed} (m/s)", true);
                    weatherEmbeds.Add(embed);
                }
                if (response.Alerts != null)
                {
                    foreach (var alert in response.Alerts)
                    {
                        var    expiration   = alert.ExpiresDateTime;
                        string alertContent = alert.Description.Humanize();
                        if (alertContent.Length >= 512)
                        {
                            alertContent = alertContent.Truncate(512) +
                                           "\n\nPlease click on the title for more details.";
                        }
                        var sb = new StringBuilder();
                        sb.AppendLine(Format.Bold(alert.Title));
                        sb.AppendLine();
                        sb.AppendLine(alertContent);
                        sb.AppendLine();
                        if (expiration > DateTimeOffset.UtcNow)
                        {
                            sb.AppendLine(Format.Italics($"Expires {expiration.Humanize()}"));
                        }
                        var alertEmbed = new EmbedBuilder
                        {
                            Color        = Color.DarkOrange,
                            Title        = $"Alert for {address}, click me for more details.",
                            Url          = alert.Uri.AbsoluteUri,
                            ThumbnailUrl = _config.Icons.Warning,
                            Description  = sb.ToString()
                        };
                        alertEmbeds.Add(alertEmbed);
                    }
                }
                return(weatherEmbeds, alertEmbeds);
            }
            _loggingService.Log($"Weather returned unexpected response: {forecast.ResponseReasonPhrase}",
                                LogSeverity.Error);
            return(null, null);
        }
Esempio n. 25
0
        public virtual async Task <ActionResult> Edit(PropertyListing model)
        {
            try
            {
                var modelToUpdate = await _property.GetPropertyByIdAsync(model.Id, true);

                var updatedFields = Request.Form.Keys.ToHashSet();
                modelToUpdate = modelToUpdate.UpdateFromFormModel(model, updatedFields);

                modelToUpdate = await _property.ReloadReferences(modelToUpdate);

                modelToUpdate.LastEditedBy = User.Identity.Name;
                modelToUpdate.LastEditedOn = DateTime.UtcNow;

                if (model.AutoGeocode)
                {
                    var StatusMessage = "";
                    try
                    {
                        try
                        {
                            GoogleAddress address = _address.GeocodeAddress(modelToUpdate);
                            if (address != null)
                            {
                                modelToUpdate.SetLocation(address.Coordinates);
                            }
                        }
                        catch (Exception ex)
                        {
                            if (ex.InnerException != null)
                            {
                                throw ex.InnerException;
                            }
                            StatusMessage = "There was an error GeoLocating the property.";
                            ModelState.AddModelError("GeoCoding", StatusMessage);
                            await _logService.AddExceptionAsync <BasePropertyController>(StatusMessage, ex, LogType.Warning);
                        }
                    }
                    catch (GoogleGeocodingException ex)
                    {
                        switch (ex.Status)
                        {
                        case GoogleStatus.RequestDenied:
                            StatusMessage = "There was an error with the Google API [RequestDenied] this means your API account is not activated for Geocoding Requests.";
                            ModelState.AddModelError("GeoCoding", StatusMessage);
                            await _logService.AddExceptionAsync <BasePropertyController>(StatusMessage, ex, LogType.Warning);

                            break;

                        case GoogleStatus.OverQueryLimit:
                            StatusMessage = "There was an error with the Google API [OverQueryLimit] this means your API account is has run out of Geocoding Requests.";
                            ModelState.AddModelError("GeoCoding", StatusMessage);
                            await _logService.AddExceptionAsync <BasePropertyController>(StatusMessage, ex, LogType.Warning);

                            break;

                        default:
                            StatusMessage = "There was an error with the Google API [" + ex.Status.ToString() + "]: " + ex.Message;
                            ModelState.AddModelError("GeoCoding", StatusMessage);
                            await _logService.AddExceptionAsync <BasePropertyController>(StatusMessage, ex, LogType.Warning);

                            break;
                        }
                    }
                }

                string type = Engine.Settings.Property.GetPlanningFromType(modelToUpdate.Planning);
                if (modelToUpdate.HasMeta("PlanningDescription"))
                {
                    modelToUpdate.UpdateMeta("PlanningDescription", type);
                }
                else
                {
                    if (modelToUpdate.Metadata == null)
                    {
                        modelToUpdate.Metadata = new List <PropertyMeta>();
                    }

                    modelToUpdate.AddMeta("PlanningDescription", type);
                }

                foreach (KeyValuePair <string, Microsoft.Extensions.Primitives.StringValues> val in Request.Form)
                {
                    if (val.Key.StartsWith("Meta:"))
                    {
                        if (modelToUpdate.HasMeta(val.Key.Replace("Meta:", "")))
                        {
                            modelToUpdate.UpdateMeta(val.Key.Replace("Meta:", ""), val.Value.ToString());
                        }
                        else
                        {
                            modelToUpdate.AddMeta(val.Key.Replace("Meta:", ""), val.Value.ToString());
                        }
                    }
                }

                await _property.UpdateAsync(modelToUpdate);

                SaveMessage = "Saved";
                MessageType = AlertType.Success;

                modelToUpdate = await LoadAgents(modelToUpdate);

                return(View(modelToUpdate));
            }
            catch (Exception ex)
            {
                await _logService.AddExceptionAsync <BasePropertyController>("Error saving a property listing.", ex);

                SaveMessage = "An error occurred: " + ex.Message;
                MessageType = AlertType.Danger;

                model = await _property.ReloadReferences(model);

                model = await LoadAgents(model);

                return(View(model));
            }
        }
        /// <summary>
        /// Maps a Google Address Object to the values of the dynamic form associated with the address country and returns the dynamic form.
        /// </summary>
        /// <exception cref="Flipdish.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="googleAddress">A Google address object, as it is retuned from the maps API.</param>
        /// <returns>RestApiResultAddressFormResponse</returns>
        public RestApiResultAddressFormResponse FormatGoogleAddress(GoogleAddress googleAddress)
        {
            ApiResponse <RestApiResultAddressFormResponse> localVarResponse = FormatGoogleAddressWithHttpInfo(googleAddress);

            return(localVarResponse.Data);
        }
Esempio n. 27
0
        private IList <ILocationAddress> OnProcessResponse(object responseResult, int maxResults, CancellationToken token)
        {
            if (IfCancellationRequested(token))
            {
                return(null);
            }

            if (responseResult == null)
            {
                return(null);
            }

            var json = responseResult as string;

            if (string.IsNullOrEmpty(json) || string.IsNullOrWhiteSpace(json))
            {
                return(null);
            }

            var response = JsonConvert.DeserializeObject <GoogleResponse>(json);

            if (response?.Status == null)
            {
                throw new GoogleGeocodingException(GoogleStatus.Error, new HttpRequestException("Empty response."));
            }

            if (response.Status != GoogleStatus.Ok && response.Status != GoogleStatus.ZeroResults)
            {
                throw new GoogleGeocodingException(response.Status, response.ErrorMessage);
            }

            if (response.Results == null || response.Results.Length == 0)
            {
                throw new GoogleGeocodingException(GoogleStatus.Error, response.ErrorMessage,
                                                   new HttpRequestException("Empty response result."));
            }

            var result = new List <ILocationAddress>();

            if (response.Status == GoogleStatus.ZeroResults)
            {
                return(result);
            }

            var count = 0;

            foreach (var respResult in response.Results.Where(p => p != null))
            {
                if (IfCancellationRequested(token))
                {
                    return(null);
                }

                if (count++ >= maxResults)
                {
                    break;
                }

                if (respResult.AddressComponents == null)
                {
                    continue;
                }

                var address = new GoogleAddress("Google");
                foreach (var component in respResult.AddressComponents.Where(p => p != null))
                {
                    if (IfCancellationRequested(token))
                    {
                        return(null);
                    }

                    foreach (var compType in component.Type)
                    {
                        if (IfCancellationRequested(token))
                        {
                            return(null);
                        }

                        switch (compType)
                        {
                        case GoogleAddressType.PostalCode:
                            address.PostalCode = component.LongName;
                            continue;

                        case GoogleAddressType.Country:
                            address.CountryName = component.LongName;
                            address.CountryCode = component.ShortName;
                            continue;

                        case GoogleAddressType.AdministrativeAreaLevel1:
                            address.AdminArea = component.LongName;
                            continue;

                        case GoogleAddressType.AdministrativeAreaLevel2:
                            address.SubAdminArea = component.LongName;
                            continue;

                        case GoogleAddressType.Locality:
                            address.Locality = component.LongName;
                            continue;

                        case GoogleAddressType.SubLocalityLevel1:
                            address.SubLocality = component.LongName;
                            continue;

                        case GoogleAddressType.SubLocalityLevel2:
                            address.Thoroughfare = component.LongName;
                            continue;

                        case GoogleAddressType.SubLocalityLevel3:
                            address.SubThoroughfare = component.LongName;
                            continue;

                        case GoogleAddressType.Premise:
                            address.Premises = component.LongName;
                            continue;

                        default:
                            continue;
                        }
                    }
                }

                if (respResult.Geometry?.Location?.Latitude != null &&
                    respResult.Geometry.Location.Longitude.HasValue)
                {
                    address.Latitude  = respResult.Geometry.Location.Latitude.Value;
                    address.Longitude = respResult.Geometry.Location.Longitude.Value;
                }

                result.Add(address);
            }

            return(result);
        }
        /// <summary>
        /// Maps a Google Address Object to the values of the dynamic form associated with the address country and returns the dynamic form.
        /// </summary>
        /// <exception cref="Flipdish.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="googleAddress">A Google address object, as it is retuned from the maps API.</param>
        /// <returns>Task of RestApiResultAddressFormResponse</returns>
        public async System.Threading.Tasks.Task <RestApiResultAddressFormResponse> FormatGoogleAddressAsync(GoogleAddress googleAddress)
        {
            ApiResponse <RestApiResultAddressFormResponse> localVarResponse = await FormatGoogleAddressAsyncWithHttpInfo(googleAddress);

            return(localVarResponse.Data);
        }
Esempio n. 29
0
 private static string FormatGeolocation(GoogleAddress address)
 {
     return(string.Format(Strings.GeocodeResult, address.FormattedAddress, address.Coordinates.Latitude,
                          address.Coordinates.Longitude));
 }
        /// <summary>
        /// Maps a Google Address Object to the values of the dynamic form associated with the address country and returns the dynamic form.
        /// </summary>
        /// <exception cref="Flipdish.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="googleAddress">A Google address object, as it is retuned from the maps API.</param>
        /// <returns>Task of ApiResponse (RestApiResultAddressFormResponse)</returns>
        public async System.Threading.Tasks.Task <ApiResponse <RestApiResultAddressFormResponse> > FormatGoogleAddressAsyncWithHttpInfo(GoogleAddress googleAddress)
        {
            // verify the required parameter 'googleAddress' is set
            if (googleAddress == null)
            {
                throw new ApiException(400, "Missing required parameter 'googleAddress' when calling AddressApi->FormatGoogleAddress");
            }

            var    localVarPath         = "/api/v1.0/address/google";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new List <KeyValuePair <String, String> >();
            var    localVarHeaderParams = new Dictionary <String, String>(this.Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json",
                "text/json",
                "application/xml",
                "text/xml",
                "application/x-www-form-urlencoded"
            };
            String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json",
                "text/json",
                "application/xml",
                "text/xml"
            };
            String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (googleAddress != null && googleAddress.GetType() != typeof(byte[]))
            {
                localVarPostBody = this.Configuration.ApiClient.Serialize(googleAddress); // http body (model) parameter
            }
            else
            {
                localVarPostBody = googleAddress; // byte array
            }

            // authentication (oauth2) required
            // oauth required
            if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
            {
                localVarHeaderParams["Authorization"] = "Bearer " + this.Configuration.AccessToken;
            }

            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await this.Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                            Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                            localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("FormatGoogleAddress", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <RestApiResultAddressFormResponse>(localVarStatusCode,
                                                                      localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                                                      (RestApiResultAddressFormResponse)this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(RestApiResultAddressFormResponse))));
        }
Esempio n. 31
0
        public ActionResult VerifyZipCode(string zipCode)
        {
            string city  = null;
            string state = null;

            var request = Request;


            //check if zipcode is a valid integer
            if (int.TryParse(zipCode, out int parsedZip) == false)
            {
                return(new JsonResult()
                {
                    Data = new { Success = false, Message = "Invalid ZipCode" }
                });
            }

            //get city and state from geocode API
            var geoCoder = new GoogleGeocoder()
            {
                ComponentFilters = new List <GoogleComponentFilter> {
                    new GoogleComponentFilter("country", "US"), new GoogleComponentFilter("postal_code", zipCode)
                }
            };

            try
            {
                GoogleAddress address = geoCoder.Geocode(zipCode).FirstOrDefault();

                if (address == null)
                {
                    return(new JsonResult()
                    {
                        Data = new { Success = false, Message = "Invalid ZipCode" }
                    });
                }

                city  = address.Components.Single(x => x.Types.Any(t => t == GoogleAddressType.Locality)).ShortName;
                state = address.Components.Single(x => x.Types.Any(t => t == GoogleAddressType.AdministrativeAreaLevel1)).ShortName;
            }
            catch
            {
                return(new JsonResult()
                {
                    Data = new { Success = false, Message = "Invalid ZipCode" }
                });
            }

            //check if zip is serviced
            var zipcode = db.ZipCodes.SingleOrDefault(z => z.Zip == parsedZip);

            if (zipcode == null)
            {
                db.ZipCodes.Add(new ZipCode()
                {
                    Zip = parsedZip, IsServiced = false
                });
                db.SaveChanges();
                return(new JsonResult()
                {
                    Data = new { Success = false, Message = db.Store.First().ZipCodeNotInServiceMessage }
                });
            }
            else if (zipcode.IsServiced)
            {
                var order = db.Orders.Add(new Order()
                {
                    ZipCode        = zipcode,
                    DateOrdered    = DateTime.Now,
                    Status         = OrderStatus.Initial,
                    City           = city,
                    State          = state,
                    SubTotal       = decimal.Zero,
                    GrandTotal     = decimal.Zero,
                    DeliveryCharge = db.Store.First().DeliveryFee
                });

                db.SaveChanges();

                return(new JsonResult()
                {
                    Data = new { Success = true, Message = "Let's Order!", OrderId = order.OrderId }
                });
            }
            else
            {
                return(new JsonResult()
                {
                    Data = new { Success = false, Message = db.Store.First().ZipCodeNotInServiceMessage }
                });
            }
        }
Esempio n. 32
0
        private async Task <IReadOnlyList <string> > NotifyUsersOverChatAsync(
            IHangoutsChatConnector connector,
            TimesheetStates state,
            Timesheet[] timesheets)
        {
            var notifiedUserList   = new List <string>();
            var addressesForUpdate = new List <GoogleAddress>();
            var storeAddresses     = await _storageService.GetAddressesAsync();

            var emails            = timesheets.Select(it => it.UserEmail).ToArray();
            var filteredAddresses = storeAddresses.Where(it => emails.Contains(it.UserEmail)).ToArray();

            IReadOnlyList <GoogleAddress> privateAddresses = new GoogleAddress[0];

            if (filteredAddresses.Length < timesheets.Length)
            {
                var storeAddressesNames = storeAddresses.Select(it => it.SpaceName).Distinct().ToArray();
                privateAddresses = connector
                                   .GetPrivateAddress(storeAddressesNames)
                                   .Select(it => new GoogleAddress
                {
                    SpaceName       = it.Space.Name,
                    UserName        = it.Sender.Name,
                    UserDisplayName = it.Sender.DisplayName
                })
                                   .ToArray();

                // Store inactive spaces, so not to be requested the next time
                addressesForUpdate.AddRange(privateAddresses.Where(it => it.UserName == null));
            }

            var textMessage = OpenAirText.GetText(state, OpenAirTextTypes.Notify);

            foreach (var timesheet in timesheets)
            {
                var message = timesheet.UserName + textMessage;
                var addr    = filteredAddresses.FirstOrDefault(it => it.UserEmail == timesheet.UserEmail);
                if (addr == null)
                {
                    addr = privateAddresses.FirstOrDefault(it => it.UserDisplayName == timesheet.UserName);
                    if (addr == null)
                    {
                        continue;
                    }

                    addr.UserEmail = timesheet.UserEmail;

                    addressesForUpdate.Add(addr);
                }

                notifiedUserList.Add(timesheet.UserName);

                await connector.SendMessageAsync(
                    message,
                    new GoogleChatAddress(addr.SpaceName, string.Empty, "DM", addr.UserName, addr.UserDisplayName));
            }

            if (addressesForUpdate.Count > 0)
            {
                await _storageService.AddAddressesAsync(addressesForUpdate);
            }

            return(notifiedUserList);
        }