using Eplan.EplApi.Base; using Eplan.EplApi.DataModel; using Eplan.EplApi.HEServices; using Eplan.EplApi.MasterData; using KPlan.Forms.Bean; using KPlan.Util; using Oracle.ManagedDataAccess.Client; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Xml; using Teamcenter.ClientX; using Teamcenter.Services.Strong.Core; using Teamcenter.Services.Strong.Core._2008_06.DataManagement; using Teamcenter.Soa.Client.Model; namespace KPlan.Forms { /// /// Interaction logic for KCheckProject.xaml /// public partial class KCheckProject_Ex : Window { private KBackgroundWorker bgWorker_load; private KBackgroundWorker bgWorker_export; private KBackgroundWorker bgWorker_save; private KBackgroundWorker bgWorker_check_all; private KBackgroundWorker bgWorker_check_error; public Project currentProject { get; set; } public string projId { get; set; } private string projName; private string projDir; public string exportFile { get; set; } private DataTable checkResultData = new DataTable(); private List titles = new List(); private List checkConfig = new List(); private Dictionary saveConfig = new Dictionary(); private List checkResultWidth = new List(); private List rowDatas = new List(); private bool enableExport = false; private bool canSave = false; private int INDEX_IND = -1; private int INDEX_RES = -1; private const string SKIP_PDF = "skip_pdf"; private Teamcenter.Soa.Client.Model.Strong.ItemRevision projItemRevision; private Teamcenter.Soa.Client.Model.Strong.Item projItem; private List errIdList2 = new List(); public KCheckProject_Ex(Project currentProject, string projectDir,string exportFile, string projectCode) { InitializeComponent(); KUtil.SetOwnerWindow(this); LoadCheckTable(); bgWorker_load = new KBackgroundWorker(this); bgWorker_load.backgroundWorker.DoWork += Async_Load; bgWorker_export = new KBackgroundWorker(this); bgWorker_export.backgroundWorker.DoWork += Async_Export; bgWorker_save = new KBackgroundWorker(this); bgWorker_save.backgroundWorker.DoWork += Async_SaveToTC; bgWorker_check_all = new KBackgroundWorker(this); bgWorker_check_all.backgroundWorker.DoWork += Async_Check_All; bgWorker_check_error = new KBackgroundWorker(this); bgWorker_check_error.backgroundWorker.DoWork += Async_Check_Error; this.currentProject = currentProject; this.projId = projectCode; this.projName = currentProject.ProjectName; this.projDir = projectDir; this.exportFile = exportFile; } public static string BackupProject(string dir, Project project) { string elkName = project.ProjectFullName + ".elk"; string zipName = project.ProjectName + ".zw1"; Progress progress = new Progress("SimpleProgress"); progress.SetTitle("备份项目..."); progress.SetAllowCancel(true); progress.BeginPart(100.0, ""); progress.ShowImmediately(); try { KUtil.Log("备份项目:" + elkName + " -> " + zipName); Backup backup = new Backup(); backup.Project(elkName, "", dir, zipName, Backup.Type.MakeBackup, Backup.Medium.Disk, 0.0, Backup.Amount.All, false, true, true, false); if (progress.Canceled()) { return null; } } catch (System.Exception ex) { KUtil.LogErr(ex); return null; } finally { progress.EndPart(true); } return dir + zipName; } public static string ExportPDF(string dir, Project project) { if (project.Pages == null || project.Pages.Length == 0) { KUtil.Log("没有Page,取消导出PDF:" + project.ProjectName); return SKIP_PDF; } string pdfName = dir + project.ProjectName + ".pdf"; Progress progress = new Progress("SimpleProgress"); progress.SetTitle("导出PDF..."); progress.SetAllowCancel(true); progress.BeginPart(100.0, ""); try { KUtil.Log("导出PDF:" + project.ProjectName + " -> " + pdfName); Export export = new Export(); export.PdfProject(project, "", pdfName, Export.DegreeOfColor.BlackAndWhite, true, "", true); if (progress.Canceled()) { return null; } } finally { progress.EndPart(true); } return pdfName; } [Obsolete] private void Async_SaveToTC(object sender, DoWorkEventArgs e) { if (KUtil.IsEmpty(projFile) || KUtil.IsEmpty(pdfFile)) { throw new Exception("文件导出异常"); } this.Dispatcher.Invoke(new Action(delegate { Visibility = Visibility.Hidden; })); try { bgWorker_save.Progress("保存项目信息...", 0); Teamcenter.Soa.Client.Model.Strong.ItemRevision projItemRevision = e.Argument as Teamcenter.Soa.Client.Model.Strong.ItemRevision; if (projItemRevision == null) { projItemRevision = TCUtil.Query_LatestRev(projId); } //检查发布,已经发布不允许保存 TCUtil.GetProperties(false, new Teamcenter.Soa.Client.Model.ModelObject[] { projItemRevision }, "item_revision_id"); string ver = projItemRevision.Item_revision_id; ProjectPropertyList projectProperties = currentProject.Properties; projectProperties.PROJ_CUSTOM_SUPPLEMENTARYFIELD100.Set(projId); projectProperties.PROJ_CUSTOM_SUPPLEMENTARYFIELD99.Set(ver); bgWorker_save.Progress("更新BOM...", 0); //更新bom CreateOrUpdateBom(projItemRevision, e); //同步项目属性 bgWorker_save.Progress("同步项目属性...", 0); KUtil.Sync_ProjProperty_to_TC(projItemRevision, currentProject); //创建数据集 CreateOrUpdateDataset(projItemRevision, e); } finally { this.Dispatcher.Invoke(new Action(delegate { Visibility = Visibility.Visible; })); } } private void CreateOrUpdateDataset(Teamcenter.Soa.Client.Model.Strong.ItemRevision projRev, DoWorkEventArgs e) { string ZW1DSType = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_ZW_DSTYPE); string ZW1DSRef = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_ZW_DSREF); string PDFDSType = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_PDF_DSTYPE); string PDFDSRef = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_PDF_DSREF); Teamcenter.Soa.Client.Model.Strong.Dataset zw1Dataset = null; Teamcenter.Soa.Client.Model.Strong.Dataset pdfDataset = null; if (!SKIP_PDF.Equals(pdfFile)) { bgWorker_save.Progress("创建PDF图纸...", 20); pdfDataset = TCUtil.CreateNewDataset(PDFDSType, projId + "PDF图纸"); if (pdfDataset == null) { throw new Exception("创建PDF图纸数据集失败"); } if (bgWorker_save.IsCancel()) { e.Cancel = true; return; } } bgWorker_save.Progress("创建EPLAN数据包...", 40); zw1Dataset = TCUtil.CreateNewDataset(ZW1DSType, projId + "EPLAN数据包"); if (zw1Dataset == null) { throw new Exception("创建EPLAN数据包数据集失败"); } if (bgWorker_save.IsCancel()) { e.Cancel = true; return; } if (pdfDataset != null) { bgWorker_save.Progress("上传PDF图纸...", 60); TCUtil.UploadFile(pdfDataset, pdfFile, PDFDSRef); if (bgWorker_save.IsCancel()) { e.Cancel = true; return; } } bgWorker_save.Progress("上传EPLAN数据包...", 80); TCUtil.UploadFile(zw1Dataset, projFile, ZW1DSRef); if (bgWorker_save.IsCancel()) { e.Cancel = true; return; } bgWorker_save.Progress("更新关系...", 100); ModelObject[] zw1Children = TCUtil.GetChild(projRev, "IMAN_specification", ZW1DSType); ModelObject[] pdfChildren = TCUtil.GetChild(projRev, "IMAN_specification", PDFDSType); TCUtil.RemoveChildren(projRev, zw1Children, "IMAN_specification"); TCUtil.RemoveChildren(projRev, pdfChildren, "IMAN_specification"); TCUtil.CreateNewRelation(projRev, zw1Dataset, "IMAN_specification"); if (pdfDataset != null) { TCUtil.CreateNewRelation(projRev, pdfDataset, "IMAN_specification"); } KUtil.DispatcherShow(this, "保存项目完成"); } private void CreateOrUpdateBom_QueryChildFromDB(Teamcenter.Soa.Client.Model.Strong.ItemRevision projRev, DoWorkEventArgs e) { int childCount = rowDatas.Count; if (childCount == 0) { return; } TCUtil.GetProperties(true, TCUtil.Refresh(projRev), "structure_revisions"); ReservationService res = ReservationService.getService(Teamcenter.ClientX.Session.getConnection()); Teamcenter.Soa.Client.Model.Strong.PSBOMViewRevision[] ps_revs = projRev.Structure_revisions; for (int j = 0; j < ps_revs.Length; j++) { Teamcenter.Soa.Client.Model.Strong.PSBOMViewRevision ps_rev = ps_revs[j]; string[] attris2 = { "is_modifiable", "object_string", "checked_out" }; TCUtil.GetProperties(true, TCUtil.Refresh(ps_rev), attris2); if (!ps_rev.Is_modifiable) { throw new Exception("当前用户无权修改BOM"); } if (ps_rev.Checked_out == "Y") { throw new Exception("BOM已经签出,请确认签入后再执行本操作"); } } ServiceData s_data = res.Checkout(ps_revs, "", ""); TCUtil.ThrowServiceDataError(s_data); KUtil.Log("同步BOM属性..."); //合并数据 List bomData = new List(); foreach (CheckTableRowData bean in rowDatas) { int index = bomData.IndexOf(bean); if (index >= 0) { bomData[index].addCombineNode(bean); } else { bomData.Add(bean); } } childCount = bomData.Count; // connect database string oradb = KUtil.GetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.DBCONN);// "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=TC)));User Id=infodba;Password=infodba;"; if (KUtil.IsEmpty(oradb)) { throw new Exception("未配置数据库连接"); } Dictionary existMap = new Dictionary(); try { Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo[] children_infos = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo[childCount]; using (OracleConnection conn = new OracleConnection(oradb)) { conn.Open(); DateTime time = DateTime.Now; for (int i = 0; i < childCount; i++) { bgWorker_save.Progress("更新BOM...", (i + 1) * 100 / childCount); if (bgWorker_save.IsCancel()) { e.Cancel = true; return; } CheckTableRowData rowData = bomData[i]; Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelOccInfo occ_info = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelOccInfo(); occ_info.AttrsToSet = rowData.GetBomProp(saveConfig); Teamcenter.Soa.Client.Model.Strong.ItemRevision itemrev = TCUtil.Query_LatestRev(rowData.itemId, conn); //Console.WriteLine("CreateOrUpdateBom------------------"+10); if (itemrev == null) { throw new Exception("对象不存在:" + rowData.itemId); } KUtil.Log((i + 1) + ". " + rowData.itemId + " > " + GetSyncInfo(occ_info.AttrsToSet)); Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo children_info = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo(); children_info.Child = itemrev; children_info.OccInfo = occ_info; children_infos[i] = children_info; } KUtil.Log("查询耗时:"+(DateTime.Now - time)); } bgWorker_save.Progress("更新BOM...", 100); Teamcenter.Services.Strong.Cad._2007_12.StructureManagement.CreateOrUpdateRelativeStructureInfo2[] struct_infos = new Teamcenter.Services.Strong.Cad._2007_12.StructureManagement.CreateOrUpdateRelativeStructureInfo2[1]; Teamcenter.Services.Strong.Cad._2007_12.StructureManagement.CreateOrUpdateRelativeStructureInfo2 struct_info = new Teamcenter.Services.Strong.Cad._2007_12.StructureManagement.CreateOrUpdateRelativeStructureInfo2(); struct_info.ChildInfo = children_infos; struct_info.Parent = projRev; struct_info.Precise = false; struct_infos[0] = struct_info; Teamcenter.Services.Strong.Cad.StructureManagementService ss_service = Teamcenter.Services.Strong.Cad.StructureManagementService.getService(Teamcenter.ClientX.Session.getConnection()); Teamcenter.Services.Strong.Cad._2007_12.StructureManagement.CreateOrUpdateRelativeStructurePref2 struct_pref = new Teamcenter.Services.Strong.Cad._2007_12.StructureManagement.CreateOrUpdateRelativeStructurePref2(); Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.CreateOrUpdateRelativeStructureResponse cursResp = ss_service.CreateOrUpdateRelativeStructure(struct_infos, "view", true, struct_pref); TCUtil.ThrowServiceDataError(cursResp.ServiceData); if (cursResp.Output.Count == 0) { throw new Exception("Bom创建失败"); } KUtil.Log("同步完成"); } finally { if (ps_revs != null) { ServiceData resp = res.Checkin(ps_revs); TCUtil.ThrowServiceDataError(resp); } } } private void CreateOrUpdateBom(Teamcenter.Soa.Client.Model.Strong.ItemRevision projRev, DoWorkEventArgs e) { int childCount = rowDatas.Count; if (childCount == 0) { return; } TCUtil.GetProperties(true, TCUtil.Refresh(projRev), "structure_revisions"); ReservationService res = ReservationService.getService(Teamcenter.ClientX.Session.getConnection()); //Teamcenter.Soa.Client.Model.Strong.PSBOMViewRevision[] ps_revs = projRev.Structure_revisions; //for (int j = 0; j < ps_revs.Length; j++) //{ // Teamcenter.Soa.Client.Model.Strong.PSBOMViewRevision ps_rev = ps_revs[j]; // string[] attris2 = { "is_modifiable", "object_string", "checked_out" }; // TCUtil.GetProperties(true, TCUtil.Refresh(ps_rev), attris2); // if (!ps_rev.Is_modifiable) // { // throw new Exception("当前用户无权修改BOM"); // } // if (ps_rev.Checked_out == "Y") // { // throw new Exception("BOM已经签出,请确认签入后再执行本操作"); // } //} //ServiceData s_data = res.Checkout(ps_revs, "", ""); //TCUtil.ThrowServiceDataError(s_data); KUtil.Log("同步BOM属性..."); //合并数据 List bomData = new List(); foreach (CheckTableRowData bean in rowDatas) { int index = bomData.IndexOf(bean); if (index >= 0) { bomData[index].addCombineNode(bean); } else { bomData.Add(bean); } } childCount = bomData.Count; try { //Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo[] children_infos = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo[childCount]; //Dictionary> projRevChildrenMap // = new Dictionary>(); Dictionary> levelRevChildrenMap = new Dictionary>(); //projectRev List projectRevRelativeStructureChildInfoList = new List(); levelRevChildrenMap.Add(projRev, projectRevRelativeStructureChildInfoList); for (int i = 0; i < childCount; i++) { bgWorker_save.Progress("更新BOM...", (i + 1) * 100 / childCount); if (bgWorker_save.IsCancel()) { e.Cancel = true; return; } CheckTableRowData rowData = bomData[i]; //获取(创建)位置层对象 String[] levelSplit = rowData.deviceTag.Split('+'); String lasterLevel = levelSplit[levelSplit.Length - 1].Split('-')[0]; String levelItemid = projRev.GetPropertyDisplayableValue("item_id") + lasterLevel; Teamcenter.Soa.Client.Model.Strong.ItemRevision levelrev = TCUtil.Query_LatestRev(levelItemid); if (levelrev == null) { levelrev = TCUtil.createItem("XA2_Productdraw", levelItemid); Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo level_info = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo(); level_info.Child = levelrev; //children_info.OccInfo = occ_info; //children_infos[i] = level_info; projectRevRelativeStructureChildInfoList.Add(level_info); //KUtil.DispatcherShow(this, "projectRevRelativeStructureChildInfoList Count->" + projectRevRelativeStructureChildInfoList.Count() + ""); } else { if (!levelRevChildrenMap.ContainsKey(levelrev)) { Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo level_info = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo(); level_info.Child = levelrev; projectRevRelativeStructureChildInfoList.Add(level_info); //List projectRevRelativeStructureChildInfoList2 = levelRevChildrenMap[projRev]; ////projectRevRelativeStructureChildInfoList2.Add(levelrev); //KUtil.DispatcherShow(this, "projectRevRelativeStructureChildInfoList2 Count->" + projectRevRelativeStructureChildInfoList2.Count() + ""); } } if (!levelRevChildrenMap.ContainsKey(levelrev)) { List relativeStructureChildInfoListNew = new List(); levelRevChildrenMap.Add(levelrev, relativeStructureChildInfoListNew); } //levelRev List relativeStructureChildInfoList = levelRevChildrenMap[levelrev]; Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelOccInfo occ_info = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelOccInfo(); occ_info.AttrsToSet = rowData.GetBomProp(saveConfig); Teamcenter.Soa.Client.Model.Strong.ItemRevision itemrev = TCUtil.Query_LatestRev(rowData.orderNo); if (itemrev == null) { throw new Exception("对象不存在:" + rowData.orderNo); } KUtil.Log((i + 1) + ". " + rowData.itemId + " > " + GetSyncInfo(occ_info.AttrsToSet)); TCUtil.GetProperties(true, TCUtil.Refresh(levelrev), "structure_revisions"); //ReservationService level_res = ReservationService.getService(Teamcenter.ClientX.Session.getConnection()); //Teamcenter.Soa.Client.Model.Strong.PSBOMViewRevision[] level_ps_revs = levelrev.Structure_revisions; //ServiceData level_s_data = level_res.Checkout(level_ps_revs, "", ""); //Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo[] level_children_infos = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo[1]; Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo level_children_info = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo(); level_children_info.Child = itemrev; level_children_info.OccInfo = occ_info; relativeStructureChildInfoList.Add(level_children_info); //level_children_infos[0] = level_children_info; } bgWorker_save.Progress("更新BOM...", 100); //KUtil.DispatcherShow(this, "levelRevChildrenMap Count->"+levelRevChildrenMap.Count()+""); Teamcenter.Services.Strong.Cad.StructureManagementService ss_service = Teamcenter.Services.Strong.Cad.StructureManagementService.getService(Teamcenter.ClientX.Session.getConnection()); foreach (Teamcenter.Soa.Client.Model.Strong.ItemRevision revKey in levelRevChildrenMap.Keys) { for (int k = 0; k < revKey.Structure_revisions.Length; k++) { Teamcenter.Soa.Client.Model.Strong.PSBOMViewRevision ps_rev = revKey.Structure_revisions[k]; string[] attris2 = { "is_modifiable", "object_string", "checked_out" }; TCUtil.GetProperties(true, TCUtil.Refresh(ps_rev), attris2); if (!ps_rev.Is_modifiable) { throw new Exception("当前用户无权修改BOM"); } if (ps_rev.Checked_out == "Y") { throw new Exception("BOM已经签出,请确认签入后再执行本操作"); } } ServiceData ss_data = res.Checkout(revKey.Structure_revisions, "", ""); List revRelativeStructureChildInfoList = levelRevChildrenMap[revKey]; //KUtil.DispatcherShow(this, "revRelativeStructureChildInfoList Count->" + revRelativeStructureChildInfoList.Count() + ""); Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo[] children_infos = revRelativeStructureChildInfoList.ToArray(); //KUtil.DispatcherShow(this, "children_infos Count->" + children_infos.Count() + ""); Teamcenter.Services.Strong.Cad._2007_12.StructureManagement.CreateOrUpdateRelativeStructureInfo2[] struct_infos = new Teamcenter.Services.Strong.Cad._2007_12.StructureManagement.CreateOrUpdateRelativeStructureInfo2[1]; Teamcenter.Services.Strong.Cad._2007_12.StructureManagement.CreateOrUpdateRelativeStructureInfo2 struct_info = new Teamcenter.Services.Strong.Cad._2007_12.StructureManagement.CreateOrUpdateRelativeStructureInfo2(); struct_info.ChildInfo = children_infos; struct_info.Parent = revKey; struct_info.Precise = false; struct_infos[0] = struct_info; Teamcenter.Services.Strong.Cad._2007_12.StructureManagement.CreateOrUpdateRelativeStructurePref2 struct_pref = new Teamcenter.Services.Strong.Cad._2007_12.StructureManagement.CreateOrUpdateRelativeStructurePref2(); Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.CreateOrUpdateRelativeStructureResponse cursResp = ss_service.CreateOrUpdateRelativeStructure(struct_infos, "view", true, struct_pref); TCUtil.ThrowServiceDataError(cursResp.ServiceData); if (cursResp.Output.Count == 0) { throw new Exception("Bom创建失败"); } if (revKey.Structure_revisions != null) { for (int k = 0; k < revKey.Structure_revisions.Length; k++) { Teamcenter.Soa.Client.Model.Strong.PSBOMViewRevision ps_rev = revKey.Structure_revisions[k]; string[] attris2 = { "is_modifiable", "object_string", "checked_out" }; TCUtil.GetProperties(true, TCUtil.Refresh(ps_rev), attris2); if (ps_rev.Checked_out == "Y") { ServiceData resp = res.Checkin(revKey.Structure_revisions); break; } } //ServiceData resp = res.Checkin(revKey.Structure_revisions); //TCUtil.ThrowServiceDataError(resp); } KUtil.Log("同步完成"); } } finally { //if (ps_revs != null) //{ // ServiceData resp = res.Checkin(ps_revs); // TCUtil.ThrowServiceDataError(resp); //} } } private string GetSyncInfo(Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.AttributesInfo[] attrs) { int len = attrs == null ? 0 : attrs.Length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.AttributesInfo attr = attrs[i]; sb.Append("|" + attr.Name + "=" + attr.Value); } sb.Append("|"); return sb.ToString(); } private void Async_Export(object sender, DoWorkEventArgs e) { bgWorker_export.Progress("准备导出项目检查数据...", 0); string fileName = e.Argument as string; KUtil.Log("导出申请单:"+fileName); if (string.IsNullOrWhiteSpace(fileName)) { throw new Exception("文件路径为空"); } System.Globalization.CultureInfo oldCI; //get the old CurrenCulture and set the new, en-US oldCI = System.Threading.Thread.CurrentThread.CurrentCulture; System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); if (File.Exists(fileName)) { File.Delete(fileName); } excel.Visible = false; excel.Application.Workbooks.Add(true); Microsoft.Office.Interop.Excel.Workbook wb = excel.ActiveWorkbook; Microsoft.Office.Interop.Excel.Worksheet st = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet; int colCnt = titles.Count; int rowIndex = 1; int col = 1; INDEX_RES = -1; INDEX_IND = -1; st.Cells.NumberFormat = "@"; for (int i = 0; i < colCnt; i++) { if (i == INDEX_IND || i == INDEX_RES) { continue; } st.Cells[rowIndex, col++] = titles[i]; } int rowCnt = rowDatas.Count; for (int i = 0; i < rowCnt; i++) { if (bgWorker_export.IsCancel()) { e.Cancel = true; break; } bgWorker_export.Progress("导出项目检查数据... " + (i + 1) + "/" + rowCnt + " ", (i + 1) * 100 / rowCnt); CheckTableRowData data = rowDatas[i]; //if (data.checkOK) { // continue; //} rowIndex++; object[] rowData = data.rowData; col = 1; for (int j = 0; j < colCnt; j++) { if (j == INDEX_IND || j == INDEX_RES) { continue; } st.Cells[rowIndex, col++] = rowData[j]?.ToString(); } // st.Cells[rowIndex, col++] = "10 / 10 / 09"; } if (e.Cancel) { wb.Close(false, Type.Missing, Type.Missing); excel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); System.GC.Collect(); return; } st.Columns.AutoFit(); st.Application.ActiveWindow.SplitRow = 1; st.Application.ActiveWindow.FreezePanes = true; // Now apply autofilter /*Microsoft.Office.Interop.Excel.Range firstRow = (Microsoft.Office.Interop.Excel.Range)st.Rows[1]; firstRow.AutoFilter(1, Type.Missing, Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlAnd, Type.Missing, true);*/ //保存excel文件 wb.SaveCopyAs(fileName); //关闭文件 wb.Close(false, Type.Missing, Type.Missing); excel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); System.GC.Collect(); this.Dispatcher.Invoke(new Action(delegate { MessageBoxResult res = MessageBox.Show(this, "数据导出完成,是否打开文件?", "", MessageBoxButton.YesNo, MessageBoxImage.Information); if (res == MessageBoxResult.Yes) { System.Diagnostics.Process.Start("explorer", "/n, " + fileName); } })); System.Threading.Thread.CurrentThread.CurrentCulture = oldCI; } private void Async_Check_All(object sender, DoWorkEventArgs e) { bool saveProject = (bool)e.Argument; enableExport = true; this.Dispatcher.Invoke(new Action(delegate { checkResultData.Rows.Clear(); })); this.rowDatas.Clear(); this.errIdList2.Clear(); XmlDocument doc = new XmlDocument(); doc.Load(exportFile); XmlNode partsList = doc.SelectSingleNode("partsList"); if (partsList == null) { KUtil.Log("没有找到节点:partsList"); return; } XmlNodeList deviceNodes = partsList.SelectNodes("device"); int deviceCnt = deviceNodes == null ? 0 : deviceNodes.Count; KUtil.Log("device数量:" + deviceCnt); string checkWire = KUtil.GetConfigValue(KConfigure.CHECK_SECTION, KConfigure.CHECK_WIRE); KUtil.Log("检查连接线:" + checkWire); //DateTime time1 = DateTime.Now; string oradb = KUtil.GetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.DBCONN);// "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=TC)));User Id=infodba;Password=infodba;"; if (KUtil.IsEmpty(oradb)) { throw new Exception("未配置数据库连接"); } Dictionary existMap = new Dictionary(); using (OracleConnection conn = new OracleConnection(oradb)) { conn.Open(); for (int i = 0; i < deviceCnt; i++) { if (bgWorker_check_all.IsCancel()) { e.Cancel = true; break; } bgWorker_check_all.Progress("检查数据... " + (i + 1) + "/" + deviceCnt + " ", (i + 1) * 100 / deviceCnt); XmlNode deviceNode = deviceNodes.Item(i); XmlNodeList partNodes = deviceNode.SelectNodes("part"); int partCnt = partNodes == null ? 0 : partNodes.Count; for (int j = 0; j < partCnt; j++) { if (bgWorker_check_all.IsCancel()) { e.Cancel = true; break; } XmlNode partNode = partNodes.Item(j); CheckPartNode(partNode, "TRUE".Equals(checkWire?.ToUpper()), conn, existMap); } } } this.Dispatcher.Invoke(new Action(delegate { b_Export.IsEnabled = enableExport; //b_save.IsEnabled = !enableExport; })); WriteErrorIds(); if (!saveProject) { return; } if (errIdList2.Count > 0) { KUtil.DispatcherShow(this, "检查出错,无法保存项目"); } else { this.Dispatcher.Invoke(new Action(delegate { SaveProject(); })); } } private void Async_Check_Error(object sender, DoWorkEventArgs e) { enableExport = true; this.Dispatcher.Invoke(new Action(delegate { checkResultData.Rows.Clear(); })); this.rowDatas.Clear(); this.errIdList2.Clear(); string[] errIds2 = TCUtil.GetPropArrayValue(projItem, KUtil.GetConfigValue(KConfigure.CHECK_SECTION, KConfigure.ERROR_ARRAY_PROP)); KUtil.Log("检查错误项:" + (errIds2 == null ? "null" : string.Join(", ", errIds2))); int len = errIds2 == null ? 0 : errIds2.Length; string oradb = KUtil.GetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.DBCONN);// "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=TC)));User Id=infodba;Password=infodba;"; if (KUtil.IsEmpty(oradb)) { throw new Exception("未配置数据库连接"); } Dictionary existMap = new Dictionary(); Eplan.EplApi.MasterData.MDPartsDatabase mdPartsDatabase = Util.EplanUtil.OpenDatabase(); using (OracleConnection conn = new OracleConnection(oradb)) { conn.Open(); for (int i = 0; i < len; i++) { if (bgWorker_check_error.IsCancel()) { e.Cancel = true; break; } bgWorker_check_error.Progress("检查错误项... " + (i + 1) + "/" + len + " ", (i + 1) * 100 / len); string orderNr = errIds2[i]; checkItemID(mdPartsDatabase, orderNr, null, conn, existMap); } } Util.EplanUtil.UpdateAndClose(mdPartsDatabase); this.Dispatcher.Invoke(new Action(delegate { b_Export.IsEnabled = enableExport; //b_save.IsEnabled = !enableExport; })); WriteErrorIds(); } private void WriteErrorIds() { //this.Dispatcher.Invoke(new Action(delegate { // b_check_error.IsEnabled = errIdList2.Count > 0; //})); //string propName = KUtil.GetConfigValue(KConfigure.CHECK_SECTION, KConfigure.ERROR_ARRAY_PROP); //string[] propVal = errIdList2.ToArray(); //KUtil.Log("更新项目错误ID:" + propName + " = " + string.Join(", ", propVal)); //TCUtil.SetArrayProperty(this.projItem, propName, propVal); } private void Async_Load(object sender, DoWorkEventArgs e) { bgWorker_load.Progress("查询项目...", 100); ProjectPropertyList projectProperties = currentProject.Properties; try { projItemRevision = TCUtil.Query_LatestRev(projId); if (projItemRevision != null) { TCUtil.GetProperties(false, TCUtil.Refresh(projItemRevision),"items_tag"); projItem = projItemRevision.Items_tag; } } catch (System.Exception e1) { KUtil.LogErr(e1); } bool projExist = projItemRevision!=null; //string[] errIds = TCUtil.GetPropArrayValue(projItem, KUtil.GetConfigValue(KConfigure.CHECK_SECTION, KConfigure.ERROR_ARRAY_PROP)); //KUtil.Log("找到原错误项:"+(errIds==null?"null":string.Join(", ",errIds))); this.Dispatcher.Invoke(new Action(delegate { this.tb_ProjId.Content = projId; this.tb_ProjName.Content = projName; })); this.Dispatcher.Invoke(new Action(delegate { b_Export.IsEnabled = enableExport; b_save.IsEnabled = projExist && !enableExport; b_check_all.IsEnabled = projExist; //b_check_error.IsEnabled = projExist && errIds!=null && errIds.Length>0; })); } private void CheckPartNode(XmlNode partNode, bool checkWire, OracleConnection conn, Dictionary existMap) { //检查是否需要检查 //连接线 XmlAttribute lenthvalue = partNode.Attributes["P_ARTICLE_PARTIAL_LENGTH_VALUE"]; if (lenthvalue != null && !checkWire) { //不检查连接线 return; } string refCount = partNode.Attributes["P_ARTICLEREF_COUNT"]?.InnerText; string lenth = lenthvalue?.InnerText; if (!KUtil.IsEmpty(refCount) && !KUtil.IsEmpty(lenth)) { double dwire_length = Convert.ToDouble(lenth); if (dwire_length != 0.0) { double drecord_num = Convert.ToDouble(refCount); drecord_num = dwire_length * drecord_num; refCount = drecord_num.ToString(); } } if ("0".Equals(refCount)) { return; } string itemId = partNode.Attributes["P_ARTICLE_ERPNR"]?.InnerText; string orderNo = partNode.Attributes["P_ARTICLE_PARTNR"]?.InnerText; string orderNo2 = partNode.Attributes["P_ARTICLE_ORDERNR"]?.InnerText; //System.Windows.Forms.MessageBox.Show(refCount +"|"+ itemId + "|"+ orderNo+ "|" +orderNo2); checkItemID(itemId, orderNo2, partNode, conn, existMap); } private void checkItemID(MDPartsDatabase mdPartDatabase, string orderNr, XmlNode partNode, OracleConnection conn, Dictionary existMap) { bool itemExist = false; string itemUid = null; MDPart[] res = EplanUtil.SearchPartByOrderNo(mdPartDatabase, orderNr); if (res == null || res.Length == 0) { throw new Exception("通过订货号["+orderNr+"]未查询到部件"); } if (res.Length > 1) { throw new Exception("通过订货号["+orderNr+"]查询到多个部件:"+res.Length); } MDPart part = res[0]; string itemId = EplanUtil.GetMDPropValue(part.Properties.ARTICLE_ERPNR); ; if (!KUtil.IsEmpty(itemId)) { if (existMap.ContainsKey(itemId)) { itemExist = existMap[itemId]; } else { //DateTime time = DateTime.Now; using (OracleCommand cmd = new OracleCommand()) { cmd.Connection = conn; cmd.CommandText = "select PUID from PITEM where PITEM_ID = '" + itemId + "'"; using (OracleDataReader dr = cmd.ExecuteReader()) { if (dr.HasRows) { itemExist = true; } if (dr.Read()) { itemUid = dr.GetString(0); //KUtil.Log("UID = "+itemUid); } //int res = dr.GetInt32(0); //KUtil.Log("查询结果数量:" + res); //itemExist = res > 0; } } existMap.Add(itemId, itemExist); // KUtil.Log("查询"+itemId+"耗时:"+(DateTime.Now-time)); } } CheckTableRowData data = new CheckTableRowData(itemId, orderNr, partNode, itemExist, itemUid); MessageBox.Show("1"); rowDatas.Add(data); object[] rowData = data.GetRowData(rowDatas.Count, checkConfig); if (!data.checkOK) { //if (!errIdList2.Contains(data.itemId)) { // errIdList2.Add(data.itemId); //} //20200508 改成订货号 P_ARTICLE_ORDERNR if (!errIdList2.Contains(orderNr)) { errIdList2.Add(orderNr); } enableExport = true; canSave = false; } this.Dispatcher.Invoke(new Action(delegate { checkResultData.Rows.Add(rowData); })); } private void checkItemID(string itemId, string orderNr, XmlNode partNode, OracleConnection conn, Dictionary existMap) { bool itemExist = false; string itemUid = null; if (!KUtil.IsEmpty(orderNr)) { if (existMap.ContainsKey(orderNr)) { itemExist = existMap[orderNr]; } else { //DateTime time = DateTime.Now; using (OracleCommand cmd = new OracleCommand()) { cmd.Connection = conn; cmd.CommandText = "select PUID from PITEM where PITEM_ID = '" + orderNr + "'"; using (OracleDataReader dr = cmd.ExecuteReader()) { if (dr.HasRows) { itemExist = true; } if (dr.Read()) { itemUid = dr.GetString(0); //KUtil.Log("UID = "+itemUid); } //int res = dr.GetInt32(0); //KUtil.Log("查询结果数量:" + res); //itemExist = res > 0; } } existMap.Add(orderNr, itemExist); // KUtil.Log("查询"+itemId+"耗时:"+(DateTime.Now-time)); } } //KUtil.DispatcherShow(this, "orderNr:" + orderNr); CheckTableRowData data = new CheckTableRowData(itemId,orderNr, partNode, itemExist, itemUid); //MessageBox.Show("2"); rowDatas.Add(data); object[] rowData = data.GetRowData(rowDatas.Count, checkConfig); if (!data.checkOK) { //if (!errIdList2.Contains(data.itemId)) { // errIdList2.Add(data.itemId); //} //20200508 改成订货号 P_ARTICLE_ORDERNR if (!errIdList2.Contains(orderNr)) { errIdList2.Add(orderNr); } enableExport = true; canSave = false; } this.Dispatcher.Invoke(new Action(delegate { checkResultData.Rows.Add(rowData); })); } private void LoadCheckTable() { checkResultData.Rows.Clear(); string queryResults = KUtil.GetConfigValue(KConfigure.CHECK_SECTION, KConfigure.CHECK_TITLE); string[] queryResultSplit = queryResults.Split(';'); int len = queryResultSplit.Length; for (int i = 0; i < len; i++) { string queryResult = queryResultSplit[i].Trim(); if (KUtil.IsEmpty(queryResult)) { continue; } string title = queryResult; string config = queryResult; int width = 50; string[] split = queryResult.Split(','); if (split.Length > 1) { title = split[0].Trim(); config = split[1].Trim(); } if (split.Length > 2) { Int32.TryParse(split[2].Trim(), out width); } titles.Add(title); checkConfig.Add(config); checkResultWidth.Add(width); if (CheckTableRowData.INDEX.Equals(config)) { INDEX_IND = i; } else if (CheckTableRowData.CHECK.Equals(config)) { INDEX_RES = i; } checkResultData.Columns.Add(new DataColumn() { ColumnName = title, DataType = CheckTableRowData.INDEX.Equals(config) ? typeof(Int32) : typeof(string) }); } string saveConfigStr = KUtil.GetConfigValue(KConfigure.CHECK_SECTION, KConfigure.SAVE_BOM_PROP); string[] saveConfigSplit = saveConfigStr?.Split(';'); len = saveConfigSplit == null ? 0 : saveConfigSplit.Length; for (int i = 0; i < len; i++) { string config = saveConfigSplit[i].Trim(); if (KUtil.IsEmpty(config)) { continue; } string[] split = config.Split('='); if (split.Length == 2) { string tc = split[0].Trim(); string eplan = split[1].Trim(); if (!KUtil.IsEmpty(tc) && !KUtil.IsEmpty(eplan)) { if (!saveConfig.ContainsKey(tc)) { saveConfig.Add(tc, eplan); } else { KUtil.Log("检测到重复配置:" + config); } } } } datagrid_CheckResult.DataContext = checkResultData.DefaultView; } private void Window_Loaded(object sender, RoutedEventArgs e) { this.bgWorker_load.Start(null); } private void datagrid_CheckResult_Loaded(object sender, RoutedEventArgs e) { int len = checkResultWidth.Count; for (int i = 0; i < len; i++) { datagrid_CheckResult.Columns[i].Width = checkResultWidth[i]; } } private void b_Close_Click(object sender, RoutedEventArgs e) { Close(); } private void b_Export_Click(object sender, RoutedEventArgs e) { if (rowDatas.Count == 0) { return; } //获取路径 //string nowtime = DateTime.Now.ToString("yyyy-MM-dd");//= DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss"); string fileName = "检查数据.xlsx"; System.Windows.Forms.SaveFileDialog sf = new System.Windows.Forms.SaveFileDialog(); sf.FileName = fileName; sf.DefaultExt = "xlsx"; sf.Filter = "Excel文件 (*.xlsx)|*.xlsx"; if (sf.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (File.Exists(fileName)) { MessageBoxResult res = MessageBox.Show(this, "文件已存在,是否覆盖?", "", MessageBoxButton.YesNo, MessageBoxImage.Information); if (res != MessageBoxResult.Yes) { return; } File.Delete(fileName); } bgWorker_export.Start(sf.FileName); } } private void SaveProject() { KUtil.Log("开始保存项目..."); System.Windows.Forms.Screen screen = System.Windows.Forms.Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(this).Handle); double top = this.Top; double left = this.Left; projFile = null; pdfFile = null; //Teamcenter.Soa.Client.Model.Strong.ItemRevision projItemRevision = null; string ver = ""; ProjectPropertyList projectProperties = currentProject.Properties; try { //projItemRevision = TCUtil.Query_LatestRev(projId); if (projItemRevision == null) { MessageBox.Show(this, "未查询到TC中的项目对象"); return; } TCUtil.Refresh(projItemRevision); //检查发布,已经发布不允许保存 TCUtil.GetProperties(false, new Teamcenter.Soa.Client.Model.ModelObject[] { projItemRevision }, "item_revision_id", "release_status_list"); Teamcenter.Soa.Client.Model.Strong.ReleaseStatus[] releaseStatus = projItemRevision.Release_status_list; if (releaseStatus != null && releaseStatus.Length > 0) { MessageBox.Show(this, "TC中项目对象“" + projId + "”的最新版本已发布,不可以进行保存"); return; } string oldVer = null; if (projectProperties.PROJ_CUSTOM_SUPPLEMENTARYFIELD99 != null && !projectProperties.PROJ_CUSTOM_SUPPLEMENTARYFIELD99.IsEmpty) { oldVer = projectProperties.PROJ_CUSTOM_SUPPLEMENTARYFIELD99.ToString(ISOCode.Language.L___); } ver = projItemRevision.Item_revision_id; if (!string.IsNullOrWhiteSpace(oldVer) && !oldVer.Equals(ver)) { MessageBoxResult res = MessageBox.Show("当前版本为" + oldVer + "版与最新版(" + ver + ")不一致是否继续保存?", "", MessageBoxButton.YesNo); if (res != MessageBoxResult.Yes) { return; } } } catch (Exception ex) { KUtil.LogErr(ex); MessageBox.Show(this, "检查项目对象出错:" + ex.Message); return; } Top = screen.Bounds.Height; Left = screen.Bounds.Width; try { projFile = BackupProject(projDir, currentProject); if (KUtil.IsEmpty(projFile)) { return; } if (!File.Exists(projFile)) { throw new Exception("导出文件不存在:" + projFile); } pdfFile = ExportPDF(projDir, currentProject); if (KUtil.IsEmpty(pdfFile)) { return; } if (!SKIP_PDF.Equals(pdfFile) && !File.Exists(pdfFile)) { throw new Exception("导出文件不存在:" + pdfFile); } } catch (System.Exception ex) { KUtil.LogErr(ex); Top = top; Left = left; MessageBox.Show(this, "导出数据出错:" + ex.Message); return; } finally { Top = top; Left = left; } try { projectProperties.PROJ_CUSTOM_SUPPLEMENTARYFIELD100.Set(projId); projectProperties.PROJ_CUSTOM_SUPPLEMENTARYFIELD99.Set(ver); } catch (Exception ex) { KUtil.LogErr(ex); MessageBox.Show(this, "更新本地项目信息出错:" + ex.Message); return; } bgWorker_save.Start(projItemRevision); } private void CheckAndSave(bool saveProject) { KUtil.Log("开始导出Partlist: " + exportFile); Progress progress = new Progress("SimpleProgress"); try { ExportPartList(progress, currentProject, exportFile); if (progress.Canceled()) { progress.EndPart(true); return; } progress.EndPart(true); if (!File.Exists(exportFile)) { MessageBox.Show("导出Partlist异常,未找到导出文件"); return; } } catch (System.Exception ex) { progress.EndPart(true); KUtil.LogErr(ex); MessageBox.Show("执行出错:" + ex.Message); return; } this.bgWorker_check_all.Start(saveProject); } private string projFile; private string pdfFile; private void b_save_Click(object sender, RoutedEventArgs e) { CheckAndSave(true); } private void b_check_error_Click(object sender, RoutedEventArgs e) { this.bgWorker_check_error.Start(null); } private void b_check_all_Click(object sender, RoutedEventArgs e) { CheckAndSave(false); } private void ExportPartList(Progress progress, Project currentProject, string exportFile) { progress.SetTitle("导出检查数据..."); progress.SetAllowCancel(true); progress.BeginPart(100.0, ""); EplanUtil.ExportPartList(currentProject, exportFile, PartsService.Format.XML); } } }