/// <summary> Сохранить объекты связанные с агрооперациями в файлы </summary> public static void SaveAgroOperationRelatedObjects() { CropioApi cropio = GetCropioClient(); Console.WriteLine("Получение объектов из Cropio ...\n"); // cropio.SaveJsonObjectsToFile <CO_AgroOperation>(); cropio.SaveJsonObjectsToFile <CO_AgriWorkPlan>(); cropio.SaveJsonObjectsToFile <CO_ApplicationMixItem>(); cropio.SaveJsonObjectsToFile <CO_Chemical>(); cropio.SaveJsonObjectsToFile <CO_Crop>(); cropio.SaveJsonObjectsToFile <CO_Fertilizer>(); cropio.SaveJsonObjectsToFile <CO_Field>(); cropio.SaveJsonObjectsToFile <CO_FieldGroup>(); cropio.SaveJsonObjectsToFile <CO_FieldShape>(); cropio.SaveJsonObjectsToFile <CO_GroupFolder>(); cropio.SaveJsonObjectsToFile <CO_Implement>(); cropio.SaveJsonObjectsToFile <CO_Machine>(); cropio.SaveJsonObjectsToFile <CO_MachineGroup>(); cropio.SaveJsonObjectsToFile <CO_MachineTask>(); cropio.SaveJsonObjectsToFile <CO_Seed>(); cropio.SaveJsonObjectsToFile <CO_User>(); cropio.SaveJsonObjectsToFile <CO_WorkType>(); cropio.SaveJsonObjectsToFile <CO_WorkTypeGroup>(); // Console.WriteLine("\nПолучение всех объектов завершено\n"); }
public static void ShowActualAlerts(this CropioApi cropio, Int32 recordsPerPage = 200) { MassResponse <Int32> alertTypesIds = cropio.GetObjectsIds <CO_AlertType>(); if (alertTypesIds.Data == null) { Console.WriteLine("Identifiers not found"); return; } MassResponse <CO_AlertType> alertTypes = cropio.GetObjects <CO_AlertType>(alertTypesIds.Data); HashSet <Int32> valuableAlertTypesIds = new HashSet <int> (alertTypes.Data.Where(x => x.AdditionalInfo.Contains("[#Run in ELMA]")).Select(x => x.Id)); List <CO_Alert> activeAlerts = new List <CO_Alert>(); MassResponse <Int32> alertsIds = cropio.GetObjectsIds <CO_Alert>(); if (alertsIds.Data == null) { Console.WriteLine("Identifiers not found"); return; } foreach (var idsPage in alertsIds.Data.Paginate(recordsPerPage)) { MassResponse <CO_Alert> objs = cropio.GetObjects <CO_Alert>(idsPage); activeAlerts.AddRange(objs.Data.Where(x => x.Status != CE_StatusOfAllert.Closed && valuableAlertTypesIds.Contains(x.Id_AlertType))); } foreach (CO_Alert alert in activeAlerts) { Console.WriteLine(alert); Console.WriteLine("———————————————————————————————"); } }
/// <summary> Показать поля и актуальные тревоги </summary> public static void ShowFieldsAndActualAlerts() { CropioApi cropio = GetCropioClient(); cropio.ShowFields(); //cropio.ShowActualAlerts(); }
public static void SyncDataTable <T>(CropioApi cropio) where T : ICropioRegularObject { if (!Directory.Exists(DirPath_LocalDataStorage)) { Directory.CreateDirectory(DirPath_LocalDataStorage); } List <T> data = LoadDataFromJsonFile <T>() ?? new List <T>(); DateTime? updatedAt = data.Max(x => x.UpdatedAt); MassResponse_Changes changedObjs = cropio.GetChangedObjectsIds <T>(updatedAt); if (changedObjs.Data.Count == 0) { return; } List <T> updatedData = new List <T>(); foreach (var ids in changedObjs.Data.Select(x => x.Id).Paginate(200)) { updatedData.AddRange(cropio.GetObjects <T>(ids).Data); } data = data.Except(updatedData, (a, b) => a.Id == b.Id).ToList(); data.AddRange(updatedData); data = data.OrderByDescending(x => x.UpdatedAt).ToList(); data.SaveDataToJsonFile(); }
/// <summary> Сохранить докумен, прикрепленный к тревоге </summary> public static void SaveAlertRelatedDocuments(Int32 idAlertWithDocument = 498) { CropioApi cropio = GetCropioClient(); // String fileFullName = ""; //Int32 idAlertWithoutoDcuments = 507; MassResponse <CO_Document> doc = cropio.ObjRelatedDocument <CO_Alert>(idAlertWithDocument); //Console.WriteLine(doc); if (doc.Data.Count == 0) { return; } foreach (CO_Document document in doc.Data) { //Console.WriteLine(document.DocumentUrl); Console.WriteLine(Path.GetFileName(Uri.UnescapeDataString(document.DocumentUrl))); if (!String.IsNullOrWhiteSpace(fileFullName)) { Byte[] fileBody = cropio.DownloadDocumentFile(document.Id); File.WriteAllBytes(fileFullName, fileBody); } } }
public static void ShowAllObjectTypes(this CropioApi cropio) { MassResponse <Int32> ids = cropio.GetObjectsIds <CO_Version>(); HashSet <String> typeNames = new HashSet <String>(); Int32 itemNo = 0; foreach (IEnumerable <Int32> page in ids.Data.Paginate(1000)) { MassResponse <CO_Version> objects = cropio.GetObjects <CO_Version>(page); if (!objects.CropioResponse.IsSuccess) { continue; } foreach (CO_Version obj in objects.Data) { if (typeNames.Contains(obj.ItemType)) { continue; } typeNames.Add(obj.ItemType); Console.Write("\n{0:00} {1,-100} ", ++itemNo, obj.ItemType); } Console.Write("."); } Console.WriteLine("Finished"); }
public static void SyncroniseData(CropioApi cropio) { String opName = "Synchronization"; Int32 itemsCount = 11; Int32 curItem = 0; opName.ProgressBar(itemsCount, curItem++); SyncDataTable <CO_User>(cropio); opName.ProgressBar(itemsCount, curItem++); SyncDataTable <CO_UserRoleAssignment>(cropio); opName.ProgressBar(itemsCount, curItem++); SyncDataTable <CO_UserRole>(cropio); opName.ProgressBar(itemsCount, curItem++); SyncDataTable <CO_UserRolePermission>(cropio); opName.ProgressBar(itemsCount, curItem++); SyncDataTable <CO_FieldGroup>(cropio); opName.ProgressBar(itemsCount, curItem++); SyncDataTable <CO_Field>(cropio); opName.ProgressBar(itemsCount, curItem++); SyncDataTable <CO_History_Item>(cropio); opName.ProgressBar(itemsCount, curItem++); SyncDataTable <CO_History_InventoryItem>(cropio); opName.ProgressBar(itemsCount, curItem++); // SyncDataTable <CO_Alert>(cropio); opName.ProgressBar(itemsCount, curItem++); SyncDataTable <CO_AlertType>(cropio); opName.ProgressBar(itemsCount, curItem++); // SyncDataTable <CO_Crop>(cropio); opName.ProgressBar(itemsCount, curItem); Console.WriteLine(); }
private static List <View_Field> GetUserRelatedFields(CropioApi cropio, Guid userExternalId) { SyncroniseData(cropio); var user = LoadDataFromJsonFile <CO_User>().FirstOrDefault(x => String.Equals(x.Id_External, userExternalId.ToString(), StringComparison.InvariantCultureIgnoreCase)); if (user == null) { throw new InvalidOperationException(String.Format("Пользователь с внешним идентификатором \"{0}\" не найден", userExternalId)); } if (user.Status == CE_UserStatus.NoAccess) { return(new List <View_Field>()); } List <View_Field> userAllowedFields = GetActualFields(cropio); if (user.Status != CE_UserStatus.User) { return(userAllowedFields); } // return fields allowed for current user List <CO_UserRoleAssignment> rolesAssignment = LoadDataFromJsonFile <CO_UserRoleAssignment>() .Where(x => x.Id_User == user.Id).ToList(); List <CO_UserRole> userRoles = LoadDataFromJsonFile <CO_UserRole>() .Intersect(rolesAssignment, (a, b) => a.Id == b.Id_UserRole).ToList(); List <CO_UserRolePermission> userRolePermissions = LoadDataFromJsonFile <CO_UserRolePermission>() .Where(x => x.SubjectType == CE_UserRolePermissionSubjectType.FieldGroup && (x.AccessLevel != CE_AccessLevel.NoAccess)) .Intersect(userRoles, (a, b) => a.Id_UserRole == b.Id).ToList(); userAllowedFields = userAllowedFields.Intersect(userRolePermissions, (a, b) => a.Id_FieldGroup == b.Id_Subject).ToList(); return(userAllowedFields); }
public static void Main(CropioApi cropio) { //Test_AsignResponsibleToMultipleAllerts(cropio); //Test_AddRemarkToMultipleAllerts(cropio); //Test_CloseMultipleAlerts(cropio); var users = GetUsersWithExternalID().OrderBy(x => x.UserName); foreach (var u in users) { List <View_Field> userAllowedFields = GetUserRelatedFields(cropio, new Guid(u.Id_External)) .OrderBy(x => x.FieldsGroupName).ThenBy(x => x.CropName).ThenBy(x => x.HistoryItemVariety).ThenBy(x => x.Name).ToList(); foreach (var usr in users) { Boolean isCurrentUser = usr.Id == u.Id; var background = Console.BackgroundColor; if (isCurrentUser) { Console.BackgroundColor = ConsoleColor.DarkGreen; } Console.WriteLine($" {(isCurrentUser ? "■" : " ")} {usr.Id_External, 50} | {usr.UserName, -50} | {usr.Position, -50} | {usr.Status}"); Console.BackgroundColor = background; } Console.WriteLine("————————————————————————————————————————————————————————————————————————————————"); Console.WriteLine($"User available fields: {userAllowedFields.Count}"); Console.WriteLine("————————————————————————————————————————————————————————————————————————————————"); Console.ReadLine(); foreach (var f in userAllowedFields) { Console.WriteLine($"{f}"); } Console.ReadLine(); Console.Clear(); } }
public static void Test_AsignResponsibleToMultipleAllerts(CropioApi cropio) { List <Int32> alertsIds = new List <int> { 831, 830, 829, 828, 827, 826, 825, 824, 823, 822, 821, 820, 819, 818, 817, 816 }; AllertsAssignResponsible(cropio, alertsIds, 9911, "[#Test] Назначен ответственный, назначены корректирующие действия", DateTime.Now); }
public static void Test_CloseMultipleAlerts(CropioApi cropio) { List <Int32> alertsIds = new List <int> { 831, 830, 829, 828, 827, 826, 825, 824, 823, 822, 821, 820, 819, 818, 817, 816 }; AlertsClose(cropio, alertsIds, "[#Test] Тревога закрыта", DateTime.Now); }
public static void Test_AddRemarkToMultipleAllerts(CropioApi cropio) { List <Int32> alertsIds = new List <int> { 831, 830, 829, 828, 827, 826, 825, 824, 823, 822, 821, 820, 819, 818, 817, 816 }; AlertsAddRemark(cropio, alertsIds, "[#Test] Выполнены корректирующие действия", DateTime.Now); }
public static void ShowDistinctValues <T1, T2>(this CropioApi cropio, Func <T1, T2> selector) where T1 : ICropioRegularObject { List <T2> values = cropio.GetUniqueValues <T1, T2>(selector).OrderBy(X => X).ToList(); foreach (var value in values) { Console.WriteLine(value); } }
public static void CreateAllerts(this CropioApi cropio) { // 01 - Насекомые // 04 - Сорняки // 05 - Заболование // 06 - Другое // 07 - погодные условия // 08 - Уровень развития растений // --- // 16153 - Кирильчук Павел Александрович // --- // CO_Alert alert01 = new CO_Alert { Status = CE_StatusOfAllert.Open, Description = "[TEST] Тревога создана программным образом.", CreatedAt = DateTime.Now, EventStartTime = DateTime.Now, Id_AlertType = 6, AlertableObjectType = CE_AlertableObjectType.Field, Id_AlertableObject = 208, // КАФ, VPL01 Id_CreatedByUser = 16153, // Кирильчук Павел Александрович Id_ResponsiblePerson = 16153 // Кирильчук Павел Александрович }; CO_Alert alert02 = new CO_Alert { Status = CE_StatusOfAllert.Open, Description = "[TEST] Тревога создана программным образом.", CreatedAt = DateTime.Now, EventStartTime = DateTime.Now, Id_AlertType = 6, AlertableObjectType = CE_AlertableObjectType.Field, Id_AlertableObject = 160, // КАХ, VBK01 Id_CreatedByUser = 16153, // Кирильчук Павел Александрович Id_ResponsiblePerson = 16153 // Кирильчук Павел Александрович }; CO_Alert alert03 = new CO_Alert { Status = CE_StatusOfAllert.Open, Description = "[TEST] Тревога создана программным образом.", CreatedAt = DateTime.Now, EventStartTime = DateTime.Now, Id_AlertType = 6, AlertableObjectType = CE_AlertableObjectType.Field, Id_AlertableObject = 170, // КАХ, VCH01 Id_CreatedByUser = 16153, // Кирильчук Павел Александрович Id_ResponsiblePerson = 16153 // Кирильчук Павел Александрович }; // Console.WriteLine(cropio.CreateObject(alert01)); Console.WriteLine(cropio.CreateObject(alert02)); Console.WriteLine(cropio.CreateObject(alert03)); }
public static void ShowIds <T>(this CropioApi cropio) where T : ICropioRegularObject { Console.WriteLine(CropioDataModel.Name <T>()); MassResponse <Int32> ids = cropio.GetObjectsIds <T>(); if (ids.Data == null) { Console.WriteLine("Data == null"); return; } Console.WriteLine(String.Join(", ", ids.Data.Select(x => x.ToString().PadLeft(8)))); }
public static void ShowItemNo <T>(this CropioApi cropio, Int32 itemNo) where T : ICropioRegularObject { MassResponse <Int32> ids = cropio.GetObjectsIds <T>(); if (ids.Data == null) { Console.WriteLine("Data == null"); return; } cropio.ShowObject <T>(ids.Data[itemNo]); }
public static void ShowObject <T>(this CropioApi cropio, Int32 objId) where T : ICropioRegularObject { Response <T> obj = cropio.GetObject <T>(objId); if (obj == null || obj.Data == null) { return; } Console.WriteLine("\n\n————— {0,6} ({1}) ——————————————————————————————————————", objId, CropioDataModel.Name <T>()); Console.WriteLine(obj.Data); }
public static void Test_CreateMultipleAlerts(CropioApi cropio) { List <Int32> fieldsIds = new List <Int32> { 198, 200, 202, 203, 205, 206, 321, 199, 201, 196, 197, 224, 204, 207, 322, 210 }; var result = AllertsCreate(cropio, fieldsIds, 6, "[#Test 5] This allert belong to allerts set #5 which was runned from 3rd party software", DateTime.Now); foreach (var res in result) { Console.WriteLine(res.IsSuccess); } }
public static void Update(this CropioApi cropio) { Response <CO_Alert> resp_alert = cropio.GetObject <CO_Alert>(433); if (resp_alert.CropioResponse.IsSuccess) { CO_Alert alert = resp_alert.Data; //alert.Id_ResponsiblePerson = 9913; alert.Id_AlertableObject = 21; alert.Description += "\n[TEST] Тревога изменена программным образом."; Console.WriteLine(cropio.UpdateObject(alert)); } }
public static List <CropioResponse> AlertsAddRemark(CropioApi cropio, List <Int32> alertsIds, String remark, DateTime timeStamp) { SyncDataTable <CO_Alert>(cropio); var alerts = LoadDataFromJsonFile <CO_Alert>().Intersect(alertsIds, (a, b) => a.Id == b); List <CropioResponse> cropioResponses = new List <CropioResponse>(); // foreach (var alert in alerts) { alert.Description += $"\n{timeStamp:yyyy.MM.dd HH:mm} \n{remark}"; cropioResponses.Add(cropio.UpdateObject(alert).CropioResponse); } return(cropioResponses); }
public static void ShowAlertTypes(this CropioApi cropio) { List <CO_AlertType> alertTypes = cropio.GetObjects <CO_AlertType>(cropio.GetObjectsIds <CO_AlertType>().Data).Data; foreach (var item in alertTypes) { if (String.IsNullOrEmpty(item.AdditionalInfo) || !item.AdditionalInfo.Contains("[#Run in ELMA]")) { continue; } Console.WriteLine(item); } Console.WriteLine(); }
public static void ShowObjects <T>(this CropioApi cropio, params Int32[] objIds) where T : ICropioRegularObject { MassResponse <T> result = cropio.GetObjects <T>(objIds); if (result.Data == null) { Console.WriteLine("Data == null"); return; } foreach (T obj in result.Data) { Console.WriteLine("\n\n————— {0,6} ({1}) ——————————————————————————————————————", obj.Id, CropioDataModel.Name <T>()); Console.WriteLine(obj); } }
public static void Create(this CropioApi cropio) { CO_Alert alert = new CO_Alert { Status = CE_StatusOfAllert.Open, AlertableObjectType = CE_AlertableObjectType.Field, Description = "[TEST] Тревога создана программным образом.", CreatedAt = DateTime.Now, EventStartTime = DateTime.Now, Id_AlertType = 1, Id_AlertableObject = 21, Id_CreatedByUser = 33481, Id_ResponsiblePerson = 9913 }; Console.WriteLine(cropio.CreateObject(alert)); }
static void Main(String[] args) { CropioApi cropio = GetCropioClient(); CO_Alert alert = cropio.GetObject <CO_Alert>(834).Data; Console.WriteLine(alert.GetTextView(1)); //RunMultipleAlertsFromOutside.Main(cropio); //var resp = cropio.GetObjectsIds<CO_Alert>(); //foreach(var ids in resp.Data.Paginate(100)) //{ // var resp2 = cropio.GetObjects<CO_Alert>(ids); // foreach(var obj in resp2.Data) // { // Console.WriteLine(obj.GetTextView(1)); // } //} }
public static List <CropioResponse> AllertsCreate(CropioApi cropio, List <Int32> fieldsIds, Int32 alertTypeId, String alertDescription, DateTime eventStartTime) { List <CropioResponse> cropioResponses = new List <CropioResponse>(); foreach (var fieldId in fieldsIds) { CO_Alert alert = new CO_Alert { Id_AlertableObject = fieldId, Description = alertDescription, Id_AlertType = alertTypeId, EventStartTime = eventStartTime, Status = CE_StatusOfAllert.Open, AlertableObjectType = CE_AlertableObjectType.Field, CreatedAt = DateTime.Now, }; cropioResponses.Add(cropio.CreateObject(alert).CropioResponse); } return(cropioResponses); }
public static void ShowAllObjects_Slowly <T>(this CropioApi cropio, Boolean showNextItemAutomated = false) where T : ICropioRegularObject { MassResponse <Int32> ids = cropio.GetObjectsIds <T>(); if (ids.Data == null) { Console.WriteLine("Identifiers not found"); return; } foreach (Int32 id in ids.Data) { Response <T> resp = cropio.GetObject <T>(id); Console.WriteLine(resp.Data); if (showNextItemAutomated) { continue; } Console.ReadKey(); Console.Clear(); } }
public static void ShowHistoryInventoryItemTypes(this CropioApi cropio) { Console.WriteLine("Получение идентификаторов для для таблицы CO_History_InventoryItem"); IEnumerable <IEnumerable <Int32> > ids = cropio.GetObjectsIds <CO_History_InventoryItem>().Data.Paginate(500); HashSet <CE_HistoryableType> historyableTypes = new HashSet <CE_HistoryableType>(); Int32 itemNo = 0; foreach (IEnumerable <Int32> page in ids) { MassResponse <CO_History_InventoryItem> objects = cropio.GetObjects <CO_History_InventoryItem>(page); foreach (CO_History_InventoryItem obj in objects.Data) { if (historyableTypes.Contains(obj.HistoryableType)) { continue; } historyableTypes.Add(obj.HistoryableType); Console.WriteLine("{0, 4} {1}", itemNo, obj.HistoryableType); } } }
public static void ShowChangedObjects(this CropioApi cropio, DateTime timeOfLastSuccessfulSynchronization) { DateTime currentTime = DateTime.Now; Console.WriteLine("Получение полей."); MassResponse_Changes fields = cropio.GetChangedObjectsIds <CO_Field>(timeOfLastSuccessfulSynchronization); Console.WriteLine("Получение групп полей."); MassResponse_Changes fieldGroups = cropio.GetChangedObjectsIds <CO_FieldGroup>(timeOfLastSuccessfulSynchronization); Console.WriteLine("Получение елементов истории."); MassResponse_Changes historyItems = cropio.GetChangedObjectsIds <CO_History_Item>(timeOfLastSuccessfulSynchronization); Console.WriteLine("Получение елементов истории инвентаря."); MassResponse_Changes inventoryHistoryItems = cropio.GetChangedObjectsIds <CO_History_InventoryItem>(timeOfLastSuccessfulSynchronization); Console.WriteLine("Получение культур."); MassResponse_Changes crops = cropio.GetChangedObjectsIds <CO_Crop>(timeOfLastSuccessfulSynchronization); Console.WriteLine("Получение тревог."); MassResponse_Changes alerts = cropio.GetChangedObjectsIds <CO_Alert>(timeOfLastSuccessfulSynchronization); Console.WriteLine("Получение типов тревог."); MassResponse_Changes alertTypes = cropio.GetChangedObjectsIds <CO_AlertType>(timeOfLastSuccessfulSynchronization); Console.WriteLine("Получение пользователей."); MassResponse_Changes users = cropio.GetChangedObjectsIds <CO_User>(timeOfLastSuccessfulSynchronization); StringBuilder sb = new StringBuilder() .Append("\n fields: ").Append(GetChangedObjectsTextInfo(fields)) .Append("\n fieldGroups: ").Append(GetChangedObjectsTextInfo(fieldGroups)) .Append("\n historyItems: ").Append(GetChangedObjectsTextInfo(historyItems)) .Append("\n inventoryHistoryItems: ").Append(GetChangedObjectsTextInfo(inventoryHistoryItems)) .Append("\n crops: ").Append(GetChangedObjectsTextInfo(crops)) .Append("\n alerts: ").Append(GetChangedObjectsTextInfo(alerts)) .Append("\n alertTypes: ").Append(GetChangedObjectsTextInfo(alertTypes)) .Append("\n users: ").Append(GetChangedObjectsTextInfo(users)); Console.WriteLine(sb.ToString()); }
public static HashSet <T2> GetUniqueValues <T, T2>(this CropioApi cropio, Func <T, T2> selector) where T : ICropioRegularObject { HashSet <T2> uniqueValues = new HashSet <T2>(); const Int32 recordsPerPage = 200; MassResponse <Int32> ids = cropio.GetObjectsIds <T>(); if (ids.Data == null) { Console.WriteLine("Identifiers not found"); return(uniqueValues); } // foreach (var page in ids.Data.Paginate(recordsPerPage)) { MassResponse <T> objects = cropio.GetObjects <T>(page); IEnumerable <T2> values = objects.Data.DistinctValues(selector); foreach (T2 value in values) { uniqueValues.Add(value); } } return(uniqueValues); }
public static void ShowAllObjects <T>(this CropioApi cropio, Boolean showNextItemAutomated = false) where T : ICropioRegularObject { const Int32 recordsPerPage = 200; MassResponse <Int32> ids = cropio.GetObjectsIds <T>(); if (ids.Data == null) { Console.WriteLine("Identifiers not found"); return; } Int32 pagesCount = (Int32)Math.Ceiling((Double)ids.Data.Count / (Double)recordsPerPage); Int32 recordNo = 0; for (Int32 pageNumber = 0; pageNumber < pagesCount; pageNumber++) { Int32 startIndex = pageNumber * recordsPerPage; Int32 recordsCount = (startIndex + recordsPerPage) < ids.Data.Count ? recordsPerPage : ids.Data.Count - startIndex; List <Int32> idsSubSet = ids.Data.GetRange(startIndex, recordsCount); // MassResponse <T> result = cropio.GetObjects <T>(idsSubSet); if (result.Data == null) { Console.WriteLine("Data == null"); break; } foreach (T obj in result.Data) { Console.WriteLine("\n─────{0}───────────────────────────────────────────────────────", (recordNo++).ToString().PadLeft(10, '─')); Console.WriteLine(obj); if (showNextItemAutomated) { continue; } Console.ReadKey(); Console.Clear(); } } }