Пример #1
0
        /// <summary>
        /// Download the list of images.
        /// </summary>
        private IEnumerable <Image> DownloadImages()
        {
            var    client = new WebClient();
            string json   = client.TryDownloadString(Bing.ArchiveUrl2);

            return(BingResponse.Parse(json).Images);
        }
Пример #2
0
        private void CreateIntent(BingResponse response)
        {
            var nMgr          = this.GetSystemService(NotificationService) as NotificationManager;
            var notification  = new Notification(Resource.Drawable.Icon, "Incoming Location Info");
            var intent        = new Intent(this, typeof(NewActivity));
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);

            notification.SetLatestEventInfo(this, "Your location has changed", "Location info", pendingIntent);
            nMgr.Notify(0, notification);
        }
Пример #3
0
        public static async Task Run([BlobTrigger("mylocations/{name}", Connection = "BlobConnectionString")] string myBlob,
                                     [CosmosDB(
                                          databaseName: Constants.CosmosDbName,
                                          collectionName: Constants.MyLocationsCollection,
                                          ConnectionStringSetting = "AzureCosmosDBConnectionString")] IAsyncCollector <Hospital> document,
                                     string name,
                                     ILogger log)
        {
            log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");

            List <Hospital> locations = JsonConvert.DeserializeObject <List <Hospital> >(myBlob);

            string BingMapsAPIKey = Environment.GetEnvironmentVariable("BingMapKey");

            HttpClient client = new HttpClient();
            int        i      = 0;

            foreach (Hospital h in locations)
            {
                try
                {
                    // Get Lat/Long from Bing
                    // Docs: https://docs.microsoft.com/en-us/bingmaps/rest-services/locations/find-a-location-by-address
                    string bingReverseLookupTemplate = $"http://dev.virtualearth.net/REST/v1/Locations/US/{HttpUtility.UrlEncode(h.State)}/{HttpUtility.UrlEncode(h.Zip)}/{HttpUtility.UrlEncode(h.City)}/{HttpUtility.UrlEncode(h.Address)}?key={BingMapsAPIKey}";

                    string locInfo = await client.GetStringAsync(bingReverseLookupTemplate);

                    BingResponse bingresults = JsonConvert.DeserializeObject <BingResponse>(locInfo);

                    if (bingresults.StatusCode == 200)
                    {
                        ResourceSet bingLocationSet = bingresults.ResourceSets.FirstOrDefault();
                        Resource    bingLocation    = bingLocationSet.Resources.FirstOrDefault();
                        if (bingLocation.Point.Coordinates.Length > 1)
                        {
                            h.Location = new Point(bingLocation.Point.Coordinates[0], bingLocation.Point.Coordinates[1]);
                        }

                        //TODO: Get the Map for hte location.
                    }

                    await document.AddAsync(h);

                    log.LogInformation($"C# Blob trigger function Processed blob\n Name:{h.Name} \n FacilityID: {h.FacilityId}");
                    i++;
                }
                catch (Exception ex)
                {
                    log.LogError(ex, "Exception Adding item to collection!");
                }
            }

            log.LogInformation($"C# Blob trigger function ALL DONE Processed {i} items");
        }
Пример #4
0
        public async Task <long> GetTotalResultsAsync(string query)
        {
            string uri     = ConfigurationManager.AppSettings["Bing.Uri"];
            string request = uri.Replace("{QUERY}", query);

            using (var response = await _httpClient.GetAsync(request))
            {
                var result = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception(result);
                }

                BingResponse bingResponse = JsonSerializer.Deserialize <BingResponse>(result);
                return(bingResponse.WebPages.TotalEstimatedMatches);
            }
        }
Пример #5
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "zip/{zipCode}")] HttpRequest req,
            string zipCode,
            ILogger log)
        {
            log.LogInformation($"FindByZip: HTTP trigger Find By Zip {zipCode}");

            string BingMapsAPIKey = Environment.GetEnvironmentVariable("BingMapKey");

            string baseAddress       = $"{req.Scheme}://{req.Host.Value}";
            string locationLookupUrl = baseAddress + "/api/custom/{0}/{1}";

            // Get the Lat/Long for the Zip Code from Bing
            string     reverseLookupTemplate = $"http://dev.virtualearth.net/REST/v1/Locations/US/{HttpUtility.UrlEncode(zipCode)}?key={BingMapsAPIKey}";
            HttpClient client = new HttpClient();

            string locInfo = await client.GetStringAsync(reverseLookupTemplate);

            BingResponse bingresults  = JsonConvert.DeserializeObject <BingResponse>(locInfo);
            WayPoint     userLocation = null;

            if (bingresults.StatusCode == 200)
            {
                ResourceSet bingLocationSet = bingresults.ResourceSets.FirstOrDefault();
                Resource    bingLocation    = bingLocationSet.Resources.FirstOrDefault();
                if (bingLocation.Point.Coordinates.Length > 1)
                {
                    userLocation = new WayPoint(bingLocation.Point);
                }

                if (userLocation != null)
                {
                    // Get the locations closest to the Zip
                    var data = await client.GetStringAsync(string.Format(locationLookupUrl, userLocation.Latitude, userLocation.Longitude));

                    return(new OkObjectResult(data));
                }
            }

            log.LogInformation($"FindByZip: Complted HTTP trigger Find By Zip {zipCode}");

            return(new OkResult());
        }
Пример #6
0
        public async Task <BingResponse> Search(string keyword)
        {
            string apiKey = _configurationBingOptions.ApiKey;
            string uri    = _configurationBingOptions.Uri + "?q=" + keyword;

            WebRequest request = WebRequest.Create(uri);

            request.Headers[_configurationBingOptions.Ocp] = apiKey;

            var response       = (HttpWebResponse)request.GetResponse();
            var dataStream     = response.GetResponseStream();
            var reader         = new StreamReader(dataStream);
            var responseString = await reader.ReadToEndAsync();

            //get json and convert to object
            BingResponse bingResponse = JsonConvert.DeserializeObject <BingResponse>(responseString);

            return(bingResponse);
        }
        public async Task <long> GetTotalResultsAsync(string query)
        {
            if (string.IsNullOrEmpty(query))
            {
                throw new ArgumentException("The specified parameter is invalid.", nameof(query));
            }

            string searchRequest = BingConfig.BaseUrl.Replace("{Query}", query);

            using (var response = await _client.GetAsync(searchRequest))
            {
                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception("We weren't able to process your request. Please try again later.");
                }

                BingResponse results = JsonHelper.Deserialize <BingResponse>(await response.Content.ReadAsStringAsync());
                return(long.Parse(results.WebPages.TotalEstimatedMatches));
            }
        }
        public async Task <string> GetRouteDistance(WayPoint p1, WayPoint p2)
        {
            string bingRouteTemplate = "http://dev.virtualearth.net/REST/V1/Routes/Driving?wp.0={0}&wp.1={1}&du=mi&key={2}";
            string requestedRouteUri = string.Format(bingRouteTemplate, p1.Coordinates, p2.Coordinates, BingMapsAPIKey);

            string routeData = await client.GetStringAsync(requestedRouteUri);

            BingResponse bingRouteResults = JsonConvert.DeserializeObject <BingResponse>(routeData);
            ResourceSet  routeResourceSet = bingRouteResults.ResourceSets.FirstOrDefault();

            if (routeResourceSet != null)
            {
                Resource routeResource = routeResourceSet.Resources.FirstOrDefault();
                if (routeResource != null)
                {
                    return($"{routeResource.TravelDistance:0.0} mi.");
                }
            }

            return("Not Sure");
        }
        public async Task <long> GetTotalResultsAsync(string searchQuery)
        {
            if (string.IsNullOrEmpty(searchQuery))
            {
                throw new ArgumentException("The term cannot be null or empty",
                                            nameof(searchQuery));
            }

            string customSearchRequestUri =
                BingConfig.BaseUri.Replace("{Query}", searchQuery);

            var response = await _client.GetAsync(customSearchRequestUri);

            using ( response )
            {
                BingResponse results =
                    JsonHelper.Deserialize <BingResponse>
                        (await response.Content.ReadAsStringAsync());

                return(long.Parse(results.webPages.totalEstimatedMatches));
            }
        }
Пример #10
0
        public async Task <IEnumerable <Destination> > GetItems(WayPoint userLocation, int numItems = 3)
        {
            List <Destination> locations = new List <Destination>();

            // Each Entity Type should be separated by comma ','
            // Type Ids are here: https://docs.microsoft.com/en-us/bingmaps/rest-services/common-parameters-and-types/type-identifiers/
            string entityTypes = "Hospitals";

            string bingEntitySearchTemplate = $"https://dev.virtualearth.net/REST/v1/LocalSearch/?type={entityTypes}&userLocation={userLocation.Coordinates}&key={BingMapsAPIKey}";

            string results = await client.GetStringAsync(bingEntitySearchTemplate);

            BingResponse bingresults = JsonConvert.DeserializeObject <BingResponse>(results);

            if (bingresults.StatusCode == 200)
            {
                ResourceSet     bingLocationSet = bingresults.ResourceSets.FirstOrDefault();
                List <Resource> bingLocations   = bingLocationSet.Resources.Take(numItems).ToList();

                Destination l;
                // Get the Map for the top 3 items
                foreach (Resource r in bingLocations)
                {
                    l = new Destination
                    {
                        Name        = r.Name,
                        PhoneNumber = r.PhoneNumber,
                        Address     = r.Address.FormattedAddress,
                        Location    = r.Point,
                        Website     = r.WebSite
                    };

                    locations.Add(l);
                }
            }

            return(locations);
        }
Пример #11
0
        private void BuildResults(List <string> queries)
        {
            List <BingResponse> responses = new List <BingResponse>();

            foreach (string query in queries)
            {
                var response = new BingResponse
                {
                    QueryContext = new QueryContextField
                    {
                        OriginalQuery = query
                    },

                    WebPages = new WebPagesField
                    {
                        TotalEstimatedMatches = _faker.Random.ULong()
                    }
                };

                responses.Add(response);
            }

            ExpectedResults = responses;
        }
Пример #12
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "nearby/{latitude}/{longitude}")] HttpRequest req,
            double latitude,
            double longitude,
            ILogger log)
        {
            List <Location> locationResults = new List <Location>();
            string          BingMapsAPIKey  = Environment.GetEnvironmentVariable("BingMapKey");
            string          point           = $"{latitude},{longitude}";

            // Each Entity Type should be separated by comma ','
            // Type Ids are here: https://docs.microsoft.com/en-us/bingmaps/rest-services/common-parameters-and-types/type-identifiers/
            string entityTypes = "Hospitals";

            string bingEntitySearchTemaplate = $"https://dev.virtualearth.net/REST/v1/LocalSearch/?type={entityTypes}&userLocation={point}&key={BingMapsAPIKey}";

            // Image With Route
            string wp0               = $"{latitude},{longitude}";
            string wp1               = "{0},{1}";
            string bingMapTemplate   = "http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/Routes/?wp.0={0};26;1&wp.1={1};28;2&key={2}";
            string bingRouteTemplate = "http://dev.virtualearth.net/REST/V1/Routes/Driving?wp.0={0}&wp.1={1}&du=mi&key={2}";

            try
            {
                HttpClient client  = new HttpClient();
                string     results = await client.GetStringAsync(bingEntitySearchTemaplate);

                BingResponse bingresults = JsonConvert.DeserializeObject <BingResponse>(results);

                if (bingresults.StatusCode == 200)
                {
                    ResourceSet     bingLocationSet = bingresults.ResourceSets.FirstOrDefault();
                    List <Resource> bingLocations   = bingLocationSet.Resources.Take(3).ToList();

                    Location l;
                    // Get the Map for the top 3 items
                    foreach (Resource r in bingLocations)
                    {
                        l = new Location
                        {
                            Name      = r.Name,
                            Telephone = r.PhoneNumber,
                            Address   = r.Address.FormattedAddress,
                            Point     = r.Point,
                            Url       = r.WebSite
                        };

                        #region Get Map Image
                        //TODO: Ensure to deal with failures/errors.
                        string requestedMapUri = string.Format(bingMapTemplate, wp0, string.Format(wp1, l.Point.Coordinates[0], l.Point.Coordinates[1]), BingMapsAPIKey);

                        var map = await client.GetStreamAsync(requestedMapUri);

                        //Upload file to the container
                        AzureStorageConfig asc = new AzureStorageConfig
                        {
                            AccountKey     = Environment.GetEnvironmentVariable("BlobAccountKey"),
                            AccountName    = Environment.GetEnvironmentVariable("BlobAccountName"),
                            ImageContainer = Environment.GetEnvironmentVariable("BlobImageContainer")
                        };

                        string fileName = Guid.NewGuid().ToString() + ".png";

                        string blobUrl = await StorageHelper.UploadFileToStorage(map, fileName, asc);

                        //Write to the blob and get URI
                        l.MapUri = blobUrl;
                        #endregion

                        #region Get Route Details
                        string requestedRouteUri = string.Format(bingRouteTemplate, wp0, string.Format(wp1, l.Point.Coordinates[0], l.Point.Coordinates[1]), BingMapsAPIKey);

                        string routeData = await client.GetStringAsync(requestedRouteUri);

                        BingResponse bingRouteResults = JsonConvert.DeserializeObject <BingResponse>(routeData);
                        ResourceSet  routeResourceSet = bingRouteResults.ResourceSets.FirstOrDefault();

                        if (routeResourceSet != null)
                        {
                            Resource routeResource = routeResourceSet.Resources.FirstOrDefault();
                            if (routeResource != null)
                            {
                                l.Distance = $"{routeResource.TravelDistance:0.0} mi.";
                            }
                        }
                        #endregion

                        locationResults.Add(l);
                    }
                }
                else
                {
                    return(new BadRequestResult());
                }
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult(ex));
            }


            return(new OkObjectResult(locationResults));
        }