示例#1
0
        /// <summary>
        /// This method does all the work of extracting data and calling methods for processing them.
        /// </summary>
        public void callMethods()
        {
            log.Info("In callMethods");
            IWorker worker = new Worker();

            // Step 1: Getting missing duties
            DataSet missingDuties = worker.getMissingDuties();

            // Step 2: Create Shift Records
            ICreateShiftRecords createShiftRecords = new CreateShift();
            IgetDutyDetailsBMS  getDutyfromBMS     = new GetDutyDetails();
            //ICreateTripRecords createTrips = new CreateTrips();
            ICreateTripRecords createTrips = null;
            IgetTripDataAVL    getAVLTrips = new GetTripDataAVL();

            /* Traverse the Missing Records DataSet,
             * One by one get the details from BMS corresponding to all the shifts(Duties).
             * Pass Duty, Duty Date and Conductor ID to get all the records.
             */

            // TEST ARRAY LIST FOR TESTING SHIFTS CREATED VS PUSHED IN PARTIAL TABLE.
            List <string>             shiftsCreated       = new List <string>();
            List <string>             shiftsWithNoAVLData = new List <string>();
            List <string>             shiftsNotCreated    = new List <string>();
            List <string>             shiftsDeleted       = new List <string>();
            Dictionary <string, bool> shiftsInsertResult  = new Dictionary <string, bool>();

            // Traversing the rows of missing duties.
            for (int i = 0; i < missingDuties.Tables[0].Rows.Count; i++)
            {
                // Get Duty[BMS_DUTY_NO],Duty_date[BMS_DUTY_DATE] and Conductor ID[BMS_CONDUCTOR_ID]
                string[] Duty         = missingDuties.Tables[0].Rows[i]["BMS_DUTY_NO"].ToString().Split(',');
                string   Duty_Date    = missingDuties.Tables[0].Rows[i]["BMS_DUTY_DATE"].ToString();
                string   Conductor_ID = missingDuties.Tables[0].Rows[i]["BMS_CONDUCTOR_ID"].ToString();

                if (Conductor_ID.Length < 5)
                {
                    Conductor_ID = "0" + Conductor_ID;
                }

                // Converting Duty Date format to one required by BMS
                string[] dutyDateArr = Duty_Date.Split(' ');
                var      ci          = new CultureInfo("");
                //var formats = new[] { "M-d-yyyy", "dd-MM-yyyy", "MM-dd-yyyy", "dd/MM/yyyy", "dd/MMM/yyyy", "dd-MMM-yyyy" }.Union(ci.DateTimeFormat.GetAllDateTimePatterns()).ToArray();
                var      formats = new[] { "dd-MM-yyyy" }.Union(ci.DateTimeFormat.GetAllDateTimePatterns()).ToArray();
                DateTime Duty_Date_con = DateTime.ParseExact(dutyDateArr[0], formats, ci, DateTimeStyles.AssumeLocal);
                string   finalDutyDate = Duty_Date_con.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);


                // In Case of Multiple Duties passed in Duty Column of BMS then Iterate through all the duties.
                for (int dutySeq = 0; dutySeq < Duty.Length; dutySeq++)
                {
                    // Step 3: Get Shift Data from BMS.
                    // Pass Type 1 for Shift and 2 for Trips
                    int type = 1;

                    /* Uncomment before moving to production */
                    DataSet dutyReceivedFromBMS = getDutyfromBMS.getDutyDetailsFromBMS(type, Duty[dutySeq], finalDutyDate, Conductor_ID);

                    /* TESTING With Dev Data */
                    //DataSet dutyReceivedFromBMS = UTC.getTestBMSShiftData(Duty[dutySeq], finalDutyDate, Conductor_ID);

                    // Iterate only if DataSet has rows in it.
                    if (dutyReceivedFromBMS.Tables[0].Rows.Count > 0)
                    {
                        /* UnComment before Moveing into Production */
                        // Step 5: Save result of BMS in Oracle
                        SaveBMSResult sbr        = new SaveBMSResult();
                        bool          saveResult = sbr.saveBMSData(dutyReceivedFromBMS);

                        if (saveResult == false)
                        {
                            // Store this [Duty, finalDutyDate, Conductor_ID] in Exceptions Table. Reason Data Fetched could not be saved
                            log.Warn(finalDutyDate + "," + Duty[dutySeq] + "," + Conductor_ID + " Could not be stored in table BMS_DATA.");
                            string query         = "INSERT INTO RECON_EXCEPTIONS (DUTY_DATE,DUTY_NAME,CONDUCTOR_ID,EXCEPTION_DATE,REMARKS) VALUES ('" + finalDutyDate + "','" + Duty[dutySeq] + "','" + Conductor_ID + "',sysdate,'Unable to Save BMS Data in BMS_DATA table')";
                            bool   saveException = oracle.saveException(query);
                            continue;
                        }
                        /* UnComment before Moveing into Production */

                        // Step 6: Create Shift
                        Dictionary <string, string> shiftDetails = new Dictionary <string, string>();
                        shiftDetails = createShiftRecords.createShift(dutyReceivedFromBMS);

                        //Proceed only when shift was successfully created
                        string shiftCreationResult = shiftDetails["Created"];

                        if (shiftCreationResult.Equals("DUTY_NOT_PRESENT"))
                        {
                            log.Warn(finalDutyDate + "," + Duty[dutySeq] + "," + Conductor_ID + " BMS and ETM Duty could not be matched.");
                            string query         = "INSERT INTO RECON_EXCEPTIONS (DUTY_DATE,DUTY_NAME,CONDUCTOR_ID,EXCEPTION_DATE,REMARKS) VALUES ('" + finalDutyDate + "','" + Duty[dutySeq] + "','" + Conductor_ID + "',sysdate,'BMS and ETM Duty could not be matched')";
                            bool   saveException = oracle.saveException(query);
                            continue;
                        }
                        else if (shiftCreationResult.Equals("TRUE"))
                        {
                            // TEST
                            shiftsCreated.Add(shiftDetails["Shift_ID"]);

                            /* UnComment before Moveing into Production */
                            // Step 7: Get Data from AVL
                            DataSet TripData_AVL = getAVLTrips.getTripDataFromAVL(Duty[dutySeq], finalDutyDate);

                            /* TESTING With Dev Data */
                            //DataSet TripData_AVL = UTC.getTestAVLData(Duty[dutySeq], finalDutyDate);

                            if (TripData_AVL.Tables[0].Rows.Count > 0)
                            {
                                // Step 8: Push shift Record to Partial_Shift_Closer Table in Oracle
                                ISaveShiftRecord saveShift    = new SaveShiftRecord();
                                bool             isShiftSaved = saveShift.saveTripRecord(shiftDetails);

                                // TEST
                                shiftsInsertResult.Add(shiftDetails["Shift_ID"], isShiftSaved);

                                /* UnComment before Moveing into Production */
                                // Step 9: Save AVL Result in Oracle
                                SaveAVLResult sar = new SaveAVLResult();
                                sar.saveAVLData(TripData_AVL);


                                /* UnComment before Moveing into Production */
                                // Step 10: Get Trip Data from BMS
                                IgetTripDataBMS tripDataBMS    = new GetTripDataBMS();
                                DataSet         tripDataBMS_DS = new DataSet();
                                tripDataBMS_DS = tripDataBMS.getTripDataFromBMS(Duty[dutySeq], finalDutyDate, Conductor_ID);

                                /* TESTING With Dev Data */
                                //DataSet tripDataBMS_DS = new DataSet();
                                //tripDataBMS_DS = UTC.getTripDataBMS(Duty[dutySeq], finalDutyDate, Conductor_ID);

                                if (tripDataBMS_DS.Tables[0].Rows.Count > 0)
                                {
                                    // Check If Trip from BMS is less than or equal to Trips in AVL, if not then save it as exception and delete its shift.
                                    if (tripDataBMS_DS.Tables[0].Rows.Count <= TripData_AVL.Tables[0].Rows.Count)
                                    {
                                        /* UnComment before Moveing into Production */
                                        // Save fetched Trip Data for records.
                                        SaveBMSTripData vSaveBMSTripData = new SaveBMSTripData();
                                        bool            tripBackupSucces = vSaveBMSTripData.saveBMSDataTRIP(tripDataBMS_DS);

                                        // Step 11: Create Trips
                                        createTrips = new CreateTrips();
                                        DataSet Trips = new DataSet();
                                        Trips = createTrips.createTrip(shiftDetails, TripData_AVL, tripDataBMS_DS);



                                        /* If Returned Trips DataSet has no record then Continue to next record in iteration */
                                        if (Trips.Tables[0].Rows.Count <= 0)
                                        {
                                            continue;
                                        }


                                        // Step 12: Push Trip Records to Partial_Closure_History Table in Oracle
                                        if (isShiftSaved)
                                        {
                                            ISaveTripRecord saveTrip    = new SaveTripRecord();
                                            bool            isTripSaved = saveTrip.saveTripRecord(Trips);
                                        }
                                        else
                                        {
                                            // Add to Exception : Shift was not inserted into Partial_Shift_Closer.
                                            log.Error(finalDutyDate + "," + Duty[dutySeq] + "," + Conductor_ID + " : Shift=" + shiftDetails["Shift_ID"] + " was not inserted into Partial_Shift_Closer");
                                            string query         = "INSERT INTO RECON_EXCEPTIONS (DUTY_DATE,DUTY_NAME,CONDUCTOR_ID,EXCEPTION_DATE,REMARKS) VALUES ('" + finalDutyDate + "','" + Duty[dutySeq] + "','" + Conductor_ID + "',sysdate,'Shift was not inserted into Partial_Shift_Closer, Check Log for Database Error')";
                                            bool   saveException = oracle.saveException(query);
                                        }
                                    }
                                    // This else would run when Trips received from BMS and AVL Mismatch.[Line no. 147]
                                    else
                                    {
                                        // Store this [Duty, finalDutyDate, Conductor_ID] in Exceptions Table.
                                        // Remarks : Shift Created but Trips Not Found in BMS.
                                        log.Error(finalDutyDate + "," + Duty[dutySeq] + "," + Conductor_ID + " : Shift=" + shiftDetails["Shift_ID"] + " Shift Created but Number of Trips mismatched in BMS and AVL.");
                                        string query                  = "INSERT INTO RECON_EXCEPTIONS (DUTY_DATE,DUTY_NAME,CONDUCTOR_ID,EXCEPTION_DATE,REMARKS) VALUES ('" + finalDutyDate + "','" + Duty[dutySeq] + "','" + Conductor_ID + "',sysdate,'Shift Created but Number of Trips mismatched in BMS and AVL.')";
                                        bool   saveException          = oracle.saveException(query);
                                        string shiftForDeletion       = shiftDetails["Shift_ID"];
                                        RollbackCreatedShift rollback = new RollbackCreatedShift();
                                        bool isShiftDeleted           = rollback.rollbackShift(shiftForDeletion);
                                        if (isShiftDeleted)
                                        {
                                            shiftsDeleted.Add(shiftForDeletion);
                                            shiftsInsertResult.Remove(shiftForDeletion);
                                            log.Warn(shiftForDeletion + " Shift_ID Deleted as Number of Trips mismatched in BMS and AVL.");
                                        }
                                    }
                                }
                                // This else would be executed when Trips are not found in BMS.
                                else
                                {
                                    // Store this [Duty, finalDutyDate, Conductor_ID] in Exceptions Table.
                                    // Remarks : Shift Created but Trips Not Found in BMS.
                                    log.Error(finalDutyDate + "," + Duty[dutySeq] + "," + Conductor_ID + " : Shift=" + shiftDetails["Shift_ID"] + " Shift Created but Trips Not Found in BMS.");
                                    string query         = "INSERT INTO RECON_EXCEPTIONS (DUTY_DATE,DUTY_NAME,CONDUCTOR_ID,EXCEPTION_DATE,REMARKS) VALUES ('" + finalDutyDate + "','" + Duty[dutySeq] + "','" + Conductor_ID + "',sysdate,'Shift Created but Trips Not Found in BMS')";
                                    bool   saveException = oracle.saveException(query);

                                    // Rollback the Shift from PARTIAL_SHIFT_CLOSER Table.
                                    string shiftForDeletion = shiftDetails["Shift_ID"];

                                    RollbackCreatedShift rollback = new RollbackCreatedShift();
                                    bool isShiftDeleted           = rollback.rollbackShift(shiftForDeletion);

                                    if (isShiftDeleted)
                                    {
                                        shiftsDeleted.Add(shiftForDeletion);
                                        shiftsInsertResult.Remove(shiftForDeletion);
                                        log.Warn(shiftForDeletion + " Shift_ID Deleted as corresponding Trips Not Found in BMS.");
                                    }
                                }
                            }
                            // This else would be executed when AVL Data is not Present.
                            else
                            {
                                // Store this [Duty, finalDutyDate, Conductor_ID] in Exceptions Table.
                                //bool error = true;
                                shiftsWithNoAVLData.Add(shiftDetails["Shift_ID"]);
                                log.Error(finalDutyDate + "," + Duty[dutySeq] + "," + Conductor_ID + "Data Not Present in AVL.");
                                string query         = "INSERT INTO RECON_EXCEPTIONS (DUTY_DATE,DUTY_NAME,CONDUCTOR_ID,EXCEPTION_DATE,REMARKS) VALUES ('" + finalDutyDate + "','" + Duty[dutySeq] + "','" + Conductor_ID + "',sysdate,'Data Not Present in AVL')";
                                bool   saveException = oracle.saveException(query);
                            }
                        }
                        // Else for shiftCreationResult
                        else
                        {
                            // Shift was Not Created.
                            // Store this [Duty, finalDutyDate, Conductor_ID] in Exceptions Table.
                            log.Error(finalDutyDate + "," + Duty[dutySeq] + "," + Conductor_ID + "Shift Could not be Created.");
                            string message = "Duty=" + Duty[dutySeq] + " Duty_Date=" + finalDutyDate + " Conductor_ID=" + Conductor_ID;
                            shiftsNotCreated.Add(message);

                            string query         = "INSERT INTO RECON_EXCEPTIONS (DUTY_DATE,DUTY_NAME,CONDUCTOR_ID,EXCEPTION_DATE,REMARKS) VALUES ('" + finalDutyDate + "','" + Duty[dutySeq] + "','" + Conductor_ID + "',sysdate,'Shift Could not be Created')";
                            bool   saveException = oracle.saveException(query);
                        }
                    }
                    // Else for dutyReceivedFromBMS
                    else
                    {
                        // BMS Does not have data for queried Duty.
                        // Store this [Duty, finalDutyDate, Conductor_ID] in Exceptions Table.
                        log.Error(finalDutyDate + "," + Duty[dutySeq] + "," + Conductor_ID + "BMS Does not have data for this duty.");
                        string query         = "INSERT INTO RECON_EXCEPTIONS (DUTY_DATE,DUTY_NAME,CONDUCTOR_ID,EXCEPTION_DATE,REMARKS) VALUES ('" + finalDutyDate + "','" + Duty[dutySeq] + "','" + Conductor_ID + "',sysdate,'BMS Does not have data for this duty')";
                        bool   saveException = oracle.saveException(query);
                    }
                    // For testing
                    //break
                } // End of for loop in case of multiple Duties passed separated by (,) in BMS.
            }
            log.Info("========================= SUMMARY OF THIS CYCLE =========================");
            log.Info("Total Number of Missing Records Present : " + missingDuties.Tables[0].Rows.Count);
            log.Info("Total Number of Shifts Created          : " + shiftsCreated.Count.ToString());
            log.Info("Total Number of Shifts With No AVL Data : " + shiftsWithNoAVLData.Count.ToString());
            log.Info("Number of Shifts failed while creation  : " + shiftsNotCreated.Count.ToString());
            log.Info("Number of Shifts Deleted while creation : " + shiftsDeleted.Count.ToString());
            // Shift_ID Insert in Partial Table Result
            log.Info("Shift_ID Insert in Partial Table Result : " + shiftsInsertResult.Count.ToString());
            log.Info("--------SHIFT_ID--------" + " : " + "-RESULT-");
            foreach (KeyValuePair <string, bool> entry in shiftsInsertResult)
            {
                log.Info((entry.Key).PadRight(26) + " : " + entry.Value);
            }
            if (shiftsWithNoAVLData.Count > 0)
            {
                log.Info("");
                log.Info("Shifts With No AVL Data    : " + shiftsWithNoAVLData.Count.ToString());
                log.Info("--------SHIFT_ID--------");
                foreach (string item in shiftsWithNoAVLData)
                {
                    log.Info(item);
                }
            }
            log.Info("========================= END OF SUMMARY ================================");
            log.Info("Exiting callMethods");
        }
示例#2
0
        public DataSet createTrip(Dictionary <string, string> shiftDetails, DataSet TripData_AVL, DataSet tripDataBMS)
        {
            log.Info("In CreateTrips");
            DataSet Trips = new DataSet();

            GetTripDataTable TripsDT = new GetTripDataTable();
            DataTable        dt      = TripsDT.TripDataTable();

            // Declaring Variables
            string DUTY_ID      = tripDataBMS.Tables[0].Rows[0]["DUTY_NO"].ToString();
            string DEPOT_ID     = shiftDetails["Depot_ID"];
            string ETM_SR_NO    = shiftDetails["ETM_SR_NO"];
            string DATE_OF_DUTY = string.Empty;
            string TRIP_ID      = string.Empty;

            string SUM_TDR_TRIP   = string.Empty;
            string COUNT_TDR_TRIP = string.Empty;

            string WAYBILL_TDR_CASH  = string.Empty;
            string WAYBILL_TDR_COUNT = string.Empty;

            string DATE_OF_SUBMISSION = string.Empty;

            string CONFIRM_TDR_CASH  = string.Empty; // would be populated on confirmation
            string CONFIRM_TDR_COUNT = string.Empty; // would be populated on confirmation

            string CONFIRMATION_FLAG = "0";

            string CONFIRMATION_DATE = string.Empty; // would be populated on confirmation
            string CONFIRMATION_ID   = string.Empty; // would be populated on confirmation

            string SUBMITTER_ID = "Auto Recon";
            string SHIFT_ID     = shiftDetails["Shift_ID"];

            string TRIP_END_TIME   = string.Empty;
            string TRIP_START_TIME = string.Empty;

            string FLAG = "C";

            string ROUTETYPE = string.Empty; // From query

            string SERVICETYPE = "1";

            string ORG_STOP_ID  = string.Empty;
            string DEST_STOP_ID = string.Empty;
            string ROUTENAME    = string.Empty;

            string REASON         = "Device got Tempered";
            string REMARKS        = "Auto Recon";
            string SUM_TDR_DMRC   = "0";
            string COUNT_TDR_DMRC = "0";

            string shiftTotalRevenue     = shiftDetails["ETM_REVENUE"];
            string shift_passenger_count = shiftDetails["PASSENGER_COUNT"];

            var ci = new CultureInfo("");
            var formats = new[] { "dd-MM-yyyy" }.Union(ci.DateTimeFormat.GetAllDateTimePatterns()).ToArray();

            // Trip Tickets Sum
            int sumOfTripTickets = 0;

            // Maintaining Trip Seq with Maximum Tickets
            int maxTicketsCount = 0;

            // Global Max Node which holds the TripSeq number and Ticket Count
            maxTicketNode maxNode = new maxTicketNode();

            /* Iterate through Data fetched from BMS and Create required records */
            for (int i = 0; i < tripDataBMS.Tables[0].Rows.Count; i++)
            {
                DataRow dr = dt.NewRow();

                //Step 1: Create Trip_ID
                TRIP_ID = "T";
                string totalTripCount = tripDataBMS.Tables[0].Rows.Count.ToString();
                string tripSeq        = tripDataBMS.Tables[0].Rows[i]["SequenceofTrip"].ToString();
                string seqNo          = "";
                if (totalTripCount.Length == 1)
                {
                    //seqNo = "0" + tripSeq;
                    seqNo = "0" + (i + 1).ToString();
                }
                else
                {
                    //seqNo = tripSeq;
                    seqNo = (i + 1).ToString();
                }

                string ETM_UID = shiftDetails["ETM_UID"];

                string[] dutyAllocationDateBMS = tripDataBMS.Tables[0].Rows[i]["DUTY_ALLOCATION_DATE"].ToString().Split(' ');
                DateTime dutyAllocationDate    = DateTime.ParseExact(dutyAllocationDateBMS[0], formats, ci, DateTimeStyles.AssumeLocal);
                string   finalDutyDate         = dutyAllocationDate.ToString("dd-MM-yy", CultureInfo.InvariantCulture);

                string[] tripStartTimeBMS = tripDataBMS.Tables[0].Rows[i]["TRIP_START_TIME"].ToString().Split(' ');
                string   finalDutyTime    = tripStartTimeBMS[1];

                string tripDateTime = finalDutyDate.Replace("-", "") + finalDutyTime.Replace(":", "").Substring(0, 4);

                TRIP_ID = TRIP_ID + ETM_UID + tripDateTime + seqNo;


                // Step 2: Create DATE_OF_DUTY
                DATE_OF_DUTY = dutyAllocationDate.ToString("dd-MMM-yy", CultureInfo.InvariantCulture);
                DATE_OF_DUTY = DATE_OF_DUTY + " " + finalDutyTime;

                // Step 3: SUM_TDR_TRIP
                SUM_TDR_TRIP = tripDataBMS.Tables[0].Rows[i]["ETM_REVENUE"].ToString();

                // Step 4: Calculate Ticket Count [COUNT_TDR_TRIP]

                /* Start of Number of Tickets Calculation for Trip in Iteration */

                // Current Trip Revenue
                double etmTripRevenue = double.Parse(SUM_TDR_TRIP);
                // Shift Total Revenue
                double etmShiftRevenue = double.Parse(shiftTotalRevenue);
                // Total number of tickets in Shift
                double shiftPassengerCount = double.Parse(shift_passenger_count);
                // Percentage of Trip revenue with Shift revenue
                double percentageTripRevenueWithShift = ((etmTripRevenue / etmShiftRevenue) * 100);
                // Number of tickets as per percentage of Trip Revenue with Shift
                double numberOfTicketsByPercentage = (percentageTripRevenueWithShift * shiftPassengerCount) / 100;
                // Get the floor value of Ticket Count
                int tripTicketCount = (int)Math.Floor(numberOfTicketsByPercentage);
                // Counting sum of tickets.
                sumOfTripTickets += tripTicketCount;

                int tripSeqInt = int.Parse(seqNo);
                // keeps the Global max ticket count.
                maxTicketsCount = Math.Max(maxTicketsCount, tripTicketCount);
                // Keep the ticket count and trip seq for current iteration
                maxTicketNode tempNode = new maxTicketNode(tripTicketCount, tripSeqInt);
                // Update COUNT_TDR_TRIP
                COUNT_TDR_TRIP = tempNode.ticketCount.ToString();

                // Compare Object to get maximum
                int res = tempNode.Compare(tempNode, maxNode);
                // If there is a new Max then update the global Max node.
                if (res == 1)
                {
                    maxNode = tempNode;
                }

                /* End of Number of Tickets Calculation for Trip in Iteration */

                // Step 5: WAYBILL_TDR_CASH
                WAYBILL_TDR_CASH = SUM_TDR_TRIP;

                // Step 6: WAYBILL_TDR_COUNT
                WAYBILL_TDR_COUNT = COUNT_TDR_TRIP;

                // Step 7: Get TRIP_END_TIME
                TRIP_START_TIME = DATE_OF_DUTY;

                // Step 8: Get TRIP_END_TIME
                string[] tripDate        = DATE_OF_DUTY.Split(' ');
                string[] tripEndTimeTemp = tripDataBMS.Tables[0].Rows[i]["TRIP_END_TIME"].ToString().Split(' ');
                TRIP_END_TIME = tripDate[0] + " " + tripEndTimeTemp[1];

                // Step 9: Get ROUTETYPE
                string   route_ID      = string.Empty;
                string[] route_ID_Temp = tripDataBMS.Tables[0].Rows[i]["DUTY_NO"].ToString().Split('/');
                string   completeRoute = route_ID_Temp[0];
                Regex    regex         = new Regex("[A-Z].{0}");
                completeRoute = regex.Replace(completeRoute, "");
                if (completeRoute[completeRoute.Length - 1].Equals('A'))
                {
                    route_ID = completeRoute.Substring(0, completeRoute.Length - 2);
                }
                else
                {
                    route_ID = completeRoute;
                }
                OracleConnection_Class con = new OracleConnection_Class();
                ROUTETYPE = con.getRouteType(route_ID);

                if (TripData_AVL.Tables[0].Rows.Count > 0)
                {
                    GetRouteDetails             GRD    = new GetRouteDetails();
                    Dictionary <string, string> result = new Dictionary <string, string>();
                    DateTime dutyDate = dutyAllocationDate;
                    result = GRD.getRouteData(SHIFT_ID, dutyDate, tripSeq);

                    //DataSet origin_destination_ID = new DataSet();
                    //string origin_dest_ID_query = "SELECT ROUTENAME,ORIGIN,DESTINATION,DIRECTION FROM ETM.ROUTE_MASTER WHERE ROUTENAME = '" + TripData_AVL.Tables[0].Rows[i]["Route_Name"].ToString().Trim()+ "'";
                    //origin_destination_ID = con.SelectRecordsETMDB(origin_dest_ID_query);

                    if (result["RESULT"].Equals("TRUE"))
                    {
                        // Step 10: ROUTENAME
                        ROUTENAME = result["ROUTENAME"].ToString();

                        // Step 11: ORG_STOP_ID
                        ORG_STOP_ID = result["ORIGIN"].ToString();

                        // Step 12: DEST_STOP_ID
                        DEST_STOP_ID = result["DESTINATION"].ToString();
                    }
                    // When ETM Db does not have data for routename passed from AVL.
                    else
                    {
                        // Check in the table AVL_ETM_ROUTEMAP

                        /*DataSet RouteNameFromAVL_ETM_Map = new DataSet();
                         * string getRouteNameFromMap = "SELECT ETM_ROUTENAME FROM AVL_ETM_ROUTEMAP where AVL_ROUTENAME='" + TripData_AVL.Tables[0].Rows[i]["Route_Name"].ToString().ToUpper().Trim() + "'";
                         * RouteNameFromAVL_ETM_Map = con.SelectRecordsOleDb(getRouteNameFromMap);
                         *
                         * // Routename found in Map
                         * if (RouteNameFromAVL_ETM_Map.Tables[0].Rows.Count > 0)
                         * {
                         *  ROUTENAME = RouteNameFromAVL_ETM_Map.Tables[0].Rows[0]["ETM_ROUTENAME"].ToString();
                         *
                         *  // Get Dest and Origin ID and Fill
                         *  DataSet OD_ID = new DataSet();
                         *  string OD_ID_Query = "SELECT ROUTENAME,ORIGIN,DESTINATION,DIRECTION FROM ETM.ROUTE_MASTER WHERE ROUTENAME = '" + ROUTENAME + "'";
                         *  OD_ID = con.SelectRecordsETMDB(OD_ID_Query);
                         *
                         *  ORG_STOP_ID = OD_ID.Tables[0].Rows[0]["ORIGIN"].ToString();
                         *
                         *  DEST_STOP_ID = OD_ID.Tables[0].Rows[0]["DESTINATION"].ToString();
                         *
                         * }
                         * // RouteName not found in Map
                         * else {
                         *  routeNameException = true;
                         *  // Add this Trip data in Partial Exceptions
                         *  ROUTENAME = TripData_AVL.Tables[0].Rows[i]["Route_Name"].ToString();
                         *  ORG_STOP_ID = TripData_AVL.Tables[0].Rows[i]["Origin_Stop_ID"].ToString(); ;
                         *  DEST_STOP_ID = TripData_AVL.Tables[0].Rows[i]["Dest_Stop_ID"].ToString();
                         * }*/
                    }
                }
                else
                {
                    // add to exception.
                }

                // Step 13: Insert into DataSet for returning trip records.
                dr["DUTY_ID"]            = DUTY_ID;
                dr["DEPOT_ID"]           = DEPOT_ID;
                dr["ETM_SR_NO"]          = ETM_SR_NO;
                dr["DATE_OF_DUTY"]       = DATE_OF_DUTY;
                dr["TRIP_ID"]            = TRIP_ID;
                dr["SUM_TDR_TRIP"]       = SUM_TDR_TRIP;
                dr["COUNT_TDR_TRIP"]     = COUNT_TDR_TRIP;
                dr["WAYBILL_TDR_CASH"]   = WAYBILL_TDR_CASH;
                dr["WAYBILL_TDR_COUNT"]  = WAYBILL_TDR_COUNT;
                dr["DATE_OF_SUBMISSION"] = DATE_OF_SUBMISSION;
                dr["CONFIRM_TDR_CASH"]   = CONFIRM_TDR_CASH;
                dr["CONFIRM_TDR_COUNT"]  = CONFIRM_TDR_COUNT;
                dr["CONFIRMATION_FLAG"]  = CONFIRMATION_FLAG;
                dr["CONFIRMATION_DATE"]  = CONFIRMATION_DATE;
                dr["CONFIRMATION_ID"]    = CONFIRMATION_ID;
                dr["SUBMITTER_ID"]       = SUBMITTER_ID;
                dr["SHIFT_ID"]           = SHIFT_ID;
                dr["TRIP_END_TIME"]      = TRIP_END_TIME;
                dr["TRIP_START_TIME"]    = TRIP_START_TIME;
                dr["FLAG"]           = FLAG;
                dr["ROUTETYPE"]      = ROUTETYPE;
                dr["SERVICETYPE"]    = SERVICETYPE;
                dr["ORG_STOP_ID"]    = ORG_STOP_ID;
                dr["DEST_STOP_ID"]   = DEST_STOP_ID;
                dr["ROUTENAME"]      = ROUTENAME;
                dr["REASON"]         = REASON;
                dr["REMARKS"]        = REMARKS;
                dr["SUM_TDR_DMRC"]   = SUM_TDR_DMRC;
                dr["COUNT_TDR_DMRC"] = COUNT_TDR_DMRC;

                dt.Rows.Add(dr);
            } // For loop ends

            Trips.Tables.Add(dt);

            // Step 14: Update the ticket Count in DataSet if any difference is found with total number of tickets in Sum of all trips tickets.
            int shiftTicketCount = int.Parse(shift_passenger_count);
            int diff             = 0;

            if (shiftTicketCount > sumOfTripTickets) // This should be true everytime.
            {
                diff = shiftTicketCount - sumOfTripTickets;
                // update the difference in number of tickets to the trip with maximum tickets.
                int tripWithMaxTicket = maxNode.tripSequenceNumber;
                Trips.Tables[0].Rows[tripWithMaxTicket - 1]["COUNT_TDR_TRIP"]    = (maxNode.ticketCount + diff).ToString();
                Trips.Tables[0].Rows[tripWithMaxTicket - 1]["WAYBILL_TDR_COUNT"] = Trips.Tables[0].Rows[tripWithMaxTicket - 1]["COUNT_TDR_TRIP"].ToString();
            }

            log.Info("Exiting CreateTrips");

            if (!routeNameException)
            {
                return(Trips);
            }
            else
            {
                //ISaveTripRecord saveTripsWithAVLRoute = new SaveTripRecord();
                //bool saved = saveTripsWithAVLRoute.savePartialTripRecord(Trips);
                //if (!saved) {
                //    RollbackCreatedShift rollback = new RollbackCreatedShift();
                //    rollback.rollbackShift(SHIFT_ID);
                //}

                RollbackCreatedShift rollback = new RollbackCreatedShift();
                rollback.rollbackShift(SHIFT_ID);

                DataSet   empty    = new DataSet();
                DataTable dt_Empty = TripsDT.TripDataTable();
                empty.Tables.Add(dt_Empty);

                return(empty);
            }
        }