예제 #1
0
        public static List<Flight> ParseJson(string jsonString)
        {
            List<Flight> lstFlight = new List<Flight>();

            try
            {
                if (!jsonString.StartsWith("{"))
                {
                    int findIndex = jsonString.IndexOf("{");
                    if (findIndex > 0)
                        jsonString = jsonString.Remove(0, findIndex);
                }

                var objReturnResult = JsonConvert.DeserializeObject<ReturnResult>(jsonString);
                if (objReturnResult.IsSucceed)
                {
                    if (objReturnResult.FlightRoutes.Count > 0)
                    {
                        FlightRoute flightRoute = objReturnResult.FlightRoutes[0];
                        foreach (var flightInfo in flightRoute.FlightsList)
                        {
                            Flight f = new Flight();
                            f.C_DateSource = "CTRIP API";
                            f.C_From = flightRoute.DCityName;
                            f.C_To = flightRoute.ACityName;
                            f.C_Departure = flightRoute.DDate;
                            f.C_FlightNo = flightInfo.Flight;
                            f.C_Airline = flightInfo.AirlineCode;
                            f.C_DEPTIME = flightInfo.TakeOffTime;
                            f.C_ARRTIME = flightInfo.ArriveTime;
                            FlightClass firstFlightClass = flightInfo.FlightClassList.Find(ff => ff.Class.Equals("F", StringComparison.CurrentCultureIgnoreCase));
                            if (firstFlightClass != null)
                                f.C_FirstClass = Convert.ToDecimal(firstFlightClass.Price);
                            FlightClass economyFlightClass = flightInfo.FlightClassList.Find(ff => ff.Class.Equals("Y", StringComparison.CurrentCultureIgnoreCase));
                            if (economyFlightClass != null)
                                f.C_Economy = Convert.ToDecimal(economyFlightClass.Price);
                            lstFlight.Add(f);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.LogErr(ex);
            }

            return lstFlight;
        }
        private List<Flight> WS_Get(City fromCity, City toCity, string departDate)
        {
            List<Flight> lstFlight = new List<Flight>();
            DateTime dtDepart = DateTime.Parse(departDate);
            AirTicketQuery.DomesticAirline.DomesticAirline wsAirLine = new DomesticAirline.DomesticAirline();
            DataSet dsFlight = wsAirLine.getDomesticAirlinesTime(fromCity.C_NAME, toCity.C_NAME, dtDepart.ToString("yyyy-MM-dd"), string.Empty);
            foreach (DataRow dr in dsFlight.Tables[0].Rows)
            {
                Flight f = new Flight();
                f.C_DateSource = "webxml";
                f.C_From = fromCity.C_NAME;
                f.C_To = toCity.C_NAME;
                f.C_Departure = departDate;
                f.C_Airline = dr["Company"].ToString();
                f.C_FlightNo = dr["AirlineCode"].ToString();
                f.C_DEPTIME = dr["StartTime"].ToString();
                f.C_ARRTIME = dr["ArriveTime"].ToString();
                f.C_Remark = string.Format("出发机场:{0}->到达机场:{1}->机型:{2}->经停:{3}->飞行周期(星期):{4}",
                    dr["StartDrome"], dr["ArriveDrome"], dr["Mode"], dr["AirlineStop"], dr["Week"]);
                lstFlight.Add(f);
            }

            return lstFlight;
        }
        private List<Flight> QUNAR_Get(City fromCity, City toCity, string departDate)
        {
            List<Flight> lstFlight = new List<Flight>();
            DateTime dtDepart = DateTime.Parse(departDate);
            ////http://flight.qunar.com/site/oneway_list.htm?searchDepartureAirport=%E5%B9%BF%E5%B7%9E&searchArrivalAirport=%E5%8C%97%E4%BA%AC&searchDepartureTime=2015-11-03&searchArrivalTime=2015-11-03&nextNDays=0&startSearch=true&fromCode=CAN&toCode=BJS&from=qunarindex&lowestPrice=null
            string strUrl = string.Format("http://flight.qunar.com/site/oneway_list.htm?searchDepartureAirport={0}&searchArrivalAirport={1}&searchDepartureTime={2}&searchArrivalTime=2015-11-03&nextNDays=0&startSearch=true&fromCode=CAN&toCode=BJS&from=qunarindex&lowestPrice=null",
                 Server.UrlEncode(fromCity.C_NAME), Server.UrlEncode(toCity.C_NAME), dtDepart.ToString("yyyy-MM-dd"));
            string downloadStr = string.Empty;
            try
            {
                Thread thread = new Thread(delegate()
                {
                    var p = new PageSnatch();
                    downloadStr = p.Navigate(strUrl, 50, "hdivResultPanel");
                });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                thread.Join();
            }
            catch (Exception ex) { throw ex; }

            HtmlDocument htmlPage = new HtmlDocument();
            htmlPage.LoadHtml(downloadStr);
            HtmlNode docNode = htmlPage.DocumentNode;
            HtmlNodeCollection findChildNodes = docNode.ChildNodes;
            if (findChildNodes.Count == 1)
            {
                if (findChildNodes[0].Id.ToUpper().Equals("HDIVRESULTPANEL"))
                    findChildNodes = docNode.ChildNodes[0].ChildNodes;
            }

            foreach (HtmlNode childNode in findChildNodes)
            {
                if (childNode.Id.ToUpper().StartsWith("ITEMBARXI"))
                {
                    Flight f = new Flight();
                    f.C_DateSource = "QUNAR";
                    f.C_From = fromCity.C_NAME;
                    f.C_To = toCity.C_NAME;
                    f.C_Departure = departDate;
                    StringBuilder sbOtherInfo = new StringBuilder();
                    if (this.GetHtmlNodeAttributeVal(childNode, "div/div", 1, 0).Equals("c1"))
                    {
                        HtmlNode checkNode = this.GetHtmlNode(childNode, "div/div", 1);
                        f.C_Airline = this.GetInnerText(checkNode.SelectSingleNode("div[@class='vlc-wp']/div[@class='vlc-con']/div[@class='air-wp']/div[@class='air-row']/div[@class='a-name']"));
                        f.C_FlightNo = this.GetInnerText(checkNode.SelectSingleNode("div[@class='vlc-wp']/div[@class='vlc-con']/div[@class='air-wp']/div[@class='air-row']/div[@class='a-model']/span"));
                    }

                    if (this.GetHtmlNodeAttributeVal(childNode, "div/div", 2, 0).Equals("c2"))
                    {
                        HtmlNode checkNode = this.GetHtmlNode(childNode, "div/div", 2);
                        f.C_DEPTIME = this.GetInnerText(checkNode.SelectSingleNode("div[@class='a-dep-time']"));
                        string depAirPort = this.GetInnerText(checkNode.SelectSingleNode("div[@class='a-dep-airport']"));
                        sbOtherInfo.AppendFormat("departAirPort:{0};", depAirPort);
                    }

                    if (this.GetHtmlNodeAttributeVal(childNode, "div/div", 3, 0).Equals("c3"))
                    {
                        HtmlNode checkNode = this.GetHtmlNode(childNode, "div/div", 3);
                        f.C_TotalTime = this.GetInnerText(checkNode.SelectSingleNode("div[@class='a-zh-wp']"));
                    }

                    if (this.GetHtmlNodeAttributeVal(childNode, "div/div", 4, 0).Equals("c4"))
                    {
                        HtmlNode checkNode = this.GetHtmlNode(childNode, "div/div", 4);
                        f.C_ARRTIME = this.GetInnerText(checkNode.SelectSingleNode("div[@class='a-arr-time']"));
                        string arrAirPort = this.GetInnerText(checkNode.SelectSingleNode("div[@class='a-arr-airport']"));
                        sbOtherInfo.AppendFormat("arriveAirPort:{0};", arrAirPort);
                    }

                    if (this.GetHtmlNodeAttributeVal(childNode, ("div/div"), 7, 0).Equals("c7"))
                    {
                        HtmlNode findNode = this.GetHtmlNode(this.GetHtmlNode(childNode, "div/div", 7), "div/div", 0);

                        if (findNode != null && findNode.ChildNodes.Count > 1)
                        {
                            HtmlNode mainPriceNode = findNode.ChildNodes[1];
                            HtmlNode node7 = this.GetHtmlNode(childNode, "div/div", 7);
                            if (node7 != null && node7.SelectNodes("div/div").Count > 1)
                            {
                                if (node7.SelectNodes("div/div")[1].ChildNodes.Count > 1)
                                    mainPriceNode = node7.SelectNodes("div/div")[1].ChildNodes[1];
                            }
                            if (mainPriceNode.Attributes["Style"] != null)
                            {
                                SortedList<string, string> lstPrice = new SortedList<string, string>();
                                if (mainPriceNode.SelectNodes("em").Count == 1)
                                {
                                    HtmlNode calcutePriceNode = mainPriceNode.SelectSingleNode("em");
                                    foreach (HtmlNode priceNode_b in calcutePriceNode.SelectNodes("b"))
                                    {
                                        if (priceNode_b.ChildNodes.Count > 1)
                                        {
                                            string styleValue = priceNode_b.Attributes["style"].Value;
                                            string style_LeftValue = styleValue.Split(new char[] { ';' })[1].ToLower().Replace("left: -", string.Empty).Replace("px", string.Empty).Trim();
                                            int outLeftPX = 0;
                                            if (int.TryParse(style_LeftValue, out outLeftPX))
                                            {
                                                foreach (HtmlNode detialPriceNode in priceNode_b.ChildNodes)
                                                {
                                                    string key = string.Format("left:-{0}px", outLeftPX);

                                                    lstPrice.Add(key, this.GetInnerText(detialPriceNode));
                                                    outLeftPX -= 16;
                                                }
                                            }
                                            else
                                            {
                                                lstPrice.Add("left:-16px", this.GetInnerText(priceNode_b.LastChild));
                                            }
                                        }
                                        else
                                        {
                                            string styleValue = priceNode_b.Attributes["style"].Value.ToLower().Replace(" ", string.Empty);
                                            if (lstPrice.ContainsKey(styleValue))
                                                lstPrice[styleValue] = this.GetInnerText(priceNode_b);
                                            else
                                                lstPrice.Add(styleValue, this.GetInnerText(priceNode_b));
                                        }
                                    }
                                }

                                if (lstPrice.Count > 0)
                                {
                                    decimal price = 0;
                                    int i = 1;
                                    foreach (var itmPrice in lstPrice)
                                    {
                                        price += Convert.ToInt16(itmPrice.Value) * i;
                                        i *= 10;
                                    }

                                    f.C_Price = price;
                                }
                            }
                        }
                    }

                    f.C_Remark = sbOtherInfo.ToString();
                    lstFlight.Add(f);
                }
            }

            return lstFlight;
        }
        private List<Flight> CSAIR_Get(City fromCity, City toCity, string departDate)
        {
            // http://b2c.csair.com/B2C40/detail-SHACAN-20151211-1-0-0-0-1-0-0-0-1-0.g2c
            List<Flight> lstFlight = new List<Flight>();
            DateTime dtDepart = DateTime.Parse(departDate);
            string strUrl = string.Format("http://b2c.csair.com/B2C40/detail-{0}{1}-{2}-1-0-0-0-1-0-0-0-1-0.g2c",
                fromCity.C_CODE, toCity.C_CODE, dtDepart.ToString("yyyyMMdd"));
            XmlDocument doc = new XmlDocument();
            doc.Load(strUrl);
            XmlHelper xmlHelper = new XmlHelper(doc);
            XmlNodeList nodelist = xmlHelper.GetXmlNodeListByXpath("FLIGHTS/SEGMENT/DATEFLIGHT/DIRECTFLIGHT/FLIGHT");
            foreach (XmlNode node in nodelist)
            {
                Flight f = new Flight();
                f.C_DateSource = "CS AIR";
                f.C_From = fromCity.C_NAME;
                f.C_To = toCity.C_NAME;
                f.C_Departure = departDate;
                f.C_FlightNo = XmlNodeHelper.ParseByNode(node, "FLIGHTNO");
                f.C_Airline = XmlNodeHelper.ParseByNode(node, "AIRLINE");
                f.C_DEPTIME = XmlNodeHelper.ParseByNode(node, "DEPTIME");
                f.C_ARRTIME = XmlNodeHelper.ParseByNode(node, "ARRTIME");
                f.C_TotalTime = XmlNodeHelper.ParseByNode(node, "TIMEDURINGFLIGHT_en");
                StringBuilder sbPriceInfo = new StringBuilder();
                XmlNodeList xnlPrice = node.SelectNodes("CABINS/CABIN");
                foreach (XmlNode childNodePrice in xnlPrice)
                {
                    string nodeName = XmlNodeHelper.ParseByNode(childNodePrice, "NAME");
                    string strPrice = XmlNodeHelper.ParseByNode(childNodePrice, "ADULTPRICE");
                    if (nodeName.Equals("P") && !string.IsNullOrEmpty(strPrice))
                    {
                        f.C_FirstClass = Convert.ToDecimal(strPrice);
                    }
                    else if (nodeName.Equals("Y") && !string.IsNullOrEmpty(strPrice))
                    {
                        f.C_Economy = Convert.ToDecimal(strPrice);
                    }
                    else if (nodeName.Equals("D") && !string.IsNullOrEmpty(strPrice))
                    {
                        f.C_Business = Convert.ToDecimal(strPrice);
                    }
                    else
                    {
                        sbPriceInfo.AppendFormat("nodeName:{0}->ADULTPRICE:{1}->DISCOUNT:{2}->ADULTFAREBASIS:{3}->GBADULTPRICE:{4}"
                            + "->BRANDTYPE:{5}->MILEAGESTANDARD:{6}",
                            nodeName, XmlNodeHelper.ParseByNode(childNodePrice, "ADULTPRICE") ?? string.Empty
                            , XmlNodeHelper.ParseByNode(childNodePrice, "DISCOUNT") ?? string.Empty
                            , XmlNodeHelper.ParseByNode(childNodePrice, "ADULTFAREBASIS") ?? string.Empty
                            , XmlNodeHelper.ParseByNode(childNodePrice, "GBADULTPRICE") ?? string.Empty
                            , XmlNodeHelper.ParseByNode(childNodePrice, "BRANDTYPE") ?? string.Empty
                            , XmlNodeHelper.ParseByNode(childNodePrice, "MILEAGESTANDARD") ?? string.Empty);
                    }
                }

                f.C_Remark = sbPriceInfo.ToString();
                lstFlight.Add(f);
            }

            return lstFlight;
        }
        private List<Flight> CEAIR_Get(City fromCity, City toCity, string departDate)
        {
            List<Flight> lstFlight = new List<Flight>();
            DateTime dtDepart = DateTime.Parse(departDate);
            string strUrl = string.Format("http://www.ceair.com/flight2014/{0}-{1}-{2}_CNY.html", fromCity.C_CE_CODE, toCity.C_CE_CODE, dtDepart.ToString("yyMMdd"));
            string downloadStr = string.Empty;
            int cnt = 0;
            while (string.IsNullOrEmpty(downloadStr) && cnt < 2)
            {
                try
                {
                    Thread thread = new Thread(delegate()
                    {
                        var p = new PageSnatch();
                        downloadStr = p.Navigate(strUrl, 50, "flight-info");
                    });
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                    thread.Join();
                }
                catch (Exception ex) { throw ex; }
                cnt++;
            }

            HtmlDocument htmlPage = new HtmlDocument();
            htmlPage.LoadHtml(downloadStr);
            HtmlNode docNode = htmlPage.DocumentNode;

            int articleIndex = 1;
            foreach (HtmlNode childNode in docNode.ChildNodes)
            {
                if (childNode.Name.Equals("article", StringComparison.CurrentCultureIgnoreCase))
                {
                    string xpathPrefix = string.Format("/article[{0}]/ul/li", articleIndex);
                    Flight f = new Flight();
                    f.C_DateSource = "CE AIR";
                    f.C_From = fromCity.C_NAME;
                    f.C_To = toCity.C_NAME;
                    f.C_Departure = departDate;
                    string flightNo = this.GetInnerText(childNode.SelectSingleNode(xpathPrefix + "[@class='f-i']").ChildNodes[1]);
                    string[] flightInfo = flightNo.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    if (flightInfo.Length >= 2)
                    {
                        f.C_Airline = flightInfo[0];
                        f.C_FlightNo = flightInfo[1];
                    }
                    else
                    {
                        f.C_FlightNo = flightNo;
                    }

                    f.C_DEPTIME = this.GetInnerText(childNode.SelectSingleNode(xpathPrefix + "[@class='f-i']/div[@class='info clearfix']/div[@class='airport r']").ChildNodes[0]);
                    string depart = this.GetInnerText(childNode.SelectSingleNode(xpathPrefix + "[@class='f-i']/div[@class='info clearfix']/div[@class='airport r']"));
                    f.C_ARRTIME = this.GetInnerText(childNode.SelectSingleNode(xpathPrefix + "[@class='f-i']/div[@class='info clearfix']/div[@class='airport']").ChildNodes[0]);
                    string arrive = this.GetInnerText(childNode.SelectSingleNode(xpathPrefix + "[@class='f-i']/div[@class='info clearfix']/div[@class='airport']"));
                    f.C_TotalTime = this.GetInnerText(childNode.SelectSingleNode(xpathPrefix + "[@class='f-i']/dfn"));
                    decimal outPrice;
                    string strFirstPrice = this.GetInnerText(childNode.SelectSingleNode(xpathPrefix + "[@name='fb']")).Replace("¥", string.Empty);
                    if (decimal.TryParse(strFirstPrice, out outPrice))
                        f.C_FirstClass = outPrice;

                    string strEconomyPrice = this.GetInnerText(childNode.SelectSingleNode(xpathPrefix + "[@name='economy']")).Replace("¥", string.Empty);
                    if (decimal.TryParse(strEconomyPrice, out outPrice))
                        f.C_Economy = outPrice;

                    string strPrice = this.GetInnerText(childNode.SelectSingleNode(xpathPrefix + "[@name='more']")).Replace("¥", string.Empty);
                    StringBuilder sbPriceInfo = new StringBuilder();
                    sbPriceInfo.AppendFormat("超值特惠:{0};", strPrice);
                    if (childNode.SelectNodes(string.Format("/article[{0}]/hgroup/dl", articleIndex)) != null)
                    {
                        foreach (HtmlNode priceNode in childNode.SelectNodes(string.Format("/article[{0}]/hgroup/dl", articleIndex)))
                        {
                            if (priceNode.SelectNodes("dd").Count >= 1)
                                sbPriceInfo.AppendFormat("{0}:{1};",
                                    this.GetInnerText(priceNode.SelectSingleNode("dt")),
                                    this.GetInnerText(priceNode.SelectNodes("dd")[1]));
                        }
                    }

                    f.C_Remark = sbPriceInfo.ToString();
                    lstFlight.Add(f);
                    //string flightNo = this.GetInnerText(childNode.SelectSingleNode("/article[1]/hgroup[3]/ul[1]/li[1]/div[4]/div[@class='flightNo']"));
                    articleIndex++;
                }
            }

            return lstFlight;
        }
예제 #6
0
        public void Flight_Get()
        {
            string jsonStr = string.Empty;
            HttpRequest req = Context.Request;
            string strFromCity = req.Form["FromCity"];
            string strToCity = req.Form["ToCity"];
            string strDeparture = req.Form["Departure"];
            string sort = req.Form["sort"];
            int page = Convert.ToInt16(req.Form["page"] ?? "1") - 1;
            int rowsCnt = Convert.ToInt16(req.Form["rows"] ?? "100");
            string order = req.Form["order"];
            Hashtable ht = new Hashtable();
            List<Flight> lstFlight = new List<Flight>();
            try
            {
                List<Flight> rsltLstFlight = new List<Flight>();
                if (!string.IsNullOrEmpty(strFromCity) && !string.IsNullOrEmpty(strToCity) && !string.IsNullOrEmpty(strDeparture))
                {
                    DB dbi = new DB(SystemConst.DBConnString);
                    string sqlCity = @"SELECT * FROM dbo.City WHERE C_CODE=@C_CODE";
                    City fromCity = EntityUtil.Create<City>(dbi.GetDataTable(sqlCity, this.InitSqlParams("C_CODE", strFromCity)).Rows[0]);
                    City toCity = EntityUtil.Create<City>(dbi.GetDataTable(sqlCity, this.InitSqlParams("C_CODE", strToCity)).Rows[0]);

                    //lstFlight.AddRange(this.CSAIR_Get(fromCity, toCity, strDeparture));
                    //lstFlight.AddRange(this.WS_Get(fromCity, toCity, strDeparture));
                    //lstFlight.AddRange(this.CTRIP_Get(fromCity, toCity, strDeparture));
                    lstFlight.AddRange(this.CEAIR_Get(fromCity, toCity, strDeparture));
                    //todo: This function is not finished, you can try.
                    //lstFlight.AddRange(this.QUNAR_Get(fromCity, toCity, strDeparture));

                    if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                        lstFlight = EntityUtil.SortList(lstFlight, sort, order.ToEnum<EntityUtil.SortOrder>());

                    Flight[] tmpFlights = new Flight[rowsCnt];
                    if (lstFlight.Count > (page * rowsCnt + rowsCnt))
                        lstFlight.CopyTo(page * rowsCnt, tmpFlights, 0, rowsCnt);
                    else if (lstFlight.Count > page * rowsCnt)
                    {
                        tmpFlights = new Flight[lstFlight.Count - page * rowsCnt];
                        lstFlight.CopyTo(page * rowsCnt, tmpFlights, 0, lstFlight.Count - page * rowsCnt);
                    }
                    else
                    {
                        tmpFlights = new Flight[lstFlight.Count];
                        lstFlight.CopyTo(0, tmpFlights, 0, lstFlight.Count);
                    }

                    rsltLstFlight.AddRange(tmpFlights);
                }

                int total = lstFlight.Count;
                ht.Add("rows", EntityUtil.Create(rsltLstFlight));
                ht.Add("total", total);
            }
            catch (Exception ex)
            {
                ht.Add("err", ex.Message);
                if (!ht.ContainsKey("rows"))
                {
                    ht.Add("rows", EntityUtil.Create(lstFlight));
                }

                ht.Add("total", 0);
            }

            jsonStr = JsonConvert.SerializeObject(ht);
            ResponseWrite(jsonStr);
        }