Ejemplo n.º 1
0
 public QueryConnectionsResult(List<Location> ambiguousFrom, List<Location> ambiguousVia, List<Location> ambiguousTo)
 {
     this.status = QueryConnectionsResult.Status.AMBIGUOUS;
     this.ambiguousFrom = ambiguousFrom;
     this.ambiguousVia = ambiguousVia;
     this.ambiguousTo = ambiguousTo;
     this.queryUri = (string)null;
     this.from = (Location)null;
     this.via = (Location)null;
     this.to = (Location)null;
     this.CommandEarlier = (string)null;
     this.connections = (List<Connection>)null;
 }
Ejemplo n.º 2
0
 public QueryConnectionsResult(string queryUri, Location from, Location via, Location to, string commandEarlier, string commandLater, List<Connection> connections)
 {
     this.status = QueryConnectionsResult.Status.OK;
     this.queryUri = queryUri;
     this.from = from;
     this.via = via;
     this.to = to;
     this.CommandEarlier = commandEarlier;
     this.CommandLater = commandLater;
     this.connections = connections;
     this.ambiguousFrom = (List<Location>)null;
     this.ambiguousVia = (List<Location>)null;
     this.ambiguousTo = (List<Location>)null;
 }
Ejemplo n.º 3
0
 public Stop(Location location, string position, DateTime time)
 {
     this.location = location;
     this.position = position;
     this.time = time;
 }
Ejemplo n.º 4
0
 public StationDepartures(Location location, List<Departure> departures, List<LineDestination> lines)
 {
     this.Location = location;
     this.Departures = departures;
     this.Lines = lines;
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Handle the response from the connections query
        /// </summary>
        /// <param name="asyncResult"></param>
        private void HandleConnectionsResponse(IAsyncResult asyncResult)  ///now this is background
        {
            // get the state information
            QueryUpdateState queryUpdateState = (QueryUpdateState)asyncResult.AsyncState;
            HttpWebRequest getConnectionsRequest = (HttpWebRequest)queryUpdateState.AsyncRequest;

            // end the async request
            queryUpdateState.AsyncResponse = (HttpWebResponse)getConnectionsRequest.EndGetResponse(asyncResult);

            Stream streamResult;
            XElement itdTripRequest;
            XElement routesElem;

            ObservableCollection<Connection> connectionList = new ObservableCollection<Connection>();

            try
            {
                // get the stream containing the response from the async call
                streamResult = queryUpdateState.AsyncResponse.GetResponseStream();

                // load the XML

                XElement tripResponse = XElement.Load(streamResult);

                //int totalResults = xmlStations.Descendants("odvNameElem").Count();


                itdTripRequest = tripResponse.Descendants("itdTripRequest").FirstOrDefault();
                routesElem = itdTripRequest.Descendants("itdRouteList").FirstOrDefault();
            }
            catch (FormatException fe)
            {
                throw new Exception("Fehler bei GetResponseStream()", fe.InnerException);
                // there was some kind of error processing the response from the web
                // additional error handling would normally be added here
            }

            // <itdRouteList>
            //   <itdRoute changes="2" vehicleTime="27" publicDuration="00:46">
            //     <itdPartialRouteList>
            //       <itdPartialRoute timeMinute="6">
            //         <itdPoint stopID="3003357" name="Erlangen Anton-Bruckner-Str." nameWO="Anton-Bruckner-Str." usage="departure" x="11017366" y="49588410" mapName="WGS84" locality="Erlangen">
            //           <itdDateTime>
            //             <itdDate year="2011" month="4" day="26" weekday="3"/>
            //             <itdTime hour="9" minute="48"/>
            //           </itdDateTime>
            //         </itdPoint>
            //         <itdPoint stopID="3003110" name="Erlangen Hauptbahnhof" nameWO="Hauptbahnhof" usage="arrival" x="11002674" y="49596106" mapName="WGS84" locality="Erlangen">
            //           <itdDateTime>
            //             <itdDate year="2011" month="4" day="26" weekday="3"/>
            //             <itdTime hour="9" minute="54"/>
            //           </itdDateTime>
            //         </itdPoint>
            //         <itdMeansOfTransport name="Stadtbus 287" shortname="287" symbol="287" type="3" motType="5" productName="Stadtbus" destination="Steudach Westfriedhof" destID="3003785" />
            //         <itdStopSeq>
            //           <itdPoint stopID="3003357" name="Erlangen Anton-Bruckner-Str." x="" y="" mapName="NAV4"/>
            //           <itdPoint stopID="3003375" name="Erlangen Sophienstr." x="" y="" mapName="NAV4"/>
            //           <itdPoint stopID="3003151" name="Erlangen Arcaden" x="" y="" mapName="NAV4"/>
            //           <itdPoint stopID="3003110" name="Erlangen Hauptbahnhof" x="" y="" mapName="NAV4"/>
            //         </itdStopSeq>
            //       </itdPartialRoute>
            //       <itdPartialRoute/>
            //       <itdPartialRoute/>
            //     </itdPartialRouteList>
            //   </itdRoute>

            //<itdMeansOfTransport name="ICE 1517 Intercity-Express" shortname="1517" symbol="" type="6" motType="0" trainType="ICE" trainName="Intercity-Express" 
            //    destination="München Hauptbahnhof" network="ddb" TTB="1" STT="1" ROP="0" destID="1008803" spTr="">
            //  <motDivaParams line="98028" project="j11" direction="H" supplement="X" network="ddb" />
            //  <itdOperator>
            //    <code>00</code>
            //    <name>Daten DB AG (sonst)</name>
            //  </itdOperator>
            //</itdMeansOfTransport>

            if (routesElem != null)
            {
                int connectionIndex = 1;

                foreach (var route in routesElem.Descendants("itdRoute"))
                {
                    if (route.HasAttributes)
                    {
                        //temp.Changes = int.Parse(route.Attribute("changes").Value);
                        //temp.Duration = route.Attribute("publicDuration").Value + "h";

                        IEnumerable<XElement> partialRoutes = route.Descendants("itdPartialRoute");

                        List<Connection.Part> parts = new List<Connection.Part>();
                        foreach (XElement partialRoute in partialRoutes)
                        {
                            // Means of Transport: Linie 287, Büchenbach/ER Mönaustr.
                            XElement partMotElem = partialRoute.Descendants("itdMeansOfTransport").FirstOrDefault();

                            bool isFootWay = false;

                            int timeMinute = -1;
                            // check if it's footway
                            if (partMotElem.Attribute("type").Value.Equals("99"))
                            {
                                timeMinute = int.Parse(partialRoute.Attribute("timeMinute").Value);
                                isFootWay = true;
                            }

                            Line line = null;
                            Location destination = null;
                            string[] colors = { "#FFFFFF", "#000000" };

                            if (!isFootWay)
                            {
                                string lineName = partMotElem.Attribute("shortname").Value;

                                string lineType = partMotElem.Attribute("productName") != null ? partMotElem.Attribute("productName").Value : partMotElem.Attribute("trainType").Value;
                                switch (lineType)
                                {
                                    case "IC":
                                    case "ICE":
                                        colors[0] = "#000000";
                                        colors[1] = "#FFFFFF";
                                        lineName = lineType + " " + lineName;
                                        break;
                                    case "Stadtbus":
                                        colors[1] = "#DC143C";
                                        break;
                                    case "U-Bahn":
                                        colors[1] = "#191970";
                                        break;
                                    case "Straßenbahn":
                                        colors[1] = "#330066";
                                        break;
                                    case "S-Bahn":
                                    case "R-Bahn":
                                        colors[1] = "#3CB371";
                                        break;
                                    default:
                                        colors[1] = "FFAAFF";
                                        break;
                                }

                                line = new Line(lineName, colors, lineType);
                                destination = new Location(LocationType.STATION, int.Parse(partMotElem.Attribute("destID").Value), lineType, partMotElem.Attribute("destination").Value);
                            }
                            else
                            {
                                colors[1] = "#AAAAAA";
                                line = new Line("Fussweg", colors, "Walk");
                                destination = new Location(LocationType.STATION, -1, "Fussweg", "");
                            }

                            // Departure: Erlangen, Sophienstr.
                            XElement partDepElem = partialRoute.Descendants("itdPoint").Where(x => x.Attribute("usage").Value.Equals("departure")).FirstOrDefault();
                            Location departure = new Location(LocationType.STATION, int.Parse(partDepElem.Attribute("stopID").Value), partDepElem.Attribute("locality").Value, partDepElem.Attribute("name").Value);

                            XElement partDepTimeElem = partDepElem.Descendants("itdTime").FirstOrDefault();
                            XElement partepDateElem = partDepElem.Descendants("itdDate").FirstOrDefault();

                            DateTime partDepTime = new DateTime(int.Parse(partepDateElem.Attribute("year").Value), int.Parse(partepDateElem.Attribute("month").Value), int.Parse(partepDateElem.Attribute("day").Value),
                                int.Parse(partDepTimeElem.Attribute("hour").Value), int.Parse(partDepTimeElem.Attribute("minute").Value), 0);

                            // Arrival: Nürnberg, Gostenhof
                            XElement partArrElem = partialRoute.Descendants("itdPoint").Where(x => x.Attribute("usage").Value.Equals("arrival")).LastOrDefault();
                            Location arrival = new Location(LocationType.STATION, int.Parse(partArrElem.Attribute("stopID").Value), partArrElem.Attribute("locality").Value, partArrElem.Attribute("name").Value);

                            XElement partArrTimeElem = partArrElem.Descendants("itdTime").FirstOrDefault();
                            XElement partArrDateElem = partArrElem.Descendants("itdDate").FirstOrDefault();

                            DateTime partArrTime = new DateTime(int.Parse(partArrDateElem.Attribute("year").Value), int.Parse(partArrDateElem.Attribute("month").Value), int.Parse(partArrDateElem.Attribute("day").Value),
                                int.Parse(partArrTimeElem.Attribute("hour").Value) == 24 ? 0 : int.Parse(partArrTimeElem.Attribute("hour").Value), int.Parse(partArrTimeElem.Attribute("minute").Value), 0);

                            //if (!isFootWay)
                            parts.Add(new Connection.Trip(line, destination, partDepTime, "departurePos", departure, partArrTime, "arrivalPos", arrival, new List<Stop>(), new List<PTE.DTO.Point>()));
                            //else
                            //    parts.Add(new Connection.Trip.FootWay(timeMinute, departure, arrival));
                        }

                        try
                        {
                            // DEPARTURE
                            XElement departureElem = route.Descendants("itdPoint").Where(x => x.Attribute("usage").Value.Equals("departure")).FirstOrDefault();
                            Location from = new Location(LocationType.STATION, int.Parse(departureElem.Attribute("stopID").Value), departureElem.Attribute("locality").Value, departureElem.Attribute("name").Value);

                            XElement depTimeElem = departureElem.Descendants("itdTime").FirstOrDefault();
                            XElement depDateElem = departureElem.Descendants("itdDate").FirstOrDefault();

                            DateTime departureTime = new DateTime(int.Parse(depDateElem.Attribute("year").Value), int.Parse(depDateElem.Attribute("month").Value), int.Parse(depDateElem.Attribute("day").Value),
                                int.Parse(depTimeElem.Attribute("hour").Value), int.Parse(depTimeElem.Attribute("minute").Value), 0);

                            // ARRIVAL
                            XElement arrivalElem = route.Descendants("itdPoint").Where(x => x.Attribute("usage").Value.Equals("arrival")).LastOrDefault();
                            Location to = new Location(LocationType.STATION, int.Parse(arrivalElem.Attribute("stopID").Value), arrivalElem.Attribute("locality").Value, arrivalElem.Attribute("name").Value);

                            XElement arrTimeElem = arrivalElem.Descendants("itdTime").FirstOrDefault();
                            XElement arrDateElem = arrivalElem.Descendants("itdDate").FirstOrDefault();

                            DateTime arrivalTime = new DateTime(int.Parse(arrDateElem.Attribute("year").Value), int.Parse(arrDateElem.Attribute("month").Value), int.Parse(arrDateElem.Attribute("day").Value),
                                int.Parse(arrTimeElem.Attribute("hour").Value), int.Parse(arrTimeElem.Attribute("minute").Value), 0);

                            // LINIE
                            XElement motElem = route.Descendants("itdMeansOfTransport").FirstOrDefault();

                            string publicDuration = route.Attribute("publicDuration").Value;
                            connectionList.Add(new Connection(connectionIndex.ToString(), publicDuration, departureTime, arrivalTime, from, to, parts, new List<IFare>()));

                            connectionIndex++;
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Fehler im HandleConnectionsResponse", ex.InnerException);
                        }
                    }
                }
            }


            OnSearchConnectionsCompleted(new SearchConnectionsCompletedEventArgs(null, false, "UserState", connectionList));

            //if (connectionList.Count == 0)
            //{
            //    ResultTextBox.Dispatcher.BeginInvoke(
            //      new Action(
            //        delegate()
            //        {
            //            ResultTextBox.Text = ResultTextBox.Text + "\n\nKeine Verbindung gefunden.";
            //        }
            //    ));

            //    return;
            //}

            //foreach (Connection item in connectionList)
            //{
            //    ResultTextBox.Dispatcher.BeginInvoke(
            //      new Action(
            //        delegate()
            //        {
            //            ResultTextBox.Text = ResultTextBox.Text + "\n\n" + item.DepartureTime.ToString("HH:mm") + " -> " + item.ArrivalTime.ToString("HH:mm") + " (Dauer: " + item.PublicDuration + ")" + ":\n";

            //            foreach (Connection.Trip trip in item.Parts)
            //            {
            //                ResultTextBox.Text = ResultTextBox.Text + "\n" + trip.DepartureTime.ToString("HH:mm") + " - [" + trip.Line.Label + "] -> " + trip.Departure.Name + "<->"+ trip.Arrival.Name;
            //            }
            //        }
            //    ));

            //    System.Threading.Thread.Sleep(50);
            //}


            //ResultTextBox.Dispatcher.BeginInvoke(
            //  new Action(
            //    delegate()
            //    {
            //        ConnectionVisual.SetConnections(connectionList);
            //    }));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Handle the found stations response returned from the async request
        /// </summary>
        /// <param name="asyncResult"></param>
        private void AsyncResponseLoadStations(IAsyncResult asyncResult)  ///now this is background
        {
            // get the state information
            QueryUpdateState queryUpdateState = (QueryUpdateState)asyncResult.AsyncState;
            HttpWebRequest getStationsRequest = (HttpWebRequest)queryUpdateState.AsyncRequest;

            // end the async request
            queryUpdateState.AsyncResponse = (HttpWebResponse)getStationsRequest.EndGetResponse(asyncResult);

            Stream streamResult;

            try
            {
                // get the stream containing the response from the async call
                streamResult = queryUpdateState.AsyncResponse.GetResponseStream();

                // load the XML
                XElement xmlStationsResponse = XElement.Load(streamResult);
                XElement originElem = xmlStationsResponse.Descendants("itdOdv").Where(elem => elem.Attribute("usage").Value.Equals("origin")).FirstOrDefault();

                List<ItemViewModel> stations = new List<ItemViewModel>();

                foreach (var xmlStation in originElem.Descendants("odvNameElem"))
                {
                    if (xmlStation.HasAttributes)
                    {
                        var station = new ItemViewModel();
                        station.SelectionBorderThickness = new Thickness(0);
                        station.City = xmlStation.Attribute("locality").Value;
                        station.StationName = xmlStation.Attribute("objectName").Value;

                        Location loc = new Location(LocationType.STATION, int.Parse(xmlStation.Attribute("id").Value));
                        station.Location = loc;
                        //temp.ThumbNailImage = new BitmapImage(new Uri("Images/Haltestelle.gif"));

                        stations.Add(station);
                    }
                }

                OnSearchNearbyLocationsCompleted(new SearchLocationsCompletedEventArgs(null, false, "items", stations));
            }
            catch (FormatException fe)
            {
                throw new Exception("Fehler bei GetResponseStream()", fe.InnerException);
                // there was some kind of error processing the response from the web
                // additional error handling would normally be added here

            }

            //long applicationCurrentMemoryUsage = (long)DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage");
        }
Ejemplo n.º 7
0
        private QueryConnectionsResult QueryConnections(string uri, string xml)
        {
            if (xml.Contains("Your session has expired."))
                return new QueryConnectionsResult(QueryConnectionsResult.Status.SESSION_EXPIRED);

            XDocument xdocument;

            try
            {
                xdocument = XDocument.Parse(xml);
            }
            catch (NotSupportedException ex)
            {
                return new QueryConnectionsResult(QueryConnectionsResult.Status.SESSION_EXPIRED);
            }

            XElement itdRequestElement = xdocument.Element("itdRequest");
            if (itdRequestElement == null)
                throw new Exception("cannot find <itdRequest />");

            string sessionId = this.GetAttributeValue(itdRequestElement, "sessionID", "cannot find attribute sessionID of itdRequest");
            XElement itdTripRequestElement = Enumerable.FirstOrDefault<XElement>(xdocument.Descendants("itdTripRequest"));

            if (itdTripRequestElement == null)
                throw new Exception("cannot find <itdTripRequest />");

            string requestId = this.GetAttributeValue(itdTripRequestElement, "requestID", "cannot find attribute requestID of itdTripRequest");
            if (itdTripRequestElement.Element("itdMessage") != null && int.Parse(itdTripRequestElement.Element("itdMessage").Attribute("code").Value) == -4000)
                return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS);

            List<Location> ambiguousFrom = null;
            List<Location> ambiguousTo = null;
            List<Location> ambiguousVia = null;
            Location from = null;
            Location via = null;
            Location to = null;

            foreach (XElement itdOdvElement in itdTripRequestElement.Elements("itdOdv"))
            {
                string usage = this.GetAttributeValue(itdOdvElement, "usage", "cannot find attribute usage of itdOdv");
                string defaultPlace = this.ProcessItdOdvPlace(itdOdvElement);
                XElement itdOdvNameElement = itdOdvElement.Element("itdOdvName");

                if (itdOdvNameElement == null)
                    throw new Exception("cannot find <itdOdvName /> inside " + usage);

                string itdOdvNameState = this.GetAttributeValue(itdOdvNameElement, "state", "cannot find attribute state of itdOdvName");
                if ("list".Equals(itdOdvNameState))
                {
                    if ("origin".Equals(usage))
                    {
                        ambiguousFrom = new List<Location>();

                        foreach (XElement odvNameElement in itdOdvNameElement.Elements("odvNameElem"))
                        {
                            ambiguousFrom.Add(this.ProcessOdvNameElem(odvNameElement, defaultPlace));
                        }
                    }
                    else if ("via".Equals(usage))
                    {
                        ambiguousVia = new List<Location>();

                        foreach (XElement odvNameElement in itdOdvNameElement.Elements("odvNameElem"))
                        {
                            ambiguousVia.Add(this.ProcessOdvNameElem(odvNameElement, defaultPlace));
                        }
                    }
                    else
                    {
                        if (!"destination".Equals(usage))
                            throw new Exception("unknown usage: " + usage);

                        ambiguousTo = new List<Location>();

                        foreach (XElement odvNameElement in itdOdvNameElement.Elements("odvNameElem"))
                        {
                            ambiguousTo.Add(this.ProcessOdvNameElem(odvNameElement, defaultPlace));
                        }
                    }
                }
                else if ("identified".Equals(itdOdvNameState))
                {
                    XElement odvNameElement = itdOdvNameElement.Element("odvNameElem");

                    if (odvNameElement == null)
                        throw new Exception("cannot find <odvNameElem /> inside " + usage);

                    if ("origin".Equals(usage))
                    {
                        from = this.ProcessOdvNameElem(odvNameElement, defaultPlace);
                    }
                    else if ("via".Equals(usage))
                    {
                        via = this.ProcessOdvNameElem(odvNameElement, defaultPlace);
                    }
                    else
                    {
                        if (!"destination".Equals(usage))
                            throw new Exception("unknown usage: " + usage);

                        to = this.ProcessOdvNameElem(odvNameElement, defaultPlace);
                    }
                }
            }

            if (ambiguousFrom != null || ambiguousTo != null || ambiguousVia != null)
                return new QueryConnectionsResult(ambiguousFrom, ambiguousVia, ambiguousTo);

            XElement itdTripDateTimeElement = itdTripRequestElement.Element("itdTripDateTime");
            if (itdTripDateTimeElement == null)
                throw new Exception("cannot find <itdTripDateTime />");

            XElement itdDateTimeElement = itdTripDateTimeElement.Element("itdDateTime");
            if (itdDateTimeElement == null)
                throw new Exception("cannot find <itdDateTime />");

            XElement itdDateElement = itdDateTimeElement.Element("itdDate");
            if (itdDateElement == null)
                throw new Exception("cannot find <itdDate />");

            XElement itdMessageElement = itdDateElement.Element("itdMessage");
            if (itdMessageElement != null && itdMessageElement.Value.Equals("invalid date"))
                return new QueryConnectionsResult(QueryConnectionsResult.Status.INVALID_DATE);

            DateTime dateTime = new DateTime();
            List<Connection> connections = new List<Connection>();

            XElement itdRouteListElement = Enumerable.FirstOrDefault(itdTripRequestElement.Descendants("itdRouteList"));
            if (itdRouteListElement == null)
                return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS);

            foreach (XElement itdRouteElement in itdRouteListElement.Elements("itdRoute"))
            {
                string routeTripIndex = (this.GetAttributeValueOrNull(itdRouteElement, "routeIndex") ?? "") + "-" + (this.GetAttributeValueOrNull(itdRouteElement, "routeTripIndex") ?? "");
                List<Connection.Part> parts = new List<Connection.Part>();
                Location departureLocation = (Location)null;
                DateTime? departureTime = new DateTime?();
                Location arrivalLocation = (Location)null;
                DateTime? arrivalTime = new DateTime?();

                foreach (XElement itdPartialRouteElement in itdRouteElement.Descendants("itdPartialRoute"))
                {
                    if (itdPartialRouteElement.Elements("itdPoint").Count() != 2)
                        throw new Exception("Departure and Arrival points expected in route");

                    XElement itdPointDeparture = Enumerable.ToList(itdPartialRouteElement.Elements("itdPoint"))[0];
                    XElement itdPointArrival = Enumerable.ToList(itdPartialRouteElement.Elements("itdPoint"))[1];
                    if (!"departure".Equals(this.GetAttributeValue(itdPointDeparture, "usage", "cannot find attribute usage of itdPointDeparture")))
                        throw new Exception("first point should be departure");

                    int departureStopId = int.Parse(this.GetAttributeValue(itdPointDeparture, "stopID", "cannot find attribute stopID of itdPointDeparture"));
                    string departureName = this.NormalizeLocationName(this.GetAttributeValue(itdPointDeparture, "name", "cannot find attribute name of itdPointDeparture"));
                    int latDeparture;
                    int lonDeparture;

                    if ("WGS84".Equals(this.GetAttributeValueOrNull(itdPointDeparture, "mapName")))
                    {
                        latDeparture = this.ParseLatLon(this.GetAttributeValue(itdPointDeparture, "y", "cannot find attribute y of itdPointDeparture"));
                        lonDeparture = this.ParseLatLon(this.GetAttributeValue(itdPointDeparture, "x", "cannot find attribute x of itdPointDeparture"));
                    }
                    else
                    {
                        latDeparture = 0;
                        lonDeparture = 0;
                    }

                    Location departure = new Location(LocationType.STATION, departureStopId, latDeparture, lonDeparture, (string)null, departureName);
                    if (departureLocation == null)
                        departureLocation = departure;

                    string departurePosition = AbstractEfaProvider.NormalizePlatform(
                        this.GetAttributeValue(itdPointDeparture, "platform", "cannot find attribute platform of itdPointDeparture"), 
                        this.GetAttributeValue(itdPointDeparture, "platformName", "cannot find attribute platformName of itdPointDeparture"));
                            
                    XElement itdDateTimeDeparture = itdPointDeparture.Element("itdDateTime");
                    if (itdDateTimeDeparture == null)
                        throw new Exception("cannot find <itdDateTime /> in itdPointDeparture");

                    DateTime depTime = this.ProcessItdDateTime(itdDateTimeDeparture);
                    if (!departureTime.HasValue)
                        departureTime = new DateTime?(depTime);

                    XElement itdDateTimeTargetDeparture = itdPointDeparture.Element("itdDateTimeTarget");

                    if (itdDateTimeTargetDeparture != null)
                        dateTime = this.ProcessItdDateTime(itdDateTimeTargetDeparture);

                    if (!"arrival".Equals(this.GetAttributeValue(itdPointArrival, "usage", "cannot find attribute usage of itdPointArrival")))
                        throw new Exception("second point should be arrival");

                    int arrivalStopId = int.Parse(this.GetAttributeValue(itdPointArrival, "stopID", "cannot find attribute stopID of itdPointArrival"));
                    string arrivalName = this.NormalizeLocationName(this.GetAttributeValue(itdPointArrival, "name", "cannot find attribute name of itdPointArrival"));
                    int latArrival;
                    int lonArrival;

                    if ("WGS84".Equals(this.GetAttributeValueOrNull(itdPointArrival, "mapName")))
                    {
                        latArrival = this.ParseLatLon(this.GetAttributeValue(itdPointArrival, "y", "cannot find attribute y of itdPointArrival"));
                        lonArrival = this.ParseLatLon(this.GetAttributeValue(itdPointArrival, "x", "cannot find attribute x of itdPointArrival"));
                    }
                    else
                    {
                        latArrival = 0;
                        lonArrival = 0;
                    }

                    Location arrival = new Location(LocationType.STATION, arrivalStopId, latArrival, lonArrival, (string)null, arrivalName);
                    arrivalLocation = arrival;

                    string arrivalPosition = AbstractEfaProvider.NormalizePlatform(this.GetAttributeValue(itdPointArrival, "platform", "cannot find attribute platform of itdPointArrival"), 
                        this.GetAttributeValue(itdPointArrival, "platformName", "cannot find attribute platformName of itdPointArrival"));

                    XElement itdDateTimeArrival = itdPointArrival.Element("itdDateTime");
                    if (itdDateTimeArrival == null)
                        throw new Exception("cannot find <itdDateTime /> in itdPointArrival");

                    DateTime arrTime = this.ProcessItdDateTime(itdDateTimeArrival);
                    arrivalTime = new DateTime?(arrTime);

                    XElement itdDateTimeTargetArrival = itdPointArrival.Element("itdDateTimeTarget");
                    if (itdDateTimeTargetArrival != null)
                        dateTime = this.ProcessItdDateTime(itdDateTimeTargetArrival);

                    XElement itdMeansOfTransport = itdPartialRouteElement.Element("itdMeansOfTransport");
                    if (itdMeansOfTransport == null)
                        throw new Exception("cannot find <itdMeansOfTransport /> in itdPartialRoute");

                    string productName = this.GetAttributeValueOrNull(itdMeansOfTransport, "productName");
                    if (productName.Equals("Fussweg") || productName.Equals("Taxi"))
                    {
                        int minutes = (arrTime - depTime).Minutes;
                        List<Point> path = null;

                        XElement itdPathCoordinates = itdMeansOfTransport.Element("itdPathCoordinates");
                        if (itdPathCoordinates != null)
                            path = this.ProcessItdPathCoordinates(itdPathCoordinates);

                        if (parts.Count > 0 && parts[parts.Count - 1] is Connection.Footway)
                        {
                            Connection.Footway footway = (Connection.Footway)parts[parts.Count - 1];
                            parts.RemoveAt(parts.Count - 1);
                            if (path != null && footway.path != null)
                                footway.path.AddRange(path);
                            parts.Add((Connection.Part)new Connection.Footway(footway.Min + minutes, footway.Departure, footway.DepartureTime, arrival, arrTime, footway.path));
                        }
                        else
                            parts.Add((Connection.Part)new Connection.Footway(minutes, departure, depTime, arrival, arrTime, path));
                    }
                    else if ("gesicherter Anschluss".Equals(productName))
                    {
                        parts.Add((Connection.Part)new Connection.SpecialTripPart(AppResources.GesicherterAnschluss, departure, arrival, (List<Point>)null));
                    }
                    else if ("nicht umsteigen".Equals(productName))
                    {
                        parts.Add((Connection.Part)new Connection.SpecialTripPart(AppResources.NichtUmsteigen, departure, arrival, (List<Point>)null));
                    }
                    else
                    {
                        string motDestId = this.GetAttributeValue(itdMeansOfTransport, "destID", "cannot find attribute destID of itdMeansOfTransport");
                        string motDestination = this.NormalizeLocationName(this.GetAttributeValue(itdMeansOfTransport, "destination", "cannot find attribute destination of itdMeansOfTransport"));

                        Location destination = motDestId.Length > 0 ?
                            new Location(LocationType.STATION, int.Parse(motDestId), (string)null, motDestination) :
                            new Location(LocationType.ANY, 0, (string)null, motDestination);

                        Line line = new Line(!"AST".Equals(this.GetAttributeValue(itdMeansOfTransport, "symbol", "cannot find attribute symbol of itdMeansOfTransport")) ?
                            this.ParseLine(this.GetAttributeValue(itdMeansOfTransport, "motType", "cannot find attribute motType of itdMeansOfTransport"),
                            this.GetAttributeValue(itdMeansOfTransport, "shortname", "cannot find attribute shortname of itdMeansOfTransport"),
                            this.GetAttributeValue(itdMeansOfTransport, "name", "cannot find attribute name of itdMeansOfTransport"), null) : "BAST");

                        List<Stop> intermediateStops = null;
                        XElement itdStopSequence = itdMeansOfTransport.Element("itdStopSeq");
                        if (itdStopSequence != null)
                        {
                            intermediateStops = new List<Stop>();

                            foreach (XElement itdPoint in itdStopSequence.Elements("itdPoint"))
                            {
                                int itdPointStopId = int.Parse(this.GetAttributeValue(itdPoint, "stopID", "cannot find attribute stopID of itdPoint"));
                                string itdPointName = this.NormalizeLocationName(this.GetAttributeValue(itdPoint, "name", "cannot find attribute name of itdPoint"));
                                int latStop;
                                int lonStop;

                                if ("WGS84".Equals(this.GetAttributeValue(itdPoint, "mapName", "cannot find attribute mapName of itdPoint")))
                                {
                                    latStop = int.Parse(this.GetAttributeValue(itdPoint, "y", "cannot find attribute y of itdPoint"));
                                    lonStop = int.Parse(this.GetAttributeValue(itdPoint, "x", "cannot find attribute x of itdPoint"));
                                }
                                else
                                {
                                    latStop = 0;
                                    lonStop = 0;
                                }

                                string position = AbstractEfaProvider.NormalizePlatform(this.GetAttributeValue(itdPoint, "platform", "cannot find attribute platform of itdPoint"),
                                    this.GetAttributeValue(itdPoint, "platformName", "cannot find attribute platformName of itdPoint"));

                                XElement itdDateTime = itdPoint.Element("itdDateTime");
                                if (itdDateTime != null)
                                {
                                    DateTime time = this.ProcessItdDateTime(itdDateTime);
                                    intermediateStops.Add(new Stop(new Location(LocationType.STATION, itdPointStopId, latStop, lonStop, null, itdPointName), position, time));
                                }
                            }

                            int count = intermediateStops.Count;
                            if (count >= 2)
                            {
                                if (intermediateStops[count - 1].location.Id != arrivalStopId)
                                    throw new Exception();

                                intermediateStops.RemoveAt(count - 1);

                                if (intermediateStops[0].location.Id != departureStopId)
                                    throw new Exception();

                                intermediateStops.RemoveAt(0);
                            }
                        }

                        List<Point> path = null;

                        XElement itdPathCoordinates = itdMeansOfTransport.Element("itdPathCoordinates");
                        if (itdPathCoordinates != null)
                            path = this.ProcessItdPathCoordinates(itdPathCoordinates);

                        parts.Add(new Connection.Trip(line, destination, depTime, departurePosition, departure, arrTime, arrivalPosition, arrival, intermediateStops, path));
                    }
                }

                List<IFare> listOfFare = new List<IFare>();
                XElement itdFareElement = Enumerable.FirstOrDefault<XElement>(itdTripRequestElement.Descendants("itdFare"));

                if (itdFareElement != null)
                {
                    XElement itdSingleTicketElement = Enumerable.FirstOrDefault<XElement>(itdFareElement.Descendants("itdSingleTicket"));
                    if (itdSingleTicketElement != null)
                    {
                        string network = this.GetAttributeValueOrNull(itdSingleTicketElement, "net");
                        string currency = this.GetAttributeValueOrNull(itdSingleTicketElement, "currency");
                        string adultPrice = this.GetAttributeValueOrNull(itdSingleTicketElement, "fareAdult");
                        string childPrice = this.GetAttributeValueOrNull(itdSingleTicketElement, "fareChild");
                        string unitName = this.GetAttributeValueOrNull(itdSingleTicketElement, "unitName");
                        string adultUnits = this.GetAttributeValueOrNull(itdSingleTicketElement, "unitsAdult").Trim();
                        string childUnits = this.GetAttributeValueOrNull(itdSingleTicketElement, "unitsChild").Trim();
                        string str = (string)null;

                        if (itdSingleTicketElement.HasElements)
                        {
                            XElement itdGenericTicketElement = (from ticket in itdSingleTicketElement.Descendants("itdGenericTicket")
                                                               where ticket.Element("ticket") != null && ticket.Element("ticket").Value == "MVV_NRTOUCHEDZONES"
                                                               select ticket).FirstOrDefault();

                            if (itdGenericTicketElement != null)
                            {
                                XElement itdGenericTicket = itdGenericTicketElement.Element("value");
                                if (itdGenericTicket != null && !string.IsNullOrEmpty(itdGenericTicket.Value))
                                    str = itdGenericTicket.Value.Trim();
                            }
                        }
                            
                        if (!string.IsNullOrEmpty(adultPrice))
                        {
                            listOfFare.Add(new Fare(network, 
                                                    Fare.SINGLE_TICKET, 
                                                    currency, 
                                                    float.Parse(adultPrice, (IFormatProvider)this._nfi), 
                                                    float.Parse(childPrice, (IFormatProvider)this._nfi), 
                                                    "Zonen", str, str));
                        }
                            
                        if (itdSingleTicketElement.HasElements)
                        {
                            foreach (XElement itdGenericTicketGroup in itdSingleTicketElement.Descendants("itdGenericTicketGroup"))
                            {
                                Fare fare = this.ProcessItdGenericTicketGroup(itdGenericTicketGroup, network, currency, unitName, adultUnits, childUnits);
                                if (fare != null)
                                    listOfFare.Add(fare);
                            }
                        }
                    }

                    XElement itdCommuterFares = ((XContainer)itdFareElement).Element("itdCommuterFares");
                    if (itdCommuterFares != null)
                    {
                        float weekAdult = float.Parse(this.GetAttributeValue(itdCommuterFares, "weekAdult", "Cannot find attribute weekAdult on itdCommuterFares"), this._nfi);
                        float weekChild = float.Parse(this.GetAttributeValue(itdCommuterFares, "weekChild", "Cannot find attribute weekChild on itdCommuterFares"), this._nfi);
                        float monthAdult = float.Parse(this.GetAttributeValue(itdCommuterFares, "monthAdult", "Cannot find attribute monthAdult on itdCommuterFares"), this._nfi);
                        float monthChild = float.Parse(this.GetAttributeValue(itdCommuterFares, "monthChild", "Cannot find attribute monthChild on itdCommuterFares"), this._nfi);
                        float weekEducation = float.Parse(this.GetAttributeValue(itdCommuterFares, "weekEducation", "Cannot find attribute weekEducation on itdCommuterFares"), this._nfi);
                        float monthEducation = float.Parse(this.GetAttributeValue(itdCommuterFares, "monthEducation", "Cannot find attribute monthEducation on itdCommuterFares"), this._nfi);
                        
                        XElement itdTariffzones = itdFareElement.Element("itdTariffzones");
                        List<int> zonesList = new List<int>();
                        string zonesString = null;

                        if (itdTariffzones != null)
                        {
                            foreach (XElement zoneElem in itdTariffzones.Descendants("zoneElem"))
                            {
                                zonesList.Add(int.Parse(zoneElem.Value));
                            }
                            zonesList.Sort();
                            if (zonesList.Count > 1)
                            {
                                zonesString = zonesList[0].ToString() 
                                    + " - " + zonesList[zonesList.Count - 1].ToString() 
                                    + " (" + (1 + zonesList[zonesList.Count - 1] - zonesList[0]).ToString() 
                                    + " " + AppResources.Rings + ")";
                            }
                            else if (zonesList.Count > 0)
                                zonesString = zonesList[0].ToString() + " (1 " + AppResources.Ring + ")";
                        }
                        CommuterFare commuterFare = new CommuterFare(weekAdult, weekChild, weekEducation, monthAdult, monthChild, monthEducation, zonesString);
                        listOfFare.Add(commuterFare);
                    }
                }
                connections.Add(new Connection(routeTripIndex, uri, departureTime.Value, arrivalTime.Value, departureLocation, arrivalLocation, parts, listOfFare.Count <= 0 ? null : listOfFare));
            }
            return new QueryConnectionsResult(uri, from, via, to, this.CommandLink(sessionId, requestId, "tripPrev"), this.CommandLink(sessionId, requestId, "tripNext"), connections);
        }
Ejemplo n.º 8
0
 public void QueryConnections(Action<QueryConnectionsResult> callback, Location from, Location via, Location to, DateTime date, bool dep, string products, WalkSpeed walkSpeed, bool forceReload)
 {
     string uri = this.XsltTripRequest2Uri(from, via, to, date, dep, products, walkSpeed, forceReload);
     new FileDownloader().Download(uri, (Action<string>)(result =>
     {
         if (string.IsNullOrEmpty(result))
         {
             if (callback == null)
                 return;
             callback((QueryConnectionsResult)null);
         }
         else
             AsyncHelper.SafeExecute((Action)(() =>
             {
                 try
                 {
                     QueryConnectionsResult queryConnectionsResult = this.QueryConnections(uri, result);
                     if (callback == null)
                         return;
                     callback(queryConnectionsResult);
                 }
                 catch (Exception ex)
                 {
                     throw ex;
                 }
             }));
     }), false);
 }
Ejemplo n.º 9
0
        private string XsltTripRequest2Uri(Location from, Location via, Location to, DateTime date, bool dep, string products, WalkSpeed walkSpeed, bool forceReload)
        {
            string dateFormat = "yyyyMMdd";
            string timeFormat = "HHmm";
            StringBuilder uri = new StringBuilder(this._apiBase);
            uri.Append("XSLT_TRIP_REQUEST2");
            this.AppendCommonRequestParams(uri);
            uri.Append("&sessionID=0");
            uri.Append("&requestID=0");
            uri.Append("&language=de");

            if (forceReload)
                uri.Append("&guid=" + Guid.NewGuid().ToString());

            AbstractEfaProvider.AppendCommonXsltTripRequest2Params(uri);
            this.AppendLocation(uri, from, "origin");
            this.AppendLocation(uri, to, "destination");

            if (via != null)
                this.AppendLocation(uri, via, "via");

            uri.Append("&itdDate=").Append(Uri.EscapeUriString(date.ToString(dateFormat)));
            uri.Append("&itdTime=").Append(Uri.EscapeUriString(date.ToString(timeFormat)));
            uri.Append("&itdTripDateTimeDepArr=").Append(dep ? "dep" : "arr");
            uri.Append("&ptOptionsActive=1");
            uri.Append("&changeSpeed=").Append(AbstractEfaProvider.WALKSPEED_MAP[walkSpeed]);

            if (products != null)
            {
                uri.Append("&includedMeans=checkbox");
                bool flag = false;
                foreach (char ch in products.ToCharArray())
                {
                    if ((int)ch == 73 || (int)ch == 82)
                    {
                        uri.Append("&inclMOT_0=on");
                        if ((int)ch == 73)
                            flag = true;
                    }
                    if ((int)ch == 83)
                        uri.Append("&inclMOT_1=on");
                    if ((int)ch == 85)
                        uri.Append("&inclMOT_2=on");
                    if ((int)ch == 84)
                        uri.Append("&inclMOT_3=on&inclMOT_4=on");
                    if ((int)ch == 66)
                        uri.Append("&inclMOT_5=on&inclMOT_6=on&inclMOT_7=on");
                    if ((int)ch == 80)
                        uri.Append("&inclMOT_10=on");
                    if ((int)ch == 70)
                        uri.Append("&inclMOT_9=on");
                    if ((int)ch == 67)
                        uri.Append("&inclMOT_8=on");
                    uri.Append("&inclMOT_11=on");
                }
                if (!flag)
                    uri.Append("&lineRestriction=403");
            }
            uri.Append("&locationServerActive=1");
            uri.Append("&useRealtime=1");
            uri.Append("&useProxFootSearch=1");

            return uri.ToString();
        }
Ejemplo n.º 10
0
 protected static string LocationValue(Location location)
 {
     string str = string.Empty;
     return AbstractEfaProvider.EscapeUmlauts(location.Type != LocationType.STATION && location.Type != LocationType.POI || !location.HasId() ? 
                                              location.Name : location.Id.ToString());
 }
Ejemplo n.º 11
0
 protected static string LocationTypeValue(Location location)
 {
     LocationType type = location.Type;
     switch (type)
     {
         case LocationType.STATION:
             return "stop";
         case LocationType.ADDRESS:
             return "any";
         case LocationType.POI:
             return "poi";
         case LocationType.ANY:
             return "any";
         default:
             throw new ArgumentException(type.ToString());
     }
 }
Ejemplo n.º 12
0
 private void AppendLocation(StringBuilder uri, Location location, string paramSuffix)
 {
     if (this._canAcceptPoiID && location.Type == LocationType.POI && location.HasId())
     {
         uri.Append("&type_").Append(paramSuffix).Append("=poiID");
         uri.Append("&name_").Append(paramSuffix).Append("=").Append(location.Id);
     }
     else if ((location.Type == LocationType.POI || location.Type == LocationType.ADDRESS) && location.HasLocation())
     {
         NumberFormatInfo numberFormatInfo = new NumberFormatInfo();
         numberFormatInfo.NumberDecimalSeparator = ".";
         uri.Append("&type_").Append(paramSuffix).Append("=coord")
             .Append("&name_").Append(paramSuffix).Append("=")
             .Append(string.Format(numberFormatInfo, "{0:0.######}:{1:0.######}", location.Lon / 1000000.0, location.Lat / 1000000.0 ))
             .Append(":WGS84");
     }
     else
     {
         uri.Append("&type_").Append(paramSuffix).Append("=").Append(AbstractEfaProvider.LocationTypeValue(location));
         uri.Append("&name_").Append(paramSuffix).Append("=").Append(Uri.EscapeUriString(AbstractEfaProvider.LocationValue(location)));
     }
 }
Ejemplo n.º 13
-1
 public QueryConnectionsResult(QueryConnectionsResult.Status status)
 {
     this.status = status;
     this.ambiguousFrom = (List<Location>)null;
     this.ambiguousVia = (List<Location>)null;
     this.ambiguousTo = (List<Location>)null;
     this.queryUri = (string)null;
     this.from = (Location)null;
     this.via = (Location)null;
     this.to = (Location)null;
     this.CommandEarlier = (string)null;
     this.connections = (List<Connection>)null;
 }