/// <summary> /// Сортирует по дням /// </summary> /// <returns>возвращает массив обьектов PLFUnitClass, каждый содержит информацию за сутки</returns> public List <PLFUnitClass> SortPlfEveryDay() { List <PLFUnitClass> plfEveryDay = new List <PLFUnitClass>(); PLFUnitClass oneDay = new PLFUnitClass(); bool newDay = true; foreach (PLFRecord record in this.Records) { if (!newDay) { if (oneDay.Records[oneDay.Records.Count - 1].SYSTEM_TIME.GetSystemTime().DayOfWeek != record.SYSTEM_TIME.GetSystemTime().DayOfWeek) { oneDay.END_PERIOD = oneDay.Records[oneDay.Records.Count - 1].SYSTEM_TIME; oneDay.TIME_STEP = this.TIME_STEP; oneDay.ID_DEVICE = this.ID_DEVICE; oneDay.VEHICLE = this.VEHICLE; oneDay.installedSensors = this.installedSensors; plfEveryDay.Add(oneDay); oneDay = new PLFUnitClass(); newDay = true; } } if (newDay) { oneDay.Records.Add(record); oneDay.START_PERIOD = record.SYSTEM_TIME; newDay = false; } else { oneDay.Records.Add(record); } if (this.Records[this.Records.Count - 1] == record) { oneDay.END_PERIOD = oneDay.Records[oneDay.Records.Count - 1].SYSTEM_TIME; oneDay.TIME_STEP = this.TIME_STEP; oneDay.ID_DEVICE = this.ID_DEVICE; oneDay.VEHICLE = this.VEHICLE; oneDay.installedSensors = this.installedSensors; plfEveryDay.Add(oneDay); } } return(plfEveryDay); }
/// <summary> /// Десериализует из XML в экземпляр этого класса /// </summary> /// <param name="filename">путь к файлу.</param> /// <returns>обьект класса PLFUnitClass</returns> public static PLFUnitClass DeserializePlfUnitClass(string filename) { // Create an instance of the XmlSerializer specifying type and namespace. XmlSerializer serializer = new XmlSerializer(typeof(PLFUnitClass)); // A FileStream is needed to read the XML document. FileStream fs = new FileStream(filename, FileMode.Open); XmlReader reader = new XmlTextReader(fs); // Declare an object variable of the type to be deserialized. PLFUnitClass i = new PLFUnitClass(); // Use the Deserialize method to restore the object's state. i = (PLFUnitClass)serializer.Deserialize(reader); reader.Close(); fs.Close(); return(i); }
/// <summary> /// Сортирует по дням /// </summary> /// <returns>возвращает массив обьектов PLFUnitClass, каждый содержит информацию за сутки</returns> public List<PLFUnitClass> SortPlfEveryDay() { List<PLFUnitClass> plfEveryDay = new List<PLFUnitClass>(); PLFUnitClass oneDay = new PLFUnitClass(); bool newDay = true; foreach (PLFRecord record in this.Records) { if (!newDay) { if (oneDay.Records[oneDay.Records.Count - 1].SYSTEM_TIME.GetSystemTime().DayOfWeek != record.SYSTEM_TIME.GetSystemTime().DayOfWeek) { oneDay.END_PERIOD = oneDay.Records[oneDay.Records.Count - 1].SYSTEM_TIME; oneDay.TIME_STEP = this.TIME_STEP; oneDay.ID_DEVICE = this.ID_DEVICE; oneDay.VEHICLE = this.VEHICLE; oneDay.installedSensors = this.installedSensors; plfEveryDay.Add(oneDay); oneDay = new PLFUnitClass(); newDay = true; } } if (newDay) { oneDay.Records.Add(record); oneDay.START_PERIOD = record.SYSTEM_TIME; newDay = false; } else { oneDay.Records.Add(record); } if (this.Records[this.Records.Count - 1] == record) { oneDay.END_PERIOD = oneDay.Records[oneDay.Records.Count - 1].SYSTEM_TIME; oneDay.TIME_STEP = this.TIME_STEP; oneDay.ID_DEVICE = this.ID_DEVICE; oneDay.VEHICLE = this.VEHICLE; oneDay.installedSensors = this.installedSensors; plfEveryDay.Add(oneDay); } } return plfEveryDay; }
/// <summary> /// Десериализует из XML в экземпляр этого класса /// </summary> /// <param name="filename">путь к файлу.</param> /// <returns>обьект класса PLFUnitClass</returns> public static PLFUnitClass DeserializePlfUnitClass(string filename) { // Create an instance of the XmlSerializer specifying type and namespace. XmlSerializer serializer = new XmlSerializer(typeof(PLFUnitClass)); // A FileStream is needed to read the XML document. FileStream fs = new FileStream(filename, FileMode.Open); XmlReader reader = new XmlTextReader(fs); // Declare an object variable of the type to be deserialized. PLFUnitClass i = new PLFUnitClass(); // Use the Deserialize method to restore the object's state. i = (PLFUnitClass)serializer.Deserialize(reader); reader.Close(); fs.Close(); return i; }
protected void AddGridCommand(object sender, DataGridCommandEventArgs e) { string connectionString = ConfigurationSettings.AppSettings["fleetnetbaseConnectionString"]; DataBlock dataBlock = new DataBlock(connectionString, ConfigurationManager.AppSettings["language"]); List<int> dataBlockIds = new List<int>(); int orgId = Convert.ToInt32(Session["CURRENT_ORG_ID"]); Status.Text = ""; DriverPreviewButtonsPanel.Visible = false; VehiclePreviewButtonsPanel.Visible = false; FilesPreviewDataGrid.DataSource = null; FilesPreviewDataGrid.DataBind(); try { if (e.CommandName == "ViewData") { if (Session["DeleteCommmand"] == "ViewDriversFile") { int tableIndex = Convert.ToInt32(e.Item.Cells[2].Text) - 1; int cardId = Convert.ToInt32(DriversSelectTree.SelectedValue); List<Driver> driversStructureList = new List<Driver>(); dataBlock.OpenConnection(); driversStructureList = LoadAllDriversLists(cardId); dataBlockIds.Add(driversStructureList[tableIndex].DataBlockId); onlyForInternal.Value = driversStructureList[tableIndex].DataBlockId.ToString(); if (driversStructureList[tableIndex].CardTypeName != "Plf") { DriverPreviewButtonsPanel.Visible = true; Driver_FileContents(null, null); } else { PLFUnit.PLFUnitClass plf = new PLFUnit.PLFUnitClass(); plf.Records = dataBlock.plfUnitInfo.Get_Records(dataBlockIds, cardId); FilesPreviewDataGrid.DataSource = PlfReportsDataTables.PLF_Data(plf.Records); FilesPreviewDataGrid.DataBind(); FilesPreviewPanel.Visible = true; } ShowDriversStatisticsForOneFile(sender, e); dataBlock.CloseConnection(); } if (Session["DeleteCommmand"] == "ViewVehiclesFile") { int tableIndex = Convert.ToInt32(e.Item.Cells[2].Text) - 1; int cardId = Convert.ToInt32(VehiclesSelectTree.SelectedValue); List<int> cardDataBlockIds = new List<int>(); dataBlock.OpenConnection(); cardDataBlockIds = dataBlock.cardsTable.GetAllDataBlockIds_byCardId(cardId); dataBlockIds.Add(cardDataBlockIds[tableIndex]); onlyForInternal.Value = cardDataBlockIds[tableIndex].ToString(); dataBlock.CloseConnection(); VehiclePreviewButtonsPanel.Visible = true; Vehicles_FileContents(null, null); ShowVehiclesStatistics(null, null); } } else if (Session["DeleteCommmand"].ToString() == "RemoveParsedData") { DelGridCommand(sender, e); } else if (Session["DeleteCommmand"].ToString() == "RemoveUnparsedData") { int number = Convert.ToInt32(e.Item.Cells[2].Text); dataBlockIds = dataBlock.GetAllUnparsedDataBlockIDs(orgId); int dataBlockId = dataBlockIds[number - 1]; dataBlock = new DataBlock(connectionString, dataBlockId, ConfigurationManager.AppSettings["language"]); dataBlock.DeleteDataBlockAndRecords(); LoadAllLists(); } else if (Session["DeleteCommmand"].ToString() == "RemoveDriversFile") { int rightIdToDelete = -1; string name = e.Item.Cells[3].Text; int recordsCount = int.Parse(e.Item.Cells[7].Text); dataBlockIds = dataBlock.GetDataBlockIdByRecordsCount(recordsCount); if (dataBlockIds.Count == 1) rightIdToDelete = dataBlockIds[0]; else if (dataBlockIds.Count > 1) { string nameTemp; foreach (int blockId in dataBlockIds) { nameTemp = dataBlock.GetDriversNameOrVehiclesNumberByBlockId(blockId); if (nameTemp == name) { rightIdToDelete = blockId; break; } } } else throw new Exception("Нет доступа к информации(или нет данных для удаления)"); if (rightIdToDelete != -1) { dataBlock = new DataBlock(connectionString, rightIdToDelete, ConfigurationManager.AppSettings["language"]); dataBlock.DeleteDataBlockAndRecords(); ManagmentLoadedInfo_SelectedNodeChanged(null, null); } } else if (Session["DeleteCommmand"].ToString() == "RecoverDriversFile") { int tableIndex = Convert.ToInt32(e.Item.Cells[2].Text) - 1; int cardId = Convert.ToInt32(UserFileRecover_TreeView.SelectedValue); List<int> filesIds = new List<int>(); dataBlock.OpenConnection(); filesIds = dataBlock.cardsTable.GetAllDataBlockIds_byCardId(cardId); int dataBlockId = filesIds[tableIndex]; onlyForInternal.Value = dataBlockId.ToString(); byte[] fileBytes = dataBlock.GetDataBlock_BytesArray(dataBlockId); string fileName = dataBlock.GetDataBlock_FileName(dataBlockId); dataBlock.CloseConnection(); Response.Clear(); Response.AddHeader("content-disposition", "attachment; filename=" + fileName); Response.AddHeader("Content-Length", fileBytes.Length.ToString()); Response.ContentType = "application/octet-stream"; Response.OutputStream.Write(fileBytes, 0, fileBytes.Length); Response.End(); Page.ClientScript.RegisterStartupScript(this.GetType(), "submit", "javascript:document.form1.submit()", true); } } catch (Exception ex) { Status.Text = ex.Message; StatusUpdatePanel.Update(); } finally { ModalPopupExtender1.Hide(); } }
public static bool ParseDataBlocks(String OrgID, String UserName) { string connectionString = ConfigurationManager.AppSettings["fleetnetbaseConnectionString"]; DataBlock dataBlock = new DataBlock(connectionString, ConfigurationManager.AppSettings["language"]); PLFUnit.PLFUnitClass plfForXml = new PLFUnit.PLFUnitClass(); List<int> dataBlockIDs = new List<int>(); int filesCounter = 0; object parsedObject; try { dataBlock.OpenConnection(); dataBlock.OpenTransaction(); int userId = dataBlock.usersTable.Get_UserID_byName(UserName); int orgId = int.Parse(OrgID); dataBlockIDs = dataBlock.GetAllUnparsedDataBlockIDs(orgId); if (dataBlockIDs.Count == 0) { return true; } string output = ""; foreach (int blockId in dataBlockIDs) { dataBlock.SetDataBlockIdForParse(blockId); dataBlock.SetOrgIdForParse(orgId); string state = dataBlock.GetDataBlockState(blockId); if (state.Equals("Not parsed")) { output = HttpContext.Current.Server.MapPath("~/XML_PLF") + "\\"; parsedObject = dataBlock.ParseRecords(true, output, userId); filesCounter++; } } dataBlock.CommitTransaction(); dataBlock.CloseConnection(); return true; } catch (Exception ex) { dataBlock.RollbackConnection(); dataBlock.CloseConnection(); throw ex; //return false; } }
protected void Parse_Click(object Sender, EventArgs e) { string connectionString = ConfigurationSettings.AppSettings["fleetnetbaseConnectionString"]; DataBlock dataBlock = new DataBlock(connectionString, ConfigurationManager.AppSettings["language"]); PLFUnit.PLFUnitClass plfForXml = new PLFUnit.PLFUnitClass(); List<int> dataBlockIDs = new List<int>(); int cardType = 0; int filesCounter = 0; object parsedObject; try { dataBlock.OpenConnection(); dataBlock.OpenTransaction(); int userId = dataBlock.usersTable.Get_UserID_byName(User.Identity.Name); int orgId = Convert.ToInt32(Session["CURRENT_ORG_ID"]); dataBlockIDs = dataBlock.GetAllUnparsedDataBlockIDs(orgId); if (dataBlockIDs.Count == 0) throw new Exception("Отсутствуют данные для разбора."); string output = ""; foreach (int blockId in dataBlockIDs) { dataBlock.SetDataBlockIdForParse(blockId); dataBlock.SetOrgIdForParse(orgId); //dataBlock = new DataBlock(connectionString, blockId, ConfigurationManager.AppSettings["language"], orgId); if (dataBlock.GetDataBlockState(blockId) == "Not parsed") { output = Server.MapPath("~/XML_PLF") + "\\"; parsedObject = dataBlock.ParseRecords(true, output, userId); filesCounter++; } else continue; } dataBlock.CommitTransaction(); dataBlock.CloseConnection(); LoadAllLists(); if (filesCounter > 0) Status.Text = "Файлы разобраны успешно! Разобрано " + filesCounter.ToString() + " файлов."; else Status.Text = "Не разобрано ни одного файла."; } catch (Exception ex) { dataBlock.RollbackConnection(); dataBlock.CloseConnection(); LoadAllLists(); Status.Text = "Ошибка: " + ex.Message; } finally { StatusUpdatePanel.Update(); ModalPopupExtender1.Hide(); } }
private PLFUnitClass LoadLogBook(READCYCLE.readcycle readcycle) { PLFUnitClass plf = new PLFUnitClass(); plf.START_PERIOD.systemTime = readcycle.TIMEFROM.ToString("yy:MM:dd HH:mm:ss"); plf.END_PERIOD.systemTime = readcycle.TIMETO.ToString("yy:MM:dd HH:mm:ss"); plf.TIME_STEP = readcycle.TIMESTEP.ToString(); plf.installedSensors = readcycle.installedSensors; fb_con.Open(); string sql = "SELECT * FROM LOGBOOK WHERE READCYCLEID=@READCYCLEID ORDER BY ID"; FbCommand cmd = new FbCommand(sql, fb_con); cmd.Parameters.AddWithValue("@READCYCLEID", readcycle.ID); int i = 0; PLFRecord onerecord = new PLFRecord(); DateTime previewDate = new DateTime(); string gettedValue; using (FbDataReader r = cmd.ExecuteReader()) { while (r.Read()) { onerecord = new PLFRecord(); if (plf.installedSensors.SYSTEM_TIME.systemTime != null) { gettedValue = r["READTIME"].ToString(); if (previewDate == new DateTime()) { onerecord.SYSTEM_TIME.systemTime = DateTime.Parse(gettedValue).ToString("yy:MM:dd HH:mm:ss"); previewDate = DateTime.Parse(gettedValue); } else { if (DateTime.Parse(gettedValue) == previewDate) { onerecord.SYSTEM_TIME.systemTime = (DateTime.Parse(gettedValue).AddSeconds(Convert.ToInt32(plf.TIME_STEP))).ToString("yy:MM:dd HH:mm:ss"); previewDate = DateTime.Parse(gettedValue); } else { onerecord.SYSTEM_TIME.systemTime = DateTime.Parse(gettedValue).ToString("yy:MM:dd HH:mm:ss"); previewDate = DateTime.Parse(gettedValue); } } } if (plf.installedSensors.FUEL_CONSUMPTION != null) onerecord.FUEL_CONSUMPTION = r["FUEL0"].ToString(); if (plf.installedSensors.FUEL_VOLUME1 != null) onerecord.FUEL_VOLUME1 = r["FUEL1"].ToString(); if (plf.installedSensors.FUEL_VOLUME2 != null) onerecord.FUEL_VOLUME2 = r["FUEL2"].ToString(); //FUELPH if (plf.installedSensors.VOLTAGE != null) onerecord.VOLTAGE = r["BATTERY"].ToString(); if (plf.installedSensors.ENGINE_RPM != null) onerecord.ENGINE_RPM = r["ENGINERPM"].ToString(); if (plf.installedSensors.TEMPERATURE1 != null) onerecord.TEMPERATURE1 = r["TEMPERATURE1"].ToString(); if (plf.installedSensors.TEMPERATURE2 != null) onerecord.TEMPERATURE2 = r["TEMPERATURE2"].ToString(); if (plf.installedSensors.WEIGHT1 != null) onerecord.WEIGHT1 = r["WEIGHT1"].ToString(); if (plf.installedSensors.WEIGHT2 != null) onerecord.WEIGHT2 = r["WEIGHT2"].ToString(); if (plf.installedSensors.WEIGHT3 != null) onerecord.WEIGHT3 = r["WEIGHT3"].ToString(); if (plf.installedSensors.WEIGHT4 != null) onerecord.WEIGHT4 = r["WEIGHT4"].ToString(); if (plf.installedSensors.WEIGHT5 != null) onerecord.WEIGHT5 = r["WEIGHT5"].ToString(); if (plf.installedSensors.ADDITIONAL_SENSORS != null) onerecord.ADDITIONAL_SENSORS = r["SENSOR1"].ToString(); if (plf.installedSensors.RESERVED_3 != null) onerecord.RESERVED_3 = r["SENSOR3"].ToString(); if (plf.installedSensors.RESERVED_4 != null) onerecord.RESERVED_4 = r["SENSOR4"].ToString(); if (plf.installedSensors.RESERVED_5 != null) onerecord.RESERVED_5 = r["SENSOR5"].ToString(); //IGNITION //ENGWORKTIME //REFUEL //FUELDELTA //REFUELTIME //REFUELTIME if (plf.installedSensors.SPEED != null) onerecord.SPEED = r["SPEED"].ToString(); if (plf.installedSensors.DISTANCE_COUNTER != null) onerecord.DISTANCE_COUNTER = r["RACE"].ToString(); //MOVETIME //IDLETIME if (plf.installedSensors.LATITUDE != null) onerecord.LATITUDE = r["LATITUDE"].ToString(); if (plf.installedSensors.LONGITUDE != null) onerecord.LONGITUDE = r["LONGITUDE"].ToString(); if (plf.installedSensors.ALTITUDE != null) onerecord.ALTITUDE = r["ALTITUDE"].ToString(); if (plf.installedSensors.FUEL_COUNTER != null) onerecord.FUEL_COUNTER = r["FUEL"].ToString(); plf.Records.Add(onerecord); } } fb_con.Close(); return plf; }
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); } }
/// <summary> /// Разбирает PLF файл, возвращает информацию в обьекте класса PLFUnitClass /// </summary> /// <param name="src">Битовый массив - считаный в память PLF файл</param> /// <returns>экземпляр PLFUnitClass</returns> public static PLFUnitClass PLFUnitData_Parse(byte[] src) { PLFUnitClass returnObject = new PLFUnitClass(); List<string> records = new List<string>(); System.Text.Encoding enc = System.Text.Encoding.Default; string myString = enc.GetString(src); string[] separator = { "#", "\r", "\n", "END", ";" }; string[] splittedString; string YESString = returnObject.installedSensors.YesString; returnObject.installedSensors.SetNForAllParams(); myString = DeleteComments(myString); splittedString = myString.Split(separator, StringSplitOptions.RemoveEmptyEntries); List<string> strings = splittedString.ToList<string>(); #region "Y N Switch Region" bool yes = false; splittedString = new string[2]; foreach (string str in strings) { splittedString = str.Split(new string[] { " = " }, StringSplitOptions.RemoveEmptyEntries); if (splittedString[1] == YESString) yes = true; switch (splittedString[0]) { case "ID_DEVICE": { returnObject.ID_DEVICE = splittedString[1]; } break; case "VEHICLE": { returnObject.VEHICLE = splittedString[1]; } break; case "TIME_STEP": { returnObject.TIME_STEP = splittedString[1]; } break; case "SYSTEM_TIME": { if (yes) { returnObject.installedSensors.SYSTEM_TIME.systemTime = splittedString[1]; yes = false; } } break; case "FUEL_VOLUME1": { if (yes) { returnObject.installedSensors.FUEL_VOLUME1 = splittedString[1]; yes = false; } } break; case "FUEL_VOLUME2": { if (yes) { returnObject.installedSensors.FUEL_VOLUME2 = splittedString[1]; yes = false; } } break; case "SPEED": { if (yes) { returnObject.installedSensors.SPEED = splittedString[1]; yes = false; } } break; case "FUEL_COUNTER": { if (yes) { returnObject.installedSensors.FUEL_COUNTER = splittedString[1]; yes = false; } } break; case "DISTANCE_COUNTER": { if (yes) { returnObject.installedSensors.DISTANCE_COUNTER = splittedString[1]; yes = false; } } break; case "FUEL_CONSUMPTION": { if (yes) { returnObject.installedSensors.FUEL_CONSUMPTION = splittedString[1]; yes = false; } } break; case "ENGINE_RPM": { if (yes) { returnObject.installedSensors.ENGINE_RPM = splittedString[1]; yes = false; } } break; case "VOLTAGE": { if (yes) { returnObject.installedSensors.VOLTAGE = splittedString[1]; yes = false; } } break; case "LATITUDE": { if (yes) { returnObject.installedSensors.LATITUDE = splittedString[1]; yes = false; } } break; case "LONGITUDE": { if (yes) { returnObject.installedSensors.LONGITUDE = splittedString[1]; yes = false; } } break; case "ALTITUDE": { if (yes) { returnObject.installedSensors.ALTITUDE = splittedString[1]; yes = false; } } break; case "TEMPERATURE1": { if (yes) { returnObject.installedSensors.TEMPERATURE1 = splittedString[1]; yes = false; } } break; case "TEMPERATURE2": { if (yes) { returnObject.installedSensors.TEMPERATURE2 = splittedString[1]; yes = false; } } break; case "WEIGHT1": { if (yes) { returnObject.installedSensors.WEIGHT1 = splittedString[1]; yes = false; } } break; case "WEIGHT2": { if (yes) { returnObject.installedSensors.WEIGHT2 = splittedString[1]; yes = false; } } break; case "WEIGHT3": { if (yes) { returnObject.installedSensors.WEIGHT3 = splittedString[1]; yes = false; } } break; case "WEIGHT4": { if (yes) { returnObject.installedSensors.WEIGHT4 = splittedString[1]; yes = false; } } break; case "WEIGHT5": { if (yes) { returnObject.installedSensors.WEIGHT5 = splittedString[1]; yes = false; } } break; case "MAIN_STATES": { if (yes) { returnObject.installedSensors.MAIN_STATES = splittedString[1]; yes = false; } } break; case "ADDITIONAL_SENSORS": { if (yes) { returnObject.installedSensors.ADDITIONAL_SENSORS = splittedString[1]; yes = false; } } break; case "RESERVED_3": { if (yes) { returnObject.installedSensors.RESERVED_3 = splittedString[1]; yes = false; } } break; case "RESERVED_4": { if (yes) { returnObject.installedSensors.RESERVED_4 = splittedString[1]; yes = false; } } break; case "RESERVED_5": { if (yes) { returnObject.installedSensors.RESERVED_5 = splittedString[1]; yes = false; } } break; case "RECORD": { records.Add(splittedString[1]); } break; } } #endregion PLFRecord plfRecord; int startIndex = 0; for (int recordIndex = startIndex; recordIndex < records.Count; recordIndex++) { plfRecord = new PLFRecord(); splittedString = records[recordIndex].Split(new string[] { ",", " ", ";" }, StringSplitOptions.RemoveEmptyEntries); #region "Присваивание значений" if (returnObject.installedSensors.SYSTEM_TIME.systemTime == YESString) { plfRecord.SYSTEM_TIME.systemTime = splittedString[0] + " " + splittedString[1]; if (recordIndex == startIndex) returnObject.START_PERIOD = new PLFSystemTime(splittedString[0]+" " + splittedString[1]); if(recordIndex == (records.Count-1)) returnObject.END_PERIOD = new PLFSystemTime(splittedString[0] + " " + splittedString[1]); } if (returnObject.installedSensors.FUEL_VOLUME1 == YESString) plfRecord.FUEL_VOLUME1 = splittedString[2]; if (returnObject.installedSensors.FUEL_VOLUME2 == YESString) plfRecord.FUEL_VOLUME2 = splittedString[3]; if (returnObject.installedSensors.SPEED == YESString) plfRecord.SPEED = splittedString[4]; if (returnObject.installedSensors.FUEL_COUNTER == YESString) plfRecord.FUEL_COUNTER = splittedString[5]; if (returnObject.installedSensors.DISTANCE_COUNTER == YESString) plfRecord.DISTANCE_COUNTER = splittedString[6]; if (returnObject.installedSensors.FUEL_CONSUMPTION == YESString) plfRecord.FUEL_CONSUMPTION = splittedString[7]; if (returnObject.installedSensors.ENGINE_RPM == YESString) plfRecord.ENGINE_RPM = splittedString[8]; if (returnObject.installedSensors.VOLTAGE == YESString) plfRecord.VOLTAGE = splittedString[9]; if (returnObject.installedSensors.LATITUDE == YESString) plfRecord.LATITUDE = splittedString[10]; if (returnObject.installedSensors.LONGITUDE == YESString) plfRecord.LONGITUDE = splittedString[11]; if (returnObject.installedSensors.ALTITUDE == YESString) plfRecord.ALTITUDE = splittedString[12]; if (returnObject.installedSensors.TEMPERATURE1 == YESString) plfRecord.TEMPERATURE1 = splittedString[13]; if (returnObject.installedSensors.TEMPERATURE2 == YESString) plfRecord.TEMPERATURE2 = splittedString[14]; if (returnObject.installedSensors.WEIGHT1 == YESString) plfRecord.WEIGHT1 = splittedString[15]; if (returnObject.installedSensors.WEIGHT2 == YESString) plfRecord.WEIGHT2 = splittedString[16]; if (returnObject.installedSensors.WEIGHT3 == YESString) plfRecord.WEIGHT3 = splittedString[17]; if (returnObject.installedSensors.WEIGHT4 == YESString) plfRecord.WEIGHT4 = splittedString[18]; if (returnObject.installedSensors.WEIGHT5 == YESString) plfRecord.WEIGHT5 = splittedString[19]; if (returnObject.installedSensors.MAIN_STATES == YESString) plfRecord.MAIN_STATES = splittedString[20]; if (returnObject.installedSensors.ADDITIONAL_SENSORS == YESString) plfRecord.ADDITIONAL_SENSORS = splittedString[21]; if (returnObject.installedSensors.RESERVED_3 == YESString) plfRecord.RESERVED_3 = splittedString[22]; if (returnObject.installedSensors.RESERVED_4 == YESString) plfRecord.RESERVED_4 = splittedString[23]; if (returnObject.installedSensors.RESERVED_5 == YESString) plfRecord.RESERVED_5 = splittedString[24]; #endregion returnObject.Records.Add(plfRecord); } return returnObject; }
//Проверить функции /////Statistics////////////////////// /// <summary> /// Получает проценты информации в карточке относительно дней в году /// </summary> /// <param name="date">Дата(год)</param> /// <param name="datablockId">ID файла, для которого нужно подсчитать</param> /// <returns>double - проценты</returns> public double Statistics_GetYearStatistics(DateTime date, int datablockId) { SQLDB_Records sqldbRecords = new SQLDB_Records(connectionString, sqlDB.GETMYSQLCONNECTION()); double stat = 0; int minutesInDay = 1440; int dayInYear = GetDaysInAYear(date.Year); PLFUnitClass plfUnitClassTemp = new PLFUnitClass(); PLFRecord sensorsInstalled = new PLFRecord(); Hashtable allSensorsParamIds = new Hashtable(); sensorsInstalled.SYSTEM_TIME.systemTime = "Y"; allSensorsParamIds = Get_AllParamsSensorsId(sensorsInstalled); //plfUnitClassTemp.Records = Get_Records(datablockId, sensorsInstalled, allSensorsParamIds); int dayInMonth = DateTime.DaysInMonth(date.Year, 12); plfUnitClassTemp.Records = Get_Records(datablockId, new DateTime(date.Year, 1, 1), new DateTime(date.Year, 12, dayInMonth), sensorsInstalled, allSensorsParamIds, sqldbRecords); plfUnitClassTemp.TIME_STEP = Get_TIME_STEP(datablockId); if (plfUnitClassTemp.TIME_STEP == " ") return 0; double temp = plfUnitClassTemp.Get_AllWorkingTime().TotalMinutes; stat = (plfUnitClassTemp.Get_AllWorkingTime().TotalMinutes / (minutesInDay * dayInYear)) * 100; return stat; }
public List<PLFRecord> Get_Records(List<int> dataBlockIDS, DateTime startPeriod, DateTime endPeriod, int driversCardId) { List<PLFRecord> records = new List<PLFRecord>(); List<int> dataBlockIdsToGet = new List<int>(); DateTime fromTemp = new DateTime(); DateTime toTemp = new DateTime(); SQLDB_Records sqldbRecords = new SQLDB_Records(connectionString, sqlDB.GETMYSQLCONNECTION()); maxPlfRecords = 0; GetedPlfRecords = 0; foreach (int dataBlock in dataBlockIDS) { fromTemp = Get_START_PERIOD(dataBlock); toTemp = Get_END_PERIOD(dataBlock); if (fromTemp.Date >= startPeriod && fromTemp.Date <= endPeriod) { dataBlockIdsToGet.Add(dataBlock); maxPlfRecords += sqldbRecords.Get_DataBlock_RecordsCount(dataBlock); continue; } if (toTemp.Date >= startPeriod && toTemp.Date <= endPeriod) { dataBlockIdsToGet.Add(dataBlock); maxPlfRecords += sqldbRecords.Get_DataBlock_RecordsCount(dataBlock); continue; } if(startPeriod >= fromTemp.Date && endPeriod <= toTemp.Date) { dataBlockIdsToGet.Add(dataBlock); maxPlfRecords += sqldbRecords.Get_DataBlock_RecordsCount(dataBlock); continue; } } List<PLFRecord> plfUnit = new List<PLFRecord>(); PLFUnitClass plfUnitClassTemp = new PLFUnitClass(); PLFRecord sensorsInstalled = new PLFRecord(); Hashtable allSensorsParamIds = new Hashtable(); /*if (dataBlockIdsToGet.Count > 0) { sensorsInstalled = Get_InstalledSensors(dataBlockIdsToGet[0]); allSensorsParamIds = Get_AllParamsSensorsId(sensorsInstalled); }*/ foreach (int id in dataBlockIdsToGet) { sensorsInstalled = Get_InstalledSensors(id); allSensorsParamIds = Get_AllParamsSensorsId(sensorsInstalled); plfUnit.AddRange(Get_Records(id, startPeriod, endPeriod, sensorsInstalled, allSensorsParamIds, sqldbRecords)); } plfUnit.Sort(PlfRecordsByTimeComparison); return plfUnit; }