public override void ParseResults(XDocument xmlDoc, Exception error)
            {
                TripDetails tripDetail = new TripDetails();

                if (xmlDoc == null || error != null)
                {
                    callback(tripDetail, error);
                }
                else
                {
                    try
                    {
                        tripDetail =
                            (from trip in xmlDoc.Descendants("entry")
                             select ParseTripDetails(trip)).First();
                    }
                    catch (WebserviceResponseException ex)
                    {
                        error = ex;
                    }
                    catch (Exception ex)
                    {
                        error = new WebserviceParsingException(requestUrl, xmlDoc.ToString(), ex);
                    }
                }

                Debug.Assert(error == null);

                callback(tripDetail, error);
            }
            public override void ParseResults(XDocument xmlDoc, Exception error)
            {
                List <ArrivalAndDeparture> arrivals = new List <ArrivalAndDeparture>();

                if (xmlDoc == null || error != null)
                {
                    callback(arrivals, error);
                }
                else
                {
                    try
                    {
                        arrivals.AddRange(from arrival in xmlDoc.Descendants("arrivalAndDeparture")
                                          select ParseArrivalAndDeparture(arrival));
                    }
                    catch (Exception ex)
                    {
                        error = new WebserviceParsingException(requestUrl, xmlDoc.ToString(), ex);
                    }
                }

                Debug.Assert(error == null);

                callback(arrivals, error);
            }
            public override void ParseResults(XDocument xmlDoc, Exception error)
            {
                List <Route> routes = new List <Route>();

                if (xmlDoc == null || error != null)
                {
                    callback(routes, error);
                }
                else
                {
                    try
                    {
                        routes.AddRange(from route in xmlDoc.Descendants("route")
                                        select ParseRoute(route, xmlDoc.Descendants("agency")));
                    }
                    catch (Exception ex)
                    {
                        error = new WebserviceParsingException(requestUrl, xmlDoc.ToString(), ex);
                    }

                    Debug.Assert(error == null);

                    callback(routes, error);
                }
            }
        public void ScheduleForStop(GeoCoordinate location, Stop stop, ScheduleForStop_Callback callback)
        {
            string requestUrl = string.Format(
                "{0}/{1}/{2}.xml?key={3}&Version={4}",
                WebServiceUrlForLocation(location),
                "schedule-for-stop",
                stop.id,
                KEY,
                APIVERSION
                );

            HttpWebRequest requestGetter = (HttpWebRequest)HttpWebRequest.Create(requestUrl);

            requestGetter.BeginGetResponse(delegate(IAsyncResult asyncResult)
            {
                XDocument xmlResponse          = null;
                List <RouteSchedule> schedules = new List <RouteSchedule>();

                try
                {
                    xmlResponse = ValidateWebCallback(asyncResult);

                    IDictionary <string, Route> routesMap = ParseAllRoutes(xmlResponse);

                    schedules.AddRange(from schedule in xmlResponse.Descendants("stopRouteSchedule")
                                       select new RouteSchedule
                    {
                        route = routesMap[SafeGetValue(schedule.Element("routeId"))],

                        directions =
                            (from direction in schedule.Descendants("stopRouteDirectionSchedule")
                             select new DirectionSchedule
                        {
                            tripHeadsign = SafeGetValue(direction.Element("tripHeadsign")),

                            trips =
                                (from trip in direction.Descendants("scheduleStopTime")
                                 select ParseScheduleStopTime(trip)).ToList <ScheduleStopTime>()
                        }).ToList <DirectionSchedule>()
                    });
                }
                catch (WebserviceResponseException)
                {
                }
                catch (Exception ex)
                {
                    Exception error = new WebserviceParsingException(requestUrl, xmlResponse.ToString(), ex);
                    throw error;
                }

                callback(schedules);
            },
                                           requestGetter);
        }
        public void RoutesForLocation(GeoCoordinate location, string query, int radiusInMeters, int maxCount, RoutesForLocation_Callback callback)
        {
            string requestUrl = string.Format(
                "{0}/{1}.xml?key={2}&lat={3}&lon={4}&radius={5}&Version={6}",
                WebServiceUrlForLocation(location),
                "routes-for-location",
                KEY,
                location.Latitude.ToString(NumberFormatInfo.InvariantInfo),
                location.Longitude.ToString(NumberFormatInfo.InvariantInfo),
                radiusInMeters,
                APIVERSION
                );

            if (string.IsNullOrEmpty(query) == false)
            {
                requestUrl += string.Format("&query={0}", query);
            }

            if (maxCount > 0)
            {
                requestUrl += string.Format("&maxCount={0}", maxCount);
            }

            HttpWebRequest requestGetter = (HttpWebRequest)HttpWebRequest.Create(requestUrl);

            requestGetter.BeginGetResponse(
                delegate(IAsyncResult asyncResult)
            {
                XDocument xmlResponse = null;
                List <Route> routes   = new List <Route>();

                try
                {
                    xmlResponse = ValidateWebCallback(asyncResult);
                    routes.AddRange(from route in xmlResponse.Descendants("route")
                                    select ParseRoute(route, xmlResponse.Descendants("agency")));
                }
                catch (WebserviceResponseException)
                {
                }
                catch (Exception ex)
                {
                    Exception error = new WebserviceParsingException(requestUrl, xmlResponse.ToString(), ex);
                    throw error;
                }

                callback(routes);
            },
                requestGetter);
        }
            public override void ParseResults(XDocument xmlDoc, Exception error)
            {
                List <Stop> stops         = new List <Stop>();;
                bool        limitExceeded = false;

                if (xmlDoc == null || error != null)
                {
                    callback(stops, limitExceeded, error);
                }
                else
                {
                    try
                    {
                        IDictionary <string, Route> routesMap = ParseAllRoutes(xmlDoc);

                        stops.AddRange(from stop in xmlDoc.Descendants("stop")
                                       select ParseStop(
                                           stop,
                                           (from routeId in stop.Element("routeIds").Descendants("string")
                                            select routesMap[SafeGetValue(routeId)]).ToList <Route>()));

                        IEnumerable <XElement> descendants = xmlDoc.Descendants("data");
                        if (descendants.Count() != 0)
                        {
                            limitExceeded = bool.Parse(SafeGetValue(descendants.First().Element("limitExceeded")));
                        }

                        Debug.Assert(limitExceeded == false);
                    }
                    catch (WebserviceResponseException ex)
                    {
                        error = ex;
                    }
                    catch (Exception ex)
                    {
                        error = new WebserviceParsingException(requestUrl, xmlDoc.ToString(), ex);
                    }
                }

                Debug.Assert(error == null);

                // Remove a page from the cache if we hit a parsing error.  This way we won't keep
                // invalid server data in the cache
                if (error != null)
                {
                    stopsCache.Invalidate(new Uri(requestUrl));
                }

                callback(stops, limitExceeded, error);
            }
Beispiel #7
0
            public void LocationForAddress_Completed(object sender, DownloadStringCompletedEventArgs e)
            {
                Exception error = e.Error;
                List <LocationForQuery> locations = null;

                try
                {
                    if (error == null)
                    {
                        XDocument xmlDoc = XDocument.Load(new StringReader(e.Result));

                        XNamespace ns = "http://schemas.microsoft.com/search/local/ws/rest/v1";

                        locations = (from location in xmlDoc.Descendants(ns + "Location")
                                     select new LocationForQuery
                        {
                            location = new GeoCoordinate(
                                Convert.ToDouble(location.Element(ns + "Point").Element(ns + "Latitude").Value),
                                Convert.ToDouble(location.Element(ns + "Point").Element(ns + "Longitude").Value)
                                ),
                            name = location.Element(ns + "Name").Value,
                            confidence = (Confidence)Enum.Parse(
                                typeof(Confidence),
                                location.Element(ns + "Confidence").Value,
                                true
                                ),
                            boundingBox = new LocationRect(
                                Convert.ToDouble(location.Element(ns + "BoundingBox").Element(ns + "NorthLatitude").Value),
                                Convert.ToDouble(location.Element(ns + "BoundingBox").Element(ns + "WestLongitude").Value),
                                Convert.ToDouble(location.Element(ns + "BoundingBox").Element(ns + "SouthLatitude").Value),
                                Convert.ToDouble(location.Element(ns + "BoundingBox").Element(ns + "EastLongitude").Value)
                                )
                        }).ToList();
                    }
                }
                catch (Exception ex)
                {
                    error = new WebserviceParsingException(requestUrl, e.Result, ex);
                }

                Debug.Assert(error == null);

                callback(locations, error);
            }
            public override void ParseResults(XDocument xmlDoc, Exception error)
            {
                List <RouteSchedule> schedules = new List <RouteSchedule>();

                if (xmlDoc == null || error != null)
                {
                    callback(schedules, error);
                }
                else
                {
                    try
                    {
                        IDictionary <string, Route> routesMap = ParseAllRoutes(xmlDoc);

                        schedules.AddRange
                            (from schedule in xmlDoc.Descendants("stopRouteSchedule")
                            select new RouteSchedule
                        {
                            route = routesMap[SafeGetValue(schedule.Element("routeId"))],

                            directions =
                                (from direction in schedule.Descendants("stopRouteDirectionSchedule")
                                 select new DirectionSchedule
                            {
                                tripHeadsign = SafeGetValue(direction.Element("tripHeadsign")),

                                trips =
                                    (from trip in direction.Descendants("scheduleStopTime")
                                     select ParseScheduleStopTime(trip)).ToList <ScheduleStopTime>()
                            }).ToList <DirectionSchedule>()
                        });
                    }
                    catch (Exception ex)
                    {
                        error = new WebserviceParsingException(requestUrl, xmlDoc.ToString(), ex);
                    }
                }

                Debug.Assert(error == null);

                callback(schedules, error);
            }
        public void ArrivalsForStop(GeoCoordinate location, Stop stop, ArrivalsForStop_Callback callback)
        {
            string requestUrl = string.Format(
                "{0}/{1}/{2}.xml?minutesAfter={3}&key={4}&Version={5}",
                WebServiceUrlForLocation(location),
                "arrivals-and-departures-for-stop",
                stop.id,
                60,
                KEY,
                APIVERSION
                );

            WebRequest arrivalsForStopRequest = WebRequest.Create(requestUrl);

            arrivalsForStopRequest.BeginGetResponse(asyncResult =>
            {
                XDocument xmlResponse = null;
                List <ArrivalAndDeparture> arrivals = new List <ArrivalAndDeparture>();

                try
                {
                    xmlResponse = ValidateWebCallback(asyncResult);

                    arrivals.AddRange(from arrival in xmlResponse.Descendants("arrivalAndDeparture")
                                      select ParseArrivalAndDeparture(arrival));
                }
                catch (WebserviceResponseException)
                {
                }
                catch (Exception ex)
                {
                    Exception error = new WebserviceParsingException(requestUrl, xmlResponse.ToString(), ex);
                    throw error;
                }

                callback(arrivals);
            },
                                                    arrivalsForStopRequest);
        }
        public void TripDetailsForArrival(GeoCoordinate location, ArrivalAndDeparture arrival, TripDetailsForArrival_Callback callback)
        {
            string requestUrl = string.Format(
                "{0}/{1}/{2}.xml?key={3}&includeSchedule={4}",
                WebServiceUrlForLocation(location),
                "trip-details",
                arrival.tripId,
                KEY,
                "false"
                );

            HttpWebRequest requestGetter = (HttpWebRequest)HttpWebRequest.Create(requestUrl);

            requestGetter.BeginGetResponse(delegate(IAsyncResult asyncResult)
            {
                XDocument xmlResponse  = null;
                TripDetails tripDetail = null;

                try
                {
                    xmlResponse = ValidateWebCallback(asyncResult);

                    tripDetail =
                        (from trip in xmlResponse.Descendants("entry")
                         select ParseTripDetails(trip)).First();
                }
                catch (Exception ex)
                {
                    Exception error = new WebserviceParsingException(requestUrl, xmlResponse.ToString(), ex);
                    throw error;
                }

                callback(tripDetail);
            },
                                           requestGetter);
        }
        public void StopsForRoute(GeoCoordinate location, Route route, StopsForRoute_Callback callback)
        {
            string requestUrl = string.Format(
                "{0}/{1}/{2}.xml?key={3}&Version={4}",
                WebServiceUrlForLocation(location),
                "stops-for-route",
                route.id,
                KEY,
                APIVERSION
                );

            HttpWebRequest requestGetter = (HttpWebRequest)HttpWebRequest.Create(requestUrl);

            requestGetter.BeginGetResponse(delegate(IAsyncResult asyncResult)
            {
                XDocument xmlResponse        = null;
                List <RouteStops> routeStops = new List <RouteStops>();

                try
                {
                    xmlResponse = ValidateWebCallback(asyncResult);

                    IDictionary <string, Route> routesMap = ParseAllRoutes(xmlResponse);

                    // parse all the stops, using previously parsed Route objects
                    IList <Stop> stops =
                        (from stop in xmlResponse.Descendants("stop")
                         select ParseStop(stop,
                                          (from routeId in stop.Element("routeIds").Descendants("string")
                                           select routesMap[SafeGetValue(routeId)]
                                          ).ToList <Route>()
                                          )).ToList <Stop>();

                    IDictionary <string, Stop> stopsMap = new Dictionary <string, Stop>();
                    foreach (Stop s in stops)
                    {
                        stopsMap.Add(s.id, s);
                    }

                    // and put it all together
                    routeStops.AddRange(from stopGroup in xmlResponse.Descendants("stopGroup")
                                        where SafeGetValue(stopGroup.Element("name").Element("type")) == "destination"
                                        select new RouteStops
                    {
                        name             = SafeGetValue(stopGroup.Descendants("names").First().Element("string")),
                        encodedPolylines = (from poly in stopGroup.Descendants("encodedPolyline")
                                            select new PolyLine
                        {
                            pointsString = SafeGetValue(poly.Element("points")),
                            length = SafeGetValue(poly.Element("length"))
                        }).ToList <PolyLine>(),
                        stops =
                            (from stopId in stopGroup.Descendants("stopIds").First().Descendants("string")
                             select stopsMap[SafeGetValue(stopId)]).ToList <Stop>(),

                        route = routesMap[route.id]
                    });
                }
                catch (WebserviceResponseException)
                {
                }
                catch (Exception ex)
                {
                    Exception error = new WebserviceParsingException(requestUrl, xmlResponse.ToString(), ex);
                    throw error;
                }

                callback(routeStops);
            },
                                           requestGetter);
        }
        public void StopsForLocation(GeoCoordinate location, string query, int radiusInMeters, int maxCount, bool invalidateCache, StopsForLocation_Callback callback)
        {
            GeoCoordinate roundedLocation = GetRoundedLocation(location);

            // ditto for the search radius -- nearest 50 meters for caching
            int roundedRadius = (int)(Math.Round(radiusInMeters / 50.0) * 50);

            string requestUrl = string.Format(
                "{0}/{1}.xml?key={2}&lat={3}&lon={4}&radius={5}&Version={6}",
                WebServiceUrlForLocation(location),
                "stops-for-location",
                KEY,
                roundedLocation.Latitude.ToString(NumberFormatInfo.InvariantInfo),
                roundedLocation.Longitude.ToString(NumberFormatInfo.InvariantInfo),
                roundedRadius,
                APIVERSION
                );

            if (string.IsNullOrEmpty(query) == false)
            {
                requestUrl += string.Format("&query={0}", query);
            }

            if (maxCount > 0)
            {
                requestUrl += string.Format("&maxCount={0}", maxCount);
            }

            Uri            requestUri    = new Uri(requestUrl);
            HttpWebRequest requestGetter = (HttpWebRequest)HttpWebRequest.Create(requestUri);

            requestGetter.BeginGetResponse(
                delegate(IAsyncResult asyncResult)
            {
                XDocument xmlResponse = null;
                List <Stop> stops     = new List <Stop>();
                bool limitExceeded    = false;

                try
                {
                    xmlResponse = ValidateWebCallback(asyncResult);

                    IDictionary <string, Route> routesMap = ParseAllRoutes(xmlResponse);

                    stops.AddRange(from stop in xmlResponse.Descendants("stop")
                                   select ParseStop
                                   (
                                       stop,
                                       (from routeId in stop.Element("routeIds").Descendants("string")
                                        select routesMap[SafeGetValue(routeId)]).ToList <Route>()
                                   ));

                    IEnumerable <XElement> descendants = xmlResponse.Descendants("data");
                    if (descendants.Count() != 0)
                    {
                        limitExceeded = bool.Parse(SafeGetValue(descendants.First().Element("limitExceeded")));
                    }

                    Debug.Assert(limitExceeded == false);
                }
                catch (WebserviceResponseException)
                {
                }
                catch (Exception ex)
                {
                    Exception error = new WebserviceParsingException(requestUrl, xmlResponse.ToString(), ex);
                    throw error;
                }

                callback(stops, limitExceeded);
            },
                requestGetter);
        }
            public override void ParseResults(XDocument xmlDoc, Exception error)
            {
                List <RouteStops> routeStops = new List <RouteStops>();

                if (xmlDoc == null || error != null)
                {
                    callback(routeStops, error);
                }
                else
                {
                    try
                    {
                        IDictionary <string, Route> routesMap = ParseAllRoutes(xmlDoc);

                        // parse all the stops, using previously parsed Route objects
                        IList <Stop> stops =
                            (from stop in xmlDoc.Descendants("stop")
                             select ParseStop(stop,
                                              (from routeId in stop.Element("routeIds").Descendants("string")
                                               select routesMap[SafeGetValue(routeId)]
                                              ).ToList <Route>()
                                              )).ToList <Stop>();

                        IDictionary <string, Stop> stopsMap = new Dictionary <string, Stop>();
                        foreach (Stop s in stops)
                        {
                            stopsMap.Add(s.id, s);
                        }

                        // and put it all together
                        routeStops.AddRange
                            (from stopGroup in xmlDoc.Descendants("stopGroup")
                            where SafeGetValue(stopGroup.Element("name").Element("type")) == "destination"
                            select new RouteStops
                        {
                            name             = SafeGetValue(stopGroup.Descendants("names").First().Element("string")),
                            encodedPolylines = (from poly in stopGroup.Descendants("encodedPolyline")
                                                select new PolyLine
                            {
                                pointsString = SafeGetValue(poly.Element("points")),
                                length = SafeGetValue(poly.Element("length"))
                            }).ToList <PolyLine>(),
                            stops =
                                (from stopId in stopGroup.Descendants("stopIds").First().Descendants("string")
                                 select stopsMap[SafeGetValue(stopId)]).ToList <Stop>(),

                            route = routesMap[routeId]
                        });
                    }
                    catch (WebserviceResponseException ex)
                    {
                        error = ex;
                    }
                    catch (Exception ex)
                    {
                        error = new WebserviceParsingException(requestUrl, xmlDoc.ToString(), ex);
                    }
                }

                Debug.Assert(error == null);

                // Remove a page from the cache if we hit a parsing error.  This way we won't keep
                // invalid server data in the cache
                if (error != null)
                {
                    directionCache.Invalidate(new Uri(requestUrl));
                }

                callback(routeStops, error);
            }