}//end of event handler //transfer button click event to transfer money from one account to aother private void btnTransfer_Click(object sender, EventArgs e) { //Note that we are creatinf a transaction here in order to make sure that if something goes //wrong in a middle of transfering money our database stays in consistent state. using (TransactionScope transaction = new TransactionScope()) { try { BLLTransactionManager manager = new BLLTransactionManager(); //Dealing with getting monney from one acc first int transferAmmount = MoneyTransformer.TransformMoney(txtAmmount.Text); int debitedAccNewBal = SourceAccount.CurrentBalance - transferAmmount; // new balance for credited account int creditedAccNewBal = DestinationAccount.CurrentBalance + transferAmmount; bool transferPossible = false; // setting the possibility of transaction to true if (SourceAccount.CurrentBalance >= transferAmmount) { transferPossible = true; } else { MessageBox.Show("Not Enough funds"); } if (transferPossible) { //testing to make sure saving account doesnt transfer to external if (SourceAccount.AccountType.Equals("saving")) { if (!ExternalTransfer) { manager.WithdrawMonies(SourceAccount.AccountNo, debitedAccNewBal, SourceAccount.AccountType); //This code can be uncommented in order to show that database doesnt change if there was an error or exceprion somewhere //Exception ex = new Exception(); //if (ex != null) //{ // MessageBox.Show("Opps SOMETHING WENT WRONG HERE !!!"); //} //throw ex; manager.DepositMonies(DestinationAccount.AccountNo, creditedAccNewBal, DestinationAccount.AccountType); int debitTransNo = 0; int creditTransNo = 0; //setting and creating transaction for debit TransactionRecord debitTrans = new TransactionRecord(); debitTrans.AccountNumber = SourceAccount.AccountNo; debitTrans.TransactionType = TransactionType.debit; debitTrans.Date = DateTime.Now; debitTrans.TransactionAmmount = transferAmmount; debitTrans.Balance = debitedAccNewBal; //creating a transaction for debited account manager.CreateTransaction(debitTrans, out debitTransNo); //setting and creating transaction for credit TransactionRecord creditTrans = new TransactionRecord(); creditTrans.AccountNumber = DestinationAccount.AccountNo; creditTrans.TransactionType = TransactionType.credit; creditTrans.Date = DateTime.Now; creditTrans.TransactionAmmount = transferAmmount; creditTrans.Balance = creditedAccNewBal; //creating a transaction for credit account manager.CreateTransaction(creditTrans, out creditTransNo); //Create Transfer Record object first TransferRecord record = new TransferRecord(); record.RecepientName = txtRecepientName.Text; record.DebitedAccount = int.Parse(txtAccountNumber.Text); //NOTE here I am setting the record transaction number to the number created for debited account record.TransactionNumber = debitTransNo; record.DestinationSortCode = txtDestinationSortCode.Text; record.DestinationAccNo = int.Parse(txtAccOutNumber.Text); record.TransferAmmount = transferAmmount; record.TransferDate = DateTime.Now; record.TransferDescription = rtfDescription.Text; bool success = false; //creating new transfer record success = manager.CreateTransfer(record); transaction.Complete(); transaction.Dispose(); if (success) { MessageBox.Show("Transfer Successfull"); } } else { MessageBox.Show("Cant transfer to an external account from saving account\nOnly internal transfers are allowed"); } } else { manager.WithdrawMonies(SourceAccount.AccountNo, debitedAccNewBal, SourceAccount.AccountType); //This code can be uncommented in order to show that database doesnt change if there was an error or exceprion somewhere //Exception ex = new Exception(); //if (ex != null) //{ // MessageBox.Show("Opps SOMETHING WENT WRONG HERE !!!"); //} //throw ex; manager.DepositMonies(DestinationAccount.AccountNo, creditedAccNewBal, DestinationAccount.AccountType); int debitTransNo = 0; int creditTransNo = 0; //setting and creating transaction for debit TransactionRecord debitTrans = new TransactionRecord(); debitTrans.AccountNumber = SourceAccount.AccountNo; debitTrans.TransactionType = TransactionType.debit; debitTrans.Date = DateTime.Now; debitTrans.TransactionAmmount = transferAmmount; debitTrans.Balance = debitedAccNewBal; //creating a transaction for debited account manager.CreateTransaction(debitTrans, out debitTransNo); //setting and creating transaction for credit TransactionRecord creditTrans = new TransactionRecord(); creditTrans.AccountNumber = DestinationAccount.AccountNo; creditTrans.TransactionType = TransactionType.credit; creditTrans.Date = DateTime.Now; creditTrans.TransactionAmmount = transferAmmount; creditTrans.Balance = creditedAccNewBal; //creating a transaction for credit account manager.CreateTransaction(creditTrans, out creditTransNo); //Create Transfer Record object first TransferRecord record = new TransferRecord(); record.RecepientName = txtRecepientName.Text; record.DebitedAccount = int.Parse(txtAccountNumber.Text); //NOTE here I am setting the record transaction number to the number created for debited account record.TransactionNumber = debitTransNo; record.DestinationSortCode = txtDestinationSortCode.Text; record.DestinationAccNo = int.Parse(txtAccOutNumber.Text); record.TransferAmmount = transferAmmount; record.TransferDate = DateTime.Now; record.TransferDescription = rtfDescription.Text; bool success = false; //creating new transfer record success = manager.CreateTransfer(record); transaction.Complete(); transaction.Dispose(); if (success) { MessageBox.Show("Transfer Successfull"); } } } } catch (TransactionException ex) { transaction.Dispose(); MessageBox.Show("OOpppps somethinge went WRONG there"); throw ex; } catch (Exception ex) { MessageBox.Show("No money were transfered"); } } }//End of TransferClick
/// <summary> /// Удаление TransferRecord /// </summary> /// <param name="transferRecord"></param> public void Delete(TransferRecord transferRecord) { // Ограничение - если у агрегата только одна transfer record - мы не можем ее удалить ... // Добавление & удаление transfer record влияет на математический аппарат // Обнуляем математический аппарат if (transferRecord.ParentComponent != null) { if (transferRecord.ParentComponent.TransferRecords.Count == 1) { throw new Exception("1153: Can not delete single transfer record"); } if (transferRecord.ConsumableId > 0) { //Поиск комплектующего, часть которого была перемещена данной записью Entities.General.Accessory.Component fromConsumable = _componentCore.GetBaseComponentById(transferRecord.ConsumableId) ?? _componentCore.GetComponentById(transferRecord.ConsumableId); if (fromConsumable != null) { //комплектующее найдено //Проверка, находится ли то комплектующее, часть которого была перемещена //на той же локации, с которой была перемещена данная часть TransferRecord consumLocation = fromConsumable.TransferRecords.GetLast(); if (consumLocation != null && ((consumLocation.DestinationObjectType == SmartCoreType.BaseComponent && consumLocation.DestinationObjectId == transferRecord.FromBaseComponentId) || (consumLocation.DestinationObjectType == SmartCoreType.Aircraft && consumLocation.DestinationObjectId == transferRecord.FromAircraftId) || (consumLocation.DestinationObjectType == SmartCoreType.Store && consumLocation.DestinationObjectId == transferRecord.FromStoreId))) { //Если последняя точка назначения исходного комплектующего //совпадает с отправной точкой данной части исходного комплектующего //то необходимо удалить данную часть комплектующуго, а кол-во //перемещенных единиц добавить к исходному комплектующему transferRecord.ParentComponent.IsDeleted = true; _newKeeper.Delete(transferRecord.ParentComponent, true, false); fromConsumable.Quantity += transferRecord.ParentComponent.Quantity > 0 ? transferRecord.ParentComponent.Quantity : 1; _componentCore.Save(fromConsumable); } else { // Иначе, если не найдена последняя запись о перемещении // исходного расходника или // если исходный расходник был перемещен с отправной точки данной части // то нужно произвести простой откат данной записи о перемещении // Сохраняем запись transferRecord.IsDeleted = true; _newKeeper.Save(transferRecord); transferRecord.ParentComponent.TransferRecords.Remove(transferRecord); // Обновляем состояние объекта _newLoader.SetDestinations(transferRecord.ParentComponent); if (transferRecord.ParentComponent is BaseComponent) { _calculator.ResetMath((BaseComponent)transferRecord.ParentComponent); } } } else { // если исходный расходник не найден // то нужно произвести простой откат данной записи о перемещении // Сохраняем запись transferRecord.IsDeleted = true; _newKeeper.Save(transferRecord); transferRecord.ParentComponent.TransferRecords.Remove(transferRecord); // Обновляем состояние объекта _newLoader.SetDestinations(transferRecord.ParentComponent); if (transferRecord.ParentComponent is BaseComponent) { _calculator.ResetMath((BaseComponent)transferRecord.ParentComponent); } } } else { // Сохраняем запись transferRecord.IsDeleted = true; _newKeeper.Save(transferRecord); transferRecord.ParentComponent.TransferRecords.Remove(transferRecord); // Обновляем состояние объекта _newLoader.SetDestinations(transferRecord.ParentComponent); if (transferRecord.ParentComponent is BaseComponent) { _calculator.ResetMath((BaseComponent)transferRecord.ParentComponent); } } } else { throw new Exception("1000: Failed to specify tranfer record parent type"); } }
/// <summary> /// Добавляет элементы в ListView /// </summary> /// <param name="itemsArray"></param> //protected override void AddItems(IBaseCoreObject[] itemsArray) //{ // ColumnHeader ch = ColumnHeaderList.FirstOrDefault(h => h.Text == "Performances"); // if (ch == null) // { // base.AddItems(itemsArray); // return; // } // if(itemsArray == null || itemsArray.Length == 0) // { // ch.Width = 0; // base.AddItems(itemsArray); // return; // } // ch.Width = itemsArray.OfType<IDirective>() // .Count(d => d.NextPerformances != null && d.NextPerformances.Count > 1) > 0 ? 100 : 0; // base.AddItems(itemsArray); //} #endregion #region protected override void SetGroupsToItems(int columnIndex) /// <summary> /// Возвращает название группы в списке агрегатов текущего склада, согласно тому, какого типа элемент /// </summary> //protected override void SetGroupsToItems(int columnIndex) // { // itemsListView.Groups.Clear(); // itemsListView.Groups.AddRange(new[] // { // new ListViewGroup("Engines", "Engines"), // new ListViewGroup("APU's", "APU's"), // new ListViewGroup("Landing Gears", "Landing Gears"), // }); // foreach (ListViewItem item in ListViewItemList.OrderBy(x => x.Text)) // { // String temp = ""; // if (!(item.Tag is IDirective)) continue; // IDirective parent = (IDirective)item.Tag; // #region Группировка по типу задачи // if (parent is ComponentDirective) // parent = ((ComponentDirective) parent).ParentComponent; // if (parent is BaseComponent) // { // if (((BaseComponent)parent).BaseComponentType == BaseComponentType.Engine) // temp = "Engines"; // else if (((BaseComponent)parent).BaseComponentType == BaseComponentType.Apu) // temp = "APU's"; // else if (((BaseComponent)parent).BaseComponentType == BaseComponentType.LandingGear) // temp = "Landing Gears"; // item.Group = itemsListView.Groups[temp]; // } // else if (parent is Component) // { // Component component = (Component)parent; // if (component.ParentBaseComponent != null) // { // BaseComponent baseComponent = component.ParentBaseComponent;//TODO:(Evgenii Babak) заменить на использование ComponentCore //temp = baseComponent + " Components"; // } // else // { // AtaChapter ata = null; //if (component.Product != null) //{ // ata = component.Product.ATAChapter; //} // else ata = component.ATAChapter; // temp = ata.ShortName + " " + ata.FullName; // } // itemsListView.Groups.Add(temp, temp); // item.Group = itemsListView.Groups[temp]; // } // #endregion // } //} #endregion #region protected override ListViewItem.ListViewSubItem[] GetListViewSubItems(IBaseCoreObject item) protected override List <CustomCell> GetListViewSubItems(IBaseEntityObject item) { var subItems = new List <CustomCell>(); DateTime? approx = null; AtaChapter ata; Store store = null; string maintenanceTypeString = ""; DateTime transferDate = DateTimeExtend.GetCASMinDateTime(); bool isPool = false, IsDangerous = false; Lifelength firstPerformance = Lifelength.Null, lastPerformance = Lifelength.Null, remains = null, next = null, warranty = Lifelength.Null, repeatInterval = Lifelength.Null; string partNumber = "", description = "", altPartNumber = "", name = "", standart = "", serialNumber = "", refference = "", effectivity = "", code = "", id = "", classString = "", batchNumber = "", idNumber = "", supplier = ""; string status = "", location = "", facility = "", lastPerformanceString = "", kitRequieredString = "", remarks = "", hiddenRemarks = "", workType = "", timesString, quantityString = "", currentString = "", shouldBeOnStockString = "", from = "", quantityInString = "", currency = "", author = ""; double manHours = 0, unitPrice = 0, totalPrice = 0, shipPrice = 0, subTotal = 0, tax1 = 0, tax2 = 0, tax3 = 0, total = 0, quantity = 0, current = 0, quantityIn = 0, shouldBeOnStock = 0, needWpQuantity = 0, reserve = 0; int times, kitCount = 0; var position = ComponentStorePosition.UNK.ToString(); IDirective parent; if (item is NextPerformance) { NextPerformance np = (NextPerformance)item; parent = np.Parent; int index = np.Parent.NextPerformances.IndexOf(np); timesString = index == 0 ? np.Parent.TimesToString : "#" + (index + 1); times = index == 0 ? np.Parent.Times : index + 1; } else { parent = item as IDirective; if (parent == null) { return(subItems); } timesString = parent.TimesToString; times = parent.Times; } if (parent is Component) { Component componentItem = (Component)parent; id = componentItem.ItemId.ToString(); store = GlobalObjects.StoreCore.GetStoreById(componentItem.ParentStoreId); if (store == null) { MessageBox.Show("qwe"); } author = GlobalObjects.CasEnvironment.GetCorrector(componentItem); approx = componentItem.NextPerformanceDate; next = componentItem.NextPerformanceSource; remains = componentItem.Remains; name = componentItem.Product?.Name; ata = componentItem.Product?.ATAChapter ?? componentItem.ATAChapter; partNumber = componentItem.Product?.PartNumber ?? componentItem.PartNumber; altPartNumber = componentItem.Product?.AltPartNumber ?? componentItem.ALTPartNumber; standart = componentItem.Product?.Standart?.ToString() ?? componentItem.Standart?.ToString(); refference = componentItem.Product?.Reference; effectivity = componentItem.Product?.IsEffectivity; description = componentItem.Description; serialNumber = componentItem.SerialNumber; code = componentItem.Product != null ? componentItem.Product.Code :componentItem.Code; classString = componentItem.GoodsClass.ToString(); batchNumber = componentItem.BatchNumber; idNumber = componentItem.IdNumber; position = componentItem.TransferRecords.GetLast()?.State?.ToString(); status = componentItem.ComponentStatus.ToString(); location = componentItem.Location.ToString(); facility = componentItem.Location.LocationsType?.ToString() ?? LocationsType.Unknown.ToString(); maintenanceTypeString = componentItem.GoodsClass.IsNodeOrSubNodeOf(GoodsClass.ComponentsAndParts) ? componentItem.MaintenanceControlProcess.ShortName : componentItem.LifeLimit.IsNullOrZero() ? "" : MaintenanceControlProcess.HT.ShortName; transferDate = componentItem.TransferRecords.GetLast().TransferDate; firstPerformance = componentItem.LifeLimit; warranty = componentItem.Warranty; kitRequieredString = componentItem.Kits.Count > 0 ? componentItem.Kits.Count + " kits" : ""; kitCount = componentItem.Kits.Count; bool isComponent = componentItem.GoodsClass.IsNodeOrSubNodeOf(new IDictionaryTreeItem[] { GoodsClass.ComponentsAndParts, GoodsClass.ProductionAuxiliaryEquipment, }); quantity = isComponent && componentItem.ItemId > 0 ? 1 : componentItem.Quantity; quantityString = quantity.ToString(); quantityIn = isComponent && componentItem.ItemId > 0 ? 1 : componentItem.QuantityIn; quantityInString = $"{quantityIn:0.##}" + (componentItem.Measure != null ? " " + componentItem.Measure + "(s)" : "") + componentItem.Packing; needWpQuantity = Math.Round(componentItem.NeedWpQuantity, 2); reserve = quantity - needWpQuantity; shouldBeOnStock = componentItem.ShouldBeOnStock; shouldBeOnStockString = componentItem.ShouldBeOnStock > 0 ? "Yes" : "No"; manHours = componentItem.ManHours; remarks = componentItem.Remarks; hiddenRemarks = componentItem.HiddenRemarks; isPool = componentItem.IsPOOL; IsDangerous = componentItem.IsDangerous; supplier = componentItem.FromSupplier.ToString(); if (componentItem.ProductCosts.Count > 0) { var productost = componentItem.ProductCosts.FirstOrDefault(); unitPrice = productost.UnitPrice; totalPrice = productost.TotalPrice; shipPrice = productost.ShipPrice; subTotal = productost.SubTotal; tax1 = productost.Tax; tax2 = productost.Tax1; tax3 = productost.Tax2; total = productost.Total; currency = productost.Currency.ToString(); } TransferRecord tr = componentItem.TransferRecords.GetLast(); if (tr.FromAircraftId == 0 && tr.FromBaseComponentId == 0 && tr.FromStoreId == 0 && tr.FromSupplierId == 0 && tr.FromSpecialistId == 0) { from = componentItem.Suppliers.ToString(); } else { from = DestinationHelper.FromObjectString(tr); } } else if (parent is ComponentDirective) { ComponentDirective dd = (ComponentDirective)parent; if (dd.Threshold.FirstPerformanceSinceNew != null && !dd.Threshold.FirstPerformanceSinceNew.IsNullOrZero()) { firstPerformance = dd.Threshold.FirstPerformanceSinceNew; } if (dd.LastPerformance != null) { lastPerformanceString = SmartCore.Auxiliary.Convert.GetDateFormat(dd.LastPerformance.RecordDate) + " " + dd.LastPerformance.OnLifelength; lastPerformance = dd.LastPerformance.OnLifelength; } if (dd.Threshold.RepeatInterval != null && !dd.Threshold.RepeatInterval.IsNullOrZero()) { repeatInterval = dd.Threshold.RepeatInterval; } store = GlobalObjects.StoreCore.GetStoreById(dd.ParentComponent.ParentStoreId); if (store == null) { MessageBox.Show("qwe"); } author = GlobalObjects.CasEnvironment.GetCorrector(dd); approx = dd.NextPerformanceDate; next = dd.NextPerformanceSource; remains = dd.Remains; ata = dd.ParentComponent.Product?.ATAChapter ?? dd.ParentComponent.ATAChapter; maintenanceTypeString = dd.ParentComponent.MaintenanceControlProcess.ShortName; warranty = dd.Threshold.Warranty; kitRequieredString = dd.Kits.Count > 0 ? dd.Kits.Count + " kits" : ""; kitCount = dd.Kits.Count; manHours = dd.ManHours; remarks = dd.Remarks; hiddenRemarks = dd.HiddenRemarks; workType = dd.DirectiveType.ToString(); position = " " + dd.ParentComponent.TransferRecords.GetLast()?.State?.ToString(); isPool = dd.IsPOOL; IsDangerous = dd.IsDangerous; partNumber = " " + (dd.ParentComponent.Product?.PartNumber ?? dd.ParentComponent.PartNumber); altPartNumber = " " + (dd.ParentComponent.Product?.AltPartNumber ?? dd.ParentComponent.ALTPartNumber); standart = dd.ParentComponent.Product?.Standart?.ToString() ?? dd.ParentComponent.Standart?.ToString(); name = " " + dd.ParentComponent.Product?.Name; description = " " + dd.ParentComponent.Description; serialNumber = " " + dd.ParentComponent.SerialNumber; classString = dd.ParentComponent.GoodsClass.ToString(); } else { ata = (AtaChapter)GlobalObjects.CasEnvironment.GetDictionary <AtaChapter>().GetItemById(21); } subItems.Add(CreateRow(store?.ToString() ?? "N/A", store.ToString())); subItems.Add(CreateRow(id, id)); subItems.Add(CreateRow(ata.ToString(), ata)); subItems.Add(CreateRow(refference, refference)); subItems.Add(CreateRow(partNumber, partNumber)); subItems.Add(CreateRow(altPartNumber, altPartNumber)); subItems.Add(CreateRow(standart, standart)); subItems.Add(CreateRow(name, name)); subItems.Add(CreateRow(description, description)); subItems.Add(CreateRow(serialNumber, serialNumber)); subItems.Add(CreateRow(classString, classString)); subItems.Add(CreateRow(batchNumber, batchNumber)); subItems.Add(CreateRow(idNumber, idNumber)); subItems.Add(CreateRow(position?.ToString().ToUpper(), position)); subItems.Add(CreateRow(status, status)); subItems.Add(CreateRow(location, location)); subItems.Add(CreateRow(facility, facility)); subItems.Add(CreateRow(from, from)); subItems.Add(CreateRow(transferDate > DateTimeExtend.GetCASMinDateTime() ? SmartCore.Auxiliary.Convert.GetDateFormat(transferDate) : "", transferDate)); subItems.Add(CreateRow(workType, Tag = workType)); subItems.Add(CreateRow(needWpQuantity.ToString(), needWpQuantity)); subItems.Add(CreateRow(reserve.ToString(), reserve)); subItems.Add(CreateRow(quantityString, quantity)); subItems.Add(CreateRow(shouldBeOnStockString, shouldBeOnStock)); subItems.Add(CreateRow(quantityInString, quantityIn)); subItems.Add(CreateRow(unitPrice.ToString(), unitPrice)); subItems.Add(CreateRow(totalPrice.ToString(), totalPrice)); subItems.Add(CreateRow(shipPrice.ToString(), shipPrice)); subItems.Add(CreateRow(subTotal.ToString(), subTotal)); subItems.Add(CreateRow(tax1.ToString(), tax1)); subItems.Add(CreateRow(tax2.ToString(), tax2)); subItems.Add(CreateRow(tax3.ToString(), tax3)); subItems.Add(CreateRow(total.ToString(), total)); subItems.Add(CreateRow(currency, currency)); subItems.Add(CreateRow(supplier, supplier)); subItems.Add(CreateRow(code, code)); subItems.Add(CreateRow(remarks, remarks)); subItems.Add(CreateRow(effectivity, effectivity)); subItems.Add(CreateRow(isPool ? "Yes" : "No", isPool)); subItems.Add(CreateRow(IsDangerous ? "Yes" : "No", IsDangerous)); subItems.Add(CreateRow(maintenanceTypeString, maintenanceTypeString)); subItems.Add(CreateRow(manHours.ToString(), manHours)); subItems.Add(CreateRow(firstPerformance.ToString(), firstPerformance)); subItems.Add(CreateRow(repeatInterval.ToString(), repeatInterval)); subItems.Add(CreateRow(timesString, times)); subItems.Add(CreateRow(approx != null ? SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)approx) + " " + next : next != null && !next.IsNullOrZero() ? next.ToString() : "", approx == null ? DateTimeExtend.GetCASMinDateTime() : (DateTime)approx)); subItems.Add(CreateRow(remains != null && !remains.IsNullOrZero() ? remains.ToString() : "", remains ?? Lifelength.Null)); subItems.Add(CreateRow(lastPerformanceString, lastPerformance)); subItems.Add(CreateRow(warranty.ToString(), warranty)); subItems.Add(CreateRow(kitRequieredString, kitCount)); subItems.Add(CreateRow(hiddenRemarks, hiddenRemarks)); subItems.Add(CreateRow(author, author)); return(subItems); }
/// <summary> /// Выставляет родителей для агрегата /// </summary> /// <param name="component"></param> /// <returns></returns> public void SetDestinations(General.Accessory.Component component) { TransferRecord lastTransfer = component.TransferRecords.GetLast(); if (lastTransfer == null) { return; } //throw new Exception($"1513: Component {component.ItemId} has no transfer records"); // if (lastTransfer.DestinationObjectType == SmartCoreType.Store) { var store = _casEnvironment.Stores.GetItemById(lastTransfer.DestinationObjectId); if (store == null) { // перемещение вникуда ! throw new Exception($"1552: Destination object ID:{lastTransfer.DestinationObjectId} was not found"); } component.ParentStoreId = store.ItemId; } else if (lastTransfer.DestinationObjectType == SmartCoreType.Operator) { var op = _casEnvironment.Operators.GetItemById(lastTransfer.DestinationObjectId); if (op == null) { // перемещение вникуда ! throw new Exception($"1552: Destination object ID:{lastTransfer.DestinationObjectId} was not found"); } component.ParentOperator = op; } else if (lastTransfer.DestinationObjectType == SmartCoreType.BaseComponent) { var baseComponent = _casEnvironment.BaseComponents.GetItemById(lastTransfer.DestinationObjectId); //TODO(Evgenii Babak): использовать ComponentCore if (baseComponent != null) { component.ParentBaseComponent = baseComponent; if (baseComponent.LastDestinationObjectType == SmartCoreType.Aircraft) { component.ParentAircraftId = baseComponent.LastDestinationObjectId; } else if (baseComponent.LastDestinationObjectType == SmartCoreType.Store) { component.ParentStoreId = baseComponent.LastDestinationObjectId; } } } else if (lastTransfer.DestinationObjectType == SmartCoreType.Aircraft) { component.ParentAircraftId = lastTransfer.DestinationObjectId; } else if (lastTransfer.DestinationObjectType == SmartCoreType.Supplier) { component.ParentSupplierId = lastTransfer.DestinationObjectId; } else if (lastTransfer.DestinationObjectType == SmartCoreType.Employee) { component.ParentSpecialistId = lastTransfer.DestinationObjectId; } if (component.ParentStoreId <= 0 && component.ParentAircraftId <= 0 && component.ParentSupplierId <= 0 && component.ParentSpecialistId <= 0 && component.ParentOperator == null) { throw new Exception("1453: Failed to specify parent object to detail"); } }
private void UpdateInformation() { textBoxSerialNumber.Text = "S/N " + currentDetail.SerialNumber; textBoxPartNumber.Text = "P/N " + currentDetail.PartNumber; TransferRecord preRecord = currentDetail.GetPreLastTransferRecord(); if (preRecord != null) { if (preRecord.TransferContainer is Aircraft || preRecord.TransferContainer is BaseDetail) { Aircraft aircraft; Store store = null; if (preRecord.TransferContainer is Aircraft) { aircraft = (Aircraft)preRecord.TransferContainer; } else { BaseDetail baseDetail = (BaseDetail)preRecord.TransferContainer; aircraft = baseDetail.ParentAircraft; if (aircraft.Type == AircraftType.Store) { store = baseDetail.Store; } } if (store != null) { textBoxFrom.Text = store.Name; labelFromAdditional.Text = "Location:"; textBoxFromAdditional.Text = preRecord.Position; } else { textBoxFrom.Text = aircraft.RegistrationNumber; labelFromAdditional.Text = "Position:"; textBoxFromAdditional.Text = preRecord.Position; } } } textBoxDate.Text = currentRecord.RecordDate.ToString(new GlobalTermsProvider()["DateFormat"].ToString()); if (currentRecord.TransferContainer is Aircraft || currentRecord.TransferContainer is BaseDetail) { Aircraft aircraft; Store store = null; if (currentRecord.TransferContainer is Aircraft) { aircraft = (Aircraft)currentRecord.TransferContainer; } else { BaseDetail baseDetail = (BaseDetail)currentRecord.TransferContainer; aircraft = baseDetail.ParentAircraft; if (aircraft.Type == AircraftType.Store) { store = baseDetail.Store; } } if (store != null) { textBoxTo.Text = store.Name; labelToAdditional.Text = "Location:"; textBoxToAdditional.Text = currentRecord.Position; } else { textBoxTo.Text = aircraft.RegistrationNumber; labelToAdditional.Text = "Position:"; textBoxToAdditional.Text = currentRecord.Position; } } textBoxRemarks.Text = currentRecord.Description; }
private void SetValues(WorkPackageClosingDataGridViewRow row, Audit wp, AbstractPerformanceRecord apr) { row.WorkPackage = wp; row.Record = apr; if (apr != null) { row.ClosingItem = apr.Parent; } if (row.ClosingItem == null || apr == null) { return; } SetLabelsAndText(row); if (apr is DirectiveRecord || apr is MaintenanceCheckRecord) { row.Cells[ColumnClosed.Index].Value = true; //Lifelength performanceSource = apr.OnLifelength; //row.Cells[ColumnHours.Index].Value = performanceSource.Hours != null ? performanceSource.Hours.ToString() : "n/a"; //row.Cells[ColumnCycles.Index].Value = performanceSource.Cycles != null ? performanceSource.Cycles.ToString() : "n/a"; //row.Cells[ColumnDays.Index].Value = performanceSource.Days != null ? performanceSource.Days.ToString() : "n/a"; row.Cells[ColumnDate.Index].Value = apr.RecordDate; row.PrevPerfDate = apr.PrevPerformanceDate; row.NextPerfDate = apr.NextPerformanceDate; } else if (apr is TransferRecord) { TransferRecord tr = (TransferRecord)apr; if (tr.ItemId > 0) { //если запись о перемещении имеет itemID > 0 //и она не подтвержддена стороной получателя, то ее можно редактировать и удалять //если подтверждена, то редактировать и удалять ее нельзя if (tr.DODR) { row.Cells[ColumnHours.Index].ReadOnly = false; row.PrevPerfDate = tr.PrevPerformanceDate; row.NextPerfDate = tr.TransferDate; } else { row.Cells[ColumnHours.Index].ReadOnly = true; row.PrevPerfDate = tr.PrevPerformanceDate; row.NextPerfDate = tr.NextPerformanceDate; } row.Cells[ColumnCycles.Index].Value = "Transfer to: " + GetDestination(tr); row.Cells[ColumnDate.Index].Value = tr.StartTransferDate; } else { row.Cells[ColumnCycles.Index].Value = "Transfer to: "; row.PrevPerfDate = apr.PrevPerformanceDate; row.NextPerfDate = apr.NextPerformanceDate; } row.Cells[ColumnClosed.Index].Value = true; } DataGridViewCalendarCell cc = row.Cells[ColumnDate.Index] as DataGridViewCalendarCell; if (cc != null) { if (row.PrevPerfDate != null) { cc.MinDate = (DateTime)row.PrevPerfDate; } else { cc.MinDate = DateTimeExtend.GetCASMinDateTime(); } if (row.NextPerfDate != null) { cc.MaxDate = (DateTime)row.NextPerfDate; } else { cc.MaxDate = DateTime.Now; } } row.MinPerfSource = apr.PrevPerformanceSource.IsNullOrZero() ? Lifelength.Zero : apr.PrevPerformanceSource; row.MaxPerfSource = apr.NextPerformanceSource.IsNullOrZero() //TODO:(Evgenii Babak) пересмотреть подход, наработка считается на конец дня, а в метод передаем DateTime.Now(может быть и концом дня) ? GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnEndOfDay(row.ClosingItem.LifeLengthParent, DateTime.Now) : apr.NextPerformanceSource; }
private void ButtonAdd_Click(object sender, EventArgs e) { if (listViewTransferedDetails.SelectedItems.Count == 0) { return; } ComponentCollection installedComponents = new ComponentCollection(); ComponentCollection removedComponents = new ComponentCollection(_removedComponents.ToArray()); List <ReplaceComponentFormItem> replaceDetailFormItems; foreach (ListViewItem item in listViewTransferedDetails.SelectedItems) { if (item.Group == listViewTransferedDetails.Groups[1]) { Component component = (Component)item.Tag; installedComponents.Add(component); //detail.TransferRecords.Last.DODR = true; ////увеличение необходимого кол-ва деталей родительского компонента ////сохранение родительского компонента //detail.ParentBaseDetail.ComponentCount++; //GlobalObjects.CasEnvironment.Keeper.Save(detail.ParentBaseDetail); //GlobalObjects.CasEnvironment.Keeper.Save(detail.TransferRecords.Last); //_installedDetails.Remove(detail); //TransferRecord record = _installedTransfers.GetTransferRecordByDetailID(detail.DetailId); //if (record != null) _installedTransfers.Remove(record); } } if (installedComponents.Count == 0) { return; } replaceDetailFormItems = new List <ReplaceComponentFormItem>(); foreach (Component item in installedComponents) { var newItem = new ReplaceComponentFormItem(item, null, _parentType); replaceDetailFormItems.Add(newItem); if (item is BaseComponent) { newItem.comboBoxReplaceByDetail.Items.AddRange(_waitremovedConfirmComponents.Where(i => i is BaseComponent).ToArray()); } if (item is Component) { newItem.comboBoxReplaceByDetail.Items.AddRange(_waitremovedConfirmComponents.Where(i => i is Component).ToArray()); } if (removedComponents.Count == 0) { newItem.UpdateInformation(true); continue; } foreach (Component removedItem in removedComponents) { //проверка по сходству ID //проверка по сходству названия if (removedItem.ItemId == item.ItemId || removedItem.Description.ToUpper() == item.Description.ToUpper()) { //Если ID идентичны, то эта деталь сначала была перемещена куда-то, //а потом обратно на самолет //если название идентично, значит эта могла быть направлена на самолет //для замены снятой newItem.ReplacedByComponent = removedItem; newItem.ReplacedByDetailTransfer = _removedTransfers.GetRecordByComponentId(removedItem.ItemId); //удаление элемента из коллекции, что бы он не попал в результат дважды removedComponents.Remove(removedItem); break; } } newItem.UpdateInformation(true); } var form = new ReplaceComponentForm(_installedComponents, _removedComponents, replaceDetailFormItems.ToArray(), _parentType); form.UpdateLabels(true); TopMost = false; //что бы данное онко не перекрывало окно диалога form.ShowDialog(); TopMost = true; //return; //Если изменения не были произведены, то просто возвращаемся из данной функции if (form.DialogResult == DialogResult.Cancel) { return; } //иначе производится замена/перемещение компонентов var replacedItems = new List <ReplaceComponentFormItem>(form.GetReplacedItems()); foreach (ReplaceComponentFormItem replacedItem in replacedItems) { if (!replacedItem.ConfirmTransfer) { continue; } if (replacedItem.ParentComponent != null) { if (replacedItem.ParentComponent.IsBaseComponent) { BaseComponent bd = GlobalObjects.CasEnvironment.BaseComponents. GetItemById(replacedItem.ParentComponent.ItemId); ActualStateRecord actual = bd.ActualStateRecords[bd.TransferRecords.GetLast().StartTransferDate]; if (actual != null) { actual.RecordDate = replacedItem.ConfirmDate; //TODO:(Evgenii Babak) пересмотреть подход, наработка считается на начало дня, а в метод передаем DateTime.Now(может быть и концом дня) actual.OnLifelength = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnStartOfDay(bd, replacedItem.ConfirmDate); GlobalObjects.NewKeeper.Save(actual); } else { actual = new ActualStateRecord { ComponentId = bd.ItemId, RecordDate = DateTime.Now, //TODO:(Evgenii Babak) пересмотреть подход, наработка считается на начало дня, а в метод передаем DateTime.Now(может быть и концом дня) OnLifelength = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnStartOfDay(bd, replacedItem.ConfirmDate) }; GlobalObjects.ComponentCore.RegisterActualState(bd, actual); } bd.TransferRecords.GetLast().DODR = true; bd.TransferRecords.GetLast().PreConfirmTransfer = true; bd.TransferRecords.GetLast().TransferDate = replacedItem.ConfirmDate; GlobalObjects.NewKeeper.Save(bd.TransferRecords.GetLast()); } else { ActualStateRecord actual = replacedItem.ParentComponent.ActualStateRecords[replacedItem.ParentComponent.TransferRecords.GetLast().StartTransferDate]; if (actual != null) { actual.RecordDate = replacedItem.ConfirmDate; //TODO:(Evgenii Babak) пересмотреть подход, наработка считается на начало дня, а в метод передаем DateTime.Now(может быть и началом дня) actual.OnLifelength = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnEndOfDay(replacedItem.ParentComponent, DateTime.Now); GlobalObjects.NewKeeper.Save(actual); } else { actual = new ActualStateRecord { ComponentId = replacedItem.ParentComponent.ItemId, RecordDate = DateTime.Now, //TODO:(Evgenii Babak) пересмотреть подход, наработка считается на начало дня, а в метод передаем DateTime.Now(может быть и началом дня) OnLifelength = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnEndOfDay(replacedItem.ParentComponent, DateTime.Now) }; GlobalObjects.ComponentCore.RegisterActualState(replacedItem.ParentComponent, actual); } if (replacedItem.ReplacedByComponent != null && replacedItem.ReplacedByComponent.ComponentDirectives.Count > 0) { foreach (var directive in replacedItem.ReplacedByComponent.ComponentDirectives) { var newDirective = directive.GetCopyUnsaved(); newDirective.ComponentId = replacedItem.ParentComponent.ItemId; newDirective.ParentComponent = replacedItem.ParentComponent; GlobalObjects.NewKeeper.Save(newDirective); } } replacedItem.ParentComponent.TransferRecords.GetLast().DODR = true; replacedItem.ParentComponent.TransferRecords.GetLast().PreConfirmTransfer = true; replacedItem.ParentComponent.TransferRecords.GetLast().TransferDate = replacedItem.ConfirmDate; //увеличение необходимого кол-ва деталей родительского компонента //сохранение родительского компонента if (replacedItem.ParentComponent.ParentBaseComponent != null) { replacedItem.ParentComponent.ParentBaseComponent.ComponentCount++; GlobalObjects.ComponentCore.Save(replacedItem.ParentComponent.ParentBaseComponent);//TODO:(Evgenii Babak) заменить на использование ComponentCore } GlobalObjects.NewKeeper.Save(replacedItem.ParentComponent.TransferRecords.GetLast()); } _installedComponents.Remove(replacedItem.ParentComponent); TransferRecord record = _installedTransfers.GetRecordByComponentId(replacedItem.ParentComponent.ItemId); if (record != null) { _installedTransfers.Remove(record); if (replacedItem.ReplacedByComponent != null) { record.ReplaceComponentId = replacedItem.ReplacedByComponent.ItemId; record.IsReplaceComponentRemoved = true; GlobalObjects.NewKeeper.Save(record); } } } if (replacedItem.ReplacedByComponent != null) { TransferRecord record = _removedTransfers.GetRecordByComponentId(replacedItem.ReplacedByComponent.ItemId); if (record != null) { _removedTransfers.Remove(record); record.PODR = true; GlobalObjects.NewKeeper.Save(record); BaseComponent from = GlobalObjects.ComponentCore.GetBaseComponentById(record.FromBaseComponentId); //уменьшение необходимого кол-ва деталей родительского компонента //сохранение родительского компонента if (from != null) { from.ComponentCount--; GlobalObjects.ComponentCore.Save(from); } _removedComponents.Remove(replacedItem.ReplacedByComponent); } } } //создание события ButtonAddClick InvokeButtonAddClick(); UpdateInformation(); }
private void ButtonDelete_Click(object sender, EventArgs e) { if (listViewTransferedDetails.SelectedItems.Count == 0) { return; } ComponentCollection removedComponents = new ComponentCollection(); ComponentCollection installedComponents = new ComponentCollection(_installedComponents.ToArray()); List <ReplaceComponentFormItem> replaceDetailFormItems; foreach (ListViewItem item in listViewTransferedDetails.SelectedItems) { if (item.Group == listViewTransferedDetails.Groups[0]) { Component component = (Component)item.Tag; removedComponents.Add(component); } } if (removedComponents.Count == 0) { return; } replaceDetailFormItems = new List <ReplaceComponentFormItem>(); foreach (Component item in removedComponents) { var newItem = new ReplaceComponentFormItem(item, null, _removedTransfers.GetRecordByComponentId(item.ItemId), null, _parentType); replaceDetailFormItems.Add(newItem); if (installedComponents.Count == 0) { newItem.UpdateInformation(false); continue; } foreach (Component installedItem in installedComponents) { //проверка по сходству ID //проверка по сходству названия if (installedItem.ItemId == item.ItemId || installedItem.Description.ToUpper() == item.Description.ToUpper()) { //Если ID идентичны, то эта деталь сначала была перемещена куда-то, //а потом обратно на самолет //если название идентично, значит эта могла быть направлена на самолет //для замены снятой newItem.ReplacedByComponent = installedItem; newItem.ReplacedByDetailTransfer = installedItem.TransferRecords.GetLast(); //удаление элемента из коллекции, что бы он не попал в результат дважды installedComponents.Remove(installedItem); break; } } newItem.UpdateInformation(false); } var form = new ReplaceComponentForm(_removedComponents, _installedComponents, replaceDetailFormItems.ToArray(), _parentType); form.UpdateLabels(false); TopMost = false; //что бы данное онко не перекрывало окно диалога form.ShowDialog(); TopMost = true; //Если изменения не были произведены, то просто возвращаемся из данной функции if (form.DialogResult == DialogResult.Cancel) { return; } //иначе производится замена/перемещение компонентов List <ReplaceComponentFormItem> replacedItems = new List <ReplaceComponentFormItem>(form.GetReplacedItems()); foreach (ReplaceComponentFormItem replacedItem in replacedItems) { if (replacedItem.ParentComponent != null) { TransferRecord record = _removedTransfers.GetRecordByComponentId(replacedItem.ParentComponent.ItemId); record.PODR = true; if (replacedItem.ReplacedByComponent != null) { record.ReplaceComponentId = replacedItem.ReplacedByComponent.ItemId; record.IsReplaceComponentRemoved = false; } GlobalObjects.NewKeeper.Save(record); BaseComponent from = GlobalObjects.ComponentCore.GetBaseComponentById(record.FromBaseComponentId); //уменьшение необходимого кол-ва деталей родительского компонента //сохранение родительского компонента if (from != null) { from.ComponentCount--; GlobalObjects.ComponentCore.Save(from); } _removedComponents.Remove(replacedItem.ParentComponent); _removedTransfers.Remove(record); } if (replacedItem.ReplacedByComponent != null) { ActualStateRecord actual = replacedItem.ReplacedByComponent.ActualStateRecords[replacedItem.ReplacedByComponent.TransferRecords.GetLast().StartTransferDate]; actual.RecordDate = replacedItem.ReplacedByDate; actual.OnLifelength = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnEndOfDay(replacedItem.ReplacedByComponent, DateTime.Now);//TODO:(Evgenii Babak) пересмотреть подход, наработка считается на начало дня, а в метод передаем DateTime.Now(может быть и началом дня) GlobalObjects.NewKeeper.Save(actual); replacedItem.ReplacedByComponent.TransferRecords.GetLast().DODR = true; replacedItem.ReplacedByComponent.TransferRecords.GetLast().TransferDate = replacedItem.ReplacedByDate; //увеличение необходимого кол-ва деталей родительского компонента //сохранение родительского компонента if (replacedItem.ReplacedByComponent.ParentBaseComponent != null) { replacedItem.ReplacedByComponent.ParentBaseComponent.ComponentCount++; GlobalObjects.ComponentCore.Save(replacedItem.ReplacedByComponent.ParentBaseComponent); } GlobalObjects.NewKeeper.Save(replacedItem.ReplacedByComponent.TransferRecords.GetLast()); _installedComponents.Remove(replacedItem.ReplacedByComponent); TransferRecord record = _installedTransfers.GetRecordByComponentId(replacedItem.ReplacedByComponent.ItemId); if (record != null) { _installedTransfers.Remove(record); } } } InvokeButtonDeleteClick(); UpdateInformation(); }
/// <summary> /// Заполняет поля /// </summary> /// <param name="row"></param> /// <param name="item"></param> private static void Fill(DataRow row, TransferRecord item) { BaseQueries.Fill(row, item); }
public void UploadFile(TransferRecord record) { var defaultLocalPath = _cfg.LocalPath; var defaultRemotePath = _cfg.RemotePath; TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Automatic; //switch (_cfg.ProtocolType) //{ // case FtpType.SFTP: // //恢復續傳 // transferOptions.ResumeSupport.State = TransferResumeSupportState.On; // break; // case FtpType.FTP: // //no way... // break; //} //傳輸速度(KB/s) if (!(_cfg.SpeedLimit == 0)) { transferOptions.SpeedLimit = _cfg.SpeedLimit; } Stopwatch sw = new Stopwatch(); string filePath = Path.Combine(defaultLocalPath, record.FileName); string remoteFilePath = Path.Combine(defaultRemotePath, record.FileName); // 嘗試次數 record.ProcessTimes++; record.LocalFilePath = filePath; record.RemoteFilePath = remoteFilePath; record.Status = "20"; Console.WriteLine($"檔名:{record.FileName}"); Console.WriteLine($"本機路徑:{record.LocalFilePath}"); Console.WriteLine($"遠端路徑:{record.RemoteFilePath}"); log.Info($"檔名:{record.FileName}"); log.Info($"本機路徑:{record.LocalFilePath}"); log.Info($"遠端路徑:{record.RemoteFilePath}"); //file exist or not if (File.Exists(filePath)) { //上傳前驗證碼檢查 record.GetFileSHA256(); if (!record.ComparisonHash()) { record.Done = false; record.ErrorCode = "SHA"; record.Status = "21"; record.ErrorMessage = "檔案上傳失敗,訊息:檔案SHA256驗證碼失敗"; log.Error($"[失敗]{record.ErrorMessage}"); Console.WriteLine($"[失敗]{record.ErrorMessage}"); return; } log.Info("開始上傳"); Console.WriteLine("開始上傳"); sw.Start(); var transferResult = _session.PutFiles(filePath, defaultRemotePath, false, transferOptions); sw.Stop(); record.TransferElapsed = sw.Elapsed; //Throw the first failure in the list transferResult.Check(); //檔案長度(位元組) record.TransferFileSize = _session.GetFileInfo(remoteFilePath).Length; record.CalAveRate(); log.Info($"檔案大小(位元組):{record.TransferFileSize.ToString("#,#")}"); log.Info($"均速(kB/s):{record.TransferSpeed.ToString("#,#")}"); Console.WriteLine($"檔案大小(位元組):{record.TransferFileSize.ToString("#,#")}"); Console.WriteLine($"均速(kB/s):{record.TransferSpeed.ToString("#,#")}"); if (transferResult.IsSuccess) { record.Done = true; record.Status = "30"; log.Info("[完成]"); Console.WriteLine("[完成]"); } else { record.Done = false; record.ErrorCode = "UpLoad"; record.Status = "21"; var error = transferResult.Transfers.FirstOrDefault(); if (error != null) { record.ErrorMessage = $"檔案上傳失敗,訊息:{ error.Error.Message}"; log.Error($"[失敗]{record.ErrorMessage}"); Console.WriteLine($"[失敗]{record.ErrorMessage}"); } } } else { record.Done = false; record.Status = "21"; record.ErrorMessage = $"檔案上傳失敗,訊息:檔案不存在"; log.Error($"[失敗]{record.ErrorMessage}"); Console.WriteLine($"[失敗]{record.ErrorMessage}"); } }
/// <summary>下載</summary> /// <param name="record"></param> public void DownloadFile(TransferRecord record) { var defaultLocalPath = _cfg.LocalPath; var defaultRemotePath = _cfg.RemotePath; TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Automatic; //恢復續傳 transferOptions.OverwriteMode = OverwriteMode.Resume; //傳輸速度(kb/s) if (!(_cfg.SpeedLimit == 0)) { transferOptions.SpeedLimit = _cfg.SpeedLimit; } Stopwatch sw = new Stopwatch(); string filePath = Path.Combine(defaultRemotePath, record.FileName); string localFilePath = Path.Combine(defaultLocalPath, record.FileName); // 嘗試次數 record.ProcessTimes++; record.LocalFilePath = localFilePath; record.RemoteFilePath = filePath; record.Status = "40"; log.Info($"檔名:{record.FileName}"); log.Info($"本機路徑:{record.LocalFilePath}"); log.Info($"遠端路徑:{record.RemoteFilePath}"); if (_session.FileExists(filePath)) { //取得檔案長度(位元組) record.TransferFileSize = _session.GetFileInfo(filePath).Length; log.Info("開始下載"); sw.Start(); var transferResult = _session.GetFiles(filePath, defaultLocalPath, false, transferOptions); sw.Stop(); record.TransferElapsed = sw.Elapsed; /* * transferResult.IsSuccess:Is true, if .failures is empty collection * If there's a failure, the transferResult.Check() throws. */ transferResult.Check(); record.CalAveRate(); log.Info($"檔案大小(位元組):{record.TransferFileSize.ToString("#,#")}"); log.Info($"均速(kB/s):{record.TransferSpeed.ToString("#,#")}"); if (transferResult.IsSuccess) { //下載後驗證碼檢查 record.GetFileSHA256(); if (record.ComparisonHash()) { record.Done = true; record.Status = "50"; log.Info("[完成]"); } else { record.Done = false; record.ErrorCode = "SHA"; record.Status = "41"; record.ErrorMessage = $"檔案下載失敗,訊息:檔案SHA256驗證碼失敗"; log.Error($"[失敗]{record.ErrorMessage}"); if (File.Exists(localFilePath)) { File.Delete(localFilePath); } } } else { // 加入錯誤訊息 record.Done = false; record.ErrorCode = "DownLoad"; record.Status = "41"; var error = transferResult.Transfers.FirstOrDefault(); if (error != null) { record.ErrorMessage = $"檔案下載失敗,訊息:{ error.Error.Message}"; log.Error($"[失敗]{record.ErrorMessage}"); } } } else { record.Done = false; record.Status = "41"; record.ErrorMessage = $"檔案下載失敗,訊息:檔案不存在"; log.Error($"[失敗]{record.ErrorMessage}"); } }
private async Task GetTransferRecords() { TransferRecords = await TransferRecord.GetTransferRecords(); }
/// <summary> /// Сохранаяет данные текущего базового агрегата /// </summary> public void SaveData() { if (_currentBaseComponent == null) { return; } if (comboBoxEngineModel.SelectedItem != null && comboBoxEngineModel.SelectedItem != _currentBaseComponent?.Model) { var d = comboBoxEngineModel.SelectedItem as ComponentModel; _currentBaseComponent.Model = d; _currentBaseComponent.Description = d.FullName; } if (textBoxManufacturer.Text != _currentBaseComponent.Manufacturer) { _currentBaseComponent.Manufacturer = textBoxManufacturer.Text; } _currentBaseComponent.ManufactureDate = dateTimePickerManufactureDate.Value; if (textBoxSerialNumber.Text != _currentBaseComponent.SerialNumber) { _currentBaseComponent.SerialNumber = textBoxSerialNumber.Text; } _currentBaseComponent.PartNumber = textBoxPartialNumber.Text; _currentBaseComponent.LifeLimit = lifelengthViewerLifeLimit.Lifelength; _currentBaseComponent.Warranty = lifelengthViewerWarranty.Lifelength; if (_currentBaseComponent.ItemId > 0) { #region Актуальное состояние на стартовую дату ActualStateRecord actualStateRecord = _currentBaseComponent.ActualStateRecords[_currentBaseComponent.StartDate]; if (actualStateRecord == null) { actualStateRecord = new ActualStateRecord(); actualStateRecord.ComponentId = _currentBaseComponent.ItemId; } actualStateRecord.RecordDate = dateTimePickerStart.Value; actualStateRecord.OnLifelength = lifelengthViewerStart.Lifelength; GlobalObjects.ComponentCore.RegisterActualState(_currentBaseComponent, actualStateRecord); #endregion _currentBaseComponent.StartDate = dateTimePickerStart.Value; _currentBaseComponent.StartLifelength = lifelengthViewerStart.Lifelength; TransferRecord record = _currentBaseComponent.TransferRecords.GetLast(); ActualStateRecord actual = _currentBaseComponent.ActualStateRecords[record.TransferDate]; if (record.Position != textBoxPosition.Text || record.TransferDate != dateTimePickerInstallation.Value || (actual != null ? !actual.OnLifelength.IsEqual(lifelengthViewerInstallation.Lifelength) : !lifelengthViewerInstallation.Lifelength.IsNullOrZero())) { record.Position = textBoxPosition.Text; if (actual != null) { if (record.TransferDate >= dateTimePickerInstallation.Value) { //Дата установки изменена на более раннюю actual.OnLifelength = lifelengthViewerInstallation.Lifelength; actual.RecordDate = dateTimePickerInstallation.Value; GlobalObjects.NewKeeper.Save(actual); } else if (record.TransferDate < dateTimePickerInstallation.Value) { _currentBaseComponent.ActualStateRecords.Remove(actual); actual.OnLifelength = lifelengthViewerInstallation.Lifelength; actual.RecordDate = dateTimePickerInstallation.Value; GlobalObjects.ComponentCore.RegisterActualState(_currentBaseComponent, actual); } } else { actual = new ActualStateRecord(); actual.ComponentId = _currentBaseComponent.ItemId; actual.RecordDate = dateTimePickerInstallation.Value; actual.OnLifelength = lifelengthViewerInstallation.Lifelength; GlobalObjects.ComponentCore.RegisterActualState(_currentBaseComponent, actual); } record.TransferDate = dateTimePickerInstallation.Value; GlobalObjects.NewKeeper.Save(record); } //GlobalObjects.CasEnvironment.Keeper.Save(_currentBaseDetail.TransferRecords.GetLast()); GlobalObjects.ComponentCore.Save(_currentBaseComponent); } else { _currentBaseComponent.StartDate = dateTimePickerStart.Value; _currentBaseComponent.StartLifelength = lifelengthViewerStart.Lifelength; GlobalObjects.ComponentCore. AddBaseComponent(_currentBaseComponent, _currentAircraft, dateTimePickerInstallation.Value, textBoxPosition.Text, lifelengthViewerInstallation.Lifelength, true, false); ActualStateRecord actualStateRecord = _currentBaseComponent.ActualStateRecords[_currentBaseComponent.StartDate]; if (actualStateRecord == null) { actualStateRecord = new ActualStateRecord(); actualStateRecord.ComponentId = _currentBaseComponent.ItemId; } actualStateRecord.RecordDate = dateTimePickerInstallation.Value; actualStateRecord.OnLifelength = lifelengthViewerInstallation.Lifelength; GlobalObjects.ComponentCore.RegisterActualState(_currentBaseComponent, actualStateRecord); } }