public async Task HandleCreateDocument(CreateDocument command) { var aggregate = await _eventStreamReader.GetAggregate <DocumentAggregate>(command.StreamId); var resultedEvent = aggregate.CreateDocument(command); await aggregate.Save(resultedEvent); }
private void CreateWayBill(Car car, Logic.Static.Actions action, Fields fields) { CreateDocument excelWayBill = new CreateDocument(car); try { excelWayBill.CreateWaybill(dtpDate.Value, null); excelWayBill.AddRouteInWayBill(dtpDate.Value, fields); if (action == Logic.Static.Actions.Print) { excelWayBill.Print(); } else { excelWayBill.Show(); } } catch (NullReferenceException ex) { MessageBox.Show(ex.Message, "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Information); excelWayBill.Exit(); } if (car == list[index]) { LoadWayBillCurrent(); } }
private CreateDocument CreateWayBill(Car car, DateTime date, int idInvoice = 0) { CreateDocument waybill = new CreateDocument(car); Driver driver = null; if (idInvoice != 0) { InvoiceList invoiceList = InvoiceList.getInstance(); Invoice invoice = invoiceList.getItem(idInvoice); DriverList driverList = DriverList.getInstance(); driver = driverList.getItem(Convert.ToInt32(invoice.DriverToID)); } waybill.createWaybill(date, driver); try { if (_type == WayBillType.Day) { waybill.AddRouteInWayBill(date, Fields.All); } } catch (NullReferenceException ex) { MessageBox.Show(ex.Message, "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Information); waybill.Exit(); throw; } return(waybill); }
private ToolStripMenuItem CreatePrintAllTable() { ToolStripMenuItem item = CreateItem("Текущий справочник"); item.Click += delegate { MyPrinter myprinter = new MyPrinter(); string printerName = myprinter.GetDefaultPrinterName(); if (string.IsNullOrEmpty(printerName)) { MessageBox.Show("Принтер по умолчанию не найден", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string message = string.Concat("Вывести справочник \"", _mainStatus.ToString(), "\" на печать на принтер ", printerName, "?"); if (MessageBox.Show(message, "Печать", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { CreateDocument doc = DgvToExcel(); doc.Print(); } }; return(item); }
private ToolStripMenuItem CreateShowNotice() { ToolStripMenuItem item = CreateItem("Извещение о страховом случае"); item.Click += delegate { Car car = _dgvMain.GetCar(); if (car == null) { return; } if (_mainStatus.Get() == Status.DTP) { DTPList dtpList = DTPList.getInstance(); DTP dtp = dtpList.getItem(_dgvMain.GetID()); CreateDocument doc = new CreateDocument(car); doc.showNotice(dtp); } else { MessageBox.Show("Для формирования извещения необходимо перейти на вид \"ДТП\"", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }; return(item); }
private ToolStripMenuItem CreateShowActFuelCard() { ToolStripMenuItem item = CreateItem("Акт передачи топливной карты"); item.Click += delegate { Car car = _dgvMain.GetCar(); if (car == null) { MessageBox.Show("Для формирования акта выберите ячейку в таблице", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { InvoiceList invoiceList = InvoiceList.getInstance(); Invoice invoice = invoiceList.getItem(_dgvMain.GetID()); if (invoice == null) { MessageBox.Show("Для формирования акта необходимо перейти на страницу \"Перемещения\"", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } CreateDocument doc = new CreateDocument(car, invoice); doc.ShowActFuelCard(); } }; return(item); }
private CreateDocument DgvToExcel() { CreateDocument doc = new CreateDocument(); doc.CreateExcelFromAllDGV(_dgvMain.GetDGV()); doc.CreateHeader("Справочник \"" + _mainStatus.ToString() + "\""); return(doc); }
protected override async Task ExecuteInternal() { //Generate some PDF's and upload them //This will return a fileId (of type Guid) Guid fileId; using (var pdf = await Pdf.Generate("<h1>This PDF was generated in test<br/><em>CreateDocumentWithReceivers</em></h1>")) { fileId = await UploadPdf.Execute(Http, pdf, "TestFile.pdf"); } Logger.WriteLine("Uploaded TestFile.pdf. Returned fileId = {0:D}", fileId); Logger.WriteLine(); //Create a CreateDocumentsRequest and post it to eSignFlow //This returns a CreateDocumentsResponse int.TryParse(ConfigurationManager.AppSettings["SignerUserId.1"], out int signerUserId1); int.TryParse(ConfigurationManager.AppSettings["ClusterId"], out int clusterId); int.TryParse(ConfigurationManager.AppSettings["TemplateId"], out int templateId); var signers = new[] { new DocumentSigner(signerUserId1) }; var receivers = new[] { new DocumentReceiver { Email = "*****@*****.**" }, new DocumentReceiver { Email = "*****@*****.**" } }; var request = new CreateDocumentsRequest { Documents = new List <Document> { new Document { FileId = fileId, Title = $"Testdocument {DateTime.Now:yyyy-MM-dd HH:mm:ss}", OrganisationClusterId = clusterId, TemplateId = templateId, DocumentType = DocumentType.Default, LanguageId = 1, Signers = signers, Receivers = receivers } } }; var created = await CreateDocument.Execute(Http, request); Logger.WriteLine("CreateDocument response:"); Logger.WriteLine(Serialize(created)); Logger.WriteLine(); }
private ToolStripMenuItem CreateShowPolicyList() { ToolStripMenuItem item = CreateItem("Сформировать таблицу страхования"); item.Click += delegate { CreateDocument doc = new CreateDocument(); doc.CreatePolicyTable(); }; return(item); }
private ToolStripMenuItem CreateShowAllTable() { ToolStripMenuItem item = CreateItem("Экспорт текущего справочника в Excel"); item.Click += delegate { CreateDocument doc = DgvToExcel(); doc.Show(); }; return(item); }
private void messageToolStripMenuItem_Click(object sender, EventArgs e) { int idDTP = 0; int.TryParse(_dgvDTP.Rows[_dgvDTP.SelectedCells[0].RowIndex].Cells[0].Value.ToString(), out idDTP); DTP dtp = _dtpList.getItem(idDTP); CreateDocument doc = new CreateDocument(_car); doc.ShowNotice(dtp); }
private ToolStripMenuItem CreatePrint() { ToolStripMenuItem item = CreateItem("Печать"); item.ShortcutKeys = Keys.Control | Keys.P; item.Click += delegate { CreateDocument doc = new CreateDocument(); doc.CreateExcelFromDGV(_dgvMain.GetDGV()); doc.Print(); }; return(item); }
public override async Task Run(CreateDocument <TDocument> message, IContext context) { message.Document.Id = Guid.NewGuid().ToString(); message.Document.CreatedTimestamp = DateTime.UtcNow; message.Document.UpdatedTimestamp = DateTime.UtcNow; await Data.Context.SaveAsync <TDocument>(message.Document); await context.Emit(new CreateDocumentResult <TDocument> { Document = message.Document }); }
public DocumentCreated CreateDocument(CreateDocument command) { return(new DocumentCreated { EventType = nameof(DocumentCreated), Timstamp = DateTime.UtcNow, Document = new Document { Id = command.StreamId, DateCreated = DateTime.UtcNow, Name = command.Name, Artifacts = command.Artifacts } }); }
private ToolStripMenuItem CreateShowProxyOnSTO() { ToolStripMenuItem item = CreateItem("Доверенность на предоставление интересов на СТО"); item.Click += delegate { CreateDocument doc = createDocument(_dgvMain.CurrentCell); if (doc != null) { doc.ShowProxyOnSTO(); } }; return(item); }
public async Task Post_DocumentDoesNotExistsAndItShouldBeCreated_MethodReturn201() { var command = new CreateDocument() { }; var documentserviceMock = new Mock <IDocumentService>(); var commandDispatcherMock = new Mock <ICommandDispatcher>(); var documentsController = new DocumentsController(commandDispatcherMock.Object, documentserviceMock.Object); var response = await documentsController.Post(command); response.Should().NotBeNull(); response.Should().BeOfType <CreatedResult>(); (response as ObjectResult).StatusCode.Should().Be(201); }
public ActionResult PackingList(string ParametroFedex) { Debug.WriteLine(ParametroFedex); PdfFormatProvider formatProvider = new PdfFormatProvider(); formatProvider.ExportSettings.ImageQuality = ImageQuality.High; byte[] renderedBytes = null; using (MemoryStream ms = new MemoryStream()) { RadFixedDocument document = CreateDocument.CreatePDFDocument(decimal.Parse(ParametroFedex)); formatProvider.Export(document, ms); renderedBytes = ms.ToArray(); } return(File(renderedBytes, "application/pdf", "PackingList (" + DateTime.Now.ToString() + ").pdf")); }
private ToolStripMenuItem CreatePrintProxyOnSTO() { ToolStripMenuItem item = CreateItem("Печать доверенности на предоставление интересов на СТО"); item.Click += delegate { foreach (DataGridViewCell cell in _dgvMain.SelectedCells) { CreateDocument doc = createDocument(cell); if (doc != null) { doc.PrintProxyOnSTO(); } } }; return(item); }
public IApiResult Create(CreateDocument operation) { var result = operation.ExecuteAsync().Result; if (result is ValidationsOutput) { return(new ApiResult <List <ValidationItem> >() { Data = ((ValidationsOutput)result).Errors }); } else { return(new ApiResult <object>() { Status = ApiResult <object> .ApiStatus.Success, ID = ((ComplateOperation <int>)result).ID.Value }); } }
public async Task HandleAsync_TemplateNotFound_ThrowsException() { var command = new CreateDocument() { TemplateId = Guid.Parse("e28d59e8-1805-478a-98dd-0f51a427daf6"), Id = Guid.Parse("1c3d42b5-7bcc-4b14-8f62-722b4b9d2931"), UserId = "auth0|5c81a3686d3d732e6aa9e88f", Content = JObject.Parse("{\"foo\" : \"bar\"}") }; var documentServiceMock = new Mock <IDocumentService>(); var templateRepositoryMock = new Mock <ITemplateRepository>(); templateRepositoryMock.Setup(x => x.GetAsync(It.IsAny <Guid>())) .ReturnsAsync(value: null); var createDocumentHandler = new CreateDocumentHandler(templateRepositoryMock.Object, documentServiceMock.Object); var exception = await Assert.ThrowsAsync <ServiceException>(() => createDocumentHandler.HandleAsync(command)); exception.Code.Should().Be("template_not_found"); }
private ToolStripMenuItem CreateShowAttacheToOrder() { ToolStripMenuItem item = CreateItem("Приложение к приказу"); item.Click += delegate { if (_mainStatus.Get() != Status.Invoice) { MessageBox.Show("Для формирования накладной необходимо перейти на страницу \"Перемещения\"", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } CreateDocument doc = createDocument(_dgvMain.CurrentCell); if (doc != null) { doc.ShowAttacheToOrder(); } }; return(item); }
public async Task HandleAsync_TemplateFoundButVersionIsOutOfDate_ThrowsException() { var templateId = Guid.Parse("e28d59e8-1805-478a-98dd-0f51a427daf6"); var command = new CreateDocument() { TemplateId = templateId, Id = Guid.Parse("1c3d42b5-7bcc-4b14-8f62-722b4b9d2931"), // old/bad version is given UserId = "auth0|5c81a3686d3d732e6aa9e88f", Content = JObject.Parse("{\"foo\" : \"bar\"}") }; var documentServiceMock = new Mock <IDocumentService>(); var templateRepositoryMock = new Mock <ITemplateRepository>(); templateRepositoryMock.Setup(x => x.GetAsync(It.IsAny <Guid>())) .ReturnsAsync(new Template(templateId, Guid.Parse("a84a4ff8-76ec-4222-ae5a-a111b33a82e0"))); //current version var createDocumentHandler = new CreateDocumentHandler(templateRepositoryMock.Object, documentServiceMock.Object); var exception = await Assert.ThrowsAsync <ServiceException>(() => createDocumentHandler.HandleAsync(command)); exception.Code.Should().Be("template_out_of_date"); }
public async Task HandleAsync_CheckDocumentIdIsItEmpty_MethodReturnOne(string id, int expectedResult) { var templateId = Guid.Parse("e28d59e8-1805-478a-98dd-0f51a427daf6"); var command = new CreateDocument() { TemplateId = templateId, Id = Guid.Parse(id), UserId = "auth0|5c81a3686d3d732e6aa9e88f", Content = JObject.Parse("{\"foo\" : \"bar\"}") }; var documentServiceMock = new Mock <IDocumentService>(); var templateRepositoryMock = new Mock <ITemplateRepository>(); templateRepositoryMock.Setup(x => x.GetAsync(It.IsAny <Guid>())) .ReturnsAsync(new Template() { Id = templateId }); var createDocumentHandler = new CreateDocumentHandler(templateRepositoryMock.Object, documentServiceMock.Object); var result = await createDocumentHandler.HandleAsync(command); result.Should().Be(expectedResult); }
private static async Task Main(string[] args) { IoC.RegisterServices(); var commandHandler = new CommandHandler((IEventStreamReader)IoC.ServiceProvider.GetService(typeof(IEventStreamReader))); var streamId = Guid.Parse("e8512419-0183-42c9-b6df-0c4ea603ad00"); Guid documentId; var quit = false; while (!quit) { var key = UI(); switch (key) { case "1": var command = new CreateDocument { StreamId = streamId, Artifacts = new Dictionary <string, string>(), Name = Guid.NewGuid().ToString() }; await commandHandler.HandleCreateDocument(command); Console.WriteLine(); Console.WriteLine("Document created."); Console.WriteLine(); break; case "2": Console.WriteLine(); Console.WriteLine("Please, inform the new name of the dcocument:"); var name = Console.ReadLine(); var commandRename = new RenameDocument { StreamId = streamId, Name = name }; await commandHandler.HandleRenameDocument(commandRename); Console.WriteLine(); Console.WriteLine($"Document renamed"); Console.WriteLine(); break; case "3": Console.WriteLine(); var commandUpdate = new UpdateArtifacts { StreamId = streamId, AddArtifacts = new Dictionary <string, string> { { Guid.NewGuid().ToString(), Guid.NewGuid().ToString() } }, RemoveArtifacts = new List <string>() }; await commandHandler.HandleUpdateArtifacts(commandUpdate); Console.WriteLine(); Console.WriteLine($"Artifacts Updated!"); Console.WriteLine(); break; case "4": Console.WriteLine(); Console.WriteLine("Please, inform the approver name"); var approverName = Console.ReadLine(); var commandApprove = new ApproveDocument { StreamId = streamId, Approver = approverName }; await commandHandler.HandleApproveDocument(commandApprove); Console.WriteLine(); Console.WriteLine($"Document approved"); Console.WriteLine(); break; case "5": Console.WriteLine(); Console.WriteLine("Please, inform the approver name"); var rejecterName = Console.ReadLine(); var commandReject = new RejectDocument { StreamId = streamId, Rejecter = rejecterName }; await commandHandler.HandleRejectDocument(commandReject); Console.WriteLine(); Console.WriteLine($"Document rejected"); Console.WriteLine(); break; case "6": Console.WriteLine(); var commandDelete = new DeleteDocument { StreamId = streamId }; await commandHandler.HandleDeleteDocument(commandDelete); Console.WriteLine(); Console.WriteLine($"Document deleted"); Console.WriteLine(); break; case "Q": quit = true; break; case "q": quit = true; break; default: Console.WriteLine(); Console.WriteLine("Invalid option, chose a valid command"); Console.WriteLine(); break; } } }
protected override async Task ExecuteInternal() { //Generate some PDF's and upload them //This will return a fileId (of type Guid) Guid fileId; using (var pdf = await Pdf.Generate("<h1>This PDF was generated in test<br/><em>CreateDocumentWithAttachments</em></h1>")) { fileId = await UploadPdf.Execute(Http, pdf, "TestFile.pdf"); } Logger.WriteLine("Uploaded TestFile.pdf. Returned fileId = {0:D}", fileId); Guid attachId1; using (var pdf = await Pdf.Generate("<h1>This PDF (attachment 1) was generated in test<br/><em>CreateDocumentWithAttachments</em></h1>")) { attachId1 = await UploadPdf.Execute(Http, pdf, "Attachment1.pdf"); } Logger.WriteLine("Uploaded Attachment1.pdf. Returned fileId = {0:D}", fileId); Guid attachId2; using (var pdf = await Pdf.Generate("<h1>This PDF (attachment 2) was generated in test<br/><em>CreateDocumentWithAttachments</em></h1>")) { attachId2 = await UploadPdf.Execute(Http, pdf, "Attachment2.pdf"); } Logger.WriteLine("Uploaded Attachment2.pdf. Returned fileId = {0:D}", fileId); Guid attachId3; using (var pdf = await Pdf.Generate("<h1>This PDF (attachment 3) was generated in test<br/><em>CreateDocumentWithAttachments</em></h1>")) { attachId3 = await UploadPdf.Execute(Http, pdf, "Attachment3.pdf"); } Logger.WriteLine("Uploaded Attachment3.pdf. Returned fileId = {0:D}", fileId); Guid attachId4; using (var pdf = await Pdf.Generate("<h1>This PDF (attachment 4) was generated in test<br/><em>CreateDocumentWithAttachments</em></h1>")) { attachId4 = await UploadPdf.Execute(Http, pdf, "Attachment4.pdf"); } Logger.WriteLine("Uploaded Attachment4.pdf. Returned fileId = {0:D}", fileId); Logger.WriteLine(); //Create a CreateDocumentsRequest and post it to eSignFlow //This returns a CreateDocumentsResponse int.TryParse(ConfigurationManager.AppSettings["SignerUserId.1"], out int signerUserId); int.TryParse(ConfigurationManager.AppSettings["ClusterId"], out int clusterId); int.TryParse(ConfigurationManager.AppSettings["TemplateId"], out int templateId); var signers = new[] { new DocumentSigner(signerUserId) }; var attachments = new[] { new DocumentAttachment { FileId = attachId1, Title = "Att 1 (no signers)", DocumentType = DocumentType.Attachment, AttachmentSignersMode = AttachmentSignersMode.NoSigners }, new DocumentAttachment { FileId = attachId2, Title = "Att (predefined signers)", DocumentType = DocumentType.Attachment, AttachmentSignersMode = AttachmentSignersMode.SignerPredefined, Signers = signers }, new DocumentAttachment { FileId = attachId3, Title = "Att 3 (inherited signers)", DocumentType = DocumentType.Attachment, AttachmentSignersMode = AttachmentSignersMode.SignersMainDocument }, new DocumentAttachment { FileId = attachId4, Title = "Att 4 (creator)", DocumentType = DocumentType.Attachment, AttachmentSignersMode = AttachmentSignersMode.Creator //creator = user linked to ApiIdentityNrn } }; var request = new CreateDocumentsRequest { Documents = new List <Document> { new Document { FileId = fileId, Title = $"Testdocument {DateTime.Now:yyyy-MM-dd HH:mm:ss}", OrganisationClusterId = clusterId, TemplateId = templateId, DocumentType = DocumentType.Default, LanguageId = 1, InternalNote = "a note for the signers within the organisation", ExternalNote = "a note for the receivers of this document", Signers = signers, Attachments = attachments } } }; var created = await CreateDocument.Execute(Http, request); Logger.WriteLine("CreateDocument response:"); Logger.WriteLine(Serialize(created)); Logger.WriteLine(); }
private void ExportStructure(ProductStructure structure, bool isConfig = false) { // верификация структуры IsValidStructure(structure); // текущий документ Document currentDoc = structure.Document; // схема структуры SchemeDataConfig schemeConfig = new SchemeDataConfig(structure); SchemeData scheme = schemeConfig.GetScheme(); // родительский элемент RowElement parentItem = structure.GetAllRowElements().Where( x => x.ParentRowElement == null).FirstOrDefault(); ElementDataConfig dataConfig = new ElementDataConfig(parentItem, scheme); ElementData itemData = dataConfig.ConfigData(); // если структура является исполнением, то обозначением головного элемента // является наименование структуры if (isConfig) { itemData.Sign = structure.Name; } // логирование log.Span = sw.Elapsed; log.User = settings.UserName; log.Document = this.doc.FileName; log.Section = itemData.Section; log.Position = itemData.Position; log.Sign = itemData.Sign; log.Name = itemData.Name; log.Qty = itemData.Qty; log.Doccode = itemData.DocCode; log.FilePath = itemData.FilePath; log.Error = null; log.Write(); // команды TFlexObjSynchRepository synchRep = new TFlexObjSynchRepository(); // родительский элемент decimal?parent = null; // код БД decimal code = 0; decimal doccode = 0; // синхронизация с КИС "Омега" V_SEPO_TFLEX_OBJ_SYNCH synchObj = synchRep.GetSynchObj( itemData.MainSection, itemData.DocCode, itemData.Sign, itemData.ObjectType); // если головной элемент не синхронизирован - выход if (synchObj == null) { return; } #region экспорт родителя switch (synchObj.KOTYPE) { case (decimal)ObjTypes.SpecFixture: #region Спецификация оснастки CreateSpecFix.Exec( itemData.Sign, itemData.Name, ownerCode, synchObj.BOSTATECODE, ompUserCode, fixTypeCode, ref code); // очищение спецификации ClearSpecification.Exec(code); // родительский элемент parent = code; // поиск файла спецификации по шаблону string signPattern = Regex.Replace(itemData.Sign, @"\D", ""); string[] files = Directory.GetFiles(currentDoc.FilePath); foreach (var file in files) { if (file.Contains(itemData.Sign) && file.Contains("СП")) { AddFile.Exec(code, file, ompUserCode, synchObj.FILEGROUP, null, fileMain, ref doccode); } } #endregion Спецификация оснастки break; case (decimal)ObjTypes.SpecDraw: #region Сборочный чертеж CreateSpecDraw.Exec( itemData.Sign, itemData.Name, ownerCode, synchObj.BOSTATECODE, ompUserCode, ref code); // присоединенный файл AddFile.Exec(code, currentDoc.FileName, ompUserCode, synchObj.FILEGROUP, null, fileMain, ref doccode); #endregion Сборочный чертеж break; case (decimal)ObjTypes.Document: case (decimal)ObjTypes.UserDocument: #region Документация CreateDocument.Exec( synchObj.BOTYPE, itemData.Sign, itemData.Name, ownerCode, synchObj.BOSTATECODE, ompUserCode, ref code); // присоединенный файл AddFile.Exec(code, currentDoc.FileName, ompUserCode, synchObj.FILEGROUP, null, fileMain, ref doccode); #endregion Документация break; case (decimal)ObjTypes.Detail: #region Деталь CreateDetail.Exec( itemData.Sign, itemData.Name, ownerCode, synchObj.BOSTATECODE, ompUserCode, ref code); // присоединенный файл AddFile.Exec(code, currentDoc.FileName, ompUserCode, synchObj.FILEGROUP, null, fileMain, ref doccode); // модели для детали var models = structure.GetAllRowElements().Where(x => x.ParentRowElement == parentItem); foreach (var model in models) { ElementDataConfig modelDataConfig = new ElementDataConfig(model, scheme); ElementData modelData = modelDataConfig.ConfigData(); if (modelData.FilePath != null) { log.Span = sw.Elapsed; log.User = settings.UserName; log.Document = this.doc.FileName; log.Section = modelData.Section; log.Position = modelData.Position; log.Sign = modelData.Sign; log.Name = modelData.Name; log.Qty = modelData.Qty; log.Doccode = modelData.DocCode; log.FilePath = modelData.FilePath; log.Error = null; decimal linkdoccode = 0; AddFile.TryExec(log, code, modelData.FilePath, ompUserCode, synchObj.FILEGROUP, doccode, fileAdditional, ref linkdoccode); } } // моделями также являются невидимые фрагменты у деталей foreach (var fragment in currentDoc.GetFragments().Where(x => !x.Visible)) { if (fragment.FullFilePath != null) { log.Span = sw.Elapsed; log.User = settings.UserName; log.Document = this.doc.FileName; log.Section = null; log.Position = null; log.Sign = null; log.Name = null; log.Qty = null; log.Doccode = null; log.FilePath = fragment.FilePath; log.Error = null; decimal linkdoccode = 0; AddFile.TryExec(log, code, fragment.FullFilePath, ompUserCode, synchObj.FILEGROUP, doccode, fileAdditional, ref linkdoccode); } } #endregion Деталь break; case (decimal)ObjTypes.Fixture: #region Оснастка CreateFixture.Exec( itemData.Sign, itemData.Name, ownerCode, synchObj.BOSTATECODE, ompUserCode, fixTypeCode, ref code); // присоединенный файл AddFile.Exec(code, currentDoc.FileName, ompUserCode, synchObj.FILEGROUP, null, fileMain, ref doccode); // модели для детали var fix_models = structure.GetAllRowElements().Where(x => x.ParentRowElement == parentItem); foreach (var model in fix_models) { ElementDataConfig modelDataConfig = new ElementDataConfig(model, scheme); ElementData modelData = modelDataConfig.ConfigData(); if (modelData.FilePath != null) { log.Span = sw.Elapsed; log.User = settings.UserName; log.Document = this.doc.FileName; log.Section = modelData.Section; log.Position = modelData.Position; log.Sign = modelData.Sign; log.Name = modelData.Name; log.Qty = modelData.Qty; log.Doccode = modelData.DocCode; log.FilePath = modelData.FilePath; log.Error = null; decimal linkdoccode = 0; AddFile.TryExec(log, code, modelData.FilePath, ompUserCode, synchObj.FILEGROUP, doccode, fileAdditional, ref linkdoccode); } } // моделями также являются невидимые фрагменты у деталей foreach (var fragment in currentDoc.GetFragments().Where(x => !x.Visible)) { if (fragment.FullFilePath != null) { log.Span = sw.Elapsed; log.User = settings.UserName; log.Document = this.doc.FileName; log.Section = null; log.Position = null; log.Sign = null; log.Name = null; log.Qty = null; log.Doccode = null; log.FilePath = fragment.FilePath; log.Error = null; decimal linkdoccode = 0; AddFile.TryExec(log, code, fragment.FullFilePath, ompUserCode, synchObj.FILEGROUP, doccode, fileAdditional, ref linkdoccode); } } #endregion Оснастка break; default: break; } #endregion экспорт родителя #region элементы спецификации if (itemData.MainSection == "Сборочные единицы") { foreach (var elem in structure .GetAllRowElements() .Where(x => x.ParentRowElement == parentItem) ) { // получение данных о документе dataConfig = new ElementDataConfig(elem, scheme); itemData = dataConfig.ConfigData(); // логирование log.Span = sw.Elapsed; log.User = settings.UserName; log.Document = this.doc.FileName; log.Section = itemData.Section; log.Position = itemData.Position; log.Sign = itemData.Sign; log.Name = itemData.Name; log.Qty = itemData.Qty; log.Doccode = itemData.DocCode; log.FilePath = itemData.FilePath; log.Error = null; log.Write(); // если обозначение или секция пустые, то переход на следующий элемент if (itemData.Sign == String.Empty || itemData.Section == String.Empty) { continue; } //System.Windows.Forms.MessageBox.Show(itemData.SignFull + " |" + itemData.Section + " | " // + itemData.MainSection + " | " + itemData.ObjectType); // синхронизация с КИС "Омега" synchObj = synchRep.GetSynchObj( itemData.MainSection, itemData.DocCode, itemData.Sign, itemData.ObjectType); // переход на следующий элемент, если позиция не синхронизирована if (synchObj == null) { continue; } switch (synchObj.KOTYPE) { case (decimal)ObjTypes.SpecFixture: #region Спецификация оснастки CreateSpecFix.Exec( itemData.SignFull, itemData.Name, ownerCode, synchObj.BOSTATECODE, ompUserCode, fixTypeCode, ref code); // очищение спецификации ClearSpecification.Exec(code); // если у сборки есть фрагмент... if (itemData.FilePath != null) { try { if (!File.Exists(itemData.FilePath)) { throw new FileNotFoundException(); } // открыть документ входящей сборки в режиме чтения Document linkDoc = TFlex.Application.OpenDocument(itemData.FilePath, false, true); // добавить документ в стек stackDocs.Add(linkDoc); // экспорт документа ExportDoc(linkDoc, itemData.SignFull); // закрытие документа linkDoc.Close(); // удалить из стека документ stackDocs.Remove(linkDoc); } catch (FileNotFoundException e) { log.Span = sw.Elapsed; log.User = settings.UserName; log.Document = this.doc.FileName; log.Section = itemData.Section; log.Position = itemData.Position; log.Sign = itemData.Sign; log.Name = itemData.Name; log.Qty = itemData.Qty; log.Doccode = itemData.DocCode; log.FilePath = itemData.FilePath; log.Error = null; log.Write(e); } catch (Exception) { throw; } } #endregion Спецификация оснастки break; case (decimal)ObjTypes.SpecDraw: #region Сборочный чертеж CreateSpecDraw.Exec( itemData.Sign, itemData.Name, ownerCode, synchObj.BOSTATECODE, ompUserCode, ref code); // присоединенный файл AddFile.Exec(code, currentDoc.FileName, ompUserCode, synchObj.FILEGROUP, null, fileMain, ref doccode); #endregion Сборочный чертеж break; case (decimal)ObjTypes.Document: case (decimal)ObjTypes.UserDocument: #region Документация CreateDocument.Exec( synchObj.BOTYPE, itemData.Sign, itemData.Name, ownerCode, synchObj.BOSTATECODE, ompUserCode, ref code); // файл if (itemData.FilePath != null) { AddFile.Exec(code, itemData.FilePath, ompUserCode, synchObj.FILEGROUP, null, fileMain, ref doccode); } #endregion Документация break; case (decimal)ObjTypes.Detail: #region Деталь CreateDetail.Exec( itemData.SignFull, itemData.Name, ownerCode, synchObj.BOSTATECODE, ompUserCode, ref code); // файл if (itemData.FilePath != null) { AddFile.Exec(code, itemData.FilePath, ompUserCode, synchObj.FILEGROUP, null, fileMain, ref doccode); } // модели для детали var models = structure.GetAllRowElements().Where(x => x.ParentRowElement == elem); foreach (var model in models) { ElementDataConfig modelDataConfig = new ElementDataConfig(model, scheme); ElementData modelData = modelDataConfig.ConfigData(); if (modelData.FilePath != null) { log.Span = sw.Elapsed; log.User = settings.UserName; log.Document = this.doc.FileName; log.Section = modelData.Section; log.Position = modelData.Position; log.Sign = modelData.Sign; log.Name = modelData.Name; log.Qty = modelData.Qty; log.Doccode = modelData.DocCode; log.FilePath = modelData.FilePath; log.Error = null; decimal linkdoccode = 0; AddFile.TryExec(log, code, modelData.FilePath, ompUserCode, synchObj.FILEGROUP, (doccode == 0) ? null : (decimal?)doccode, fileAdditional, ref linkdoccode); } } // открывается документ на деталь, если есть if (itemData.FilePath != null) { try { if (!File.Exists(itemData.FilePath)) { throw new FileNotFoundException(); } // открыть документ входящей сборки в режиме чтения Document linkDoc = TFlex.Application.OpenDocument(itemData.FilePath, false, true); // добавить документ в стек stackDocs.Add(linkDoc); // экспорт документа ExportDoc(linkDoc, itemData.SignFull); // закрытие документа linkDoc.Close(); // удалить из стека документ stackDocs.Remove(linkDoc); } catch (FileNotFoundException e) { log.Span = sw.Elapsed; log.User = settings.UserName; log.Document = this.doc.FileName; log.Section = itemData.Section; log.Position = itemData.Position; log.Sign = itemData.Sign; log.Name = itemData.Name; log.Qty = itemData.Qty; log.Doccode = itemData.DocCode; log.FilePath = itemData.FilePath; log.Error = null; log.Write(e); } catch (Exception) { throw; } } #endregion Деталь break; case (decimal)ObjTypes.Fixture: #region Оснастка CreateFixture.Exec( itemData.SignFull, itemData.Name, ownerCode, synchObj.BOSTATECODE, ompUserCode, fixTypeCode, ref code); // файл if (itemData.FilePath != null) { AddFile.Exec(code, itemData.FilePath, ompUserCode, synchObj.FILEGROUP, null, fileMain, ref doccode); } // модели для детали var fix_models = structure.GetAllRowElements().Where(x => x.ParentRowElement == elem); foreach (var model in fix_models) { ElementDataConfig modelDataConfig = new ElementDataConfig(model, scheme); ElementData modelData = modelDataConfig.ConfigData(); if (modelData.FilePath != null) { log.Span = sw.Elapsed; log.User = settings.UserName; log.Document = this.doc.FileName; log.Section = modelData.Section; log.Position = modelData.Position; log.Sign = modelData.Sign; log.Name = modelData.Name; log.Qty = modelData.Qty; log.Doccode = modelData.DocCode; log.FilePath = modelData.FilePath; log.Error = null; decimal linkdoccode = 0; AddFile.Exec(code, modelData.FilePath, ompUserCode, synchObj.FILEGROUP, (doccode == 0) ? null : (decimal?)doccode, fileAdditional, ref linkdoccode); } } // открывается документ на деталь, если есть if (itemData.FilePath != null) { try { if (!File.Exists(itemData.FilePath)) { throw new FileNotFoundException(); } // открыть документ входящей сборки в режиме чтения Document linkDoc = TFlex.Application.OpenDocument(itemData.FilePath, false, true); // добавить документ в стек stackDocs.Add(linkDoc); // экспорт документа ExportDoc(linkDoc, itemData.SignFull); // закрытие документа linkDoc.Close(); // удалить из стека документ stackDocs.Remove(linkDoc); } catch (FileNotFoundException e) { log.Span = sw.Elapsed; log.User = settings.UserName; log.Document = this.doc.FileName; log.Section = itemData.Section; log.Position = itemData.Position; log.Sign = itemData.Sign; log.Name = itemData.Name; log.Qty = itemData.Qty; log.Doccode = itemData.DocCode; log.FilePath = itemData.FilePath; log.Error = null; log.Write(e); } catch (Exception) { throw; } } #endregion Оснастка break; default: code = 0; break; } // добавить очередной элемент в спецификацию if (code != 0) { AddElement.Exec( parent.Value, code, synchObj.KOTYPE, synchObj.OMPSECTION, itemData.Qty.Value, itemData.Position, ompUserCode); } } } #endregion элементы спецификации }
private DABImportDocuments.Response DABImportDocumentsHandler(DABImportDocuments command) { var response = new DABImportDocuments.Response(); var processes = Platform.ProjectionQuery <Process>().Where(p => p.FinalMaterialId != null).ToDictionary(p => p.Id, p => p.FinalMaterialId.Value); var finalMaterialIds = processes.Select(p => p.Value).Distinct().ToList(); var finalMaterials = Platform.ProjectionQuery <MaterialDefinition>().Where(m => finalMaterialIds.Contains(m.Id)).ToList(); WindchillDocConnector docConnector = new WindchillDocConnector(); var matDocDictionary = new Dictionary <int, List <Guid> >(); foreach (var finalMat in finalMaterials) { Platform.Tracer.Write("Siemens-SimaticIT-Trace-UADMRuntime", $"Retrieving documents for FinalMaterial {finalMat.NId} {finalMat.Revision}"); string revision = finalMat.Revision == "n/a" ? string.Empty : finalMat.Revision; var docInfoList = docConnector.GetDocumentList(finalMat.NId, revision); if (!docInfoList.Any()) { continue; } matDocDictionary.Add(finalMat.Id, new List <Guid>()); foreach (var docInfo in docInfoList) { string docNId = $"{docInfo.Revision}_{docInfo.Number}"; if (Platform.ProjectionQuery <Document>().Any(doc => doc.FileName == docInfo.Number && doc.Type == docInfo.DocType && doc.NId == doc.NId)) { continue; } Platform.Tracer.Write("Siemens-SimaticIT-Trace-UADMRuntime", $"Importing document {docNId} for FinalMaterial {finalMat.NId} {finalMat.Revision}"); var docFile = docConnector.DownloadDoc(docInfo); if (docFile == null) { continue; } var createDocInput = new CreateDocument() { Document = new DocumentParameterType { File = docFile.Content, FileName = docFile.Name, NId = docNId, Type = docFile.DocType, MIMEType = GetMimeType(docFile.Name) } }; var createDocResponse = Platform.CallCommand <CreateDocument, CreateDocument.Response>(createDocInput); if (!createDocResponse.Succeeded) { response.SetError(createDocResponse.Error.ErrorCode, createDocResponse.Error.ErrorMessage); return(response); } matDocDictionary[finalMat.Id].Add(createDocResponse.Id.Value); } foreach (var mat in matDocDictionary.Keys) { var processIds = processes.Where(kvp => kvp.Value.Equals(mat)).Select(kvp => kvp.Key); foreach (var procId in processIds) { var opIds = Platform.ProjectionQuery <Process>().Include(p => p.Operations).Where(p => p.Id.Equals(procId)).SelectMany(p => p.Operations).Select(o => o.Id); foreach (var opId in opIds) { if (!Platform.ProjectionQuery <OperationDependency>().Any(od => od.ContextProcess_Id.Equals(procId) && od.ToOperation_Id.Equals(opId))) { var createDocAssoc = Platform.CallCommand <LinkDocumentListToOperation, LinkDocumentListToOperation.Response>(new LinkDocumentListToOperation { ListOfDocumentId = matDocDictionary[mat], OperationId = opId }); if (!createDocAssoc.Succeeded) { response.SetError(createDocAssoc.Error.ErrorCode, createDocAssoc.Error.ErrorMessage); return(response); } break; } } } } } return(response); }
public async Task <IActionResult> Post([FromBody] CreateDocument command) { await _commandDispatcher.DispatchAsync(command); return(Created($"documents/{command.Id}", null)); }