first commit

master
刘建兵 4 months ago
commit ef741673b2

63
.gitattributes vendored

@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

340
.gitignore vendored

@ -0,0 +1,340 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- Backup*.rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb

@ -0,0 +1,171 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="proj_sync_eplan_to_tc" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="proj_sync" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="part_sync_tc_to_eplan" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="part_sync_eplan_to_tc" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="part_sync" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="part_sync_classification" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="ref" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="proj_check" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="bmsq" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="ui_some" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="part_query" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="eplan_data" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="fms" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="query_proj" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="login" type="System.Configuration.AppSettingsSection" />
<section name="log" type="System.Configuration.AppSettingsSection" />
</configSections>
<proj_sync_eplan_to_tc>
<clear />
<add key="ITEM.object_desc" value="PROJ_INSTALLATIONNAME" />
<add key="REV.object_desc" value="PROJ_INSTALLATIONNAME" />
</proj_sync_eplan_to_tc>
<part_sync_tc_to_eplan>
<clear />
</part_sync_tc_to_eplan>
<part_sync_eplan_to_tc>
<clear />
</part_sync_eplan_to_tc>
<part_sync_classification>
<clear />
<add key="Electric.ElectricalPlc" value="ICM01" />
<add key="Electric.ElectricalSwitch" value="ICM01" />
<add key="Electric.ElectricalTransmissionpath" value="ICM01" />
<add key="Electric.ElectricalSignaldevice" value="ICM01" />
<add key="Electric.ElectricalBreak" value="ICM01" />
<add key="Mechanic.Mechanics19inchSystem" value="ICM01" />
<add key="Mechanic.MechanicsHookUp" value="ICM01" />
<add key="Mechanic.MechanicsRoutingPointTopology" value="ICM01" />
<add key="Mechanic.MechanicsRoutingPathTopology" value="ICM01" />
<add key="Mechanic.MechanicsRoutingAccessories" value="ICM01" />
<add key="Mechanic.MechanicsHousing" value="ICM01" />
<add key="Fluid.FluidSignalsensor" value="ICM01" />
<add key="Fluid.FluidSignaldevice" value="ICM01" />
<add key="Fluid.FluidAccumulator" value="ICM01" />
<add key="Fluid.FluidSeparator" value="ICM01" />
<add key="Process.ProcessThreewayarmature" value="ICM01" />
<add key="Process.ProcessLockarmature" value="ICM01" />
<add key="Process.ProcessCooler" value="ICM01" />
<add key="Process.ProcessSeparator" value="ICM01" />
</part_sync_classification>
<proj_sync>
<add key="object_type" value="J6_ElecHWDesign" />
<add key="pdf_dataset_type" value="PDF" />
<add key="pdf_dataset_ref" value="PDF_Reference" />
<add key="zw_dataset_type" value="J6_EPLAN" />
<add key="zw_dataset_ref" value="J6_EPLAN_zw1" />
</proj_sync>
<part_sync>
<add key="object_type" value="J6_WGPart" />
<add key="ordernr_tc" value="REV.j6_dhsx" />
</part_sync>
<ref>
<add key="bomtitle" value="" />
<add key="erpcode" value="" />
<add key="lineCount" value="" />
<add key="deleteXML" value="" />
</ref>
<proj_check>
<add key="table_table" value="序号,INDEX,50;&#xD;&#xA;检查结果,CHECK,80;&#xD;&#xA;ERP编码,P_ARTICLE_ERPNR,120;&#xD;&#xA;部件编码,P_ARTICLE_PARTNR,120;&#xD;&#xA;订货号,P_ARTICLE_ORDERNR,120;&#xD;&#xA;名称,P_ARTICLE_DESCR1@L_zh_CN,120;&#xD;&#xA;类型编号,P_ARTICLE_TYPENR,120;&#xD;&#xA;数量,P_ARTICLEREF_COUNT,120;&#xD;&#xA;制造商,P_ARTICLE_SUPPLIER,120;&#xD;&#xA;装配位置,P_DESIGNATION_LOCATION_DESCR@L_zh_CN,120;&#xD;&#xA;完整设备标识符,P_FUNC_IDENTDEVICETAG,150;" />
<add key="check_wire" value="TRUE" />
<add key="save_xml" value="TRUE" />
<add key="bom_prop" value="bl_item_object_desc=P_ARTICLE_MANUFACTURER;&#xD;&#xA;bl_quantity=P_ARTICLEREF_COUNT;" />
<add key="erpno_prop" value="j6_dhsx" />
<add key="group_bomline" value="4" />
</proj_check>
<bmsq>
<add key="item_type" value="" />
<add key="row_type" value="" />
<add key="table" value="" />
<add key="ordernr" value="" />
<add key="guid" value="" />
<add key="unit" value="" />
<add key="desc_cn" value="" />
<add key="desc_en" value="" />
<add key="preference" value="" />
<add key="process_template" value="" />
</bmsq>
<ui_some>
<add key="rev.object_type" value="" />
<add key="rev.owning_user" value="" />
</ui_some>
<part_query>
<add key="name" value="J6_WGPart" />
<add key="field_itemid" value="ID" />
<add key="field_ordernr" value="dhsx" />
</part_query>
<eplan_data>
<add key="data_folder" value="D:\Data" />
<add key="data_skip_folders" value="-Projects" />
<add key="dataset_uid" value="" />
<add key="template_item_id" value="000026" />
<add key="template_dataset_type" value="J6_EPLAN" />
<add key="workspace" value="D:\TEMP1" />
<add key="en_to_cn" value="" />
<add key="keep_zip_file" value="" />
</eplan_data>
<fms>
<add key="url" value="http://192.168.37.128:4544" />
<add key="path" value="D:\\File" />
</fms>
<query_proj>
<add key="name" value="Item..." />
<add key="fields" value="零组件ID,Item ID; 名称,Name; 类型,Type" />
<add key="result_table" value="序号,INDEX,50; ID,item_id,100; 名称,object_name,150; 类型,object_type,80" />
<add key="height" value="180" />
</query_proj>
<login>
<add key="host" value="http://localhost:7001/tc" />
<add key="user" value="admin" />
<add key="password" value="1" />
<add key="role" value="" />
<add key="oracle_conn" value="Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=JDNEWPLM)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=TC)));User Id=infodba;Password=infodba;" />
</login>
<log>
<add key="log_state" value="ON" />
<add key="log_config_path" value="C:\TC\Siemens\Teamcenter11\tccs\EPlan" />
</log>
<appSettings>
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<system.web>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="TcSoaCommon" publicKeyToken="0edd5b5ddd601444" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-12000.1.0.0" newVersion="12000.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="TcSoaClient" publicKeyToken="0edd5b5ddd601444" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-12000.1.0.0" newVersion="12000.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="TcSoaStrongModel" publicKeyToken="0edd5b5ddd601444" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-12000.1.0.0" newVersion="12000.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="ICSharpCode.SharpZipLib" publicKeyToken="1b03e6acf1164f73" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.2.0.246" newVersion="1.2.0.246" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Binary file not shown.

Binary file not shown.

@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KPlan", "KPlan\KPlan.csproj", "{A7F5F234-14A2-4AC1-A8FF-4535D68A3B40}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A7F5F234-14A2-4AC1-A8FF-4535D68A3B40}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A7F5F234-14A2-4AC1-A8FF-4535D68A3B40}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A7F5F234-14A2-4AC1-A8FF-4535D68A3B40}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A7F5F234-14A2-4AC1-A8FF-4535D68A3B40}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Binary file not shown.

@ -0,0 +1,155 @@
using Eplan.EplApi.ApplicationFramework;
using Eplan.EplApi.Base;
using Eplan.EplApi.DataModel;
using Eplan.EplApi.HEServices;
using KPlan.RefActions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using KPlan.Util;
namespace KPlan.Actions {
class CheckProjectAction : Eplan.EplApi.ApplicationFramework.IEplAction {
private String projectCode = string.Empty;
private String PROJ_NAME = string.Empty; //Project's property which return Name of Project - project name only without path.
private String PROJ_FULL_NAME = string.Empty;//string : project's full name for example "C:\EPLANPROJECTSDEMO2_D"
public bool Execute(ActionCallingContext ctx) {
if (!Util.TCUtil.CheckLogin()) {
return true;
}
try {
SelectionSet selectionSet = new SelectionSet();
Project currentProject = selectionSet.GetCurrentProject(false);
if (currentProject == null) {
MessageBox.Show("项目不存在!", "提示");
return true;
}
projectCode = EplanUtil.GetPropValue(currentProject.Properties.PROJ_DRAWINGNUMBER);
if (projectCode == String.Empty) {
MessageBox.Show("项目编号不能为空!", "提示");
return true;
}
string prjPath = currentProject.ProjectDirectoryPath;
// MessageBox.Show("prjPath--------------" + prjPath, "提示");
DirectoryInfo di = new DirectoryInfo(prjPath);
prjPath = di.Parent.FullName;
//MessageBox.Show("prjPath2--------------" + prjPath, "提示");
if (!prjPath.EndsWith("\\")) {
prjPath += "\\";
}
// MessageBox.Show("prjPath3--------------" + prjPath, "提示");
//项目打包并生成Xml
if (ExportXml(currentProject, prjPath)) {
//MessageBox.Show("打包--------------" , "提示");
CheckForm checkForm = new CheckForm();
checkForm.projectCode = projectCode;
checkForm.currentProject = currentProject;
checkForm.xmlFilePath = prjPath + currentProject.ProjectName + ".xml";
checkForm.ShowDialog();
if (TCTool.deleteXML.Equals("TRUE", StringComparison.OrdinalIgnoreCase)) {
File.Delete(prjPath + currentProject.ProjectName + ".xml");
}
}
}
catch (System.Exception ex) {
Util.KUtil.LogErr(ex);
MessageBox.Show("执行出错:" + ex.Message);
}
return true;
}
public bool OnRegister(ref string Name, ref int Ordinal) {
Name = "CheckProjectAction";
Ordinal = 20;
return true;
}
public void GetActionProperties(ref ActionProperties actionProperties) {
//actionProperties.Description = "Action test with parameters.";
}
private bool ExportXml(Project currentProject, string exportPath) {
Progress progress = new Progress("SimpleProgress");
try {
progress.SetTitle("检查项目...");
progress.SetAllowCancel(true);
progress.BeginPart(100.0, "");
//progress.ShowImmediately();
PROJ_FULL_NAME = currentProject.ProjectFullName;
PROJ_NAME = currentProject.ProjectName;
string xmlFilePath = exportPath + PROJ_NAME + ".xml";
KUtil.Log("导出Partlist"+xmlFilePath);
PartsService ps = new PartsService();
ps.ExportPartsList(currentProject, xmlFilePath, PartsService.Format.XML);
if (progress.Canceled()) {
progress.EndPart(true);
return false;
}
progress.EndPart(true);
}
catch(System.Exception ex) {
KUtil.LogErr(ex);
progress.EndPart(true);
MessageBox.Show("导出xml信息失败");
return false;
}
return true;
}
private bool ExportXml_old(Project currentProject, string exportPath) {
//MessageBox.Show("开始导出xml信息");
bool result = true;
try {
PROJ_FULL_NAME = currentProject.ProjectFullName;
PROJ_NAME = currentProject.ProjectName;
string elkName = PROJ_FULL_NAME + ".elk";
string xmlFilePath = exportPath + PROJ_NAME + ".xml";
// MessageBox.Show("xmlFilePath------------------" + xmlFilePath);
ActionCallingContext context_temp = new ActionCallingContext();
context_temp.AddParameter("TYPE", "EXPORT");
context_temp.AddParameter("PROJECTNAME", elkName);
context_temp.AddParameter("EXPORTFILE", xmlFilePath);
//context_temp.AddParameter("FORMAT", "XPalXmlExporter");
context_temp.AddParameter("MODE", "0");
context_temp.AddParameter("ADDITIONAL_LANGUAGE", "1");
Progress progress = new Progress("SimpleProgress");
progress.SetActionText("检查");
progress.BeginPart(100.0, "");
progress.ShowImmediately();
progress.SetAllowCancel(true);
if (!progress.Canceled()) {
CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter();
if (!Util.KUtil.FileIsUsed(xmlFilePath)) {
if (!commandLineInterpreter.Execute("partslist", context_temp)) {
MessageBox.Show("导出xml信息失败");
result = false;
progress.EndPart(true);
return result;
}
}
progress.EndPart();
}
progress.EndPart(true);
}
catch (Exception ex) {
MessageBox.Show("Error:" + ex.Message);
result = false;
}
return result;
}
}
}

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eplan.EplApi.ApplicationFramework;
using KPlan.Forms;
namespace KPlan.Actions {
class ConfigureAction : Eplan.EplApi.ApplicationFramework.IEplAction {
public bool Execute(ActionCallingContext ctx) {
if (!Util.TCUtil.CheckLogin()) {
return true;
}
new Configure().ShowDialog();
return true;
}
public bool OnRegister(ref string Name, ref int Ordinal) {
Name = "ConfigureAction";
Ordinal = 20;
return true;
}
public void GetActionProperties(ref ActionProperties actionProperties) {
//actionProperties.Description = "Action test with parameters.";
}
}
}

@ -0,0 +1,39 @@
using Eplan.EplApi.ApplicationFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KPlan.Forms;
namespace KPlan.Actions {
class CreateProjectAction : Eplan.EplApi.ApplicationFramework.IEplAction {
public bool Execute(ActionCallingContext ctx) {
CreateProject projDialog = new CreateProject();
projDialog.ShowDialog();
if (projDialog.create) {
try {
projDialog.DoCreateProject();
}
catch (Exception ex) {
System.Windows.MessageBox.Show("创建项目出错:" + ex.Message);
Util.KUtil.LogErr(ex);
}
}
return true;
}
public bool OnRegister(ref string Name, ref int Ordinal) {
Name = "CreateProjectAction";
Ordinal = 20;
return true;
}
public void GetActionProperties(ref ActionProperties actionProperties) {
//actionProperties.Description = "Action test with parameters.";
}
}
}

@ -0,0 +1,222 @@
using Eplan.EplApi.ApplicationFramework;
using KPlan.RefActions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KPlan.Util;
using System.Windows.Forms;
using System.IO;
using Teamcenter.ClientX;
using Teamcenter.Soa.Client;
using Eplan.EplApi.Base;
using KPlan.Forms;
using System.ComponentModel;
using System.Threading;
using Teamcenter.Soa.Client.Model;
namespace KPlan.Actions {
class DownloadTCDataAction : Eplan.EplApi.ApplicationFramework.IEplAction {
public bool Execute(ActionCallingContext ctx) {
TCUtil.DO_NOTHING();
if (!Util.TCUtil.CheckLogin()) {
return true;
}
Progress progress = new Progress("SimpleProgress");
try {
loadEplanEnv(progress);
progress.EndPart(true);
}
catch (System.Exception ex) {
progress.EndPart(true);
KUtil.LogErr(ex);
MessageBox.Show("执行出错:" + ex.Message);
}
return true;
}
public bool OnRegister(ref string Name, ref int Ordinal) {
Name = "DownloadTCDataAction";
Ordinal = 20;
return true;
}
public void GetActionProperties(ref ActionProperties actionProperties) {
//actionProperties.Description = "Action test with parameters.";
}
static private short loadEplanEnv(Progress progress) {
progress.SetTitle("下载TC数据");
progress.SetAllowCancel(false);
progress.BeginPart(30.0, "查询数据");
progress.ShowImmediately();
progress.SetActionText("查询数据...");
string loadEplanEnvTime = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_DATABASE_LAST_UPDATE_TIME);
bool load = false;
string eplanDataFolderPath = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_DATA_FOLDER);
string dsUid = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_DATASET_UID);
if (KUtil.IsEmpty(dsUid)) {
throw new Exception("未配置TC数据集UID");
}
if (!System.IO.Directory.Exists(eplanDataFolderPath)) {
throw new Exception("EPLAN数据文件夹不存在请检查配置" + eplanDataFolderPath);
}
KUtil.Log("准备下载EPLAN数据文件夹" + eplanDataFolderPath);
ModelObject mo = TCUtil.StringToComponent(dsUid);
if (mo == null) {
throw new Exception("未查询到数据集 uid = " + dsUid + ",请检查配置");
}
ModelObject[] mos = TCUtil.Refresh(mo);
TCUtil.GetProperties(false, mos, "object_string");
string dsName = mo.GetPropertyDisplayableValue("object_string");
KUtil.Log("找到数据集:" + dsName);
if (!TCUtil.IsType(mo.SoaType, "Zip")) {
throw new Exception("配置的数据集<" + dsName + ">不是Zip数据集uid = " + dsUid);
}
Teamcenter.Soa.Client.Model.Strong.Dataset dataset_zip = mo as Teamcenter.Soa.Client.Model.Strong.Dataset;
if (dataset_zip == null) {
return 0;
}
/*string dbItemID = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_DATABSE_ITEMID);
Teamcenter.Soa.Client.Model.Strong.ItemRevision eplanEnvItemRevision = TCTool.getLastItemRev(dbItemID);
TCUtil.Refresh(eplanEnvItemRevision);
Teamcenter.Soa.Client.Model.Strong.Dataset dataset_zip = TCTool.getDataset(eplanEnvItemRevision, "Zip", "EPLAN_PARTS");
if (dataset_zip != null) {
TCUtil.Refresh(dataset_zip);
if (0 != TCTool.checkZipDatasetCheckout(dataset_zip)) {
return 1;
}
//if (0 != TCTool.deleteDataset(projItemRevision, dataset_zw1))
//{
// return 2;
//}
}
else {
dataset_zip = TCTool.createDataset(eplanEnvItemRevision, "Zip", "EPLAN_PARTS");
if (dataset_zip == null) {
return 3;
}
}*/
String[] attributes2 = { "last_mod_date" };
TCUtil.dmService.GetProperties(mos, attributes2);
string last_mod_date = dataset_zip.Last_mod_date.ToString("yyyyMMddHHmmss");
KUtil.Log("数据修改时间:" + last_mod_date);
KUtil.Log("当前数据版本:" + loadEplanEnvTime);
if (string.IsNullOrEmpty(loadEplanEnvTime)) {
load = true;
}
if (!load) {
if (-1 == string.Compare(loadEplanEnvTime, last_mod_date)) {
load = true;
}
}
if (!load) {
MessageBox.Show("当前EPLAN部件库已经是最新的无须更新", "提示");
return 0;
}
progress.EndPart();
progress.BeginPart(30.0, "下载数据集");
progress.SetActionText("下载数据集...");
string fmsHome = Environment.GetEnvironmentVariable("FMS_HOME");
string zipFile = fmsHome + "\\EPlan\\" + "EPLAN_PARTS.zip";
try {
// Console.WriteLine("0-------------------------");
List<String> orgFileNames = new List<string>();
List<String> orgFilePaths = new List<string>();
String cacheDir = KUtil.GetConfigValue(KConfigure.FMS_SECTION, KConfigure.FMS_PATH);
if (!Directory.Exists(cacheDir)) {
Directory.CreateDirectory(cacheDir);
}
String[] FMS_Bootstrap_Urls = new String[] { KUtil.GetConfigValue(KConfigure.FMS_SECTION, KConfigure.FMS_URL) };
FileManagementUtility fMSFileManagement = new FileManagementUtility(Session.getConnection(), null, null, FMS_Bootstrap_Urls, cacheDir);
TCUtil.dmService.GetProperties(new Teamcenter.Soa.Client.Model.ModelObject[] { dataset_zip }, new string[] { "ref_list" });
Teamcenter.Soa.Client.Model.ModelObject[] ref_list = dataset_zip.Ref_list;
//Console.WriteLine("1-------------------------");
foreach (Teamcenter.Soa.Client.Model.ModelObject refobj in ref_list) {
Teamcenter.Soa.Client.Model.ModelObject[] ref_list1 = new Teamcenter.Soa.Client.Model.ModelObject[1];
ref_list1[0] = refobj;
TCUtil.dmService.GetProperties(ref_list1, new string[] { "original_file_name" });
string original_file_name = ref_list1[0].GetProperty("original_file_name").StringValue;
//Console.WriteLine("1.1-------------------------");
Teamcenter.Soa.Client.GetFileResponse fileresp = fMSFileManagement.GetFiles(ref_list1);
//Console.WriteLine("1.2-------------------------");
if (fileresp != null && fileresp.SizeOfFiles() > 0) {
FileInfo[] fis = fileresp.GetFiles();
FileInfo fi = fis[0];
orgFileNames.Add(original_file_name);
orgFilePaths.Add(fi.FullName);
break;
}
}
// Console.WriteLine("2-------------------------");
fMSFileManagement.Term();
// Console.WriteLine("2.1-------------------------");
if (orgFilePaths.Count > 0) {
if (File.Exists(zipFile)) {
FileInfo fi = new FileInfo(zipFile);
if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
fi.Attributes = FileAttributes.Normal;
File.Delete(zipFile);
}
System.IO.File.Copy(orgFilePaths[0], zipFile, true);
{
FileInfo fi = new FileInfo(zipFile);
if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
fi.Attributes = FileAttributes.Normal;
}
//Console.WriteLine("3-------------------------");
{
FileInfo fi = new FileInfo(orgFilePaths[0]);
if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
fi.Attributes = FileAttributes.Normal;
File.Delete(orgFilePaths[0]);
}
//Console.WriteLine("4-------------------------");
}
}
catch (SystemException e) {
progress.EndPart(true);
MessageBox.Show("下载EPLAN部件库失败\r\n" + e.ToString(), "提示");
return 11;
}
progress.EndPart();
progress.BeginPart(40.0, "解压文件");
progress.SetActionText("解压文件...");
//Console.WriteLine("待解压的文件-------------------------" + zipFile);
if (File.Exists(zipFile)) {
// Console.WriteLine("解压目录-------------------------" + TCTool.DatabaseInfo["ELECPartLib"]);
//Console.WriteLine("测试解压-------------------------" );
// if (!ZipHelper.UnZips(zipFile, TCTool.DatabaseInfo["ELECPartLib"]))
//string unzipPath = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_UNZIP_PATH);
KUtil.ReplaceZipContentName(zipFile);
if (!ZipHelper.UnZips(zipFile, eplanDataFolderPath)) {
progress.EndPart(true);
MessageBox.Show("解压缩EPLAN部件库失败", "提示");
return 21;
}
/* if (!ZipHelper.UnZips(zipFile, "D:\\AS2"))
{
MessageBox.Show("解压缩D:\\AS失败", "提示");
return 21;
}*/
/* if (!ZipHelper.UnZip(zipFile, TCTool.DatabaseInfo["ELECPartLibUnzip"]))
{
MessageBox.Show("解压缩EPLAN部件库失败", "提示");
return 21;
}*/
}
KUtil.SetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_DATABASE_LAST_UPDATE_TIME, last_mod_date);
progress.EndPart(true);
//iniFile.WriteString("databaseinfo", "更新时间", last_mod_date);
MessageBox.Show("下载EPLAN部件库完毕", "提示");
return 0;
}
}
}

@ -0,0 +1,81 @@
using System;
using System.IO;
using System.Windows;
using Eplan.EplApi.ApplicationFramework;
using Eplan.EplApi.DataModel;
using Eplan.EplApi.HEServices;
using KPlan.Util;
using Progress = Eplan.EplApi.Base.Progress;
namespace KPlan.Actions {
class KCheckProjectAction : Eplan.EplApi.ApplicationFramework.IEplAction {
public bool Execute(ActionCallingContext ctx) {
TCUtil.DO_NOTHING();
if (!TCUtil.CheckLogin()) {
return true;
}
SelectionSet selectionSet = new SelectionSet();
Project currentProject = selectionSet.GetCurrentProject(false);
if (currentProject == null) {
MessageBox.Show("没有选择项目");
return true;
}
string projectCode = EplanUtil.GetPropValue(currentProject.Properties.PROJ_DRAWINGNUMBER);
if (KUtil.IsEmpty(projectCode)) {
MessageBox.Show("项目编号不可为空");
return true;
}
string projPath = currentProject.ProjectDirectoryPath;
DirectoryInfo di = new DirectoryInfo(projPath);
projPath = di.Parent.FullName;
KUtil.Log("加载项目信息[" + currentProject.ProjectName + "]" + projPath);
if (!projPath.EndsWith("\\")) {
projPath += "\\";
}
string exportFile = projPath + currentProject.ProjectName + ".xml";
Progress progress = new Progress("SimpleProgress");
try {
ExportPartList(progress,currentProject,exportFile);
if (progress.Canceled()) {
progress.EndPart(true);
return true;
}
progress.EndPart(true);
if (!File.Exists(exportFile)) {
MessageBox.Show("导出Partlist异常未找到导出文件");
return true;
}
}
catch (System.Exception ex) {
progress.EndPart(true);
KUtil.LogErr(ex);
MessageBox.Show("执行出错:" + ex.Message);
}
new Forms.KCheckProject(currentProject,projPath,exportFile,projectCode).ShowDialog();
string save = KUtil.GetConfigValue(KConfigure.CHECK_SECTION, KConfigure.CHECK_SAVEXML);
if (!"TRUE".Equals(save?.ToUpper())) {
File.Delete(exportFile);
}
return true;
}
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);
}
public bool OnRegister(ref string Name, ref int Ordinal) {
Name = "KCheckProjectAction";
Ordinal = 20;
return true;
}
public void GetActionProperties(ref ActionProperties actionProperties) {
//actionProperties.Description = "Action test with parameters.";
}
}
}

@ -0,0 +1,53 @@
using System;
using System.IO;
using System.Windows;
using Eplan.EplApi.ApplicationFramework;
using Eplan.EplApi.DataModel;
using Eplan.EplApi.HEServices;
using KPlan.Util;
using Progress = Eplan.EplApi.Base.Progress;
namespace KPlan.Actions {
class KCheckProjectAction_Ex : Eplan.EplApi.ApplicationFramework.IEplAction {
public bool Execute(ActionCallingContext ctx) {
TCUtil.DO_NOTHING();
if (!TCUtil.CheckLogin()) {
return true;
}
SelectionSet selectionSet = new SelectionSet();
Project currentProject = selectionSet.GetCurrentProject(false);
if (currentProject == null) {
MessageBox.Show("没有选择项目");
return true;
}
string projectCode = EplanUtil.GetPropValue(currentProject.Properties.PROJ_DRAWINGNUMBER);
if (KUtil.IsEmpty(projectCode)) {
MessageBox.Show("项目编号不可为空");
return true;
}
string projPath = currentProject.ProjectDirectoryPath;
DirectoryInfo di = new DirectoryInfo(projPath);
projPath = di.Parent.FullName;
KUtil.Log("项目路径[" + currentProject.ProjectName + "]" + projPath);
if (!projPath.EndsWith("\\")) {
projPath += "\\";
}
string exportFile = projPath + currentProject.ProjectName + ".xml";
KUtil.Log("导出路径[" + currentProject.ProjectName + "]" + exportFile);
new Forms.KCheckProject_Ex(currentProject, projPath, exportFile, projectCode).Show();//.ShowDialog();
return true;
}
public bool OnRegister(ref string Name, ref int Ordinal) {
Name = "KCheckProjectAction_Ex";
Ordinal = 20;
return true;
}
public void GetActionProperties(ref ActionProperties actionProperties) {
//actionProperties.Description = "Action test with parameters.";
}
}
}

@ -0,0 +1,122 @@
using Eplan.EplApi.ApplicationFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KPlan.Forms;
using KPlan.Util;
using System.ComponentModel;
using System.Windows;
using Eplan.EplApi.Base;
using System.Threading;
using Teamcenter.Soa.Client.Model;
using System.IO;
namespace KPlan.Actions {
class KDownloadTCDataAction : Eplan.EplApi.ApplicationFramework.IEplAction {
public bool Execute(ActionCallingContext ctx) {
TCUtil.DO_NOTHING();
if (!Util.TCUtil.CheckLogin()) {
return true;
}
Progress progress = new Progress("SimpleProgress");
try {
Download(progress);
progress.EndPart(true);
}
catch(Exception ex) {
progress.EndPart(true);
KUtil.LogErr(ex);
MessageBox.Show("执行出错:" + ex.Message);
}
return true;
}
private void Download(Progress progress) {
progress.SetTitle("下载TC数据");
progress.SetAllowCancel(false);
progress.BeginPart(30.0, "查询数据");
progress.SetActionText("查询数据...");
progress.ShowImmediately();
string loadEplanEnvTime = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_DATABASE_LAST_UPDATE_TIME);
string eplanDataFolderPath = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_DATA_FOLDER);
string dsUid = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_DATASET_UID);
if (KUtil.IsEmpty(dsUid)) {
throw new Exception("未配置TC数据集UID");
}
if (!System.IO.Directory.Exists(eplanDataFolderPath)) {
throw new Exception("EPLAN数据文件夹不存在请检查配置" + eplanDataFolderPath);
}
KUtil.Log("准备下载EPLAN数据文件夹" + eplanDataFolderPath);
ModelObject mo = TCUtil.StringToComponent(dsUid);
if (mo == null) {
throw new Exception("未查询到Zip数据集 uid = " + dsUid + ",请检查配置");
}
ModelObject[] mos = TCUtil.Refresh(mo);
TCUtil.GetProperties(false, mos, "object_string");
string dsName = mo.GetPropertyDisplayableValue("object_string");
KUtil.Log("找到数据集:" + dsName);
if (!TCUtil.IsType(mo.SoaType, "Zip")) {
throw new Exception("配置的数据集<" + dsName + ">不是Zip数据集uid = " + dsUid);
}
Teamcenter.Soa.Client.Model.Strong.Dataset dataset_zip = mo as Teamcenter.Soa.Client.Model.Strong.Dataset;
if (dataset_zip == null) {
return;
}
TCUtil.GetProperties(false,mos, "last_mod_date");
string last_mod_date = dataset_zip.Last_mod_date.ToString("yyyyMMddHHmmss");
KUtil.Log("数据修改时间:" + last_mod_date);
KUtil.Log("当前数据版本:" + loadEplanEnvTime);
if (last_mod_date.Equals(loadEplanEnvTime)) {
MessageBox.Show("当前EPLAN部件库已经是最新的无须更新", "提示");
return;
}
progress.EndPart(false);
progress.BeginPart(30.0, "下载数据集");
progress.SetActionText("下载数据集...");
List<Teamcenter.Soa.Client.Model.Strong.ImanFile> zipFiles = TCUtil.GetDatasetFile(dataset_zip, "");
int len = zipFiles == null ? 0 : zipFiles.Count;
if (len == 0) {
KUtil.Log("数据集<" + dsName + ">不存在文件引用");
throw new Exception("缺少Eplan主数据请确认是否已上传Eplan主数据");
//throw new Exception("数据集<"+dsName+">不存在文件引用");
}
if (len > 1) {
throw new Exception("数据集<" + dsName + ">存在多个文件引用:"+len);
}
FileInfo zipFile = TCUtil.GetFileInfo(zipFiles[0]);
if (zipFile == null || !File.Exists(zipFile.FullName)){
throw new Exception("从数据集<" + dsName + ">下载文件失败");
}
KUtil.Log("下载文件:"+zipFile.FullName);
progress.EndPart(false);
progress.BeginPart(40.0, "解压文件");
progress.SetActionText("解压文件...");
KUtil.ReplaceZipContentName(zipFile.FullName);
KUtil.UnZipDirectory(zipFile.FullName, eplanDataFolderPath);
KUtil.SetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_DATABASE_LAST_UPDATE_TIME, last_mod_date);
progress.EndPart(true);
if (!"TRUE".Equals(KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_KEEP_ZIP)?.ToUpper())) {
zipFile.Delete();
KUtil.Log("已清理临时文件");
}
MessageBox.Show("下载EPLAN部件库完毕", "提示");
}
public bool OnRegister(ref string Name, ref int Ordinal) {
Name = "KDownloadTCDataAction";
Ordinal = 20;
return true;
}
public void GetActionProperties(ref ActionProperties actionProperties) {
//actionProperties.Description = "Action test with parameters.";
}
}
}

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eplan.EplApi.ApplicationFramework;
using KPlan.Forms;
namespace KPlan.Actions {
class KPartSyncAction : Eplan.EplApi.ApplicationFramework.IEplAction {
public bool Execute(ActionCallingContext ctx) {
if (!Util.TCUtil.CheckLogin()) {
return true;
}
Eplan.EplApi.MasterData.MDPartsDatabase mdPartsDatabase = Util.EplanUtil.OpenDatabase();
new KPartSync(mdPartsDatabase).ShowDialog();
Util.EplanUtil.UpdateAndClose(mdPartsDatabase);
return true;
}
public bool OnRegister(ref string Name, ref int Ordinal) {
Name = "KPartSyncAction";
Ordinal = 20;
return true;
}
public void GetActionProperties(ref ActionProperties actionProperties) {
//actionProperties.Description = "Action test with parameters.";
}
}
}

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eplan.EplApi.ApplicationFramework;
using KPlan.Util;
using KPlan.Forms;
using System.Windows;
namespace KPlan.Actions {
class LoginAction : Eplan.EplApi.ApplicationFramework.IEplAction {
public bool Execute(ActionCallingContext ctx) {
new Login().ShowDialog();
return true;
}
public bool OnRegister(ref string Name, ref int Ordinal) {
Name = "LoginAction";
Ordinal = 20;
return true;
}
public void GetActionProperties(ref ActionProperties actionProperties) {
//actionProperties.Description = "Action test with parameters.";
}
}
}

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eplan.EplApi.ApplicationFramework;
using KPlan.Forms;
using KPlan.Util;
namespace KPlan.Actions {
class OpenFromTCAction : Eplan.EplApi.ApplicationFramework.IEplAction {
public bool Execute(ActionCallingContext ctx) {
if (!TCUtil.CheckLogin()) {
return true;
}
new OpenFromTC().ShowDialog();
return true;
}
public bool OnRegister(ref string Name, ref int Ordinal) {
Name = "OpenFromTCAction";
Ordinal = 20;
return true;
}
public void GetActionProperties(ref ActionProperties actionProperties) {
//actionProperties.Description = "Action test with parameters.";
}
}
}

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eplan.EplApi.ApplicationFramework;
using KPlan.Forms;
namespace KPlan.Actions {
class PartSyncAction : Eplan.EplApi.ApplicationFramework.IEplAction {
public bool Execute(ActionCallingContext ctx) {
if (!Util.TCUtil.CheckLogin()) {
return true;
}
Eplan.EplApi.MasterData.MDPartsDatabase mdPartsDatabase = Util.EplanUtil.OpenDatabase();
new PartSync(mdPartsDatabase).ShowDialog();
Util.EplanUtil.UpdateAndClose(mdPartsDatabase);
return true;
}
public bool OnRegister(ref string Name, ref int Ordinal) {
Name = "PartSyncAction";
Ordinal = 20;
return true;
}
public void GetActionProperties(ref ActionProperties actionProperties) {
//actionProperties.Description = "Action test with parameters.";
}
}
}

@ -0,0 +1,659 @@
using Eplan.EplApi.ApplicationFramework;
using Eplan.EplApi.Base;
using Eplan.EplApi.DataModel;
using Eplan.EplApi.HEServices;
using KPlan.RefActions;
using KPlan.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace KPlan.Actions {
class SaveProjectAction : Eplan.EplApi.ApplicationFramework.IEplAction {
private String projectCode = string.Empty;
private String PROJ_NAME = string.Empty; //Project's property which return Name of Project - project name only without path.
private String PROJ_FULL_NAME = string.Empty;//string : project's full name for example "C:\EPLANPROJECTSDEMO2_D"
public bool Execute(ActionCallingContext ctx) {
if (!Util.TCUtil.CheckLogin()) {
return true;
}
try {
TCTool.ReadConfigs();
SelectionSet selectionSet = new SelectionSet();
Project currentProject = selectionSet.GetCurrentProject(false);
if (currentProject == null) {
MessageBox.Show("项目不存在11!", "提示");
return true;
}
projectCode = EplanUtil.GetProjectCode(currentProject);
if (projectCode == String.Empty) {
MessageBox.Show("项目编号不能为空!", "提示");
return true;
}
string prjPath = currentProject.ProjectDirectoryPath;
DirectoryInfo di = new DirectoryInfo(prjPath);
prjPath = di.Parent.FullName;
if (!prjPath.EndsWith("\\")) {
prjPath += "\\";
}
Dictionary<string, string> nameToPaths = new Dictionary<string, string>();
if (ZipProjectAndExport(currentProject, prjPath, nameToPaths)) {
KUtil.Log(prjPath);
SaveForm saveForm = new SaveForm();
saveForm.projectCode = projectCode;
saveForm.currentProject = currentProject;
saveForm.xmlFilePath = prjPath + currentProject.ProjectName + ".xml";
saveForm.nameToPaths = nameToPaths;
saveForm.ShowDialog();
if (TCTool.deleteXML.Equals("TRUE", StringComparison.OrdinalIgnoreCase)) {
File.Delete(prjPath + currentProject.ProjectName + ".xml");
}
Dictionary<string, string>.KeyCollection kc = nameToPaths.Keys;
foreach (string name in kc) {
File.Delete(nameToPaths[name]);
}
}
}
catch (System.Exception ex) {
KUtil.LogErr(ex);
MessageBox.Show("执行出错:" + ex.Message);
}
return true;
}
public bool OnRegister(ref string Name, ref int Ordinal) {
Name = "SaveProjectAction";
Ordinal = 20;
return true;
}
public void GetActionProperties(ref ActionProperties actionProperties) {
//actionProperties.Description = "Action test with parameters.";
}
private bool ZipProjectAndExport(Project currentProject, string exportPath, Dictionary<string, string> nameToPaths) {
bool result = true;
Progress progress = new Progress("SimpleProgress");
try {
PROJ_FULL_NAME = currentProject.ProjectFullName;
PROJ_NAME = currentProject.ProjectName;
string elkName = PROJ_FULL_NAME + ".elk";
string zipName = PROJ_NAME + ".zw1";
string pdfName = exportPath + PROJ_NAME + ".pdf";
string xmlFilePath = exportPath + PROJ_NAME + ".xml";
KUtil.Log(xmlFilePath);
progress.BeginPart(100.0, "");
progress.ShowImmediately();
progress.SetAllowCancel(true);
// MessageBox.Show("progress----------------1" );
if (!progress.Canceled()) {
// MessageBox.Show("progress----------------2");
File.Delete(zipName);
// MessageBox.Show("progress----------------3");
if (File.Exists(zipName)) {
MessageBox.Show("项目不能备份1!");
result = false;
progress.EndPart(true);
return result;
}
KUtil.Log("备份项目:"+elkName+" -> "+exportPath+"|"+zipName);
Backup backup = new Backup();
backup.Project(elkName, "", exportPath, zipName, Backup.Type.MakeBackup, Backup.Medium.Disk, 0.0, Backup.Amount.All, false, true, true, false);
nameToPaths.Add("ZW1", exportPath + zipName);
if (!KUtil.FileIsUsed(xmlFilePath)) {
File.Delete(xmlFilePath);
if (File.Exists(xmlFilePath)) {
MessageBox.Show("导出xml信息失败1!");
result = false;
progress.EndPart(true);
return result;
}
PartsService ps = new PartsService();
ps.ExportPartsList(currentProject, xmlFilePath, PartsService.Format.XML);
}
bool readResult = ReadXMLFile(xmlFilePath);
//MessageBox.Show("progress----------------8");
if (readResult) {
//MessageBox.Show("progress----------------9");
File.Delete(pdfName);
//MessageBox.Show("progress----------------10");
if (File.Exists(pdfName)) {
MessageBox.Show("导出PDF失败1!");
result = false;
progress.EndPart(true);
return result;
}
Export export = new Export();
//MessageBox.Show("progress----------------11");
export.PdfProject(currentProject, "", pdfName, Export.DegreeOfColor.BlackAndWhite, true, "", true);
// MessageBox.Show("progress----------------12");
if (!File.Exists(pdfName)) {
MessageBox.Show("导出PDF失败2!");
result = false;
progress.EndPart(true);
return result;
}
KUtil.Log(pdfName);
// MessageBox.Show("progress----------------13");
if (!nameToPaths.ContainsKey(PROJ_NAME)) {
nameToPaths.Add(PROJ_NAME, pdfName);
}
// MessageBox.Show("progress----------------14");
Page[] pages = currentProject.Pages;
int pageNum = pages.Length;
StringBuilder invalidCharSB = new StringBuilder("");
for (int i = 0; i < pageNum; i++) {
string pageName = pages[i].Name;
if (!pageName.StartsWith("&")) {
string plant = "";
if (!pages[i].Properties.DESIGNATION_PLANT.IsEmpty) {
plant = pages[i].Properties.get_DESIGNATION_FULLPLANT(0);
}
string plant_descr = "";
if (!pages[i].Properties.DESIGNATION_PLANT_DESCR.IsEmpty) {
plant_descr = pages[i].Properties.DESIGNATION_PLANT_DESCR.ToString(EplanUtil.Language_CN);
}
string userDefiend = "";
if (!pages[i].Properties.DESIGNATION_USERDEFINED.IsEmpty) {
userDefiend = pages[i].Properties.get_DESIGNATION_FULLUSERDEFINED(0);
}
string plantFullName = plant + " " + plant_descr;
if (plantFullName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) {
if (!invalidCharSB.ToString().Contains(plantFullName)) {
invalidCharSB.Append(plantFullName).Append(",");
}
continue;
}
//string pagePdfName = exportPath + plantFullName + ".pdf";
ArrayList listPlant = new ArrayList();
ArrayList listCnLocation = new ArrayList();
ArrayList listCtLocation = new ArrayList();
ArrayList listPreLocation = new ArrayList();
StringBuilder cadPathSB = new StringBuilder("");
//bool isDocument = false;
//if (!pages[i].Properties.PAGE_EXTDOCUMENT.IsEmpty)
//{
// string docName = pages[i].Properties.PAGE_EXTDOCUMENT.ToString().Trim();
// if (!docName.Equals(""))
// {
// isDocument = true;
// if (docName.EndsWith(".dwg"))
// {
// string cadPath = docName.Replace("$(DOC)",
// currentProject.ProjectDirectoryPath +
// "\\DOC");
// if (File.Exists(cadPath))
// {
// cadPathSB.Append(cadPath + ";");
// }
// }
// }
//}
//if (!isDocument)
//{
listPlant.Add(pages[i]);
//}
string location = "";
string cnPdfName = "";
string ctPdfName = "";
if (!pages[i].Properties.DESIGNATION_LOCATION.IsEmpty) {
location = pages[i].Properties.DESIGNATION_LOCATION.ToString();
if (location.Equals("CN")) {
string locationDescr = pages[i].Properties.DESIGNATION_LOCATION_DESCR.ToString();
listCnLocation.Add(pages[i]);
//cnPdfName = exportPath + plantFullName + "+" + location + " " + TcTool.getCNString(locationDescr) + ".pdf";
}
else if (location.Equals("CT")) {
string locationDescr = pages[i].Properties.DESIGNATION_LOCATION_DESCR.ToString();
listCtLocation.Add(pages[i]);
//ctPdfName = exportPath + plantFullName + "+" + location + " " + TcTool.getCNString(locationDescr) + ".pdf";
}
else {
listPreLocation.Add(pages[i]);
}
}
//export.DxfDwgPageToDisk(pages[i], "", exportPath, pages[i].Properties.PAGE_FULLNAME.ToString().Replace("/", "&"));
for (int j = (i + 1); j < pageNum; j++) {
string nextPageName = pages[j].Name;
//bool isDocument2 = false;
//if (!pages[j].Properties.PAGE_EXTDOCUMENT.IsEmpty)
//{
// string docName = pages[j].Properties.PAGE_EXTDOCUMENT.ToString().Trim();
// if (!docName.Equals(""))
// {
// isDocument2 = true;
// if (docName.EndsWith(".dwg"))
// {
// string cadPath = docName.Replace("$(DOC)", currentProject.ProjectDirectoryPath + "\\DOC");
// if (File.Exists(cadPath))
// {
// cadPathSB.Append(cadPath + ";");
// }
// }
// }
//}
string nextPlant = "";
if (!pages[j].Properties.DESIGNATION_PLANT.IsEmpty) {
nextPlant = pages[j].Properties.get_DESIGNATION_FULLPLANT(0);
}
if (!nextPageName.StartsWith("&") && nextPlant.Equals(plant)) {
//export.DxfDwgPageToDisk(pages[j], "", exportPath, pages[j].Properties.PAGE_FULLNAME.ToString().Replace("/", "&"));
if (!pages[j].Properties.DESIGNATION_LOCATION.IsEmpty) {
string nextLocation = pages[j].Properties.DESIGNATION_LOCATION.ToString();
if (nextLocation.Equals("CN")) {
listCnLocation.Add(pages[j]);
if (cnPdfName.Equals("")) {
string locationDescr = pages[j].Properties.DESIGNATION_LOCATION_DESCR.ToString();
//cnPdfName = exportPath + plantFullName + "+" + nextLocation + " " + TcTool.getCNString(locationDescr) + ".pdf";
}
}
else if (nextLocation.Equals("CT")) {
listCtLocation.Add(pages[j]);
if (ctPdfName.Equals("")) {
string locationDescr = pages[j].Properties.DESIGNATION_LOCATION_DESCR.ToString();
//ctPdfName = exportPath + plantFullName + "+" + nextLocation + " " + TcTool.getCNString(locationDescr) + ".pdf";
}
}
else {
listPreLocation.Add(pages[j]);
}
}
//if (!isDocument2)
//{
listPlant.Add(pages[j]);
//}
i++;
}
else {
//export.DxfDwgPageToDisk(pages[j], "", exportPath, pages[j].Properties.PAGE_FULLNAME.ToString().Replace("/", "&"));
break;
}
}
StringBuilder pdfPathSB = new StringBuilder("");
if (listCnLocation.Count > 0) {
File.Delete(cnPdfName);
//export.PdfPages(listCnLocation, "", cnPdfName, Export.DegreeOfColor.Color, true, "", true);
//pdfPathSB.Append(cnPdfName).Append(";");
}
if (listCtLocation.Count > 0) {
File.Delete(cnPdfName);
//export.PdfPages(listCtLocation, "", ctPdfName, Export.DegreeOfColor.Color, true, "", true);
//pdfPathSB.Append(ctPdfName).Append(";");
}
if (!nameToPaths.ContainsKey(plantFullName)) {
if (pdfPathSB.ToString().Equals("")) {
if (listPlant.Count > 0) {
//File.Delete(pagePdfName);
//export.PdfPages(listPlant, "", pagePdfName, Export.DegreeOfColor.Color, true, "", true);
}
//MessageBox.Show("plantFullName=" + plantFullName + ",pagePdfName=" + pagePdfName);
//nameToPaths.Add(plantFullName, pagePdfName);
}
else {
if (listPreLocation.Count > 0) {
//File.Delete(pagePdfName);
//export.PdfPages(listPlant, "", pagePdfName, Export.DegreeOfColor.Color, true, "", true);
//pdfPathSB.Append(pagePdfName).Append(";");
}
//MessageBox.Show("plantFullName=" + plantFullName + ",pagePdfName=" + pdfPathSB.ToString());
//nameToPaths.Add(plantFullName, pdfPathSB.ToString());
}
}
}
}
if (!invalidCharSB.ToString().Equals("")) {
MessageBox.Show("高层" + invalidCharSB.ToString().Substring(0, invalidCharSB.ToString().Length - 1) + "含有非法字符,请修改后再保存!");
result = false;
progress.EndPart(true);
return result;
}
if (!File.Exists(pdfName)) {
MessageBox.Show("导出PDF失败");
result = false;
progress.EndPart(true);
return result;
}
}
progress.EndPart();
}
progress.EndPart(true);
}
catch (Exception ex) {
KUtil.LogErr(ex);
MessageBox.Show("Error!!!" + ex.Message);
result = false;
progress.EndPart(true);
}
return result;
}
private bool ZipProjectAndExport_old(Project currentProject, string exportPath, Dictionary<string, string> nameToPaths) {
bool result = true;
try {
PROJ_FULL_NAME = currentProject.ProjectFullName;
PROJ_NAME = currentProject.ProjectName;
string elkName = PROJ_FULL_NAME + ".elk";
string zipName = PROJ_NAME + ".zw1";
string pdfName = exportPath + PROJ_NAME + ".pdf";
// MessageBox.Show("pdfName----------------" + pdfName);
ActionCallingContext actionCallingContext_zw1 = new ActionCallingContext();
actionCallingContext_zw1.AddParameter("TYPE", "PROJECT");
actionCallingContext_zw1.AddParameter("PROJECTNAME", elkName);
actionCallingContext_zw1.AddParameter("DESTINATIONPATH", exportPath);
actionCallingContext_zw1.AddParameter("ARCHIVENAME", zipName);
actionCallingContext_zw1.AddParameter("BACKUPMETHOD", "BACKUP");
actionCallingContext_zw1.AddParameter("BACKUPMEDIA", "DISK");
actionCallingContext_zw1.AddParameter("SPLITSIZE", "0.0");
actionCallingContext_zw1.AddParameter("BACKUPAMOUNT", "BACKUPAMOUNT_ALL");
actionCallingContext_zw1.AddParameter("COMPRESSPRJ", "0");
actionCallingContext_zw1.AddParameter("INCLEXTDOCS", "1");
actionCallingContext_zw1.AddParameter("INCLIMAGES", "1");
// MessageBox.Show("pdfName1----------------" + pdfName);
//=============通过项目生成PART_LIST,导出PART_LIST的CSV文件======
string partListPath = currentProject.ProjectDirectoryPath;//string : project's directory path for example "C:\EPLANPROJECTSDEMO2_D.EDB"
//================通过项目导出PART_LIST的XML文件
string xmlFilePath = exportPath + PROJ_NAME + ".xml";
// MessageBox.Show("pdfName2----------------" + pdfName);
// MessageBox.Show("导出xml3");
ActionCallingContext actionCallingContext_xml = new ActionCallingContext();
actionCallingContext_xml.AddParameter("TYPE", "EXPORT");
actionCallingContext_xml.AddParameter("PROJECTNAME", elkName);
actionCallingContext_xml.AddParameter("EXPORTFILE", xmlFilePath);
//context_temp.AddParameter("FORMAT", "XPalXmlExporter");
actionCallingContext_xml.AddParameter("MODE", "0");
actionCallingContext_xml.AddParameter("ADDITIONAL_LANGUAGE", "1");
KUtil.Log(xmlFilePath);
Progress progress = new Progress("SimpleProgress");
progress.BeginPart(100.0, "");
progress.ShowImmediately();
progress.SetAllowCancel(true);
// MessageBox.Show("progress----------------1" );
if (!progress.Canceled()) {
// MessageBox.Show("progress----------------2");
File.Delete(zipName);
// MessageBox.Show("progress----------------3");
if (File.Exists(zipName)) {
MessageBox.Show("项目不能备份1!");
result = false;
progress.EndPart(true);
return result;
}
CommandLineInterpreter commandLineInterpreter = new CommandLineInterpreter();
if (!commandLineInterpreter.Execute("backup", actionCallingContext_zw1)) {
MessageBox.Show("项目不能备份2!");
result = false;
progress.EndPart(true);
return result;
}
nameToPaths.Add("ZW1", exportPath + zipName);
if (!KUtil.FileIsUsed(xmlFilePath)) {
File.Delete(xmlFilePath);
if (File.Exists(xmlFilePath)) {
MessageBox.Show("导出xml信息失败1!");
result = false;
progress.EndPart(true);
return result;
}
//MessageBox.Show("progress----------------4");
if (!commandLineInterpreter.Execute("partslist", actionCallingContext_xml)) {
MessageBox.Show("导出xml信息失败2");
result = false;
progress.EndPart(true);
return result;
}
// MessageBox.Show("progress----------------5");
}
bool readResult = ReadXMLFile(xmlFilePath);
//MessageBox.Show("progress----------------8");
if (readResult) {
//MessageBox.Show("progress----------------9");
File.Delete(pdfName);
//MessageBox.Show("progress----------------10");
if (File.Exists(pdfName)) {
MessageBox.Show("导出PDF失败1!");
result = false;
progress.EndPart(true);
return result;
}
Export export = new Export();
//MessageBox.Show("progress----------------11");
export.PdfProject(currentProject, "", pdfName, Export.DegreeOfColor.BlackAndWhite, true, "", true);
// MessageBox.Show("progress----------------12");
if (!File.Exists(pdfName)) {
MessageBox.Show("导出PDF失败2!");
result = false;
progress.EndPart(true);
return result;
}
KUtil.Log(pdfName);
// MessageBox.Show("progress----------------13");
if (!nameToPaths.ContainsKey(PROJ_NAME)) {
nameToPaths.Add(PROJ_NAME, pdfName);
}
// MessageBox.Show("progress----------------14");
Page[] pages = currentProject.Pages;
int pageNum = pages.Length;
StringBuilder invalidCharSB = new StringBuilder("");
for (int i = 0; i < pageNum; i++) {
string pageName = pages[i].Name;
if (!pageName.StartsWith("&")) {
string plant = "";
if (!pages[i].Properties.DESIGNATION_PLANT.IsEmpty) {
plant = pages[i].Properties.get_DESIGNATION_FULLPLANT(0);
}
string plant_descr = "";
if (!pages[i].Properties.DESIGNATION_PLANT_DESCR.IsEmpty) {
plant_descr = pages[i].Properties.DESIGNATION_PLANT_DESCR.ToString(EplanUtil.Language_CN);
}
string userDefiend = "";
if (!pages[i].Properties.DESIGNATION_USERDEFINED.IsEmpty) {
userDefiend = pages[i].Properties.get_DESIGNATION_FULLUSERDEFINED(0);
}
string plantFullName = plant + " " + plant_descr;
if (plantFullName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) {
if (!invalidCharSB.ToString().Contains(plantFullName)) {
invalidCharSB.Append(plantFullName).Append(",");
}
continue;
}
//string pagePdfName = exportPath + plantFullName + ".pdf";
ArrayList listPlant = new ArrayList();
ArrayList listCnLocation = new ArrayList();
ArrayList listCtLocation = new ArrayList();
ArrayList listPreLocation = new ArrayList();
StringBuilder cadPathSB = new StringBuilder("");
//bool isDocument = false;
//if (!pages[i].Properties.PAGE_EXTDOCUMENT.IsEmpty)
//{
// string docName = pages[i].Properties.PAGE_EXTDOCUMENT.ToString().Trim();
// if (!docName.Equals(""))
// {
// isDocument = true;
// if (docName.EndsWith(".dwg"))
// {
// string cadPath = docName.Replace("$(DOC)",
// currentProject.ProjectDirectoryPath +
// "\\DOC");
// if (File.Exists(cadPath))
// {
// cadPathSB.Append(cadPath + ";");
// }
// }
// }
//}
//if (!isDocument)
//{
listPlant.Add(pages[i]);
//}
string location = "";
string cnPdfName = "";
string ctPdfName = "";
if (!pages[i].Properties.DESIGNATION_LOCATION.IsEmpty) {
location = pages[i].Properties.DESIGNATION_LOCATION.ToString();
if (location.Equals("CN")) {
string locationDescr = pages[i].Properties.DESIGNATION_LOCATION_DESCR.ToString();
listCnLocation.Add(pages[i]);
//cnPdfName = exportPath + plantFullName + "+" + location + " " + TcTool.getCNString(locationDescr) + ".pdf";
}
else if (location.Equals("CT")) {
string locationDescr = pages[i].Properties.DESIGNATION_LOCATION_DESCR.ToString();
listCtLocation.Add(pages[i]);
//ctPdfName = exportPath + plantFullName + "+" + location + " " + TcTool.getCNString(locationDescr) + ".pdf";
}
else {
listPreLocation.Add(pages[i]);
}
}
//export.DxfDwgPageToDisk(pages[i], "", exportPath, pages[i].Properties.PAGE_FULLNAME.ToString().Replace("/", "&"));
for (int j = (i + 1); j < pageNum; j++) {
string nextPageName = pages[j].Name;
//bool isDocument2 = false;
//if (!pages[j].Properties.PAGE_EXTDOCUMENT.IsEmpty)
//{
// string docName = pages[j].Properties.PAGE_EXTDOCUMENT.ToString().Trim();
// if (!docName.Equals(""))
// {
// isDocument2 = true;
// if (docName.EndsWith(".dwg"))
// {
// string cadPath = docName.Replace("$(DOC)", currentProject.ProjectDirectoryPath + "\\DOC");
// if (File.Exists(cadPath))
// {
// cadPathSB.Append(cadPath + ";");
// }
// }
// }
//}
string nextPlant = "";
if (!pages[j].Properties.DESIGNATION_PLANT.IsEmpty) {
nextPlant = pages[j].Properties.get_DESIGNATION_FULLPLANT(0);
}
if (!nextPageName.StartsWith("&") && nextPlant.Equals(plant)) {
//export.DxfDwgPageToDisk(pages[j], "", exportPath, pages[j].Properties.PAGE_FULLNAME.ToString().Replace("/", "&"));
if (!pages[j].Properties.DESIGNATION_LOCATION.IsEmpty) {
string nextLocation = pages[j].Properties.DESIGNATION_LOCATION.ToString();
if (nextLocation.Equals("CN")) {
listCnLocation.Add(pages[j]);
if (cnPdfName.Equals("")) {
string locationDescr = pages[j].Properties.DESIGNATION_LOCATION_DESCR.ToString();
//cnPdfName = exportPath + plantFullName + "+" + nextLocation + " " + TcTool.getCNString(locationDescr) + ".pdf";
}
}
else if (nextLocation.Equals("CT")) {
listCtLocation.Add(pages[j]);
if (ctPdfName.Equals("")) {
string locationDescr = pages[j].Properties.DESIGNATION_LOCATION_DESCR.ToString();
//ctPdfName = exportPath + plantFullName + "+" + nextLocation + " " + TcTool.getCNString(locationDescr) + ".pdf";
}
}
else {
listPreLocation.Add(pages[j]);
}
}
//if (!isDocument2)
//{
listPlant.Add(pages[j]);
//}
i++;
}
else {
//export.DxfDwgPageToDisk(pages[j], "", exportPath, pages[j].Properties.PAGE_FULLNAME.ToString().Replace("/", "&"));
break;
}
}
StringBuilder pdfPathSB = new StringBuilder("");
if (listCnLocation.Count > 0) {
File.Delete(cnPdfName);
//export.PdfPages(listCnLocation, "", cnPdfName, Export.DegreeOfColor.Color, true, "", true);
//pdfPathSB.Append(cnPdfName).Append(";");
}
if (listCtLocation.Count > 0) {
File.Delete(cnPdfName);
//export.PdfPages(listCtLocation, "", ctPdfName, Export.DegreeOfColor.Color, true, "", true);
//pdfPathSB.Append(ctPdfName).Append(";");
}
if (!nameToPaths.ContainsKey(plantFullName)) {
if (pdfPathSB.ToString().Equals("")) {
if (listPlant.Count > 0) {
//File.Delete(pagePdfName);
//export.PdfPages(listPlant, "", pagePdfName, Export.DegreeOfColor.Color, true, "", true);
}
//MessageBox.Show("plantFullName=" + plantFullName + ",pagePdfName=" + pagePdfName);
//nameToPaths.Add(plantFullName, pagePdfName);
}
else {
if (listPreLocation.Count > 0) {
//File.Delete(pagePdfName);
//export.PdfPages(listPlant, "", pagePdfName, Export.DegreeOfColor.Color, true, "", true);
//pdfPathSB.Append(pagePdfName).Append(";");
}
//MessageBox.Show("plantFullName=" + plantFullName + ",pagePdfName=" + pdfPathSB.ToString());
//nameToPaths.Add(plantFullName, pdfPathSB.ToString());
}
}
}
}
if (!invalidCharSB.ToString().Equals("")) {
MessageBox.Show("高层" + invalidCharSB.ToString().Substring(0, invalidCharSB.ToString().Length - 1) + "含有非法字符,请修改后再保存!");
result = false;
progress.EndPart(true);
return result;
}
if (!File.Exists(pdfName)) {
MessageBox.Show("导出PDF失败");
result = false;
progress.EndPart(true);
return result;
}
}
progress.EndPart();
}
progress.EndPart(true);
}
catch (Exception ex) {
MessageBox.Show("Error!!!" + ex.Message);
result = false;
}
return result;
}
public bool ReadXMLFile(String url) {
//MessageBox.Show("progress----------------7");
XmlTextReader xtr = new XmlTextReader(url);
try {
while (xtr.Read()) {
if (xtr.NodeType == XmlNodeType.Element) {
String element_name = xtr.Name;
if (xtr.HasAttributes) {
if (element_name == "part") {
return true;
}
}
}
}
xtr.Close();
}
catch (XmlException ex) {
MessageBox.Show(ex.Message);
}
return false;
}
}
}

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="query_proj" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="login" type="System.Configuration.AppSettingsSection" />
<section name="log" type="System.Configuration.AppSettingsSection" />
</configSections>
<query_proj>
<add key="name" value="Item..." />
<add key="fields" value="零组件ID,Item ID; 名称,Name; 类型,Type" />
<add key="result_table" value="序号,INDEX,50; ID,item_id,100; 名称,object_name,150; 类型,object_type,80" />
<add key="height" value="180" />
</query_proj>
<login>
<add key="host" value="http://localhost:7001/tc" />
<add key="user" value="admin" />
<add key="password" value="123" />
<add key="role" value="" />
</login>
<log>
<add key="log_state" value="ON" />
<add key="log_config_path" value="C:\TC\Siemens\Teamcenter11\tccs\EPlan" />
</log>
<appSettings>
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<system.web>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="TcSoaCommon" publicKeyToken="0edd5b5ddd601444" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-12000.1.0.0" newVersion="12000.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="TcSoaClient" publicKeyToken="0edd5b5ddd601444" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-12000.1.0.0" newVersion="12000.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="TcSoaStrongModel" publicKeyToken="0edd5b5ddd601444" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-12000.1.0.0" newVersion="12000.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="ICSharpCode.SharpZipLib" publicKeyToken="1b03e6acf1164f73" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.2.0.246" newVersion="1.2.0.246" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

@ -0,0 +1,146 @@
//==================================================
//
// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved.
//
//==================================================
using System;
using System.IO;
using Teamcenter.Schemas.Soa._2006_03.Exceptions;
using Teamcenter.Soa;
using Teamcenter.Soa.Common;
using Teamcenter.Soa.Client;
using Teamcenter.Soa.Exceptions;
namespace Teamcenter.ClientX
{
/**
* The CredentialManager is used by the Teamcenter Services framework to get the
* user's credentials when challanged by the server. This can occur after a period
* of inactivity and the server has timed-out the user's session, at which time
* the client application will need to re-authenitcate. The framework will
* call one of the getCredentials methods (depending on circumstances) and will
* send the SessionService.login service request. Upon successfull completion of
* the login service request. The last service request (one that cuased the challange)
* will be resent.
*
* The framework will also call the setUserPassword setGroupRole methods when ever
* these credentials change, thus allowing this implementation of the CredentialManager
* to cache these values so prompting of the user is not requried for re-authentication.
*
*/
public class AppXCredentialManager : CredentialManager
{
private String name = null;
private String password = null;
private String group = ""; // default group
private String role = ""; // default role
private String discriminator = "SoaAppX"; // always connect same user
// to same instance of server
/**
* Return the type of credentials this implementation provides,
* standard (user/password) or Single-Sign-On. In this case
* Standard credentials are returned.
*
* @see com.teamcenter.soa.client.CredentialManager#getCredentialType()
*/
public int CredentialType
{
get { return SoaConstants.CLIENT_CREDENTIAL_TYPE_STD; }
}
/**
* Prompt's the user for credentials.
* This method will only be called by the framework when a login attempt has
* failed.
*
* @see com.teamcenter.soa.client.CredentialManager#getCredentials(com.teamcenter.schemas.soa._2006_03.exceptions.InvalidCredentialsException)
*/
public string[] GetCredentials(InvalidCredentialsException e)
//throws CanceledOperationException
{
Console.WriteLine(e.Message);
return PromptForCredentials();
}
/**
* Return the cached credentials.
* This method will be called when a service request is sent without a valid
* session ( session has expired on the server).
*
* @see com.teamcenter.soa.client.CredentialManager#getCredentials(com.teamcenter.schemas.soa._2006_03.exceptions.InvalidUserException)
*/
public String[] GetCredentials(InvalidUserException e)
//throws CanceledOperationException
{
// Have not logged in yet, shoult not happen but just in case
if (name == null) return PromptForCredentials();
// Return cached credentials
String[] tokens = { name, password, group, role, discriminator };
return tokens;
}
/**
* Cache the group and role
* This is called after the SessionService.setSessionGroupMember service
* operation is called.
*
* @see com.teamcenter.soa.client.CredentialManager#setGroupRole(java.lang.String,
* java.lang.String)
*/
public void SetGroupRole(String group, String role)
{
this.group = group;
this.role = role;
}
/**
* Cache the User and Password
* This is called after the SessionService.login service operation is called.
*
* @see com.teamcenter.soa.client.CredentialManager#setUserPassword(java.lang.String,
* java.lang.String, java.lang.String)
*/
public void SetUserPassword(String user, String password, String discriminator)
{
this.name = user;
this.password = password;
this.discriminator = discriminator;
}
public String[] PromptForCredentials()
//throws CanceledOperationException
{
try
{
Console.WriteLine("Please enter user credentials (return to quit):");
Console.Write("User Name: ");
name = Console.ReadLine();
if (name.Length == 0)
throw new CanceledOperationException("");
Console.Write("Password: ");
password = Console.ReadLine();
}
catch (IOException e)
{
String message = "Failed to get the name and password.\n" + e.Message;
Console.WriteLine(message);
throw new CanceledOperationException(message);
}
String[] tokens = { name, password, group, role, discriminator };
return tokens;
}
}
}

@ -0,0 +1,101 @@
//==================================================
//
// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved.
//
//==================================================
using System;
using System.IO;
using Teamcenter.Schemas.Soa._2006_03.Exceptions;
using Teamcenter.Soa.Client;
using Teamcenter.Soa.Exceptions;
namespace Teamcenter.ClientX
{
/**
* Implementation of the ExceptionHandler. For ConnectionExceptions (server
* temporarily down .etc) prompts the user to retry the last request. For other
* exceptions convert to a RunTime exception.
*/
public class AppXExceptionHandler : ExceptionHandler
{
/*
* (non-Javadoc)
*
* @see com.teamcenter.soa.client.ExceptionHandler#handleException(com.teamcenter.schemas.soa._2006_03.exceptions.InternalServerException)
*/
public void HandleException(InternalServerException ise)
{
Console.WriteLine("");
Console.WriteLine("*****");
Console.WriteLine("Exception caught in com.teamcenter.clientx.AppXExceptionHandler.handleException(InternalServerException).");
KPlan.Util.KUtil.LogErr(ise);
throw new System.Exception(ise.Message);
if (ise is ConnectionException)
{
// ConnectionException are typically due to a network error (server
// down .etc) and can be recovered from (the last request can be sent again,
// after the problem is corrected).
Console.Write("\nThe server returned an connection error.\n" + ise.Message
+ "\nDo you wish to retry the last service request?[y/n]");
}
else if (ise is ProtocolException)
{
// ProtocolException are typically due to programming errors
// (content of HTTP
// request is incorrect). These are generally can not be
// recovered from.
Console.Write("\nThe server returned an protocol error.\n" + ise.Message
+ "\nThis is most likely the result of a programming error."
+ "\nDo you wish to retry the last service request?[y/n]");
}
else
{
Console.WriteLine("\nThe server returned an internal server error.\n"
+ ise.Message
+ "\nThis is most likely the result of a programming error."
+ "\nA RuntimeException will be thrown.");
throw new SystemException(ise.Message);
}
try
{
String retry = Console.ReadLine();
// If yes, return to the calling SOA client framework, where the
// last service request will be resent.
if (retry.ToLower().Equals("y") || retry.ToLower().Equals("yes"))
return;
throw new SystemException("The user has opted not to retry the last request");
}
catch (IOException e)
{
Console.Error.WriteLine("Failed to read user response.\nA RuntimeException will be thrown.");
throw new SystemException(e.Message);
}
}
/*
* (non-Javadoc)
*
* @see com.teamcenter.soa.client.ExceptionHandler#handleException(com.teamcenter.soa.exceptions.CanceledOperationException)
*/
public void HandleException(CanceledOperationException coe)
{
Console.WriteLine("");
Console.WriteLine("*****");
Console.WriteLine("Exception caught in com.teamcenter.clientx.AppXExceptionHandler.handleException(CanceledOperationException).");
// Expecting this from the login tests with bad credentials, and the
// AnyUserCredentials class not
// prompting for different credentials
throw new SystemException(coe.Message);
}
}
}

@ -0,0 +1,65 @@
//==================================================
//
// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved.
//
//==================================================
using System;
using Teamcenter.Soa.Client.Model;
using Teamcenter.Soa.Exceptions;
namespace Teamcenter.ClientX
{
/**
* Implementation of the ChangeListener. Print out all objects that have been updated.
*
*/
public class AppXModelEventListener : ModelEventListener
{
override public void LocalObjectChange(ModelObject[] objects)
{
if (objects.Length == 0) return;
System.Console.WriteLine("");
System.Console.WriteLine("Modified Objects handled in com.teamcenter.clientx.AppXUpdateObjectListener.modelObjectChange");
System.Console.WriteLine("The following objects have been updated in the client data model:");
for (int i = 0; i < objects.Length; i++)
{
String uid = objects[i].Uid;
String type = objects[i].GetType().Name;
String name = "";
if (objects[i].GetType().Name.Equals("WorkspaceObject"))
{
ModelObject wo = objects[i];
try
{
name = wo.GetProperty("object_string").StringValue;
}
catch (NotLoadedException /*e*/) {} // just ignore
}
System.Console.WriteLine(" " + uid + " " + type + " " + name);
}
}
override public void LocalObjectDelete(string[] uids)
{
if (uids.Length == 0)
return;
System.Console.WriteLine("");
System.Console.WriteLine("Deleted Objects handled in com.teamcenter.clientx.AppXDeletedObjectListener.modelObjectDelete");
System.Console.WriteLine("The following objects have been deleted from the server and removed from the client data model:");
for (int i = 0; i < uids.Length; i++)
{
System.Console.WriteLine(" " + uids[i]);
}
}
}
}

@ -0,0 +1,68 @@
//==================================================
//
// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved.
//
//==================================================
using System;
using Teamcenter.Soa.Client.Model;
namespace Teamcenter.ClientX
{
/**
* Implementation of the PartialErrorListener. Print out any partial errors
* returned.
*
*/
public class AppXPartialErrorListener : PartialErrorListener
{
/*
* (non-Javadoc)
*
* @see com.teamcenter.soa.client.model.PartialErrorListener#handlePartialError(com.teamcenter.soa.client.model.ErrorStack[])
*/
public void HandlePartialError(ErrorStack[] stacks)
{
if (stacks.Length == 0) return;
Console.WriteLine("");
Console.WriteLine("*****");
Console.WriteLine("Partial Errors caught in com.teamcenter.clientx.AppXPartialErrorListener.");
for (int i = 0; i < stacks.Length; i++)
{
ErrorValue[] errors = stacks[i].ErrorValues;
Console.Write("Partial Error for ");
// The different service implementation may optionally associate
// an ModelObject, client ID, or nothing, with each partial error
if (stacks[i].HasAssociatedObject() )
{
Console.WriteLine("object "+ stacks[i].AssociatedObject.Uid);
}
else if (stacks[i].HasClientId())
{
Console.WriteLine("client id "+ stacks[i].ClientId);
}
else if (stacks[i].HasClientIndex())
{
Console.WriteLine("client index " + stacks[i].ClientIndex);
}
// Each Partial Error will have one or more contributing error messages
for (int j = 0; j < errors.Length; j++)
{
Console.WriteLine(" Code: " + errors[j].Code + "\tSeverity: "
+ errors[j].Level + "\t" + errors[j].Message);
}
}
}
}
}

@ -0,0 +1,42 @@
//==================================================
//
// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved.
//
//==================================================
using System;
using Teamcenter.Soa.Client;
namespace Teamcenter.ClientX
{
/**
* This implemenation of the RequestListener, logs each service request
* to the console.
*
*/
public class AppXRequestListener : RequestListener
{
/**
* Called before each request is sent to the server.
*/
public void ServiceRequest(ServiceInfo info)
{
// will log the service name when done
}
/**
* Called after each response from the server.
* Log the service operation to the console.
*/
public void ServiceResponse(ServiceInfo info)
{
Console.WriteLine(info.Id + ": " + info.Service + "." + info.Operation);
}
}
}

@ -0,0 +1,266 @@
//==================================================
//
// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved.
//
//==================================================
using System;
using System.Collections;
using System.Net;
using Teamcenter.Schemas.Soa._2006_03.Exceptions;
using Teamcenter.Services.Strong.Core;
using Teamcenter.Services.Strong.Core._2006_03.Session;
using Teamcenter.Soa;
using Teamcenter.Soa.Client;
using Teamcenter.Soa.Client.Model;
using Teamcenter.Soa.Exceptions;
using WorkspaceObject = Teamcenter.Soa.Client.Model.Strong.WorkspaceObject;
using User = Teamcenter.Soa.Client.Model.Strong.User;
using KPlan.Util;
namespace Teamcenter.ClientX
{
public class Session
{
/**
* Single instance of the Connection object that is shared throughtout
* the application. This Connection object is needed whenever a Service
* stub is instantiated.
*/
private static Connection connection;
/**
* The credentialManager is used both by the Session class and the Teamcenter
* Services Framework to get user credentials.
*
*/
private static AppXCredentialManager credentialManager;
/**
* Create an instance of the Session with a connection to the specified
* server.
*
* Add implementations of the ExceptionHandler, PartialErrorListener,
* ChangeListener, and DeleteListeners.
*
* @param host Address of the host to connect to, http://serverName:port/tc
*/
public Session(String host)
{
// Create an instance of the CredentialManager, this is used
// by the SOA Framework to get the user's credentials when
// challanged by the server (sesioin timeout on the web tier).
credentialManager = new AppXCredentialManager();
string proto = null;
string envNameTccs = null;
if (host.StartsWith("http"))
{
proto = SoaConstants.HTTP;
}
else if (host.StartsWith("tccs"))
{
proto = SoaConstants.TCCS;
int envNameStart = host.IndexOf('/') + 2;
envNameTccs = host.Substring(envNameStart, host.Length - envNameStart);
}
// Create the Connection object, no contact is made with the server
// until a service request is made
connection = new Connection(host, new System.Net.CookieCollection(), credentialManager, SoaConstants.REST, proto, false);
if (proto == SoaConstants.TCCS)
connection.SetOption(Connection.TCCS_ENV_NAME, envNameTccs);
// Add an ExceptionHandler to the Connection, this will handle any
// InternalServerException, communication errors, xml marshalling errors
// .etc
connection.ExceptionHandler = new AppXExceptionHandler();
// While the above ExceptionHandler is required, all of the following
// Listeners are optional. Client application can add as many or as few Listeners
// of each type that they want.
// Add a Partial Error Listener, this will be notified when ever a
// a service returns partial errors.
connection.ModelManager.AddPartialErrorListener(new AppXPartialErrorListener());
// Add a Change and Delete Listener, this will be notified when ever a
// a service returns model objects that have been updated or deleted.
connection.ModelManager.AddModelEventListener(new AppXModelEventListener());
// Add a Request Listener, this will be notified before and after each
// service request is sent to the server.
Connection.AddRequestListener(new AppXRequestListener());
}
/**
* Get the single Connection object for the application
*
* @return connection
*/
public static Connection getConnection()
{
return connection;
}
public User Login2(string username, string password, string usergroup, string userrole) {
// Get the service stub
SessionService sessionService = SessionService.getService(connection);
LoginResponse resp = sessionService.Login(username, password, usergroup, userrole, "", "");
TCUtil.ThrowServiceDataError(resp.ServiceData);
//LoginResponse resp = sessionService.Login(username, password, usergroup, userrole, "", "");
return resp.User;
}
/**
* Login to the Teamcenter Server
*
*/
public User login()
{
// Get the service stub
SessionService sessionService = SessionService.getService(connection);
try
{
// Prompt for credentials until they are right, or until user
// cancels
String[] credentials = credentialManager.PromptForCredentials();
while (true)
{
try
{
// *****************************
// Execute the service operation
// *****************************
LoginResponse resp = sessionService.Login(credentials[0], credentials[1],
credentials[2], credentials[3],"",credentials[4]);
return resp.User;
}
catch (InvalidCredentialsException e)
{
credentials = credentialManager.GetCredentials(e);
}
}
}
// User canceled the operation, don't need to tell him again
catch (CanceledOperationException /*e*/) {}
// Exit the application
//System.exit(0);
return null;
}
/**
* Terminate the session with the Teamcenter Server
*
*/
public void logout()
{
// Get the service stub
SessionService sessionService = SessionService.getService(connection);
try
{
// *****************************
// Execute the service operation
// *****************************
sessionService.Logout();
}
catch (ServiceException /*e*/) { }
}
/**
* Print some basic information for a list of objects
*
* @param objects
*/
public static void printObjects(ModelObject[] objects)
{
if(objects == null)
return;
// Ensure that the referenced User objects that we will use below are loaded
getUsers( objects );
Console.WriteLine("Name\t\tOwner\t\tLast Modified");
Console.WriteLine("====\t\t=====\t\t=============");
for (int i = 0; i < objects.Length; i++)
{
if(!(objects[i] is WorkspaceObject ))
continue;
WorkspaceObject wo = (WorkspaceObject)objects[i];
try
{
String name = wo.Object_string;
User owner = (User) wo.Owning_user;
DateTime lastModified =wo.Last_mod_date;
Console.WriteLine(name + "\t" + owner.User_name + "\t" + lastModified.ToString());
}
catch (NotLoadedException e)
{
// Print out a message, and skip to the next item in the folder
// Could do a DataManagementService.getProperties call at this point
Console.WriteLine(e.Message);
Console.WriteLine("The Object Property Policy ($TC_DATA/soa/policies/Default.xml) is not configured with this property.");
}
}
}
private static void getUsers(ModelObject[] objects)
{
if(objects == null)
return;
DataManagementService dmService = DataManagementService.getService(Session.getConnection());
ArrayList unKnownUsers = new ArrayList();
for (int i = 0; i < objects.Length; i++)
{
if(!(objects[i] is WorkspaceObject ))
continue;
WorkspaceObject wo = (WorkspaceObject)objects[i];
User owner = null;
try
{
owner = (User) wo.Owning_user;
String userName = owner.User_name;
}
catch (NotLoadedException /*e*/)
{
if(owner != null)
unKnownUsers.Add(owner);
}
}
User[] users = new User[unKnownUsers.Count];
unKnownUsers.CopyTo( users );
String[] attributes = { "user_name" };
// *****************************
// Execute the service operation
// *****************************
dmService.GetProperties(users, attributes);
}
}
}

@ -0,0 +1,203 @@
using Eplan.EplApi.Base;
using KPlan.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Teamcenter.Services.Strong.Cad._2007_01.StructureManagement;
namespace KPlan.Forms.Bean {
public class CheckTableRowData {
public const string INDEX = "INDEX";
public const string CHECK = "CHECK";
public const string COUNT = "P_ARTICLEREF_COUNT";
public const string ITEMID = "P_ARTICLE_ERPNR";
public const string ORDERNR = "P_ARTICLE_ORDERNR";
public const string DEVICETAG = "P_FUNC_IDENTDEVICETAG";
private string title = "";
private XmlNode node2;
public bool checkOK = false;
public object[] rowData;
public string itemId;
public string orderNo;
public string itemUid;
public string deviceTag;
private List<XmlNode> nodeToCombine = new List<XmlNode>();
private bool itemExist;
public CheckTableRowData(string itemId,string orderNo, XmlNode node, bool itemExist, string itemUid) {
this.node2 = node;
if (!string.IsNullOrWhiteSpace(itemId)) {
this.itemId = itemId;
}
else {
this.itemId = GetPropValue(ITEMID, -1)?.ToString();
}
if (!string.IsNullOrWhiteSpace(orderNo)) {
this.orderNo = orderNo;
}
else {
this.orderNo = GetPropValue(ORDERNR, -1)?.ToString();
}
this.deviceTag = GetPropValue(DEVICETAG, -1)?.ToString();
this.itemExist = itemExist;
this.itemUid = itemUid;
}
public void addCombineNode(CheckTableRowData bean) {
if (bean.node2 != null) {
nodeToCombine.Add(bean.node2);
}
}
public bool CheckOK() {
return checkOK;
}
public override bool Equals(object obj) {
CheckTableRowData bean = obj as CheckTableRowData;
if (bean == null) { return false; }
if (!this.itemId.Equals(bean.itemId)){
return false;
}
if (this.deviceTag == null) {
return bean.deviceTag == null;
}
else {
return this.deviceTag.Equals(bean.deviceTag);
}
}
public object[] GetRowData(int index, List<string> config) {
int len = config.Count;
object[] res = new object[len];
/*if (len > 0) {
title = GetPropValue(config[0], index);
res[0] = this;
}*/
for (int i = 0; i < len; i++) {
res[i] = GetPropValue(config[i], index);
// KUtil.DispatcherShow(kCheckProject_Ex, "i:" + i + "config[i]:"+ config[i] + " res[i]:" + res[i]);
}
rowData = res;
return res;
}
public AttributesInfo[] GetBomProp(Dictionary<string, string> saveConfig) {
if (saveConfig == null) {
return null;
}
List<AttributesInfo> res = new List<AttributesInfo>();
foreach (string tc in saveConfig.Keys) {
string eplan = saveConfig[tc];
string val = GetPropValue(eplan,-1)?.ToString();
AttributesInfo info = new AttributesInfo();
info.Name = tc;
info.Value = val == null ? "" : val;
res.Add(info);
}
return res.ToArray();
}
private object GetPropValue(string config, int index) {
if (INDEX.Equals(config)) {
return index;
}
if (CHECK.Equals(config)) {
return Check();
}
if (COUNT.Equals(config)) {
return Count();
}
if (ITEMID.Equals(config)) {
return itemId;
}
if (ORDERNR.Equals(config)) {
return orderNo;
}
int ind = config.IndexOf('@');
string language = null;
if (ind > 0) {
language = config.Substring(ind + 1);
config = config.Substring(0, ind);
}
string val = null;
if (node2 != null) {
val = node2.Attributes[config]?.InnerText;
if (!KUtil.IsEmpty(val) && !KUtil.IsEmpty(language)) {
MultiLangString multiLangString = new MultiLangString();
multiLangString.SetAsString(val);
val = multiLangString.GetString((ISOCode.Language)Enum.Parse(typeof(ISOCode.Language), language));
}
}
//XmlAttribute attr = node.Attributes[config];
return val == null ? "" : val;
}
private string Count() {
if (node2 == null) {
return "";
}
double total = 0;
string refCount = node2.Attributes["P_ARTICLEREF_COUNT"]?.InnerText;
string lenth = node2.Attributes["P_ARTICLE_PARTIAL_LENGTH_VALUE"]?.InnerText;
if (KUtil.IsEmpty(lenth)) {
lenth = "1";
}
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;
total += drecord_num;
}
}
foreach(XmlNode node in nodeToCombine) {
refCount = node.Attributes["P_ARTICLEREF_COUNT"]?.InnerText;
lenth = node.Attributes["P_ARTICLE_PARTIAL_LENGTH_VALUE"]?.InnerText;
if (KUtil.IsEmpty(lenth)) {
lenth = "1";
}
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;
total += drecord_num;
}
}
}
return total.ToString();
}
private string Check() {
if (node2 != null) {
XmlAttribute discontinue = node2.Attributes["P_ARTICLE_DISCONTINUED"];//?.InnerText;
if (discontinue != null && !"0".Equals(discontinue.InnerText)) {
return "停产部件";
}
}
//string itemId = node.Attributes["P_ARTICLE_ERPNR"]?.InnerText;
//string itemId = erpAttr == null ? "" : erpAttr.Value;
if (itemExist) {
//if (TCUtil.ItemExist(itemId)) {
checkOK = true;
return "TC存在";
}
return "TC不存在";
}
public override string ToString() {
return title;
}
}
}

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KPlan.Forms.Bean {
class DuplicateOrderNrBean {
public string orderNr { get; set; }
public string partNr { get; set; }
public string manufacturer { get; set; }
public string reason = "TC中存在多个相同 Order Number 的物料";
}
}

@ -0,0 +1,36 @@
using Eplan.EplApi.Base;
using Eplan.EplApi.DataModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KPlan.Util;
namespace KPlan.Forms.Bean {
class EPlanPropBean {
public string disName { get; set; }
public string realName { get; set; }
public string type { get; set; }
public string language { get; set; }
public bool isComboReadOnly { get; set; }
public EPlanPropBean(string type) {
this.type = type;
this.isComboReadOnly = PropertyDefinition.PropertyType.MultilangString.ToString().Equals(type);
}
public string getConfigValue() {
if ("MultilangString".Equals(type)){
if (KUtil.IsEmpty(language)){
return "";
// throw new Exception("未选择语言环境:"+disName+"/"+realName+"/"+type);
}
return realName + "@" + language;
}
return realName;
}
}
}

@ -0,0 +1,67 @@
using Eplan.EplApi.MasterData;
using KPlan.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
namespace KPlan.Forms {
public class EPlanTreeItem : TreeViewItem {
public string object_string { get; set; }
public MDPart part { get; set; }
public bool isLoadMark = false;
public int groupId { get; set; }
/// <summary>
/// 分类用
/// </summary>
public MDPartsDatabaseItem.Enums.ProductGroup productGroup { get; set; }
public MDPartsDatabaseItem.Enums.ProductTopGroup productTopGroup { get; set; }
public bool isProductGroup = false;
public EPlanTreeItem() {
Header = "Loading";
isLoadMark = true;
}
public EPlanTreeItem(MDPart obj,string groupName) {
if (obj == null) {
Header = "Loading";
}
else {
this.part = obj;
this.object_string = this.part.PartNr;
Header = this.object_string;
Resources["ICON"] = TCUtil.GetIcon(groupName);
}
}
public EPlanTreeItem(MDPartsDatabaseItem.Enums.ProductTopGroup topGroup) {
this.groupId = (int)topGroup;
string header = MDPartsDatabaseItem.GetProductTopGroupName(topGroup);
if (KUtil.IsEmpty(header)) { header = topGroup.ToString(); }
Header = header;
Resources["ICON"] = new BitmapImage(new Uri("pack://application:,,,/EPLAN.EplAddin.KPlan;component/Resources_EPLAN/e_folder.png"));
}
public EPlanTreeItem(MDPartsDatabaseItem.Enums.ProductTopGroup topGroup,MDPartsDatabaseItem.Enums.ProductGroup group) {
this.groupId = (int)group;
this.productGroup = group;//分类用
this.productTopGroup = topGroup;
this.isProductGroup = true;
string header = MDPartsDatabaseItem.GetProductGroupName(group);
Header = header;
Resources["ICON"] = TCUtil.GetIcon(header);
}
public EPlanTreeItem(string header) {
Header = header;
Resources["ICON"] = new BitmapImage(new Uri("pack://application:,,,/EPLAN.EplAddin.KPlan;component/Resources_EPLAN/e_folder.png"));
}
}
}

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KPlan.Forms.Bean {
public class KPartSyncDataRow {
public int index { get; set; }
public string eplan_orderno { get; set; }
public string eplan_partno { get; set; }
public string eplan_erpno { get; set; }
public string eplan_name { get; set; }
public string eplan_desc { get; set; }
public string eplan_manufacturer { get; set; }
public string tc_itemid { get; set; }
public string tc_name { get; set; }
public string tc_revid { get; set; }
public string tc_desc { get; set; }
public string tc_manufacturer { get; set; }
public string tc_releasestatus { get; set; }
public string sync_status { get; set; }
public Eplan.EplApi.MasterData.MDPart part {get;set;}
public Teamcenter.Soa.Client.Model.Strong.ItemRevision rev { get; set; }
public override bool Equals(object obj) {
KPartSyncDataRow row = obj as KPartSyncDataRow;
if (row == null) {
return false;
}
if (this == obj) {
return true;
}
string partNr1 = eplan_partno == null ? "" : eplan_partno;
string partNr2 = row.eplan_partno == null ? "" : row.eplan_partno;
string itemId1 = tc_itemid == null ? "" : tc_itemid;
string itemId2 = row.tc_itemid == null ? "" : row.tc_itemid;
string rev1 = tc_revid == null ? "" : tc_revid;
string rev2 = row.tc_revid == null ? "" : row.tc_revid;
return partNr1.Equals(partNr2) && itemId1.Equals(itemId2) && rev1.Equals(rev2);
}
}
}

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Teamcenter.Soa.Client.Model;
namespace KPlan.Forms.Bean {
class ModelObjectBean {
public ModelObject mo { get; set; }
public string objectString { get; set; }
public ModelObjectBean(ModelObject mo,string objectString) {
this.mo = mo;
this.objectString = objectString;
}
public override string ToString() {
return objectString;
}
}
}

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KPlan.Forms.Bean {
class PartSyncClassConfigBean {
public string from { get; set; }
public string to { get; set; }
public override bool Equals(object obj) {
if (obj != null && obj.GetType() == typeof(PartSyncClassConfigBean)) {
PartSyncClassConfigBean b = (PartSyncClassConfigBean)obj;
if (from != null) {
return from.Equals(b.from);
}
}
return false;
}
}
}

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KPlan.Forms.Bean {
class PartSyncConfigBean {
public string from { get; set; }
public string to { get; set; }
public override bool Equals(object obj) {
if (obj != null && obj.GetType() == typeof(PartSyncConfigBean)) {
PartSyncConfigBean b = (PartSyncConfigBean)obj;
if (to != null) {
return to.Equals(b.to);
}
}
return false;
}
}
}

@ -0,0 +1,29 @@
using Eplan.EplApi.MasterData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KPlan.Forms {
class PartSyncDataRow {
public int index { get; set; }
public string partNr { get; set; }
public string name { get; set; }
public string itemID { get; set; }
public string itemName { get; set; }
public string itemRev { get; set; }
public string type { get; set; }
public string releaseStatus { get; set; }
public string syncStatus { get; set; }
public MDPart part { get; set; }
public Teamcenter.Soa.Client.Model.Strong.ItemRevision tcRev { get; set; }
public override bool Equals(object obj) {
if (partNr!= null&&obj.GetType() == typeof(PartSyncDataRow)) {
return partNr.Equals(((PartSyncDataRow)obj).partNr);
}
return false;
}
}
}

@ -0,0 +1,25 @@
using Eplan.EplApi.MasterData;
using KPlan.Forms.Bean;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KPlan.Forms {
public class SyncResult {
public SyncResult(KPartSyncDataRow dataRow) {
this.dataRow = dataRow;
}
public KPartSyncDataRow dataRow { get; set; }
public string partNr { get; set; }
public string orderNr { get; set; }
public string name { get; set; }
public string jldw { get; set; }
public string desc_cn { get; set; }
public string desc_en { get; set; }
public string reason { get; set; }
}
}

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KPlan.Forms.Bean {
class TCPropBean {
public string location { get; set; }
public string disName { get; set; }
public string realName { get; set; }
public string typeName { get; set; }
}
}

@ -0,0 +1,39 @@
using KPlan.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using Teamcenter.Soa.Client.Model;
namespace KPlan.Forms {
class TCTreeItem : TreeViewItem{
public ModelObject mo { get; set; }
public string object_string { get; set; }
public TCTreeItem(ModelObject obj) {
if (obj == null) {
Header = "Loading";
}
else {
this.mo = obj;
ModelObject[] objs = TCUtil.Refresh(mo);
TCUtil.GetProperties(false, objs, "object_string");
this.object_string = "[" + mo.SoaType.Name + "]" + mo.GetPropertyDisplayableValue("object_string");
Header = this.object_string;
Resources["ICON"] = new BitmapImage(new Uri("pack://application:,,,/EPLAN.EplAddin.KPlan;component/Resources/" + TCUtil.GetIconName(mo)));
}
}
public TCTreeItem(ModelObject mo, string folderName,string iconName) {
Header = folderName;
this.mo = mo;
Resources["ICON"] = new BitmapImage(new Uri("pack://application:,,,/EPLAN.EplAddin.KPlan;component/Resources/"+iconName));
}
}
}

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Teamcenter.Soa.Client.Model;
using KPlan.Util;
namespace KPlan.Forms {
class TableRowData {
private const string INDEX = "INDEX";
public ModelObject mo { get; set; }
private string title = "";
public TableRowData(ModelObject mo) {
this.mo = mo;
}
public object[] GetRowData(int index,List<string> config) {
int len = config.Count;
object[] res = new object[len];
if (len > 0) {
title = GetPropValue(mo, config[0], index);
res[0] = this;
}
for (int i = 1; i < len; i++) {
res[i] = GetPropValue(mo, config[i],index);
}
return res;
}
private string GetPropValue(ModelObject mo, string config, int index) {
if (INDEX.Equals(config)) {
return index + "";
}
return TCUtil.GetPropValue(mo, config);
}
public override string ToString() {
return title;
}
}
}

@ -0,0 +1,37 @@
<UserControl x:Class="KPlan.Forms.Config_Classification"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:KPlan.Forms"
mc:Ignorable="d"
UseLayoutRounding="True"
d:DesignHeight="450" d:DesignWidth="800" >
<Grid Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="0" Margin="5,0,5,5">
<GroupBox.Header>EPLAN元器件组</GroupBox.Header>
<TreeView Name="tree_Part_Groups" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MouseDoubleClick="Tree_Part_Groups_MouseDoubleClick" />
</GroupBox>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="1" Margin="0,0,5,5">
<GroupBox.Header>分类映射关系</GroupBox.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<DataGrid Grid.Row="0" CanUserAddRows="False" ItemsSource="{Binding}" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" HeadersVisibility="Column" Name="table_Class" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="200" ColumnHeaderHeight="25" RowHeight="23" CanUserResizeRows="False">
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True" Header="EPLAN组ID" Width="180" Binding="{Binding from}"/>
<DataGridTextColumn IsReadOnly="False" Header="TC分类ID" Width="180" Binding="{Binding to}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</GroupBox>
</Grid>
</UserControl>

@ -0,0 +1,105 @@
using Eplan.EplApi.MasterData;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
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 KPlan.Forms.Bean;
using KPlan.Util;
namespace KPlan.Forms {
/// <summary>
/// Interaction logic for Config_Classification.xaml
/// </summary>
public partial class Config_Classification : UserControl {
private ObservableCollection<PartSyncClassConfigBean> class_config = new ObservableCollection<PartSyncClassConfigBean>();
public Config_Classification() {
InitializeComponent();
this.table_Class.ItemsSource = class_config;
}
public void LoadPartGroups() {
EPlanTreeItem tree_home = new EPlanTreeItem("Parts");
tree_Part_Groups.Items.Add(tree_home);
Init_TopGroup(MDPartsDatabaseItem.Enums.ProductTopGroup.Electric, tree_home);
Init_TopGroup(MDPartsDatabaseItem.Enums.ProductTopGroup.Mechanic, tree_home);
Init_TopGroup(MDPartsDatabaseItem.Enums.ProductTopGroup.Fluid, tree_home);
Init_TopGroup(MDPartsDatabaseItem.Enums.ProductTopGroup.Process, tree_home);
Init_TopGroup(MDPartsDatabaseItem.Enums.ProductTopGroup.Invaild, tree_home);
Init_TopGroup(MDPartsDatabaseItem.Enums.ProductTopGroup.Undefined, tree_home);
this.Dispatcher.Invoke(new Action(delegate {
tree_home.IsExpanded = true;
}));
}
private void Init_TopGroup(MDPartsDatabaseItem.Enums.ProductTopGroup topGroup, EPlanTreeItem tree_home) {
EPlanTreeItem tree_TopGroup = new EPlanTreeItem(topGroup);
//KUtil.Log(tree_TopGroup.Header.ToString());
tree_home.Items.Add(tree_TopGroup);
//加载Group
MDPartsDatabaseItem.Enums.ProductGroup[] groups = MDPartsDatabaseItem.GetAvailableProductGroups(topGroup);
for (int i = 0; i < groups.Length; i++) {
MDPartsDatabaseItem.Enums.ProductGroup group = groups[i];
EPlanTreeItem tree_Group = new EPlanTreeItem(topGroup,group);
tree_TopGroup.Items.Add(tree_Group);
}
tree_TopGroup.Items.SortDescriptions.Add(new SortDescription("Header", ListSortDirection.Ascending));
tree_TopGroup.Items.Refresh();
}
public void SaveConfiguration() {
table_Class.Items.Refresh();
KUtil.ClearConfigSection(KConfigure.PART_SYNC_CLASSIFICATION);
//eplan to tc
Dictionary<string, string> classMap = new Dictionary<string, string>();
for (int i = 0; i < class_config.Count; i++) {
PartSyncClassConfigBean bean = class_config[i];
//KUtil.Log(bean.from+"->"+bean.to);
if (!KUtil.IsEmpty(bean.to) && !KUtil.IsEmpty(bean.from)) {
classMap.Add(bean.from, bean.to);
}
}
KUtil.SetConfigValue(KConfigure.PART_SYNC_CLASSIFICATION, classMap);
}
public void LoadConfiguration() {
Dictionary<string, string> eplan_to_tc = KUtil.GetConfigValue(KConfigure.PART_SYNC_CLASSIFICATION);
foreach (string key in eplan_to_tc.Keys) {
string val = eplan_to_tc[key];
//KUtil.Log(key + "->" + val);
if (!KUtil.IsEmpty(key) && !KUtil.IsEmpty(val)) {
PartSyncClassConfigBean bean = new PartSyncClassConfigBean() { from = key, to = val };
class_config.Add(bean);
}
}
}
private void Tree_Part_Groups_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
EPlanTreeItem selectedItem = tree_Part_Groups.SelectedItem as EPlanTreeItem;
if (selectedItem == null || !selectedItem.isProductGroup) {
return;
}
PartSyncClassConfigBean bean = new PartSyncClassConfigBean() { from = selectedItem.productTopGroup.ToString() + "." + selectedItem.productGroup.ToString() };
if (!class_config.Contains(bean)) {
class_config.Add(bean);
}
table_Class.Items.Refresh();
table_Class.SelectedItem = bean;
table_Class.ScrollIntoView(bean);
}
}
}

@ -0,0 +1,317 @@
<UserControl x:Class="KPlan.Forms.Config_Others"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:KPlan.Forms"
mc:Ignorable="d"
d:DesignHeight="2650" d:DesignWidth="800">
<ScrollViewer Background="White" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Grid.Row="0">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="0" Margin="5,5,5,5">
<GroupBox.Header>打开配置</GroupBox.Header>
<Grid Margin="4">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="70"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="查询名称" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_QueryName" Grid.Row="0" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="1" Grid.Column="0" Content="查询字段" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_QueryField" Grid.Row="1" Grid.Column="1" Height="70" Margin="0,2,0,8" TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto"/>
<Label Grid.Row="2" Grid.Column="0" Content="查询结果" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_QueryTable" Grid.Row="2" Grid.Column="1" Height="70" Margin="0,2,0,8" TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto"/>
<Label Grid.Row="3" Grid.Column="0" Content="查询框高度" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_QueryHeight" Grid.Row="3" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Grid Grid.Row="4" Grid.Column="1">
<TextBox Background="LightGray" FontSize="12"
Text="配置说明:打开功能的查询配置
&#x0a;查询名称:查询的名称
&#x0a;查询字段查询的字段格式显示名称1,查询字段名称1;显示名称2,查询字段名称2
&#x0a;--示例零组件ID,Item ID;名称,Name;类型,Type
&#x0a;查询结果查询结果表格定义格式列名称1,属性真实名称1,列宽1;列名称2,属性真实名称2,列宽2
&#x0a;--示例:序号,INDEX,50;ID,item_id,100;名称,object_name,150
&#x0a;查询框高度:默认显示的查询框高度"/>
</Grid>
</Grid>
</GroupBox>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1" Margin="5,5,5,5">
<GroupBox.Header>文件服务</GroupBox.Header>
<Grid Margin="4">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="70"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="服务地址" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_FMSUrl" Grid.Row="0" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="1" Grid.Column="0" Content="缓存路径" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_FMSTemp" Grid.Row="1" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Grid Grid.Row="2" Grid.Column="1">
<TextBox Background="LightGray" FontSize="12"
Text="配置说明:
&#x0a;服务地址FMS服务地址
&#x0a;--示例http://127.0.0.1:4544
&#x0a;缓存路径从Teamcenter下载文件的缓存路径
&#x0a;--示例D:\\FILE"/>
</Grid>
</Grid>
</GroupBox>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="2" Margin="5,5,5,5">
<GroupBox.Header>EPLAN数据</GroupBox.Header>
<Grid Margin="4">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="70"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="数据目录" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_EPLANData" Grid.Row="0" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Button Grid.Row="0" Grid.Column="2" Click="ChooseFolder_Button_Click" Width="25" Height="24" Content="..." HorizontalAlignment="Left" Margin="5,1,0,8"/>
<Label Grid.Row="1" Grid.Column="0" Content="上传跳过文件夹" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_EPLANDataSkip" Grid.Row="1" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="2" Grid.Column="0" Content="TC数据集UID" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_EPLANDataDsUid" Grid.Row="2" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="3" Grid.Column="0" Content="项目模板对象ID" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_TemplateItemID" Grid.Row="3" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="4" Grid.Column="0" Content="项目模板数据集类型" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_TemplateDatasetType" Grid.Row="4" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="5" Grid.Column="0" Content="打开项目解压目录" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_workspace" Grid.Row="5" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="6" Grid.Column="0" Content="压缩包内文件替换" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_en_cn" Grid.Row="6" Grid.Column="1" Height="100" Margin="0,2,0,8" TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto"/>
<Label Grid.Row="7" Grid.Column="0" Content="保留EPLAN__PARTS" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_keepzip" Grid.Row="7" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Grid Grid.Row="8" Grid.Column="1">
<TextBox Background="LightGray" FontSize="12"
Text="配置说明:
&#x0a;数据目录EPLAN数据文件上传功能上传的目录
&#x0a;上传跳过文件夹EPLAN数据文件上传功能上传时跳过的文件夹名称名称前加-,多个用;分隔。示例:-文件夹1;-文件夹2
&#x0a;TC数据集UIDEPLAN数据上传功能上传的目标数据集uid
&#x0a;模板对象ID新建项目存放项目模板的对象ID模板放在对象最新版本规范关系下
&#x0a;模板数据集类型:项目模板的数据集类型
&#x0a;打开项目解压目录从TC打开项目时项目的解压路径
&#x0a;压缩包内文件替换如果当前显示语言为中文替换EPLAN数据压缩包中英文名称为中文名称
&#x0a;--格式英文名称1=中文名称1;英文名称2=中文名称2
&#x0a;保留EPLAN_PARTS如配置TRUE保留下载TC数据至EPLAN功能中的临时文件"/>
</Grid>
</Grid>
</GroupBox>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="3" Margin="5,5,5,5">
<GroupBox.Header>TC部件查询</GroupBox.Header>
<Grid Margin="4">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="70"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="查询名称" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_Query_Part_Name" Grid.Row="0" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="1" Grid.Column="0" Content="Item ID字段" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_Query_Part_Field_ItemID" Grid.Row="1" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="2" Grid.Column="0" Content="PartNr字段" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_Query_Part_Field_PartNr" Grid.Row="2" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Grid Grid.Row="3" Grid.Column="1">
<TextBox Background="LightGray" FontSize="12" Text="配置说明配置从Teamcenter中查询相关对象的查询信息"/>
</Grid>
</Grid>
</GroupBox>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="4" Margin="5,5,5,5">
<GroupBox.Header>UI杂项</GroupBox.Header>
<Grid Margin="4">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="70"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="规格描述TC属性" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_UI_PROP_DESC" Grid.Row="0" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="1" Grid.Column="0" Content="制造商TC属性" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_UI_PROP_MANUFACTURER" Grid.Row="1" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Grid Grid.Row="2" Grid.Column="1">
<TextBox Background="LightGray" FontSize="12" Text="配置说明配置部件库同步功能中相关列的属性来源。格式示例ITEM.object_name"/>
</Grid>
</Grid>
</GroupBox>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="5" Margin="5,5,5,5">
<GroupBox.Header>编码申请</GroupBox.Header>
<Grid Margin="4">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="70"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="申请对象类型" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_BMSQ_TYPE" Grid.Row="0" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="1" Grid.Column="0" Content="行属性对象类型" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_BMSQ_ROWTYPE" Grid.Row="1" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="2" Grid.Column="0" Content="版本表单申请表属性" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_BMSQ_TABLE" Grid.Row="2" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="3" Grid.Column="0" Content="订货号属性" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_BMSQ_DHH" Grid.Row="3" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="4" Grid.Column="0" Content="Guid属性" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_BMSQ_GUID" Grid.Row="4" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="5" Grid.Column="0" Content="计量单位属性" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_BMSQ_JLDW" Grid.Row="5" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="6" Grid.Column="0" Content="描述(中文)属性" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_BMSQ_MSCN" Grid.Row="6" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="7" Grid.Column="0" Content="描述(英文)属性" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_BMSQ_MCEN" Grid.Row="7" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="8" Grid.Column="0" Content="存放文件夹首选项" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_BMSQ_PREF" Grid.Row="8" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="9" Grid.Column="0" Content="流程模板首选项" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_BMSQ_PROCESS" Grid.Row="9" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Grid Grid.Row="10" Grid.Column="1">
<TextBox Background="LightGray" FontSize="12" Text="配置说明:配置编码申请功能&#x0a;属性名称:直接填写属性的真实名称&#x0a;文件夹首选项配置首选项名称首选项中配置文件夹UID&#x0a;流程模板首选项:配置首选项名称,首选项中配置流程模板名称"/>
</Grid>
</Grid>
</GroupBox>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="6" Margin="5,5,5,5">
<GroupBox.Header>项目保存</GroupBox.Header>
<Grid Margin="4">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="70"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="检查结果表" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_Checktable" Grid.Row="0" Grid.Column="1" Height="100" Margin="0,2,0,8" TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto"/>
<Label Grid.Row="1" Grid.Column="0" Content="检查连接线" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_CheckWire" Grid.Row="1" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="2" Grid.Column="0" Content="保留Partlist文件" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_SaveAfterCheck" Grid.Row="2" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="3" Grid.Column="0" Content="BOM属性同步" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_bomprop" Grid.Row="3" Grid.Column="1" Height="100" Margin="0,2,0,8" TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto"/>
<Label Grid.Row="4" Grid.Column="0" Content="记录订货号属性" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_PropError" Grid.Row="4" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Grid Grid.Row="5" Grid.Column="1">
<TextBox Background="LightGray" FontSize="12"
Text="配置说明:
&#x0a;检测结果表:检查结果表格定义,[检查结果]列改名需要开发调整部分代码
&#x0a;--格式列名称1,导出文件属性名称1,列宽1;列名称2,导出文件属性名称2@语言,列宽2
&#x0a;--示例:序号,INDEX,50;检查结果,CHECK,80;ERP编码,P_ARTICLE_ERPNR,120;名称,P_ARTICLE_DESCR1@L_de_DE,120;
&#x0a;检查连接线配置TRUE将检查P_ARTICLE_PARTIAL_LENGTH_VALUE不为空的部件并将数量设置为该值x数量
&#x0a;BOM属性同步保存项目时同步BOM属性
&#x0a;--格式TCBOM属性名称1=数据文件属性名称1;TCBOM属性名称2=数据文件属性名称2"/>
</Grid>
</Grid>
</GroupBox>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="7" Margin="5,5,5,5">
<GroupBox.Header>引用功能</GroupBox.Header>
<Grid Margin="4">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="70"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="[bomtitle]" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_BomTitle" Grid.Row="0" Grid.Column="1" Height="100" Margin="0,2,0,8" TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto"/>
<Label Grid.Row="1" Grid.Column="0" Content="[erpcode]" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_erpcode" Grid.Row="1" Grid.Column="1" Height="100" Margin="0,2,0,8" TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto"/>
<Label Grid.Row="2" Grid.Column="0" Content="[linecount]" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_linecount" Grid.Row="2" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="3" Grid.Column="0" Content="[deleteXML]" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_deleteXML" Grid.Row="3" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<!--<Label Grid.Row="4" Grid.Column="0" Content="[PartLibItemID]" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_Database_ItemID" Grid.Row="4" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>
<Label Grid.Row="5" Grid.Column="0" Content="[PartLibUnzip]" HorizontalContentAlignment="Right"/>
<TextBox Name="tb_UnzipPath" Grid.Row="5" Grid.Column="1" Height="25" Margin="0,2,0,8" VerticalContentAlignment="Center"/>-->
<Grid Grid.Row="7" Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="27*"/>
<ColumnDefinition Width="190*"/>
</Grid.ColumnDefinitions>
<TextBox Background="LightGray" FontSize="12" Text="配置说明:从旧版本引用的功能配置,原多行属性需要用英文分号分隔行" Grid.ColumnSpan="2"/>
</Grid>
</Grid>
</GroupBox>
</Grid>
</ScrollViewer>
</UserControl>

@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
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.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using KPlan.Util;
namespace KPlan.Forms {
/// <summary>
/// Interaction logic for Config_Others.xaml
/// </summary>
public partial class Config_Others : System.Windows.Controls.UserControl {
public Config_Others() {
InitializeComponent();
}
public void SaveConfiguration() {
Dictionary<string, string> queryProjConfig = new Dictionary<string, string>();
queryProjConfig.Add(KConfigure.QUERY_PROJ_NAME, tb_QueryName.Text);
queryProjConfig.Add(KConfigure.QUERY_PROJ_FIELDS, tb_QueryField.Text);
queryProjConfig.Add(KConfigure.QUERY_PROJ_RESULTS, tb_QueryTable.Text);
queryProjConfig.Add(KConfigure.QUERY_PROJ_HEIGHT, tb_QueryHeight.Text);
KUtil.SetConfigValue(KConfigure.QUERY_PROJ_SECTION, queryProjConfig);
Dictionary<string, string> fmsConfig = new Dictionary<string, string>();
fmsConfig.Add(KConfigure.FMS_URL, tb_FMSUrl.Text);
fmsConfig.Add(KConfigure.FMS_PATH, tb_FMSTemp.Text);
KUtil.SetConfigValue(KConfigure.FMS_SECTION, fmsConfig);
Dictionary<string, string> edConfig = new Dictionary<string, string>();
edConfig.Add(KConfigure.EPLAN_DATA_FOLDER, tb_EPLANData.Text);
edConfig.Add(KConfigure.EPLAN_DATA_SKIP_FOLDER, tb_EPLANDataSkip.Text);
edConfig.Add(KConfigure.EPLAN_DATASET_UID, tb_EPLANDataDsUid.Text);
edConfig.Add(KConfigure.EPLAN_TEMPLATE_ITEM_ID, tb_TemplateItemID.Text);
edConfig.Add(KConfigure.EPLAN_TEMPLATE_DATASET_TYPE, tb_TemplateDatasetType.Text);
edConfig.Add(KConfigure.EPLAN_WORKSAPCE, tb_workspace.Text);
edConfig.Add(KConfigure.EPLAN_EN_TO_CN, tb_en_cn.Text);
edConfig.Add(KConfigure.EPLAN_KEEP_ZIP, tb_keepzip.Text);
KUtil.SetConfigValue(KConfigure.EPLAN_DATA_SECTION, edConfig);
Dictionary<string, string> partQueryConfig = new Dictionary<string, string>();
partQueryConfig.Add(KConfigure.PART_QUERY_NAME, tb_Query_Part_Name.Text);
partQueryConfig.Add(KConfigure.PART_QUERY_ITEM_ID, tb_Query_Part_Field_ItemID.Text);
partQueryConfig.Add(KConfigure.PART_QUERY_ORDERNR, tb_Query_Part_Field_PartNr.Text);
KUtil.SetConfigValue(KConfigure.PART_QUERY_SECTION, partQueryConfig);
Dictionary<string, string> uiConfig = new Dictionary<string, string>();
uiConfig.Add(KConfigure.UI_PROP_DESC, tb_UI_PROP_DESC.Text);
uiConfig.Add(KConfigure.UI_PROP_MANUFACTURER, tb_UI_PROP_MANUFACTURER.Text);
KUtil.SetConfigValue(KConfigure.UI_SOME_SECTION, uiConfig);
Dictionary<string, string> bmsqConfig = new Dictionary<string, string>();
bmsqConfig.Add(KConfigure.BMSQ_ITEMTYPE, tb_BMSQ_TYPE.Text);
bmsqConfig.Add(KConfigure.BMSQ_ROWTYPE, tb_BMSQ_ROWTYPE.Text);
bmsqConfig.Add(KConfigure.BMSQ_TABLE, tb_BMSQ_TABLE.Text);
bmsqConfig.Add(KConfigure.BMSQ_ORDERNR, tb_BMSQ_DHH.Text);
bmsqConfig.Add(KConfigure.BMSQ_GUID, tb_BMSQ_GUID.Text);
bmsqConfig.Add(KConfigure.BMSQ_UNIT, tb_BMSQ_JLDW.Text);
bmsqConfig.Add(KConfigure.BMSQ_DESC_CN, tb_BMSQ_MSCN.Text);
bmsqConfig.Add(KConfigure.BMSQ_DESC_EN, tb_BMSQ_MCEN.Text);
bmsqConfig.Add(KConfigure.BMSQ_POSITION_PREF, tb_BMSQ_PREF.Text);
bmsqConfig.Add(KConfigure.BMSQ_PROCESS_TEMPLATE, tb_BMSQ_PROCESS.Text);
KUtil.SetConfigValue(KConfigure.BMSQ_SECTION, bmsqConfig);
Dictionary<string, string> checkConfig = new Dictionary<string, string>();
checkConfig.Add(KConfigure.CHECK_TITLE, tb_Checktable.Text);
checkConfig.Add(KConfigure.CHECK_WIRE, tb_CheckWire.Text);
checkConfig.Add(KConfigure.CHECK_SAVEXML, tb_SaveAfterCheck.Text);
checkConfig.Add(KConfigure.SAVE_BOM_PROP, tb_bomprop.Text);
checkConfig.Add(KConfigure.ERROR_ARRAY_PROP, tb_PropError.Text);
KUtil.SetConfigValue(KConfigure.CHECK_SECTION, checkConfig);
Dictionary<string, string> refConfig = new Dictionary<string, string>();
refConfig.Add(KConfigure.REF_BOM_TITILE, tb_BomTitle.Text);
refConfig.Add(KConfigure.REF_ERPCODE, tb_erpcode.Text);
refConfig.Add(KConfigure.REF_LINECOUNT, tb_linecount.Text);
refConfig.Add(KConfigure.REF_DELETEXML, tb_deleteXML.Text);
//refConfig.Add(KConfigure.REF_DATABSE_ITEMID, tb_Database_ItemID.Text);
//refConfig.Add(KConfigure.REF_UNZIP_PATH, tb_UnzipPath.Text);
//refConfig.Add(KConfigure.REF_BOM_PROPS, tb_bomprop.Text);
KUtil.SetConfigValue(KConfigure.REF_SECTION, refConfig);
}
public void LoadConfiguration() {
//读取查询项目配置
tb_QueryName.Text = KUtil.GetConfigValue(KConfigure.QUERY_PROJ_SECTION, KConfigure.QUERY_PROJ_NAME);
tb_QueryField.Text = KUtil.GetConfigValue(KConfigure.QUERY_PROJ_SECTION, KConfigure.QUERY_PROJ_FIELDS);
tb_QueryTable.Text = KUtil.GetConfigValue(KConfigure.QUERY_PROJ_SECTION, KConfigure.QUERY_PROJ_RESULTS);
tb_QueryHeight.Text = KUtil.GetConfigValue(KConfigure.QUERY_PROJ_SECTION, KConfigure.QUERY_PROJ_HEIGHT);
//FMS配置
tb_FMSUrl.Text = KUtil.GetConfigValue(KConfigure.FMS_SECTION, KConfigure.FMS_URL);
tb_FMSTemp.Text = KUtil.GetConfigValue(KConfigure.FMS_SECTION, KConfigure.FMS_PATH);
//EPLAN数据配置
tb_EPLANData.Text = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_DATA_FOLDER);
tb_EPLANDataSkip.Text = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_DATA_SKIP_FOLDER);
tb_EPLANDataDsUid.Text = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_DATASET_UID);
tb_TemplateItemID.Text = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_TEMPLATE_ITEM_ID);
tb_TemplateDatasetType.Text = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_TEMPLATE_DATASET_TYPE);
tb_workspace.Text = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_WORKSAPCE);
tb_en_cn.Text = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_EN_TO_CN);
tb_keepzip.Text = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_KEEP_ZIP);
//Part查询
tb_Query_Part_Name.Text = KUtil.GetConfigValue(KConfigure.PART_QUERY_SECTION, KConfigure.PART_QUERY_NAME);
tb_Query_Part_Field_ItemID.Text = KUtil.GetConfigValue(KConfigure.PART_QUERY_SECTION, KConfigure.PART_QUERY_ITEM_ID);
tb_Query_Part_Field_PartNr.Text = KUtil.GetConfigValue(KConfigure.PART_QUERY_SECTION, KConfigure.PART_QUERY_ORDERNR);
//UI杂项
tb_UI_PROP_DESC.Text = KUtil.GetConfigValue(KConfigure.UI_SOME_SECTION, KConfigure.UI_PROP_DESC);
tb_UI_PROP_MANUFACTURER.Text = KUtil.GetConfigValue(KConfigure.UI_SOME_SECTION, KConfigure.UI_PROP_MANUFACTURER);
//编码申请
tb_BMSQ_TYPE.Text = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_ITEMTYPE);
tb_BMSQ_ROWTYPE.Text = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_ROWTYPE);
tb_BMSQ_TABLE.Text = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_TABLE);
tb_BMSQ_DHH.Text = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_ORDERNR);
tb_BMSQ_GUID.Text = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_GUID);
tb_BMSQ_JLDW.Text = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_UNIT);
tb_BMSQ_MSCN.Text = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_DESC_CN);
tb_BMSQ_MCEN.Text = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_DESC_EN);
tb_BMSQ_PREF.Text = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_POSITION_PREF);
tb_BMSQ_PROCESS.Text = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_PROCESS_TEMPLATE);
//检查
tb_Checktable.Text = KUtil.GetConfigValue(KConfigure.CHECK_SECTION, KConfigure.CHECK_TITLE);
tb_CheckWire.Text = KUtil.GetConfigValue(KConfigure.CHECK_SECTION, KConfigure.CHECK_WIRE);
tb_SaveAfterCheck.Text = KUtil.GetConfigValue(KConfigure.CHECK_SECTION, KConfigure.CHECK_SAVEXML);
tb_bomprop.Text = KUtil.GetConfigValue(KConfigure.CHECK_SECTION, KConfigure.SAVE_BOM_PROP);
tb_PropError.Text = KUtil.GetConfigValue(KConfigure.CHECK_SECTION, KConfigure.ERROR_ARRAY_PROP);
//引用功能
tb_BomTitle.Text = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_BOM_TITILE);
tb_erpcode.Text = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_ERPCODE);
tb_linecount.Text = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_LINECOUNT);
tb_deleteXML.Text = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_DELETEXML);
//tb_Database_ItemID.Text = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_DATABSE_ITEMID);
//tb_UnzipPath.Text = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_UNZIP_PATH);
//tb_bomprop.Text = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_BOM_PROPS);
}
private void ChooseFolder_Button_Click(object sender, RoutedEventArgs e) {
FolderBrowserDialog fb = new FolderBrowserDialog();
fb.RootFolder = Environment.SpecialFolder.Desktop;
fb.Description = "选择EPLAN数据文件夹";
if (fb.ShowDialog() == DialogResult.OK) {
tb_EPLANData.Text = fb.SelectedPath;
}
}
}
}

@ -0,0 +1,209 @@
<Grid x:Class="KPlan.Forms.Config_PartSync"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:KPlan.Forms"
mc:Ignorable="d"
UseLayoutRounding="True"
d:DesignHeight="450" d:DesignWidth="900" MinWidth="900" MinHeight="500">
<Grid Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--顶栏 类型和id映射-->
<Grid Grid.Row="0" Margin="15,10,5,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="对象类型" HorizontalContentAlignment="Right"/>
<TextBox Grid.Column="1" Name="tb_ObjectType" VerticalContentAlignment="Center" KeyDown="Tb_ObjectType_KeyDown"/>
<Button Grid.Column="2" Content="确定" Height="24" Width="60" Margin="5,0,15,0" Click="ChangeType_Button_Click"/>
<Label Grid.Column="3" Content=" ERP编码在TC中的属性"/>
<TextBox Grid.Column="4" Name="tb_OrderNr_Prop" VerticalContentAlignment="Center"/>
<!--<Label Grid.Column="5" Content=" Item ID映射属性"/>
<TextBox Grid.Column="6" Name="tb_ItemID_Prop" VerticalContentAlignment="Center"/>-->
</Grid>
<!--映射组-->
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!--TC属性-->
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="0" Margin="5,0,5,5">
<GroupBox.Header>Teamcenter</GroupBox.Header>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--搜索框-->
<Grid Grid.Row="0" Margin="5,3,5,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<ComboBox Grid.Column="0" x:Name="cb_Location" Width="85" Height="24" Margin="0,1" SelectionChanged="Cb_Location_SelectionChanged"/>
<TextBox Grid.Column="2" Name="tb_TCProp" VerticalContentAlignment="Center" KeyDown="Tb_TCProp_KeyDown" />
<Button Grid.Column="4" Click="Find_TC_PropButton_Click" Content="筛选" Width="60" Height="24" Margin="0,1"/>
</Grid>
<DataGrid Grid.Row="1" ItemsSource="{Binding}" SelectionChanged="PropTable_SelectionChanged" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" HeadersVisibility="Column" IsReadOnly="True" Name="table_TC_Prop" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="200" ColumnHeaderHeight="25" RowHeight="23" CanUserResizeRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="显示名称" Width="150" Binding="{Binding disName}"/>
<DataGridTextColumn Header="真实名称" Width="150" Binding="{Binding realName}"/>
<DataGridTextColumn Header="所在类型" Width="120" Binding="{Binding typeName}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</GroupBox>
<!--eplan属性-->
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="1" Margin="5,0,5,5">
<GroupBox.Header>Eplan</GroupBox.Header>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--搜索框-->
<Grid Grid.Row="0" Margin="5,3,5,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Name="tb_EPlanProp" VerticalContentAlignment="Center" KeyDown="Tb_EPlanProp_KeyDown"/>
<Button Grid.Column="2" Content="筛选" Width="60" Height="24" Margin="0,1" Click="Find_EPlan_Prop_Button_Click"/>
</Grid>
<DataGrid Grid.Row="1" ItemsSource="{Binding}" SelectionChanged="PropTable_SelectionChanged" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" HeadersVisibility="Column" Name="table_Eplan_Prop" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="200" ColumnHeaderHeight="25" RowHeight="23" CanUserResizeRows="False">
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True" Header="显示名称" Width="150" Binding="{Binding disName}"/>
<DataGridTextColumn IsReadOnly="True" Header="真实名称" Width="150" Binding="{Binding realName}"/>
<DataGridTextColumn IsReadOnly="True" Header="类型" Width="120" Binding="{Binding type}"/>
<DataGridComboBoxColumn x:Name="col_language" IsReadOnly="False" Header="语言环境" Width="100" SelectedItemBinding="{Binding language}" >
<DataGridComboBoxColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="IsEnabled" Value="{Binding isComboReadOnly}" />
</Style>
</DataGridComboBoxColumn.CellStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}">
<EventSetter Event="SelectionChanged" Handler="COL_ComboBox_SelectionChanged" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</GroupBox>
<!--映射关系-->
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="2" Margin="5,0,5,5">
<GroupBox.Header>映射关系</GroupBox.Header>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--搜索框-->
<Grid Grid.Row="0" Margin="5,3,5,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Content="双向添加" Width="80" Height="24" Margin="0,1" Click="Add_All_Button_Click"/>
<Button Grid.Column="2" Content="清空所有" Width="80" Height="24" Margin="0,1" Click="Clear_All_Button_Click"/>
</Grid>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1">
<GroupBox.Header>Eplan to TC</GroupBox.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<DataGrid Grid.Row="0" ItemsSource="{Binding}" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" HeadersVisibility="Column" IsReadOnly="True" Name="table_EPLAN_TO_TC" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="200" ColumnHeaderHeight="25" RowHeight="23" CanUserResizeRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="From" Width="150" Binding="{Binding from}"/>
<DataGridTextColumn Header="To" Width="150" Binding="{Binding to}"/>
</DataGrid.Columns>
</DataGrid>
<Grid Grid.Row="1" Margin="0,5,0,0" Height="25">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Click="EPLAN_TO_TC_ADD_Button_Click" Content="+" Width="25" Height="25" Margin="0,0,5,0"/>
<Button Grid.Column="1" Content="-" Click="EPLAN_TO_TC_REMOVE_Button_Click" Width="25" Height="25" Margin="0,0,5,0"/>
<Button Grid.Column="2" Click="EPLAN_TO_TC_MODIFY_Button_Click" Width="25" Height="25" Margin="0,0,5,0">
<Image Source="/EPLAN.EplAddin.KPlan;component/Resources/edit_16.png" Stretch="None" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Button>
<TextBox Grid.Column="3" Name="tb_EPLAN_TO_TC_eplan" VerticalContentAlignment="Center"/>
<Label Grid.Column="4" Content="to"/>
<TextBox Grid.Column="5" Name="tb_EPLAN_TO_TC_tc" VerticalContentAlignment="Center"/>
</Grid>
</Grid>
</GroupBox>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="2">
<GroupBox.Header>TC to Eplan</GroupBox.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<DataGrid Grid.Row="0" ItemsSource="{Binding}" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" HeadersVisibility="Column" IsReadOnly="True" Name="table_TC_TO_EPLAN" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="200" ColumnHeaderHeight="25" RowHeight="23" CanUserResizeRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="From" Width="150" Binding="{Binding from}"/>
<DataGridTextColumn Header="To" Width="150" Binding="{Binding to}"/>
</DataGrid.Columns>
</DataGrid>
<Grid Grid.Row="1" Margin="0,5,0,0" Height="25">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Content="+" Click="TC_TO_EPLAN_ADD_Button_Click" Width="25" Height="25" Margin="0,0,5,0"/>
<Button Grid.Column="1" Content="-" Click="TC_TO_EPLAN_REMOVE_Button_Click" Width="25" Height="25" Margin="0,0,5,0"/>
<Button Grid.Column="2" Click="TC_TO_EPLAN_MODIFY_Button_Click" Width="25" Height="25" Margin="0,0,5,0">
<Image Source="/EPLAN.EplAddin.KPlan;component/Resources/edit_16.png" Stretch="None" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Button>
<TextBox Grid.Column="3" Name="tb_TC_TO_EPLAN_tc" VerticalContentAlignment="Center"/>
<Label Grid.Column="4" Content="to"/>
<TextBox Grid.Column="5" Name="tb_TC_TO_EPLAN_eplan" VerticalContentAlignment="Center"/>
</Grid>
</Grid>
</GroupBox>
</Grid>
</GroupBox>
</Grid>
</Grid>
</Grid>

@ -0,0 +1,369 @@
using System;
using System.Collections.Generic;
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 KPlan.Util;
using KPlan.Forms.Bean;
using System.Collections.ObjectModel;
using Eplan.EplApi.MasterData;
using Eplan.EplApi.Base;
namespace KPlan.Forms {
/// <summary>
/// Interaction logic for Config_PartSync.xaml
/// </summary>
public partial class Config_PartSync : Grid {
private string loadedType;
private List<EPlanPropBean> ePlanPropBeanList = new List<EPlanPropBean>();
private ObservableCollection<EPlanPropBean> ePlanPropBeanData = new ObservableCollection<EPlanPropBean>();
private ObservableCollection<TCPropBean> tcPropBeanData = new ObservableCollection<TCPropBean>();
private ObservableCollection<PartSyncConfigBean> eplan_to_tc_config = new ObservableCollection<PartSyncConfigBean>();
private ObservableCollection<PartSyncConfigBean> tc_to_eplan_config = new ObservableCollection<PartSyncConfigBean>();
private Dictionary<string, List<TCPropBean>> tcPropMap = new Dictionary<string, List<TCPropBean>>();
public ObservableCollection<string> language_list = new ObservableCollection<string>();
public Config_PartSync() {
InitializeComponent();
ReadEplanProperty();
table_Eplan_Prop.ItemsSource = ePlanPropBeanData;
table_TC_Prop.ItemsSource = tcPropBeanData;
table_EPLAN_TO_TC.ItemsSource = eplan_to_tc_config;
table_TC_TO_EPLAN.ItemsSource = tc_to_eplan_config;
string[] ENUM_LANGUAGES = Enum.GetNames(typeof(ISOCode.Language));
Array.Sort(ENUM_LANGUAGES);
foreach (string l in ENUM_LANGUAGES) {
language_list.Add(l);
}
col_language.ItemsSource = language_list;
try {
string itemTypeName = KUtil.GetConfigValue(KConfigure.PART_SYNC_SECTION, KConfigure.PART_SYNC_TC_ITEM_TYPE);
TCUtil.GetDefinedProperties(itemTypeName);
ReadTcProperty(itemTypeName);
}
catch (System.Exception ex) {
KUtil.LogErr(ex);
//MessageBox.Show("加载数据出错:" + ex.Message);
}
}
private void ChangeType() {
string newType = tb_ObjectType.Text;
if (KUtil.IsEmpty(newType)) {
MessageBox.Show("请输入对象类型");
return;
}
if (newType.Equals(loadedType)) {
return;
}
MessageBoxResult res = MessageBox.Show("重新加载对象类型将清空当前映射配置,是否继续?", "", MessageBoxButton.YesNo);
if (res != MessageBoxResult.Yes) {
return;
}
//清空
ClearPropConfig();
//加载TC属性
ReadTcProperty(newType);
loadedType = newType;
}
private void ReadTcProperty(string itemTypeName) {
tcPropBeanData.Clear();
cb_Location.Items.Clear();
cb_Location.Items.Add("");
this.tcPropMap = TCUtil.GetDefinedProperties(itemTypeName);
foreach (string key in tcPropMap.Keys) {
cb_Location.Items.Add(key);
List<TCPropBean> list = tcPropMap[key];
foreach (TCPropBean b in list) {
tcPropBeanData.Add(b);
}
}
}
private void ReadEplanProperty() {
ePlanPropBeanList.Clear();
ePlanPropBeanData.Clear();
Eplan.EplApi.DataModel.AnyPropertyId[] props = Eplan.EplApi.DataModel.Properties.AllArticlePropIDs;
for (int i = 0; i < props.Length; i++) {
Eplan.EplApi.DataModel.AnyPropertyId prop = props[i];
//MessageBox.Show("disName:"+ prop.Definition.Name+ " realName:"+ prop.AsArticle.ToString());
if (prop.Definition.IsReadOnly) {
continue;
}
EPlanPropBean bean = new EPlanPropBean(prop.Definition.Type.ToString()) { disName = prop.Definition.Name, realName = prop.AsArticle.ToString() };
ePlanPropBeanList.Add(bean);
ePlanPropBeanData.Add(bean);
}
}
private void ClearPropConfig() {
eplan_to_tc_config.Clear();
tc_to_eplan_config.Clear();
}
private void Remove_Config(DataGrid dataGrid, ObservableCollection<PartSyncConfigBean> data) {
try {
System.Collections.IList selectedItems = dataGrid.SelectedItems;
if (selectedItems == null || selectedItems.Count == 0) {
return;
}
while (selectedItems.Count > 0) {
data.Remove((PartSyncConfigBean)selectedItems[0]);
dataGrid.Items.Refresh();
}
dataGrid.Items.Refresh();
}
catch (System.Exception ex) {
KUtil.LogErr(ex);
MessageBox.Show(ex.Message);
}
}
private void Modify_Config(DataGrid dataGrid, ObservableCollection<PartSyncConfigBean> data, string from, string to) {
if (KUtil.IsEmpty(from) || KUtil.IsEmpty(to)) {
return;
}
PartSyncConfigBean selectedBean = dataGrid.SelectedItem as PartSyncConfigBean;
if (selectedBean == null) {
return;
}
int existInd = data.IndexOf(new PartSyncConfigBean() { from = from, to = to });
if (existInd >= 0 && !to.Equals(selectedBean.to)) {
MessageBox.Show("已存在属性映射到"+to);
return;
}
//PartSyncConfigBean bean = (PartSyncConfigBean)dataGrid.Items[ind];
selectedBean.from = from;
selectedBean.to = to;
dataGrid.Items.Refresh();
dataGrid.SelectedItem = selectedBean;
}
private void Add_Config(DataGrid dataGrid, ObservableCollection<PartSyncConfigBean> data, string from, string to) {
if (KUtil.IsEmpty(from) || KUtil.IsEmpty(to)) {
return;
}
PartSyncConfigBean bean = new PartSyncConfigBean() { from = from, to = to };
if (!data.Contains(bean)) {
data.Add(bean);
}
dataGrid.SelectedItem = bean;
dataGrid.ScrollIntoView(bean);
}
private void Read_Prop_Refection_to_Textbox() {
EPlanPropBean eplanBean = table_Eplan_Prop.SelectedItem as EPlanPropBean;
TCPropBean tcBean = table_TC_Prop.SelectedItem as TCPropBean;
string eplanConfig = "";
string tcConfig = "";
if (eplanBean != null) {
eplanConfig = eplanBean.getConfigValue();
}
if (tcBean != null) {
tcConfig = tcBean.location + "." + tcBean.realName;
}
tb_TC_TO_EPLAN_tc.Text = tcConfig;
tb_TC_TO_EPLAN_eplan.Text = eplanConfig;
tb_EPLAN_TO_TC_eplan.Text = eplanConfig;
tb_EPLAN_TO_TC_tc.Text = tcConfig;
}
private void Find_TC_Props() {
string text = tb_TCProp.Text;
string type = cb_Location.SelectedItem as string;
tcPropBeanData.Clear();
if (KUtil.IsEmpty(type) && KUtil.IsEmpty(text)) {
foreach (List<TCPropBean> list in tcPropMap.Values) {
foreach (TCPropBean b in list) {
tcPropBeanData.Add(b);
}
}
}
else {
text = text.ToLower();
foreach (List<TCPropBean> list in tcPropMap.Values) {
foreach (TCPropBean b in list) {
if (KUtil.RegexMatch(b.disName.ToLower(), text) || KUtil.RegexMatch(b.realName.ToLower(), text)) {
//if (b.disName.ToLower().Contains(text) || b.realName.ToLower().Contains(text)) {
if (KUtil.IsEmpty(type) || b.typeName.Equals(type)) {
tcPropBeanData.Add(b);
}
}
}
}
}
}
private void Find_EPlan_Props() {
string text = tb_EPlanProp.Text;
ePlanPropBeanData.Clear();
if (KUtil.IsEmpty(text)) {
foreach (EPlanPropBean bean in ePlanPropBeanList) {
ePlanPropBeanData.Add(bean);
}
}
else {
text = text.ToLower();
foreach (EPlanPropBean bean in ePlanPropBeanList) {
if (KUtil.RegexMatch(bean.disName.ToLower(), text) || KUtil.RegexMatch(bean.realName.ToLower(), text)) {
//if (bean.disName.ToLower().Contains(text) || bean.realName.ToLower().Contains(text)) {
ePlanPropBeanData.Add(bean);
}
}
}
}
public void SaveConfiguration() {
Dictionary<string, string> syncConfig = new Dictionary<string, string>();
syncConfig.Add(KConfigure.PART_SYNC_TC_ITEM_TYPE, tb_ObjectType.Text);
syncConfig.Add(KConfigure.PART_SYNC_OrderNr_TC, tb_OrderNr_Prop.Text);
//syncConfig.Add(KConfigure.PART_SYNC_ItemID_EPlan, tb_ItemID_Prop.Text);
KUtil.SetConfigValue(KConfigure.PART_SYNC_SECTION, syncConfig);
KUtil.ClearConfigSection(KConfigure.PART_SYNC_EPLAN_TO_TC_SECTION);
KUtil.ClearConfigSection(KConfigure.PART_SYNC_TC_TO_EPLAN_SECTION);
//eplan to tc
Dictionary<string, string> eplan_to_tc = new Dictionary<string, string>();
for(int i=0;i< eplan_to_tc_config.Count;i++) {
PartSyncConfigBean bean = eplan_to_tc_config[i];
eplan_to_tc.Add(bean.to, bean.from);
}
KUtil.SetConfigValue(KConfigure.PART_SYNC_EPLAN_TO_TC_SECTION, eplan_to_tc);
//tc to eplan
Dictionary<string, string> tc_to_eplan = new Dictionary<string, string>();
for(int i = 0; i < tc_to_eplan_config.Count; i++) {
PartSyncConfigBean bean = tc_to_eplan_config[i];
tc_to_eplan.Add(bean.to, bean.from);
}
KUtil.SetConfigValue(KConfigure.PART_SYNC_TC_TO_EPLAN_SECTION, tc_to_eplan);
}
public void LoadConfiguration() {
this.loadedType = KUtil.GetConfigValue(KConfigure.PART_SYNC_SECTION, KConfigure.PART_SYNC_TC_ITEM_TYPE);
tb_ObjectType.Text = this.loadedType;
tb_OrderNr_Prop.Text = KUtil.GetConfigValue(KConfigure.PART_SYNC_SECTION, KConfigure.PART_SYNC_OrderNr_TC);
//tb_ItemID_Prop.Text = KUtil.GetConfigValue(KConfigure.PART_SYNC_SECTION, KConfigure.PART_SYNC_ItemID_EPlan);
//eplan to tc
Dictionary<string, string> eplan_to_tc = KUtil.GetConfigValue(KConfigure.PART_SYNC_EPLAN_TO_TC_SECTION);
foreach(string key in eplan_to_tc.Keys) {
PartSyncConfigBean bean = new PartSyncConfigBean() { from=eplan_to_tc[key],to = key };
eplan_to_tc_config.Add(bean);
}
//tc to eplan
Dictionary<string, string> tc_to_eplan = KUtil.GetConfigValue(KConfigure.PART_SYNC_TC_TO_EPLAN_SECTION);
foreach(string key in tc_to_eplan.Keys) {
PartSyncConfigBean bean = new PartSyncConfigBean() { from = tc_to_eplan[key], to = key };
tc_to_eplan_config.Add(bean);
}
}
private void Find_EPlan_Prop_Button_Click(object sender, RoutedEventArgs e) {
Find_EPlan_Props();
}
private void Tb_EPlanProp_KeyDown(object sender, KeyEventArgs e) {
if (e.Key == Key.Return) {
Find_EPlan_Props();
}
}
private void Find_TC_PropButton_Click(object sender, RoutedEventArgs e) {
Find_TC_Props();
}
private void Tb_TCProp_KeyDown(object sender, KeyEventArgs e) {
if (e.Key == Key.Return) {
Find_TC_Props();
}
}
private void ChangeType_Button_Click(object sender, RoutedEventArgs e) {
try {
ChangeType();
}
catch (System.Exception ex) {
KUtil.LogErr(ex);
MessageBox.Show("加载数据出错:" + ex.Message);
}
}
private void Tb_ObjectType_KeyDown(object sender, KeyEventArgs e) {
if (e.Key == Key.Return) {
try {
ChangeType();
}
catch (System.Exception ex) {
KUtil.LogErr(ex);
MessageBox.Show("加载数据出错:" + ex.Message);
}
}
}
private void Cb_Location_SelectionChanged(object sender, SelectionChangedEventArgs e) {
Find_TC_Props();
}
private void PropTable_SelectionChanged(object sender, SelectionChangedEventArgs e) {
Read_Prop_Refection_to_Textbox();
}
private void EPLAN_TO_TC_ADD_Button_Click(object sender, RoutedEventArgs e) {
Add_Config(table_EPLAN_TO_TC, eplan_to_tc_config, tb_EPLAN_TO_TC_eplan.Text, tb_EPLAN_TO_TC_tc.Text);
}
private void TC_TO_EPLAN_ADD_Button_Click(object sender, RoutedEventArgs e) {
Add_Config(table_TC_TO_EPLAN, tc_to_eplan_config, tb_TC_TO_EPLAN_tc.Text, tb_TC_TO_EPLAN_eplan.Text);
}
private void EPLAN_TO_TC_REMOVE_Button_Click(object sender, RoutedEventArgs e) {
Remove_Config(table_EPLAN_TO_TC, eplan_to_tc_config);
}
private void TC_TO_EPLAN_REMOVE_Button_Click(object sender, RoutedEventArgs e) {
Remove_Config(table_TC_TO_EPLAN, tc_to_eplan_config);
}
private void EPLAN_TO_TC_MODIFY_Button_Click(object sender, RoutedEventArgs e) {
Modify_Config(table_EPLAN_TO_TC, eplan_to_tc_config, tb_EPLAN_TO_TC_eplan.Text, tb_EPLAN_TO_TC_tc.Text);
}
private void TC_TO_EPLAN_MODIFY_Button_Click(object sender, RoutedEventArgs e) {
Modify_Config(table_TC_TO_EPLAN, tc_to_eplan_config, tb_TC_TO_EPLAN_tc.Text, tb_TC_TO_EPLAN_eplan.Text);
}
private void Clear_All_Button_Click(object sender, RoutedEventArgs e) {
MessageBoxResult res = MessageBox.Show("确认清空?", "", MessageBoxButton.YesNo);
if (res != MessageBoxResult.Yes) {
return;
}
ClearPropConfig();
}
private void Add_All_Button_Click(object sender, RoutedEventArgs e) {
Add_Config(table_EPLAN_TO_TC, eplan_to_tc_config, tb_EPLAN_TO_TC_eplan.Text, tb_EPLAN_TO_TC_tc.Text);
Add_Config(table_TC_TO_EPLAN, tc_to_eplan_config, tb_TC_TO_EPLAN_tc.Text, tb_TC_TO_EPLAN_eplan.Text);
}
private void COL_ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
EPlanPropBean eplanBean = table_Eplan_Prop.SelectedItem as EPlanPropBean;
ComboBox cb = e.Source as ComboBox;
if (eplanBean == null||cb==null) {
return;
}
eplanBean.language = cb.SelectedItem as string;
}
}
}

@ -0,0 +1,200 @@
<Grid x:Class="KPlan.Forms.Config_ProjSync"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:KPlan.Forms"
mc:Ignorable="d"
UseLayoutRounding="True"
d:DesignHeight="450" d:DesignWidth="900" MinWidth="900" MinHeight="500">
<Grid Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--顶栏 类型和id映射-->
<Grid Grid.Row="0" Margin="15,10,5,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="对象类型" HorizontalContentAlignment="Right"/>
<TextBox Grid.Column="1" Name="tb_ObjectType" VerticalContentAlignment="Center" KeyDown="Tb_ObjectType_KeyDown"/>
<Button Grid.Column="2" Content="确定" Height="24" Width="60" Margin="5,0,15,0" Click="ChangeType_Button_Click"/>
</Grid>
<!--映射组-->
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!--TC属性-->
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="0" Margin="5,0,5,5">
<GroupBox.Header>Teamcenter</GroupBox.Header>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--搜索框-->
<Grid Grid.Row="0" Margin="5,3,5,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<ComboBox Grid.Column="0" x:Name="cb_Location" Width="85" Height="24" Margin="0,1" SelectionChanged="Cb_Location_SelectionChanged"/>
<TextBox Grid.Column="2" Name="tb_TCProp" VerticalContentAlignment="Center" KeyDown="Tb_TCProp_KeyDown" />
<Button Grid.Column="4" Click="Find_TC_PropButton_Click" Content="筛选" Width="60" Height="24" Margin="0,1"/>
</Grid>
<DataGrid Grid.Row="1" ItemsSource="{Binding}" SelectionChanged="PropTable_SelectionChanged" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" HeadersVisibility="Column" IsReadOnly="True" Name="table_TC_Prop" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="200" ColumnHeaderHeight="25" RowHeight="23" CanUserResizeRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="显示名称" Width="150" Binding="{Binding disName}"/>
<DataGridTextColumn Header="真实名称" Width="150" Binding="{Binding realName}"/>
<DataGridTextColumn Header="所在类型" Width="120" Binding="{Binding typeName}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</GroupBox>
<!--eplan属性-->
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="1" Margin="5,0,5,5">
<GroupBox.Header>Eplan</GroupBox.Header>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--搜索框-->
<Grid Grid.Row="0" Margin="5,3,5,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Name="tb_EPlanProp" VerticalContentAlignment="Center" KeyDown="Tb_EPlanProp_KeyDown"/>
<Button Grid.Column="2" Content="筛选" Width="60" Height="24" Margin="0,1" Click="Find_EPlan_Prop_Button_Click"/>
</Grid>
<DataGrid Grid.Row="1" ItemsSource="{Binding}" SelectionChanged="PropTable_SelectionChanged" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" HeadersVisibility="Column" Name="table_Eplan_Prop" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="200" ColumnHeaderHeight="25" RowHeight="23" CanUserResizeRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="显示名称" Width="150" Binding="{Binding disName}" IsReadOnly="True"/>
<DataGridTextColumn Header="真实名称" Width="150" Binding="{Binding realName}" IsReadOnly="True"/>
<DataGridTextColumn Header="类型" Width="120" Binding="{Binding type}" IsReadOnly="True"/>
<DataGridComboBoxColumn x:Name="col_language" IsReadOnly="False" Header="语言环境" Width="100" SelectedItemBinding="{Binding language}" >
<DataGridComboBoxColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="IsEnabled" Value="{Binding isComboReadOnly}" />
</Style>
</DataGridComboBoxColumn.CellStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}">
<EventSetter Event="SelectionChanged" Handler="COL_ComboBox_SelectionChanged" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</GroupBox>
<!--映射关系-->
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="2" Margin="5,0,5,5">
<GroupBox.Header>映射关系</GroupBox.Header>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<!--搜索框-->
<Grid Grid.Row="0" Margin="5,3,5,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Content="清空所有" Width="80" Height="24" Margin="0,1" Click="Clear_All_Button_Click"/>
</Grid>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1">
<GroupBox.Header>Eplan to TC</GroupBox.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<DataGrid Grid.Row="0" ItemsSource="{Binding}" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" HeadersVisibility="Column" IsReadOnly="True" Name="table_EPLAN_TO_TC" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="200" ColumnHeaderHeight="25" RowHeight="23" CanUserResizeRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="From" Width="150" Binding="{Binding from}"/>
<DataGridTextColumn Header="To" Width="150" Binding="{Binding to}"/>
</DataGrid.Columns>
</DataGrid>
<Grid Grid.Row="1" Margin="0,5,0,0" Height="25">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Click="EPLAN_TO_TC_ADD_Button_Click" Content="+" Width="25" Height="25" Margin="0,0,5,0"/>
<Button Grid.Column="1" Content="-" Click="EPLAN_TO_TC_REMOVE_Button_Click" Width="25" Height="25" Margin="0,0,5,0"/>
<Button Grid.Column="2" Click="EPLAN_TO_TC_MODIFY_Button_Click" Width="25" Height="25" Margin="0,0,5,0">
<Image Source="/EPLAN.EplAddin.KPlan;component/Resources/edit_16.png" Stretch="None" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Button>
<TextBox Grid.Column="3" Name="tb_EPLAN_TO_TC_eplan" VerticalContentAlignment="Center"/>
<Label Grid.Column="4" Content="to"/>
<TextBox Grid.Column="5" Name="tb_EPLAN_TO_TC_tc" VerticalContentAlignment="Center"/>
</Grid>
</Grid>
</GroupBox>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="2">
<GroupBox.Header>其他</GroupBox.Header>
<Grid Margin="10,5,10,10">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="70"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Content="PDF数据集类型"/>
<TextBox Grid.Row="1" Height="24" x:Name="tb_pdftype"/>
<Label Grid.Row="0" Grid.Column="2" Content="引用"/>
<TextBox Grid.Row="1" Grid.Column="2" Height="24" x:Name="tb_pdfref"/>
<Label Grid.Row="2" Content="EPLAN项目数据集类型"/>
<TextBox Grid.Row="3" Height="24" x:Name="tb_zwtype"/>
<Label Grid.Row="2" Grid.Column="2" Content="引用"/>
<TextBox Grid.Row="3" Grid.Column="2" Height="24" x:Name="tb_zwref"/>
<!--<Label Grid.Row="4" Content="模板位置:"/>
<TextBox Grid.Row="5" Grid.ColumnSpan="3" Height="24" x:Name="tb_templateid"/>-->
</Grid>
</GroupBox>
</Grid>
</GroupBox>
</Grid>
</Grid>
</Grid>

@ -0,0 +1,338 @@
using System;
using System.Collections.Generic;
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 KPlan.Util;
using KPlan.Forms.Bean;
using System.Collections.ObjectModel;
namespace KPlan.Forms {
/// <summary>
/// Interaction logic for Config_ProjSync.xaml
/// </summary>
public partial class Config_ProjSync : Grid {
private string loadedType;
private List<EPlanPropBean> ePlanPropBeanList = new List<EPlanPropBean>();
private ObservableCollection<EPlanPropBean> ePlanPropBeanData = new ObservableCollection<EPlanPropBean>();
private ObservableCollection<TCPropBean> tcPropBeanData = new ObservableCollection<TCPropBean>();
private ObservableCollection<PartSyncConfigBean> eplan_to_tc_config = new ObservableCollection<PartSyncConfigBean>();
private Dictionary<string, List<TCPropBean>> tcPropMap = new Dictionary<string, List<TCPropBean>>();
public ObservableCollection<string> language_list = new ObservableCollection<string>();
public Config_ProjSync() {
InitializeComponent();
ReadEplanProperty();
table_Eplan_Prop.ItemsSource = ePlanPropBeanData;
table_TC_Prop.ItemsSource = tcPropBeanData;
table_EPLAN_TO_TC.ItemsSource = eplan_to_tc_config;
string[] ENUM_LANGUAGES = Enum.GetNames(typeof(Eplan.EplApi.Base.ISOCode.Language));
Array.Sort(ENUM_LANGUAGES);
foreach (string l in ENUM_LANGUAGES) {
language_list.Add(l);
}
col_language.ItemsSource = language_list;
try {
string itemTypeName = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_TC_ITEM_TYPE);
TCUtil.GetDefinedProperties(itemTypeName);
ReadTcProperty(itemTypeName);
}
catch (System.Exception ex) {
KUtil.LogErr(ex);
//MessageBox.Show("加载数据出错:" + ex.Message);
}
}
private void ChangeType() {
string newType = tb_ObjectType.Text;
if (KUtil.IsEmpty(newType)) {
MessageBox.Show("请输入对象类型");
return;
}
if (newType.Equals(loadedType)) {
return;
}
MessageBoxResult res = MessageBox.Show("重新加载对象类型将清空当前映射配置,是否继续?", "", MessageBoxButton.YesNo);
if (res != MessageBoxResult.Yes) {
return;
}
//清空
ClearPropConfig();
//加载TC属性
ReadTcProperty(newType);
loadedType = newType;
}
private void ReadTcProperty(string itemTypeName) {
tcPropBeanData.Clear();
cb_Location.Items.Clear();
cb_Location.Items.Add("");
this.tcPropMap = TCUtil.GetDefinedProperties(itemTypeName);
foreach (string key in tcPropMap.Keys) {
cb_Location.Items.Add(key);
List<TCPropBean> list = tcPropMap[key];
foreach (TCPropBean b in list) {
tcPropBeanData.Add(b);
}
}
}
private void ReadEplanProperty() {
ePlanPropBeanList.Clear();
ePlanPropBeanData.Clear();
Eplan.EplApi.DataModel.AnyPropertyId[] props = Eplan.EplApi.DataModel.Properties.AllProjectPropIDs;
for (int i = 0; i < props.Length; i++) {
Eplan.EplApi.DataModel.AnyPropertyId prop = props[i];
if (prop.Definition.IsReadOnly) {
continue;
}
EPlanPropBean bean = new EPlanPropBean(prop.Definition.Type.ToString()) { realName = prop.AsProject.ToString(), disName = prop.Definition.Name, type = prop.Definition.Type.ToString() };
ePlanPropBeanList.Add(bean);
ePlanPropBeanData.Add(bean);
}
}
private void ClearPropConfig() {
eplan_to_tc_config.Clear();
}
private void Remove_Config(DataGrid dataGrid, ObservableCollection<PartSyncConfigBean> data) {
try {
System.Collections.IList selectedItems = dataGrid.SelectedItems;
if (selectedItems == null || selectedItems.Count == 0) {
return;
}
while (selectedItems.Count > 0) {
data.Remove((PartSyncConfigBean)selectedItems[0]);
dataGrid.Items.Refresh();
}
dataGrid.Items.Refresh();
}
catch (System.Exception ex) {
KUtil.LogErr(ex);
MessageBox.Show(ex.Message);
}
}
private void Modify_Config(DataGrid dataGrid, ObservableCollection<PartSyncConfigBean> data, string from, string to) {
if (KUtil.IsEmpty(from) || KUtil.IsEmpty(to)) {
return;
}
PartSyncConfigBean selectedBean = dataGrid.SelectedItem as PartSyncConfigBean;
if (selectedBean == null) {
return;
}
int existInd = data.IndexOf(new PartSyncConfigBean() { from = from, to = to });
if (existInd >= 0 && !to.Equals(selectedBean.to)) {
MessageBox.Show("已存在属性映射到" + to);
return;
}
//PartSyncConfigBean bean = (PartSyncConfigBean)dataGrid.Items[ind];
selectedBean.from = from;
selectedBean.to = to;
dataGrid.Items.Refresh();
dataGrid.SelectedItem = selectedBean;
}
private void Add_Config(DataGrid dataGrid, ObservableCollection<PartSyncConfigBean> data, string from, string to) {
if (KUtil.IsEmpty(from) || KUtil.IsEmpty(to)) {
return;
}
PartSyncConfigBean bean = new PartSyncConfigBean() { from = from, to = to };
if (!data.Contains(bean)) {
data.Add(bean);
}
dataGrid.SelectedItem = bean;
dataGrid.ScrollIntoView(bean);
}
private void Read_Prop_Refection_to_Textbox() {
EPlanPropBean eplanBean = table_Eplan_Prop.SelectedItem as EPlanPropBean;
TCPropBean tcBean = table_TC_Prop.SelectedItem as TCPropBean;
string eplanConfig = "";
string tcConfig = "";
if (eplanBean != null) {
eplanConfig = eplanBean.getConfigValue();
}
if (tcBean != null) {
tcConfig = tcBean.location + "." + tcBean.realName;
}
tb_EPLAN_TO_TC_eplan.Text = eplanConfig;
tb_EPLAN_TO_TC_tc.Text = tcConfig;
}
private void Find_TC_Props() {
string text = tb_TCProp.Text;
string type = cb_Location.SelectedItem as string;
tcPropBeanData.Clear();
if (KUtil.IsEmpty(type) && KUtil.IsEmpty(text)) {
foreach (List<TCPropBean> list in tcPropMap.Values) {
foreach (TCPropBean b in list) {
tcPropBeanData.Add(b);
}
}
}
else {
text = text.ToLower();
foreach (List<TCPropBean> list in tcPropMap.Values) {
foreach (TCPropBean b in list) {
if (KUtil.RegexMatch(b.disName.ToLower(),text) || KUtil.RegexMatch(b.realName.ToLower(), text)) {
//if (b.disName.ToLower().Contains(text) || b.realName.ToLower().Contains(text)) {
if (KUtil.IsEmpty(type) || b.typeName.Equals(type)) {
tcPropBeanData.Add(b);
}
}
}
}
}
}
private void Find_EPlan_Props() {
string text = tb_EPlanProp.Text;
ePlanPropBeanData.Clear();
if (KUtil.IsEmpty(text)) {
foreach (EPlanPropBean bean in ePlanPropBeanList) {
ePlanPropBeanData.Add(bean);
}
}
else {
text = text.ToLower();
foreach (EPlanPropBean bean in ePlanPropBeanList) {
if (KUtil.RegexMatch(bean.disName.ToLower(),text) || KUtil.RegexMatch(bean.realName.ToLower(), text)){
//if (bean.disName.ToLower().Contains(text) || bean.realName.ToLower().Contains(text)) {
ePlanPropBeanData.Add(bean);
}
}
}
}
public void SaveConfiguration() {
Dictionary<string, string> syncConfig = new Dictionary<string, string>();
syncConfig.Add(KConfigure.PROJ_SYNC_TC_ITEM_TYPE, tb_ObjectType.Text);
// syncConfig.Add(KConfigure.PROJ_SYNC_TEMPLATE_ID, tb_templateid.Text);
syncConfig.Add(KConfigure.PROJ_SYNC_PDF_DSTYPE, tb_pdftype.Text);
syncConfig.Add(KConfigure.PROJ_SYNC_PDF_DSREF, tb_pdfref.Text);
syncConfig.Add(KConfigure.PROJ_SYNC_ZW_DSTYPE, tb_zwtype.Text);
syncConfig.Add(KConfigure.PROJ_SYNC_ZW_DSREF, tb_zwref.Text);
//syncConfig.Add(KConfigure.PROJ_SYNC_ItemID_EPlan, tb_ItemID_Prop.Text);
KUtil.SetConfigValue(KConfigure.PROJ_SYNC_SECTION, syncConfig);
KUtil.ClearConfigSection(KConfigure.PROJ_SYNC_EPLAN_TO_TC_SECTION);
//eplan to tc
Dictionary<string, string> eplan_to_tc = new Dictionary<string, string>();
for (int i = 0; i < eplan_to_tc_config.Count; i++) {
PartSyncConfigBean bean = eplan_to_tc_config[i];
eplan_to_tc.Add(bean.to, bean.from);
}
KUtil.SetConfigValue(KConfigure.PROJ_SYNC_EPLAN_TO_TC_SECTION, eplan_to_tc);
}
public void LoadConfiguration() {
this.loadedType = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_TC_ITEM_TYPE);
tb_ObjectType.Text = this.loadedType;
//tb_templateid.Text = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_TEMPLATE_ID);
tb_pdftype.Text = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_PDF_DSTYPE);
tb_pdfref.Text = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_PDF_DSREF);
tb_zwtype.Text = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_ZW_DSTYPE);
tb_zwref.Text = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_ZW_DSREF);
//tb_ItemID_Prop.Text = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_ItemID_EPlan);
//eplan to tc
Dictionary<string, string> eplan_to_tc = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_EPLAN_TO_TC_SECTION);
foreach (string key in eplan_to_tc.Keys) {
PartSyncConfigBean bean = new PartSyncConfigBean() { from = eplan_to_tc[key], to = key };
eplan_to_tc_config.Add(bean);
}
}
private void Find_EPlan_Prop_Button_Click(object sender, RoutedEventArgs e) {
Find_EPlan_Props();
}
private void Tb_EPlanProp_KeyDown(object sender, KeyEventArgs e) {
if (e.Key == Key.Return) {
Find_EPlan_Props();
}
}
private void Find_TC_PropButton_Click(object sender, RoutedEventArgs e) {
Find_TC_Props();
}
private void Tb_TCProp_KeyDown(object sender, KeyEventArgs e) {
if (e.Key == Key.Return) {
Find_TC_Props();
}
}
private void ChangeType_Button_Click(object sender, RoutedEventArgs e) {
try {
ChangeType();
}
catch (System.Exception ex) {
KUtil.LogErr(ex);
MessageBox.Show("加载数据出错:" + ex.Message);
}
}
private void Tb_ObjectType_KeyDown(object sender, KeyEventArgs e) {
if (e.Key == Key.Return) {
try {
ChangeType();
}
catch (System.Exception ex) {
KUtil.LogErr(ex);
MessageBox.Show("加载数据出错:" + ex.Message);
}
}
}
private void Cb_Location_SelectionChanged(object sender, SelectionChangedEventArgs e) {
Find_TC_Props();
}
private void PropTable_SelectionChanged(object sender, SelectionChangedEventArgs e) {
Read_Prop_Refection_to_Textbox();
}
private void EPLAN_TO_TC_ADD_Button_Click(object sender, RoutedEventArgs e) {
Add_Config(table_EPLAN_TO_TC, eplan_to_tc_config, tb_EPLAN_TO_TC_eplan.Text, tb_EPLAN_TO_TC_tc.Text);
}
private void EPLAN_TO_TC_REMOVE_Button_Click(object sender, RoutedEventArgs e) {
Remove_Config(table_EPLAN_TO_TC, eplan_to_tc_config);
}
private void EPLAN_TO_TC_MODIFY_Button_Click(object sender, RoutedEventArgs e) {
Modify_Config(table_EPLAN_TO_TC, eplan_to_tc_config, tb_EPLAN_TO_TC_eplan.Text, tb_EPLAN_TO_TC_tc.Text);
}
private void Clear_All_Button_Click(object sender, RoutedEventArgs e) {
MessageBoxResult res = MessageBox.Show("确认清空?", "", MessageBoxButton.YesNo);
if (res != MessageBoxResult.Yes) {
return;
}
ClearPropConfig();
}
private void COL_ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
EPlanPropBean eplanBean = table_Eplan_Prop.SelectedItem as EPlanPropBean;
ComboBox cb = e.Source as ComboBox;
if (eplanBean == null || cb == null) {
return;
}
eplanBean.language = cb.SelectedItem as string;
}
}
}

@ -0,0 +1,46 @@
<Window x:Class="KPlan.Forms.Configure"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:Controls="clr-namespace:KPlan.Forms"
mc:Ignorable="d" WindowStartupLocation="CenterOwner" Height="700" Width="1100" MinHeight="480" MinWidth="640" Icon="/EPLAN.EplAddin.KPlan;component/Resources/logo_16.ico" Title="设置">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="38"/>
</Grid.RowDefinitions>
<!--配置区域-->
<TabControl HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="5,5,5,0">
<TabItem Header="项目属性" >
<Controls:Config_ProjSync x:Name="config_ProjSync" />
<!--<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
</ScrollViewer>-->
</TabItem>
<TabItem Header="部件库属性" >
<Controls:Config_PartSync x:Name="config_PartSync" />
<!--<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
</ScrollViewer>-->
</TabItem>
<TabItem Header="分类属性" >
<Controls:Config_Classification x:Name="config_Classification"/>
</TabItem>
<TabItem Header="其他">
<Controls:Config_Others x:Name="config_others"/>
</TabItem>
</TabControl>
<Grid Grid.Row="1" HorizontalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Button Name="b_Save" Grid.Column="0" Content="确定" Height="25" Width="75" Click="b_Save_Click"/>
<Button Name="b_Apply" Grid.Column="1" Content="应用" Height="25" Width="75" Click="b_Apply_Click"/>
<Button Name="b_Close" Grid.Column="2" Content="取消" Height="25" Width="75" Click="b_Close_Click"/>
</Grid>
</Grid>
</Window>

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
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 KPlan.Util;
namespace KPlan.Forms {
/// <summary>
/// Configure.xaml 的交互逻辑
/// </summary>
public partial class Configure : Window {
public Configure() {
InitializeComponent();
KUtil.SetOwnerWindow(this);
LoadConfiguration();
}
private void b_Save_Click(object sender, RoutedEventArgs e) {
try {
SaveConfiguration();
Close();
}
catch (System.Exception ex) {
MessageBox.Show(this, "保存配置出错:" + ex.Message, "错误");
KUtil.LogErr(ex);
}
}
private void b_Apply_Click(object sender, RoutedEventArgs e) {
try {
SaveConfiguration();
}
catch (System.Exception ex) {
MessageBox.Show(this, "保存配置出错:" + ex.Message, "错误");
KUtil.LogErr(ex);
}
}
private void b_Close_Click(object sender, RoutedEventArgs e) {
Close();
}
private void SaveConfiguration() {
this.config_others.SaveConfiguration();
this.config_Classification.SaveConfiguration();
//部件库同步
this.config_PartSync.SaveConfiguration();
this.config_ProjSync.SaveConfiguration();
}
private void LoadConfiguration() {
this.config_others.LoadConfiguration();
this.config_Classification.LoadConfiguration();
this.config_Classification.LoadPartGroups();
//部件库同步
this.config_PartSync.LoadConfiguration();
this.config_ProjSync.LoadConfiguration();
}
}
}

@ -0,0 +1,77 @@
<Window x:Class="KPlan.Forms.CreateProject"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:KPlan.Forms"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d" WindowStartupLocation="CenterOwner" Height="310" Width="640" MinHeight="310" MinWidth="360" Icon="/EPLAN.EplAddin.KPlan;component/Resources/logo_16.ico" Title="创建项目">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.6*"/>
<ColumnDefinition x:Name="colDef_TCTemplate" Width="0.4*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Margin="15,15,10,15">
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="8"/>
<RowDefinition Height="25"/>
<RowDefinition Height="8"/>
<RowDefinition Height="25"/>
<RowDefinition Height="8"/>
<RowDefinition Height="25"/>
<RowDefinition Height="8"/>
<RowDefinition Height="25"/>
<RowDefinition Height="8"/>
<RowDefinition Height="25"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="项目编码"/>
<TextBox Grid.Row="0" Grid.Column="1" x:Name="tb_ProjCode" VerticalContentAlignment="Center"/>
<Label Grid.Row="2" Grid.Column="0" Content="项目名称"/>
<TextBox Grid.Row="2" Grid.Column="1" x:Name="tb_ProjName" VerticalContentAlignment="Center"/>
<Label Grid.Row="4" Grid.Column="0" Content="保存位置"/>
<TextBox Grid.Row="4" Grid.Column="1" x:Name="tb_SavePosition" VerticalContentAlignment="Center"/>
<Button Grid.Row="4" Grid.Column="2" Content="..." Click="SavePosition_Button_Click" Width="25" Height="25" HorizontalAlignment="Left" Margin="5,0"/>
<Label Grid.Row="6" Grid.Column="0" Content="模板"/>
<TextBox Grid.Row="6" Grid.Column="1" x:Name="tb_Template" VerticalContentAlignment="Center"/>
<Button Grid.Row="6" Grid.Column="2" Content="..." Click="Template_Button_Click" Width="25" Height="25" HorizontalAlignment="Left" Margin="5,0"/>
<CheckBox Grid.Row="8" Grid.Column="0" Content="设置创建时间" VerticalAlignment="Center" Name="cb_CreationDate" Click="CreationDate_CheckBox_SelectionChanged"/>
<xctk:DateTimePicker Grid.Row="8" Grid.Column="1" IsEnabled="False" Name="dp_CreationDate" Format="Custom" FormatString="yyyy/MM/dd HH:mm:ss" TimeFormat="Custom" TimeFormatString="HH:mm:ss"/>
<CheckBox Grid.Row="10" Grid.Column="0" Content="设置创建者" VerticalAlignment="Center" Name="cb_Creator" Click="Cb_Creator_SelectionChanged"/>
<TextBox Grid.Row="10" Grid.Column="1" Name="tb_Creator" VerticalContentAlignment="Center" IsEnabled="False" />
</Grid>
<Grid Grid.Row="1" HorizontalAlignment="Center" Margin="0,5,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="35"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Button Content="确定" Width="75" Height="24" Grid.Column="0" Click="CreateProj_Button_Click"/>
<Button Content="取消" Width="75" Height="24" Grid.Column="2" Click="Close_Button_Click"/>
</Grid>
</Grid>
<GroupBox x:Name="groupbox_TCTemplate" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="1" Margin="5,0,5,5">
<GroupBox.Header>Teamcenter模板</GroupBox.Header>
<ListView x:Name="list_TCTemplate" SelectionChanged="List_TCTemplate_SelectionChanged"/>
</GroupBox>
</Grid>
</Window>

@ -0,0 +1,207 @@
using System;
using System.Collections;
using System.Collections.Generic;
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 KPlan.Util;
using Teamcenter.Soa.Client.Model;
using KPlan.Forms.Bean;
using System.Collections.ObjectModel;
using System.Windows.Forms;
using System.ComponentModel;
using Eplan.EplApi.DataModel;
using Eplan.EplApi.MasterData;
using Eplan.EplApi.Base;
namespace KPlan.Forms {
/// <summary>
/// Interaction logic for CreateProject.xaml
/// </summary>
public partial class CreateProject : Window {
public const double W_NO_TEMPLATE = 400;
public const double W_TEMPLATE = 640;
private ModelObject[] templates;
private ObservableCollection<ModelObjectBean> templatesListData = new ObservableCollection<ModelObjectBean>();
private ModelObjectBean selectedTemplateBean;
string projCode = "";
string projName = "";
string savePosition = "";
string templateName = "";
DateTime? creation_date = null;
string creator = "";
public bool create = false;
public CreateProject() {
InitializeComponent();
KUtil.SetOwnerWindow(this);
list_TCTemplate.ItemsSource = templatesListData;
try {
loadTCTemplate();
}
catch (System.Exception ex) {
KUtil.LogErr(ex);
}
}
private void CreateProj_Button_Click(object sender, RoutedEventArgs e) {
create = true;
projCode = tb_ProjCode.Text;
projName = tb_ProjName.Text;
savePosition = tb_SavePosition.Text;
templateName = tb_Template.Text;
if (cb_CreationDate.IsChecked.Value) {
creation_date = dp_CreationDate.Value;
}
if (cb_Creator.IsChecked.Value) {
creator = tb_Creator.Text;
}
if (KUtil.IsEmpty(projCode) || KUtil.IsEmpty(projName) || KUtil.IsEmpty(savePosition) || KUtil.IsEmpty(templateName)) {
KUtil.DispatcherShow(this, "请填写项目信息");
return;
}
Close();
}
public void DoCreateProject() {
System.IO.FileInfo fileInfo;
if (selectedTemplateBean != null && templateName.Equals(selectedTemplateBean.objectString)) {
List<Teamcenter.Soa.Client.Model.Strong.ImanFile> imanFiles = TCUtil.GetDatasetFile(selectedTemplateBean.mo, null);
if (imanFiles == null || imanFiles.Count == 0) {
throw new Exception("数据集<" + templateName + ">不存在文件引用");
}
if (imanFiles.Count > 1) {
throw new Exception("数据集<" + templateName + ">存在多个文件引用");
}
fileInfo = TCUtil.GetFileInfo(imanFiles[0]);
if (fileInfo == null) {
throw new Exception("从数据集<" + templateName + ">下载文件引用失败");
}
}
else {
fileInfo = new System.IO.FileInfo(templateName);
}
if (fileInfo == null || !fileInfo.Exists) {
throw new Exception("获取模板异常,文件不存在:" + templateName);
}
KUtil.Log("项目模板:" + fileInfo.FullName);
if (!System.IO.Directory.Exists(savePosition)) {
System.IO.Directory.CreateDirectory(savePosition);
}
KUtil.Log(savePosition + "\\" + projName + ".elk|" + fileInfo.FullName);
Progress progress = new Progress("SimpleProgress");
progress.BeginPart(100.0, "");
progress.ShowImmediately();
progress.SetAllowCancel(true);
try {
string projPath = savePosition + "\\" + projName + ".elk";
string tempPath = fileInfo.FullName;
KUtil.Log("创建项目:" + projPath);
KUtil.Log("使用模板:" + tempPath);
Project proj = EplanUtil.Create(projPath, tempPath, true);
proj.Properties.PROJ_DRAWINGNUMBER = projCode;
proj.Properties.PROJ_CUSTOM_SUPPLEMENTARYFIELD100 = projCode;//item_id
if (!KUtil.IsEmpty(creator)) {
KUtil.Log("设置创建者:" + creator);
proj.Properties.PROJ_CREATOR = creator;
}
if (creation_date != null) {
KUtil.Log("设置创建时间:" + creation_date.Value);
proj.Properties.PROJ_CREATIONDATE = creation_date.Value;
}
//去掉感叹号
proj.Close();
proj = EplanUtil.OpenProject(projPath);
KUtil.Log("创建完成");
}
finally {
progress.EndPart(true);
}
}
private void loadTCTemplate() {
string itemId = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_TEMPLATE_ITEM_ID);
string dsType = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_TEMPLATE_DATASET_TYPE);
if (TCUtil.user == null || KUtil.IsEmpty(itemId) || KUtil.IsEmpty(dsType)) {
colDef_TCTemplate.Width = new GridLength(0);
this.Width = W_NO_TEMPLATE;
this.MinWidth = W_NO_TEMPLATE;
return;
}
this.Width = W_TEMPLATE;
this.MinWidth = W_TEMPLATE;
KUtil.Log("加载TC中项目模板" + itemId);
Teamcenter.Soa.Client.Model.Strong.ItemRevision rev = TCUtil.Query_LatestRev(itemId);
if (rev == null) {
KUtil.Log("配置对象不存在:" + itemId);
return;
}
templates = TCUtil.GetChild(rev, TCUtil.REL_REV_EPLAN, dsType);
int len = templates == null ? 0 : templates.Length;
if (len > 0) {
TCUtil.dmService.RefreshObjects(templates);
TCUtil.GetProperties(false, templates, "object_string");
for (int i = 0; i < len; i++) {
Teamcenter.Soa.Client.Model.Strong.Dataset ds = (Teamcenter.Soa.Client.Model.Strong.Dataset)templates[i];
templatesListData.Add(new ModelObjectBean(ds, ds.Object_string));
}
}
KUtil.Log("加载完成");
}
private void CreationDate_CheckBox_SelectionChanged(object sender, RoutedEventArgs e) {
dp_CreationDate.IsEnabled = cb_CreationDate.IsChecked.Value;
if (cb_CreationDate.IsChecked.Value) {
dp_CreationDate.Text = DateTime.Now.ToString(dp_CreationDate.FormatString);
}
}
private void Cb_Creator_SelectionChanged(object sender, RoutedEventArgs e) {
tb_Creator.IsEnabled = cb_Creator.IsChecked.Value;
}
private void Close_Button_Click(object sender, RoutedEventArgs e) {
Close();
}
private void SavePosition_Button_Click(object sender, RoutedEventArgs e) {
FolderBrowserDialog fb = new FolderBrowserDialog();
fb.RootFolder = Environment.SpecialFolder.Desktop;
fb.Description = "选择项目保存位置";
if (fb.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
tb_SavePosition.Text = fb.SelectedPath;
}
}
private void Template_Button_Click(object sender, RoutedEventArgs e) {
OpenFileDialog fd = new OpenFileDialog();
fd.Title = "选择项目模板";
fd.Filter = "模板文件|*.ept";
if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
tb_Template.Text = fd.FileName;
}
}
private void List_TCTemplate_SelectionChanged(object sender, SelectionChangedEventArgs e) {
selectedTemplateBean = list_TCTemplate.SelectedItem as ModelObjectBean;
if (selectedTemplateBean == null) {
return;
}
tb_Template.Text = selectedTemplateBean.objectString;
}
}
}

@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using KPlan.Util;
namespace KPlan.Forms {
class KBackgroundWorker {
public BackgroundWorker backgroundWorker { get; set; }
private Window parent;
private KBgWorker2 pbDialog;
public KBackgroundWorker(Window parent) {
this.parent = parent;
//可以返回工作进度
backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
//允许取消
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
//更新进度条
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
//backgroundWorker.DoWork += Query_Async;
//backgroundWorker.DoWork += backgroundWorker_DoWork;
//开始执行DoWork
//backgroundWorker.RunWorkerAsync();
}
public void Start(object param,bool disableCancel) {
if (backgroundWorker.IsBusy) {
return;
}
if (parent != null) {
parent.IsEnabled = false;
}
pbDialog = new KBgWorker2(parent, backgroundWorker);
if (disableCancel) {
pbDialog.tb_cancel.Width = 0;
pbDialog.tb_cancel.Visibility = Visibility.Hidden;
}
backgroundWorker.RunWorkerAsync(param);
}
public void Start(object param) {
if (backgroundWorker.IsBusy) {
return;
}
if (parent != null) {
parent.IsEnabled = false;
}
pbDialog = new KBgWorker2(parent, backgroundWorker);
backgroundWorker.RunWorkerAsync(param);
}
public bool IsCancel() {
return backgroundWorker.CancellationPending;
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
pbDialog.Dispatcher.Invoke(new Action(delegate {
pbDialog.Close();
}));
if (parent != null) {
parent.IsEnabled = true;
}
if (e.Error != null) {
KUtil.LogErr(e.Error);
MessageBox.Show(parent, "发生异常:" + e.Error.Message);
}
else {
if (e.Cancelled) {
MessageBox.Show(parent, "已取消");
}
//else {
// MessageBox.Show(parent, "操作完成");
//}
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) {
pbDialog.progressBar.Value = e.ProgressPercentage;
}
public void Progress(string text, int progress) {
pbDialog.Dispatcher.Invoke(new Action(delegate {
pbDialog.lable.Content = text;
}));
backgroundWorker.ReportProgress(progress);
}
}
}

@ -0,0 +1,38 @@
<Window x:Class="KPlan.Forms.KBgWorker2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" Icon="/EPLAN.EplAddin.KPlan;component/Resources/logo_16.ico" Background="{x:Null}" Visibility="Visible" WindowStartupLocation="CenterOwner"
MouseDown="Window_MouseDown" Height="90" Width="288" FontFamily="Microsoft YaHei" Foreground="{x:Null}" TextOptions.TextFormattingMode="Display" AllowsTransparency="True" WindowStyle="None" ResizeMode="NoResize" Padding="0">
<!--<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="KStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>-->
<Grid Margin="0,0,-2,-2">
<Rectangle Fill="#FFFBFBFB" RadiusX="8" RadiusY="8" Margin="10,10,10,10">
<Rectangle.Effect>
<DropShadowEffect BlurRadius="10" ShadowDepth="-5" Opacity="0.8" Direction="0" Color="#FF303030"/>
</Rectangle.Effect>
</Rectangle>
<Label Name="lable" Content="正在执行:" HorizontalAlignment="Left" Margin="23,25,0,0" VerticalAlignment="Top"/>
<Grid Margin="23,20,23,0" Height="18" VerticalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<ProgressBar Grid.Column="0" Name="progressBar" HorizontalAlignment="Stretch" Height="12" VerticalAlignment="Center"/>
<TextBlock Grid.Column="1" x:Name="tb_cancel" HorizontalAlignment="Center" TextAlignment="Center" TextWrapping="NoWrap" Width="30" VerticalAlignment="Center">
<Hyperlink Click="CancelWork">取消</Hyperlink>
</TextBlock>
</Grid>
<!--<ProgressBar Name="progressBar" HorizontalAlignment="Stretch" Height="12" Margin="23,50,23,0" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Right" Margin="0,47,23,0" TextWrapping="NoWrap" Visibility="Hidden" VerticalAlignment="Top">
<Hyperlink Click="CancelWork">取消</Hyperlink>
</TextBlock>-->
</Grid>
</Window>

@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
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.Diagnostics;
using System.ComponentModel;
using KPlan.Util;
namespace KPlan.Forms {
/// <summary>
/// KBgWorker2.xaml 的交互逻辑
/// </summary>
public partial class KBgWorker2 : Window {
private BackgroundWorker backgroundWorker;
public KBgWorker2(Window parent, BackgroundWorker backgroundWorker) {
InitializeComponent();
if (parent == null) {
KUtil.SetOwnerWindow(this);
}
else {
this.Owner = parent;
}
this.backgroundWorker = backgroundWorker;
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e) {
if (e.ChangedButton == MouseButton.Left)
this.DragMove();
}
private void CancelWork(object sender, RoutedEventArgs e) {
backgroundWorker.CancelAsync();
Close();
}
}
}

@ -0,0 +1,81 @@
<Window x:Class="KPlan.Forms.KCheckProject"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:KPlan.Forms"
mc:Ignorable="d" Loaded="Window_Loaded" WindowStartupLocation="CenterOwner" Height="600" Width="800" MinHeight="480" MinWidth="640" Icon="/EPLAN.EplAddin.KPlan;component/Resources/logo_16.ico" Title="检查项目">
<!--<Window.Resources>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<Trigger Property="Text" Value="TC不存在">
<Setter Property="Foreground" Value="Red"/>
</Trigger>
<Trigger Property="Text" Value="停用部件">
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>-->
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="35"/>
<RowDefinition Height="*"/>
<RowDefinition Height="35"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="25"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="15"/>
</Grid.ColumnDefinitions>
<Label Content=" 项目编号:" Grid.Column="0" VerticalAlignment="Center" />
<Label x:Name="tb_ProjId" BorderThickness="0 0 0 2" BorderBrush="DarkGray" Grid.Column="1" Width="160" Height="25" VerticalContentAlignment="Center"/>
<Label Content="项目名称:" Grid.Column="3" VerticalAlignment="Center"/>
<Label x:Name="tb_ProjName" BorderThickness="0 0 0 2" BorderBrush="DarkGray" Grid.Column="4" Width="160" Height="25" VerticalContentAlignment="Center"/>
<Button x:Name="b_save" Content="保存" Click="b_save_Click" Grid.Column="6" Width="95" Height="25" />
</Grid>
<DataGrid Margin="5 0 5 0" Grid.Row="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Loaded="datagrid_CheckResult_Loaded" ItemsSource="{Binding}" HeadersVisibility="Column" IsReadOnly="True" Name="datagrid_CheckResult" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="300" ColumnHeaderHeight="25">
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}" >
<!--<Setter Property="Foreground" Value="Green"/>-->
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Path=Column.Header, RelativeSource={RelativeSource Self}}" Value="检查结果"/>
<Condition Binding="{Binding [检查结果]}" Value="TC不存在"/>
</MultiDataTrigger.Conditions>
<Setter Property="Foreground" Value="Red"/>
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Path=Column.Header, RelativeSource={RelativeSource Self}}" Value="检查结果"/>
<Condition Binding="{Binding [检查结果]}" Value="停产部件"/>
</MultiDataTrigger.Conditions>
<Setter Property="Foreground" Value="Red"/>
</MultiDataTrigger>
<!--<DataTrigger Binding="{Binding [检查结果]}" Value="TC不存在">
<Setter Property="Foreground" Value="Red"/>
</DataTrigger>-->
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
</DataGrid>
<Grid Grid.Row="2" HorizontalAlignment="Right">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="18"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="15"/>
</Grid.ColumnDefinitions>
<Button Name="b_Export" Click="b_Export_Click" Content="导出" IsEnabled="False" Width="95" Height="25" Grid.Column="0"/>
<Button Name="b_Close" Click="b_Close_Click" Content="退出" Width="95" Height="25" Grid.Column="2"/>
</Grid>
</Grid>
</Window>

@ -0,0 +1,702 @@
using Eplan.EplApi.Base;
using Eplan.EplApi.DataModel;
using Eplan.EplApi.HEServices;
using KPlan.Forms.Bean;
using KPlan.Util;
using Oracle.ManagedDataAccess.Client;
using System;
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.Services.Strong.Core;
using Teamcenter.Soa.Client.Model;
namespace KPlan.Forms {
/// <summary>
/// Interaction logic for KCheckProject.xaml
/// </summary>
public partial class KCheckProject : Window {
private KBackgroundWorker bgWorker_load;
private KBackgroundWorker bgWorker_export;
private KBackgroundWorker bgWorker_save;
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<string> titles = new List<string>();
private List<string> checkConfig = new List<string>();
private Dictionary<string, string> saveConfig = new Dictionary<string, string>();
private List<int> checkResultWidth = new List<int>();
private List<CheckTableRowData> rowDatas = new List<CheckTableRowData>();
private bool enableExport = false;
private int INDEX_IND = -1;
private int INDEX_RES = -1;
private const string SKIP_PDF = "skip_pdf";
public KCheckProject(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;
this.currentProject = currentProject;
this.exportFile = exportFile;
this.projId = projectCode;
this.projName = currentProject.ProjectName;
this.projDir = projectDir;
}
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("文件导出异常");
}
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);
}
private void CreateOrUpdateDataset_old(Teamcenter.Soa.Client.Model.Strong.ItemRevision projRev) {
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;
bgWorker_save.Progress("获取EPLAN数据包...", 20);
ModelObject[] zw1Children = TCUtil.GetChild(projRev, "IMAN_specification", ZW1DSType);
int len = zw1Children == null ? 0 : zw1Children.Length;
if (len > 1 || len == 0) {
zw1Dataset = TCUtil.CreateNewDataset(ZW1DSType, projId + "EPLAN数据包");
if (zw1Dataset != null) {
TCUtil.CreateNewRelation(projRev, zw1Dataset, "IMAN_specification");
}
else {
throw new Exception("创建EPLAN数据包数据集失败");
}
}
else {
zw1Dataset = zw1Children[0] as Teamcenter.Soa.Client.Model.Strong.Dataset;
}
TCUtil.CheckDatasetForUpdate(zw1Dataset);
bgWorker_save.Progress("上传EPLAN数据包...", 40);
TCUtil.UploadFile(zw1Dataset, projFile, ZW1DSRef);
if (!SKIP_PDF.Equals(pdfFile)) {
bgWorker_save.Progress("获取PDF图纸...", 60);
ModelObject[] pdfChildren = TCUtil.GetChild(projRev, "IMAN_specification", PDFDSType);
len = pdfChildren == null ? 0 : pdfChildren.Length;
if (len > 1 || len == 0) {
pdfDataset = TCUtil.CreateNewDataset(PDFDSType, projId + "PDF图纸");
if (pdfDataset != null) {
TCUtil.CreateNewRelation(projRev, pdfDataset, "IMAN_specification");
}
else {
throw new Exception("创建PDF图纸数据集失败");
}
}
else {
pdfDataset = pdfChildren[0] as Teamcenter.Soa.Client.Model.Strong.Dataset;
}
TCUtil.CheckDatasetForUpdate(pdfDataset);
bgWorker_save.Progress("上传PDF图纸...", 80);
TCUtil.UploadFile(pdfDataset, pdfFile, PDFDSRef);
}
bgWorker_save.Progress("保存完成", 100);
KUtil.DispatcherShow(this, "保存项目完成");
}
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(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<CheckTableRowData> bomData = new List<CheckTableRowData>();
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];
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);
//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;
}
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 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);
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();
string nowtime = DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss");
string fileName = Environment.GetEnvironmentVariable("temp") + "\\申请清单" + nowtime + ".xlsx";
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;
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_Load(object sender, DoWorkEventArgs e) {
bgWorker_load.Progress("检查数据...", 0);
bool projExist = TCUtil.ItemExist(projId);
this.Dispatcher.Invoke(new Action(delegate {
this.tb_ProjId.Content = projId;
this.tb_ProjName.Content = projName;
}));
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<string, bool> existMap = new Dictionary<string, bool>();
using (OracleConnection conn = new OracleConnection(oradb)) {
conn.Open();
for (int i = 0; i < deviceCnt; i++) {
if (bgWorker_load.IsCancel()) {
e.Cancel = true;
break;
}
bgWorker_load.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_load.IsCancel()) {
e.Cancel = true;
break;
}
XmlNode partNode = partNodes.Item(j);
CheckPart(partNode, "TRUE".Equals(checkWire?.ToUpper()), conn, existMap);
}
}
}
this.Dispatcher.Invoke(new Action(delegate {
b_Export.IsEnabled = enableExport;
b_save.IsEnabled = projExist && !enableExport;
}));
}
private void CheckPart(XmlNode partNode, bool checkWire, OracleConnection conn, Dictionary<string, bool> 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;
bool itemExist = false;
string itemUid = null;
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,null, partNode, itemExist, itemUid);
rowDatas.Add(data);
object[] rowData = data.GetRowData(rowDatas.Count, checkConfig);
if (!data.checkOK) {
enableExport = true;
}
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) {
bgWorker_export.Start(null);
}
private string projFile;
private string pdfFile;
private void b_save_Click(object sender, RoutedEventArgs e) {
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);
}
}
}

@ -0,0 +1,87 @@
<Window x:Class="KPlan.Forms.KCheckProject_Ex"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:KPlan.Forms"
mc:Ignorable="d" Loaded="Window_Loaded" WindowStartupLocation="CenterOwner" Height="600" Width="900" MinHeight="480" MinWidth="880" Icon="/EPLAN.EplAddin.KPlan;component/Resources/logo_16.ico" Title="检查项目">
<!--<Window.Resources>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<Trigger Property="Text" Value="TC不存在">
<Setter Property="Foreground" Value="Red"/>
</Trigger>
<Trigger Property="Text" Value="停用部件">
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>-->
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="35"/>
<RowDefinition Height="*"/>
<RowDefinition Height="35"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="25"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="15"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="15"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="15"/>
</Grid.ColumnDefinitions>
<Label Content=" 项目编号:" Grid.Column="0" VerticalAlignment="Center" />
<Label x:Name="tb_ProjId" BorderThickness="0 0 0 2" BorderBrush="DarkGray" Grid.Column="1" Width="160" Height="25" VerticalContentAlignment="Center"/>
<Label Content="项目名称:" Grid.Column="3" VerticalAlignment="Center"/>
<Label x:Name="tb_ProjName" BorderThickness="0 0 0 2" BorderBrush="DarkGray" Grid.Column="4" Width="160" Height="25" VerticalContentAlignment="Center"/>
<!--<Button x:Name="b_check_error" Content="检查错误项" Click="b_check_error_Click" Grid.Column="6" Width="95" Height="25" />-->
<Button x:Name="b_check_all" Content="检查全部" Click="b_check_all_Click" Grid.Column="8" Width="95" Height="25" />
<Button x:Name="b_save" Content="检查并保存" Click="b_save_Click" Grid.Column="10" Width="95" Height="25" />
</Grid>
<DataGrid Margin="5 0 5 0" Grid.Row="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Loaded="datagrid_CheckResult_Loaded" ItemsSource="{Binding}" HeadersVisibility="Column" IsReadOnly="True" Name="datagrid_CheckResult" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="300" ColumnHeaderHeight="25">
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}" >
<!--<Setter Property="Foreground" Value="Green"/>-->
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Path=Column.Header, RelativeSource={RelativeSource Self}}" Value="检查结果"/>
<Condition Binding="{Binding [检查结果]}" Value="TC不存在"/>
</MultiDataTrigger.Conditions>
<Setter Property="Foreground" Value="Red"/>
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Path=Column.Header, RelativeSource={RelativeSource Self}}" Value="检查结果"/>
<Condition Binding="{Binding [检查结果]}" Value="停产部件"/>
</MultiDataTrigger.Conditions>
<Setter Property="Foreground" Value="Red"/>
</MultiDataTrigger>
<!--<DataTrigger Binding="{Binding [检查结果]}" Value="TC不存在">
<Setter Property="Foreground" Value="Red"/>
</DataTrigger>-->
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
</DataGrid>
<Grid Grid.Row="2" HorizontalAlignment="Right">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="18"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="15"/>
</Grid.ColumnDefinitions>
<Button Name="b_Export" Click="b_Export_Click" Content="导出" IsEnabled="False" Width="95" Height="25" Grid.Column="0"/>
<Button Name="b_Close" Click="b_Close_Click" Content="退出" Width="95" Height="25" Grid.Column="2"/>
</Grid>
</Grid>
</Window>

File diff suppressed because it is too large Load Diff

@ -0,0 +1,150 @@
<Window x:Class="KPlan.Forms.KPartSync"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:KPlan.Forms"
mc:Ignorable="d" Loaded="Window_Loaded" UseLayoutRounding="True" WindowStartupLocation="CenterOwner" Height="700" Width="1100" MinHeight="480" MinWidth="640" Icon="/EPLAN.EplAddin.KPlan;component/Resources/logo_16.ico" Title="部件库同步">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="KStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<!--<Grid.ColumnDefinitions>
<ColumnDefinition Width="211*"/>
<ColumnDefinition Width="565*"/>
</Grid.ColumnDefinitions>-->
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Margin="0,10,0,5" Grid.ColumnSpan="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Label Content="ERP编号" Grid.Column="0" Margin="20,0,0,0"/>
<TextBox x:Name="tb_PartNr" Grid.Column="1" Margin="0,0,20,0" VerticalContentAlignment="Center"/>
<Label Content="Item ID" Grid.Column="2"/>
<TextBox x:Name="tb_ERPNr" Grid.Column="3" Margin="0,0,20,0" VerticalContentAlignment="Center"/>
<Button Content="查询 EPLAN" Click="Query_Button_Click" Grid.Column="4" Width="80" Height="24"/>
<Button Content="查询 TC" Click="TC_Query_Button_Click" Grid.Column="6" Width="80" Height="24"/>
<Button Content="查询 EPLAN 未同步零部件" Click="Add_All_Button_Click" Grid.Column="8" Width="160" Height="24"/>
<!--<Button Content="发起编码申请流程" Click="Apply_Button_Click" Grid.Column="10" Width="120" Height="24"/>-->
</Grid>
<Grid Grid.Row="1" Grid.ColumnSpan="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="0" Margin="5,0,5,5">
<GroupBox.Header>EPLAN元器件库</GroupBox.Header>
<TreeView Name="tree_Parts" MouseDoubleClick="Tree_Parts_MouseDoubleClick" TreeViewItem.Expanded="Tree_Parts_Expanded" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</GroupBox>
<Grid VerticalAlignment="Center" Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="15"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="15"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Button Click="Add_Button_Click" Grid.Row="0" Width="32" Height="30">
<Image Source="/EPLAN.EplAddin.KPlan;component/Resources/add16.png" Height="16" Stretch="Uniform" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Button>
<Button Click="Remove_Button_Click" Grid.Row="2" Width="32" Height="30">
<Image Source="/EPLAN.EplAddin.KPlan;component/Resources/delete16.png" Width="16" Stretch="Uniform" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Button>
</Grid>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="2" Margin="5,0,5,5">
<GroupBox.Header>待同步元器件库</GroupBox.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="2*"/>
</Grid.RowDefinitions>
<!--<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1"/>
<ColumnDefinition Width="{Binding ElementName=C0, Path=ActualWidth}"/>
<ColumnDefinition Width="{Binding ElementName=C1, Path=ActualWidth}"/>
<ColumnDefinition Width="{Binding ElementName=C2, Path=ActualWidth}"/>
<ColumnDefinition Width="{Binding ElementName=C3, Path=ActualWidth}"/>
<ColumnDefinition Width="{Binding ElementName=C4, Path=ActualWidth}"/>
<ColumnDefinition Width="{Binding ElementName=C5, Path=ActualWidth}"/>
<ColumnDefinition Width="{Binding ElementName=C6, Path=ActualWidth}"/>
<ColumnDefinition Width="{Binding ElementName=C7, Path=ActualWidth}"/>
<ColumnDefinition Width="{Binding ElementName=C8, Path=ActualWidth}"/>
<ColumnDefinition Width="{Binding ElementName=C9, Path=ActualWidth}"/>
<ColumnDefinition Width="{Binding ElementName=C10, Path=ActualWidth}"/>
<ColumnDefinition Width="{Binding ElementName=C11, Path=ActualWidth}"/>
<ColumnDefinition Width="{Binding ElementName=C12, Path=ActualWidth}"/>
<ColumnDefinition Width="{Binding ElementName=C13, Path=ActualWidth}"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Background="#688CAF" Grid.Column="0" Grid.ColumnSpan="2"/>
<Label Background="#FF5959" Foreground="White" Grid.Column="2" Grid.ColumnSpan="6" HorizontalContentAlignment="Center">EPLAN 属性</Label>
<Label Background="#49BEB7" Foreground="White" Grid.Column="8" Grid.ColumnSpan="6" HorizontalContentAlignment="Center">TC 属性</Label>
<Label Grid.Column="14" Grid.ColumnSpan="2" Background="#688CAF"/>
</Grid>-->
<DataGrid Grid.Row="1" ItemsSource="{Binding}" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Loaded="Table_Sync_To_TC_Loaded" HeadersVisibility="Column" IsReadOnly="True" x:Name="table_Sync_To_TC" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="300" ColumnHeaderHeight="25" MinRowHeight="23" CanUserResizeRows="True" CanUserReorderColumns="False">
<DataGrid.Columns>
<DataGridTextColumn x:Name="C0" Header="序号" Width="50" HeaderStyle="{StaticResource white_header}" Binding="{Binding index}"/>
<!--<DataGridTextColumn Header="" CanUserResize="False" Width="1" MinWidth="1" />-->
<DataGridTextColumn x:Name="C1" Header="订货号" Width="120" HeaderStyle="{StaticResource eplan_header}" Binding="{Binding eplan_orderno}"/>
<DataGridTextColumn x:Name="C2" Header="部件编号" Width="80" HeaderStyle="{StaticResource eplan_header}" Binding="{Binding eplan_partno}"/>
<DataGridTextColumn x:Name="C3" Header="ERP编号" Width="80" HeaderStyle="{StaticResource eplan_header}" Binding="{Binding eplan_erpno}"/>
<DataGridTextColumn x:Name="C4" Header="名称" Width="120" HeaderStyle="{StaticResource eplan_header}" Binding="{Binding eplan_name}"/>
<DataGridTextColumn x:Name="C5" Header="规格描述" Width="80" HeaderStyle="{StaticResource eplan_header}" Binding="{Binding eplan_desc}"/>
<DataGridTextColumn x:Name="C6" Header="制造商" Width="80" HeaderStyle="{StaticResource eplan_header}" Binding="{Binding eplan_manufacturer}"/>
<!--<DataGridTextColumn Header="" CanUserResize="False" Width="1" MinWidth="1" />-->
<DataGridTextColumn x:Name="C7" Header="ItemID" Width="120" HeaderStyle="{StaticResource tc_header}" Binding="{Binding tc_itemid}"/>
<DataGridTextColumn x:Name="C8" Header="Item名称" Width="120" HeaderStyle="{StaticResource tc_header}" Binding="{Binding tc_name}"/>
<DataGridTextColumn x:Name="C9" Header="版本" Width="40" HeaderStyle="{StaticResource tc_header}" Binding="{Binding tc_revid}"/>
<DataGridTextColumn x:Name="C10" Header="规格描述" Width="80" HeaderStyle="{StaticResource tc_header}" Binding="{Binding tc_desc}"/>
<DataGridTextColumn x:Name="C11" Header="制造商" Width="80" HeaderStyle="{StaticResource tc_header}" Binding="{Binding tc_manufacturer}"/>
<DataGridTextColumn x:Name="C12" Header="发布状态" Width="80" HeaderStyle="{StaticResource tc_header}" Binding="{Binding tc_releasestatus}"/>
<!--<DataGridTextColumn Header="" CanUserResize="False" Width="1" MinWidth="1" />-->
<DataGridTextColumn x:Name="C13" Header="同步状态" Width="80" HeaderStyle="{StaticResource white_header}" Binding="{Binding sync_status}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</GroupBox>
</Grid>
<Grid Grid.Row="2" HorizontalAlignment="Center" Margin="0,5,0,10" Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Button Content="EPLAN 数据同步至 TC" Width="140" Height="24" Grid.Column="0" Click="EPlan_to_TC_Button_Click"/>
<Button Content="TC 数据同步至 EPLAN" Margin="15,0" Width="140" Height="24" Grid.Column="1" Click="TC_to_EPLAN_Button_Click"/>
<Button Content="ItemID 同步至 订货号" Width="140" Height="24" Grid.Column="2" Click="SyncErpCode_Button_Click"/>
<!--<Button Content="部件升版" Width="80" Height="24" Grid.Column="3" Margin="15,0,120,0" Click="Revise_Button_Click"/>
<Button Content="上传 EPLAN 项目主数据" Width="150" Height="24" Grid.Column="4" Click="Upload_PartsDB"/>-->
</Grid>
</Grid>
</Window>

File diff suppressed because it is too large Load Diff

@ -0,0 +1,58 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:f="clr-namespace:KPlan.Forms">
<Style TargetType="{x:Type f:EPlanTreeItem}">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image
Width="16"
Height="16"
Stretch="Fill"
Source="{DynamicResource ICON}"
/>
<TextBlock Text="{Binding}" Margin="5,0" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="Margin" Value="0 2 0 0" />
</Style>
<Style TargetType="{x:Type f:TCTreeItem}">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image
Width="16"
Height="16"
Stretch="Fill"
Source="{DynamicResource ICON}"
/>
<TextBlock Text="{Binding}" Margin="5,0" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type DataGridColumnHeader}" x:Key="white_header">
<Setter Property="Background" Value="LightGray" />
<Setter Property="BorderBrush" Value="#000"/>
<Setter Property="BorderThickness" Value="0,0,1,0"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
<Style TargetType="{x:Type DataGridColumnHeader}" x:Key="tc_header">
<Setter Property="Background" Value="#49BEB7" />
<Setter Property="BorderBrush" Value="#000"/>
<Setter Property="BorderThickness" Value="0,0,1,0"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
<Style TargetType="{x:Type DataGridColumnHeader}" x:Key="eplan_header">
<Setter Property="Background" Value="#FF5959" />
<Setter Property="BorderBrush" Value="#000"/>
<Setter Property="BorderThickness" Value="0,0,1,0"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
</ResourceDictionary>

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
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 KPlan.Util;
namespace KPlan.Forms {
/// <summary>
/// KStyle.xaml 的交互逻辑
/// </summary>
public partial class KStyle : ResourceDictionary {
public KStyle() {
}
}
}

@ -0,0 +1,36 @@
<Window x:Class="KPlan.Forms.Login"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" Icon="/EPLAN.EplAddin.KPlan;component/Resources/logo_16.ico" Background="{x:Null}" Visibility="Visible" WindowStartupLocation="CenterOwner"
MouseDown="Window_MouseDown" Height="290" Width="288" FontFamily="Microsoft YaHei" Foreground="{x:Null}" TextOptions.TextFormattingMode="Display" AllowsTransparency="True" WindowStyle="None" ResizeMode="NoResize" Padding="0"
>
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="KStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid Margin="0,0,-2,-2">
<Rectangle Fill="#FFFBFBFB" RadiusX="8" RadiusY="8" Margin="10,10,10,10">
<Rectangle.Effect>
<DropShadowEffect BlurRadius="10" ShadowDepth="-5" Opacity="0.8" Direction="0" Color="#FF303030"/>
</Rectangle.Effect>
</Rectangle>
<Label Content="用户名" HorizontalAlignment="Left" Margin="48,57,0,0" VerticalAlignment="Top"/>
<Label Content="密 码" HorizontalAlignment="Left" Margin="48,102,0,0" VerticalAlignment="Top"/>
<Label Content="角 色" HorizontalAlignment="Left" Margin="48,147,0,0" VerticalAlignment="Top"/>
<TextBox Name="tb_UserName" HorizontalAlignment="Left" Height="27" Margin="98,54,0,0" VerticalAlignment="Top" Width="150" BorderThickness="0,0,0,2" VerticalContentAlignment="Bottom" ToolTip="" Background="#FFFBFBFB"/>
<PasswordBox Name="tb_Password" HorizontalAlignment="Left" Height="27" Margin="98,99,0,0" VerticalAlignment="Top" Width="150" VerticalContentAlignment="Bottom" BorderThickness="0,0,0,2" Background="#FFFBFBFB"/>
<TextBox Name="tb_Character" HorizontalAlignment="Left" Height="27" Margin="98,144,0,0" VerticalAlignment="Top" Width="150" VerticalContentAlignment="Bottom" BorderThickness="0,0,0,2" Background="#FFFBFBFB"/>
<CheckBox Name="cb_AutoLogin" Content="自动登录" HorizontalAlignment="Right" Margin="0,183,50,0" VerticalAlignment="Top"/>
<Button x:Name="b_Login" Content="登录" HorizontalAlignment="Left" Margin="50,214,0,0" VerticalAlignment="Top" Width="75" Height="24" IsDefault="True" Click="DoLogin"/>
<Rectangle Name="rec_Logout" Fill="#FFFBFBFB" RadiusX="8" RadiusY="8" Margin="10,10,10,10" Visibility="Hidden"/>
<Button x:Name="b_Close" Content="关闭" HorizontalAlignment="Right" Margin="0,214,50,0" VerticalAlignment="Top" Width="75" Height="24" Click="Button_Click_1" IsCancel="True"/>
<Button Name="b_Logout" Content="注销" HorizontalAlignment="Left" Margin="50,214,0,0" VerticalAlignment="Top" Width="75" Height="24" Click="DoLogout" Visibility="Hidden"/>
<Label Name="l_UserNameTitle" Content="当前登录用户:" HorizontalAlignment="Left" Margin="48,116,0,0" VerticalAlignment="Top" Visibility="Hidden"/>
<Label Name="l_UserName" Content="" HorizontalAlignment="Left" Margin="142,116,0,0" VerticalAlignment="Top" Visibility="Hidden"/>
</Grid>
</Window>

@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
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 KPlan.Util;
using System.Threading;
using System.Windows.Threading;
namespace KPlan.Forms {
/// <summary>
/// Login.xaml 的交互逻辑
/// </summary>
public partial class Login : System.Windows.Window {
public Login() {
InitializeComponent();
KUtil.SetOwnerWindow(this);
LoadFromConfig();
}
private void Button_Click_1(object sender, RoutedEventArgs e) {
Close();
}
private void SetLoginVisible(string userName) {
Visibility v;
if (KUtil.IsEmpty(userName)) {
v = Visibility.Hidden;
}
else {
//KUtil.Log("用户已登录:" + userName);
v = Visibility.Visible;
}
l_UserName.Content = userName;
rec_Logout.Visibility = v;
b_Logout.Visibility = v;
l_UserName.Visibility = v;
l_UserNameTitle.Visibility = v;
b_Login.IsEnabled = KUtil.IsEmpty(userName);
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e) {
if (e.ChangedButton == MouseButton.Left)
this.DragMove();
}
private void DoLogin(object sender, RoutedEventArgs e) {
string userName = tb_UserName.Text;
string password = tb_Password.Password;
string character = tb_Character.Text;
bool autoLogin = cb_AutoLogin.IsChecked.Value;
string host = KUtil.GetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.HOST);
try {
TCUtil.Login(host, userName, password, character, autoLogin);
SetLoginVisible(TCUtil.userName);
}
catch (Teamcenter.Schemas.Soa._2006_03.Exceptions.InvalidCredentialsException e1) {
MessageBox.Show(this, "登录失败,用户名或密码错误", "提示");
KUtil.LogErr(e1);
}
catch (System.Exception ex) {
MessageBox.Show(this, "登录失败:\n" + ex.Message, "提示");
KUtil.LogErr(ex);
}
//new Thread(() => {
// Action<string, string, string, string> loginAction = new Action<string, string, string, string>(LoginInThread);
// this.Dispatcher.BeginInvoke(loginAction, host, userName, password, character);
//}).Start();
}
private void LoadFromConfig() {
SetLoginVisible(TCUtil.userName);
tb_UserName.Text = KUtil.GetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.LOGIN_USER);
tb_Character.Text = KUtil.GetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.LOGIN_ROLE);
if (!KUtil.IsEmpty(KUtil.GetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.LOGIN_PWD))) {
cb_AutoLogin.IsChecked = true;
}
//new Thread(() => {
// this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate() {
// SetLoginVisible(TCUtil.userName);
// });
//}).Start();
}
private void DoLogout(object sender, RoutedEventArgs e) {
try {
TCUtil.Logout();
SetLoginVisible(TCUtil.userName);
//new Thread(() => {
// this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate() {
// SetLoginVisible(TCUtil.userName);
// });
//}).Start();
}
catch (System.Exception ex) {
MessageBox.Show(this, "注销出错:\n" + ex.Message, "提示");
KUtil.LogErr(ex);
}
}
//protected override void OnDeactivated(EventArgs e) {
// base.OnDeactivated(e);
// Close();
//}
}
}

@ -0,0 +1,38 @@
<Window x:Class="KPlan.Forms.NewPartNr"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:KPlan.Forms"
mc:Ignorable="d" ResizeMode="NoResize" UseLayoutRounding="True" WindowStartupLocation="CenterOwner" Height="230" Width="400" MinHeight="230" MinWidth="400" Icon="/EPLAN.EplAddin.KPlan;component/Resources/logo_16.ico" Title="新建部件">
<Grid Margin="20,20,20,10">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="12"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="12"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Content="该部件不存在于Eplan部件库如需同步请赋予部件编号前缀" Grid.Row="0" Grid.ColumnSpan="2"/>
<Label Content="制造商缩写" Grid.Row="2" Grid.Column="0"/>
<TextBox TextChanged="Tb_manufacturer_TextChanged" x:Name="tb_manufacturer" Grid.Row="2" Grid.Column="1" Width="200" HorizontalAlignment="Left" VerticalContentAlignment="Center"/>
<Label Content="部件编号预览" Grid.Row="4" Grid.Column="0"/>
<TextBox VerticalContentAlignment="Center" Text="“制造商缩写”+“.”+“订货号”" x:Name="tb_preview" Grid.Row="4" Grid.Column="1" Width="200" HorizontalAlignment="Left" IsEnabled="False"/>
<Grid Grid.Row="6" Grid.ColumnSpan="2" HorizontalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="25"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Button Content="确定" Grid.Column="0" Width="80" Height="24" Click="Button_Click"/>
<Button Content="取消" Grid.Column="2" Width="80" Height="24" Click="Button_Click_1"/>
</Grid>
</Grid>
</Window>

@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
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;
namespace KPlan.Forms {
/// <summary>
/// Interaction logic for NewPartNr.xaml
/// </summary>
public partial class NewPartNr : Window {
private string orderNr;
public string partNr { get; set; }
public NewPartNr(KPartSync kPartSync, string orderNr) {
InitializeComponent();
this.Owner = kPartSync;
this.orderNr = orderNr;
}
private string getPartNr() {
string manufacurer = tb_manufacturer.Text;
if (KPlan.Util.KUtil.IsEmpty(manufacurer)) {
return "";
}
string partNr = manufacurer + "." + orderNr;
return partNr;
}
private void Button_Click(object sender, RoutedEventArgs e) {
partNr = getPartNr();
Close();
}
private void Button_Click_1(object sender, RoutedEventArgs e) {
Close();
}
private void Tb_manufacturer_TextChanged(object sender, TextChangedEventArgs e) {
tb_preview.Text = getPartNr();
}
}
}

@ -0,0 +1,85 @@
<Window x:Class="KPlan.Forms.OpenFromTC"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" Loaded="WindowLoaded" UseLayoutRounding="True" WindowStartupLocation="CenterOwner" Height="600" Width="800" MinHeight="480" MinWidth="640" Icon="/EPLAN.EplAddin.KPlan;component/Resources/logo_16.ico" Title="打开">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="KStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="5" MaxWidth="5"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Name="rd_QueryField" Height="*"/>
<RowDefinition Height="5"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="0" Margin="5,2,5,5" >
<GroupBox.Header>查询条件</GroupBox.Header>
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="0">
<Grid MinWidth="300" Margin="0,7,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="5"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Grid Name="grid_QueryField" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
</Grid>
<Grid HorizontalAlignment="Center" VerticalAlignment="Stretch" Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Button Name="b_Open" Content="打开" Width="75" Height="24" Grid.Column="0" Click="b_Open_Click"/>
<Button Name="b_Query" Content="查询" Width="75" Height="24" Grid.Column="1" Click="b_Query_Click"/>
<Button Name="b_Reset" Content="重置" Width="75" Height="24" Grid.Column="2" Click="b_Reset_Click"/>
</Grid>
</Grid>
</ScrollViewer>
</GroupBox>
<GridSplitter HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1" Background="#FFE6E6E6" />
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="2" Margin="5,2,5,5">
<GroupBox.Header>查询结果</GroupBox.Header>
<DataGrid VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Loaded="QueryTableLoaded" ItemsSource="{Binding}" HeadersVisibility="Column" IsReadOnly="True" Name="datagrid_SearchResult" SelectionChanged="dataGrid_SelectionChanged" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="300" ColumnHeaderHeight="25" RowHeight="23" CanUserResizeRows="False" />
<!--<ScrollViewer Name="scroll_Datagrid" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" >
</ScrollViewer>-->
</GroupBox>
</Grid>
<GridSplitter HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="1" Background="#FFE6E6E6"/>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="2" Margin="5,2,5,5">
<GroupBox.Header>我的Teamcenter</GroupBox.Header>
<TabControl x:Name="tab_home" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,2,0,0">
<TabItem Header="Home">
<!--<TabItem.Style>
<Style TargetType="TabItem">
<Setter Property="Header">
<Setter.Value>
<Image Height="16" Width="16" Source="/EPLAN.EplAddin.KPlan;component/Resources/openhome_16.png"/>
</Setter.Value>
</Setter>
</Style>
</TabItem.Style>-->
<TreeView Name="tree_Home" SelectedItemChanged="tree_SelectionChanged" TreeViewItem.Expanded="ExpandHomeTree" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</TabItem>
<TabItem Name="tabItem_SearchTarget" Header="TabItem" Visibility="Hidden">
<TreeView Name="tree_SearchTarget" SelectedItemChanged="tree_SelectionChanged" TreeViewItem.Expanded="ExpandHomeTree" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</TabItem>
</TabControl>
</GroupBox>
</Grid>
</Window>

@ -0,0 +1,606 @@
using System;
using System.Collections.Generic;
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 KPlan.Util;
using System.Data;
using Teamcenter.Soa.Client.Model;
using System.ComponentModel;
using Teamcenter.Soa.Client.Model.Strong;
using System.IO;
using Eplan.EplApi.DataModel;
using Eplan.EplApi.Base;
using Eplan.EplApi.ApplicationFramework;
using Action = System.Action;
using Eplan.EplApi.HEServices;
using System.Collections.Specialized;
using Label = System.Windows.Controls.Label;
namespace KPlan.Forms {
/// <summary>
/// OpenFromTC.xaml 的交互逻辑
/// </summary>
public partial class OpenFromTC : Window {
private string queryName;
private Dictionary<string, TextBox> queryFieldMap = new Dictionary<string,TextBox>();
private DataTable queryResultData = new DataTable();
private List<string> queryResultConfig = new List<string>();
private List<int> queryResultWidth = new List<int>();
private KBackgroundWorker bgWorker_Query;
private KBackgroundWorker bgWorker_Homer;
private KBackgroundWorker bgWorker_Open;
private ModelObject selectedObject;
public OpenFromTC() {
InitializeComponent();
KUtil.SetOwnerWindow(this);
LoadFromConfiguration();
bgWorker_Query = new KBackgroundWorker(this);
bgWorker_Query.backgroundWorker.DoWork += Async_Query;
bgWorker_Homer = new KBackgroundWorker(this);
bgWorker_Homer.backgroundWorker.DoWork += Async_LoadHome;
bgWorker_Open = new KBackgroundWorker(this);
bgWorker_Open.backgroundWorker.DoWork += Async_Open;
}
private void Async_Open(object sender, DoWorkEventArgs e) {
ModelObject mo = (ModelObject)e.Argument;
if (mo == null) {
return;
}
bgWorker_Open.Progress("正在打开...", 1);
string eplanDSType = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_ZW_DSTYPE);
List<Dataset> target = new List<Dataset>();
if (TCUtil.IsType(mo.SoaType, "Dataset")) {
//if (!TCUtil.IsType(mo.SoaType, TCUtil.TYPE_EPLAN)) {
// KUtil.DispatcherShow(this, "请选择" + TCUtil.TYPE_EPLAN + "数据集进行操作");
// return;
//}
target.Add((Dataset)mo);
}else if (TCUtil.IsType(mo.SoaType, "ItemRevision")) {
ModelObject[] children = TCUtil.GetChildFromPref(mo);
for(int i = 0; i < children.Length; i++) {
if (TCUtil.IsType(children[i].SoaType, eplanDSType)) {
target.Add((Dataset)children[i]);
}
}
}
else {
KUtil.DispatcherShow(this,"请选择版本或数据集进行操作");
return;
}
if (target.Count == 0) {
KUtil.DispatcherShow(this, "当前对象下不存在EPLAN数据集");
return;
}
if (target.Count > 1) {
KUtil.DispatcherShow(this,"当前对象下存在多个数据集,请选择要打开的数据集");
return;
}
Dataset ds = target[0];
List<ImanFile> imanFiles = TCUtil.GetDatasetFile(ds, null);
TCUtil.GetProperties(false, TCUtil.Refresh(ds), "object_string");
if (imanFiles.Count == 0) {
KUtil.DispatcherShow(this, "数据集<"+ds.Object_string+">下没有找到引用文件");
return;
}
if (imanFiles.Count > 1) {
KUtil.DispatcherShow(this, "数据集<" + ds.Object_string + ">下找到多个引用文件");
return;
}
FileInfo file = TCUtil.GetFileInfo(imanFiles[0]);
if (file == null) {
KUtil.DispatcherShow(this, "从数据集<"+ds.Object_string+">下载引用文件失败");
return;
}
if (file.Attributes.ToString().IndexOf("ReadOnly") != -1) {
file.Attributes = FileAttributes.Normal;
}
if (file.FullName.ToLower().EndsWith("zw1")) {
string projName = file.Name.Replace(".zw1", "").Replace(".ZW1", "");
KUtil.Log("打开项目:"+projName+" - "+file.FullName);
string targetFolder = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_WORKSAPCE);
if (KUtil.IsEmpty(targetFolder)) {
KUtil.DispatcherShow(this, "未配置项目解压路径");
return;
}
if (!Directory.Exists(targetFolder)) {
Directory.CreateDirectory(targetFolder);
}
RestoreProject(targetFolder,file.FullName, projName);
}
else {
System.Diagnostics.Process.Start(file.FullName);
}
}
private void openDs(ModelObject mo, Progress progress) {
if (mo == null) {
return;
}
string eplanDSType = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_ZW_DSTYPE);
List<Dataset> target = new List<Dataset>();
if (TCUtil.IsType(mo.SoaType, "Dataset")) {
//if (!TCUtil.IsType(mo.SoaType, TCUtil.TYPE_EPLAN)) {
// KUtil.DispatcherShow(this, "请选择" + TCUtil.TYPE_EPLAN + "数据集进行操作");
// return;
//}
target.Add((Dataset)mo);
}
else if (TCUtil.IsType(mo.SoaType, "ItemRevision")) {
ModelObject[] children = TCUtil.GetChildFromPref(mo);
for (int i = 0; i < children.Length; i++) {
if (TCUtil.IsType(children[i].SoaType, eplanDSType)) {
target.Add((Dataset)children[i]);
}
}
}
else {
KUtil.DispatcherShow(this, "请选择版本或数据集进行操作");
return;
}
if (target.Count == 0) {
KUtil.DispatcherShow(this, "当前对象下不存在EPLAN数据集");
return;
}
if (target.Count > 1) {
KUtil.DispatcherShow(this, "当前对象下存在多个数据集,请选择要打开的数据集");
return;
}
Dataset ds = target[0];
List<ImanFile> imanFiles = TCUtil.GetDatasetFile(ds, null);
TCUtil.GetProperties(false, TCUtil.Refresh(ds), "object_string");
if (imanFiles.Count == 0) {
KUtil.DispatcherShow(this, "数据集<" + ds.Object_string + ">下没有找到引用文件");
return;
}
if (imanFiles.Count > 1) {
KUtil.DispatcherShow(this, "数据集<" + ds.Object_string + ">下找到多个引用文件");
return;
}
FileInfo file = TCUtil.GetFileInfo(imanFiles[0]);
if (file == null) {
KUtil.DispatcherShow(this, "从数据集<" + ds.Object_string + ">下载引用文件失败");
return;
}
if (file.Attributes.ToString().IndexOf("ReadOnly") != -1) {
file.Attributes = FileAttributes.Normal;
}
Close();
progress.BeginPart(100.0, "");
progress.ShowImmediately();
progress.SetAllowCancel(true);
if (file.FullName.ToLower().EndsWith("zw1")) {
string projName = file.Name.Replace(".zw1", "").Replace(".ZW1", "");
KUtil.Log("打开项目:" + projName + " - " + file.FullName);
string targetFolder = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION,KConfigure.EPLAN_WORKSAPCE);
if (KUtil.IsEmpty(targetFolder)) {
KUtil.DispatcherShow(this, "未配置项目解压路径");
return;
}
if (!Directory.Exists(targetFolder)) {
Directory.CreateDirectory(targetFolder);
}
using (new LockingStep()) {
RestoreProject(targetFolder,file.FullName, projName);
}
}
else {
System.Diagnostics.Process.Start(file.FullName);
}
}
private bool RestoreProject(string folderPath,string zipName, string projName) {
Restore restore = new Restore();
StringCollection archives = new StringCollection();
archives.Add(zipName);
restore.Project(archives, folderPath, projName, false, true);
ProjectManager manager = new ProjectManager();
if (File.Exists(folderPath + "\\" + projName + ".elk")) {
manager.OpenProject(folderPath + "\\" + projName + ".elk");
}
else if (File.Exists(folderPath + "\\" + projName + ".ell")) {
manager.OpenProject(folderPath + "\\" + projName + ".ell");
}
else {
throw new Exception("未找到项目文件");
}
/*try {
manager = new ProjectManager();
context = new ActionCallingContext();
context.AddParameter("TYPE", "PROJECT");
context.AddParameter("ARCHIVENAME", zipName);
context.AddParameter("PROJECTNAME", projName);
context.AddParameter("UNPACKPROJECT", "0");
// progress = new Progress("SimpleProgress");
//progress.BeginPart(100.0, "");
//progress.ShowImmediately();
// progress.SetAllowCancel(true);
interpreter = new CommandLineInterpreter();
if (interpreter.Execute("restore", context)) {
//MessageBox.Show("该项目不能恢复!");
}
// progress.EndPart(true);
manager.OpenProject(PathMap.SubstitutePath(projName));
}
catch (Exception exception1) {
KUtil.LogErr(exception1);
KUtil.DispatcherShow(this, exception1.Message);
}*/
return true;
}
private void b_Open_Click(object sender, RoutedEventArgs e) {
if (this.selectedObject == null) {
MessageBox.Show(this, "请选择要打开的对象");
}
else {
Progress progress = new Progress("SimpleProgress");
try {
openDs(selectedObject, progress);
progress.EndPart(true);
}
catch(System.Exception ex) {
KUtil.LogErr(ex);
progress.EndPart(true);
MessageBox.Show(this,"打开出错:"+ex.Message);
}
//bgWorker_Open.Start(this.selectedObject);
}
}
private void LoadFromConfiguration() {
//加载查询条件
LoadQueryFields();
//加载查询结果
LoadQueryTable();
}
private void LoadQueryTable() {
queryResultData.Rows.Clear();
string queryResults = KUtil.GetConfigValue(KConfigure.QUERY_PROJ_SECTION, KConfigure.QUERY_PROJ_RESULTS);
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 titile = queryResult;
string config = queryResult;
int width = 50;
string[] split = queryResult.Split(',');
if (split.Length > 1) {
titile = split[0].Trim();
config = split[1].Trim();
}
if (split.Length > 2) {
Int32.TryParse(split[2].Trim(), out width);
}
queryResultConfig.Add(config);
queryResultWidth.Add(width);
queryResultData.Columns.Add(new DataColumn() {
ColumnName = titile,
DataType = i == 0 ? typeof(TableRowData) : typeof(string)
});
}
//queryResultData.Rows.Add(new object[] { 1 });
datagrid_SearchResult.DataContext = queryResultData.DefaultView;
}
private void LoadQueryFields() {
string heightConfig = KUtil.GetConfigValue(KConfigure.QUERY_PROJ_SECTION, KConfigure.QUERY_PROJ_HEIGHT);
if(!KUtil.IsEmpty(heightConfig)){
double h = 0;
Double.TryParse(heightConfig,out h);
if (h > 0) {
rd_QueryField.Height = new GridLength(h);
}
}
this.queryName = KUtil.GetConfigValue(KConfigure.QUERY_PROJ_SECTION, KConfigure.QUERY_PROJ_NAME);
string queryFields = KUtil.GetConfigValue(KConfigure.QUERY_PROJ_SECTION, KConfigure.QUERY_PROJ_FIELDS);
string[] queryFieldSplit = queryFields.Split(';');
int len = queryFieldSplit.Length;
for (int i = 0; i < len; i++) {
string queryField = queryFieldSplit[i].Trim();
if (KUtil.IsEmpty(queryField)) {
continue;
}
string disName = queryField;
string realName = queryField;
string[] split = queryField.Split(',');
if (split.Length == 2) {
disName = split[0].Trim();
realName = split[1].Trim();
}
if (queryFieldMap.ContainsKey(realName)) {
continue;
}
RowDefinition rd = new RowDefinition();
rd.Height = new GridLength(1.0, GridUnitType.Auto);
grid_QueryField.RowDefinitions.Add(rd);
Label label = new Label();
label.Content = disName;
label.HorizontalContentAlignment=HorizontalAlignment.Right;
Grid.SetRow(label,queryFieldMap.Count);
Grid.SetColumn(label,0);
grid_QueryField.Children.Add(label);
TextBox textBox = new TextBox();
Grid.SetRow(textBox, queryFieldMap.Count);
Grid.SetColumn(textBox, 1);
textBox.Margin = new Thickness(0, 2, 0, 8);
textBox.Height = 24;
textBox.VerticalContentAlignment = VerticalAlignment.Center;
grid_QueryField.Children.Add(textBox);
queryFieldMap.Add(realName, textBox);
}
}
private void Async_Query(object sender, DoWorkEventArgs e) {
Dictionary<string, string> fields = (Dictionary<string, string>)e.Argument;
ModelObject[] queryRes=null;
try {
bgWorker_Query.Progress("正在查询...", 1);
queryRes = TCUtil.query(queryName, fields);
}
catch (System.Exception ex) {
this.Dispatcher.Invoke(new Action(delegate {
MessageBox.Show(this, "查询出错:" + ex.Message, "错误");
}));
KUtil.LogErr(ex);
return;
}
if (queryRes == null) {
return;
}
//提取信息
TCUtil.dmService.RefreshObjects(queryRes);
try {
int len = queryRes.Length;
for (int i = 0; i < len; i++) {
if (bgWorker_Query.IsCancel()) {
e.Cancel = true;
break;
}
bgWorker_Query.Progress("加载数据 " + (i + 1) + "/" + len + " ", (i + 1) * 100 / len);
TableRowData data = new TableRowData(queryRes[i]);
object[] rowData = data.GetRowData(i + 1, queryResultConfig);
this.Dispatcher.Invoke(new Action(delegate {
queryResultData.Rows.Add(rowData);
}));
}
}
catch (System.Exception ex) {
this.Dispatcher.Invoke(new Action(delegate {
MessageBox.Show(this, "读取数据出错:" + ex.Message, "错误");
}));
KUtil.LogErr(ex);
return;
}
}
private void Async_LoadHome(object sender, DoWorkEventArgs e) {
TCTreeItem parent = (TCTreeItem)e.Argument;
if (parent == null) {
//tree_Home.Items.Clear();
if (TCUtil.user == null) {
throw new Exception("加载Home失败用户未登录");
}
Folder home = TCUtil.user.Home_folder;
//TreeViewItem node_home = null;
bgWorker_Homer.Progress("加载中...", 0);
TCTreeItem tree_home = null;
this.Dispatcher.Invoke(new Action(delegate {
tree_home = new TCTreeItem(home);
tree_Home.Items.Add(tree_home);
tree_home.Items.Add(new TCTreeItem(null));
}));
}
else {
Cycle_Home(parent, e);
}
//this.Dispatcher.Invoke(new Action(delegate {
// MessageBox.Show(this,"Home下对象数量"+mo.Length);
//}));
}
private void Cycle_Home(TCTreeItem treeItem, DoWorkEventArgs e) {
if (!(treeItem.Items.Count == 1 && ((TCTreeItem)treeItem.Items.GetItemAt(0)).mo == null)) {
return;
}
this.Dispatcher.Invoke(new Action(delegate {
treeItem.Items.Clear();
}));
ModelObject parent = treeItem.mo;
ModelObject[] children = null;
//var t = parent.GetType();
SoaType soaType = parent.SoaType;
ModelObject[] mo = TCUtil.Refresh(parent);
if (TCUtil.IsType(soaType,"Folder")) {
TCUtil.GetProperties(false, mo, "contents");
children = ((Folder)parent).Contents;
}
else if (TCUtil.IsType(soaType, "Item") || TCUtil.IsType(soaType, "ItemRevision")) {
children = TCUtil.GetChildFromPref(parent);
}
//else if(TCUtil.IsType(soaType,"Item")){
// TCUtil.GetProperties(false, mo, "displayable_revisions");
// children = ((Item)parent).Displayable_revisions;
//}
//else if (TCUtil.IsType(soaType,"ItemRevision")) {
// TCUtil.GetProperties(false, mo, "IMAN_specification");
// children = ((ItemRevision)parent).GetProperty("IMAN_specification").ModelObjectArrayValue;
//}
else if (TCUtil.IsType(soaType,"Dataset")) {
children = null;
}
else {
return;
}
if (children == null) {
return;
}
if (bgWorker_Query.IsCancel()) {
e.Cancel = true;
return;
}
string eplanDSType = KUtil.GetConfigValue(KConfigure.PROJ_SYNC_SECTION, KConfigure.PROJ_SYNC_ZW_DSTYPE);
ItemCollection node_children = null;
this.Dispatcher.Invoke(new Action(delegate {
node_children = treeItem.Items;
}));
int len = children.Length;
for (int i=0;i<len;i++) {
if (bgWorker_Query.IsCancel()) {
e.Cancel = true;
return;
}
bgWorker_Homer.Progress("加载中...( "+(i+1)+" / "+len+" )", (i + 1) * 100 / len);
ModelObject c = children[i];
if (TCUtil.IsType(c.SoaType, "Dataset")&&!TCUtil.IsType(c.SoaType, eplanDSType)) {
continue;
}
TCTreeItem node_child = null;
this.Dispatcher.Invoke(new Action(delegate {
node_child = new TCTreeItem(c);
node_children.Add(node_child);
node_child.Items.Add(new TCTreeItem(null));
}));
//Cycle_Home(c, node_children2, false);
}
//添加视图
if(TCUtil.IsType(soaType, "ItemRevision")&&!TCUtil.IsType(soaType, "SF6_ElecHWDesignRevision")) {
TCUtil.GetProperties(false, new ModelObject[] { parent }, new string[] { "view" });
ModelObject[] bomChildren = ((ItemRevision)parent).View;
int bomCnt = bomChildren == null ? 0 : bomChildren.Length;
if (bomCnt > 0) {
this.Dispatcher.Invoke(new Action(delegate {
TCTreeItem viewNode = new TCTreeItem(parent, "View", "folder_16.png");
node_children.Add(viewNode);
ItemCollection view_children = viewNode.Items;
for(int i = 0; i < bomCnt; i++) {
if (bgWorker_Query.IsCancel()) {
e.Cancel = true;
return;
}
bgWorker_Homer.Progress("加载视图...( " + (i + 1) + " / " + bomCnt + " )", (i + 1) * 100 / bomCnt);
TCTreeItem cc = new TCTreeItem(bomChildren[i]);
view_children.Add(cc);
cc.Items.Add(new TCTreeItem(null));
}
}));
}
}
}
private void WindowLoaded(object sender, RoutedEventArgs e) {
bgWorker_Homer.Start(null);
}
private void ExpandHomeTree(object sender, RoutedEventArgs e) {
TCTreeItem item = e.OriginalSource as TCTreeItem;
bgWorker_Homer.Start(item);
}
private void b_Query_Click(object sender, RoutedEventArgs e) {
queryResultData.Rows.Clear();
//查询
Dictionary<string, string> fields= new Dictionary<string, string>();
foreach (string key in queryFieldMap.Keys) {
string value = queryFieldMap[key].Text;
if (!KUtil.IsEmpty(value)) {
fields.Add(key, value);
}
}
if (fields.Count == 0) {
MessageBox.Show(this, "请输入查询条件", "提示");
return;
}
//异步执行
bgWorker_Query.Start(fields);
//bgWorker = new KBgWorker2(this,backgroundWorker);
//backgroundWorker.RunWorkerAsync(fields);
}
private void b_Reset_Click(object sender, RoutedEventArgs e) {
foreach (TextBox tb in queryFieldMap.Values) {
tb.Text = "";
}
queryResultData.Rows.Clear();
}
//private void DataGrid_PreviewMouseWheel(object sender, MouseWheelEventArgs e) {
// ScrollViewer scv = (ScrollViewer)sender;
// scv.ScrollToVerticalOffset(scv.VerticalOffset - e.Delta);
// e.Handled = true;
//}
private void QueryTableLoaded(object sender, RoutedEventArgs e) {
int len = queryResultWidth.Count;
for (int i = 0; i < len; i++) {
datagrid_SearchResult.Columns[i].Width = queryResultWidth[i];
}
}
private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) {
int index = datagrid_SearchResult.SelectedIndex;
if (index < 0) {
tabItem_SearchTarget.Visibility = Visibility.Hidden;
tab_home.SelectedIndex = 0;
selectedObject = null;
return;
}
tabItem_SearchTarget.Visibility = Visibility.Visible;
tab_home.SelectedIndex = 1;
try {
tree_SearchTarget.Items.Clear();
DataRow row = queryResultData.Rows[index];
TableRowData ss = row.Field<TableRowData>(0);
ModelObject mo = ss.mo;
this.selectedObject = mo;
ModelObject[] mos = TCUtil.Refresh(mo);
TCUtil.GetProperties(false, mos, "object_string");
tabItem_SearchTarget.Header = mo.GetPropertyDisplayableValue("object_string");
TCTreeItem target = new TCTreeItem(mo);
tree_SearchTarget.Items.Add(target);
target.Items.Add(new TCTreeItem(null));
this.Dispatcher.Invoke(new Action(delegate {
target.ExpandSubtree();
}));
} catch (System.Exception ex) {
KUtil.LogErr(ex);
MessageBox.Show(ex.Message);
}
}
private void tree_SelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e) {
TCTreeItem target = e.NewValue as TCTreeItem;
if(target == null) {
this.selectedObject = null;
}
else {
this.selectedObject = target.mo;
}
}
}
}

@ -0,0 +1,145 @@
<Window x:Class="KPlan.Forms.PartSync"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" Loaded="Window_Loaded" UseLayoutRounding="True" WindowStartupLocation="CenterScreen" Height="640" Width="1120" MinHeight="480" MinWidth="640" Icon="/EPLAN.EplAddin.KPlan;component/Resources/logo_16.ico" Title="部件库同步">
<!--<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="KStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>-->
<TabControl HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="5,5,5,5">
<TabItem Header="EPLAN to TC">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Margin="0,10,0,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Label Content="部件编号" Grid.Column="0"/>
<TextBox x:Name="tb_PartNr" Grid.Column="1" Margin="0,0,20,0" VerticalContentAlignment="Center"/>
<Label Content="Item ID" Grid.Column="2"/>
<TextBox x:Name="tb_ERPNr" Grid.Column="3" Margin="0,0,20,0" VerticalContentAlignment="Center"/>
<Button Content="查询" Click="Query_Button_Click" Grid.Column="4" Width="80" Height="24"/>
</Grid>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="0" Margin="5,0,5,5">
<GroupBox.Header>EPLAN元器件库</GroupBox.Header>
<TreeView Name="tree_Parts" MouseDoubleClick="Tree_Parts_MouseDoubleClick" TreeViewItem.Expanded="Tree_Parts_Expanded" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</GroupBox>
<Grid VerticalAlignment="Center" Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="15"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="15"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Button Content=">" Click="Add_Button_Click" Grid.Row="0" Width="60" Height="30"/>
<Button Content="-" Click="Remove_Button_Click" Grid.Row="2" Width="60" Height="30"/>
<Button Grid.Row="4" Click="Add_All_Button_Click" Width="60
" Height="50">
<TextBlock Text="添加EPLAN未同步零件" TextWrapping="Wrap" TextAlignment="Center"/>
</Button>
</Grid>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="2" Margin="5,0,5,5">
<GroupBox.Header>待同步元器件库</GroupBox.Header>
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Loaded="Table_Sync_To_TC_Loaded" HeadersVisibility="Column" IsReadOnly="True" Name="table_Sync_To_TC" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="300" ColumnHeaderHeight="25" RowHeight="23" CanUserResizeRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="序号" Width="50" Binding="{Binding index}"/>
<DataGridTextColumn Header="部件编号" Width="120" Binding="{Binding partNr}"/>
<DataGridTextColumn Header="名称" Width="80" Binding="{Binding name}"/>
<DataGridTextColumn Header="Item ID" Width="80" Binding="{Binding itemID}"/>
<DataGridTextColumn Header="Item名称" Width="80" Binding="{Binding itemName}"/>
<DataGridTextColumn Header="Item版本" Width="80" Binding="{Binding itemRev}"/>
<DataGridTextColumn Header="零件类别" Width="80" Binding="{Binding type}"/>
<DataGridTextColumn Header="发布状态" Width="80" Binding="{Binding releaseStatus}"/>
<DataGridTextColumn Header="同步状态" Width="80" Binding="{Binding syncStatus}"/>
</DataGrid.Columns>
</DataGrid>
</GroupBox>
</Grid>
<Grid Grid.Row="2" HorizontalAlignment="Center" Margin="0,5,0,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="140"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Button Content="EPLAN to TC" Width="80" Height="24" Grid.Column="0" Click="EPlan_to_TC_Button_Click"/>
<Button Content="修订" Width="80" Height="24" Grid.Column="1" Click="Revise_Button_Click"/>
<Button Content="EPLAN数据文件上传" Width="120" Height="24" Grid.Column="2" Click="Upload_PartsDB"/>
<Button Content="同步ERP编码" Width="80" Height="24" Grid.Column="3" Click="SyncErpCode_Button_Click"/>
<Button Content="取消" Width="80" Height="24" Grid.Column="4" Click="Close_Button_Click"/>
</Grid>
</Grid>
</TabItem>
<TabItem Header="TC to EPLAN">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Margin="0,10,0,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Label Content="部件编号" Grid.Column="0"/>
<TextBox x:Name="tb_PartNr_TC" Grid.Column="1" Margin="0,0,20,0" VerticalContentAlignment="Center"/>
<Label Content="Item ID" Grid.Column="2"/>
<TextBox x:Name="tb_ItemID_TC" Grid.Column="3" Margin="0,0,20,0" VerticalContentAlignment="Center"/>
<Button Content="查询" Grid.Column="4" Width="80" Height="24" Click="TC_Query_Button_Click"/>
</Grid>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1" Margin="5,0,5,5">
<GroupBox.Header>待同步元器件库</GroupBox.Header>
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Loaded="Table_Sync_To_TC_Loaded" HeadersVisibility="Column" IsReadOnly="True" Name="table_Sync_To_EPLAN" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="300" ColumnHeaderHeight="25" RowHeight="23" CanUserResizeRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="序号" Width="50" Binding="{Binding index}"/>
<DataGridTextColumn Header="部件编号" Width="180" Binding="{Binding partNr}"/>
<DataGridTextColumn Header="名称" Width="150" Binding="{Binding name}"/>
<DataGridTextColumn Header="Item ID" Width="150" Binding="{Binding itemID}"/>
<DataGridTextColumn Header="Item名称" Width="150" Binding="{Binding itemName}"/>
<DataGridTextColumn Header="Item版本" Width="80" Binding="{Binding itemRev}"/>
<DataGridTextColumn Header="零件类别" Width="80" Binding="{Binding type}"/>
<DataGridTextColumn Header="发布状态" Width="80" Binding="{Binding releaseStatus}"/>
<DataGridTextColumn Header="同步状态" Width="80" Binding="{Binding syncStatus}"/>
</DataGrid.Columns>
</DataGrid>
</GroupBox>
<Grid Grid.Row="2" HorizontalAlignment="Center" Margin="0,5,0,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Button Content="TC to EPLAN" Width="80" Height="24" Grid.Column="0" Click="TC_to_EPLAN_Button_Click"/>
<Button Content="取消" Click="Close_Button_Click" Width="80" Height="24" Grid.Column="2"/>
</Grid>
</Grid>
</TabItem>
</TabControl>
</Window>

@ -0,0 +1,923 @@
using Eplan.EplApi.MasterData;
using System;
using System.Collections.Generic;
using System.ComponentModel;
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 KPlan.Util;
using System.Collections.ObjectModel;
using ModelObject = Teamcenter.Soa.Client.Model.ModelObject;
namespace KPlan.Forms {
/// <summary>
/// Interaction logic for PartSync.xaml
/// </summary>
public partial class PartSync : Window {
public const string NOT_RELEASEED = "未发布";
public const string NOT_SYNCED = "未同步";
private MDPartsDatabase mdPartsDatabase;
private KBackgroundWorker bgWorker_Parts;
private KBackgroundWorker bgWorker_AddAll;
private KBackgroundWorker bgWorker_Query;
private KBackgroundWorker bgWorker_Query_TC;
private KBackgroundWorker bgWorker_EPlan_to_TC;
private KBackgroundWorker bgWorker_TC_to_EPlan;
private KBackgroundWorker bgWorker_Revise;
private KBackgroundWorker bgWorker_UploadPartsDB;
private KBackgroundWorker bgWorker_SyncErpCode;
private int sync_Success = 0;
//private MDPart[] allParts;
private Dictionary<MDPartsDatabaseItem.Enums.ProductTopGroup, EPlanGroup> topGroupMap = new Dictionary<MDPartsDatabaseItem.Enums.ProductTopGroup, EPlanGroup>();
private ObservableCollection<PartSyncDataRow> ePlanToTCData = new ObservableCollection<PartSyncDataRow>();
private ObservableCollection<PartSyncDataRow> tcToEPlanData = new ObservableCollection<PartSyncDataRow>();
private ObservableCollection<SyncResult> errData = new ObservableCollection<SyncResult>();
private class EPlanGroup {
public EPlanTreeItem topGroup { get; set; }
public EPlanGroup(EPlanTreeItem topGroup) {
this.topGroup = topGroup;
}
public Dictionary<MDPartsDatabaseItem.Enums.ProductGroup, EPlanTreeItem> productGroupMap = new Dictionary<MDPartsDatabaseItem.Enums.ProductGroup, EPlanTreeItem>();
}
public PartSync(MDPartsDatabase mdPartsDatabase) {
InitializeComponent();
this.mdPartsDatabase = mdPartsDatabase;
bgWorker_Parts = new KBackgroundWorker(this);
bgWorker_Parts.backgroundWorker.DoWork += Async_LoadParts;
bgWorker_AddAll = new KBackgroundWorker(this);
bgWorker_AddAll.backgroundWorker.DoWork += Async_AddAllUnsyncedParts;
bgWorker_Query = new KBackgroundWorker(this);
bgWorker_Query.backgroundWorker.DoWork += Async_QueryParts;
bgWorker_EPlan_to_TC = new KBackgroundWorker(this);
bgWorker_EPlan_to_TC.backgroundWorker.DoWork += Async_EPlan_to_TC;
bgWorker_EPlan_to_TC.backgroundWorker.RunWorkerCompleted += bgWorker_EPlan_to_TC_RunWorkerCompleted;
bgWorker_TC_to_EPlan = new KBackgroundWorker(this);
bgWorker_TC_to_EPlan.backgroundWorker.DoWork += Async_TC_to_EPlan;
bgWorker_TC_to_EPlan.backgroundWorker.RunWorkerCompleted += bgWorker_EPlan_to_TC_RunWorkerCompleted;
bgWorker_Revise = new KBackgroundWorker(this);
bgWorker_Revise.backgroundWorker.DoWork += Async_Revise;
bgWorker_Query_TC = new KBackgroundWorker(this);
bgWorker_Query_TC.backgroundWorker.DoWork += Async_QueryTCParts;
bgWorker_UploadPartsDB = new KBackgroundWorker(this);
bgWorker_UploadPartsDB.backgroundWorker.DoWork += Async_UploadPartsDB;
bgWorker_SyncErpCode = new KBackgroundWorker(this);
bgWorker_SyncErpCode.backgroundWorker.DoWork += Async_SyncErpCode;
table_Sync_To_TC.ItemsSource = ePlanToTCData;
table_Sync_To_EPLAN.ItemsSource = tcToEPlanData;
TCUtil.DO_NOTHING();
//Init_TreeGroups();
//allParts = EplanUtil.mdPartsDatabase.Parts;
}
private void Async_SyncErpCode(object sender, DoWorkEventArgs e) {
KUtil.Log("开始执行同步ERP编码");
bgWorker_SyncErpCode.Progress("查询EPLAN数据...", 0);
MDPart[] parts = EplanUtil.QueryParts(null, "");
int len = parts == null ? 0 : parts.Length;
KUtil.Log("查询结果数量:"+len);
if (len == 0) {
return;
}
Dictionary<string, string> orderNr_itemId = new Dictionary<string, string>();
for(int i = 0; i < len; i++) {
if (bgWorker_SyncErpCode.IsCancel()) {
e.Cancel = true;
return;
}
MDPart part = parts[i];
string orderNr = EplanUtil.GetMDPropValue(part.Properties.ARTICLE_PARTNR);
KUtil.Log((i+1)+". 检查部件:" + part.PartNr+"|"+orderNr);
bgWorker_SyncErpCode.Progress("同步数据...( " + (i + 1) + " / " + len + " )", (i + 1) * 100 / len);
if (!KUtil.IsEmpty(orderNr)) {
string itemId = "";
if (orderNr_itemId.ContainsKey(orderNr)) {
itemId = orderNr_itemId[orderNr];
}
else {
Teamcenter.Soa.Client.Model.Strong.ItemRevision rev = TCUtil.Query_LatestRevByOrderNr_single(orderNr);
if (rev != null) {
ModelObject[] mos = TCUtil.Refresh(rev);
TCUtil.GetProperties(false, mos, "item_id");
itemId = rev.Item_id;
}
orderNr_itemId.Add(orderNr, itemId);
}
KUtil.Log(">> 设置ERPNumber = "+itemId);
//写入ERPNumber
MDPartsDatabaseTransaction trans = mdPartsDatabase.CreateTransaction();
part.Properties.ARTICLE_ERPNR = itemId;
trans.Commit();
trans.Dispose();
}
}
KUtil.Log("执行结束");
MessageBox.Show(this, "同步完成");
}
private void Async_UploadPartsDB(object sender, DoWorkEventArgs e) {
bgWorker_UploadPartsDB.Progress("准备上传EPLAN数据...", 0);
string fmsHome = Environment.GetEnvironmentVariable("FMS_HOME");
string zipFile = fmsHome + "\\EPlan\\" + "EPLAN_PARTS.zip";
string eplanDataFolderPath = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_DATA_FOLDER);
string skipFolders = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_DATA_SKIP_FOLDER);
string dsUid = KUtil.GetConfigValue(KConfigure.EPLAN_DATA_SECTION, KConfigure.EPLAN_DATASET_UID);
if (KUtil.IsEmpty(eplanDataFolderPath)) {
throw new Exception("未配置EPLAN数据文件夹");
}
if (KUtil.IsEmpty(dsUid)) {
throw new Exception("未配置TC数据集UID");
}
if (!System.IO.Directory.Exists(eplanDataFolderPath)) {
throw new Exception("EPLAN数据文件夹不存在请检查配置" + eplanDataFolderPath);
}
KUtil.Log("准备上传EPLAN数据文件夹" + eplanDataFolderPath);
ModelObject mo = TCUtil.StringToComponent(dsUid);
if (mo == null) {
throw new Exception("未查询到数据集 uid = "+dsUid+",请检查配置");
}
ModelObject[] mos = TCUtil.Refresh(mo);
TCUtil.GetProperties(false, mos, "object_string");
string dsName = mo.GetPropertyDisplayableValue("object_string");
KUtil.Log("找到数据集:" + dsName);
if (!TCUtil.IsType(mo.SoaType, "Zip")) {
throw new Exception("配置的数据集<" + dsName + ">不是Zip数据集uid = " + dsUid);
}
this.bgWorker_UploadPartsDB.Progress("压缩目录...",30);
if (!KUtil.ZipDirectory(eplanDataFolderPath, zipFile, null, skipFolders)) {
throw new Exception("压缩EPLAN部件库失败");
}
KUtil.Log("压缩完成");
this.bgWorker_UploadPartsDB.Progress("上传文件...", 70);
TCUtil.UploadFile((Teamcenter.Soa.Client.Model.Strong.Dataset)mo, zipFile, "ZIPFILE");
KUtil.Log("上传成功");
this.Dispatcher.Invoke(new Action(delegate {
MessageBox.Show(this, "上传成功");
}));
}
private void Async_Revise(object sender, DoWorkEventArgs e) {
List<PartSyncDataRow> reviseList = e.Argument as List<PartSyncDataRow>;
if (reviseList.Count == 0) {
return;
}
bgWorker_Revise.Progress("正在升版...",0);
int len = reviseList.Count;
for(int i = 0; i < len; i++) {
if (bgWorker_Revise.IsCancel()) {
e.Cancel = true;
return;
}
bgWorker_Revise.Progress("正在升版...( "+(i+1)+" / "+len+" )", (i+1)*100/len);
PartSyncDataRow bean = reviseList[i];
Teamcenter.Soa.Client.Model.Strong.ItemRevision newRev = TCUtil.Revise(bean.tcRev);
if (newRev == null) {
throw new Exception("对象升版失败:"+bean.itemID);
}
Teamcenter.Soa.Client.Model.ModelObject[] mo = TCUtil.Refresh(newRev);
TCUtil.GetProperties(false, mo, "item_revision_id");
MDPartsDatabaseTransaction trans = mdPartsDatabase.CreateTransaction();
bean.part.Properties.ARTICLE_CERTIFICATE_ATEX = "";
trans.Commit();
trans.Dispose();
this.Dispatcher.Invoke(new Action(delegate {
bean.itemRev = newRev.Item_revision_id;
bean.releaseStatus = NOT_RELEASEED;
bean.syncStatus = NOT_SYNCED;
table_Sync_To_TC.Items.Refresh();
}));
}
}
private void Async_TC_to_EPlan(object sender, DoWorkEventArgs e) {
sync_Success = 0;
this.Dispatcher.Invoke(new Action(delegate {
errData.Clear();
}));
bgWorker_TC_to_EPlan.Progress("执行中...", 0);
int len = 0;
this.Dispatcher.Invoke(new Action(delegate {
len = tcToEPlanData.Count;
}));
for (int i = 0; i < len; i++) {
if (bgWorker_TC_to_EPlan.IsCancel()) {
e.Cancel = true;
return;
}
bgWorker_TC_to_EPlan.Progress("执行中...( " + (i + 1) + " / " + len + " )", (i + 1) * 100 / len);
PartSyncDataRow bean = tcToEPlanData[i];
string errMsg = null;
try {
errMsg = Item_to_EPlan(bean);
}
catch (System.Exception ex) {
KUtil.LogErr(ex);
errMsg = ex.Message;
}
if (KUtil.IsEmpty(errMsg)) {
sync_Success++;
}
else {
if (!"已同步".Equals(errMsg)) {
this.Dispatcher.Invoke(new Action(delegate {
errData.Add(new SyncResult(null) { partNr = bean.partNr, name = bean.name, reason = errMsg });
}));
}
}
}
}
private void Async_EPlan_to_TC(object sender, DoWorkEventArgs e) {
sync_Success = 0;
this.Dispatcher.Invoke(new Action(delegate {
errData.Clear();
}));
bgWorker_EPlan_to_TC.Progress("执行中...",0);
int len =0;
this.Dispatcher.Invoke(new Action(delegate {
len = ePlanToTCData.Count;
}));
for (int i = 0; i < len; i++) {
if (bgWorker_EPlan_to_TC.IsCancel()) {
e.Cancel = true;
return;
}
bgWorker_EPlan_to_TC.Progress("执行中...( " + (i + 1) + " / " + len + " )", (i + 1) * 100 / len);
PartSyncDataRow bean = ePlanToTCData[i];
string errMsg = null;
try {
errMsg = Part_to_TC(bean);
}
catch (System.Exception ex) {
KUtil.LogErr(ex);
errMsg = ex.Message;
}
if (KUtil.IsEmpty(errMsg)) {
sync_Success++;
}
else {
if (!"已同步".Equals(errMsg)) {
this.Dispatcher.Invoke(new Action(delegate {
errData.Add(new SyncResult(null) { partNr = bean.partNr, name = bean.name, reason = errMsg });
}));
}
}
}
//this.Dispatcher.Invoke(new Action(delegate{
// new PartSyncResult(this, sync_Success, ePlanToTCData.Count - sync_Success - errData.Count, errData).ShowDialog();
//}));
}
private void bgWorker_EPlan_to_TC_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
if (e.Error == null) {
new PartSyncResult(mdPartsDatabase, this, sync_Success, ePlanToTCData.Count - sync_Success - errData.Count, errData).ShowDialog();
//else {
// MessageBox.Show(parent, "操作完成");
//}
}
}
private String Item_to_EPlan(PartSyncDataRow bean) {
Teamcenter.Soa.Client.Model.Strong.ItemRevision rev = bean.tcRev;
MDPart part = bean.part;
if (part == null) {
return "部件不存在";
}
//同步属性到EPlan
KUtil.Sync_Property_to_EPlan(mdPartsDatabase, rev, bean.part);
return "";
}
private string Part_to_TC(PartSyncDataRow bean) {
string errMsg = null;
string releaseStatus = bean.releaseStatus;
string syncStatus = bean.syncStatus;
Teamcenter.Soa.Client.Model.Strong.ItemRevision rev = null;
switch (syncStatus) {
case NOT_SYNCED:
if (NOT_RELEASEED.Equals(releaseStatus)) {
//通过item获取对象
rev = TCUtil.Query_LatestRev(bean.itemID);
if (rev == null) {
errMsg = "未查询到对象:" + bean.itemID;
}
}
else {
//失败:未升版
errMsg = "未升版";
}
break;
case "新增":
//新建对象 反写ID
string tcItemType = KUtil.GetConfigValue(KConfigure.PART_SYNC_SECTION, KConfigure.PART_SYNC_TC_ITEM_TYPE);
if (KUtil.IsEmpty(tcItemType)) {
throw new Exception("未配置TC数据类型");
}
rev = TCUtil.CreateNewRev(tcItemType);
if (rev == null) {
errMsg = "新建对象失败";
}
//else {
// Teamcenter.Soa.Client.Model.ModelObject[] mo = TCUtil.Refresh(rev);
// TCUtil.GetProperties(false, mo, "item_id","item_revision_id","object_name");
// MDPartsDatabaseTransaction trans = EplanUtil.mdPartsDatabase.CreateTransaction();
// bean.part.Properties.ARTICLE_ERPNR = rev.Item_id;
// trans.Commit();
// trans.Dispose();
// this.Dispatcher.Invoke(new Action(delegate {
// bean.itemID = rev.Item_id;
// bean.itemRev = rev.Item_revision_id;
// bean.itemName = rev.Object_name;
// table_Sync_To_TC.Items.Refresh();
// }));
//}
break;
case "SAP未分配ID":
//失败:
errMsg = "SAP未分配ID";
break;
case "已同步":
return "已同步";
default:
//失败:未知状态
errMsg = "未知同步状态:" + syncStatus;
break;
}
if (KUtil.IsEmpty(errMsg)) {
if (rev == null) {
errMsg = "获取TC对象异常";
}
else {
//属性同步 发送分类
KUtil.Sync_Property_to_TC(rev, bean.part);
Teamcenter.Soa.Client.Model.ModelObject[] mo = TCUtil.Refresh(rev);
TCUtil.GetProperties(false, mo, "item_id", "item_revision_id", "object_name");
MDPartsDatabaseTransaction trans = mdPartsDatabase.CreateTransaction();
bean.part.Properties.ARTICLE_ERPNR = rev.Item_id;
bean.part.Properties.ARTICLE_CERTIFICATE_ATEX = "已同步";
trans.Commit();
trans.Dispose();
this.Dispatcher.Invoke(new Action(delegate {
bean.itemID = rev.Item_id;
bean.itemRev = rev.Item_revision_id;
bean.itemName = rev.Object_name;
bean.syncStatus = "已同步";
table_Sync_To_TC.Items.Refresh();
}));
}
}
return errMsg;
}
private void Async_QueryTCParts(object sender, DoWorkEventArgs e) {
string partNr = "";
string itemId = "";
this.Dispatcher.Invoke(new Action(delegate {
partNr = tb_PartNr_TC.Text;
itemId = tb_ItemID_TC.Text;
}));
string queryName = KUtil.GetConfigValue(KConfigure.PART_QUERY_SECTION, KConfigure.PART_QUERY_NAME);
string itemField = KUtil.GetConfigValue(KConfigure.PART_QUERY_SECTION, KConfigure.PART_QUERY_ITEM_ID);
string partField = KUtil.GetConfigValue(KConfigure.PART_QUERY_SECTION, KConfigure.PART_QUERY_ORDERNR);
if (KUtil.IsEmpty(queryName) || KUtil.IsEmpty(itemField) || KUtil.IsEmpty(partField)) {
throw new Exception("TC部件查询配置缺失请检查设置");
}
string partNrProp = KUtil.GetConfigValue(KConfigure.PART_SYNC_SECTION, KConfigure.PART_SYNC_OrderNr_TC);
if (KUtil.IsEmpty(partNrProp)) {
throw new Exception("未配置部件编号在TC中的属性");
}
Dictionary<string, string> fields = new Dictionary<string, string>();
if (!KUtil.IsEmpty(itemId)) {
fields.Add(itemField, itemId);
}
if (!KUtil.IsEmpty(partNr)) {
fields.Add(partField, partNr);
}
if (fields.Count == 0) {
MessageBox.Show(this, "请输入查询条件");
return;
}
KUtil.Log("查询部件PartNR = " + partNr + ", ErpNR = " + itemId);
bgWorker_Query_TC.Progress("查询中...",0);
ModelObject[] unsyncItems = TCUtil.query(queryName, fields);
int len = unsyncItems == null ? 0 : unsyncItems.Length;
KUtil.Log("查询结果数量:" + len);
for (int i = 0; i < len; i++) {
if (bgWorker_Query_TC.IsCancel()) {
e.Cancel = true;
return;
}
bgWorker_Query_TC.Progress("加载数据...( " + (i + 1) + " / " + len + " )", (i + 1) * 100 / len);
ModelObject rev = unsyncItems[i];
ModelObject[] mo = TCUtil.Refresh(rev);
TCUtil.GetProperties(false, mo, "object_string");
if (!TCUtil.IsType(rev.SoaType, "ItemRevision")) {
throw new Exception("获取配置属性失败,对象不是版本类型:" + rev.GetPropertyDisplayableValue("object_string"));
}
Add_Sync_Data((Teamcenter.Soa.Client.Model.Strong.ItemRevision)rev, partNrProp);
}
}
private void Async_QueryParts(object sender, DoWorkEventArgs e) {
string partNr = "";
string erpNr = "";
this.Dispatcher.Invoke(new Action(delegate {
partNr = tb_PartNr.Text;
erpNr = tb_ERPNr.Text;
}));
KUtil.Log("查询部件PartNR = " + partNr + ", ErpNR = " + erpNr);
bgWorker_Query.Progress("查询中...", 0);
MDPart[] unsyncParts = EplanUtil.QueryParts(mdPartsDatabase, partNr, erpNr);
int len = unsyncParts == null ? 0 : unsyncParts.Length;
KUtil.Log("查询结果数量:" + len);
for (int i = 0; i < len; i++) {
if (bgWorker_Query.IsCancel()) {
e.Cancel = true;
return;
}
bgWorker_Query.Progress("加载数据...( " + (i + 1) + " / " + len + " )", (i + 1) * 100 / len);
Add_Sync_Data(unsyncParts[i], false);
}
}
private void Async_AddAllUnsyncedParts(object sender, DoWorkEventArgs e) {
string partNr = "";
string erpNr = "";
this.Dispatcher.Invoke(new Action(delegate {
partNr = tb_PartNr.Text;
erpNr = tb_ERPNr.Text;
}));
KUtil.Log("查询未同步部件PartNR = " + partNr + ", ErpNR = " + erpNr);
bgWorker_AddAll.Progress("查询中...", 0);
List<MDPart> unsyncParts = EplanUtil.GetUnsyncedParts(mdPartsDatabase, partNr, erpNr);
int len = unsyncParts == null? 0 :unsyncParts.Count;
KUtil.Log("查询全部未同步部件数量:"+len);
for(int i = 0; i < len; i++) {
if (bgWorker_AddAll.IsCancel()) {
e.Cancel = true;
return;
}
bgWorker_AddAll.Progress("加载数据...( "+(i+1)+" / "+len+" )",(i+1)*100/len);
Add_Sync_Data(unsyncParts[i], false);
}
}
private void Async_LoadParts(object sender, DoWorkEventArgs e) {
EPlanTreeItem parent = (EPlanTreeItem)e.Argument;
if (parent != null) {
Cycle_Home(parent, e);
return;
}
//TreeViewItem node_home = null;
bgWorker_Parts.Progress("加载数据...", 0);
EPlanTreeItem tree_home = null;
this.Dispatcher.Invoke(new Action(delegate {
tree_home = new EPlanTreeItem("Parts");
tree_Parts.Items.Add(tree_home);
}));
/*int len = allParts.Length;
for (int i = 0; i < len; i++) {
if (bgWorkder_Parts.IsCancel()) {
e.Cancel = true;
return;
}
bgWorkder_Parts.Progress("加载数据...( "+(i+1)+" / "+len+" )", (i + 1) * 100 / len);
MDPart p = allParts[i];
EPlanTreeItem groupItem = FindTreeItem(p.GenericProductGroup, p.ProductGroup, tree_home);
if (groupItem == null) {
throw new Exception("获取组节点异常");
}
this.Dispatcher.Invoke(new Action(delegate {
groupItem.Items.Add(new EPlanTreeItem(p));
}));
}
this.Dispatcher.Invoke(new Action(delegate {
foreach (EPlanGroup g in topGroupMap.Values) {
g.topGroup.Items.SortDescriptions.Add(new SortDescription("Header", ListSortDirection.Ascending));
g.topGroup.Items.Refresh();
}
}));*/
//加载TOPGROUP
Init_TopGroup(MDPartsDatabaseItem.Enums.ProductTopGroup.Electric, tree_home);
Init_TopGroup(MDPartsDatabaseItem.Enums.ProductTopGroup.Mechanic, tree_home);
Init_TopGroup(MDPartsDatabaseItem.Enums.ProductTopGroup.Fluid, tree_home);
Init_TopGroup(MDPartsDatabaseItem.Enums.ProductTopGroup.Process, tree_home);
Init_TopGroup(MDPartsDatabaseItem.Enums.ProductTopGroup.Invaild, tree_home);
Init_TopGroup(MDPartsDatabaseItem.Enums.ProductTopGroup.Undefined, tree_home);
this.Dispatcher.Invoke(new Action(delegate {
tree_home.IsExpanded = true;
}));
}
private EPlanTreeItem FindTreeItem(MDPartsDatabaseItem.Enums.ProductTopGroup topGroup,MDPartsDatabaseItem.Enums.ProductGroup group,EPlanTreeItem root) {
EPlanGroup ePlanGroup = null;
if (topGroupMap.ContainsKey(topGroup)) {
ePlanGroup = topGroupMap[topGroup];
}
else {
this.Dispatcher.Invoke(new Action(delegate {
//string topGroupName = MDPartsDatabaseItem.GetProductTopGroupName(topGroup);
EPlanTreeItem topGroupItem = new EPlanTreeItem(topGroup);
ePlanGroup = new EPlanGroup(topGroupItem);
root.Items.Add(topGroupItem);
topGroupMap.Add(topGroup, ePlanGroup);
}));
}
if (ePlanGroup == null) { return null; }
if (ePlanGroup.productGroupMap.ContainsKey(group)) {
return ePlanGroup.productGroupMap[group];
}
else {
EPlanTreeItem groupItem = null;
this.Dispatcher.Invoke(new Action(delegate {
//string groupName = MDPartsDatabaseItem.GetProductGroupName(group);
groupItem = new EPlanTreeItem(topGroup,group);
ePlanGroup.topGroup.Items.Add(groupItem);
ePlanGroup.productGroupMap.Add(group, groupItem);
}));
return groupItem;
}
}
private void Init_TopGroup(MDPartsDatabaseItem.Enums.ProductTopGroup topGroup, EPlanTreeItem tree_home) {
//if (!EplanUtil.TopGroupHasPart(topGroup)) {
// return;
//}
//string topGroupName = MDPartsDatabaseItem.GetProductTopGroupName(topGroup);
EPlanTreeItem tree_TopGroup = null;
this.Dispatcher.Invoke(new Action(delegate {
tree_TopGroup = new EPlanTreeItem(topGroup);
//KUtil.Log(tree_TopGroup.Header.ToString());
tree_home.Items.Add(tree_TopGroup);
}));
//加载Group
MDPartsDatabaseItem.Enums.ProductGroup[] groups = MDPartsDatabaseItem.GetAvailableProductGroups(topGroup);
for (int i = 0; i < groups.Length; i++) {
MDPartsDatabaseItem.Enums.ProductGroup group = groups[i];
//if (!EplanUtil.GroupHasPart(topGroup, group)) {
// continue;
//}
this.Dispatcher.Invoke(new Action(delegate {
EPlanTreeItem tree_Group = new EPlanTreeItem(topGroup, group);
//KUtil.Log(">> " + tree_Group.Header.ToString());
tree_TopGroup.Items.Add(tree_Group);
tree_Group.Items.Add(new EPlanTreeItem());//展开加载标记
}));
}
this.Dispatcher.Invoke(new Action(delegate {
tree_TopGroup.Items.SortDescriptions.Add(new SortDescription("Header", ListSortDirection.Ascending));
tree_TopGroup.Items.Refresh();
}));
}
private void Cycle_Home(EPlanTreeItem treeItem, DoWorkEventArgs e) {
bool flag = false;
this.Dispatcher.Invoke(new Action(delegate {
if (!(treeItem.Items.Count == 1 && ((EPlanTreeItem)treeItem.Items.GetItemAt(0)).isLoadMark)) {
flag = true;
}
}));
if (flag) { return; }
int topGroupId = -404;
int groupId = -404;
string groupName="";
this.Dispatcher.Invoke(new Action(delegate {
treeItem.Items.Clear();
EPlanTreeItem topGroupItem = (EPlanTreeItem)treeItem.Parent;
KUtil.Log("查询:"+topGroupItem.Header+"|" + treeItem.Header);
topGroupId = topGroupItem.groupId;
groupId = treeItem.groupId;
groupName = treeItem.Header.ToString();
}));
if (topGroupId ==-404 && groupId == -404) {
return;
}
bgWorker_Parts.Progress("查询中...",0);
MDPart[] parts = EplanUtil.GetParts(mdPartsDatabase, topGroupId, groupId);
int len = parts == null ? 0:parts.Length;
for(int i = 0; i < len; i++) {
if (bgWorker_Parts.IsCancel()) {
e.Cancel = true;
return;
}
bgWorker_Parts.Progress("加载数据...( " + (i + 1) + " / " + len + " )", (i + 1) * 100 / len);
this.Dispatcher.Invoke(new Action(delegate {
treeItem.Items.Add(new EPlanTreeItem(parts[i],groupName));
}));
}
//string group = treeItem.Header as string;
//MDPartsDatabaseItem.GetAvailableProductGroups
//ModelObject parent = treeItem.mo;
//ModelObject[] children = null;
////var t = parent.GetType();
//SoaType soaType = parent.SoaType;
//ModelObject[] mo = TCUtil.Refresh(parent);
//if (TCUtil.IsType(soaType, "Folder")) {
// TCUtil.GetProperties(false, mo, "contents");
// children = ((Folder)parent).Contents;
//}
//else if (TCUtil.IsType(soaType, "Item") || TCUtil.IsType(soaType, "ItemRevision")) {
// children = TCUtil.GetChildFromPref(parent);
//}
//else if (TCUtil.IsType(soaType, "Dataset")) {
// children = null;
//}
//else {
// return;
//}
//if (children == null) {
// return;
//}
//if (bgWorker_Query.IsCancel()) {
// e.Cancel = true;
// return;
//}
//ItemCollection node_children = null;
//this.Dispatcher.Invoke(new Action(delegate {
// node_children = treeItem.Items;
//}));
//int len = children.Length;
//for (int i = 0; i < len; i++) {
// if (bgWorker_Query.IsCancel()) {
// e.Cancel = true;
// return;
// }
// bgWorker_Homer.Progress("加载中...( " + (i + 1) + " / " + len + " )", (i + 1) * 100 / len);
// ModelObject c = children[i];
// EPlanTreeItem node_child = null;
// this.Dispatcher.Invoke(new Action(delegate {
// node_child = new EPlanTreeItem(c);
// node_children.Add(node_child);
// node_child.Items.Add(new EPlanTreeItem(null));
// }));
//}
}
private void Window_Loaded(object sender, RoutedEventArgs e) {
bgWorker_Parts.Start(null);
}
private void Tree_Parts_Expanded(object sender, RoutedEventArgs e) {
EPlanTreeItem item = e.OriginalSource as EPlanTreeItem;
bgWorker_Parts.Start(item);
}
private void Table_Sync_To_TC_Loaded(object sender, RoutedEventArgs e) {
}
private void Add_Button_Click(object sender, RoutedEventArgs e) {
EPlanTreeItem selectedItem = tree_Parts.SelectedItem as EPlanTreeItem;
if (selectedItem == null || selectedItem.part==null) {
return;
}
try {
Add_Sync_Data(selectedItem.part,true);
}
catch(System.Exception ex) {
KUtil.LogErr(ex);
MessageBox.Show(this, "添加数据出错:"+ex.Message);
}
}
private void Add_Sync_Data(MDPart part,bool select) {
string partNr = part.PartNr;
string orderNr = EplanUtil.GetMDPropValue(part.Properties.ARTICLE_PARTNR);
PartSyncDataRow b = new PartSyncDataRow() {
partNr = partNr
};
bool flag = false;
this.Dispatcher.Invoke(new Action(delegate {
if (ePlanToTCData.Contains(b)) {
if (select) {
table_Sync_To_TC.SelectedItem = b;
table_Sync_To_TC.ScrollIntoView(b);
}
flag = true;
//MessageBox.Show(this,"已经添加过该对象");
//return;
}
}));
if (flag) { return; }
Teamcenter.Soa.Client.Model.Strong.ItemRevision tcRev = TCUtil.Query_LatestRevByOrderNr_single(orderNr);
string itemID = "";
string itemRev = "";
string itemName = "";
string releaseStatus = "";
if (tcRev != null) {
Teamcenter.Soa.Client.Model.ModelObject[] mo = TCUtil.Refresh(tcRev);
TCUtil.GetProperties(false, mo, "item_id", "item_revision_id","object_name","release_status_list");
itemID = tcRev.Item_id;
itemRev = tcRev.Item_revision_id;
itemName = tcRev.Object_name;
Teamcenter.Soa.Client.Model.Strong.ReleaseStatus[] releaseList = tcRev.Release_status_list;
TCUtil.GetProperties(false, releaseList, "name");
for (int i = 0; i < releaseList.Length; i++) {
releaseStatus += releaseList[i].Name;
if (i != releaseList.Length - 1) {
releaseStatus += ", ";
}
}
}
if (KUtil.IsEmpty(releaseStatus)) {
releaseStatus = NOT_RELEASEED;
}
string type = EplanUtil.GetMDPropValue(part.Properties.ARTICLE_MANUFACTURER,EplanUtil.Language).Trim();
string syncStatus = GetSyncStatus(EplanUtil.GetMDPropValue(part.Properties.ARTICLE_CERTIFICATE_ATEX,EplanUtil.Language), type, itemID);
b.index = ePlanToTCData.Count + 1 ;
b.name = EplanUtil.GetMDPropValue(part.Properties.ARTICLE_DESCR1,EplanUtil.Language);
b.itemID = itemID;
b.itemName = itemName;
b.itemRev = itemRev;
b.type = type;
b.releaseStatus = releaseStatus;
b.syncStatus = syncStatus;
b.part = part;
b.tcRev = tcRev;
this.Dispatcher.Invoke(new Action(delegate {
ePlanToTCData.Add(b);
table_Sync_To_TC.ScrollIntoView(b);
}));
}
private void Add_Sync_Data(Teamcenter.Soa.Client.Model.Strong.ItemRevision rev, string partNrConfig) {
ModelObject[] mo = TCUtil.Refresh(rev);
TCUtil.GetProperties(false, mo, "item_id","item_revision_id", "release_status_list","object_string");
string partNr = TCUtil.GetRevConfigProp(rev, partNrConfig);
PartSyncDataRow b = new PartSyncDataRow() {
partNr = partNr
};
if (!KUtil.IsEmpty(partNr) && tcToEPlanData.Contains(b)) {
this.Dispatcher.Invoke(new Action(delegate {
table_Sync_To_EPLAN.SelectedItem = b;
table_Sync_To_EPLAN.ScrollIntoView(b);
}));
throw new Exception("无法添加对象“"+rev.Object_string+"”,部件编号为<" + partNr + ">的对象已添加,请检查查询条件或处理数据后再进行操作");
}
string itemID = rev.Item_id;
string itemRev = rev.Item_revision_id;
string itemName = rev.Object_name;
string releaseStatus = "";
Teamcenter.Soa.Client.Model.Strong.ReleaseStatus[] releaseList = rev.Release_status_list;
TCUtil.GetProperties(false, releaseList, "name");
for (int i = 0; i < releaseList.Length; i++) {
releaseStatus += releaseList[i].Name;
if (i != releaseList.Length - 1) {
releaseStatus += ", ";
}
}
if (KUtil.IsEmpty(releaseStatus)) {
releaseStatus = NOT_RELEASEED;
}
MDPart part = null;
string type = "";
string syncStatus = "";
string name = "";
if (!KUtil.IsEmpty(partNr)) {
part = EplanUtil.GetPart(mdPartsDatabase, partNr);
if (part != null) {
type = EplanUtil.GetMDPropValue(part.Properties.ARTICLE_MANUFACTURER,EplanUtil.Language).Trim();
string erpNr = EplanUtil.GetMDPropValue(part.Properties.ARTICLE_ERPNR);
syncStatus = GetSyncStatus(EplanUtil.GetMDPropValue(part.Properties.ARTICLE_CERTIFICATE_ATEX,EplanUtil.Language), type, erpNr);
name = EplanUtil.GetMDPropValue(part.Properties.ARTICLE_DESCR1,EplanUtil.Language);
}
}
b.index = tcToEPlanData.Count + 1 ;
b.name = name;
b.itemID = itemID;
b.itemName = itemName;
b.itemRev = itemRev;
b.type = type;
b.releaseStatus = releaseStatus;
b.syncStatus = syncStatus;
b.part = part;
b.tcRev = rev;
this.Dispatcher.Invoke(new Action(delegate {
tcToEPlanData.Add(b);
table_Sync_To_EPLAN.ScrollIntoView(b);
}));
}
private string GetSyncStatus(string syncStatus, string type, string itemID) {
if (!"已同步".Equals(syncStatus)) {
if (KUtil.IsEmpty(itemID)) {
if ("Siemens".Equals(type)) {
return "SAP未分配ID";
}
else {
return "新增";
}
}
else {
return NOT_SYNCED;
}
}
return syncStatus;
}
private void Remove_Button_Click(object sender, RoutedEventArgs e) {
try {
System.Collections.IList selectedItems = table_Sync_To_TC.SelectedItems;
if (selectedItems == null || selectedItems.Count == 0) {
return;
}
while (selectedItems.Count > 0) {
ePlanToTCData.Remove((PartSyncDataRow)selectedItems[0]);
table_Sync_To_TC.Items.Refresh();
}
for (int i = 0; i < ePlanToTCData.Count; i++) {
ePlanToTCData[i].index = (i + 1);
}
table_Sync_To_TC.Items.Refresh();
}
catch(System.Exception ex) {
KUtil.LogErr(ex);
MessageBox.Show(this, ex.Message);
}
}
private void Add_All_Button_Click(object sender, RoutedEventArgs e) {
this.bgWorker_AddAll.Start(null);
}
private void Query_Button_Click(object sender, RoutedEventArgs e) {
this.bgWorker_Query.Start(null);
}
private void EPlan_to_TC_Button_Click(object sender, RoutedEventArgs e) {
this.bgWorker_EPlan_to_TC.Start(null);
}
private void Close_Button_Click(object sender, RoutedEventArgs e) {
Close();
}
private void Revise_Button_Click(object sender, RoutedEventArgs e) {
System.Collections.IList selectedItems = table_Sync_To_TC.SelectedItems;
if (selectedItems == null || selectedItems.Count == 0) {
return;
}
List<PartSyncDataRow> reviseList = new List<PartSyncDataRow>();
for(int i = 0; i < selectedItems.Count; i++) {
PartSyncDataRow bean = selectedItems[i] as PartSyncDataRow;
if (bean.tcRev!=null) {
reviseList.Add(bean);
}
}
if (reviseList.Count == 0) {
MessageBox.Show(this, "没有可升版的数据");
return;
}
bgWorker_Revise.Start(reviseList);
}
private void TC_to_EPLAN_Button_Click(object sender, RoutedEventArgs e) {
this.bgWorker_TC_to_EPlan.Start(null);
}
private void TC_Query_Button_Click(object sender, RoutedEventArgs e) {
tcToEPlanData.Clear();
bgWorker_Query_TC.Start(null);
}
private void Tree_Parts_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
Add_Button_Click(sender, e);
}
private void Upload_PartsDB(object sender, RoutedEventArgs e) {
bgWorker_UploadPartsDB.Start(null);
}
private void SyncErpCode_Button_Click(object sender, RoutedEventArgs e) {
bgWorker_SyncErpCode.Start(null);
}
}
}

@ -0,0 +1,49 @@
<Window x:Class="KPlan.Forms.PartSyncResult"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:KPlan.Forms"
mc:Ignorable="d" Loaded="Window_Loaded" UseLayoutRounding="True" WindowStartupLocation="CenterOwner" Height="480" Width="900" MinHeight="480" MinWidth="600" Icon="/EPLAN.EplAddin.KPlan;component/Resources/logo_16.ico" Title="同步结果">
<!--<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="KStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>-->
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Label Name="l_Summary" Content="同步成功XXX行同步失败XXX行" Grid.Row="0" Margin="5,10,5,5"/>
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1" Margin="5,0,5,5">
<GroupBox.Header>同步失败条目</GroupBox.Header>
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" HeadersVisibility="Column" IsReadOnly="True" Name="table_Sync_Result" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="300" ColumnHeaderHeight="25" RowHeight="23" CanUserResizeRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="部件编号" Width="120" Binding="{Binding partNr}"/>
<DataGridTextColumn Header="订货号" Width="120" Binding="{Binding orderNr}"/>
<DataGridTextColumn Header="名称" Width="120" Binding="{Binding name}"/>
<DataGridTextColumn Header="计量单位" Width="80" Binding="{Binding jldw}"/>
<DataGridTextColumn Header="描述(中文)" Width="120" Binding="{Binding desc_cn}"/>
<DataGridTextColumn Header="描述(英文)" Width="120" Binding="{Binding desc_en}"/>
<DataGridTextColumn Header="失败原因" Width="180" Binding="{Binding reason}"/>
</DataGrid.Columns>
</DataGrid>
</GroupBox>
<Grid Grid.Row="2" Margin="0,0,0,8" HorizontalAlignment="Center" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="25"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="25"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Button Content="确认" Width="80" Height="24" Grid.Column="0" Click="CLose_Button_Click"/>
<Button x:Name="b_Apply" Content="发起编码申请流程" Width="140" Height="24" Grid.Column="2" Click="Apply_Button_Click"/>
<Button x:Name="b_Export" Content="导出" Width="80" Height="24" Grid.Column="4" Click="Export_Button_Click"/>
</Grid>
</Grid>
</Window>

@ -0,0 +1,325 @@
using KPlan.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using System.ComponentModel;
using Teamcenter.Soa.Client.Model.Strong;
using Teamcenter.Soa.Client.Model;
using Eplan.EplApi.MasterData;
namespace KPlan.Forms {
/// <summary>
/// Interaction logic for PartSyncResult.xaml
/// </summary>
public partial class PartSyncResult : Window {
private ObservableCollection<SyncResult> tableData;
public const string EXPORT_FILE_NAME = "同步失败条目";
public const string EXPORT_FILE_EXT = "xlsx";
private KBackgroundWorker bgWorkder_apply;
private MDPartsDatabase mdPartsDatabase;
public PartSyncResult(MDPartsDatabase mdPartsDatabase, Window parent, int success, int canceled, ObservableCollection<SyncResult> resData) {
InitializeComponent();
this.mdPartsDatabase = mdPartsDatabase;
this.Owner = parent;
table_Sync_Result.ItemsSource = resData;
this.tableData = resData;
l_Summary.Content = "同步成功"+success+"行,同步失败"+resData.Count+"行"+(canceled>0?", 取消"+canceled+"行":"");
bgWorkder_apply = new KBackgroundWorker(this);
bgWorkder_apply.backgroundWorker.DoWork += Async_DoApply;
}
private void doExport() {
int rowCnt = tableData.Count;
if (rowCnt == 0) {
return;
}
string targetPath = null;
using (var fbd = new FolderBrowserDialog()) {
DialogResult result = fbd.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK) {
targetPath = fbd.SelectedPath;
}
}
if (string.IsNullOrWhiteSpace(targetPath)) {
return;
}
KUtil.Log("导出同步失败条目...");
KUtil.Log("导出路径:"+targetPath);
string filePath = KUtil.GetFilePath(targetPath, EXPORT_FILE_NAME, EXPORT_FILE_EXT);
KUtil.Log("导出文件:"+filePath);
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null) {
System.Windows.MessageBox.Show("Excel 未正确安装");
return;
}
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "部件编号";
xlWorkSheet.Cells[1, 2] = "订货号";
xlWorkSheet.Cells[1, 3] = "名称";
xlWorkSheet.Cells[1, 4] = "计量单位";
xlWorkSheet.Cells[1, 5] = "描述(中文)";
xlWorkSheet.Cells[1, 6] = "描述(英文)";
xlWorkSheet.Cells[1, 7] = "失败原因";
for(int i = 0; i < rowCnt; i++) {
int r = i + 2;
SyncResult bean = tableData[i];
xlWorkSheet.Cells[r, 1] = bean.partNr;
xlWorkSheet.Cells[r, 2] = bean.orderNr;
xlWorkSheet.Cells[r, 3] = bean.name;
xlWorkSheet.Cells[r, 4] = bean.jldw;
xlWorkSheet.Cells[r, 5] = bean.desc_cn;
xlWorkSheet.Cells[r, 6] = bean.desc_en;
xlWorkSheet.Cells[r, 7] = bean.reason;
}
//Here saving the file in xlsx
xlWorkBook.SaveAs(filePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, misValue,
misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
System.Windows.MessageBox.Show("导出完成");
}
private void Async_DoApply(object sender, DoWorkEventArgs e) {
KUtil.Log("发起编码申请...");
List<SyncResult> applyData = new List<SyncResult>();
bgWorkder_apply.Progress("检查数据...", 0);
bool descEmpty = false;
this.Dispatcher.Invoke(new Action(delegate {
int len = tableData.Count;
for (int i = 0; i < len; i++) {
SyncResult bean = tableData[i];
if (KUtil.IsEmpty(bean.desc_en)) {
KUtil.Log("描述缺失:"+bean.partNr);
descEmpty = true;
//break;
}
if (KPartSync.SAP_NEED_ID.Equals(bean.reason)) {
applyData.Add(bean);
}
}
}));
if (descEmpty) {
KUtil.Log("缺少英文描述,请填写后重新申请");
KUtil.DispatcherShow(this, "缺少英文描述,请填写后重新申请");
return;
}
DoApply(this, applyData,mdPartsDatabase);
}
public static void DoApply(Window window, List<SyncResult> applyData, MDPartsDatabase mdPartsDatabase) {
if (applyData.Count == 0) {
KUtil.Log("没有数据");
KUtil.DispatcherShow(window, "请选择“"+KPartSync.SAP_NEED_ID+"”的数据进行操作");
return;
}
//新建对象
string itemType = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_ITEMTYPE);
if (KUtil.IsEmpty(itemType)) {
throw new Exception("未配置编码申请对象类型");
}
ItemRevision rev = TCUtil.CreateNewDocument(itemType, "编码申请单");
if (rev == null) {
throw new Exception("新建对象异常");
}
ModelObject[] mo = TCUtil.Refresh(rev);
TCUtil.GetProperties(false, mo, "object_string", "items_tag", "IMAN_master_form_rev");
KUtil.Log("新建对象完成:" + rev.Object_string);
//设置表单属性
ModelObject[] form = rev.IMAN_master_form_rev;
string tableProp = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_TABLE);
string rowType = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_ROWTYPE);
if (!KUtil.IsEmpty(tableProp) && !KUtil.IsEmpty(rowType) && form.Length > 0) {
KUtil.Log("保存表格属性:" + rowType + "|" + tableProp);
List<ModelObject> rows = new List<ModelObject>();
for (int i = 0; i < applyData.Count; i++) {
SyncResult bean = applyData[i];
Dictionary<string, string> props = new Dictionary<string, string>();
AddProp(props, bean.orderNr, KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_ORDERNR));
AddProp(props, Guid.NewGuid().ToString("D"), KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_GUID));
AddProp(props, bean.jldw, KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_UNIT));
AddProp(props, bean.desc_cn, KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_DESC_CN));
AddProp(props, bean.desc_en, KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_DESC_EN));
// AddProp(props, "ElecElement", "sf6_Classification");
ModelObject rowComp = TCUtil.CreateNewRow(rowType, props);
if (rowComp != null) {
KUtil.Log("添加行数据:" + KUtil.ToString(props));
rows.Add(rowComp);
}
}
TCUtil.SetRefProperty(form[0], tableProp, rows);
}
//存放位置
Folder targetFolder = GetSaveFolder();
if (targetFolder != null) {
TCUtil.CreateNewRelation(targetFolder, rev.Items_tag, "contents");
}
//发起流程
string prefName = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_PROCESS_TEMPLATE);
string[] templateNames = TCUtil.GetPrefVals(prefName);
if (templateNames != null && templateNames.Length > 0) {
KUtil.Log("准备发起流程:" + templateNames[0]);
TCUtil.CreateNewProcess(templateNames[0], rev, 1);//root_target_attachments EPM_target_attachment
KUtil.Log("发起流程结束");
try {
SetStatus(mdPartsDatabase, applyData, KPartSync.APPLYING);
}catch(System.Exception ex) {
KUtil.LogErr(ex);
KUtil.Log("更改状态失败,再次尝试更改");
SetStatus(mdPartsDatabase, applyData, KPartSync.APPLYING);
}
KUtil.DispatcherShow(window, "编码申请流程已经发起");
}
else {
KUtil.DispatcherShow(window, "新建对象完成,未找到编码申请流程信息");
}
}
private static void SetStatus( MDPartsDatabase mdPartsDatabase, List<SyncResult> applyData,string status) {
if (applyData==null||applyData.Count == 0) {
return;
}
Eplan.EplApi.MasterData.MDPartsDatabaseTransaction trans = mdPartsDatabase.CreateTransaction();
try {
for (int i = 0; i < applyData.Count; i++) {
SyncResult bean = applyData[i];
if (bean.dataRow.part != null) {
KUtil.Log("更改状态:" + bean.partNr + " -> " + status);
bean.dataRow.part.Properties.ARTICLE_CERTIFICATE_ATEX = status;
bean.dataRow.sync_status = status;
}
}
trans.Commit();
}
finally {
trans.Dispose();
}
}
private static void AddProp(Dictionary<string, string> props, string propVal, string propName) {
if (!KUtil.IsEmpty(propName)) {
int ind = propName.IndexOf('=');
string def = "";
if (ind > 0) {
def = propName.Substring(ind + 1);
propName = propName.Substring(0, ind);
}
if (KUtil.IsEmpty(propVal)) {
props.Add(propName, def);
}
else {
props.Add(propName, propVal);
}
}
}
private static Folder GetSaveFolder() {
string prefName = KUtil.GetConfigValue(KConfigure.BMSQ_SECTION, KConfigure.BMSQ_POSITION_PREF);
Folder targetFolder = null;
if (!KUtil.IsEmpty(prefName)) {
string[] uids = TCUtil.GetPrefVals(prefName);
if (uids != null && uids.Length > 0) {
string uid = uids[0].Trim();
KUtil.Log("从首选项获取存放文件夹:" + uid);
ModelObject comp = TCUtil.StringToComponent(uid);
if (comp != null) {
targetFolder = comp as Folder;
TCUtil.Refresh(targetFolder);
TCUtil.GetProperties(false, new ModelObject[] { targetFolder }, "object_name","contents");
KUtil.Log("找到文件夹:" + targetFolder.Object_name);
WorkspaceObject[] contents = targetFolder.Contents;
TCUtil.GetProperties(false, contents, "object_name","creation_date");
int len = contents==null?0: contents.Length;
DateTime latest = DateTime.MinValue;
for(int i = 0; i < len; i++) {
Folder cFolder = contents[i] as Folder;
if (cFolder == null) {
continue;
}
DateTime cDate = cFolder.Creation_date;
KUtil.Log("找到子文件夹:"+cFolder.Object_name+"|创建时间:"+cDate);
if (latest == null) {
latest = cDate;
targetFolder = cFolder;
}
else {
if (latest.CompareTo(cDate) < 0) {
latest = cDate;
targetFolder = cFolder;
}
}
}
}
}
}
if (targetFolder == null) {
KUtil.Log("没有指定存放文件夹放到NewStuff");
TCUtil.GetProperties(false, new ModelObject[] { TCUtil.user }, "newstuff_folder");
targetFolder = TCUtil.user.Newstuff_folder;
}
else {
KUtil.Log("找到最新的文件夹:"+targetFolder.Object_name);
}
return targetFolder;
}
private void Window_Loaded(object sender, RoutedEventArgs e) {
int len = tableData.Count;
bool needApply = false;
for(int i = 0; i < len; i++) {
if (KPartSync.SAP_NEED_ID.Equals(tableData[i].reason)) {
needApply = true;
}
}
b_Apply.IsEnabled = needApply;
b_Export.IsEnabled = len != 0;
}
private void CLose_Button_Click(object sender, RoutedEventArgs e) {
Close();
}
private void Export_Button_Click(object sender, RoutedEventArgs e) {
try {
doExport();
}catch(System.Exception ex) {
System.Windows.MessageBox.Show(this, "导出出错:"+ex.Message);
KUtil.LogErr(ex);
}
}
private void Apply_Button_Click(object sender, RoutedEventArgs e) {
this.bgWorkder_apply.Start(null);
}
}
}

@ -0,0 +1,12 @@
<Window x:Class="KPlan.Forms.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" WindowStartupLocation="CenterOwner">
<Grid>
<Label Content="啊啊啊啊啊啊啊" HorizontalAlignment="Left" Margin="171,112,0,0" VerticalAlignment="Top"/>
</Grid>
</Window>

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
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;
namespace KPlan.Forms {
/// <summary>
/// UserControl1.xaml 的交互逻辑
/// </summary>
public partial class TestWindow : System.Windows.Window {
public TestWindow() {
InitializeComponent();
}
}
}

@ -0,0 +1,482 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{A7F5F234-14A2-4AC1-A8FF-4535D68A3B40}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>KPlan</RootNamespace>
<AssemblyName>EPLAN.EplAddin.KPlan</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>false</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>2606_Public.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<PropertyGroup>
<DelaySign>true</DelaySign>
</PropertyGroup>
<ItemGroup>
<Reference Include="Eplan.EplApi.AFu, Version=1.0.0.0, Culture=neutral, PublicKeyToken=57aaa27e22f7b107, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>lib\Eplan.EplApi.AFu.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Eplan.EplApi.Baseu, Version=1.0.0.0, Culture=neutral, PublicKeyToken=57aaa27e22f7b107, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>lib\Eplan.EplApi.Baseu.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Eplan.EplApi.DataModelu, Version=1.0.0.0, Culture=neutral, PublicKeyToken=57aaa27e22f7b107, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>lib\Eplan.EplApi.DataModelu.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Eplan.EplApi.EServicesu, Version=1.0.0.0, Culture=neutral, PublicKeyToken=57aaa27e22f7b107, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>lib\Eplan.EplApi.EServicesu.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Eplan.EplApi.Guiu, Version=1.0.0.0, Culture=neutral, PublicKeyToken=57aaa27e22f7b107, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>lib\Eplan.EplApi.Guiu.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Eplan.EplApi.HEServicesu, Version=1.0.0.0, Culture=neutral, PublicKeyToken=57aaa27e22f7b107, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>lib\Eplan.EplApi.HEServicesu.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Eplan.EplApi.MasterDatau, Version=1.0.0.0, Culture=neutral, PublicKeyToken=57aaa27e22f7b107, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>lib\Eplan.EplApi.MasterDatau.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Eplan.EplApi.Starteru, Version=1.0.0.0, Culture=neutral, PublicKeyToken=57aaa27e22f7b107, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>lib\Eplan.EplApi.Starteru.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="FCCNetClientProxy40">
<HintPath>lib\FCCNetClientProxy40.dll</HintPath>
</Reference>
<Reference Include="FMSNetTicket40">
<HintPath>lib\FMSNetTicket40.dll</HintPath>
</Reference>
<Reference Include="FSCNetClientProxy40">
<HintPath>lib\FSCNetClientProxy40.dll</HintPath>
</Reference>
<Reference Include="ICSharpCode.SharpZipLib, Version=1.2.0.246, Culture=neutral, PublicKeyToken=1b03e6acf1164f73, processorArchitecture=MSIL">
<HintPath>..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll</HintPath>
</Reference>
<Reference Include="log4net">
<HintPath>lib\log4net.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Office.Interop.Excel, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Office, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Oracle.ManagedDataAccess, Version=2.0.19.1, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=MSIL">
<HintPath>..\packages\Oracle.ManagedDataAccess.Core.2.19.60\lib\netstandard2.0\Oracle.ManagedDataAccess.dll</HintPath>
</Reference>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Data.OracleClient" />
<Reference Include="System.Drawing" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.IO.Compression.FileSystem" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xaml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="TcMemNetBinding40">
<HintPath>lib\TcMemNetBinding40.dll</HintPath>
</Reference>
<Reference Include="TcMemNetBindingInterface40">
<HintPath>lib\TcMemNetBindingInterface40.dll</HintPath>
</Reference>
<Reference Include="TcServerNetBinding40">
<HintPath>lib\TcServerNetBinding40.dll</HintPath>
</Reference>
<Reference Include="TcServerNetBindingInterface40">
<HintPath>lib\TcServerNetBindingInterface40.dll</HintPath>
</Reference>
<Reference Include="TcSoaAdministrationStrong">
<HintPath>lib\TcSoaAdministrationStrong.dll</HintPath>
</Reference>
<Reference Include="TcSoaAdministrationTypes">
<HintPath>lib\TcSoaAdministrationTypes.dll</HintPath>
</Reference>
<Reference Include="TcSoaCadBomAlignmentStrong">
<HintPath>lib\TcSoaCadBomAlignmentStrong.dll</HintPath>
</Reference>
<Reference Include="TcSoaCadBomAlignmentTypes">
<HintPath>lib\TcSoaCadBomAlignmentTypes.dll</HintPath>
</Reference>
<Reference Include="TcSoaCadStrong">
<HintPath>lib\TcSoaCadStrong.dll</HintPath>
</Reference>
<Reference Include="TcSoaCadTypes">
<HintPath>lib\TcSoaCadTypes.dll</HintPath>
</Reference>
<Reference Include="TcSoaClassificationStrong">
<HintPath>lib\TcSoaClassificationStrong.dll</HintPath>
</Reference>
<Reference Include="TcSoaClassificationTypes">
<HintPath>lib\TcSoaClassificationTypes.dll</HintPath>
</Reference>
<Reference Include="TcSoaClient, Version=11000.2.0.0, Culture=neutral, PublicKeyToken=0edd5b5ddd601444, processorArchitecture=MSIL">
<HintPath>lib\TcSoaClient.dll</HintPath>
<SpecificVersion>False</SpecificVersion>
</Reference>
<Reference Include="TcSoaCommon">
<HintPath>lib\TcSoaCommon.dll</HintPath>
</Reference>
<Reference Include="TcSoaCoreStrong">
<HintPath>lib\TcSoaCoreStrong.dll</HintPath>
</Reference>
<Reference Include="TcSoaCoreTypes">
<HintPath>lib\TcSoaCoreTypes.dll</HintPath>
</Reference>
<Reference Include="TcSoaFMS64">
<HintPath>lib\TcSoaFMS64.dll</HintPath>
</Reference>
<Reference Include="TcSoaQueryStrong">
<HintPath>lib\TcSoaQueryStrong.dll</HintPath>
</Reference>
<Reference Include="TcSoaQueryTypes">
<HintPath>lib\TcSoaQueryTypes.dll</HintPath>
</Reference>
<Reference Include="TcSoaStrongModel">
<HintPath>lib\TcSoaStrongModel.dll</HintPath>
</Reference>
<Reference Include="TcSoaWorkflowStrong">
<HintPath>lib\TcSoaWorkflowStrong.dll</HintPath>
</Reference>
<Reference Include="TcSoaWorkflowTypes">
<HintPath>lib\TcSoaWorkflowTypes.dll</HintPath>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="Xceed.Wpf.AvalonDock">
<HintPath>..\packages\Extended.Wpf.Toolkit.3.5.0\lib\net40\Xceed.Wpf.AvalonDock.dll</HintPath>
</Reference>
<Reference Include="Xceed.Wpf.AvalonDock.Themes.Aero">
<HintPath>..\packages\Extended.Wpf.Toolkit.3.5.0\lib\net40\Xceed.Wpf.AvalonDock.Themes.Aero.dll</HintPath>
</Reference>
<Reference Include="Xceed.Wpf.AvalonDock.Themes.Metro">
<HintPath>..\packages\Extended.Wpf.Toolkit.3.5.0\lib\net40\Xceed.Wpf.AvalonDock.Themes.Metro.dll</HintPath>
</Reference>
<Reference Include="Xceed.Wpf.AvalonDock.Themes.VS2010">
<HintPath>..\packages\Extended.Wpf.Toolkit.3.5.0\lib\net40\Xceed.Wpf.AvalonDock.Themes.VS2010.dll</HintPath>
</Reference>
<Reference Include="Xceed.Wpf.Toolkit">
<HintPath>..\packages\Extended.Wpf.Toolkit.3.5.0\lib\net40\Xceed.Wpf.Toolkit.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Actions\CheckProjectAction.cs" />
<Compile Include="Actions\ConfigureAction.cs" />
<Compile Include="Actions\CreateProjectAction.cs" />
<Compile Include="Actions\DownloadTCDataAction.cs" />
<Compile Include="Actions\KCheckProjectAction.cs" />
<Compile Include="Actions\KCheckProjectAction_Ex.cs" />
<Compile Include="Actions\KDownloadTCDataAction.cs" />
<Compile Include="Actions\KPartSyncAction.cs" />
<Compile Include="Actions\LoginAction.cs" />
<Compile Include="Actions\OpenFromTCAction.cs" />
<Compile Include="Actions\PartSyncAction.cs" />
<Compile Include="Actions\SaveProjectAction.cs" />
<Compile Include="ClientX\AppXCredentialManager.cs" />
<Compile Include="ClientX\AppXExceptionHandler.cs" />
<Compile Include="ClientX\AppXModelEventListener.cs" />
<Compile Include="ClientX\AppXPartialErrorListener.cs" />
<Compile Include="ClientX\AppXRequestListener.cs" />
<Compile Include="ClientX\Session.cs" />
<Compile Include="Forms\Bean\CheckTableRowData.cs" />
<Compile Include="Forms\Bean\DuplicateOrderNrBean.cs" />
<Compile Include="Forms\Bean\EPlanPropBean.cs" />
<Compile Include="Forms\Bean\KPartSyncDataRow.cs" />
<Compile Include="Forms\Bean\ModelObjectBean.cs" />
<Compile Include="Forms\Bean\PartSyncClassConfigBean.cs" />
<Compile Include="Forms\Bean\PartSyncDataRow.cs" />
<Compile Include="Forms\Bean\EPlanTreeItem.cs" />
<Compile Include="Forms\Bean\PartSyncConfigBean.cs" />
<Compile Include="Forms\Bean\SyncResult.cs" />
<Compile Include="Forms\Bean\TCPropBean.cs" />
<Compile Include="Forms\Bean\TCTreeItem.cs" />
<Compile Include="Forms\Configure.xaml.cs">
<DependentUpon>Configure.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\Config_Classification.xaml.cs">
<DependentUpon>Config_Classification.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\Config_Others.xaml.cs">
<DependentUpon>Config_Others.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\Config_PartSync.xaml.cs">
<DependentUpon>Config_PartSync.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\Config_ProjSync.xaml.cs">
<DependentUpon>Config_ProjSync.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\CreateProject.xaml.cs">
<DependentUpon>CreateProject.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\KBackgroundWorker.cs" />
<Compile Include="Forms\KBgWorker2.xaml.cs">
<DependentUpon>KBgWorker2.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\KCheckProject.xaml.cs">
<DependentUpon>KCheckProject.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\KCheckProject_Ex.xaml.cs">
<DependentUpon>KCheckProject_Ex.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\KPartSync.xaml.cs">
<DependentUpon>KPartSync.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\KStyle.xaml.cs">
<DependentUpon>KStyle.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\Login.xaml.cs">
<DependentUpon>Login.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\NewPartNr.xaml.cs">
<DependentUpon>NewPartNr.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\OpenFromTC.xaml.cs">
<DependentUpon>OpenFromTC.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\PartSync.xaml.cs">
<DependentUpon>PartSync.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\PartSyncResult.xaml.cs">
<DependentUpon>PartSyncResult.xaml</DependentUpon>
</Compile>
<Compile Include="Forms\Bean\TableRowData.cs" />
<Compile Include="Forms\TestWindow.xaml.cs">
<DependentUpon>TestWindow.xaml</DependentUpon>
</Compile>
<Compile Include="KPlanModule.cs" />
<Compile Include="KTestAction.cs" />
<Compile Include="Logger\TDefaultLogger.cs" />
<Compile Include="Logger\TLogAgent.cs" />
<Compile Include="Logger\TLogManager.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="RefActions\CheckForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="RefActions\CheckForm.Designer.cs">
<DependentUpon>CheckForm.cs</DependentUpon>
</Compile>
<Compile Include="RefActions\EplimPublicMethod.cs" />
<Compile Include="RefActions\GeneralListForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="RefActions\GeneralListForm.Designer.cs">
<DependentUpon>GeneralListForm.cs</DependentUpon>
</Compile>
<Compile Include="RefActions\SaveForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="RefActions\SaveForm.Designer.cs">
<DependentUpon>SaveForm.cs</DependentUpon>
</Compile>
<Compile Include="RefActions\TCTool.cs" />
<Compile Include="RefActions\ZipHelper.cs" />
<Compile Include="Util\EplanUtil.cs" />
<Compile Include="Util\KConfigure.cs" />
<Compile Include="Util\KUtil.cs" />
<Compile Include="Util\TCUtil.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="Logger\LogConfig.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Resource Include="Resources_EPLAN\Busbars.png" />
<Resource Include="Resources_EPLAN\Cable ducts.png" />
<Resource Include="Resources\add16.png" />
<Resource Include="Resources\delete16.png" />
<Content Include="Resources_EPLAN\edit_16.png" />
<Content Include="Resources_EPLAN\edit_24.png" />
<Resource Include="Resources_EPLAN\Electrical engineering - special items.png" />
<Resource Include="Resources_EPLAN\Enclosure.png" />
<Resource Include="Resources_EPLAN\Field distribution device.png" />
<Resource Include="Resources_EPLAN\Heating.png" />
<Resource Include="Resources_EPLAN\Housing accessories, external extension.png" />
<Resource Include="Resources_EPLAN\Housing accessories, internal extension.png" />
<Resource Include="Resources_EPLAN\Housing.png" />
<Resource Include="Resources_EPLAN\Light.png" />
<Resource Include="Resources_EPLAN\Lock systems.png" />
<Resource Include="Resources_EPLAN\Logic items.png" />
<Resource Include="Resources_EPLAN\Measuring instruments, test devices.png" />
<Resource Include="Resources_EPLAN\Motors.png" />
<Resource Include="Resources_EPLAN\PLC.png" />
<Resource Include="Resources_EPLAN\Plugs.png" />
<Resource Include="Resources_EPLAN\Power switchgear.png" />
<Resource Include="Resources_EPLAN\Protection devices.png" />
<Resource Include="Resources_EPLAN\Relays, contactors.png" />
<Resource Include="Resources_EPLAN\Resistors.png" />
<Resource Include="Resources_EPLAN\Sensor, switch, and pushbutton.png" />
<Resource Include="Resources_EPLAN\Signal devices.png" />
<Resource Include="Resources_EPLAN\Terminals.png" />
<Resource Include="Resources_EPLAN\Transformers.png" />
<Resource Include="Resources_EPLAN\Transmission paths.png" />
<Resource Include="Resources_EPLAN\Undefined.png" />
<Resource Include="Resources_EPLAN\User-defined rail.png" />
<Resource Include="Resources_EPLAN\Valves.png" />
<Resource Include="Resources_EPLAN\Voltage source and generator.png" />
<Resource Include="Resources\edit_16.png" />
<Resource Include="Resources_EPLAN\Cables.png" />
<Resource Include="Resources_EPLAN\Connections.png" />
<Resource Include="Resources_EPLAN\Converters.png" />
<Resource Include="Resources_EPLAN\Amplifiers, controllers.png" />
<Resource Include="Resources_EPLAN\e_folder.png" />
<Resource Include="Resources\form_16.png" />
<Resource Include="Resources\mailboxfolder_16.png" />
<Resource Include="Resources\newstufffolder_16.png" />
<Resource Include="Resources\dataset_16.png" />
<Resource Include="Resources\itemrevision_16.png" />
<Resource Include="Resources\item_16.png" />
<Resource Include="Resources\folder_16.png" />
<Resource Include="Resources\homefolder_16.png" />
<Resource Include="Resources\logo_16.ico" />
</ItemGroup>
<ItemGroup>
<Page Include="Forms\Configure.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\Config_Classification.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\Config_Others.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\Config_PartSync.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\Config_ProjSync.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\CreateProject.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\KBgWorker2.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\KCheckProject.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\KCheckProject_Ex.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\KPartSync.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\KStyle.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\Login.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\NewPartNr.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\OpenFromTC.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\PartSync.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\PartSyncResult.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Forms\TestWindow.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Include="RefActions\CheckForm.resx">
<DependentUpon>CheckForm.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="RefActions\GeneralListForm.resx">
<DependentUpon>GeneralListForm.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="RefActions\SaveForm.resx">
<DependentUpon>SaveForm.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="2606_Public.snk" />
<None Include="App.config">
<SubType>Designer</SubType>
</None>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

@ -0,0 +1,86 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eplan.EplApi.Gui;
using KPlan.Util;
namespace KPlan
{
public class KPlanModule:Eplan.EplApi.ApplicationFramework.IEplAddIn
{
public static Menu kMenu = new Menu();
public static uint menuId;
public const int PART_SYNC_MENU_INDEX = 0;
public static uint PART_SYNC_MENU_ID;
public static uint SETTING_MENU_ID;
public bool OnRegister(ref System.Boolean bLoadOnStart) {
bLoadOnStart = true;
return true;
}
public bool OnUnregister() {
return true;
}
public bool OnInit() {
return true;
}
public static void AddSpMenu() {
PART_SYNC_MENU_ID = kMenu.AddMenuItem("部件库同步", "KPartSyncAction", "", menuId, PART_SYNC_MENU_INDEX, false, false);
SETTING_MENU_ID = kMenu.AddMenuItem("设置", "ConfigureAction", "", menuId, 0, false, false);
KUtil.Log("添加菜单:"+PART_SYNC_MENU_ID);
}
public static void RemoveSpMenu() {
KUtil.Log("移除菜单:"+PART_SYNC_MENU_ID);
kMenu.RemoveMenuItem(PART_SYNC_MENU_ID);
kMenu.RemoveMenuItem(SETTING_MENU_ID);
}
public bool OnInitGui() {
//Eplan.EplApi.Gui.Menu oMenu = new Eplan.EplApi.Gui.Menu();
menuId = kMenu.AddMainMenu("Teamcenter集成", Menu.MainMenuName.eMainMenuUtilities, "检查并保存", "KCheckProjectAction_Ex", "", 0);
kMenu.AddMenuItem("登录", "LoginAction", "", menuId, 0, false, false);
//kMenu.AddMenuItem("设置", "ConfigureAction", "", menuId, 0, false, false);
kMenu.AddMenuItem("新建", "CreateProjectAction", "", menuId, 0, false, false);
kMenu.AddMenuItem("打开", "OpenFromTCAction", "", menuId, 0, false, true);
//kMenu.AddMenuItem("检查并保存", "KCheckProjectAction_Ex", "", menuId, 0, false, false);
//kMenu.AddMenuItem("检查", "CheckProjectAction", "", menuId, 5, false, false);
//kMenu.AddMenuItem("保存", "SaveProjectAction", "", menuId, 6, false, false);
// kMenu.AddMenuItem("设置", "ConfigureAction", "", menuId, 0, false, true);
// kMenu.AddMenuItem("下载 EPLAN 主数据", "KDownloadTCDataAction", "", menuId, 0, true, false);
//kMenu.AddMenuItem("部件库同步 (new)", "KPartSyncAction", "", menuId, 8, false, false);
//kMenu.AddMenuItem("部件库同步", "PartSyncAction", "", menuId, 7, false, false);
//TCUtil.PreLogin(); KTestAction
//kMenu.AddMenuItem("测试", "KTestAction", "", menuId, 11, false, false);
//kMenu.AddMenuItem("检查并保存", "KCheckProjectAction", "", menuId, 12, true, false);
//kMenu.AddMenuItem("下载TC数据至EPLAN", "KDownloadTCDataAction", "", menuId, 14, false, false);
return true;
}
public bool OnExit() {
KUtil.Log("系统退出");
//退出soa登录
try {
TCUtil.Logout();
}
catch (System.Exception ex) {
KUtil.LogErr(ex);
}
//try {
// EplanUtil.mdPartsDatabase.Close();
// KUtil.Log("PartsDatabase已关闭");
//}
//catch (System.Exception ex) {
// KUtil.LogErr(ex);
//}
return true;
}
}
}

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eplan.EplApi.ApplicationFramework;
using KPlan.Util;
using KPlan.Forms;
using System.Windows;
using Eplan.EplApi.MasterData;
using Eplan.EplApi.DataModel;
using Eplan.EplApi.Base;
using System.Threading;
namespace KPlan {
class KTestAction : Eplan.EplApi.ApplicationFramework.IEplAction{
public bool Execute(ActionCallingContext ctx) {
//MDPartsDatabase mDPartsDatabase = EplanUtil.OpenDatabase();
//List<MDPart> parts = EplanUtil.GetUnsyncedParts(mDPartsDatabase, "", "");
//int cnt = parts==null?0:parts.Count;
//MessageBox.Show(""+cnt);
//Util.EplanUtil.UpdateAndClose(mDPartsDatabase);
Eplan.EplApi.MasterData.MDPartsDatabase mdPartsDatabase = Util.EplanUtil.OpenDatabase();
mdPartsDatabase.UpdateSearchIndex();
new KPartSync(mdPartsDatabase).ShowDialog();
Util.EplanUtil.UpdateAndClose(mdPartsDatabase);
return true;
}
public bool OnRegister(ref string Name, ref int Ordinal) {
Name = "KTestAction";
Ordinal = 20;
return true;
}
public void GetActionProperties(ref ActionProperties actionProperties) {
//actionProperties.Description = "Action test with parameters.";
}
}
}

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<!--日志默认在用户temp目录-->
<appender name="StackTrace" type="log4net.Appender.RollingFileAppender">
<file value="${TMP}/StackTrace.log" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<maximumFileSize value="200KB" />
<maxSizeRollBackups value="10" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline %n记录时间: %date %n线程ID: [%thread] %n日志级别: %-5level %n出错类: %logger property: [%property{NDC}] %n错误描述: %message%newline %n" />
</layout>
</appender>
<appender name="KDebug" type="log4net.Appender.RollingFileAppender">
<file value="C:\\KPlanLog\\KPLAN.log" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<maximumFileSize value="200KB" />
<maxSizeRollBackups value="10" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="[%date] %message %newline" />
</layout>
</appender>
<!-- Loggers -->
<!--<root>
<level value="DEBUG" />
<appender-ref ref="StackTrace" />
</root>
-->
<logger name="KLogger">
<level value="DEBUG"/>
<appender-ref ref="KDebug" />
</logger>
<!--
<logger name="cn.com.extech.PLM.StackTrace" additivity="false">
<level value="DEBUG"/>
<appender-ref ref="StackTrace" />
</logger>
-->
</log4net>

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KPlan.Util;
namespace KPlan.Logger {
public class TDefaultLogger {
private const string APPENDER = "cn.com.connor.WorkTimeSheetsManagement";
private static TDefaultLogger _instance = null;
private TLogManager theLogManager;
private TLogAgent logger;
public TLogAgent LogAgent {
get {
return logger;
}
}
public static TDefaultLogger CreateInstance() {
if (_instance == null)
TDefaultLogger._instance = new TDefaultLogger();
return _instance;
}
public static void UpdateInstance() {
TDefaultLogger._instance = null;
TDefaultLogger._instance = new TDefaultLogger();
}
public TLogManager Get() {
return theLogManager;
}
public TLogAgent GetLogagent(string tag) {
return theLogManager.GetLogger(tag);
}
public TLogAgent GetLogagent(object tag) {
return theLogManager.GetLogger(tag);
}
public TLogAgent GetLogagent(Type tag) {
return theLogManager.GetLogger(tag);
}
private TDefaultLogger() {
theLogManager = TLogManager.Create();
theLogManager.State = TLogManager.StateType.AlwaysON;
logger = theLogManager.GetLogger("KLogger");
}
}
}

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KPlan.Util;
namespace KPlan.Logger {
public class TDefaultLogger {
private static TDefaultLogger _instance = null;
private TLogManager theLogManager;
private TLogAgent logger;
public TLogAgent LogAgent {
get {
return logger;
}
}
public static TDefaultLogger CreateInstance() {
if (_instance == null)
TDefaultLogger._instance = new TDefaultLogger();
return _instance;
}
public static void UpdateInstance() {
TDefaultLogger._instance = null;
TDefaultLogger._instance = new TDefaultLogger();
}
public TLogManager Get() {
return theLogManager;
}
public TLogAgent GetLogagent(string tag) {
return theLogManager.GetLogger(tag);
}
public TLogAgent GetLogagent(object tag) {
return theLogManager.GetLogger(tag);
}
public TLogAgent GetLogagent(Type tag) {
return theLogManager.GetLogger(tag);
}
private TDefaultLogger() {
theLogManager = TLogManager.Create();
theLogManager.State = TLogManager.StateType.AlwaysON;
logger = theLogManager.GetLogger("KLogger");
}
}
}

@ -0,0 +1,278 @@
using log4net;
using log4net.Core;
using System;
using KPlan.Util;
namespace KPlan.Logger {
public class TLogAgent {
private TLogManager logManager;
private ILog theLogger;
private string subSystem;
private bool IsOn {
get {
if (this.logManager != null && this.logManager.IsOn) {
if (this.theLogger == null) {
this.theLogger = LogManager.GetLogger(this.subSystem);
}
return true;
}
return false;
}
}
public bool IsDebugEnabled {
get {
return this.IsOn && this.theLogger.IsDebugEnabled;
}
}
public bool IsInfoEnabled {
get {
return this.IsOn && this.theLogger.IsInfoEnabled;
}
}
public bool IsWarnEnabled {
get {
return this.IsOn && this.theLogger.IsWarnEnabled;
}
}
public bool IsErrorEnabled {
get {
return this.IsOn && this.theLogger.IsErrorEnabled;
}
}
public bool IsFatalEnabled {
get {
return this.IsOn && this.theLogger.IsFatalEnabled;
}
}
public ILogger Logger {
get {
return null;
}
}
internal TLogAgent(TLogManager m, string s) {
this.logManager = m;
this.subSystem = s;
}
public void Fatal(object message) {
if (this.IsOn && this.theLogger.IsFatalEnabled) {
this.theLogger.Fatal(message);
}
}
public void Fatal(object message, Exception exception) {
if (this.IsOn && this.theLogger.IsFatalEnabled) {
this.theLogger.Fatal(message, exception);
}
}
public void FatalFormat(string format, object arg0) {
if (this.IsOn && this.theLogger.IsFatalEnabled) {
this.theLogger.FatalFormat(format, arg0);
}
}
public void FatalFormat(string format, object arg0, object arg1) {
if (this.IsOn && this.theLogger.IsFatalEnabled) {
this.theLogger.FatalFormat(format, arg0, arg1);
}
}
public void FatalFormat(string format, object arg0, object arg1, object arg2) {
if (this.IsOn && this.theLogger.IsFatalEnabled) {
this.theLogger.FatalFormat(format, arg0, arg1, arg2);
}
}
public void FatalFormat(string format, params object[] args) {
if (this.IsOn && this.theLogger.IsFatalEnabled) {
this.theLogger.FatalFormat(format, args);
}
}
public void FatalFormat(IFormatProvider provider, string format, params object[] args) {
if (this.IsOn && this.theLogger.IsFatalEnabled) {
this.theLogger.FatalFormat(provider, format, args);
}
}
public void Error(object message) {
if (this.IsOn && this.theLogger.IsErrorEnabled) {
this.theLogger.Error(message);
}
}
public void Error(object message, Exception exception) {
if (this.IsOn && this.theLogger.IsErrorEnabled) {
this.theLogger.Error(message, exception);
}
}
public void ErrorFormat(string format, object arg0) {
if (this.IsOn && this.theLogger.IsErrorEnabled) {
this.theLogger.ErrorFormat(format, arg0);
}
}
public void ErrorFormat(string format, object arg0, object arg1) {
if (this.IsOn && this.theLogger.IsErrorEnabled) {
this.theLogger.ErrorFormat(format, arg0, arg1);
}
}
public void ErrorFormat(string format, object arg0, object arg1, object arg2) {
if (this.IsOn && this.theLogger.IsErrorEnabled) {
this.theLogger.ErrorFormat(format, arg0, arg1, arg2);
}
}
public void ErrorFormat(string format, params object[] args) {
if (this.IsOn && this.theLogger.IsErrorEnabled) {
this.theLogger.ErrorFormat(format, args);
}
}
public void ErrorFormat(IFormatProvider provider, string format, params object[] args) {
if (this.IsOn && this.theLogger.IsErrorEnabled) {
this.theLogger.ErrorFormat(provider, format, args);
}
}
public void Warn(object message, Exception exception) {
if (this.IsOn && this.theLogger.IsWarnEnabled) {
this.theLogger.Warn(message, exception);
}
}
public void Warn(object message) {
if (this.IsOn && this.theLogger.IsWarnEnabled) {
this.theLogger.Warn(message);
}
}
public void WarnFormat(string format, object arg0) {
if (this.IsOn && this.theLogger.IsWarnEnabled) {
this.theLogger.WarnFormat(format, arg0);
}
}
public void WarnFormat(string format, object arg0, object arg1) {
if (this.IsOn && this.theLogger.IsWarnEnabled) {
this.theLogger.WarnFormat(format, arg0, arg1);
}
}
public void WarnFormat(string format, object arg0, object arg1, object arg2) {
if (this.IsOn && this.theLogger.IsWarnEnabled) {
this.theLogger.WarnFormat(format, arg0, arg1, arg2);
}
}
public void WarnFormat(IFormatProvider provider, string format, params object[] args) {
if (this.IsOn && this.theLogger.IsWarnEnabled) {
this.theLogger.WarnFormat(provider, format, args);
}
}
public void WarnFormat(string format, params object[] args) {
if (this.IsOn && this.theLogger.IsWarnEnabled) {
this.theLogger.WarnFormat(format, args);
}
}
public void Info(object message) {
if (this.IsOn && this.theLogger.IsInfoEnabled) {
this.theLogger.Info(message);
}
}
public void Info(object message, Exception exception) {
if (this.IsOn && this.theLogger.IsInfoEnabled) {
this.theLogger.Info(message, exception);
}
}
public void InfoFormat(string format, object arg0) {
if (this.IsOn && this.theLogger.IsInfoEnabled) {
this.theLogger.InfoFormat(format, arg0);
}
}
public void InfoFormat(string format, object arg0, object arg1) {
if (this.IsOn && this.theLogger.IsInfoEnabled) {
this.theLogger.InfoFormat(format, arg0, arg1);
}
}
public void InfoFormat(string format, object arg0, object arg1, object arg2) {
if (this.IsOn && this.theLogger.IsInfoEnabled) {
this.theLogger.InfoFormat(format, arg0, arg1, arg2);
}
}
public void InfoFormat(string format, params object[] args) {
if (this.IsOn && this.theLogger.IsInfoEnabled) {
this.theLogger.InfoFormat(format, args);
}
}
public void InfoFormat(IFormatProvider provider, string format, params object[] args) {
if (this.IsOn && this.theLogger.IsInfoEnabled) {
this.theLogger.InfoFormat(provider, format, args);
}
}
public void Debug(object message) {
if (this.IsOn && this.theLogger.IsDebugEnabled) {
this.theLogger.Debug(message);
}
}
public void Debug(object message, Exception exception) {
if (this.IsOn && this.theLogger.IsDebugEnabled) {
this.theLogger.Debug(message, exception);
}
}
public void DebugFormat(string format, object arg0) {
if (this.IsOn && this.theLogger.IsDebugEnabled) {
this.theLogger.DebugFormat(format, arg0);
}
}
public void DebugFormat(string format, object arg0, object arg1) {
if (this.IsOn && this.theLogger.IsDebugEnabled) {
this.theLogger.DebugFormat(format, arg0, arg1);
}
}
public void DebugFormat(string format, object arg0, object arg1, object arg2) {
if (this.IsOn && this.theLogger.IsDebugEnabled) {
this.theLogger.DebugFormat(format, arg0, arg1, arg2);
}
}
public void DebugFormat(string format, params object[] args) {
if (this.IsOn && this.theLogger.IsDebugEnabled) {
this.theLogger.DebugFormat(format, args);
}
}
public void DebugFormat(IFormatProvider provider, string format, params object[] args) {
if (this.IsOn && this.theLogger.IsDebugEnabled) {
this.theLogger.DebugFormat(provider, format, args);
}
}
}
}

@ -0,0 +1,277 @@
using log4net;
using log4net.Core;
using System;
namespace KPlan.Logger {
public class TLogAgent {
private TLogManager logManager;
private ILog theLogger;
private string subSystem;
private bool IsOn {
get {
if (this.logManager != null && this.logManager.IsOn) {
if (this.theLogger == null) {
this.theLogger = LogManager.GetLogger(this.subSystem);
}
return true;
}
return false;
}
}
public bool IsDebugEnabled {
get {
return this.IsOn && this.theLogger.IsDebugEnabled;
}
}
public bool IsInfoEnabled {
get {
return this.IsOn && this.theLogger.IsInfoEnabled;
}
}
public bool IsWarnEnabled {
get {
return this.IsOn && this.theLogger.IsWarnEnabled;
}
}
public bool IsErrorEnabled {
get {
return this.IsOn && this.theLogger.IsErrorEnabled;
}
}
public bool IsFatalEnabled {
get {
return this.IsOn && this.theLogger.IsFatalEnabled;
}
}
public ILogger Logger {
get {
return null;
}
}
internal TLogAgent(TLogManager m, string s) {
this.logManager = m;
this.subSystem = s;
}
public void Fatal(object message) {
if (this.IsOn && this.theLogger.IsFatalEnabled) {
this.theLogger.Fatal(message);
}
}
public void Fatal(object message, Exception exception) {
if (this.IsOn && this.theLogger.IsFatalEnabled) {
this.theLogger.Fatal(message, exception);
}
}
public void FatalFormat(string format, object arg0) {
if (this.IsOn && this.theLogger.IsFatalEnabled) {
this.theLogger.FatalFormat(format, arg0);
}
}
public void FatalFormat(string format, object arg0, object arg1) {
if (this.IsOn && this.theLogger.IsFatalEnabled) {
this.theLogger.FatalFormat(format, arg0, arg1);
}
}
public void FatalFormat(string format, object arg0, object arg1, object arg2) {
if (this.IsOn && this.theLogger.IsFatalEnabled) {
this.theLogger.FatalFormat(format, arg0, arg1, arg2);
}
}
public void FatalFormat(string format, params object[] args) {
if (this.IsOn && this.theLogger.IsFatalEnabled) {
this.theLogger.FatalFormat(format, args);
}
}
public void FatalFormat(IFormatProvider provider, string format, params object[] args) {
if (this.IsOn && this.theLogger.IsFatalEnabled) {
this.theLogger.FatalFormat(provider, format, args);
}
}
public void Error(object message) {
if (this.IsOn && this.theLogger.IsErrorEnabled) {
this.theLogger.Error(message);
}
}
public void Error(object message, Exception exception) {
if (this.IsOn && this.theLogger.IsErrorEnabled) {
this.theLogger.Error(message, exception);
}
}
public void ErrorFormat(string format, object arg0) {
if (this.IsOn && this.theLogger.IsErrorEnabled) {
this.theLogger.ErrorFormat(format, arg0);
}
}
public void ErrorFormat(string format, object arg0, object arg1) {
if (this.IsOn && this.theLogger.IsErrorEnabled) {
this.theLogger.ErrorFormat(format, arg0, arg1);
}
}
public void ErrorFormat(string format, object arg0, object arg1, object arg2) {
if (this.IsOn && this.theLogger.IsErrorEnabled) {
this.theLogger.ErrorFormat(format, arg0, arg1, arg2);
}
}
public void ErrorFormat(string format, params object[] args) {
if (this.IsOn && this.theLogger.IsErrorEnabled) {
this.theLogger.ErrorFormat(format, args);
}
}
public void ErrorFormat(IFormatProvider provider, string format, params object[] args) {
if (this.IsOn && this.theLogger.IsErrorEnabled) {
this.theLogger.ErrorFormat(provider, format, args);
}
}
public void Warn(object message, Exception exception) {
if (this.IsOn && this.theLogger.IsWarnEnabled) {
this.theLogger.Warn(message, exception);
}
}
public void Warn(object message) {
if (this.IsOn && this.theLogger.IsWarnEnabled) {
this.theLogger.Warn(message);
}
}
public void WarnFormat(string format, object arg0) {
if (this.IsOn && this.theLogger.IsWarnEnabled) {
this.theLogger.WarnFormat(format, arg0);
}
}
public void WarnFormat(string format, object arg0, object arg1) {
if (this.IsOn && this.theLogger.IsWarnEnabled) {
this.theLogger.WarnFormat(format, arg0, arg1);
}
}
public void WarnFormat(string format, object arg0, object arg1, object arg2) {
if (this.IsOn && this.theLogger.IsWarnEnabled) {
this.theLogger.WarnFormat(format, arg0, arg1, arg2);
}
}
public void WarnFormat(IFormatProvider provider, string format, params object[] args) {
if (this.IsOn && this.theLogger.IsWarnEnabled) {
this.theLogger.WarnFormat(provider, format, args);
}
}
public void WarnFormat(string format, params object[] args) {
if (this.IsOn && this.theLogger.IsWarnEnabled) {
this.theLogger.WarnFormat(format, args);
}
}
public void Info(object message) {
if (this.IsOn && this.theLogger.IsInfoEnabled) {
this.theLogger.Info(message);
}
}
public void Info(object message, Exception exception) {
if (this.IsOn && this.theLogger.IsInfoEnabled) {
this.theLogger.Info(message, exception);
}
}
public void InfoFormat(string format, object arg0) {
if (this.IsOn && this.theLogger.IsInfoEnabled) {
this.theLogger.InfoFormat(format, arg0);
}
}
public void InfoFormat(string format, object arg0, object arg1) {
if (this.IsOn && this.theLogger.IsInfoEnabled) {
this.theLogger.InfoFormat(format, arg0, arg1);
}
}
public void InfoFormat(string format, object arg0, object arg1, object arg2) {
if (this.IsOn && this.theLogger.IsInfoEnabled) {
this.theLogger.InfoFormat(format, arg0, arg1, arg2);
}
}
public void InfoFormat(string format, params object[] args) {
if (this.IsOn && this.theLogger.IsInfoEnabled) {
this.theLogger.InfoFormat(format, args);
}
}
public void InfoFormat(IFormatProvider provider, string format, params object[] args) {
if (this.IsOn && this.theLogger.IsInfoEnabled) {
this.theLogger.InfoFormat(provider, format, args);
}
}
public void Debug(object message) {
if (this.IsOn && this.theLogger.IsDebugEnabled) {
this.theLogger.Debug(message);
}
}
public void Debug(object message, Exception exception) {
if (this.IsOn && this.theLogger.IsDebugEnabled) {
this.theLogger.Debug(message, exception);
}
}
public void DebugFormat(string format, object arg0) {
if (this.IsOn && this.theLogger.IsDebugEnabled) {
this.theLogger.DebugFormat(format, arg0);
}
}
public void DebugFormat(string format, object arg0, object arg1) {
if (this.IsOn && this.theLogger.IsDebugEnabled) {
this.theLogger.DebugFormat(format, arg0, arg1);
}
}
public void DebugFormat(string format, object arg0, object arg1, object arg2) {
if (this.IsOn && this.theLogger.IsDebugEnabled) {
this.theLogger.DebugFormat(format, arg0, arg1, arg2);
}
}
public void DebugFormat(string format, params object[] args) {
if (this.IsOn && this.theLogger.IsDebugEnabled) {
this.theLogger.DebugFormat(format, args);
}
}
public void DebugFormat(IFormatProvider provider, string format, params object[] args) {
if (this.IsOn && this.theLogger.IsDebugEnabled) {
this.theLogger.DebugFormat(provider, format, args);
}
}
}
}

@ -0,0 +1,182 @@
using log4net;
using log4net.Config;
using log4net.Core;
using log4net.Repository.Hierarchy;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using KPlan.Util;
namespace KPlan.Logger {
public class TLogManager {
public enum StateType {
On,
Off,
AlwaysON,
AlwaysOff
}
private const string LoggerStateKey = "LoggerState";
private static TLogManager.StateType globalState;
private bool isConfigured;
private string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\SyncTaskStatus\\Logger");
private string configName = "LogConfig.xml";
private bool isWatching = true;
private Level OldLevel = Level.All;
private TLogManager.StateType logState = TLogManager.StateType.Off;
private static List<TLogManager> loggers = new List<TLogManager>();
public TLogManager.StateType State {
get {
return this.logState;
}
set {
this.logState = value;
if (this.logState == TLogManager.StateType.Off || this.logState == TLogManager.StateType.AlwaysOff) {
this.OldLevel = ((Hierarchy)LogManager.GetRepository()).Root.Level;
((Hierarchy)LogManager.GetRepository()).Root.Level = Level.Off;
return;
}
((Hierarchy)LogManager.GetRepository()).Root.Level = this.OldLevel;
}
}
public static TLogManager.StateType GlobalState {
get {
return TLogManager.globalState;
}
set {
TLogManager.globalState = value;
TLogManager.ChangeState(TLogManager.globalState);
}
}
public bool IsOn {
get {
return this.logState != TLogManager.StateType.Off;
}
}
public bool IsConfigured {
get {
return this.isConfigured;
}
}
public bool IsWatching {
get {
return this.isWatching;
}
set {
this.isWatching = value;
this.Configure();
}
}
public string ConfigName {
get {
return this.configName;
}
set {
this.configName = value;
this.Configure();
}
}
public string ConfigPath {
get {
return this.configPath;
}
set {
this.configPath = value;
this.Configure();
}
}
public string ConfigFile {
get {
return Path.Combine(this.configPath, this.configName);
}
}
public TLogManager() {
TLogManager.loggers.Add(this);
}
public static void SetStateFromConfig() {
//string text = ConfigurationManager.AppSettings["LoggerState"];
string text = KUtil.GetConfigValue(KConfigure.LOG_SECTION,KConfigure.LOG_SWITCH);
TLogManager.GlobalState = ((!string.IsNullOrEmpty(text) && text.ToUpper() == "ON") ? TLogManager.StateType.On : TLogManager.StateType.Off);
}
public static TLogManager Create(string logDir) {
return new TLogManager {
State = TLogManager.GlobalState,
ConfigPath = logDir
};
}
public static TLogManager Create() {
//string Path = ConfigurationManager.AppSettings["LogPath"];
string Path = KUtil.GetConfigValue(KConfigure.LOG_SECTION, KConfigure.LOG_CONFIG_PATH);
if (!string.IsNullOrEmpty(Path))
return TLogManager.Create(Path);
else
return TLogManager.Create("..\\..\\Logger");
}
public TLogAgent GetLogger(string subSystem) {
return new TLogAgent(this, subSystem);
}
public TLogAgent GetLogger(Type t) {
return this.GetLogger(t.Name);
}
public TLogAgent GetLogger(object o) {
return this.GetLogger(o.GetType());
}
public void Configure() {
FileInfo fileInfo = new FileInfo(this.ConfigFile);
if (!fileInfo.Exists) {
this.isConfigured = false;
return;
}
if (this.IsWatching) {
XmlConfigurator.ConfigureAndWatch(fileInfo);
}
else {
XmlConfigurator.Configure(fileInfo);
}
this.isConfigured = true;
}
public void ConfigureFromString(string xml) {
Stream configStream = new MemoryStream(Encoding.Default.GetBytes(xml));
XmlConfigurator.Configure(configStream);
this.isWatching = false;
this.isConfigured = true;
}
private static void ChangeState(TLogManager.StateType state) {
foreach (TLogManager current in TLogManager.loggers) {
if (current.State != TLogManager.StateType.AlwaysON && current.State != TLogManager.StateType.AlwaysOff) {
current.State = state;
}
}
}
}
}

@ -0,0 +1,185 @@
using log4net;
using log4net.Config;
using log4net.Core;
using log4net.Repository.Hierarchy;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using KPlan.Util;
namespace KPlan.Logger {
public class TLogManager {
public enum StateType {
On,
Off,
AlwaysON,
AlwaysOff
}
private const string LoggerStateKey = "LoggerState";
private static TLogManager.StateType globalState;
private bool isConfigured;
private string configPath = "";// Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\SyncTaskStatus\\Logger");
private string configName = "LogConfig.xml";
private bool isWatching = true;
private Level OldLevel = Level.All;
private TLogManager.StateType logState = TLogManager.StateType.On;
private static List<TLogManager> loggers = new List<TLogManager>();
public TLogManager.StateType State {
get {
return this.logState;
}
set {
this.logState = value;
if (this.logState == TLogManager.StateType.Off || this.logState == TLogManager.StateType.AlwaysOff) {
this.OldLevel = ((Hierarchy)LogManager.GetRepository()).Root.Level;
((Hierarchy)LogManager.GetRepository()).Root.Level = Level.Off;
return;
}
((Hierarchy)LogManager.GetRepository()).Root.Level = this.OldLevel;
}
}
public static TLogManager.StateType GlobalState {
get {
return TLogManager.globalState;
}
set {
TLogManager.globalState = value;
TLogManager.ChangeState(TLogManager.globalState);
}
}
public bool IsOn {
get {
return this.logState != TLogManager.StateType.Off;
}
}
public bool IsConfigured {
get {
return this.isConfigured;
}
}
public bool IsWatching {
get {
return this.isWatching;
}
set {
this.isWatching = value;
this.Configure();
}
}
public string ConfigName {
get {
return this.configName;
}
set {
this.configName = value;
this.Configure();
}
}
public string ConfigPath {
get {
return this.configPath;
}
set {
this.configPath = value;
this.Configure();
}
}
public string ConfigFile {
get {
return Path.Combine(this.configPath, this.configName);
}
}
public TLogManager() {
TLogManager.loggers.Add(this);
}
//public static void SetStateFromConfig() {
// //string text = ConfigurationManager.AppSettings["LoggerState"];
// string text = KUtil.GetConfigValue("LoggerState");
// TLogManager.GlobalState = ((!string.IsNullOrEmpty(text) && text.ToUpper() == "ON") ? TLogManager.StateType.On : TLogManager.StateType.Off);
//}
public static TLogManager Create(string logDir) {
return new TLogManager {
State = TLogManager.GlobalState,
ConfigPath = logDir
};
}
public static TLogManager Create() {
return TLogManager.Create("C:\\EPlanLog");
//string Path = ConfigurationManager.AppSettings["LogPath"];
//string Path = KUtil.GetConfigValue("LogPath");
//if (!string.IsNullOrEmpty(Path))
// return TLogManager.Create(Path);
//else
// return TLogManager.Create("..\\..\\Logger");
}
public TLogAgent GetLogger(string subSystem) {
return new TLogAgent(this, subSystem);
}
public TLogAgent GetLogger(Type t) {
return this.GetLogger(t.Name);
}
public TLogAgent GetLogger(object o) {
return this.GetLogger(o.GetType());
}
public void Configure() {
FileInfo fileInfo = new FileInfo(this.ConfigFile);
//System.Windows.Forms.MessageBox.Show("配置文件:"+this.ConfigFile);
if (!fileInfo.Exists) {
//System.Windows.Forms.MessageBox.Show("不存在");
this.isConfigured = false;
return;
}
if (this.IsWatching) {
XmlConfigurator.ConfigureAndWatch(fileInfo);
}
else {
XmlConfigurator.Configure(fileInfo);
}
this.isConfigured = true;
}
public void ConfigureFromString(string xml) {
Stream configStream = new MemoryStream(Encoding.Default.GetBytes(xml));
XmlConfigurator.Configure(configStream);
this.isWatching = false;
this.isConfigured = true;
}
private static void ChangeState(TLogManager.StateType state) {
foreach (TLogManager current in TLogManager.loggers) {
if (current.State != TLogManager.StateType.AlwaysON && current.State != TLogManager.StateType.AlwaysOff) {
current.State = state;
}
}
}
}
}

@ -0,0 +1,37 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
//using Eplan.EplApi.Starter;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("KPlan")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("KPlan")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("42a97c65-91aa-4797-8d06-a34d6db9c459")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
//[assembly: EplanSignedAssemblyAttribute(true)]

@ -0,0 +1,73 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace KPlan.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("KPlan.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon logo_16 {
get {
object obj = ResourceManager.GetObject("logo_16", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
}
}

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="logo_16" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\logo_16.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

@ -0,0 +1,89 @@
namespace KPlan.RefActions {
partial class CheckForm {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CheckForm));
this.btnGenerateList = new System.Windows.Forms.Button();
this.ComListView = new System.Windows.Forms.ListView();
this.btnCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnGenerateList
//
this.btnGenerateList.Location = new System.Drawing.Point(580, 407);
this.btnGenerateList.Name = "btnGenerateList";
this.btnGenerateList.Size = new System.Drawing.Size(111, 27);
this.btnGenerateList.TabIndex = 1;
this.btnGenerateList.Text = "生成申请清单";
this.btnGenerateList.UseVisualStyleBackColor = true;
this.btnGenerateList.Click += new System.EventHandler(this.generateListButton_Click);
//
// ComListView
//
this.ComListView.FullRowSelect = true;
this.ComListView.GridLines = true;
this.ComListView.Location = new System.Drawing.Point(12, 13);
this.ComListView.Name = "ComListView";
this.ComListView.Size = new System.Drawing.Size(803, 387);
this.ComListView.TabIndex = 0;
this.ComListView.UseCompatibleStateImageBehavior = false;
this.ComListView.View = System.Windows.Forms.View.Details;
this.ComListView.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.ComListView_ColumnClick);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(704, 407);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(111, 27);
this.btnCancel.TabIndex = 1;
this.btnCancel.Text = "退出";
this.btnCancel.UseVisualStyleBackColor = true;
//
// CheckForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(827, 442);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnGenerateList);
this.Controls.Add(this.ComListView);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "CheckForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "检查";
this.Load += new System.EventHandler(this.CheckForm_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button btnGenerateList;
private System.Windows.Forms.ListView ComListView;
private System.Windows.Forms.Button btnCancel;
}
}

@ -0,0 +1,344 @@
using Eplan.EplApi.Base;
using Eplan.EplApi.DataModel;
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using KPlan.Util;
using KPlan.RefActions;
namespace KPlan.RefActions {
public partial class CheckForm : Form {
public String projectCode = "";
public Project currentProject = null;
public string xmlFilePath = "";
public CheckForm() {
InitializeComponent();
}
private void CheckForm_Load(object sender, EventArgs e) {
TCTool.ReadConfigs();
int titleNum = TCTool.BomTitleName.Count;
this.ComListView.Columns.Add("检查结果", 80, HorizontalAlignment.Left); //一步添加表头信息
foreach (string str in TCTool.BomTitleName) {
this.ComListView.Columns.Add(str, 120, HorizontalAlignment.Left); //一步添加表头信息
}
Progress progress = new Progress("EnhancedProgress");
progress.SetActionText("正在加载表单...");
progress.SetTitle("加载表单");
progress.BeginPart(100.0, "进度");
progress.ShowImmediately();
progress.SetAllowCancel(true);
if (!ReadXMLFile()) {
btnGenerateList.Enabled = false;
}
else {
btnGenerateList.Enabled = true;
}
progress.EndPart(true);
}
/**
*
* partslist XML
*
*
*
* partslist XML
*
*/
public bool ReadXMLFile() {
XmlTextReader xtr = new XmlTextReader(xmlFilePath);
//MessageBox.Show("xtr---------------------------" + xmlFilePath);
string name_f = "@@";
bool is_dos = false;
bool is_device = false;
string device_name = "";
bool hasError = false;
int record_code_idx = -1;
int record_num_idx = -1;
int PropertyNoum = TCTool.BomPropertyKey.Count;
for (int step = 0; step < PropertyNoum; step++) {
//MessageBox.Show("TCTool.BomPropertyKey[step]---------------------------" + TCTool.BomPropertyKey[step]);
if (TCTool.BomPropertyKey[step].Equals("P_ARTICLE_ERPNR")) {
record_code_idx = step;
}
if (TCTool.BomPropertyKey[step].Equals("P_ARTICLEREF_COUNT")) {
record_num_idx = step;
}
}
try {
this.ComListView.BeginUpdate(); //数据更新UI暂时挂起直到EndUpdate绘制控件可以有效避免闪烁并大大提高加载速度
while (xtr.Read()) {
bool is_other = true;
if (is_device) {
if (xtr.NodeType == XmlNodeType.EndElement) {
is_device = false;
}
else {
continue;
}
}
if (xtr.NodeType != XmlNodeType.Element) {
continue;
}
if (!xtr.HasAttributes) {
continue;
}
string element_name = xtr.Name;
bool is_P_ARTICLE_DISCONTINUED = false;
bool is_wire = false;
string wire_length = "";
string record_code = "";
string record_num = "";
string record_type = "";
string[] propertyValue = new string[PropertyNoum];
while (xtr.MoveToNextAttribute()) {
if (xtr.Name == "P_ARTICLEREF_IDENTNAME") {
device_name = xtr.Value;
}
//if (xtr.Name == "P_ARTICLEREF_IDENTNAME" && xtr.Value.Equals("=+"))
//{
// xtr.MoveToElement();
// is_device = true;
// break;
//}
if (xtr.Name == "P_ARTICLE_DISCONTINUED") //停用
{
if (!xtr.Value.Equals("0")) {
is_P_ARTICLE_DISCONTINUED = true;
}
}
if (xtr.Name == "P_ARTICLE_PARTIAL_LENGTH_VALUE") //此处标识出连接线的部件
{
is_wire = true;
wire_length = xtr.Value;
}
else if (xtr.Name == "P_ARTICLE_ERPNR") {
is_other = false;
record_code = xtr.Value;
}
else if (xtr.Name == "P_ARTICLEREF_COUNT") {
record_num = xtr.Value;
}
else if (xtr.Name == "P_ARTICLE_TYPENR") {
record_type = xtr.Value;
}
for (int step = 0; step < PropertyNoum; step++) {
if (xtr.Name == TCTool.BomPropertyKey[step].ToString()) {
//if (xtr.Name.Equals("P_ARTICLE_ERPNR") && record_code_idx == -1)
//{
// record_code_idx = step;
//}
//if (xtr.Name.Equals("P_ARTICLEREF_COUNT") && record_num_idx == -1)
//{
// record_num_idx = step;
//}
is_other = false;
if (xtr.Value.Contains("@") && xtr.Value.Contains(";")) {
string[] arrStr = xtr.Value.Split(';');
int arrLen = arrStr.Length;
for (int cnt = 0; cnt < arrLen; cnt++) {
if (arrStr[cnt].StartsWith("zh_CN") || arrStr[cnt].StartsWith("??")) {
propertyValue[step] = arrStr[cnt].Split('@')[1];
break;
}
}
}
else {
propertyValue[step] = xtr.Value;
}
break;
}
}
}
if (element_name == "device") //此处过滤掉一些组合设备的部件
{
if (device_name.IndexOf(name_f) != -1) {
is_dos = true;
}
else {
is_dos = false;
}
}
else if (element_name == "part") {
if (is_dos) {
continue;
}
if (TCTool.lineCount != "TRUE") {
if (is_wire) {
continue;
}
}
else {
if (is_wire) {
if (!string.IsNullOrEmpty(wire_length) && !string.IsNullOrEmpty(record_num)) {
double dwire_length = Convert.ToDouble(wire_length);
if (dwire_length != 0.0) {
double drecord_num = Convert.ToDouble(record_num);
drecord_num = dwire_length * drecord_num;
record_num = drecord_num.ToString();
propertyValue[record_num_idx] = record_num;
}
}
}
}
if (record_num.Equals("0")) {
continue;
}
if (is_other) {
name_f = device_name;
}
ListViewItem lvi = new ListViewItem();
lvi.UseItemStyleForSubItems = false;
if (record_code.Equals("")) {
for (int i = 0; i < TCTool.P_ARTICLE_TYPENRs.Count; i++) {
if (record_type.Equals(TCTool.P_ARTICLE_TYPENRs[i].ToString(), StringComparison.OrdinalIgnoreCase)) {
record_code = TCTool.P_ARTICLE_ERPNRs[i].ToString();
propertyValue[record_code_idx] = record_code;
break;
}
}
}
if (is_P_ARTICLE_DISCONTINUED) {
lvi.ForeColor = Color.Red;
hasError = true;
lvi.Text = "停产部件";
}
else {
if (record_code.Equals("")) {
lvi.ForeColor = Color.Red;
hasError = true;
lvi.Text = "TC不存在2";
}
else {
int findItem = TCTool.checkItem(record_code);
if (findItem == 0) {
lvi.ForeColor = Color.Red;
hasError = true;
lvi.Text = "TC不存在3";
}
else {
lvi.Text = "TC存在";
}
}
}
for (int step = 0; step < PropertyNoum; step++) {
if (propertyValue[step] == null) {
lvi.SubItems.Add("");
}
else {
lvi.SubItems.Add(propertyValue[step]).ForeColor=Color.Black;
}
}
this.ComListView.Items.Add(lvi);
}
}
xtr.Close();
this.ComListView.EndUpdate(); //结束数据处理UI界面一次性绘制。
}
catch (XmlException ex) {
MessageBox.Show(ex.Message);
}
return hasError;
}
private void generateListButton_Click(object sender, EventArgs e) {
Progress progress = new Progress("EnhancedProgress");
progress.SetActionText("正在生成excel...");
progress.SetTitle("生成申请清单");
progress.BeginPart(100.0, "进度");
progress.ShowImmediately();
progress.SetAllowCancel(true);
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
string nowtime = DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss");
string fileName = Environment.GetEnvironmentVariable("temp") + "\\申请清单" + nowtime + ".xlsx";
if (File.Exists(fileName)) {
File.Delete(fileName);
}
excel.Visible = false;
excel.Application.Workbooks.Add(true);
Workbook wb = (Workbook)excel.ActiveWorkbook;
Worksheet st = (Worksheet)wb.ActiveSheet;
int col = 1;
foreach (string str in TCTool.BomTitleName) {
st.Cells[1, col] = str;
col++;
}
int row = 2;
for (int i = 0; i < ComListView.Items.Count; i++) {
if (ComListView.Items[i].Text == "TC存在") {
continue;
}
for (int j = 0; j < col - 1; j++) {
st.Cells[row, j + 1] = ComListView.Items[i].SubItems[j + 1].Text;
}
row++;
}
//保存excel文件
wb.SaveCopyAs(fileName);
//关闭文件
wb.Close(false, Type.Missing, Type.Missing);
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.GC.Collect();
progress.EndPart(true);
GeneralListForm generalListForm = new GeneralListForm();
generalListForm.labelName = "申请清单生成完成,请查看!";
generalListForm.xlsPath = fileName;
generalListForm.ShowDialog();
}
private void ComListView_ColumnClick(object sender, ColumnClickEventArgs e) {
ComListView.ListViewItemSorter = new ListViewItemComparer(e.Column);
ComListView.Sort();
}
}
public class ListViewItemComparer : IComparer {
private int col;
public ListViewItemComparer(int col) {
this.col = col;
}
public int Compare(object x, object y) {
int returnVal = -1;
returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text,
((ListViewItem)y).SubItems[col].Text);
return returnVal;
}
}
}

@ -0,0 +1,145 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="$this.Icon" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAABloxIAXZYwBGOgDIccAAhtLwEYPWAGHjdmBhZVSQIGAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAULj2NhmX4nwAhNO+BWuntmEvHGiSLQCmelIB0k12BuBEdgbIVVsEmHUsAECGNwAGAAAAAAAA
AAAAAAAAAAAAALLg+0p/zfvYQLP4/ziRx/A7bY70UFRc/1ZaMv93ZBH/m14C/6BKAP+QLwDqfyoAgIIs
AAwAAAAAAAAAAAAAAAAAAAAAy8/VTKi+z+6umYj/sauM/3GzxP8zmdD/G3mx/zVcbf9zTSn/pEEF/5Qw
APhyOQF6I24HAgAAAAAAAAAAAAAAALU1AWLTZCr45IUl//icAv/xvRf/0s1M/5fIlv9Er9f/EIjO/ydi
g/9iSSn/UV0F5EJmATYAAAAAAAAAAKQ2BxDEPwG672AA//qVAv/7vQb//NgK//zkB//55Qn/49os/53E
hP80p9v/CYbI/xpyYP8wZR6CAAAAAAAAAACwPAoo0UQB4vl0Bf/9rRT//tYr//7tNf/+9zD//fgi//zs
Ev/41Q7/z7Y8/2Glt/8gneX/JoKoxCFokxoAAAAAsjgDONVIAur8gBP//74+///kZP//9XH/+/pk//Lx
Rv/98zH/+90h//i6GP/CmiT/Uaat/0Ky9PwrmNmMAG3BBrI8CSjQSAfi+4Us///Kbv//6pz///mz/7K5
bP+KkTb/++xM//7bN//lxDL/oLUl/2iQMP9Tp9P/XLv06h+Y4EqpMQAOxUYNuPGFRf//yor//+y8/8fM
qv84XyX/R1oe/+XRWv//0kz/z8hI/7WsQv+TZhD8THaO9GjG//9FsvKSAAAAALtFEWTff1H4/7+R/9bB
kv9NcTX/Lmca/zJRGv+VqFP/68pg/7zMXv+srlb/klgn9jl+quJnx///ULz8oAAAAAC1QREQ03xXqNOe
eP9dcjT/QHYt/1WIQf8tVxv/YohJ/6TMb/+e2nb/h7pw/0OBnP84q/D/Z8f/7kC4/14AAAAAAAAAAIRl
MTJTaCriSHo1/36mcP93oWf/NGAi/19/Tf+Ovnb/isSA8j+XnOoxq/HkTL3/uk29/1wVo/8IAAAAAB1X
BgwuZhuQYI1Q+qC9lf+1zK3/oL2V/0h0N/xQcT3OhqVhkm+TZ0oMeb8yL7H+Ije1/w4AAAAAAAAAAAAA
AAAlYg1KS4A31I+xguiqxKHutsyu9rnPsfx1mWjyJU4RVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAKWgRDjp2Ix5EfS4uT4Q7SGOSUWJ4oWl4ZpJVii9iGzgAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAA//8AAMg/AACADwAAwA8AAMAHAACAAwAAgAMAAIABAACAAQAAgAAAAMAAAADAAQAA4AMAAMA/
AADA/wAA/v8AAA==
</value>
</data>
</root>

@ -0,0 +1,411 @@
namespace KPlan.RefActions {
using Eplan.EplApi.ApplicationFramework;
using Eplan.EplApi.Base;
using Eplan.EplApi.DataModel;
using Eplan.EplApi.HEServices;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.Office.Interop.Excel;
using System.Data;
using System.Diagnostics;
public class EplimPublicMethod {
private string eplan_temp_path;
private List<string> parts_list;
private string PROJ_FULL_NAME;
private string PROJ_NAME;
private string xml_file_name;
private string zwl_file_name;
public EplimPublicMethod() {
this.parts_list = new List<string>();
}
public bool Execute() {
Boolean isOk = false;
SelectionSet set;
Eplan.EplApi.DataModel.Project project;
string str;
this.eplan_temp_path = Environment.GetEnvironmentVariable("TEMP").ToString() + @"\";
try {
set = new SelectionSet();
project = set.GetCurrentProject(true);
if (project == null) {
MessageBox.Show("项目不存在。");
return false;
}
// flag2 = 0;
// goto Label_00A9;
// Label_0052:
str = this.TcPath(project.ProjectFullName);
if (str == null) {
MessageBox.Show("项目名称为空。");
return false;
}
isOk = this.ZipProject(project, str);
this.WriteEplanMsg();
}
catch {
MessageBox.Show("Error!");
return false;
}
return isOk;
}
public List<string> get_parts_list() {
List<string> list;
list = this.parts_list;
return list;
}
public string get_proj_full_name() {
string str;
str = this.PROJ_FULL_NAME;
return str;
}
public string get_proj_name() {
string str;
str = this.PROJ_NAME;
return str;
}
private string TcPath(string projectName) {
string str;
string str2;
string str3;
string str4;
string str5;
string str6;
string str7;
string str8;
string[] strArray;
bool flag;
str = null;
str2 = @"Eplan\Electric P8\EplLog.txt";
str3 = System.Windows.Forms.Application.CommonAppDataPath;
str4 = System.Windows.Forms.Application.CompanyName;
str5 = System.Windows.Forms.Application.ProductName;
str6 = System.Windows.Forms.Application.ProductVersion;
str7 = str4 + @"\" + str5 + @"\" + str6;
if ((str3.Contains(str7))) {
goto Label_007A;
}
str3 = str3.Substring(0, str3.IndexOf(str7));
Label_007A:
str8 = this.eplan_temp_path;
return str8;
}
public bool WriteEplanMsg() {
bool flag;
string str;
FileStream stream;
StreamWriter writer;
Exception exception;
try {
stream = new FileStream(this.eplan_temp_path + "eplan_msg.txt", FileMode.OpenOrCreate, FileAccess.Write);
stream.Seek(0L, 0);
stream.SetLength(0L);
writer = new StreamWriter(stream);
writer.WriteLine(this.PROJ_NAME);
writer.WriteLine(this.zwl_file_name);
writer.WriteLine(this.xml_file_name);
writer.Close();
stream.Close();
}
catch (Exception exception1) {
exception = exception1;
MessageBox.Show(exception.Message);
}
return true;
}
//--------------------------------将EXCEL转换成xml-------------------------------------------------
/// <summary>
/// 将xml转换成XML
/// </summary>
/// <param name="xlsPath"></param>
/// <param name="xmlPath"></param>
/// <returns></returns>
private List<ElecPartInfo> xlsToXml(String excelFilePath) {
Stopwatch wath = new Stopwatch();
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Sheets sheets = null;
Microsoft.Office.Interop.Excel.Workbook workbook = null;
object oMissiong = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Range range = null;
List<ElecPartInfo> dt = new List<ElecPartInfo>();
wath.Start();
try {
if (app == null) {
return null;
}
workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
//将数据读入到DataTable中——Start
sheets = workbook.Worksheets;
// UI.GetUI().NXMessageBox.Show("MSG",NXMessageBox.DialogType.Information,"111");
Microsoft.Office.Interop.Excel.Worksheet worksheet = sheets.get_Item(1) as Microsoft.Office.Interop.Excel.Worksheet;//读取第一张表
// UI.GetUI().NXMessageBox.Show("MSG", NXMessageBox.DialogType.Information, "22");
if (worksheet == null)
return null;
string cellContent = null;
int iRowCount = worksheet.UsedRange.Rows.Count;
int iColCount = worksheet.UsedRange.Columns.Count;
int partNo = -1;
int partCount = -1;
int partErp = -1;
int xmh = -1;
//负责列头Start
for (int iCol = 1; iCol <= iColCount; iCol++) {
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, iCol];
cellContent = (range.Value2 == null) ? "" : range.Text.ToString();
switch (cellContent) {
case "物料编码":
partNo = iCol;
break;
case "数量":
partCount = iCol;
break;
case "ERP编码":
partErp = iCol;
break;
case "项目号":
xmh = iCol;
break;
default:
break;
}
}
for (int iRow = 2; iRow <= iRowCount; iRow++) {
ElecPartInfo partInfo = new ElecPartInfo();
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[iRow, partCount];
partInfo.P_ARTICLEREF_COUNT = (range.Value2 == null) ? "" : range.Text.ToString();
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[iRow, partErp];
partInfo.P_ARTICLE_ERPNR = (range.Value2 == null) ? "" : range.Text.ToString();
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[iRow, partNo];
partInfo.P_ARTICLEREF_PARTNO = (range.Value2 == null) ? "" : range.Text.ToString();
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[iRow, xmh];
partInfo.P_ARTICLEREF_IDENTNAME = (range.Value2 == null) ? "" : range.Text.ToString();
Microsoft.Office.Interop.Excel.Range rangetemp = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[iRow, 1];
String cellStr = (rangetemp.Value2 == null) ? "" : rangetemp.Text.ToString();
if (cellStr.Trim().Equals("")) {
break;
}
if (partInfo.P_ARTICLEREF_COUNT != null && !partInfo.P_ARTICLEREF_COUNT.Equals("0"))
dt.Add(partInfo);
}
wath.Stop();
TimeSpan ts = wath.Elapsed;
return dt;
}
catch (Exception ex) {
return dt;
}
finally {
workbook.Close(false, oMissiong, oMissiong);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
app.Workbooks.Close();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
return dt;
}
/// <summary>
/// 写入XML文件
/// </summary>
/// <param name="xmlPath"></param>
/// <param name="partList"></param>
/// <returns></returns>
private bool writeXml(String xmlPath, List<ElecPartInfo> partList) {
bool flag = true;
StringBuilder xmlResult = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
if (partList != null && partList.Count > 0) {
xmlResult.AppendFormat("<partlist RECORD_COUNT=\"{0}\">", partList.Count);
foreach (ElecPartInfo part in partList) {
xmlResult.AppendFormat("<device P_ARTICLEREF_IDENTNAME=\"{0}\">", part.P_ARTICLEREF_IDENTNAME);
xmlResult.AppendFormat("<part P_ARTICLEREF_PARTNO=\"{0}\" P_ARTICLE_ERPNR=\"{1}\" P_ARTICLEREF_COUNT=\"{2}\"/>", part.P_ARTICLEREF_PARTNO, part.P_ARTICLE_ERPNR, part.P_ARTICLEREF_COUNT);
xmlResult.Append("</device>");
}
xmlResult.Append("</partlist>");
}
//写入文件
try {
//1.创建文件流
FileStream fileStream = new FileStream(xmlPath, FileMode.Create);
//2.创建写入器
StreamWriter streamWriter = new StreamWriter(fileStream);
//3.将内容写入文件
streamWriter.WriteLine(xmlResult);
//4.关闭写入器
streamWriter.Close();
//5.关闭文件流
fileStream.Close();
}
catch (Exception e) { }
return flag;
}
//-------------------------------------------------------------------------------------
private bool ZipProject(Eplan.EplApi.DataModel.Project currentProject, string tcPath) {
bool flag;
string str;
ActionCallingContext context;
string[] strArray;
string str2;
ActionCallingContext context2;
ActionCallingContext context3;
PartsService service;
Progress progress;
CommandLineInterpreter interpreter;
Exception exception;
try {
this.PROJ_FULL_NAME = currentProject.ProjectFullName;
str = this.PROJ_FULL_NAME + ".zw1";
this.PROJ_NAME = currentProject.ProjectName;
this.zwl_file_name = "";
this.zwl_file_name = tcPath + this.PROJ_NAME + ".zw1";
context = new ActionCallingContext();
strArray = context.GetParameters();
context.AddParameter("TYPE", "PROJECT");
context.AddParameter("DESTINATIONPATH", tcPath);
context.AddParameter("ARCHIVENAME", str);
context.AddParameter("BACKUPMETHOD", "BACKUP");
context.AddParameter("BACKUPMEDIA", "DISK");
context.AddParameter("SPLITSIZE", "0.0");
context.AddParameter("BACKUPAMOUNT", "BACKUPAMOUNT_ALL");
context.AddParameter("SPLITSIZE", "0.0");
context.AddParameter("INCLEXTDOCS", "1");
context.AddParameter("INCLIMAGES", "1");
str2 = currentProject.ProjectDirectoryPath;
context2 = new ActionCallingContext();
context2.AddParameter("TYPE", "MASTERDATA");
context2.AddParameter("ARCHIVENAME", "D.xls");
context2.AddParameter("PROJECTNAME", str2);
context2.AddParameter("DESTINATIONPATH ", @"c:\");
context2.AddParameter("BACKUPMETHOD", "BACKUP");
context2.AddParameter("BACKUPMEDIA", "DISK");
context2.AddParameter("SOURCEPATH", "");
context2.AddParameter("SPLITSIZE", "0.0");
context2.AddParameter("BACKUPAMOUNT", "BAKAMOUNT_ALL");
context2.AddParameter("INCLEXTDOCS", "1");
context2.AddParameter("INCLIMAGES", "1");
context3 = new ActionCallingContext();
//context3.AddParameter("PROJECTNAME", "EXPORT");
context3.AddParameter("PROJECTNAME", str2);
this.xml_file_name = tcPath + this.PROJ_NAME + ".xml";
String xls_file_name = tcPath + this.PROJ_NAME + ".xls";
context3.AddParameter("CONFIGSCHEME", "部件汇总表2加ERP编码");
context3.AddParameter("LANGUAGE", "zh_CN");
context3.AddParameter("DESTINATIONFILE", xls_file_name);
//context3.AddParameter("MODE", "0");
//context3.AddParameter("ADDITIONAL_LANGUAGE", "1");
service = new PartsService();
progress = new Progress("SimpleProgress");
progress.BeginPart(100.0, "");
progress.ShowImmediately();
progress.SetAllowCancel(true);
if (progress.Canceled()) {
MessageBox.Show("操作终止");
progress.EndPart(true);
return false;
}
interpreter = new CommandLineInterpreter();
if (!interpreter.Execute("backup", context)) {
MessageBox.Show("项目不能备份");
progress.EndPart(true);
return false;
}
if (!interpreter.Execute("label", context3)) {
MessageBox.Show("导出XML失败");
progress.EndPart(true);
return false;
}
List<ElecPartInfo> partList = xlsToXml(xls_file_name);
writeXml(this.xml_file_name, partList);
}
catch (Exception exception1) {
exception = exception1;
MessageBox.Show(exception.Message);
return false;
}
return true;
}
}
/// <summary>
/// 元器件解析单元
/// </summary>
class ElecPartInfo {
public String P_ARTICLE_ERPNR { get; set; }
public String P_ARTICLEREF_PARTNO { get; set; }
public String P_ARTICLEREF_COUNT { get; set; }
public String P_ARTICLEREF_IDENTNAME { get; set; }
}
}

@ -0,0 +1,85 @@
namespace KPlan.RefActions {
partial class GeneralListForm {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GeneralListForm));
this.panel = new System.Windows.Forms.Panel();
this.label = new System.Windows.Forms.Label();
this.openListExcelFileButton = new System.Windows.Forms.Button();
this.panel.SuspendLayout();
this.SuspendLayout();
//
// panel
//
this.panel.Controls.Add(this.label);
this.panel.Location = new System.Drawing.Point(20, 25);
this.panel.Name = "panel";
this.panel.Size = new System.Drawing.Size(257, 46);
this.panel.TabIndex = 0;
//
// label
//
this.label.AutoSize = true;
this.label.Location = new System.Drawing.Point(13, 14);
this.label.Name = "label";
this.label.Size = new System.Drawing.Size(0, 13);
this.label.TabIndex = 0;
//
// openListExcelFileButton
//
this.openListExcelFileButton.Location = new System.Drawing.Point(106, 94);
this.openListExcelFileButton.Name = "openListExcelFileButton";
this.openListExcelFileButton.Size = new System.Drawing.Size(89, 25);
this.openListExcelFileButton.TabIndex = 1;
this.openListExcelFileButton.Text = "打开申请清单";
this.openListExcelFileButton.UseVisualStyleBackColor = true;
this.openListExcelFileButton.Click += new System.EventHandler(this.openListExcelFileButton_Click);
//
// GeneralListForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(289, 132);
this.Controls.Add(this.openListExcelFileButton);
this.Controls.Add(this.panel);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MaximumSize = new System.Drawing.Size(425, 454);
this.Name = "GeneralListForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "提示";
this.Load += new System.EventHandler(this.GeneralListForm_Load);
this.panel.ResumeLayout(false);
this.panel.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel;
private System.Windows.Forms.Button openListExcelFileButton;
private System.Windows.Forms.Label label;
}
}

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KPlan.RefActions {
public partial class GeneralListForm : Form {
public String labelName = "";
public String xlsPath = "";
public GeneralListForm() {
InitializeComponent();
}
private void GeneralListForm_Load(object sender, EventArgs e) {
label.Text = labelName;
}
private void openListExcelFileButton_Click(object sender, EventArgs e) {
System.Diagnostics.Process.Start("explorer", "/n, " + xlsPath);
}
}
}

@ -0,0 +1,145 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="$this.Icon" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAABloxIAXZYwBGOgDIccAAhtLwEYPWAGHjdmBhZVSQIGAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAULj2NhmX4nwAhNO+BWuntmEvHGiSLQCmelIB0k12BuBEdgbIVVsEmHUsAECGNwAGAAAAAAAA
AAAAAAAAAAAAALLg+0p/zfvYQLP4/ziRx/A7bY70UFRc/1ZaMv93ZBH/m14C/6BKAP+QLwDqfyoAgIIs
AAwAAAAAAAAAAAAAAAAAAAAAy8/VTKi+z+6umYj/sauM/3GzxP8zmdD/G3mx/zVcbf9zTSn/pEEF/5Qw
APhyOQF6I24HAgAAAAAAAAAAAAAAALU1AWLTZCr45IUl//icAv/xvRf/0s1M/5fIlv9Er9f/EIjO/ydi
g/9iSSn/UV0F5EJmATYAAAAAAAAAAKQ2BxDEPwG672AA//qVAv/7vQb//NgK//zkB//55Qn/49os/53E
hP80p9v/CYbI/xpyYP8wZR6CAAAAAAAAAACwPAoo0UQB4vl0Bf/9rRT//tYr//7tNf/+9zD//fgi//zs
Ev/41Q7/z7Y8/2Glt/8gneX/JoKoxCFokxoAAAAAsjgDONVIAur8gBP//74+///kZP//9XH/+/pk//Lx
Rv/98zH/+90h//i6GP/CmiT/Uaat/0Ky9PwrmNmMAG3BBrI8CSjQSAfi+4Us///Kbv//6pz///mz/7K5
bP+KkTb/++xM//7bN//lxDL/oLUl/2iQMP9Tp9P/XLv06h+Y4EqpMQAOxUYNuPGFRf//yor//+y8/8fM
qv84XyX/R1oe/+XRWv//0kz/z8hI/7WsQv+TZhD8THaO9GjG//9FsvKSAAAAALtFEWTff1H4/7+R/9bB
kv9NcTX/Lmca/zJRGv+VqFP/68pg/7zMXv+srlb/klgn9jl+quJnx///ULz8oAAAAAC1QREQ03xXqNOe
eP9dcjT/QHYt/1WIQf8tVxv/YohJ/6TMb/+e2nb/h7pw/0OBnP84q/D/Z8f/7kC4/14AAAAAAAAAAIRl
MTJTaCriSHo1/36mcP93oWf/NGAi/19/Tf+Ovnb/isSA8j+XnOoxq/HkTL3/uk29/1wVo/8IAAAAAB1X
BgwuZhuQYI1Q+qC9lf+1zK3/oL2V/0h0N/xQcT3OhqVhkm+TZ0oMeb8yL7H+Ije1/w4AAAAAAAAAAAAA
AAAlYg1KS4A31I+xguiqxKHutsyu9rnPsfx1mWjyJU4RVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAKWgRDjp2Ix5EfS4uT4Q7SGOSUWJ4oWl4ZpJVii9iGzgAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAA//8AAMg/AACADwAAwA8AAMAHAACAAwAAgAMAAIABAACAAQAAgAAAAMAAAADAAQAA4AMAAMA/
AADA/wAA/v8AAA==
</value>
</data>
</root>

@ -0,0 +1,371 @@
namespace KPlan.RefActions {
partial class SaveForm {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SaveForm));
this.label1 = new System.Windows.Forms.Label();
this.tbProjectCode = new System.Windows.Forms.TextBox();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.cbxType = new System.Windows.Forms.ComboBox();
this.btnEPlanItem = new System.Windows.Forms.Button();
this.btnItemID = new System.Windows.Forms.Button();
this.tbEPlanItem = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.tbRevId = new System.Windows.Forms.TextBox();
this.tbItemId = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.ComListView = new System.Windows.Forms.ListView();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.PageListView = new System.Windows.Forms.ListView();
this.tbProjectName = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.SaveButton = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.generateListButton = new System.Windows.Forms.Button();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.tabPage3.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(17, 20);
this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(78, 17);
this.label1.TabIndex = 0;
this.label1.Text = "项目编号:";
//
// tbProjectCode
//
this.tbProjectCode.Location = new System.Drawing.Point(112, 12);
this.tbProjectCode.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.tbProjectCode.Name = "tbProjectCode";
this.tbProjectCode.ReadOnly = true;
this.tbProjectCode.Size = new System.Drawing.Size(449, 22);
this.tbProjectCode.TabIndex = 1;
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.Location = new System.Drawing.Point(20, 62);
this.tabControl1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(1093, 577);
this.tabControl1.TabIndex = 2;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.label6);
this.tabPage1.Controls.Add(this.label7);
this.tabPage1.Controls.Add(this.cbxType);
this.tabPage1.Controls.Add(this.btnEPlanItem);
this.tabPage1.Controls.Add(this.btnItemID);
this.tabPage1.Controls.Add(this.tbEPlanItem);
this.tabPage1.Controls.Add(this.label4);
this.tabPage1.Controls.Add(this.tbRevId);
this.tabPage1.Controls.Add(this.tbItemId);
this.tabPage1.Controls.Add(this.label3);
this.tabPage1.Location = new System.Drawing.Point(4, 25);
this.tabPage1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.tabPage1.Size = new System.Drawing.Size(1085, 548);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "项目属性";
this.tabPage1.UseVisualStyleBackColor = true;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(40, 36);
this.label6.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(78, 17);
this.label6.TabIndex = 9;
this.label6.Text = "电气子项目";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(52, 362);
this.label7.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(78, 17);
this.label7.TabIndex = 9;
this.label7.Text = "零组件类型";
this.label7.Visible = false;
//
// cbxType
//
this.cbxType.FormattingEnabled = true;
this.cbxType.Location = new System.Drawing.Point(155, 357);
this.cbxType.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.cbxType.Name = "cbxType";
this.cbxType.Size = new System.Drawing.Size(281, 24);
this.cbxType.TabIndex = 8;
this.cbxType.Visible = false;
//
// btnEPlanItem
//
this.btnEPlanItem.Location = new System.Drawing.Point(545, 30);
this.btnEPlanItem.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.btnEPlanItem.Name = "btnEPlanItem";
this.btnEPlanItem.Size = new System.Drawing.Size(100, 31);
this.btnEPlanItem.TabIndex = 6;
this.btnEPlanItem.Text = "选择";
this.btnEPlanItem.UseVisualStyleBackColor = true;
this.btnEPlanItem.Visible = false;
this.btnEPlanItem.Click += new System.EventHandler(this.btnEPlanItem_Click);
//
// btnItemID
//
this.btnItemID.Location = new System.Drawing.Point(545, 84);
this.btnItemID.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.btnItemID.Name = "btnItemID";
this.btnItemID.Size = new System.Drawing.Size(100, 31);
this.btnItemID.TabIndex = 6;
this.btnItemID.Text = "指派";
this.btnItemID.UseVisualStyleBackColor = true;
this.btnItemID.Visible = false;
this.btnItemID.Click += new System.EventHandler(this.assignButton_Click);
//
// tbEPlanItem
//
this.tbEPlanItem.Enabled = false;
this.tbEPlanItem.Location = new System.Drawing.Point(143, 32);
this.tbEPlanItem.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.tbEPlanItem.Name = "tbEPlanItem";
this.tbEPlanItem.Size = new System.Drawing.Size(393, 22);
this.tbEPlanItem.TabIndex = 6;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(88, 144);
this.label4.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(36, 17);
this.label4.TabIndex = 3;
this.label4.Tag = "";
this.label4.Text = "版本";
this.label4.Visible = false;
//
// tbRevId
//
this.tbRevId.Enabled = false;
this.tbRevId.Location = new System.Drawing.Point(143, 138);
this.tbRevId.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.tbRevId.Name = "tbRevId";
this.tbRevId.Size = new System.Drawing.Size(95, 22);
this.tbRevId.TabIndex = 2;
this.tbRevId.Visible = false;
//
// tbItemId
//
this.tbItemId.Enabled = false;
this.tbItemId.Location = new System.Drawing.Point(143, 84);
this.tbItemId.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.tbItemId.Name = "tbItemId";
this.tbItemId.Size = new System.Drawing.Size(393, 22);
this.tbItemId.TabIndex = 1;
this.tbItemId.Visible = false;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(64, 87);
this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(55, 17);
this.label3.TabIndex = 0;
this.label3.Text = "Item_ID";
this.label3.Visible = false;
//
// tabPage2
//
this.tabPage2.Controls.Add(this.ComListView);
this.tabPage2.Location = new System.Drawing.Point(4, 25);
this.tabPage2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.tabPage2.Size = new System.Drawing.Size(1085, 548);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "元器件";
this.tabPage2.UseVisualStyleBackColor = true;
//
// ComListView
//
this.ComListView.FullRowSelect = true;
this.ComListView.GridLines = true;
this.ComListView.Location = new System.Drawing.Point(9, 10);
this.ComListView.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.ComListView.Name = "ComListView";
this.ComListView.Size = new System.Drawing.Size(1068, 532);
this.ComListView.TabIndex = 0;
this.ComListView.UseCompatibleStateImageBehavior = false;
this.ComListView.View = System.Windows.Forms.View.Details;
this.ComListView.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.ComListView_ColumnClick);
//
// tabPage3
//
this.tabPage3.Controls.Add(this.PageListView);
this.tabPage3.Location = new System.Drawing.Point(4, 25);
this.tabPage3.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.tabPage3.Size = new System.Drawing.Size(1085, 548);
this.tabPage3.TabIndex = 1;
this.tabPage3.Text = "页属性";
this.tabPage3.UseVisualStyleBackColor = true;
//
// PageListView
//
this.PageListView.FullRowSelect = true;
this.PageListView.GridLines = true;
this.PageListView.Location = new System.Drawing.Point(9, 10);
this.PageListView.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.PageListView.Name = "PageListView";
this.PageListView.Size = new System.Drawing.Size(1064, 525);
this.PageListView.TabIndex = 0;
this.PageListView.UseCompatibleStateImageBehavior = false;
this.PageListView.View = System.Windows.Forms.View.Details;
//
// tbProjectName
//
this.tbProjectName.Enabled = false;
this.tbProjectName.Location = new System.Drawing.Point(656, 15);
this.tbProjectName.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.tbProjectName.Name = "tbProjectName";
this.tbProjectName.ReadOnly = true;
this.tbProjectName.Size = new System.Drawing.Size(451, 22);
this.tbProjectName.TabIndex = 6;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(577, 20);
this.label5.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(64, 17);
this.label5.TabIndex = 4;
this.label5.Text = "项目名称";
//
// SaveButton
//
this.SaveButton.Location = new System.Drawing.Point(983, 646);
this.SaveButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.SaveButton.Name = "SaveButton";
this.SaveButton.Size = new System.Drawing.Size(131, 31);
this.SaveButton.TabIndex = 3;
this.SaveButton.Text = "保存";
this.SaveButton.UseVisualStyleBackColor = true;
this.SaveButton.Click += new System.EventHandler(this.SaveButton_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(311, 20);
this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label2.MaximumSize = new System.Drawing.Size(240, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(0, 17);
this.label2.TabIndex = 4;
//
// generateListButton
//
this.generateListButton.Location = new System.Drawing.Point(25, 646);
this.generateListButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.generateListButton.Name = "generateListButton";
this.generateListButton.Size = new System.Drawing.Size(116, 31);
this.generateListButton.TabIndex = 5;
this.generateListButton.Text = "生成申请清单";
this.generateListButton.UseVisualStyleBackColor = true;
this.generateListButton.Visible = false;
//
// SaveForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1129, 693);
this.Controls.Add(this.generateListButton);
this.Controls.Add(this.label2);
this.Controls.Add(this.SaveButton);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.tbProjectCode);
this.Controls.Add(this.label1);
this.Controls.Add(this.tbProjectName);
this.Controls.Add(this.label5);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.Name = "SaveForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "保存";
this.Load += new System.EventHandler(this.SaveForm_Load);
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage1.PerformLayout();
this.tabPage2.ResumeLayout(false);
this.tabPage3.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox tbProjectCode;
private System.Windows.Forms.TextBox tbProjectName;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox tbEPlanItem;
private System.Windows.Forms.Button btnEPlanItem;
private System.Windows.Forms.TextBox tbItemId;
private System.Windows.Forms.Button btnItemID;
private System.Windows.Forms.TextBox tbRevId;
private System.Windows.Forms.ComboBox cbxType;
private System.Windows.Forms.ListView ComListView;
private System.Windows.Forms.ListView PageListView;
private System.Windows.Forms.Button generateListButton;
private System.Windows.Forms.Button SaveButton;
}
}

@ -0,0 +1,765 @@
using Eplan.EplApi.Base;
using Eplan.EplApi.DataModel;
using KPlan.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using Teamcenter.Soa.Client.Model.Strong;
namespace KPlan.RefActions {
public partial class SaveForm : System.Windows.Forms.Form {
public string projectCode = "";
public Eplan.EplApi.DataModel.Project currentProject = null;
public string xmlFilePath = "";
public Dictionary<string, string> nameToPaths;
private List<string> childItem_id = new List<string>();
private List<string> childItem_num = new List<string>();
//private List<string> childItem_installpos1 = new List<string>();
//private List<string> childItem_Manufacturer = new List<string>();//制造商
private Dictionary<string, List<string>> customPropMap = new Dictionary<string, List<string>>();
private int idIdx = -1;
private int numIdx = -1;
private int installposIdx = -1;
private int devidIdx = -1;
private int errorPartNum = 0;
public SaveForm() {
InitializeComponent();
}
private void SaveForm_Load(object sender, EventArgs e) {
tbProjectCode.Text = projectCode;
tbProjectName.Text = currentProject.ProjectName;
if (0 == TCTool.checkItem(projectCode)) {
SaveButton.Enabled = false;
//btnEPlanItem.Show();
}
else {
tbEPlanItem.Text = projectCode;
}
int titleNum = TCTool.BomTitleName.Count;
this.ComListView.Columns.Add("检查结果", 80, HorizontalAlignment.Left); //一步添加表头信息
for (int i = 0; i < TCTool.BomTitleName.Count; i++) {
this.ComListView.Columns.Add(TCTool.BomTitleName[i].ToString(), 120, HorizontalAlignment.Left); //一步添加表头信息
if (TCTool.BomPropertyKey[i].ToString().Equals("P_ARTICLE_ERPNR", StringComparison.OrdinalIgnoreCase)) {
idIdx = i + 1;
}
else if (TCTool.BomPropertyKey[i].ToString().Equals("P_ARTICLEREF_COUNT", StringComparison.OrdinalIgnoreCase)) {
numIdx = i + 1;
}
else if (TCTool.BomPropertyKey[i].ToString().Equals("P_DESIGNATION_LOCATION_DESCR", StringComparison.OrdinalIgnoreCase)) {
installposIdx = i + 1;
}
else if (TCTool.BomPropertyKey[i].ToString().Equals("P_FUNC_DEVICETAG_FULLNAME", StringComparison.OrdinalIgnoreCase)) {
devidIdx = i + 1;
}
}
this.PageListView.Columns.Add("名称", 580, HorizontalAlignment.Left);
Dictionary<string, string>.KeyCollection kc = nameToPaths.Keys;
foreach (string name in kc) {
ListViewItem lvi = new ListViewItem();
lvi.Text = nameToPaths[name];
this.PageListView.Items.Add(lvi);
}
Progress progress = new Progress("EnhancedProgress");
progress.SetActionText("正在加载表单...");
progress.SetTitle("加载表单");
progress.BeginPart(100.0, "进度");
progress.ShowImmediately();
progress.SetAllowCancel(true);
ReadXMLFile();
if (errorPartNum > 0) {
generateListButton.Enabled = true;
}
else {
generateListButton.Enabled = false;
}
progress.EndPart(true);
}
/**
*
* partslist XML
*
*
*
* partslist XML
*
*/
public void ReadXMLFile() {
errorPartNum = 0;
childItem_id.Clear();
childItem_num.Clear();
customPropMap.Clear();
//childItem_installpos1.Clear();
//childItem_Manufacturer.Clear();
//MessageBox.Show("xmlFilePath------" + xmlFilePath);
XmlTextReader xtr = new XmlTextReader(xmlFilePath);
string name_f = "@@";
bool is_dos = false;
bool is_device = false;
string device_name = "";
int record_code_idx = -1;
int record_num_idx = -1;
int PropertyNoum = TCTool.BomPropertyKey.Count;
for (int step = 0; step < PropertyNoum; step++) {
// MessageBox.Show("ReadXMLFile------1" );
if (TCTool.BomPropertyKey[step].Equals("P_ARTICLE_ERPNR")) {
record_code_idx = step;
}
if (TCTool.BomPropertyKey[step].Equals("P_ARTICLEREF_COUNT")) {
record_num_idx = step;
}
}
try {
// MessageBox.Show("ReadXMLFile------2");
this.ComListView.BeginUpdate(); //数据更新UI暂时挂起直到EndUpdate绘制控件可以有效避免闪烁并大大提高加载速度
while (xtr.Read()) {
bool is_other = true;
if (is_device) {
if (xtr.NodeType == XmlNodeType.EndElement) {
is_device = false;
}
else {
continue;
}
}
if (xtr.NodeType != XmlNodeType.Element) {
continue;
}
if (!xtr.HasAttributes) {
continue;
}
string element_name = xtr.Name;
bool is_P_ARTICLE_DISCONTINUED = false;
bool is_wire = false;
string wire_length = "";
string record_code = "";
string record_num = "";
string record_type = "";
Dictionary<string, string> customValMap = new Dictionary<string, string>();
string record_installpos1 = "";
//string record_manufacturer = "";
string record_devid = "";
string[] propertyValue = new string[PropertyNoum];
//MessageBox.Show("ReadXMLFile------3");
while (xtr.MoveToNextAttribute()) {
//MessageBox.Show("ReadXMLFile------xtr.Name" + xtr.Name);
//MessageBox.Show("ReadXMLFile------ xtr.Value" + xtr.Value);
if (xtr.Name == "P_ARTICLEREF_IDENTNAME")
//if (xtr.Value == "P_ARTICLEREF_IDENTNAME")
{
device_name = xtr.Value;
}
//if (xtr.Name == "P_ARTICLEREF_IDENTNAME" && xtr.Value.Equals("=+"))
//{
// xtr.MoveToElement();
// is_device = true;
// break;
//}
if (xtr.Name == "P_ARTICLE_DISCONTINUED") //停用
//if (xtr.Value == "P_ARTICLE_DISCONTINUED") //停用
{
if (!xtr.Value.Equals("0")) {
is_P_ARTICLE_DISCONTINUED = true;
}
}
if (xtr.Name == "P_ARTICLE_PARTIAL_LENGTH_VALUE") //此处标识出连接线的部件
// if (xtr.Value == "P_ARTICLE_PARTIAL_LENGTH_VALUE") //此处标识出连接线的部件
{
if (!string.IsNullOrEmpty(xtr.Value) && !xtr.Value.Equals("0")) {
is_wire = true;
wire_length = xtr.Value;
}
}
else if (xtr.Name == "P_ARTICLE_ERPNR")
// else if (xtr.Value == "P_ARTICLE_ERPNR")
{
is_other = false;
record_code = xtr.Value;
}
else if (xtr.Name == "P_ARTICLEREF_COUNT")
//else if (xtr.Value == "P_ARTICLEREF_COUNT")
{
record_num = xtr.Value;
}
else if (xtr.Name == "P_ARTICLE_TYPENR")
// else if (xtr.Value == "P_ARTICLE_TYPENR")
{
record_type = xtr.Value;
}
else if (xtr.Name == "P_DESIGNATION_LOCATION_DESCR")
// else if (xtr.Value == "P_DESIGNATION_LOCATION_DESCR")
{
//MessageBox.Show(xtr.Value);
record_installpos1 = TCTool.getCNString(xtr.Value);
// MessageBox.Show(record_installpos);
}
/*else if(xtr.Name == "P_ARTICLE_MANUFACTURER") {
record_manufacturer = xtr.Value;
}*/
else if (xtr.Name == "P_FUNC_DEVICETAG_FULLNAME")
// else if (xtr.Value == "P_FUNC_DEVICETAG_FULLNAME")
{
record_devid = TCTool.getCNString(xtr.Value);
}
else {
string eName = xtr.Name;
if (TCTool.customBomPropConfig.ContainsKey(eName)) {
//KUtil.Log("读取xml属性"+eName +" = "+xtr.Value);
string tName = TCTool.customBomPropConfig[eName];
if (customValMap.ContainsKey(tName)) {
customValMap.Remove(tName);
}
customValMap.Add(tName, TCTool.getCNString(xtr.Value));
}
}
for (int step = 0; step < PropertyNoum; step++) {
if (xtr.Name == TCTool.BomPropertyKey[step].ToString()) {
//if (xtr.Name.Equals("P_ARTICLE_ERPNR") && record_code_idx == -1)
//{
// record_code_idx = step;
//}
is_other = false;
if (xtr.Value.Contains("@") && xtr.Value.Contains(";")) {
string[] arrStr = xtr.Value.Split(';');
int arrLen = arrStr.Length;
for (int cnt = 0; cnt < arrLen; cnt++) {
if (arrStr[cnt].StartsWith("zh_CN") || arrStr[cnt].StartsWith("??")) {
propertyValue[step] = arrStr[cnt].Split('@')[1];
break;
}
}
}
else {
propertyValue[step] = xtr.Value;
}
break;
}
}
}
if (element_name == "device") //此处过滤掉一些组合设备的部件
{
if (device_name.IndexOf(name_f) != -1) {
is_dos = true;
}
else {
is_dos = false;
}
}
else if (element_name == "part") {
if (is_dos) {
continue;
}
if (TCTool.lineCount != "TRUE") {
if (is_wire) {
continue;
}
}
else {
if (is_wire) {
if (!string.IsNullOrEmpty(wire_length) && !string.IsNullOrEmpty(record_num)) {
double dwire_length = Convert.ToDouble(wire_length);
double drecord_num = Convert.ToDouble(record_num);
drecord_num = dwire_length * drecord_num;
record_num = drecord_num.ToString();
}
}
}
if (record_num.Equals("0")) {
continue;
}
if (is_other) {
name_f = device_name;
}
bool findsame = false;
for (int i = 0; i < ComListView.Items.Count; i++) {
string id = ComListView.Items[i].SubItems[idIdx].Text.ToString();
string installpos = ComListView.Items[i].SubItems[installposIdx].Text.ToString();
if (!id.Equals("") && !installpos.Equals("") && id.Equals(record_code) && installpos.Equals(record_installpos1)) {
string num = ComListView.Items[i].SubItems[numIdx].Text.ToString();
num = (double.Parse(num) + double.Parse(record_num)).ToString();
ComListView.Items[i].SubItems[numIdx].Text = num;
childItem_num[i] = num;
string devid = ComListView.Items[i].SubItems[devidIdx].Text.ToString();
devid += ";" + record_devid;
ComListView.Items[i].SubItems[devidIdx].Text = devid;
findsame = true;
}
}
if (findsame) {
continue;
}
ListViewItem lvi = new ListViewItem();
lvi.UseItemStyleForSubItems = false;
if (record_code.Equals("")) {
for (int i = 0; i < TCTool.P_ARTICLE_TYPENRs.Count; i++) {
if (record_type.Equals(TCTool.P_ARTICLE_TYPENRs[i].ToString(), StringComparison.OrdinalIgnoreCase)) {
record_code = TCTool.P_ARTICLE_ERPNRs[i].ToString();
propertyValue[record_code_idx] = record_code;
break;
}
}
}
if (is_P_ARTICLE_DISCONTINUED) {
lvi.ForeColor = Color.Red;
SaveButton.Enabled = false;
errorPartNum++;
lvi.Text = "停产部件";
}
else {
if (record_code.Equals("")) {
lvi.ForeColor = Color.Red;
SaveButton.Enabled = false;
errorPartNum++;
lvi.Text = "TC不存在";
}
else {
int findItem = TCTool.checkItem(record_code);
if (findItem == 0) {
lvi.ForeColor = Color.Red;
SaveButton.Enabled = false;
errorPartNum++;
lvi.Text = "TC不存在";
}
else {
lvi.Text = "TC存在";
}
}
}
record_code = record_code.Replace("\r", "");
record_code = record_code.Replace("\n", "");
childItem_id.Add(record_code);
record_num = record_num.Replace("\r", "");
record_num = record_num.Replace("\n", "");
childItem_num.Add(record_num);
//添加未获取值
foreach (string key in TCTool.customBomPropConfig.Keys) {
string tName = TCTool.customBomPropConfig[key];
if (!customValMap.ContainsKey(tName)) {
//KUtil.Log("补充xml属性" + key);
customValMap.Add(tName, "");
}
}
foreach (string key in customValMap.Keys) {
string val = customValMap[key];
val = val.Replace("\r", "").Replace("\n", "");
//KUtil.Log("添加属性映射:"+key+" = "+val);
if (customPropMap.ContainsKey(key)) {
customPropMap[key].Add(val);
}
else {
List<string> l = new List<string>();
l.Add(val);
customPropMap.Add(key, l);
}
}
/*record_installpos1 = record_installpos1.Replace("\r", "");
record_installpos1 = record_installpos1.Replace("\n", "");
childItem_installpos1.Add(record_installpos1);
record_manufacturer = record_manufacturer.Replace("\r", "");
record_manufacturer = record_manufacturer.Replace("\n", "");
childItem_Manufacturer.Add(record_manufacturer);*/
for (int step = 0; step < PropertyNoum; step++) {
if (record_num_idx == step) {
lvi.SubItems.Add(record_num).ForeColor = Color.Black;
}
else {
if (propertyValue[step] == null) {
lvi.SubItems.Add("");
}
else {
lvi.SubItems.Add(propertyValue[step]).ForeColor = Color.Black;
}
}
}
this.ComListView.Items.Add(lvi);
}
}
xtr.Close();
this.ComListView.EndUpdate(); //结束数据处理UI界面一次性绘制。
}
catch (XmlException ex) {
MessageBox.Show(ex.Message);
}
}
private void assignButton_Click(object sender, EventArgs e) {
//if (cbxType.SelectedItem == null || cbxType.SelectedItem.ToString().Equals(""))
//{
// MessageBox.Show("请选择零组件类型再指派Item_ID和版本");
// return;
//}
//string outputstr = "";
//string[] arrStr = new string[3];
//arrStr[0] = "project";
//arrStr[1] = cbxType.SelectedItem.ToString();
//arrStr[2] = "1";
//TCTool.invokeTC("assignNewIdAndRev", null, arrStr, out outputstr);
//string[] itemidAndRev = outputstr.Split('$');
//tbItemId.Text = itemidAndRev[0];
//tbRevId.Text = itemidAndRev[1];
////if (projectIdTextBox.Text.Trim().Equals(""))
////{
//// projectIdTextBox.Text = itemidAndRev[2];
////}
//TCTool.ProjectString = itemidAndRev[2];
//btnItemID.Enabled = false;
//if (errorPartNum == 0)
//{
// SaveButton.Enabled = true;
//}
}
private void btnEPlanItem_Click(object sender, EventArgs e) {
//SelectElecPartsForm form = new SelectElecPartsForm();
//if (DialogResult.OK == form.ShowDialog())
//{
// tbProjectCode.Text = form.selectItem_id;
// tbRevId.Text = form.selectItem_revision_id;
//}
}
private void SaveButton_Click(object sender, EventArgs e) {
// MessageBox.Show("保存前操作----------");
ItemRevision projItemRevision = TCUtil.Query_LatestRev(projectCode);
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(projectCode);
projectProperties.PROJ_CUSTOM_SUPPLEMENTARYFIELD99.Set(ver);
/////////////////////////////////////////////////////////
List<string> saveFileItemData = new List<string>();
foreach (ListViewItem lvi in PageListView.Items) {
saveFileItemData.Add(lvi.Text);
}
SaveProjectBean saveProjBean = new SaveProjectBean() { projectCode = projectCode,childItem_id=childItem_id,childItem_num = childItem_num,custPropMap=customPropMap,saveFileItemData=saveFileItemData };
/////////////////////////////////////////////////////////
/*string fmsHome = Environment.GetEnvironmentVariable("FMS_HOME");
string dataFile = fmsHome + "\\EPlan\\" + "data";
try {
FileStream aFile = new FileStream(@dataFile, FileMode.Create);
StreamWriter sw = new StreamWriter(aFile);
sw.WriteLine(projectCode);
sw.WriteLine(string.Join("@@", childItem_id.ToArray()));
sw.WriteLine(string.Join("@@", childItem_num.ToArray()));
//MessageBox.Show("childItem_installpos----------" + childItem_installpos);
sw.WriteLine(string.Join("@@", childItem_installpos1.ToArray()));
sw.WriteLine(string.Join("@@", childItem_Manufacturer.ToArray()));
sw.WriteLine(string.Join("@@", saveFileItemData.ToArray()));
sw.Close();
}
catch (IOException ex) {
MessageBox.Show("写入数据文件失败:\r\n" + ex.ToString(), "提示");
return;
}
short nRes = SaveProject(dataFile);*/
short nRes = SaveProject(saveProjBean);
// string para = String.Format("\"{0}||{1}||{2}||{3}\"", TCTool.LoginUser, TCTool.PWD, "saveProject", dataFile);
//short nRes = TCTool.execTools(para);
if (nRes == 0) {
MessageBox.Show("保存项目完毕!", "提示");
this.DialogResult = DialogResult.OK;
}
}
public class SaveProjectBean {
public string projectCode { get; set; }
public List<string> childItem_id { get; set; }
public List<string> childItem_num { get; set; }
public Dictionary<string,List<string>> custPropMap { get; set; }
public List<string> saveFileItemData { get; set; }
}
private void ComListView_ColumnClick(object sender, ColumnClickEventArgs e) {
ComListView.ListViewItemSorter = new ListViewItemComparer(e.Column);
ComListView.Sort();
}
private short SaveProject(string filename) {
{
//Console.WriteLine("filename------------------" + filename);
string projectCode = "";
string[] childItem_id = null;
string[] childItem_num = null;
string[] childItem_installpos1 = null;
string[] childItem_manufacturer = null;
string[] saveFileItemData = null;
try {
FileStream aFile = new FileStream(@filename, FileMode.Open);
StreamReader sr = new StreamReader(aFile);
projectCode = sr.ReadLine();
//Console.WriteLine("projectCode------------------" + projectCode);
string childItem_idLine = sr.ReadLine();
// Console.WriteLine("childItem_idLine------------------" + childItem_idLine);
if (!String.IsNullOrEmpty(childItem_idLine)) {
// Console.WriteLine("1------------------" + childItem_idLine);
childItem_id = Regex.Split(childItem_idLine, "@@", RegexOptions.IgnoreCase);
}
string childItem_numLine = sr.ReadLine();
if (!String.IsNullOrEmpty(childItem_numLine)) {
// Console.WriteLine("2------------------" + childItem_numLine);
childItem_num = Regex.Split(childItem_numLine, "@@", RegexOptions.IgnoreCase);
}
string childItem_installposLine = sr.ReadLine();
if (!String.IsNullOrEmpty(childItem_installposLine)) {
// Console.WriteLine("3------------------" + childItem_installposLine);
childItem_installpos1 = Regex.Split(childItem_installposLine, "@@", RegexOptions.IgnoreCase);
}
string childItem_manufacturerLine = sr.ReadLine();
if (!String.IsNullOrEmpty(childItem_manufacturerLine)) {
// Console.WriteLine("3------------------" + childItem_installposLine);
childItem_manufacturer = Regex.Split(childItem_manufacturerLine, "@@", RegexOptions.IgnoreCase);
}
// Console.WriteLine("4------------------");
saveFileItemData = Regex.Split(sr.ReadLine(), "@@", RegexOptions.IgnoreCase);
//Console.WriteLine("5------------------");
sr.Close();
}
catch (IOException ex) {
MessageBox.Show("读取数据文件失败:\r\n" + ex.ToString(), "提示");
return 2001;
}
//Console.WriteLine("6------------------");
//Console.WriteLine("9------------------" + projectCode);
Teamcenter.Soa.Client.Model.Strong.ItemRevision projItemRevision = TCUtil.Query_LatestRev(projectCode);
////////////////////////////////////////////////////////////
//Console.WriteLine("10------------------");
short nRes = 0;
if (childItem_id != null) {
// Console.WriteLine("11------------------");
//Console.WriteLine("childItem_id------------------" + childItem_id.Length);
//Console.WriteLine("childItem_num------------------" + childItem_num.Length);
//Console.WriteLine("childItem_installpos------------------" + childItem_installpos.Length);
/* if (childItem_id.ToList()==null)
{
Console.WriteLine("childItem_id.ToList()==null");
}
if (childItem_num.ToList() == null)
{
Console.WriteLine("childItem_num.ToList()");
}*/
/* if (childItem_installpos.ToList() == null)
{
Console.WriteLine("childItem_installpos.ToList()==null");
}*/
// nRes = TCTool.CreateOrUpdateBom(projItemRevision, childItem_id.ToList(), childItem_num.ToList(), childItem_installpos.ToList());
// nRes = TCTool.CreateOrUpdateBom(projItemRevision, childItem_id.ToList(), childItem_num.ToList(), childItem_installpos1,childItem_manufacturer);
nRes = TCTool.CreateOrUpdateBom(projItemRevision, childItem_id.ToList(), childItem_num.ToList(), customPropMap);
// Console.WriteLine("12------------------");
if (0 > nRes) {
//Console.WriteLine("13------------------");
MessageBox.Show("保存BOM失败!", "提示");
return 2011;
}
else if (0 < nRes) {
return 2012;
}
// kk 同步项目属性
try {
KUtil.Sync_ProjProperty_to_TC(projItemRevision, currentProject);
}
catch (Exception ex) {
KUtil.LogErr(ex);
MessageBox.Show("同步项目属性出错:"+ex.Message);
return 2013;
}
}
////////////////////////////////////////////////////////////
// Console.WriteLine("14------------------");
nRes = createProjctDataset(projectCode, projItemRevision, saveFileItemData.ToList());
if (0 > nRes) {
MessageBox.Show("保存文件失败!", "提示");
return 2021;
}
else if (0 < nRes) {
return 2022;
}
}
return 0;
}
private short SaveProject(SaveProjectBean bean) {
{
//Console.WriteLine("6------------------");
//Console.WriteLine("9------------------" + projectCode);
Teamcenter.Soa.Client.Model.Strong.ItemRevision projItemRevision = TCUtil.Query_LatestRev(projectCode);
////////////////////////////////////////////////////////////
//Console.WriteLine("10------------------");
short nRes = 0;
if (childItem_id != null) {
// Console.WriteLine("11------------------");
//Console.WriteLine("childItem_id------------------" + childItem_id.Length);
//Console.WriteLine("childItem_num------------------" + childItem_num.Length);
//Console.WriteLine("childItem_installpos------------------" + childItem_installpos.Length);
/* if (childItem_id.ToList()==null)
{
Console.WriteLine("childItem_id.ToList()==null");
}
if (childItem_num.ToList() == null)
{
Console.WriteLine("childItem_num.ToList()");
}*/
/* if (childItem_installpos.ToList() == null)
{
Console.WriteLine("childItem_installpos.ToList()==null");
}*/
// nRes = TCTool.CreateOrUpdateBom(projItemRevision, childItem_id.ToList(), childItem_num.ToList(), childItem_installpos.ToList());
nRes = TCTool.CreateOrUpdateBom(projItemRevision, bean.childItem_id, bean.childItem_num, bean.custPropMap);
// Console.WriteLine("12------------------");
if (0 > nRes) {
//Console.WriteLine("13------------------");
MessageBox.Show("保存BOM失败!", "提示");
return 2011;
}
else if (0 < nRes) {
return 2012;
}
// kk 同步项目属性
try {
KUtil.Sync_ProjProperty_to_TC(projItemRevision, currentProject);
}
catch (Exception ex) {
KUtil.LogErr(ex);
MessageBox.Show("同步项目属性出错:" + ex.Message);
return 2013;
}
}
////////////////////////////////////////////////////////////
// Console.WriteLine("14------------------");
nRes = createProjctDataset(projectCode, projItemRevision, bean.saveFileItemData);
if (0 > nRes) {
MessageBox.Show("保存文件失败!", "提示");
return 2021;
}
else if (0 < nRes) {
return 2022;
}
}
return 0;
}
static private short createProjctDataset(string projectCode, Teamcenter.Soa.Client.Model.Strong.ItemRevision projItemRevision, List<String> saveFileItemData) {
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);
// Console.WriteLine("开始获取cad数据集--------------");
Teamcenter.Soa.Client.Model.Strong.Dataset dataset_zw1 = TCTool.getDataset(projItemRevision, ZW1DSType, projectCode + TCTool.ZW1Name);
if (dataset_zw1 != null) {
// Console.WriteLine("检查cad是否签出--------------");
if (0 != TCTool.checkDatasetCheckout(dataset_zw1)) {
return 1;
}
//if (0 != TCTool.deleteDataset(projItemRevision, dataset_zw1))
//{
// return 2;
//}
}
else {
dataset_zw1 = TCTool.createDataset(projItemRevision, ZW1DSType, projectCode + TCTool.ZW1Name);
if (dataset_zw1 == null) {
return 3;
}
}
// Console.WriteLine("开始获取pdf数据集--------------");
//Console.WriteLine("projectCode + TCTool.PDFName--------------" + projectCode + TCTool.PDFName);
Teamcenter.Soa.Client.Model.Strong.Dataset dataset_pdf = TCTool.getDataset(projItemRevision, PDFDSType, projectCode + TCTool.PDFName);
if (dataset_pdf != null) {
// Console.WriteLine("pdf数据集不为空--------------");
if (0 != TCTool.checkDatasetCheckout(dataset_pdf)) {
// Console.WriteLine("检查pdf数据集签出故障--------------");
return 11;
}
//if (0 != TCTool.deleteDataset(projItemRevision, dataset_pdf))
//{
// return 12;
//}
}
else {
//Console.WriteLine("pdf数据集为空开始创建pdf数据集--------------");
dataset_pdf = TCTool.createDataset(projItemRevision, PDFDSType, projectCode + TCTool.PDFName);
if (dataset_pdf == null) {
return 13;
}
}
foreach (string filename in saveFileItemData) {
//Console.WriteLine("filename--------------" + filename);
FileInfo fi = new FileInfo(filename);
string extension = System.IO.Path.GetExtension(filename);
if (extension.Equals(".zw1", StringComparison.OrdinalIgnoreCase)) {
//Console.WriteLine("添加.zw1--------------");
// MessageBox.Show("添加.zw1-------------", "提示");
//TCTool.addNameRef(dataset_zw1, TCTool.ZW1NameRef, filename);
TCUtil.UploadFile(dataset_zw1, filename, ZW1DSRef);
}
else if (extension.Equals(".pdf", StringComparison.OrdinalIgnoreCase)) {
// Console.WriteLine("添加.pdf--------------");
//MessageBox.Show("添加.pdf-------------", "提示");
//TCTool.addNameRef(dataset_pdf, TCTool.PDFNameRef, filename);
TCUtil.UploadFile(dataset_pdf, filename, PDFDSRef);
}
}
return 0;
}
}
}

@ -0,0 +1,145 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="$this.Icon" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAABloxIAXZYwBGOgDIccAAhtLwEYPWAGHjdmBhZVSQIGAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAULj2NhmX4nwAhNO+BWuntmEvHGiSLQCmelIB0k12BuBEdgbIVVsEmHUsAECGNwAGAAAAAAAA
AAAAAAAAAAAAALLg+0p/zfvYQLP4/ziRx/A7bY70UFRc/1ZaMv93ZBH/m14C/6BKAP+QLwDqfyoAgIIs
AAwAAAAAAAAAAAAAAAAAAAAAy8/VTKi+z+6umYj/sauM/3GzxP8zmdD/G3mx/zVcbf9zTSn/pEEF/5Qw
APhyOQF6I24HAgAAAAAAAAAAAAAAALU1AWLTZCr45IUl//icAv/xvRf/0s1M/5fIlv9Er9f/EIjO/ydi
g/9iSSn/UV0F5EJmATYAAAAAAAAAAKQ2BxDEPwG672AA//qVAv/7vQb//NgK//zkB//55Qn/49os/53E
hP80p9v/CYbI/xpyYP8wZR6CAAAAAAAAAACwPAoo0UQB4vl0Bf/9rRT//tYr//7tNf/+9zD//fgi//zs
Ev/41Q7/z7Y8/2Glt/8gneX/JoKoxCFokxoAAAAAsjgDONVIAur8gBP//74+///kZP//9XH/+/pk//Lx
Rv/98zH/+90h//i6GP/CmiT/Uaat/0Ky9PwrmNmMAG3BBrI8CSjQSAfi+4Us///Kbv//6pz///mz/7K5
bP+KkTb/++xM//7bN//lxDL/oLUl/2iQMP9Tp9P/XLv06h+Y4EqpMQAOxUYNuPGFRf//yor//+y8/8fM
qv84XyX/R1oe/+XRWv//0kz/z8hI/7WsQv+TZhD8THaO9GjG//9FsvKSAAAAALtFEWTff1H4/7+R/9bB
kv9NcTX/Lmca/zJRGv+VqFP/68pg/7zMXv+srlb/klgn9jl+quJnx///ULz8oAAAAAC1QREQ03xXqNOe
eP9dcjT/QHYt/1WIQf8tVxv/YohJ/6TMb/+e2nb/h7pw/0OBnP84q/D/Z8f/7kC4/14AAAAAAAAAAIRl
MTJTaCriSHo1/36mcP93oWf/NGAi/19/Tf+Ovnb/isSA8j+XnOoxq/HkTL3/uk29/1wVo/8IAAAAAB1X
BgwuZhuQYI1Q+qC9lf+1zK3/oL2V/0h0N/xQcT3OhqVhkm+TZ0oMeb8yL7H+Ije1/w4AAAAAAAAAAAAA
AAAlYg1KS4A31I+xguiqxKHutsyu9rnPsfx1mWjyJU4RVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAKWgRDjp2Ix5EfS4uT4Q7SGOSUWJ4oWl4ZpJVii9iGzgAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAA//8AAMg/AACADwAAwA8AAMAHAACAAwAAgAMAAIABAACAAQAAgAAAAMAAAADAAQAA4AMAAMA/
AADA/wAA/v8AAA==
</value>
</data>
</root>

@ -0,0 +1,399 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using KPlan.Util;
using Teamcenter.Schemas.Soa._2006_03.Exceptions;
using Teamcenter.Services.Strong.Core;
using Teamcenter.Services.Strong.Core._2007_01.DataManagement;
using Teamcenter.Soa.Client.Model;
using Teamcenter.Soa.Client.Model.Strong;
namespace KPlan.RefActions {
class TCTool {
public static ArrayList BomTitleName = new ArrayList();
public static ArrayList BomPropertyKey = new ArrayList();
public static ArrayList P_ARTICLE_TYPENRs = new ArrayList();
public static ArrayList P_ARTICLE_ERPNRs = new ArrayList();
public static string lineCount = "";
public static string deleteXML = "TRUE";
static public string ZW1Name = "EPLAN数据包";
static public string PDFName = "PDF图纸";
public static Dictionary<string, string> customBomPropConfig = new Dictionary<string, string>();
public static void ReadConfigs() {
BomTitleName.Clear();
BomPropertyKey.Clear();
P_ARTICLE_TYPENRs.Clear();
P_ARTICLE_ERPNRs.Clear();
customBomPropConfig.Clear();
string bomConfig = KUtil.GetConfigValue(KConfigure.CHECK_SECTION, KConfigure.SAVE_BOM_PROP);
//KUtil.Log(bomConfig);
string[] bomConfigSplit = bomConfig.Split(';');
foreach(string c in bomConfigSplit) {
string[] ss = c.Split('=');
if (ss.Length == 2) {
// KUtil.Log(ss[0]+" = "+ss[1]);
string tc = ss[0].Trim();
string eplan = ss[1].Trim();
if (!KUtil.IsEmpty(tc) && !KUtil.IsEmpty(eplan)) {
if (customBomPropConfig.ContainsKey(eplan)) {
KUtil.Log("重复配置:"+tc+"="+eplan);
}
else {
customBomPropConfig.Add(eplan, tc);
}
}
}
}
string config = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_BOM_TITILE);
string[] split = config.Split(';');
foreach (string c in split) {
string[] ss = c.Split('=');
if (ss.Length == 2) {
BomTitleName.Add(ss[0].Trim());
BomPropertyKey.Add(ss[1].Trim());
}
}
string erpcode = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_ERPCODE);
string[] erpcodeSplit = erpcode.Split(';');
foreach (string c in erpcodeSplit) {
string[] ss = c.Split('=');
if (ss.Length == 2) {
if (ss[0].Trim().StartsWith("P_ARTICLE_TYPENR")) {
P_ARTICLE_TYPENRs.Add(ss[1].Trim());
}
else {
P_ARTICLE_ERPNRs.Add(ss[1].Trim());
}
}
}
lineCount = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_LINECOUNT);
deleteXML = KUtil.GetConfigValue(KConfigure.REF_SECTION, KConfigure.REF_DELETEXML);
}
public static string getCNString(string descString) {
string target_descr = "";
if (descString.Contains("@") && descString.Contains(";")) {
string[] arrStr = descString.Split(';');
int arrLen = arrStr.Length;
for (int cnt = 0; cnt < arrLen; cnt++) {
if (arrStr[cnt].StartsWith("zh_CN") || arrStr[cnt].StartsWith("??")) {
target_descr = arrStr[cnt].Split('@')[1];
break;
}
}
}
else {
target_descr = descString;
}
return target_descr;
}
public static short checkZipDatasetCheckout(Dataset dataset) {
try {
ModelObject[] objects2 = { dataset };
String[] attributes2 = { "is_modifiable", "checked_out", "checked_out_user" };
//TcTool.dmService.RefreshObjects(objects2);
TCUtil.dmService.GetProperties(objects2, attributes2);
//2019.05.14下载TC数据至EPLAN 不用检查
Teamcenter.Soa.Client.Model.Strong.User checkUserInfo = dataset.Checked_out_user as Teamcenter.Soa.Client.Model.Strong.User;
if (checkUserInfo != null) {
if (checkUserInfo.Uid != TCUtil.user.Uid) {
MessageBox.Show("数据集由其他用户签出,无法保存数据集!", "提示");
return 2;
}
}
}
catch (Teamcenter.Soa.Exceptions.NotLoadedException ex) {
MessageBox.Show("错误:\r\n" + ex.Message, "提示");
return 11;
}
return 0;
}
public static ItemRevision getLastItemRev(String item_id) {
GetItemFromIdInfo OneInfo = new GetItemFromIdInfo();
GetItemFromIdInfo[] Infos = new GetItemFromIdInfo[1];
GetItemFromIdPref Pref = new GetItemFromIdPref();
OneInfo.ItemId = item_id;
Infos[0] = OneInfo;
GetItemFromIdResponse InfoResp = TCUtil.dmService.GetItemFromId(Infos, 1, Pref); // 1个数是最新版本
// MessageBox.Show(item_id + "-------------" + InfoResp.Output.Length, "提示");
if (InfoResp.Output.Length > 0) {
if (InfoResp.Output[0].ItemRevOutput.Length > 0) {
ItemRevision itemRev = InfoResp.Output[0].ItemRevOutput[0].ItemRevision;
ModelObject[] modelobject = { itemRev };
//MessageBox.Show(item_id + "-------------" + itemRev.Uid, "提示");
//dmService.RefreshObjects(modelobject);
//MessageBox.Show("RefreshObjects", "提示");
String[] attributes = { "item_id", "object_name", "item_revision_id", "creation_date", "owning_user" };
TCUtil.dmService.GetProperties(modelobject, attributes);
//MessageBox.Show("item_revision_id----------" + itemRev.Item_revision_id, "提示");
//return InfoResp.Output[0].ItemRevOutput[0].ItemRevision;
return itemRev;
}
}
return null;
}
public static short CreateOrUpdateBom(ItemRevision parentItemRevision, List<string> childItem_id, List<string> childItem_num, Dictionary<string,List<string>> custPropMap) {
//Console.WriteLine("CreateOrUpdateBom------------------"+1);
int childCount = childItem_id.Count;
//Console.WriteLine("CreateOrUpdateBom------------------"+2);
ReservationService res = ReservationService.getService(Teamcenter.ClientX.Session.getConnection());
//Console.WriteLine("CreateOrUpdateBom------------------"+3);
Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo[] children_infos = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelativeStructureChildInfo[childCount];
//Console.WriteLine("CreateOrUpdateBom------------------"+4);
for (int i = 0; i < childCount; i++) {
// Console.WriteLine("CreateOrUpdateBom------------------"+5);
// Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.AttributesInfo[] attr_infos = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.AttributesInfo[2];
Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.AttributesInfo[] attr_infos = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.AttributesInfo[1+custPropMap.Count];
//Console.WriteLine("CreateOrUpdateBom------------------"+6);
attr_infos[0] = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.AttributesInfo();
attr_infos[0].Name = "bl_quantity";
attr_infos[0].Value = childItem_num[i];
//Console.WriteLine("CreateOrUpdateBom------------------"+7);
int index = 1;
foreach(string key in custPropMap.Keys) {
//KUtil.Log(key+":"+custPropMap[key].Count);
string val = custPropMap[key][i];
//KUtil.Log((i+1)+". 添加BOM同步信息" + key+" = "+val);
attr_infos[index] = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.AttributesInfo();
attr_infos[index].Name = key;
attr_infos[index].Value =val;
index++;
}
/*attr_infos[1] = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.AttributesInfo();
//attr_infos[1].Name = "YSR8_InstallP_bom";//安川项目
attr_infos[1].Name = "SF6_InstallP_bom";//毛思达
// attr_infos[1].Name = "SF2_InstallP_bom";//仇俊永
attr_infos[1].Value = childItem_installpos[i];
attr_infos[2] = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.AttributesInfo();
attr_infos[2].Name = "SF6_Manufacturer";//毛思达
attr_infos[2].Value = childItem_manufacturer[i];*/
//Console.WriteLine("CreateOrUpdateBom------------------"+8);
Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelOccInfo occ_info = new Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.RelOccInfo();
occ_info.AttrsToSet = attr_infos;
//Console.WriteLine("CreateOrUpdateBom------------------"+9);
ItemRevision itemrev = getLastItemRev(childItem_id[i]);
//Console.WriteLine("CreateOrUpdateBom------------------"+10);
if (itemrev == null) {
MessageBox.Show("获取版本对象失败!\r\n" + childItem_id[i], "提示");
return 1;
}
//Console.WriteLine("CreateOrUpdateBom------------------"+11);
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;
}
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 = parentItemRevision;
struct_info.Precise = false;
struct_infos[0] = struct_info;
ModelObject[] objpirs = { parentItemRevision };
String[] attris = { "structure_revisions" };
//dmService.RefreshObjects(objpirs);
ServiceData s_data = TCUtil.dmService.GetProperties(objpirs, attris);
//Console.WriteLine("CreateOrUpdateBom------------------"+12);
Teamcenter.Soa.Client.Model.Strong.PSBOMViewRevision ps_rev = null;
try {
for (int j = 0; j < parentItemRevision.Structure_revisions.Length; j++) {
ps_rev = parentItemRevision.Structure_revisions[j];
ModelObject[] objs2 = { ps_rev };
String[] attris2 = { "is_modifiable", "object_string", "checked_out" };
//dmService.RefreshObjects(objs2);
TCUtil.dmService.GetProperties(objs2, attris2);
if (!ps_rev.Is_modifiable) {
MessageBox.Show("当前用户无权修改BOM", "提示");
return 11;
}
if (ps_rev.Checked_out == "Y") {
MessageBox.Show("BOM已经签出请确认签入后再执行本操作", "提示");
return 12;
}
string bvr_name = ps_rev.Object_string;
// Console.WriteLine("bvr_name------------------" + bvr_name);
ModelObject[] objbvrs = new ModelObject[1];
objbvrs[0] = ps_rev;
s_data = res.Checkout(objbvrs, "", "");
if (s_data.sizeOfPartialErrors() > 0) {
MessageBox.Show("签出BOM失败请重新执行操作", "提示");
return 13;
}
}
}
catch (ServiceException ex) {
MessageBox.Show(ex.Message);
return 14;
}
Console.WriteLine("CreateOrUpdateBom------------------" + 13);
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();
try {
Teamcenter.Services.Strong.Cad._2007_01.StructureManagement.CreateOrUpdateRelativeStructureResponse cursResp =
ss_service.CreateOrUpdateRelativeStructure(struct_infos, "view", true, struct_pref);
// ss_service.DeleteRelativeStructure
if (cursResp.Output.Count == 0) {
// MessageBox.Show("Bom删除成功\n");
//}else{
MessageBox.Show("Bom创建失败", "提示");
}
}
catch (System.Exception ex) {
MessageBox.Show(ex.Message);
return 21;
}
finally {
if (ps_rev != null) {
ModelObject[] checkIn_vec = new ModelObject[1];
checkIn_vec[0] = ps_rev;
try {
res.Checkin(checkIn_vec);
}
catch (ServiceException ex) {
MessageBox.Show(ex.Message);
}
}
}
return 0;
}
public static Dataset getDataset(ItemRevision itemRevision, string dsType, string dsName) {
GetItemFromIdPref pref = new GetItemFromIdPref();
Teamcenter.Services.Strong.Core._2007_06.DataManagement.ExpandGRMRelationsPref myPref = new Teamcenter.Services.Strong.Core._2007_06.DataManagement.ExpandGRMRelationsPref();
Teamcenter.Services.Strong.Core._2007_06.DataManagement.RelationAndTypesFilter2 myFilter = new Teamcenter.Services.Strong.Core._2007_06.DataManagement.RelationAndTypesFilter2();
myFilter.RelationName = "IMAN_specification";
string[] typeVec = new string[1];
typeVec[0] = dsType;
myFilter.ObjectTypeNames = typeVec;
myPref.ExpItemRev = false;
Teamcenter.Services.Strong.Core._2007_06.DataManagement.RelationAndTypesFilter2[] myFilterVec = { myFilter };
myPref.Info = myFilterVec;
ModelObject[] primaryObjects = { itemRevision };
Teamcenter.Services.Strong.Core._2007_06.DataManagement.ExpandGRMRelationsResponse myResp = TCUtil.dmService.ExpandGRMRelationsForPrimary(primaryObjects, myPref);
for (int k = 0; k < myResp.Output.Length; k++) {
Teamcenter.Services.Strong.Core._2007_06.DataManagement.ExpandGRMRelationsOutput grmOutput = myResp.Output[k];
for (int l = 0; l < grmOutput.OtherSideObjData.Length; l++) {
Teamcenter.Services.Strong.Core._2007_06.DataManagement.ExpandGRMRelationsData otherSideData = grmOutput.OtherSideObjData[l];
if (otherSideData.OtherSideObjects.Length > 0) {
for (int m = 0; m < otherSideData.OtherSideObjects.Length; m++) {
//Teamcenter.Soa.Client.Model.ServiceData sData;
Dataset dataset = otherSideData.OtherSideObjects[m] as Dataset;
string ds_name = dataset.Object_string;
if (ds_name == dsName) {
return dataset;
}
}
}
}
}
return null;
}
public static short checkDatasetCheckout(Dataset dataset) {
try {
ModelObject[] objects2 = { dataset };
String[] attributes2 = { "is_modifiable", "checked_out", "checked_out_user" };
//TcTool.dmService.RefreshObjects(objects2);
TCUtil.dmService.GetProperties(objects2, attributes2);
if (!dataset.Is_modifiable) {
MessageBox.Show("数据集为只读格式,无法保存数据集!", "提示");
return 1;
}
Teamcenter.Soa.Client.Model.Strong.User checkUserInfo = dataset.Checked_out_user as Teamcenter.Soa.Client.Model.Strong.User;
if (checkUserInfo != null) {
if (checkUserInfo.Uid != TCUtil.user.Uid) {
MessageBox.Show("数据集由其他用户签出,无法保存数据集!", "提示");
return 2;
}
}
}
catch (Teamcenter.Soa.Exceptions.NotLoadedException ex) {
MessageBox.Show("错误:\r\n" + ex.Message, "提示");
return 11;
}
return 0;
}
public static Dataset createDataset(ItemRevision itemRevision, string type, string name) {
// MessageBox.Show("数组越界--------------1", "提示");
Teamcenter.Services.Strong.Core._2008_06.DataManagement.DatasetProperties2[] data_tts = new Teamcenter.Services.Strong.Core._2008_06.DataManagement.DatasetProperties2[1];
// MessageBox.Show("数组越界--------------2", "提示");
Teamcenter.Services.Strong.Core._2008_06.DataManagement.DatasetProperties2 one_data_tt = new Teamcenter.Services.Strong.Core._2008_06.DataManagement.DatasetProperties2();
//MessageBox.Show("数组越界--------------3", "提示");
one_data_tt.ClientId = "esappCreateDatasetClientID";
//MessageBox.Show("数组越界--------------4", "提示");
one_data_tt.Type = type;
one_data_tt.Name = name;
one_data_tt.Description = name;
one_data_tt.Container = null;
// MessageBox.Show("数组越界--------------5", "提示");
data_tts[0] = one_data_tt;
//MessageBox.Show("数组越界--------------6", "提示");
Teamcenter.Services.Strong.Core._2006_03.DataManagement.CreateDatasetsResponse dsResp = TCUtil.dmService.CreateDatasets2(data_tts);
//MessageBox.Show("数组越界--------------7", "提示");
TCUtil.ThrowServiceDataError(dsResp.ServiceData);
Dataset createdataset = dsResp.Output[0].Dataset;
//MessageBox.Show("数组越界--------------8", "提示");
if (createdataset == null) {
MessageBox.Show("创建数据集失败!", "提示");
return null;
}
//MessageBox.Show("数组越界--------------9", "提示");
string clientid = dsResp.Output[0].ClientId;
//MessageBox.Show("数组越界--------------10", "提示");
Teamcenter.Services.Strong.Core._2006_03.DataManagement.Relationship[] rela_vec = new Teamcenter.Services.Strong.Core._2006_03.DataManagement.Relationship[1];
// MessageBox.Show("数组越界--------------11", "提示");
Teamcenter.Services.Strong.Core._2006_03.DataManagement.Relationship one_rela = new Teamcenter.Services.Strong.Core._2006_03.DataManagement.Relationship();
//MessageBox.Show("数组越界--------------12", "提示");
one_rela.ClientId = "";
one_rela.PrimaryObject = itemRevision;
one_rela.SecondaryObject = createdataset;
one_rela.RelationType = "IMAN_specification";
one_rela.UserData = null;
rela_vec[0] = one_rela;
Teamcenter.Services.Strong.Core._2006_03.DataManagement.CreateRelationsResponse reResp = TCUtil.dmService.CreateRelations(rela_vec);
TCUtil.ThrowServiceDataError(reResp.ServiceData);
if (reResp.Output.Length == 0) {
MessageBox.Show("创建数据集关系失败,可能的原因是没有所选电气子项目的权限!", "提示");
return null;
}
return createdataset;
}
public static int checkItem(string item_id) {
GetItemFromIdInfo OneInfo = new GetItemFromIdInfo();
GetItemFromIdInfo[] Infos = new GetItemFromIdInfo[1];
GetItemFromIdPref Pref = new GetItemFromIdPref();
OneInfo.ItemId = item_id;
Infos[0] = OneInfo;
GetItemFromIdResponse InfoResp = TCUtil.dmService.GetItemFromId(Infos, 1, Pref); // 1个数是最新版本
return InfoResp.Output.Length;
}
}
}

@ -0,0 +1,500 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip;
using System.Text.RegularExpressions;
using ICSharpCode.SharpZipLib.Checksum;
using System.IO.Compression;
namespace KPlan.RefActions {
public class ZipHelper {
#region 压缩
/* private static string get_uft8(string unicodeString)
{
 Encoding ec = Encoding.GetEncoding("iso-8859-1");
byte[] btArr = ec.GetBytes(unicodeString);
            string strBuffer = Encoding.Default.GetString(btArr);
return strBuffer;
}*/
/// <summary>
/// 递归压缩文件夹的内部方法
/// </summary>
/// <param name="folderToZip">要压缩的文件夹路径</param>
/// <param name="zipStream">压缩输出流</param>
/// <param name="parentFolderName">此文件夹的上级文件夹</param>
/// <returns></returns>
///
private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName, string skipFolder) {
// 出现乱码就是因为CodePage不对
bool result = true;
string[] folders, files;
ZipEntry ent = null;
FileStream fs = null;
Crc32 crc = new Crc32();
string[] skipFolders = Regex.Split(skipFolder, "@@", RegexOptions.IgnoreCase);
try {
Console.WriteLine("parentFolderName----------------" + parentFolderName);
Console.WriteLine("folderToZip----------------" + folderToZip);
// 出现乱码就是因为CodePage不对
/*
FileStream fs1 = new FileStream("D:\\ss.txt", FileMode.Open);
StreamWriter sw = new StreamWriter(fs1);
//开始写入
sw.Write(parentFolderName);
sw.Write(folderToZip);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs1.Close();*/
string[] sArray = Regex.Split(folderToZip, "Data", RegexOptions.IgnoreCase);
//ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/"));
string newFoldToZip = "";
if (sArray.Length == 1) {
newFoldToZip = "Data";
}
else {
newFoldToZip = "Data" + sArray[1];
}
string newParentFoldToZip = "";
if (parentFolderName.Length > 0) {
sArray = Regex.Split(parentFolderName, "Data", RegexOptions.IgnoreCase);
if (sArray.Length == 1) {
newParentFoldToZip = "Data\\";
}
else {
newParentFoldToZip = "Data" + sArray[1];
}
}
//Console.WriteLine("------------------1--------"+Path.GetFileName(newFoldToZip) + "/");
//Console.WriteLine("-------------------2-------"+Path.Combine(parentFolderName, Path.GetFileName(newFoldToZip) + "/"));
ent = new ZipEntry(Path.Combine(newParentFoldToZip, Path.GetFileName(newFoldToZip) + "/"));
/* Encoding gbk = Encoding.GetEncoding("gbk");
ICSharpCode.SharpZipLib.Zip.ZipConstants.DefaultCodePage = gbk.CodePage; */
zipStream.PutNextEntry(ent);
zipStream.Flush();
files = Directory.GetFiles(folderToZip);
foreach (string file in files) {
if (skipFolders.Contains<string>(Path.GetFileName(file))) {
continue;
}
fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
//ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file)));
string newParentFoldToZip2 = "";
if (parentFolderName.Length > 0) {
sArray = Regex.Split(parentFolderName, "Data", RegexOptions.IgnoreCase);
if (sArray.Length == 1) {
newParentFoldToZip2 = "Data\\";
}
else {
newParentFoldToZip2 = "Data" + sArray[1];
}
}
//Console.WriteLine("------------------3--------" + Path.GetFileName(newFoldToZip) + "/");
//Console.WriteLine("------------------4--------" + Path.Combine(newParentFoldToZip2, Path.GetFileName(newFoldToZip) + "/"));
ent = new ZipEntry(Path.Combine(newParentFoldToZip2, Path.GetFileName(newFoldToZip) + "/" + Path.GetFileName(file)));
ent.DateTime = DateTime.Now;
ent.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
ent.Crc = crc.Value;
zipStream.PutNextEntry(ent);
zipStream.Write(buffer, 0, buffer.Length);
}
}
catch {
result = false;
}
finally {
if (fs != null) {
fs.Close();
fs.Dispose();
}
if (ent != null) {
ent = null;
}
GC.Collect();
GC.Collect(1);
}
folders = Directory.GetDirectories(folderToZip);
foreach (string folder in folders) {
if (skipFolders.Contains<string>(Path.GetFileName(folder))) {
continue;
}
if (!ZipDirectory(folder, zipStream, folderToZip, skipFolder))
return false;
}
return result;
}
/// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="folderToZip">要压缩的文件夹路径</param>
/// <param name="zipedFile">压缩文件完整路径</param>
/// <param name="password">密码</param>
/// <returns>是否压缩成功</returns>
public static bool ZipDirectory(string folderToZip, string zipedFile, string password, string skipFolder) {
bool result = false;
Console.WriteLine("folderToZip-------------" + folderToZip);
if (!Directory.Exists(folderToZip)) {
Console.WriteLine("不存在----------");
return result;
}
/* Encoding gbk = Encoding.GetEncoding("gbk");
ICSharpCode.SharpZipLib.Zip.ZipConstants.DefaultCodePage = gbk.CodePage; */
ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipedFile));
Console.WriteLine("zipedFile-------------" + zipedFile);
zipStream.SetLevel(6);
if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
Console.WriteLine("skipFolder-------------" + skipFolder);
result = ZipDirectory(folderToZip, zipStream, "", skipFolder);
zipStream.Finish();
zipStream.Close();
return result;
}
/// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="folderToZip">要压缩的文件夹路径</param>
/// <param name="zipedFile">压缩文件完整路径</param>
/// <returns>是否压缩成功</returns>
public static bool ZipDirectory(string folderToZip, string zipedFile, string skipFolder) {
bool result = ZipDirectory(folderToZip, zipedFile, null, skipFolder);
return result;
}
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="fileToZip">要压缩的文件全名</param>
/// <param name="zipedFile">压缩后的文件名</param>
/// <param name="password">密码</param>
/// <returns>压缩结果</returns>
public static bool ZipFile(string fileToZip, string zipedFile, string password) {
bool result = true;
ZipOutputStream zipStream = null;
FileStream fs = null;
ZipEntry ent = null;
if (!File.Exists(fileToZip))
return false;
try {
fs = File.OpenRead(fileToZip);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
fs = File.Create(zipedFile);
zipStream = new ZipOutputStream(fs);
if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
ent = new ZipEntry(Path.GetFileName(fileToZip));
zipStream.PutNextEntry(ent);
zipStream.SetLevel(6);
zipStream.Write(buffer, 0, buffer.Length);
}
catch {
result = false;
}
finally {
if (zipStream != null) {
zipStream.Finish();
zipStream.Close();
}
if (ent != null) {
ent = null;
}
if (fs != null) {
fs.Close();
fs.Dispose();
}
}
GC.Collect();
GC.Collect(1);
return result;
}
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="fileToZip">要压缩的文件全名</param>
/// <param name="zipedFile">压缩后的文件名</param>
/// <returns>压缩结果</returns>
public static bool ZipFile(string fileToZip, string zipedFile) {
bool result = ZipFile(fileToZip, zipedFile, null);
return result;
}
/// <summary>
/// 压缩文件或文件夹
/// </summary>
/// <param name="fileToZip">要压缩的路径</param>
/// <param name="zipedFile">压缩后的文件名</param>
/// <param name="password">密码</param>
/// <returns>压缩结果</returns>
public static bool Zip(string fileToZip, string zipedFile, string password) {
bool result = false;
if (Directory.Exists(fileToZip))
result = ZipDirectory(fileToZip, zipedFile, password, null);
else if (File.Exists(fileToZip))
result = ZipFile(fileToZip, zipedFile, password);
return result;
}
/// <summary>
/// 压缩文件或文件夹
/// </summary>
/// <param name="fileToZip">要压缩的路径</param>
/// <param name="zipedFile">压缩后的文件名</param>
/// <returns>压缩结果</returns>
public static bool Zip(string fileToZip, string zipedFile) {
bool result = Zip(fileToZip, zipedFile, null);
return result;
}
#endregion
#region 解压
/// <summary>
/// 解压功能(解压压缩文件到指定目录)
/// </summary>
/// <param name="fileToUnZip">待解压的文件</param>
/// <param name="zipedFolder">指定解压目标目录</param>
/// <param name="password">密码</param>
/// <returns>解压结果</returns>
public static bool UnZip(string fileToUnZip, string zipedFolder, string password) {
bool result = true;
FileStream fs = null;
ZipInputStream zipStream = null;
ZipEntry ent = null;
string fileName;
if (!File.Exists(fileToUnZip))
return false;
if (!Directory.Exists(zipedFolder))
Directory.CreateDirectory(zipedFolder);
try {
zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
while ((ent = zipStream.GetNextEntry()) != null) {
if (!string.IsNullOrEmpty(ent.Name)) {
fileName = Path.Combine(zipedFolder, ent.Name);
fileName = fileName.Replace('/', '\\');//change by Mr.HopeGi
if (fileName.EndsWith("\\")) {
Directory.CreateDirectory(fileName);
continue;
}
fs = File.Create(fileName);
int size = 2048;
byte[] data = new byte[size];
while (true) {
size = zipStream.Read(data, 0, data.Length);
if (size > 0)
fs.Write(data, 0, data.Length);
else
break;
}
}
}
}
catch {
result = false;
}
finally {
if (fs != null) {
fs.Close();
fs.Dispose();
}
if (zipStream != null) {
zipStream.Close();
zipStream.Dispose();
}
if (ent != null) {
ent = null;
}
GC.Collect();
GC.Collect(1);
}
return result;
}
public static bool UnZips(string zipFilePath, string unZipDir) {
if (zipFilePath == string.Empty) {
throw new Exception("压缩文件不能为空!");
}
if (!File.Exists(zipFilePath)) {
throw new FileNotFoundException("压缩文件不存在!");
}
//解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
if (unZipDir == string.Empty)
unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
if (!unZipDir.EndsWith("\\"))
unZipDir += "\\";
Console.WriteLine("解压目录-------------------------" + unZipDir);
if (!Directory.Exists(unZipDir))
Directory.CreateDirectory(unZipDir);
Util.KUtil.Log("解压文件:"+zipFilePath+" -> "+unZipDir);
KPlan.Util.KUtil.UnZipDirectory(zipFilePath, unZipDir);
/*ZipArchive archive = null;
using (archive = System.IO.Compression.ZipFile.OpenRead(zipFilePath)){
foreach(ZipArchiveEntry entry in archive.Entries) {
entry.ExtractToFile(Path.Combine(unZipDir, entry.FullName), true);
}
}*/
//System.IO.Compression.ZipFile.ExtractToDirectory(zipFilePath, unZipDir);
/*using (var s = new ZipInputStream(File.OpenRead(zipFilePath))) {
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null) {
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
Util.KUtil.Log(directoryName + "||" + fileName);
if (!string.IsNullOrEmpty(directoryName)) {
Directory.CreateDirectory(unZipDir + directoryName);
}
if (directoryName != null && !directoryName.EndsWith("/")) {
}
if (fileName != String.Empty) {
using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name)) {
int size;
byte[] data = new byte[2048];
while (true) {
size = s.Read(data, 0, data.Length);
if (size > 0) {
streamWriter.Write(data, 0, size);
}
else {
break;
}
}
}
}
}
}*/
return true;
}
public static bool UnZipVoid(string FileToUpZip, string ZipedFolder) {
if (!File.Exists(FileToUpZip)) {
return false;
}
if (!Directory.Exists(ZipedFolder)) {
Directory.CreateDirectory(ZipedFolder);
}
ZipInputStream sInput = new ZipInputStream(File.OpenRead(FileToUpZip));
try {
ZipEntry theEntry;
while ((theEntry = sInput.GetNextEntry()) != null) {
if (theEntry.Name != String.Empty) {
string fileName = Path.Combine(ZipedFolder, theEntry.Name);
//判断文件路径是否是文件夹
if (fileName.EndsWith("/") || fileName.EndsWith("\\")) {
Directory.CreateDirectory(fileName);
continue;
}
string newDir = Path.GetDirectoryName(fileName);
if (!Directory.Exists(newDir)) {
Directory.CreateDirectory(newDir);
}
FileStream streamWriter = File.Create(fileName);
try {
int size = 2048;
byte[] data = new byte[2048];
while (true) {
size = sInput.Read(data, 0, data.Length);
if (size <= 0) {
break;
}
streamWriter.Write(data, 0, size);
}
}
finally {
streamWriter.Close();
streamWriter.Dispose();
streamWriter = null;
}
}
}
}
finally {
sInput.Close();
sInput.Dispose();
sInput = null;
}
return true;
}
/// <summary>
/// 解压功能(解压压缩文件到指定目录)
/// </summary>
/// <param name="fileToUnZip">待解压的文件</param>
/// <param name="zipedFolder">指定解压目标目录</param>
/// <returns>解压结果</returns>
public static bool UnZip(string fileToUnZip, string zipedFolder) {
bool result = UnZip(fileToUnZip, zipedFolder, null);
return result;
}
#endregion
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save