///Запуск службы на стронних машинах: ///1. закидываем службу нужной сборки Release x64 для Win x64 и Release x86 для Win x86. /// установка из консоли с правами админа /// c:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe "место расположения файла службы без пробелов" /// <summary> /// Обработка таблици упаковок /// </summary> private void SuitcaseProcess() { //1.Get last id from big DB // 1.1 Получить ID машины. // 1.2 Сформировать запрос на сервер // 1.3 Получить данные с сервера //2. Выбрать эти данные из локальной базы данных // 2.1 если есть то отдать на сервер status 1 // 2.2 если НЕТ то отдать на сервер status 0 try { var last_local_ids = new ListIDs(); //1. Получаем последний ID из локальной БД //Константа CHECK_DB определеятеся по тому какая БД стоит на локальной машине MDB или ACCDB, //соответственно выбираются разные адаптеры для определения последнего ID в локальной БД if (!CHECK_DB) { //MDB var last_local_ID = suitTableAdapter.GetLastIDlist(); last_local_ids.localid = (int)last_local_ID.Rows[0][0]; last_local_ids.local_total = (int)last_local_ID.Rows[0][1]; last_local_ids.local_parziale = (int)last_local_ID.Rows[0][2]; } else { //ACCDB var last_local_ID = suittabAd.GetLastIDList(); last_local_ids.localid = (int)last_local_ID.Rows[0][0]; last_local_ids.local_total = (int)last_local_ID.Rows[0][1]; last_local_ids.local_parziale = (int)last_local_ID.Rows[0][2]; } eventLog1.WriteEntry(string.Format("ID:{0}; Totale_ID:{1}; Parziale_ID: {2}", last_local_ids.localid, last_local_ids.local_total, last_local_ids.local_parziale), EventLogEntryType.Information, 10); //2. Получаем последний ID из большой базы var last_outer_ID = GetLastIDFromBIGDB(ID_Machina, adress, "Suitcase"); if (last_outer_ID != String.Empty) { //если данные из большой БД пришли, то запускаем парсинг json, разбор полученных данных ServerSuitResponse resp = JsonConvert.DeserializeObject <ServerSuitResponse>(last_outer_ID); if (resp.data.polycommid == 0 && resp.data.totalid == 0 && resp.data.partialid == 0) { //Пришло сервера 000 // если сервер вернул нули, то есть в БД еще нет упаковок от данной машины string jsonSuitcases_str = ""; if (!CHECK_DB) { //MDB jsonSuitcases_str = GetSuitcasesfromlocalDB(resp.data.polycommid, suitTableAdapter); //GetSuitcasesfromlocalDB - } else if (CHECK_DB) { //ACCDB jsonSuitcases_str = GetSuitcasesfromlocalDB(resp.data.polycommid, suittabAd); } if (!String.IsNullOrEmpty(jsonSuitcases_str)) { //Отправляем все данные что есть в локальной бд Send_data(ID_Machina, jsonSuitcases_str, adress, "Suitcase"); } } else { if (!CHECK_DB) { // если пришли не 000, то проверяем есть ли данная цепочка идентификаторов в локальной БД if ((int)suitTableAdapter.GetValidData(resp.data.polycommid, resp.data.totalid, resp.data.partialid) == 0) { // если цепочки нет, то шлем на сервер статуст 0 Check_status_send(ID_Machina, 0, adress); eventLog1.WriteEntry("Data flow from this machine was stoped by machine by Suitcase", EventLogEntryType.Error, 1); } else { //если цепочка есть, то отправляем статус 1 на сервер и на основании ответа var status = Check_status_send(ID_Machina, 1, adress); if (status) { //выбираем все записи из локальной БД больше if (last_local_ids.localid > resp.data.polycommid) { string jsonSuitcases_str = GetSuitcasesfromlocalDB(resp.data.polycommid, suitTableAdapter); if (!String.IsNullOrEmpty(jsonSuitcases_str)) { // Отправляем данные на сервер методом POST Send_data(ID_Machina, jsonSuitcases_str, adress, "Suitcase"); } } else { eventLog1.WriteEntry("Don`t have new suitcases", EventLogEntryType.Information, 2); } } else { eventLog1.WriteEntry("Data flow from this machine was stoped by server", EventLogEntryType.Error, 3); } } } else { // если пришли не нули, то проверяем есть ли данная цепочка идентификаторов в локальной БД if ((int)suittabAd.GetValidData(resp.data.polycommid, resp.data.totalid, resp.data.partialid) == 0) { // если нет, то шлем на сервер статуст 0 Check_status_send(ID_Machina, 0, adress); eventLog1.WriteEntry("Data flow from this machine was stoped by machine by Suitcase", EventLogEntryType.Error, 1); } else { //если цепочка есть, то отправляем статус 1 на сервер и на основании ответа var status = Check_status_send(ID_Machina, 1, adress); if (status) { //выбираем все записи из локальной БД больше if (last_local_ids.localid > resp.data.polycommid) { string jsonSuitcases_str = GetSuitcasesfromlocalDB(resp.data.polycommid, suittabAd); if (!String.IsNullOrEmpty(jsonSuitcases_str)) { // Отправляем данные на сервер методом POST Send_data(ID_Machina, jsonSuitcases_str, adress, "Suitcase"); } } else { eventLog1.WriteEntry("Don`t have new suitcases", EventLogEntryType.Information, 2); } } else { eventLog1.WriteEntry("Data flow from this machine was stoped by server", EventLogEntryType.Error, 3); } } } } } } catch (Exception exc) { eventLog1.WriteEntry(string.Format("Trouble: {0} ", exc.ToString()), EventLogEntryType.Error, 3); } }
protected override bool Execute(CodeActivityContext context) { Error.Set(context, null); EnumGroupTPPowerReportMode?typecalc = null; if (GroupTPPowerReportMode == GroupTPPowerReportMode.OpenPeriod) { typecalc = EnumGroupTPPowerReportMode.OpenPeriod; } if (GroupTPPowerReportMode == GroupTPPowerReportMode.ClosedCurrPeriod) { typecalc = EnumGroupTPPowerReportMode.ClosedCurrPeriod; } if (GroupTPPowerReportMode == GroupTPPowerReportMode.ClosedNextPeriod) { typecalc = EnumGroupTPPowerReportMode.ClosedNextPeriod; } if (GroupTPPowerReportMode == GroupTPPowerReportMode.ClosedPrevPeriod) { typecalc = EnumGroupTPPowerReportMode.ClosedPrevPeriod; } string userName = UserName;//.Get(context); string userID = null; if (string.IsNullOrEmpty(userName)) { Error.Set(context, "Значение свойства 'Пользователь' не может быть пустым"); return(false); } try { List <UserInfo> UList = ARM_Service.EXPL_Get_All_Users(); foreach (UserInfo u in UList) { if (u.UserName.ToLower(System.Globalization.CultureInfo.InvariantCulture) == userName.ToLower(System.Globalization.CultureInfo.InvariantCulture)) { userID = u.User_ID; break; } } } catch (Exception ex) { Error.Set(context, ex.Message); if (!HideException.Get(context)) { throw ex; } } if (!string.IsNullOrEmpty(Error.Get(context))) { return(false); } if (string.IsNullOrEmpty(userID)) { Error.Set(context, "Не найден пользователь с именем '" + UserName + "'"); return(false); } List <int> listIDs = ListIDs.Get(context); if (listIDs == null) { Error.Set(context, "Неопределен список идентификаторов"); return(false); } List <ID_TypeHierarchy> idList = new List <ID_TypeHierarchy>(); foreach (int id in listIDs) { ID_TypeHierarchy idTypeHier = new ID_TypeHierarchy(); idTypeHier.ID = id; idTypeHier.TypeHierarchy = TypeIDs; idList.Add(idTypeHier); } MemoryStream doc = null; try { SectionIntegralComplexResults res; if (ReportType == enumReportType.ReportReplacementOfMeters) { //TODO часовой пояс res = ARM_Service.Rep_ReplacementOfAccountingFacilities(idList, StartDateTime.Get(context), EndDateTime.Get(context), ReportType, typecalc, userName, null); } else { //TODO часовой пояс res = ARM_Service.REP_OverflowControl(idList, StartDateTime.Get(context), EndDateTime.Get(context), ReportType, typecalc, userName, null, null, false, 3, ",", enumTimeDiscreteType.DBHours, null); } if (res.Document != null) { res.Document.Position = 0; var ms = CompressUtility.DecompressGZip(res.Document); ms.Position = 0; Document.Set(context, ms); //File.WriteAllBytes(@"C:\12\test_SysRep.xls",ms.ToArray()); } switch (res.AdapterType) { case TExportExcelAdapterType.toXLS: FileExtention.Set(context, "xls"); break; case TExportExcelAdapterType.toXLSx: FileExtention.Set(context, "xlsx"); break; case TExportExcelAdapterType.toHTML: FileExtention.Set(context, "html"); break; case TExportExcelAdapterType.toPDF: FileExtention.Set(context, "pdf"); break; } if (res.Errors != null) { Error.Set(context, res.Errors.ToString()); } } catch (Exception ex) { Error.Set(context, ex.Message); if (!HideException.Get(context)) { throw ex; } } return(string.IsNullOrEmpty(Error.Get(context))); }