public string GetAvailableTrips1(int sourceId, int destinationId, String dateofjourney, Int16 resultSetIndex, String ConsumerKey, String ConsumerSecret)
        {
            try
            {

                ClientAPIList objClientAPIList = new ClientAPIList();

                BusesAvailabilityResponse objBusesAvailabilityResponse = new BusesAvailabilityResponse();

                //Check if Cache already contains the Providers API List
                //Else get it from database
                // if (HttpContext.Current.Cache["ClientAPI-" + ConsumerKey] == null)
                GetAPIProvidersList(ConsumerKey, ConsumerSecret);

                objClientAPIList = (ClientAPIList)HttpContext.Current.Cache["ClientAPI-" + ConsumerKey];

                //Check if atleast one provider is accessible
                if (objClientAPIList != null && objClientAPIList.Count > 0)
                {
                    BusesSearchFilter objBusesSearchFilter = new BusesSearchFilter();
                    for (int i = 0; i < objClientAPIList.Count; i++)
                    {

                        objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[i], sourceId, destinationId, dateofjourney);
                        //check if resultset index exceeds accessible providers list call the requested api
                        if (resultSetIndex > 0 && resultSetIndex <= objClientAPIList.Count)
                        {
                            //Check if request has valid source and destination ids
                            if (objBusesSearchFilter.SourceID > 0 && objBusesSearchFilter.DestinationID > 0)
                            {
                                //check if valid available trips are fetched
                                try
                                {

                                    objBusesAvailabilityResponse.availableTrips = GetAvailableTripsByProviderName(objClientAPIList[i], objBusesSearchFilter);
                                    objBusesAvailabilityResponse.responseStatus = HttpStatusCode.OK;

                                }
                                catch (Exception ex)
                                {
                                    //return the exception
                                    objBusesAvailabilityResponse.availableTrips = null;
                                    objBusesAvailabilityResponse.responseStatus = HttpStatusCode.BadRequest;
                                    objBusesAvailabilityResponse.message = ex.Message;
                                }
                            }
                            else
                            {
                                //objBusesAvailabilityResponse.availableTrips = "No results found.";
                                // objBusesAvailabilityResponse.responseStatus = HttpStatusCode.NoContent;
                                objBusesAvailabilityResponse.availableTrips = null;
                            }
                            objBusesAvailabilityResponse.providersCount = objClientAPIList.Count - resultSetIndex;
                        }
                        else
                        {
                            //objBusesAvailabilityResponse.availableTrips = "Invalid request. Please correct resultSetIndex value";
                            objBusesAvailabilityResponse.providersCount = 0;
                            objBusesAvailabilityResponse.responseStatus = HttpStatusCode.BadRequest;
                        }

                        if (objBusesAvailabilityResponse.availableTrips != null)
                        {
                            if (HttpContext.Current.Session["AvailResponse"] == null)
                            {
                                HttpContext.Current.Session["AvailResponse"] = objBusesAvailabilityResponse;
                                bus = trips(objBusesAvailabilityResponse.availableTrips);
                                //HttpContext.Current.Session["AvailResponseTrips"] = bus;
                                //bus = trips(bus);
                            }
                            else
                            {
                                //bus = trips((AvailableTrips)HttpContext.Current.Session["AvailResponseTrips"]);
                                bus = trips(objBusesAvailabilityResponse.availableTrips);
                            }
                        }
                    }
                    /*** Uncomment this if available trips of all providers should be fetched in one go ***/

                }
                else
                {

                    objBusesAvailabilityResponse.providersCount = 0;
                    objBusesAvailabilityResponse.responseStatus = HttpStatusCode.NoContent;
                }

                objBusesAvailabilityResponse.availableTrips = bus;
                HttpContext.Current.Session["AvailResponse"] = objBusesAvailabilityResponse;
                return JsonConvert.SerializeObject(objBusesAvailabilityResponse);

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        public string GetAvailableTrips2(int sourceId, int destinationId, String dateofjourney, Int16 resultSetIndex, String ConsumerKey, String ConsumerSecret)
        {
            try
            {
                ClientAPIList objClientAPIList = new ClientAPIList();
                BusesAvailabilityResponse objBusesAvailabilityResponse = new BusesAvailabilityResponse();
                if (resultSetIndex != 2)
                {
                    HttpContext.Current.Session["AvailResponse"] = null;
                    HttpRuntime.Cache["bus"] = "";

                    //Check if Cache already contains the Providers API List
                    //Else get it from database
                    GetAPIProvidersList(ConsumerKey, ConsumerSecret);
                    objClientAPIList = (ClientAPIList)HttpContext.Current.Cache["ClientAPI-" + ConsumerKey];
                    //Check if atleast one provider is accessible
                    if (objClientAPIList != null && objClientAPIList.Count > 0)
                    {
                        BusesSearchFilter objBusesSearchFilter = new BusesSearchFilter();
                        threadcount = Convert.ToInt32(objClientAPIList.Count());
                        thread = new Thread[threadcount];
                        for (i = 0; i < thread.Count(); i++)
                        {
                            thread[i] = new Thread(() =>
                            {
                                if (objClientAPIList[i].ProviderName == "TICKETGOOSE")
                                {
                                    int T = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[T], sourceId, destinationId, dateofjourney);
                                    if (objBusesSearchFilter.SourceID > 0 && objBusesSearchFilter.DestinationID > 0)
                                    {
                                        TSID = Convert.ToInt32(objBusesSearchFilter.SourceID);
                                        TDID = Convert.ToInt32(objBusesSearchFilter.DestinationID);
                                        TDate = objBusesSearchFilter.JourneyDate;
                                        TURL = objClientAPIList[T].APIURL;
                                        TConsumerKey = objClientAPIList[T].ConsumerKey;
                                        TCOnsumerSecretKey = objClientAPIList[T].ConsumerSecret;
                                        TPID = objClientAPIList[T].ProviderID;
                                        Tbus = Ticketgoose(TURL, TConsumerKey, TCOnsumerSecretKey, TPID, TSID, TDID, TDate);
                                        if (Tbus != null)
                                        {
                                            if (Tbus.Count() > 0)
                                            {
                                                bus = trips(Tbus);
                                                HttpRuntime.Cache["bus"] = Tbus;
                                                objBusesAvailabilityResponse.providersCount = 10;
                                            }

                                        }
                                    }
                                }
                                else if (objClientAPIList[i].ProviderName == "MORNINGSTAR")
                                {
                                    int M = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[M], sourceId, destinationId, dateofjourney);
                                    if (objBusesSearchFilter.SourceID > 0 && objBusesSearchFilter.DestinationID > 0)
                                    {
                                        MSID = Convert.ToInt32(objBusesSearchFilter.SourceID);
                                        MDID = Convert.ToInt32(objBusesSearchFilter.DestinationID);
                                        MDate = objBusesSearchFilter.JourneyDate;
                                        MURL = objClientAPIList[M].APIURL + "/";
                                        MConsumerKey = objClientAPIList[M].ConsumerKey;
                                        MCOnsumerSecretKey = objClientAPIList[M].ConsumerSecret;
                                        MPID = objClientAPIList[M].ProviderID;
                                        MProviderName = objClientAPIList[M].ProviderName;
                                        Tbus = MORNINGSTAR(MURL, MConsumerKey, MCOnsumerSecretKey, MPID, MProviderName, MSID, MDID, MDate);
                                        if (Tbus != null)
                                        {
                                            if (Tbus.Count() > 0)
                                            {
                                                bus = trips(Tbus);
                                            }

                                            // b = true;
                                        }
                                    }
                                }
                                else if (objClientAPIList[i].ProviderName == "BITLA")
                                {
                                    int B = i;
                                    bus = GETBITLROUTES(objBusesSearchFilter, objClientAPIList[B], sourceId, destinationId, dateofjourney);

                                }
                                else if (objClientAPIList[i].ProviderName == "KALLADA")
                                {
                                    int kD = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[kD], sourceId, destinationId, dateofjourney);
                                    if (objBusesSearchFilter.SourceID > 0 && objBusesSearchFilter.DestinationID > 0)
                                    {
                                        KDSID = Convert.ToInt32(objBusesSearchFilter.SourceID);
                                        KDDID = Convert.ToInt32(objBusesSearchFilter.DestinationID);
                                        KDDate = objBusesSearchFilter.JourneyDate;
                                        KDURL = objClientAPIList[kD].APIURL;
                                        KDConsumerKey = objClientAPIList[kD].ConsumerKey;
                                        KDCOnsumerSecretKey = objClientAPIList[kD].ConsumerSecret;
                                        KDProviderName = objClientAPIList[kD].ProviderName;
                                        Kbus = KALLADA(KDURL, KDConsumerKey, KDCOnsumerSecretKey, KDProviderName, KDSID, KDDID, KDDate);
                                        if (Kbus != null)
                                        {
                                            if (Kbus.Count() > 0)
                                            {
                                                bus = trips(Kbus);
                                            }
                                        }
                                    }
                                }
                                else if (objClientAPIList[i].ProviderName == "SAIANJANA")
                                {
                                    int s = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[s], sourceId, destinationId, dateofjourney);
                                    if (objBusesSearchFilter.SourceID > 0 && objBusesSearchFilter.DestinationID > 0)
                                    {
                                        SSID = Convert.ToInt32(objBusesSearchFilter.SourceID);
                                        SDID = Convert.ToInt32(objBusesSearchFilter.DestinationID);
                                        SDate = objBusesSearchFilter.JourneyDate;
                                        SURL = objClientAPIList[s].APIURL;
                                        SConsumerKey = objClientAPIList[s].ConsumerKey;
                                        SCOnsumerSecretKey = objClientAPIList[s].ConsumerSecret;
                                        SProviderName = objClientAPIList[s].ProviderName;
                                        Kbus = SAIANJANA(SURL, SConsumerKey, SCOnsumerSecretKey, SProviderName, SSID, SDID, SDate);
                                        if (Kbus != null)
                                        {
                                            if (Kbus.Count() > 0)
                                            {
                                                bus = trips(Kbus);

                                            }
                                        }
                                    }
                                }
                                else if (objClientAPIList[i].ProviderName == "SVR")
                                {
                                    int sv = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[sv], sourceId, destinationId, dateofjourney);
                                    if (objBusesSearchFilter.SourceID > 0 && objBusesSearchFilter.DestinationID > 0)
                                    {
                                        SVSID = Convert.ToInt32(objBusesSearchFilter.SourceID);
                                        SVDID = Convert.ToInt32(objBusesSearchFilter.DestinationID);
                                        SVDate = objBusesSearchFilter.JourneyDate;
                                        SVURL = objClientAPIList[sv].APIURL;
                                        SVConsumerKey = objClientAPIList[sv].ConsumerKey;
                                        SVCOnsumerSecretKey = objClientAPIList[sv].ConsumerSecret;
                                        SVProviderName = objClientAPIList[sv].ProviderName;
                                        Kbus = GETSVR(SVURL, SVConsumerKey, SVCOnsumerSecretKey, SVProviderName, SVSID, SVDID, SVDate);
                                        if (Kbus != null)
                                        {
                                            if (Kbus.Count() > 0)
                                            {
                                                bus = trips(Kbus);
                                            }
                                        }
                                    }
                                }
                                else if (objClientAPIList[i].ProviderName == "RAJESH")
                                {
                                    int r = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[r], sourceId, destinationId, dateofjourney);
                                    if (objBusesSearchFilter.SourceID > 0 && objBusesSearchFilter.DestinationID > 0)
                                    {
                                        RSID = Convert.ToInt32(objBusesSearchFilter.SourceID);
                                        RDID = Convert.ToInt32(objBusesSearchFilter.DestinationID);
                                        RDate = objBusesSearchFilter.JourneyDate;
                                        RURL = objClientAPIList[r].APIURL;
                                        RConsumerKey = objClientAPIList[r].ConsumerKey;
                                        RCOnsumerSecretKey = objClientAPIList[r].ConsumerSecret;
                                        RProviderName = objClientAPIList[r].ProviderName;
                                        Kbus = Rajesh(RURL, RConsumerKey, RCOnsumerSecretKey, RProviderName, RSID, RDID, RDate);
                                        if (Kbus != null)
                                        {
                                            if (Kbus.Count() > 0)
                                            {
                                                bus = trips(Kbus);
                                                //HttpRuntime.Cache["bus"] = Tbus;
                                            }

                                        }
                                    }
                                }
                                else if (objClientAPIList[i].ProviderName == "KAVERI")
                                {
                                    int k = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[k], sourceId, destinationId, dateofjourney);
                                    if (objBusesSearchFilter.SourceID > 0 && objBusesSearchFilter.DestinationID > 0)
                                    {
                                        KSID = Convert.ToInt32(objBusesSearchFilter.SourceID);
                                        KDID = Convert.ToInt32(objBusesSearchFilter.DestinationID);
                                        KDate = objBusesSearchFilter.JourneyDate;
                                        KURL = objClientAPIList[i].APIURL;
                                        KConsumerKey = objClientAPIList[k].ConsumerKey;
                                        KCOnsumerSecretKey = objClientAPIList[k].ConsumerSecret;
                                        KProviderName = objClientAPIList[k].ProviderName;
                                        Kbus = KAVERI(KURL, KConsumerKey, KCOnsumerSecretKey, KProviderName, KSID, KDID, KDate);
                                        if (Kbus != null)
                                        {
                                            if (Kbus.Count() > 0)
                                            {
                                                bus = trips(Kbus);
                                                //HttpRuntime.Cache["Kbus"] = Kbus;

                                            }

                                        }
                                    }
                                }
                            });
                            // threat initialisation ends

                            if (c == true)
                            {
                                thread[i].Start();
                                thread[i].Join(500);
                                if (i == thread.Count() - 1)
                                {
                                    i = thread.Count() - 1;
                                    break;
                                }
                            }

                        }
                    }
                }

                if (resultSetIndex != 2)
                {

                Found:
                    int j = 0;
                    foreach (var thd in thread)
                    {
                        if (thd.IsAlive)
                        {
                            thd.Join(1000);
                            b = false;
                        }
                        else
                        {
                            j++;
                        }
                        if (j == threadcount)
                        {
                            b = true;
                            i = 0;
                            break;
                        }

                    }

                    if (c == true)
                    {
                        c = false;
                    }
                    if (b == false)
                    {
                        goto Found;
                    }
                    else
                    {
                        b = false;
                        //check if resultset index exceeds accessible providers list call the requested api
                        if (resultSetIndex > 0 && resultSetIndex <= objClientAPIList.Count)
                        {
                            try
                            {
                                // objBusesAvailabilityResponse.availableTrips = GetAvailableTripsByProviderName(objClientAPIList[i], objBusesSearchFilter);
                                objBusesAvailabilityResponse.responseStatus = HttpStatusCode.OK;

                            }
                            catch (Exception ex)
                            {
                                //return the exception
                                objBusesAvailabilityResponse.availableTrips = null;
                                objBusesAvailabilityResponse.responseStatus = HttpStatusCode.BadRequest;
                                objBusesAvailabilityResponse.message = ex.Message;
                            }
                            if (objBusesAvailabilityResponse.providersCount == 10)
                            {
                                objBusesAvailabilityResponse.providersCount = 0;
                            }
                            else
                            {
                                objBusesAvailabilityResponse.providersCount = objClientAPIList.Count - resultSetIndex;
                            }
                        }
                        else
                        {
                            objBusesAvailabilityResponse.providersCount = 0;
                            objBusesAvailabilityResponse.responseStatus = HttpStatusCode.BadRequest;
                        }
                    }
                }
                if (HttpContext.Current.Session["AvailResponse"] == null)
                {
                    objBusesAvailabilityResponse.availableTrips = bus;
                    HttpContext.Current.Session["AvailResponse"] = objBusesAvailabilityResponse;
                    HttpRuntime.Cache["bus"] = "";
                }
                else
                {
                bump:
                    if (HttpRuntime.Cache["bus"].ToString() != "")
                    {
                        Tbus = (AvailableTrips)HttpRuntime.Cache["bus"];

                        if (Tbus.Count() > 0)
                        {
                            BusesAvailabilityResponse busback = new BusesAvailabilityResponse();
                            Tbus = (AvailableTrips)HttpRuntime.Cache["bus"];
                            busback = (BusesAvailabilityResponse)HttpContext.Current.Session["AvailResponse"];
                            bus = trips((AvailableTrips)busback.availableTrips);
                            bus = trips(Tbus);
                            busback.availableTrips = bus;
                            busback.responseStatus = HttpStatusCode.OK;
                            busback.providersCount = 0;
                            HttpContext.Current.Session["AvailResponse"] = busback;
                            objBusesAvailabilityResponse.availableTrips = Tbus;
                            objBusesAvailabilityResponse.responseStatus = HttpStatusCode.OK;
                            objBusesAvailabilityResponse.providersCount = 0;
                            HttpRuntime.Cache["bus"] = "";

                        }

                    }
                    else
                    {
                        objClientAPIList = (ClientAPIList)HttpContext.Current.Cache["ClientAPI-" + ConsumerKey];
                        if (objClientAPIList[1].ProviderName == "TICKETGOOSE")
                        {
                            goto bump;
                        }
                        else
                        {

                        }
                    }

                }
                return JsonConvert.SerializeObject(objBusesAvailabilityResponse);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        public String CancelTicket(String bookingId, String seatNos, String ProviderName, String ConsumerKey, String ConsumerSecret)
        {
            if (ValidateRequest(ConsumerKey, ConsumerSecret))
            {
                ClientAPIList objClientAPIList = new ClientAPIList();

                if (HttpContext.Current.Cache["ClientAPI-" + ConsumerKey] == null)
                    GetAPIProvidersList(ConsumerKey, ConsumerSecret);

                objClientAPIList = (ClientAPIList)HttpContext.Current.Cache["ClientAPI-" + ConsumerKey];

                ClientAPIDetails objClientAPIDetails = objClientAPIList.SingleOrDefault(element => element.ProviderName == ProviderName);

                String strCancelResponse = String.Empty;
                try
                {
                    switch (ProviderName)
                    {
                        case "BITLA":
                        case "MORNINGSTAR":
                            BitlaAPI clsBitlaAPI = new BitlaAPI();
                            strCancelResponse = clsBitlaAPI.cancelTicket(bookingId, seatNos, objClientAPIDetails.APIURL, objClientAPIDetails.ConsumerKey);
                            break;
                        case "TICKETGOOSE":
                            TicketGooseAPI clsTicketGooseAPI = new TicketGooseAPI();
                            strCancelResponse = clsTicketGooseAPI.confirmTicketCancellation(bookingId, seatNos, objClientAPIDetails.APIURL, objClientAPIDetails.ConsumerKey, objClientAPIDetails.ConsumerSecret);
                            break;
                        case "ABHIBUS":
                        case "SVR":
                        case "KALLADA":
                        case "KAVERI":
                        case "RAJESH":
                        case "SAIANJANA":
                            AbhibusAPI clsAbhiBusAPI = new AbhibusAPI();
                            strCancelResponse = "";//clsAbhiBusAPI.cancelTicket(objClientAPIDetails.APIURL, objClientAPIDetails.ConsumerKey, bookingId);
                            break;
                        case "EASYBUS":
                            EasybusAPI clsEasyBusAPI = new EasybusAPI();
                            strCancelResponse = "";//  clsEasyBusAPI.cancelTicket(bookingId, seatNos, objClientAPIDetails.APIURL, objClientAPIDetails.ConsumerKey, objClientAPIDetails.ConsumerSecret);
                            break;
                        default:
                            break;
                    }
                }
                catch (Exception)
                {
                    //
                }
                return strCancelResponse;
            }
            else
            {
                return null;
                //throw new http exception
                // throw new System.Web.Http.HttpResponseException(HttpStatusCode.Forbidden);
            }
        }
        public string GetAvailableTrips(int sourceId, int destinationId, String dateofjourney, Int16 resultSetIndex, String ConsumerKey, String ConsumerSecret)
        {
            try
            {
                ClientAPIList objClientAPIList = new ClientAPIList();
                BusesAvailabilityResponse objBusesAvailabilityResponse = new BusesAvailabilityResponse();
                if (resultSetIndex != 2)
                {
                    HttpContext.Current.Session["AvailResponse"] = null;
                    HttpRuntime.Cache["bus"] = "";

                    //Check if Cache already contains the Providers API List
                    //Else get it from database
                    GetAPIProvidersList(ConsumerKey, ConsumerSecret);
                    objClientAPIList = (ClientAPIList)HttpContext.Current.Cache["ClientAPI-" + ConsumerKey];
                    //Check if atleast one provider is accessible
                    if (objClientAPIList != null && objClientAPIList.Count > 0)
                    {
                        BusesSearchFilter objBusesSearchFilter = new BusesSearchFilter();
                        threadcount = Convert.ToInt32(objClientAPIList.Count());
                        thread = new Thread[threadcount];
                        for (i = 0; i < thread.Count(); i++)
                        {
                            thread[i] = new Thread(() =>
                            {
                                if (objClientAPIList[i].ProviderName == "TICKETGOOSE")
                                {
                                    int T = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[T], sourceId, destinationId, dateofjourney);
                                    if (Tsource_ids.ToString() != "" && TDestination_Ids.ToString() != "")
                                    {
                                        string[] Tsu = Tsource_ids.Split(',');
                                        string[] Tdu = TDestination_Ids.Split(',');
                                        string[] TSdr = Tsu.Distinct().ToArray();
                                        string[] TDdr = Tdu.Distinct().ToArray();
                                        foreach (string Tsr in TSdr)
                                        {
                                            foreach (string Tdr in TDdr)
                                            {
                                                TSID = Convert.ToInt32(Tsr);
                                                TDID = Convert.ToInt32(Tdr);
                                                TDate = objBusesSearchFilter.JourneyDate;
                                                TURL = objClientAPIList[T].APIURL;
                                                TConsumerKey = objClientAPIList[T].ConsumerKey;
                                                TCOnsumerSecretKey = objClientAPIList[T].ConsumerSecret;
                                                TPID = objClientAPIList[T].ProviderID;
                                                Tbus = Ticketgoose(TURL, TConsumerKey, TCOnsumerSecretKey, TPID, TSID, TDID, TDate);
                                                if (Tbus != null)
                                                {
                                                    if (Tbus.Count() > 0)
                                                    {
                                                        bus = trips(Tbus);
                                                        HttpRuntime.Cache["bus"] = Tbus;
                                                        objBusesAvailabilityResponse.providersCount = 10;
                                                    }

                                                }

                                            }
                                        }
                                    }
                                }
                                else if (objClientAPIList[i].ProviderName == "MORNINGSTAR")
                                {
                                    int M = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[M], sourceId, destinationId, dateofjourney);
                                    if (Msource_ids.ToString() != "" && MDestination_Ids.ToString() != "")
                                    {
                                        string[] Msu = Msource_ids.Split(',');
                                        string[] Mdu = MDestination_Ids.Split(',');
                                        string[] MSdr = Msu.Distinct().ToArray();
                                        string[] MDdr = Mdu.Distinct().ToArray();
                                        foreach (string Msr in MSdr)
                                        {
                                            foreach (string Mdr in MDdr)
                                            {
                                                MSID = Convert.ToInt32(Msr);
                                                MDID = Convert.ToInt32(Mdr);
                                                MDate = objBusesSearchFilter.JourneyDate;
                                                MURL = objClientAPIList[M].APIURL + "/";
                                                MConsumerKey = objClientAPIList[M].ConsumerKey;
                                                MCOnsumerSecretKey = objClientAPIList[M].ConsumerSecret;
                                                MPID = objClientAPIList[M].ProviderID;
                                                MProviderName = objClientAPIList[M].ProviderName;
                                                Tbus = MORNINGSTAR(MURL, MConsumerKey, MCOnsumerSecretKey, MPID, MProviderName, MSID, MDID, MDate);
                                                if (Tbus != null)
                                                {
                                                    if (Tbus.Count() > 0)
                                                    {
                                                        bus = trips(Tbus);
                                                    }
                                                }

                                            }
                                        }
                                    }
                                }
                                else if (objClientAPIList[i].ProviderName == "BITLA")
                                {
                                    //objBusesSearchFilter.SourceID = Sdr.ToString() == "" ? 0 : int.Parse(Sdr.ToString());
                                    //objBusesSearchFilter.DestinationID = Ddr.ToString() == "" ? 0 : Convert.ToInt32(Ddr.ToString());
                                    //objBusesSearchFilter.JourneyDate = dateofjourney;
                                    int B = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[B], sourceId, destinationId, dateofjourney);
                                    if (source_ids.ToString() != "" && Destination_Ids.ToString() != "")
                                    {
                                        string[] su = source_ids.Split(',');
                                        string[] du = Destination_Ids.Split(',');
                                        string[] SSdr = su.Distinct().ToArray();
                                        string[] DDdr = du.Distinct().ToArray();
                                        foreach (string Sdr in SSdr)
                                        {
                                            foreach (string Ddr in DDdr)
                                            {
                                                BSID = Convert.ToInt32(Sdr);
                                                BDID = Convert.ToInt32(Ddr);
                                                BDate = objBusesSearchFilter.JourneyDate;
                                                BURL = objClientAPIList[B].APIURL + "/";
                                                BConsumerKey = objClientAPIList[B].ConsumerKey;
                                                BCOnsumerSecretKey = objClientAPIList[B].ConsumerSecret;
                                                BPID = objClientAPIList[B].ProviderID;
                                                BProviderName = objClientAPIList[B].ProviderName;
                                                Tbus = BITLA(BURL, BConsumerKey, BCOnsumerSecretKey, BPID, BProviderName, BSID, BDID, BDate);
                                                if (Tbus != null)
                                                {
                                                    if (Tbus.Count() > 0)
                                                    {
                                                        bus = trips(Tbus);
                                                    }
                                                }

                                            }
                                        }
                                    }

                                }
                                else if (objClientAPIList[i].ProviderName == "KALLADA")
                                {
                                    int kD = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[kD], sourceId, destinationId, dateofjourney);
                                    if (KDsource_ids.ToString() != "" && KDDestination_Ids.ToString() != "")
                                    {
                                        string[] KDsu = KDsource_ids.Split(',');
                                        string[] KDdu = KDDestination_Ids.Split(',');
                                        string[] KSdr = KDsu.Distinct().ToArray();
                                        string[] KDdr = KDdu.Distinct().ToArray();
                                        foreach (string Ksr in KSdr)
                                        {
                                            foreach (string Kdr in KDdr)
                                            {

                                                KDSID = Convert.ToInt32(Ksr);
                                                KDDID = Convert.ToInt32(Kdr);
                                                KDDate = objBusesSearchFilter.JourneyDate;
                                                KDURL = objClientAPIList[kD].APIURL;
                                                KDConsumerKey = objClientAPIList[kD].ConsumerKey;
                                                KDCOnsumerSecretKey = objClientAPIList[kD].ConsumerSecret;
                                                KDProviderName = objClientAPIList[kD].ProviderName;
                                                Kbus = KALLADA(KDURL, KDConsumerKey, KDCOnsumerSecretKey, KDProviderName, KDSID, KDDID, KDDate);
                                                if (Kbus != null)
                                                {
                                                    if (Kbus.Count() > 0)
                                                    {
                                                        bus = trips(Kbus);
                                                    }
                                                }

                                            }
                                        }
                                    }
                                }
                                else if (objClientAPIList[i].ProviderName == "SAIANJANA")
                                {
                                    int s = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[s], sourceId, destinationId, dateofjourney);
                                    if (SSsource_ids.ToString() != "" && SSDestination_Ids.ToString() != "")
                                    {
                                        string[] SSsu = SSsource_ids.Split(',');
                                        string[] SSdu = SSDestination_Ids.Split(',');
                                        string[] SSdr = SSsu.Distinct().ToArray();
                                        string[] SDdr = SSdu.Distinct().ToArray();
                                        foreach (string Ssr in SSdr)
                                        {
                                            foreach (string Sdr in SDdr)
                                            {
                                                SSID = Convert.ToInt32(Ssr);
                                                SDID = Convert.ToInt32(Sdr);
                                                SDate = objBusesSearchFilter.JourneyDate;
                                                SURL = objClientAPIList[s].APIURL;
                                                SConsumerKey = objClientAPIList[s].ConsumerKey;
                                                SCOnsumerSecretKey = objClientAPIList[s].ConsumerSecret;
                                                SProviderName = objClientAPIList[s].ProviderName;
                                                Kbus = SAIANJANA(SURL, SConsumerKey, SCOnsumerSecretKey, SProviderName, SSID, SDID, SDate);
                                                if (Kbus != null)
                                                {
                                                    if (Kbus.Count() > 0)
                                                    {
                                                        bus = trips(Kbus);

                                                    }
                                                }

                                            }
                                        }
                                    }
                                }
                                else if (objClientAPIList[i].ProviderName == "SVR")
                                {
                                    int sv = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[sv], sourceId, destinationId, dateofjourney);
                                    if (Ssource_ids.ToString() != "" && SDestination_Ids.ToString() != "")
                                    {
                                        string[] sssu = Ssource_ids.Split(',');
                                        string[] ssdu = SDestination_Ids.Split(',');
                                        string[] SSSdr = sssu.Distinct().ToArray();
                                        string[] SSDdr = ssdu.Distinct().ToArray();
                                        foreach (string SSsr in SSSdr)
                                        {
                                            foreach (string SSdr in SSDdr)
                                            {

                                                SVSID = Convert.ToInt32(SSsr);
                                                SVDID = Convert.ToInt32(SSdr);
                                                SVDate = objBusesSearchFilter.JourneyDate;
                                                SVURL = objClientAPIList[sv].APIURL;
                                                SVConsumerKey = objClientAPIList[sv].ConsumerKey;
                                                SVCOnsumerSecretKey = objClientAPIList[sv].ConsumerSecret;
                                                SVProviderName = objClientAPIList[sv].ProviderName;
                                                Kbus = GETSVR(SVURL, SVConsumerKey, SVCOnsumerSecretKey, SVProviderName, SVSID, SVDID, SVDate);
                                                if (Kbus != null)
                                                {
                                                    if (Kbus.Count() > 0)
                                                    {
                                                        bus = trips(Kbus);
                                                    }
                                                }

                                            }
                                        }
                                    }
                                }
                                else if (objClientAPIList[i].ProviderName == "RAJESH")
                                {
                                    int r = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[r], sourceId, destinationId, dateofjourney);
                                    if (Rsource_ids.ToString() != "" && RDestination_Ids.ToString() != "")
                                    {
                                        string[] Rsu = Rsource_ids.Split(',');
                                        string[] Rdu = RDestination_Ids.Split(',');
                                        string[] RSdr = Rsu.Distinct().ToArray();
                                        string[] RDdr = Rdu.Distinct().ToArray();
                                        foreach (string Rsr in RSdr)
                                        {
                                            foreach (string Rdr in RDdr)
                                            {
                                                RSID = Convert.ToInt32(Rsr);
                                                RDID = Convert.ToInt32(Rdr);
                                                RDate = objBusesSearchFilter.JourneyDate;
                                                RURL = objClientAPIList[r].APIURL;
                                                RConsumerKey = objClientAPIList[r].ConsumerKey;
                                                RCOnsumerSecretKey = objClientAPIList[r].ConsumerSecret;
                                                RProviderName = objClientAPIList[r].ProviderName;
                                                Kbus = Rajesh(RURL, RConsumerKey, RCOnsumerSecretKey, RProviderName, RSID, RDID, RDate);
                                                if (Kbus != null)
                                                {
                                                    if (Kbus.Count() > 0)
                                                    {
                                                        bus = trips(Kbus);
                                                        //HttpRuntime.Cache["bus"] = Tbus;
                                                    }

                                                }

                                            }
                                        }
                                    }
                                }
                                else if (objClientAPIList[i].ProviderName == "KAVERI")
                                {
                                    int k = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[k], sourceId, destinationId, dateofjourney);
                                    if (Ksource_ids.ToString() != "" && KDestination_Ids.ToString() != "")
                                    {
                                        string[] Ksu = Ksource_ids.Split(',');
                                        string[] Kdu = KDestination_Ids.Split(',');
                                        string[] KSdr = Ksu.Distinct().ToArray();
                                        string[] KDdr = Kdu.Distinct().ToArray();
                                        foreach (string Ksr in KSdr)
                                        {
                                            foreach (string Kdr in KDdr)
                                            {
                                                KSID = Convert.ToInt32(Ksr);
                                                KDID = Convert.ToInt32(Kdr);
                                                KDate = objBusesSearchFilter.JourneyDate;
                                                KURL = objClientAPIList[i].APIURL;
                                                KConsumerKey = objClientAPIList[k].ConsumerKey;
                                                KCOnsumerSecretKey = objClientAPIList[k].ConsumerSecret;
                                                KProviderName = objClientAPIList[k].ProviderName;
                                                Kbus = KAVERI(KURL, KConsumerKey, KCOnsumerSecretKey, KProviderName, KSID, KDID, KDate);
                                                if (Kbus != null)
                                                {
                                                    if (Kbus.Count() > 0)
                                                    {
                                                        bus = trips(Kbus);
                                                        //HttpRuntime.Cache["Kbus"] = Kbus;

                                                    }

                                                }

                                            }
                                        }
                                    }
                                }
                                //easy bus 17-05-2013
                                else if (objClientAPIList[i].ProviderName == "EASYBUS")
                                {
                                    int E = i;
                                    objBusesSearchFilter = GetCityIDsOfProviders(objBusesSearchFilter, objClientAPIList[E], sourceId, destinationId, dateofjourney);
                                    if (Esource_ids.ToString() != "" && EDestination_Ids.ToString() != "")
                                    {
                                        string[] Esu = Esource_ids.Split(',');
                                        string[] Edu = EDestination_Ids.Split(',');
                                        string[] ESdr = Esu.Distinct().ToArray();
                                        string[] EDdr = Edu.Distinct().ToArray();
                                        foreach (string Esr in ESdr)
                                        {
                                            foreach (string Edr in EDdr)
                                            {

                                                ESID = Convert.ToInt32(Esr);
                                                EDID = Convert.ToInt32(Edr);
                                                EDate = dateofjourney;
                                                EURL = objClientAPIList[E].APIURL;
                                                EConsumerKey = objClientAPIList[E].ConsumerKey;
                                                ECOnsumerSecretKey = objClientAPIList[E].ConsumerSecret;
                                                EProviderName = objClientAPIList[E].ProviderName;
                                                Kbus = EASY(EURL, EConsumerKey, ECOnsumerSecretKey, EProviderName, ESID, EDID, EDate);
                                                if (Kbus != null)
                                                {
                                                    if (Kbus.Count() > 0)
                                                    {
                                                        bus = trips(Kbus);
                                                    }
                                                }

                                            }
                                        }
                                    }

                                }
                            });
                            // threat initialisation ends

                            if (c == true)
                            {
                                thread[i].Start();
                                thread[i].Join(500);
                                if (i == thread.Count() - 1)
                                {
                                    i = thread.Count() - 1;
                                    break;
                                }
                            }

                        }
                    }
                }

                if (resultSetIndex != 2)
                {

                Found:
                    int j = 0;
                    foreach (var thd in thread)
                    {
                        if (thd.IsAlive)
                        {
                            thd.Join(1000);
                            b = false;
                        }
                        else
                        {
                            j++;
                        }
                        if (j == threadcount)
                        {
                            b = true;
                            i = 0;
                            break;
                        }

                    }

                    if (c == true)
                    {
                        c = false;
                    }
                    if (b == false)
                    {
                        goto Found;
                    }
                    else
                    {
                        b = false;
                        //check if resultset index exceeds accessible providers list call the requested api
                        if (resultSetIndex > 0 && resultSetIndex <= objClientAPIList.Count)
                        {
                            try
                            {
                                // objBusesAvailabilityResponse.availableTrips = GetAvailableTripsByProviderName(objClientAPIList[i], objBusesSearchFilter);
                                objBusesAvailabilityResponse.responseStatus = HttpStatusCode.OK;

                            }
                            catch (Exception ex)
                            {
                                //return the exception
                                objBusesAvailabilityResponse.availableTrips = null;
                                objBusesAvailabilityResponse.responseStatus = HttpStatusCode.BadRequest;
                                objBusesAvailabilityResponse.message = ex.Message;
                            }
                            if (objBusesAvailabilityResponse.providersCount == 10)
                            {
                                objBusesAvailabilityResponse.providersCount = 0;
                            }
                            else
                            {
                                objBusesAvailabilityResponse.providersCount = 0;
                                //  objBusesAvailabilityResponse.providersCount = objClientAPIList.Count - resultSetIndex;
                            }
                        }
                        else
                        {
                            objBusesAvailabilityResponse.providersCount = 0;
                            objBusesAvailabilityResponse.responseStatus = HttpStatusCode.BadRequest;
                        }
                    }
                }
                if (HttpContext.Current.Session["AvailResponse"] == null)
                {
                    objBusesAvailabilityResponse.availableTrips = bus;
                    HttpContext.Current.Session["AvailResponse"] = objBusesAvailabilityResponse;
                    HttpRuntime.Cache["bus"] = "";
                }
                else
                {
                bump:
                    if (HttpRuntime.Cache["bus"].ToString() != "")
                    {
                        Tbus = (AvailableTrips)HttpRuntime.Cache["bus"];

                        if (Tbus.Count() > 0)
                        {
                            BusesAvailabilityResponse busback = new BusesAvailabilityResponse();
                            Tbus = (AvailableTrips)HttpRuntime.Cache["bus"];
                            busback = (BusesAvailabilityResponse)HttpContext.Current.Session["AvailResponse"];
                            bus = trips((AvailableTrips)busback.availableTrips);
                            bus = trips(Tbus);
                            busback.availableTrips = bus;
                            busback.responseStatus = HttpStatusCode.OK;
                            busback.providersCount = 0;
                            HttpContext.Current.Session["AvailResponse"] = busback;
                            objBusesAvailabilityResponse.availableTrips = Tbus;
                            objBusesAvailabilityResponse.responseStatus = HttpStatusCode.OK;
                            objBusesAvailabilityResponse.providersCount = 0;
                            HttpRuntime.Cache["bus"] = "";

                        }

                    }
                    else
                    {
                        objClientAPIList = (ClientAPIList)HttpContext.Current.Cache["ClientAPI-" + ConsumerKey];
                        if (objClientAPIList[1].ProviderName == "TICKETGOOSE")
                        {
                            goto bump;
                        }
                        else
                        {

                        }
                    }

                }
                return JsonConvert.SerializeObject(objBusesAvailabilityResponse);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        public string BookTicket(BlockSeats blockSeats, String ConsumerKey, String ConsumerSecret)
        {
            if (ValidateRequest(ConsumerKey, ConsumerSecret))
            {
                ClientAPIList objClientAPIList = new ClientAPIList();

                //if (HttpContext.Current.Cache["ClientAPI-" + ConsumerKey] == null)
                GetAPIProvidersList(ConsumerKey, ConsumerSecret);
                objClientAPIList = (ClientAPIList)HttpContext.Current.Cache["ClientAPI-" + ConsumerKey];
                ClientAPIDetails objClientAPIDetails = objClientAPIList.SingleOrDefault(element => element.ProviderName == blockSeats.ProviderName);
                BookSeatsResponse objBookResponse = new BookSeatsResponse();
                if (objClientAPIDetails != null)
                {
                    try
                    {
                        switch (blockSeats.ProviderName)
                        {
                            case "BITLA":
                            case "MORNINGSTAR":
                                BitlaAPI clsBitlaAPI = new BitlaAPI();
                                objBookResponse = clsBitlaAPI.bookTicket(blockSeats.SourceId, blockSeats.DestinationId, blockSeats.TripId,
                                    objClientAPIDetails.APIURL, objClientAPIDetails.ConsumerKey, blockSeats.NoOfSeats, blockSeats.BoardingId.ToString(), blockSeats.SeatNo, blockSeats.Title, blockSeats.Name,
                                    blockSeats.Age, blockSeats.Sex, blockSeats.Address, blockSeats.BookingRefNo, blockSeats.IdCardType, blockSeats.IdCardNo, blockSeats.IdCardIssuedBy,
                                    blockSeats.MobileNo, blockSeats.EmergencyMobileNo, blockSeats.EmailId);
                                break;
                            case "TICKETGOOSE":
                                TicketGooseAPI clsTicketGooseAPI = new TicketGooseAPI();
                                objBookResponse = clsTicketGooseAPI.BookTicket(blockSeats.BookingId, objClientAPIDetails.APIURL, objClientAPIDetails.ConsumerKey, objClientAPIDetails.ConsumerSecret);
                                break;
                            case "ABHIBUS":
                            case "SVR":
                            case "KALLADA":
                            case "KAVERI":
                            case "RAJESH":
                            case "SAIANJANA":
                                AbhibusAPI clsAbhiBusAPI = new AbhibusAPI();
                                objBookResponse = clsAbhiBusAPI.bookSeats(blockSeats.SourceId, blockSeats.DestinationId, blockSeats.JourneyDate
                                    , blockSeats.TripId, blockSeats.SeatNo, blockSeats.Title, blockSeats.Name, blockSeats.BoardingId, blockSeats.Address
                                    , blockSeats.Name, blockSeats.MobileNo, blockSeats.EmailId, blockSeats.BookingRefNo, objClientAPIDetails.APIURL
                                    , objClientAPIDetails.ConsumerKey);

                                objBookResponse.extraseatinfo = blockSeats.SourceId + "," + blockSeats.DestinationId + "," + blockSeats.JourneyDate
                              + "," + blockSeats.TripId + "," + blockSeats.SeatNo + "," + blockSeats.Title + "," + blockSeats.Name + "," + blockSeats.BoardingId + "," + blockSeats.Address
                              + "," + blockSeats.Name + "," + blockSeats.MobileNo + "," + blockSeats.EmailId + "," + blockSeats.BookingRefNo;
                                break;

                            case "EASYBUS":
                                EasybusAPI clsEasyBusAPI = new EasybusAPI();
                                objBookResponse = clsEasyBusAPI.bookSeats(blockSeats.SourceId, blockSeats.DestinationId, blockSeats.JourneyDate
                                    , blockSeats.TripId, blockSeats.SeatNo, blockSeats.Sex, blockSeats.Name, blockSeats.BoardingId, blockSeats.Address
                                    , blockSeats.Name, blockSeats.MobileNo, blockSeats.EmailId, blockSeats.BookingRefNo, objClientAPIDetails.APIURL
                                    , objClientAPIDetails.ConsumerKey);

                                objBookResponse.extraseatinfo = blockSeats.SourceId + "," + blockSeats.DestinationId + "," + blockSeats.JourneyDate
                              + "," + blockSeats.TripId + "," + blockSeats.SeatNo + "," + blockSeats.Title + "," + blockSeats.Name + "," + blockSeats.BoardingId + "," + blockSeats.Address
                              + "," + blockSeats.Name + "," + blockSeats.MobileNo + "," + blockSeats.EmailId + "," + blockSeats.BookingRefNo;

                                break;
                            default:
                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        objBookResponse.Message = ex.ToString();
                    }
                }
                else
                {
                    objBookResponse.Message = "no api found";
                }
                return JsonConvert.SerializeObject(objBookResponse);
            }
            else
            {
                return null;
                //throw new http exception
                //throw new System.Web.Http.HttpResponseException(HttpStatusCode.Forbidden);

            }
        }
        /// <summary>
        /// Method to get API providers list for given client credentials
        /// </summary>
        /// <param name="ConsumerKey"></param>
        /// <param name="ConsumerSecret"></param>
        private void GetAPIProvidersList(String ConsumerKey, String ConsumerSecret)
        {
            ClientAPIList objClientAPIList = new ClientAPIList();
            DataSet dsProviders = new DataSet();
            Connection = new SqlConnection(ConnectionString);
            command = new SqlCommand();
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "SP_WebAPI_GetProviders";
            command.Parameters.Add("@ConsumerKey", SqlDbType.VarChar).Value = ConsumerKey;
            command.Parameters.Add("@ConsumerSecret", SqlDbType.VarChar).Value = ConsumerSecret;
            command.Connection = Connection;
            Connection.Open();
            SqlDataAdapter da = new SqlDataAdapter(command);
            da.Fill(dsProviders);
            Connection.Close();

            //Check if atleast one provider is accessible
            if (dsProviders != null && dsProviders.Tables.Count > 0 && dsProviders.Tables[0].Rows.Count > 0)
            {
                //Loop each record, get the provider api details and add to objClientAPIList
                foreach (DataRow drProvider in dsProviders.Tables[0].Rows)
                {
                    ClientAPIDetails objClientAPIDetails = new ClientAPIDetails();
                    objClientAPIDetails.ClientID = int.Parse(drProvider["Client_ID"].ToString());
                    objClientAPIDetails.ProviderID = int.Parse(drProvider["Provider_ID"].ToString());
                    objClientAPIDetails.APIURL = drProvider["API_URL"].ToString();
                    objClientAPIDetails.ConsumerKey = drProvider["API_ConsumerKey"].ToString();
                    objClientAPIDetails.ConsumerSecret = drProvider["API_ConsumerSecret"].ToString();
                    objClientAPIDetails.DomainIP = drProvider["Domain_IP"].ToString();
                    objClientAPIDetails.ProviderName = drProvider["Provider_Name"].ToString();
                    objClientAPIList.Add(objClientAPIDetails);
                }
                //Set cache to expire after 20 minutes,i.e., the object expires
                //  and is removed from the cache 20 minutes after it is last accessed.
                HttpContext.Current.Cache.Add("ClientAPI-" + ConsumerKey, objClientAPIList, null, System.Web.Caching.Cache.NoAbsoluteExpiration,
                        new TimeSpan(0, 10, 0), System.Web.Caching.CacheItemPriority.Default, null);
                //HttpContext.Current.Cache["ClientAPI-" + ConsumerKey] = objClientAPIList;
            }
        }
        public DataSet GetcallBack(string Resrvation_Id, string url, string ConsumerKey, string ConsumerSecret, string doj)
        {
            DataSet ds = new DataSet();
            ClientAPIList objClientAPIList = new ClientAPIList();
            GetAPIProvidersList(ConsumerKey, ConsumerSecret);

            objClientAPIList = (ClientAPIList)HttpContext.Current.Cache["ClientAPI-" + ConsumerKey];

            //Check if atleast one provider is accessible
            if (objClientAPIList != null && objClientAPIList.Count > 0)
            {
                objClientAPIList.Where(e => e.ProviderName == Convert.ToString("BITLA"));
                BitlaAPI bitla = new BitlaAPI();
                SeatsInfo seat = new SeatsInfo();
                seat = bitla.getServiceDetails(Resrvation_Id, objClientAPIList[0].APIURL, objClientAPIList[0].ConsumerKey);
                ds = convertJsonStringToDataSet(JsonConvert.SerializeObject(seat));

            }
            return ds;
        }
    protected void btnSignIn_Click(object sender, EventArgs e)
    {
        try
        {

            DataSet dsticketdetails = CheckTicketID();

            if (CheckStatus)
            {
                if (dsticketdetails != null)
                {
                    int BookingId = Convert.ToInt32(dsticketdetails.Tables[0].Rows[0]["BookingId"].ToString());
                    int tentativeId = Convert.ToInt32(dsticketdetails.Tables[0].Rows[0]["TentativeId"].ToString());
                    string EmailId = dsticketdetails.Tables[0].Rows[0]["EmailId"].ToString();
                    string Name = dsticketdetails.Tables[0].Rows[0]["FullName"].ToString();
                    string seatnumbers = dsticketdetails.Tables[0].Rows[0]["SeatNos"].ToString();
                    string totalfareabhi = dsticketdetails.Tables[0].Rows[0]["TotalFare"].ToString();
                    string ticketNumberBitla = dsticketdetails.Tables[0].Rows[0]["PNRNumber"].ToString();

                    string BoardingPointName = dsticketdetails.Tables[0].Rows[0]["BoardingPointName"].ToString();
                    string DateofJourney = dsticketdetails.Tables[0].Rows[0]["DateOfJourney"].ToString();
                    string[] dd = DateofJourney.Split(' ');
                    string[] bd = BoardingPointName.Split('-');
                    string dateofjourney = dd[0];
                    string datenow = dd[0] + "" + bd[1];
                    string APIName = dsticketdetails.Tables[0].Rows[0]["APIName"].ToString();
                    lblCode.Text = GenerateRandomCode();
                    TimeSpan s = DateTime.Parse(datenow) - DateTime.Now;

                    if (s.Days > 0)
                    {
                        dayhours = Convert.ToInt32(s.Days) * 24;
                    }
                    if (s.Minutes > 30)
                    {
                        hour = dayhours + s.Hours + 1;
                    }
                    if (s.Minutes <= 30)
                    {
                        hour = dayhours + s.Hours;
                    }
                    if (hour > 0)
                    {

                        Session["NameMail"] = Name;
                        Session["EmailIdMail"] = EmailId;

                        #region Kesineni
                        if (dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "Kesineni")
                        {
                            ViewState["APIName"] = "Kesineni";
                            rbtnlstCancelType.Visible = gvPartialCancellation.Visible = btnConfrmCancel.Visible = false;
                            gvPartialCancellation.DataSource = dsticketdetails.Tables[1];
                            gvPartialCancellation.DataBind();
                            ViewState["dsticketdetails"] = dsticketdetails.Tables[0];
                            btnConfrmCancel_Click(sender, e);
                        }
                        #endregion

                        #region AbhiBus
                        else if (dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "SVR" || dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "KAVERI" || dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "RAJESH" || dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "SAIANJANA" || dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "KALLADA")
                        {
                            string ticketNumberAbhiBus = dsticketdetails.Tables[0].Rows[0]["PNRNumber"].ToString();
                            //cancelTicket
                            ClientAPIList objClientAPIList = new ClientAPIList();
                            objClientAPIList = GetAPIProvidersList(ConsumerKey, ConsumerSecret);
                            ClientAPIDetails objClientAPIDetails = objClientAPIList.SingleOrDefault(element => element.ProviderName == dsticketdetails.Tables[0].Rows[0]["APIName"].ToString()); //objClientAPIList.ElementAt(resultSet - 1)
                            LJ.CLB.Buses.AbhibusAPI obj = new LJ.CLB.Buses.AbhibusAPI();
                            DataTable dtAbhiBus = obj.cancelTicket(objClientAPIDetails.APIURL, objClientAPIDetails.ConsumerKey, ticketNumberAbhiBus);

                            if (dtAbhiBus != null)
                            {
                                if (dtAbhiBus.Rows.Count > 0)
                                {
                                    if (dtAbhiBus.Rows[0]["status"].ToString().ToUpper().Trim().ToString() == "SUCCESS")
                                    {
                                        string totalRefundAmount = dtAbhiBus.Rows[0]["total_refund_amount"].ToString();
                                        string canpercentage = dtAbhiBus.Rows[0]["cancellation_parcentage"].ToString();
                                        string[] canindec = canpercentage.Split('%');
                                        double cancelcharges = Convert.ToDouble(totalfareabhi) * (Convert.ToDouble(canindec[0].ToString()) / 100);
                                        AddCancellation(BookingId, tentativeId, seatnumbers, EmailId,
                                            Convert.ToString(Convert.ToDouble(totalfareabhi) - cancelcharges), Convert.ToString(totalfareabhi), APIName, hour);
                                        Mail(dsticketdetails.Tables[0].Rows[0]["EmailId"].ToString(), dsticketdetails.Tables[0].Rows[0]["PGMBRefNo"].ToString());
                                        // DataSet dsBalance = objBAL.GetAgentByUserId(Convert.ToInt32(Session["UserID"].ToString()));
                                        //string balance = dsBalance.Tables[0].Rows[0]["Balance"].ToString();
                                        //  Label lbl = (Label)this.Master.FindControl("lblBalance");
                                        //lbl.Text = balance;
                                        //Session["Balance"] = balance;
                                        txtEmailID.Text = txtMBRefNo.Text = "";

                                    }
                                    else
                                    {
                                        lblMsg.Text = "Ticket cancelled failed. Try Again";
                                    }
                                }
                                else
                                {
                                    lblMsg.Text = "Ticket cancelled failed. Try Again";
                                }
                            }
                            else
                            {
                                lblMsg.Text = "Ticket cancelled failed. Try Again";
                            }
                        }
                        #endregion

                        #region Kallada
                        if (dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "kallada")
                        {
                            string ticketNumberkallada = dsticketdetails.Tables[0].Rows[0]["PNRNumber"].ToString();
                            DataTable dtkallada = objkalladaAPILayer.CancellationConfirmation(ticketNumberkallada);
                            if (dtkallada != null)
                            {
                                if (dtkallada.Rows.Count > 0)
                                {
                                    if (dtkallada.Rows[0]["status"].ToString() == "Success")
                                    {
                                        string totalRefundAmount = dtkallada.Rows[0]["total_refund_amount"].ToString();
                                        string canpercentage = dtkallada.Rows[0]["cancellation_parcentage"].ToString();
                                        string[] canindec = canpercentage.Split('%');
                                        double cancelcharges = Convert.ToDouble(totalfareabhi) * (Convert.ToDouble(canindec[0].ToString()) / 100);

                                        DataTable dtKallada1 = objkalladaAPILayer.TicketCancellation(ticketNumberkallada);
                                        if (dtKallada1.Rows.Count > 0 && dtKallada1.Columns.Count > 1)
                                        {
                                            if (dtKallada1.Rows[0]["status"].ToString().ToUpper().Trim().ToString() != "FAIL")
                                            {
                                                AddCancellation(BookingId, tentativeId, seatnumbers, EmailId,
                                                    Convert.ToString(Convert.ToDouble(totalfareabhi) - cancelcharges), Convert.ToString(totalfareabhi), APIName, hour);

                                                //objBAL = new ClsBAL();
                                                //objBAL.AdjustAgentBalance(txtMBRefNo.Text.Trim().ToString(),
                                                //    Convert.ToDouble(Convert.ToDouble(totalfareabhi) - cancelcharges), Convert.ToDouble(cancelcharges),
                                                //    Convert.ToInt32(Session["UserID"].ToString()));
                                            }
                                            else { lblMsg.Text = "Ticket cancelled failed."; }

                                            DataSet dsBalance = objBAL.GetAgentByUserId(Convert.ToInt32(Session["UserID"].ToString()));

                                            string balance = dsBalance.Tables[0].Rows[0]["Balance"].ToString();
                                            Label lbl = (Label)this.Master.FindControl("lblBalance");
                                            lbl.Text = balance;
                                            Session["Balance"] = balance;
                                            txtEmailID.Text = txtMBRefNo.Text = "";
                                        }
                                    }
                                    else
                                    {
                                        lblMsg.Text = "Ticket cancelled failed. Try Again";
                                        lblMsg.ForeColor = System.Drawing.Color.Red;
                                    }
                                }
                                else
                                {
                                    lblMsg.Text = "Ticket cancelled failed. Try Again";
                                    lblMsg.ForeColor = System.Drawing.Color.Red;
                                }
                            }
                            else
                            {
                                lblMsg.Text = "Ticket cancelled failed. Try Again";
                                lblMsg.ForeColor = System.Drawing.Color.Red;
                            }
                        }
                        #endregion

                        #region Bitla
                        else if (dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "BITLA")
                        {
                            ViewState["APIName"] = "Bitla";
                            rbtnlstCancelType.Visible = gvPartialCancellation.Visible = btnConfrmCancel.Visible = false;
                            gvPartialCancellation.DataSource = dsticketdetails.Tables[1];
                            gvPartialCancellation.DataBind();
                            ViewState["dsticketdetails"] = dsticketdetails.Tables[0];
                            btnConfrmCancel_Click(sender, e);
                        }
                        #endregion

                        #region TicketGoose
                        else if (dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "TICKETGOOSE")
                        {
                            ViewState["APIName"] = "TicketGoose";
                            string ticketNumber = dsticketdetails.Tables[0].Rows[0]["PNRNumber"].ToString();
                            string[] seatNos = dsticketdetails.Tables[0].Rows[0]["SeatNos"].ToString().Split(',');
                            DataTable dt = objTicketGooseAPILayer.CancelTicket(ticketNumber, seatNos);
                            if (dt != null)
                            {
                                if (dt.Rows.Count > 0)
                                {
                                    if (dt.Rows[0]["Status"].ToString() == "Success")
                                    {
                                        DataTable dtt = objTicketGooseAPILayer.ConfirmTicketCancellation(ticketNumber, seatNos);
                                        if (dtt != null)
                                        {
                                            if (dtt.Rows.Count > 0)
                                            {
                                                if (dtt.Rows[0]["Status"].ToString() == "Success")
                                                {
                                                    string refAmount = dtt.Rows[0]["refundAmount"].ToString();

                                                    AddCancellation(BookingId, tentativeId, seatnumbers, EmailId,
                                                   refAmount, Convert.ToString(Convert.ToDouble(totalfareabhi)), APIName, hour);

                                                    Mail(dsticketdetails.Tables[0].Rows[0]["EmailId"].ToString(), dsticketdetails.Tables[0].Rows[0]["PGMBRefNo"].ToString());

                                                    //objBAL = new ClsBAL();
                                                    //objBAL.AdjustAgentBalance(txtMBRefNo.Text.Trim().ToString(),
                                                    //    Convert.ToDouble(refAmount), Convert.ToDouble(Convert.ToDouble(totalfareabhi) - Convert.ToDouble(refAmount)),
                                                    //    Convert.ToInt32(Session["UserID"]));
                                                }
                                                else { lblMsg.Text = "Ticket cancelled failed. Try Again"; }

                                                //DataSet dsBalance = objBAL.GetAgentByUserId(Convert.ToInt32(Session["UserID"]));

                                                //string balance = dsBalance.Tables[0].Rows[0]["Balance"].ToString();
                                                //Label lbl = (Label)this.Master.FindControl("lblBalance");
                                                //lbl.Text = balance;
                                                //Session["Balance"] = balance;
                                                txtEmailID.Text = txtMBRefNo.Text = "";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion

                        #region EasyBus

                        else if (dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "EASYBUS")
                        {
                            string ticketNumberEasybus = dsticketdetails.Tables[0].Rows[0]["PNRNumber"].ToString();
                            //cancelTicket
                            ClientAPIList objClientAPIList = new ClientAPIList();
                            objClientAPIList = GetAPIProvidersList(ConsumerKey, ConsumerSecret);
                            ClientAPIDetails objClientAPIDetails = objClientAPIList.SingleOrDefault(element => element.ProviderName == dsticketdetails.Tables[0].Rows[0]["APIName"].ToString()); //objClientAPIList.ElementAt(resultSet - 1)
                            LJ.CLB.Buses.EasybusAPI obj = new LJ.CLB.Buses.EasybusAPI();
                            DataTable dtEasybus = obj.cancelTicket(objClientAPIDetails.APIURL, objClientAPIDetails.ConsumerKey, ticketNumberEasybus, seatnumbers, dateofjourney);
                            if (dtEasybus != null)
                            {
                                if (dtEasybus.Rows.Count > 0)
                                {
                                    if (dtEasybus.Rows[0]["Message"].ToString() == "Your Ticket has been cancelled")
                                    {

                                        string totalRefundAmount = totalfareabhi;
                                        string canpercentage = "10";
                                        string[] canindec = canpercentage.Split('%');
                                        double cancelcharges = Convert.ToDouble(totalfareabhi) * (Convert.ToDouble(canindec[0].ToString()) / 100);

                                        AddCancellation(BookingId, tentativeId, seatnumbers, EmailId,
                                           Convert.ToString(Convert.ToDouble(totalfareabhi) - cancelcharges), Convert.ToString(totalfareabhi), APIName, hour);
                                        Mail(dsticketdetails.Tables[0].Rows[0]["EmailId"].ToString(), dsticketdetails.Tables[0].Rows[0]["PGMBRefNo"].ToString());

                                    }
                                }
                            }

                        }
                        #endregion
                    }
                    else
                    {
                        tdmsg.Visible = true;
                        lblMainMsg.Text = "Invalid LoveJourney Ref No.";
                        lblMainMsg.ForeColor = System.Drawing.Color.Maroon;
                        txtMBRefNo.Text = "";
                    }
                }
                else
                {
                    tdmsg.Visible = true;
                    lblMainMsg.Text = "Invalid LoveJourney Ref No.";
                    lblMainMsg.ForeColor = System.Drawing.Color.Maroon;
                    txtMBRefNo.Text = "";

                }
            }
            else
            {
                tdmsg.Visible = true;
                lblMainMsg.Text = "Invalid LoveJourney Ref No.";
                lblMainMsg.ForeColor = System.Drawing.Color.Maroon;
                txtMBRefNo.Text = "";
                txtEmailID.Text = "";

            }

        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
            throw ex;
        }
    }
    protected void btnSignIn_Click(object sender, EventArgs e)
    {
        try
        {
            DataSet dsticketdetails = CheckTicketID();
            if (CheckStatus)
            {
                if (dsticketdetails != null)
                {
                    int BookingId = Convert.ToInt32(dsticketdetails.Tables[0].Rows[0]["BookingId"].ToString());
                    int tentativeId = Convert.ToInt32(dsticketdetails.Tables[0].Rows[0]["TentativeId"].ToString());
                    string EmailId = dsticketdetails.Tables[0].Rows[0]["EmailId"].ToString();
                    string Name = dsticketdetails.Tables[0].Rows[0]["FullName"].ToString();
                    string seatnumbers = dsticketdetails.Tables[0].Rows[0]["SeatNos"].ToString();
                    string totalfareabhi = dsticketdetails.Tables[0].Rows[0]["TotalFare"].ToString();
                    string ticketNumberBitla = dsticketdetails.Tables[0].Rows[0]["PNRNumber"].ToString();

                    Session["NameMail"] = Name;
                    Session["EmailIdMail"] = EmailId;

                    #region Kesineni
                    if (dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "Kesineni")
                    {
                        ViewState["APIName"] = "Kesineni";
                        rbtnlstCancelType.Visible = gvPartialCancellation.Visible = btnConfrmCancel.Visible = true;
                        gvPartialCancellation.DataSource = dsticketdetails.Tables[1];
                        gvPartialCancellation.DataBind();
                        ViewState["dsticketdetails"] = dsticketdetails.Tables[0];
                    }
                    #endregion

                    #region AbhiBus
                    else if (dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "SVR" || dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "KAVERI" || dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "RAJESH" || dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "SAIANJANA" || dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "KALLADA")
                    {
                        string ticketNumberAbhiBus = dsticketdetails.Tables[0].Rows[0]["PNRNumber"].ToString();//"OHYD19615";
                        //cancelTicket
                        ClientAPIList objClientAPIList = new ClientAPIList();
                        objClientAPIList = GetAPIProvidersList(ConsumerKey, ConsumerSecret);
                        ClientAPIDetails objClientAPIDetails = objClientAPIList.SingleOrDefault(element => element.ProviderName == dsticketdetails.Tables[0].Rows[0]["APIName"].ToString()); //objClientAPIList.ElementAt(resultSet - 1)
                        LJ.CLB.Buses.AbhibusAPI obj = new LJ.CLB.Buses.AbhibusAPI();
                        DataTable dtAbhiBus = obj.cancelTicket(objClientAPIDetails.APIURL, objClientAPIDetails.ConsumerKey, ticketNumberAbhiBus);

                        if (dtAbhiBus != null)
                        {
                            if (dtAbhiBus.Rows.Count > 0)
                            {
                                if (dtAbhiBus.Rows[0]["status"].ToString().ToUpper().Trim().ToString() == "SUCCESS")
                                {
                                    string totalRefundAmount = dtAbhiBus.Rows[0]["total_refund_amount"].ToString();
                                    string canpercentage = dtAbhiBus.Rows[0]["cancellation_parcentage"].ToString();
                                    string[] canindec = canpercentage.Split('%');
                                    double cancelcharges = Convert.ToDouble(totalfareabhi) * (Convert.ToDouble(canindec[0].ToString()) / 100);
                                    AddCancellation(BookingId, tentativeId, seatnumbers, EmailId, Convert.ToString(Convert.ToDouble(totalfareabhi) - cancelcharges), Convert.ToString(cancelcharges));
                                    Mail(dtAbhiBus.Rows[0]["EmailId"].ToString(), dtAbhiBus.Rows[0]["PGMBRefNo"].ToString());
                                }
                            }
                            else
                            {
                                lblMsg.Text = "Ticket cancelled failed.Try Again";
                            }
                        }
                        else
                        {
                            lblMsg.Text = "Ticket cancelled failed.Try Again";
                        }
                    }
                    #endregion

                    #region Bitla
                    else if (dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "BITLA")
                    {
                        ViewState["APIName"] = "Bitla";
                        rbtnlstCancelType.Visible = gvPartialCancellation.Visible = btnConfrmCancel.Visible = true;
                        gvPartialCancellation.DataSource = dsticketdetails.Tables[1];
                        gvPartialCancellation.DataBind();
                        ViewState["dsticketdetails"] = dsticketdetails.Tables[0];
                        btnConfrmCancel_Click(sender, e);
                    }
                    #endregion

                    #region Kallada
                    if (dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "kallada")
                    {

                        string ticketNumberkallada = dsticketdetails.Tables[0].Rows[0]["PNRNumber"].ToString();//"OHYD19615";
                        DataTable dtkallada = objkalladaAPILayer.CancellationConfirmation(ticketNumberkallada);
                        if (dtkallada != null)
                        {
                            if (dtkallada.Rows.Count > 0)
                            {
                                if (dtkallada.Rows[0]["status"].ToString() == "Success")
                                {
                                    string totalRefundAmount = dtkallada.Rows[0]["total_refund_amount"].ToString();
                                    string canpercentage = dtkallada.Rows[0]["cancellation_parcentage"].ToString();
                                    string[] canindec = canpercentage.Split('%');
                                    double cancelcharges = Convert.ToDouble(totalfareabhi) * (Convert.ToDouble(canindec[0].ToString()) / 100);

                                    DataTable dtKallada1 = objkalladaAPILayer.TicketCancellation(ticketNumberkallada);
                                    if (dtKallada1.Rows.Count > 0 && dtKallada1.Columns.Count > 1)
                                    {
                                        AddCancellation(BookingId, tentativeId, seatnumbers, EmailId, Convert.ToString(Convert.ToDouble(totalfareabhi) - cancelcharges), Convert.ToString(cancelcharges));
                                    }
                                }
                                else
                                {
                                    lblMsg.Text = "Ticket cancelled failed.Try Again";
                                    lblMsg.ForeColor = System.Drawing.Color.Red;
                                }
                            }
                            else
                            {
                                lblMsg.Text = "Ticket cancelled failed.Try Again";
                                lblMsg.ForeColor = System.Drawing.Color.Red;
                            }
                        }
                        else
                        {
                            lblMsg.Text = "Ticket cancelled failed.Try Again";
                            lblMsg.ForeColor = System.Drawing.Color.Red;
                        }
                    }
                    #endregion

                    #region TicketGoose
                    else if (dsticketdetails.Tables[0].Rows[0]["APIName"].ToString() == "TICKETGOOSE")
                    {
                        ViewState["APIName"] = "TicketGoose";
                        string ticketNumber = dsticketdetails.Tables[0].Rows[0]["PNRNumber"].ToString();
                        string[] seatNos = dsticketdetails.Tables[0].Rows[0]["SeatNos"].ToString().Split(',');
                        DataTable dt = objTicketGooseAPILayer.CancelTicket(ticketNumber, seatNos);
                        if (dt != null)
                        {
                            if (dt.Rows.Count > 0)
                            {
                                if (dt.Rows[0]["Status"].ToString() == "Success")
                                {
                                    DataTable dtt = objTicketGooseAPILayer.ConfirmTicketCancellation(ticketNumber, seatNos);
                                    if (dtt != null)
                                    {
                                        if (dtt.Rows.Count > 0)
                                        {
                                            if (dtt.Rows[0]["Status"].ToString() == "Success")
                                            {
                                                string refAmount = dtt.Rows[0]["refundAmount"].ToString();

                                                AddCancellation(BookingId, tentativeId, seatnumbers, EmailId,
                                               refAmount, Convert.ToString(Convert.ToDouble(totalfareabhi) - Convert.ToDouble(refAmount)));

                                                Mail(dt.Rows[0]["EmailId"].ToString(), dt.Rows[0]["PGMBRefNo"].ToString());

                                            }
                                            else { lblMsg.Text = "Ticket cancelled failed. Try Again"; }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }
                else
                {
                    txtMBRefNo.Text = "";
                    lblCancelMessage.Visible = true;
                    lblCancelMessage.Text = "Invalid Love Journey RefNo";
                    lblCancelMessage.ForeColor = System.Drawing.Color.Maroon;
                }
            }
            else
            {
                txtMBRefNo.Text = "";
                lblCancelMessage.Visible = true;
                lblCancelMessage.Text = "Invalid Love Journey RefNo";
                lblCancelMessage.ForeColor = System.Drawing.Color.Maroon;

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }