Пример #1
0
        /// <summary>
        /// Парсить блок данных
        /// </summary>
        /// <param name="generateXML">генерировать ли XML файл</param>
        /// <param name="output">путь, куда XML сохранять</param>
        /// <param name="userId">ID пользователя, от имени которого вызывается этот метод</param>
        /// <returns>разобранный обьект</returns>
        public object ParseRecords(bool generateXML, string output, int userId)
        {
            Exception noOrg = new Exception("No organization entered");
            Exception CardVehicleError = new Exception("Ошибка в базе данных. Нет связи Карта - ТС!");

            if (organizationID == 0)
                throw noOrg;

            if (DATA_BLOCK_ID == -1)
                throw (new Exception("Can't find this Data Block"));
            else
            {
                //SQLDB sqlDB = new SQLDB(connectionString);
                SQLDB_Records sqlDB_rec = new SQLDB_Records(connectionString, sqlDb.GETMYSQLCONNECTION());
                ReflectObjectToTableClass reflectedItemsList;
                Type type = null;
                object myParseObject = new object();
                PARSER.DDDParser dddParser = new DDDParser();
                string fileName = "";

                try
                {

                    fileName = sqlDB_rec.Get_ParamValue(DATA_BLOCK_ID, "DataBlock_FileName");
                    byte[] blockDataBlob = sqlDb.GetDataBlock(DATA_BLOCK_ID);
                    blockDataBlob = UnZipBytes(blockDataBlob);//АнЗипим файл!
                    dddParser.ParseFile(blockDataBlob, fileName);

                    int cardType = dddParser.GetCardType();
                    currentCardType = cardType;

                    //test
                    //OpenConnection();
                    //OpenTransaction();
                    //

                    if (cardType == 0)// 0 - card(driver)
                    {
                        int cardId;
                        if (dddParser.cardUnitClass.ef_identification.driverCardHolderIdentification != null)
                        {
                            string drName = dddParser.cardUnitClass.ef_identification.driverCardHolderIdentification.cardHolderName.ToString();
                            string drNumber = dddParser.cardUnitClass.ef_identification.cardIdentification.cardNumber.ToString();
                            //sqlDB.OpenConnection();
                            cardId = cardsTable.GetCardId(drName, drNumber, cardsTable.driversCardTypeId);
                            if (cardId <= 0)
                            {
                                int grId = cardsTable.GetAllGroupIds(organizationID, 0)[0];
                                UserFromTable userData = new UserFromTable();
                                userData.name = "";
                                userData.pass = "";
                                int newUserId = usersTable.AddNewUser(userData, usersTable.DriverUserTypeId, 1, organizationID, userId);
                                string[] arr=drName.Split(' ');
                                usersTable.AddUserInfoValue(newUserId, DataBaseReference.UserInfo_Name, arr[0]);
                                usersTable.AddUserInfoValue(newUserId, DataBaseReference.UserInfo_Surname, arr[1]);
                                cardId = cardsTable.CreateNewCard(drName, drNumber, cardsTable.driversCardTypeId, organizationID, newUserId, "Init DataBlockId = " + DATA_BLOCK_ID, userId, grId);
                            }
                            sqlDb.SetDataBlock_CardId(DATA_BLOCK_ID, cardId);
                            //sqlDB.CloseConnection();
                        }
                        else
                        {
                            //sqlDB.OpenConnection();
                            sqlDb.SetDataBlockState(DATA_BLOCK_ID, 4);
                            //sqlDB.CloseConnection();
                            throw new Exception("Поддерживаются только водительские карты и информация с бортового устройства.");
                        }
                        type = dddParser.cardUnitClass.GetType();
                        myParseObject = dddParser.cardUnitClass;
                    }
                    else if (cardType == 1)//vehicle
                    {
                        /////////////////////////
                        int vehicleId;
                        if (dddParser.vehicleUnitClass.vehicleOverview.vehicleRegistrationIdentification != null)
                        {
                            int cardId;
                            string vehRegNumber = dddParser.vehicleUnitClass.vehicleOverview.vehicleRegistrationIdentification.vehicleRegistrationNumber.ToString();
                            string vin = dddParser.vehicleUnitClass.vehicleOverview.vehicleIdentificationNumber.ToString();
                            cardId = cardsTable.GetCardId(vehRegNumber, vin, cardsTable.vehicleCardTypeId);
                            vehicleId = vehiclesTables.GetVehicleId_byVinRegNumbers(vin, vehRegNumber);
                            if ((vehicleId <= 0 && cardId > 0) || (vehicleId > 0 && cardId <= 0))
                                throw CardVehicleError;

                            if (cardId <= 0)
                            {
                                string marka = "";
                                DateTime BLOCKED = dddParser.vehicleUnitClass.vehicleOverview.vuDownloadablePeriod.maxDownloadableTime.getTimeRealDate();
                                int grId = cardsTable.GetAllGroupIds(organizationID,0)[0];
                                cardId = cardsTable.CreateNewCard(vehRegNumber, vin, cardsTable.vehicleCardTypeId, organizationID, userId, "Init DataBlockId = " + DATA_BLOCK_ID, userId, grId);
                                //vehiclesTables.OpenConnection();
                                vehicleId = vehiclesTables.AddNewVehicle(vehRegNumber, marka, vin, 0, 1, cardId, BLOCKED, 1);
                                //vehiclesTables.CloseConnection();
                                // SetAllVehiclesIDS(vehicleId);
                            }
                            sqlDb.SetDataBlock_CardId(DATA_BLOCK_ID, cardId);
                        }
                        /////////////////////////
                        type = dddParser.vehicleUnitClass.GetType();
                        myParseObject = dddParser.vehicleUnitClass;
                    }
                    else if (cardType == 2)//plf
                    {
                        //////////////////////устанавливаем PLF карту нужного водителя. Незнаю почему именно здесь, но так получилось.
                        int plfDriversCardType = sqlDB_rec.Get_DataBlockCardType(DATA_BLOCK_ID);
                        sqlDb.SetDataBlock_CardId(DATA_BLOCK_ID, plfDriversCardType);
                        // sqlDB.OpenConnection();
                        int cardTypeParamId = sqlDb.AddParam("cardType", 0, 255);
                        //sqlDB.OpenConnection();
                        sqlDb.DeleteDataRecord(DATA_BLOCK_ID, cardTypeParamId);
                        // sqlDB.CloseConnection();
                        //////////////////////
                        type = dddParser.plfUnitClass.GetType();
                        myParseObject = dddParser.plfUnitClass;
                    }
                    else if (cardType == -1)
                        throw new Exception("Информация непригодна для разбора(не опознан тип карты");

                    //sqlDB.OpenConnection();
                    SetParseBDate(sqlDb);
                    //sqlDB.CloseConnection();

                    List<ReflectObjectToTableClass> allRecordsToAdd = new List<ReflectObjectToTableClass>();

                    foreach (PropertyInfo pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                    {
                        reflectedItemsList = new ReflectObjectToTableClass();
                        string fieldName = pi.Name;
                        object field2 = pi.GetValue(myParseObject, null);

                        if (field2 != null)
                        {
                            reflectedItemsList.ReflectObjectToTable(fieldName, field2);//Не удалять!
                            allRecordsToAdd.Add(AddRecords(reflectedItemsList));//не удалять
                        }
                    }

                    foreach (ReflectObjectToTableClass recordList in allRecordsToAdd)
                    {
                        dataRecord.AddDataArray(recordList.reflectedItemsList);
                    }

                    //sqlDB.OpenConnection();
                    SetParseEDate(sqlDb);
                    sqlDb.SetDataBlockState(DATA_BLOCK_ID, 2);
                    int dataBlockParseRecords = sqlDb.SetDataBlockParseRecords(DATA_BLOCK_ID);
                    Console.WriteLine("\n\r" + dataBlockParseRecords.ToString() + " records added");
                    //XML GENERATING
                    if (generateXML)
                        dddParser.GenerateXmlFile(output);
                    //
                    //Добавляем лог для каждого типа блока данных свой.
                    string logNote;
                    HistoryTable historyTable = new HistoryTable(connectionString, CurrentLanguage, sqlDb);
                    if (currentCardType == 0)//driver
                    {
                        string drName = dddParser.cardUnitClass.ef_identification.driverCardHolderIdentification.cardHolderName.ToString();
                        string drNumber = dddParser.cardUnitClass.ef_identification.cardIdentification.cardNumber.ToString();
                        logNote = "Driver: " + drName + "(" + drNumber + ")" + ", records number: " + dataBlockParseRecords.ToString();
                        historyTable.AddHistoryRecord("fn_data_block", "DATA_BLOCK_ID", DATA_BLOCK_ID, userId, historyTable.DDDDriversDataBlockLoaded, logNote, sqlDb);
                    }
                    if (currentCardType == 1)//vehicle
                    {
                        string logVehRegNumber = dddParser.vehicleUnitClass.vehicleOverview.vehicleRegistrationIdentification.vehicleRegistrationNumber.ToString();
                        string logVin = dddParser.vehicleUnitClass.vehicleOverview.vehicleIdentificationNumber.ToString();
                        logNote = "Vehicle: " + logVehRegNumber + "(" + logVin + ")" + ", records number: " + dataBlockParseRecords.ToString();
                        historyTable.AddHistoryRecord("fn_data_block", "DATA_BLOCK_ID", DATA_BLOCK_ID, userId, historyTable.DDDVehiclesDataBlockLoaded, logNote, sqlDb);
                    }
                    if (currentCardType == 2)//plf
                    {
                        string vehPlfIdent = dddParser.plfUnitClass.VEHICLE;
                        string plfDeviceId = dddParser.plfUnitClass.ID_DEVICE;
                        string period = dddParser.plfUnitClass.START_PERIOD.GetSystemTime().ToShortDateString() + " - " + dddParser.plfUnitClass.END_PERIOD.GetSystemTime().ToShortDateString();
                        logNote = "PLF File: " + vehPlfIdent + "(" + plfDeviceId + ")" + ", period: " + period + ", records number: " + dataBlockParseRecords.ToString();
                        historyTable.AddHistoryRecord("fn_data_block", "DATA_BLOCK_ID", DATA_BLOCK_ID, userId, historyTable.PLFDataBlockLoaded, logNote, sqlDb);
                    }
                    //
                    //sqlDb.CommitConnection();
                    //sqlDb.CloseConnection();
                }
                catch (Exception ex)
                {
                    //sqlDb.RollbackConnection();
                    //sqlDb.CloseConnection();
                    throw ex;
                }
                finally
                {
                }
                return myParseObject;
            }
        }
Пример #2
0
        public void LoadAllInfo()
        {
            Console.WriteLine("Conerting starts");
            DateTime startLoadTime = DateTime.Now;

            PLFUnit.PLFUnitClass plf;

            CARS cars = new CARS(fb_con);
            cars.LoadAllCars();

            DEPARTMENTS depar = new DEPARTMENTS(fb_con);
            depar.LoadAllDepartments();

            WORKERS workers = new WORKERS(fb_con);
            workers.LoadAllWorkers();

            DEVICES devices = new DEVICES(fb_con);
            devices.LoadAllDevices();

            READCYCLE readcycle = new READCYCLE(fb_con);
            readcycle.LoadAllReadCycles();

            DataBlock datablock = new DataBlock(connectionStringMysql, currentLanguage);
            try
            {
                List<KeyValuePair<int, int>> orgOldNewIds = new List<KeyValuePair<int, int>>();
                List<KeyValuePair<int, int>> workOldNewIds = new List<KeyValuePair<int, int>>();
                List<KeyValuePair<int, int>> carsOldNewIds = new List<KeyValuePair<int, int>>();
                List<KeyValuePair<READCYCLE.readcycle, int>> readCycleAndorgIdList = new List<KeyValuePair<READCYCLE.readcycle, int>>();

                List<int> allIds = new List<int>();
                int newDeviceId = -1;
                int userInfoId;
                KeyValuePair<int, int> tempOldNewIds;
                List<int> addedWorkers = new List<int>();
                datablock.OpenConnection();
                datablock.OpenTransaction();
                //Создание организация, работников и ТС
                foreach (DEPARTMENTS.department department in depar.departments)
                {
                    addedWorkers = new List<int>();
                    int orgId = datablock.organizationTable.AddNewOrganization(department.DEPARTMENT, 1, 1, 1);
                    tempOldNewIds = new KeyValuePair<int, int>(department.ID, orgId);
                    orgOldNewIds.Add(tempOldNewIds);
                    int carId = -1;
                    #region "cars"
                    IEnumerable<CARS.car> carsList =
                       from car in cars.carsArray
                       where car.DEPARTMENTID == department.ID
                       select car;

                    foreach (CARS.car car in carsList)
                    {
                        IEnumerable<int> scoreQuery =
                        from devId in readcycle.cycles
                        where devId.CARID == car.ID
                        select devId.DEVICEID;
                        allIds = scoreQuery.ToList();

                        if (allIds.Count > 0)
                        {
                            IEnumerable<DEVICES.device> oneDevice =
                            from devId in devices.devices
                            where devId.ID == allIds[0]
                            select devId;

                            if (oneDevice.ToList().Count > 0)
                            {
                                DEVICES.device NewDevice = oneDevice.ToList()[0];
                                newDeviceId = datablock.deviceTable.AddNewDevice(1, NewDevice.DEVICE, NewDevice.VERSION, DateTime.Now, 1, 23442324);
                            }
                            else
                                newDeviceId = datablock.deviceTable.AddNewDevice(1, "UndefinedDevice", "UndefinedVersion", DateTime.Now, 1, 23442324);
                        }
                        else
                            newDeviceId = datablock.deviceTable.AddNewDevice(1, "UndefinedDevice", "UndefinedVersion", DateTime.Now, 1, 23442324);

                        if (car.DEPARTMENTID == department.ID)
                        {
                            int cardId = datablock.cardsTable.CreateNewCard(car.REGNUMBER, "Unknown", datablock.cardsTable.vehicleCardTypeId, orgId, 0, "Created from FIREBIRD database", 0, 1);
                            carId = datablock.vehiclesTables.AddNewVehicle(car.REGNUMBER, car.CARMODEL, "Unknown", 1, newDeviceId, cardId, DateTime.Now, 1);
                            tempOldNewIds = new KeyValuePair<int, int>(car.ID, carId);
                            carsOldNewIds.Add(tempOldNewIds);
                        }
                    }
                    #endregion
                    #region "workers"
                    IEnumerable<WORKERS.worker> workersList =
                         from worker in workers.workers
                         where worker.DEPARTMENTID == department.ID
                         select worker;

                    foreach (WORKERS.worker workerForAdd in workersList)
                    {
                        int newWId = datablock.cardsTable.CreateNewCard(workerForAdd.FIRSTNAME + " " + workerForAdd.SURNAME, workerForAdd.WORKERINTID.ToString(), datablock.cardsTable.driversCardTypeId,
                            orgId, 0, "Created from firebird", 0, 1);
                        /*userInfoId = datablock.usersTable.GetUserInfoNameId(DataBaseReference.UserInfo_Patronimic);
                        datablock.usersTable.EditUserInfo(newWId, userInfoId, workerForAdd.MIDDLENAME);
                        userInfoId = datablock.usersTable.GetUserInfoNameId(DataBaseReference.UserInfo_Name);
                        datablock.usersTable.EditUserInfo(newWId, userInfoId, workerForAdd.FIRSTNAME);
                        userInfoId = datablock.usersTable.GetUserInfoNameId(DataBaseReference.UserInfo_Surname);
                        datablock.usersTable.EditUserInfo(newWId, userInfoId, workerForAdd.SURNAME);
                        userInfoId = datablock.usersTable.GetUserInfoNameId(DataBaseReference.UserInfo_Birthday);
                        datablock.usersTable.EditUserInfo(newWId, userInfoId, workerForAdd.BIRTHDAY.ToShortDateString());
                        userInfoId = datablock.usersTable.GetUserInfoNameId(DataBaseReference.UserInfo_DriversCertificate);
                        datablock.usersTable.EditUserInfo(newWId, userInfoId, workerForAdd.LICENCE);*/
                        addedWorkers.Add(workerForAdd.ID);
                        tempOldNewIds = new KeyValuePair<int, int>(workerForAdd.ID, newWId);
                        workOldNewIds.Add(tempOldNewIds);
                    }
                    #endregion
                    #region "set orgId to READCYCLES"
                    if(addedWorkers.Count>0)
                        for(int i=0;i<readcycle.cycles.Count;i++)
                        {
                            if(addedWorkers.Contains(readcycle.cycles[i].WORKER1ID) || addedWorkers.Contains(readcycle.cycles[i].WORKER2ID))
                            {
                                KeyValuePair<READCYCLE.readcycle, int> readCycleAndorgId = new KeyValuePair<READCYCLE.readcycle, int>(readcycle.cycles[i], orgId);
                                readCycleAndorgIdList.Add(readCycleAndorgId);
                            }
                        }
                    #endregion
                }
                Console.WriteLine("Added workers, departmens, cars");

                if (readCycleAndorgIdList.Count != readcycle.cycles.Count)
                {
                    if (false) //база фигово связана
                        throw new Exception("Куда-то пропала часть инфы");
                }
                //Загрузка файлов ПЛФ в ранее созданные организации.
                foreach (KeyValuePair<READCYCLE.readcycle, int> readedcycle in readCycleAndorgIdList)
                {
                    SQLDB sqlDb = datablock.sqlDb;
                    SQLDB_Records sqlDB_rec = new SQLDB_Records(connectionStringMysql, sqlDb.GETMYSQLCONNECTION());
                    ReflectObjectToTableClass reflectedItemsList;
                    byte[] bytes = Guid.NewGuid().ToByteArray();
                    int orgId = readedcycle.Value;
                    Type type = null;
                    object myParseObject = new object();
                    plf = new PLFUnitClass();
                    plf = LoadLogBook(readedcycle.Key);
                    plf.cardType = 2;

                    IEnumerable<string> selCar =
                            from car in cars.carsArray
                            where car.ID == readedcycle.Key.CARID
                            select car.REGNUMBER;
                    if(selCar.ToList().Count>0)
                        plf.VEHICLE = selCar.ToList()[0];

                    IEnumerable<string> selDeviceName =
                            from dev in devices.devices
                            where dev.ID == readedcycle.Key.DEVICEID
                            select dev.DEVICE;
                    if (selDeviceName.ToList().Count > 0)
                        plf.ID_DEVICE = selDeviceName.ToList()[0];

                    int driverId = -1;
                    foreach (KeyValuePair<int, int> oldNew in workOldNewIds)
                    {
                        if (oldNew.Key == readedcycle.Key.WORKER1ID)
                            driverId = oldNew.Value;
                    }
                    int dataBlockId = datablock.AddPlfTypeData(orgId, bytes,
                        "AutoGenerated " + plf.VEHICLE + " " + plf.START_PERIOD.ToString() + " - " + plf.END_PERIOD.ToString(),
                        driverId);
                    DataRecords dataRecord = new DataRecords(connectionString, dataBlockId, currentLanguage, sqlDb);

                        //////////////////////устанавливаем PLF карту нужного водителя. Незнаю почему именно здесь, но так получилось.
                    int plfDriversCardType = sqlDB_rec.Get_DataBlockCardType(dataBlockId);
                    sqlDb.SetDataBlock_CardId(dataBlockId, plfDriversCardType);
                       // sqlDB.OpenConnection();
                        int cardTypeParamId = sqlDb.AddParam("cardType", 0, 255);
                        //sqlDB.OpenConnection();
                        sqlDb.DeleteDataRecord(dataBlockId, cardTypeParamId);
                       // sqlDB.CloseConnection();
                        //////////////////////
                        type = plf.GetType();
                        myParseObject = plf;

                    //sqlDB.OpenConnection();
                    SetParseBDate(sqlDb, dataBlockId);
                    //sqlDB.CloseConnection();

                    List<ReflectObjectToTableClass> allRecordsToAdd = new List<ReflectObjectToTableClass>();

                    foreach (PropertyInfo pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                    {
                        reflectedItemsList = new ReflectObjectToTableClass();
                        string fieldName = pi.Name;
                        object field2 = pi.GetValue(myParseObject, null);

                        if (field2 != null)
                        {
                            reflectedItemsList.ReflectObjectToTable(fieldName, field2);//Не удалять!
                            allRecordsToAdd.Add(AddRecords(reflectedItemsList, sqlDb));//не удалять
                        }
                    }

                    foreach (ReflectObjectToTableClass recordList in allRecordsToAdd)
                    {
                        dataRecord.AddDataArray(recordList.reflectedItemsList);
                    }

                    //sqlDB.OpenConnection();
                    SetParseEDate(sqlDb,dataBlockId);
                    sqlDb.SetDataBlockState(dataBlockId, 2);
                    int dataBlockParseRecords = sqlDb.SetDataBlockParseRecords(dataBlockId);
                    Console.WriteLine("" + dataBlockParseRecords.ToString()+" records added");
                }

                Console.WriteLine("\n\r" + "Время начала импорта " + startLoadTime.ToShortDateString() + " " + startLoadTime.ToShortTimeString());
                Console.WriteLine("\n\r" + "Время окончания импорта " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString());
                //throw new Exception();
                datablock.CommitTransaction();
                datablock.CloseConnection();

            }
            catch (Exception ex)
            {
                datablock.RollbackConnection();
                datablock.CloseConnection();
                Console.WriteLine(ex.Message);
            }
        }